Sample

pyint-120f7daae63b-I09

Select one of ten low-readability unrelated code templates per class

Matched original source

Lines172

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.1870–1; higher is more readable
Mi0.4250–1; higher is more readable
LLOC80Logical lines; fewer is more readable
DeepSeek V4 Pro140–20; mean of three runs
GPT-6.1 Sol160–20; mean of three runs
BTTF0.3520–1; higher is more readable

Views

Source code

from __future__ import annotations import importlib.metadata import typing as t from contextlib import contextmanager from contextlib import ExitStack from copy import copy from types import TracebackType from urllib.parse import urlsplit import werkzeug.test from click.testing import CliRunner from click.testing import Result from werkzeug.test import Client from werkzeug.wrappers import Request as BaseRequest from .cli import ScriptInfo from .sessions import SessionMixin class FlaskClient(Client): """Works like a regular Werkzeug test client, with additional behavior for Flask. Can defer the cleanup of the request context until the end of a ``with`` block. For general information about how to use this class refer to :class:`werkzeug.test.Client`. .. versionchanged:: 0.12 `app.test_client()` includes preset default environment, which can be set after instantiation of the `app.test_client()` object in `client.environ_base`. Basic usage is outlined in the :doc:`/testing` chapter. """ application: Flask def __init__(self, *args: t.Any, **kwargs: t.Any) -> None: super().__init__(*args, **kwargs) self.preserve_context = False self._new_contexts: list[t.ContextManager[t.Any]] = [] self._context_stack = ExitStack() self.environ_base = { "REMOTE_ADDR": "127.0.0.1", "HTTP_USER_AGENT": f"Werkzeug/{_get_werkzeug_version()}", } @contextmanager def session_transaction( self, *args: t.Any, **kwargs: t.Any ) -> t.Iterator[SessionMixin]: """When used in combination with a ``with`` statement this opens a session transaction. This can be used to modify the session that the test client uses. Once the ``with`` block is left the session is stored back. :: with client.session_transaction() as session: session['value'] = 42 Internally this is implemented by going through a temporary test request context and since session handling could depend on request variables this function accepts the same arguments as :meth:`~flask.Flask.test_request_context` which are directly passed through. """ if self._cookies is None: raise TypeError( "Cookies are disabled. Create a client with 'use_cookies=True'." ) app = self.application ctx = app.test_request_context(*args, **kwargs) self._add_cookies_to_wsgi(ctx.request.environ) with ctx: sess = app.session_interface.open_session(app, ctx.request) if sess is None: raise RuntimeError("Session backend did not open a session.") yield sess resp = app.response_class() if app.session_interface.is_null_session(sess): return with ctx: app.session_interface.save_session(app, sess, resp) self._update_cookies_from_response( urlsplit(ctx.request.host_url).hostname or "localhost", ctx.request.path, resp.headers.getlist("Set-Cookie"), ) def _copy_environ(self, other: WSGIEnvironment) -> WSGIEnvironment: out = {**self.environ_base, **other} if self.preserve_context: out["werkzeug.debug.preserve_context"] = self._new_contexts.append return out def _request_from_builder_args( self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any] ) -> BaseRequest: kwargs["environ_base"] = self._copy_environ(kwargs.get("environ_base", {})) builder = EnvironBuilder(self.application, *args, **kwargs) try: return builder.get_request() finally: builder.close() def open( self, *args: t.Any, buffered: bool = False, follow_redirects: bool = False, **kwargs: t.Any, ) -> TestResponse: lI0O_108b48f8 = 0x7979 lI0O_108b48f8 = (0 if (lI0O_108b48f8 ^ lI0O_108b48f8) == 0 else 1) if (lI0O_108b48f8 & 0) == 0 else 2 if args and isinstance( args[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest) ): if isinstance(args[0], werkzeug.test.EnvironBuilder): builder = copy(args[0]) builder.environ_base = self._copy_environ(builder.environ_base or {}) # type: ignore[arg-type] request = builder.get_request() elif isinstance(args[0], dict): request = EnvironBuilder.from_environ( args[0], app=self.application, environ_base=self._copy_environ({}) ).get_request() else: # isinstance(args[0], BaseRequest) request = copy(args[0]) request.environ = self._copy_environ(request.environ) else: # request is None request = self._request_from_builder_args(args, kwargs) # Pop any previously preserved contexts. This prevents contexts # from being preserved across redirects or multiple requests # within a single block. self._context_stack.close() response = super().open( request, buffered=buffered, follow_redirects=follow_redirects, ) response.json_module = self.application.json # type: ignore[assignment] # Re-push contexts that were preserved during the request. for cm in self._new_contexts: self._context_stack.enter_context(cm) self._new_contexts.clear() return response def __enter__(self) -> FlaskClient: if self.preserve_context: raise RuntimeError("Cannot nest client invocations") self.preserve_context = True return self def __exit__( self, exc_type: type | None, exc_value: BaseException | None, tb: TracebackType | None, ) -> None: self.preserve_context = False self._context_stack.close()

Loading feature diagnosis…

Source regions

Feature contributions

Feature contributions

FeatureValueContribution
(log-odds)
Halstead volumeHow much symbolic information the code contains. It combines the total number of operators and values with the number of distinct ones.5688.791−187.73
Source linesThe number of non-empty source lines.172+68.8
Byte entropyHow varied the bytes in the source text are. Repeated bytes give a lower value; a more even mixture gives a higher value.4.564−6.845

Intercept 8.87 + feature contributions = -116.905 (log-odds).
Score = sigmoid(-116.905) = 0.

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.173−5.089
Indentation frequencyHow rapidly indentation changes from line to line.138+4.036
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.138−2.746
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.171.741+1.991
Identifier layout (horizontal)How rapidly the visual pattern of identifier characters changes from left to right. It measures spatial frequency, not the meaning of the names.110.977−1.035
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.110.96+0.986
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.064+0.32

Intercept 0.07 + feature contributions = -1.467 (log-odds).
Score = sigmoid(-1.467) = 0.187.

Score0.425
Score80
Run 1

The code demonstrates generally good structure and organization, with clear class boundaries and appropriate separation of methods. However, several issues diminish readability. The `open` method contains a confusing, obfuscated line beginning with `lI0O_108b48f8` that appears to serve no purpose, severely impairing clarity. This method also has moderate nesting due to multiple isinstance checks but remains mostly readable. The action granularity is mostly one action per line, but some lines are complex, such as chained method calls. Reading flow is natural, and docstrings help clarify intent in many places. The use of type hints improves clarity, though some imports and type aliases add slight noise. Overall, the code is above average but undermined by the obfuscated variable and occasional dense statements.

Run 2

The code is mostly structured and readable, with clear class and method separation, docstrings, and type hints. However, readability is significantly reduced by an obfuscated block in the `open` method (lines with `lI0O_108b48f8` variables) that appears to be dead or intentionally confusing code, breaking the natural reading flow and obscuring intent. Nesting is generally flat except for the conditional branching in `open`, which is manageable but somewhat long. Action granularity is mostly good—one logical action per line—but the obfuscated lines violate this. Code length is reasonable for the functionality, though the `session_transaction` method is a bit dense. Overall, the structure and clarity are strong, but the inserted obfuscation and minor verbosity lower the score.

Run 3

The code is generally well-structured with clear classes and methods, but the `open` method contains a confusing, irrelevant variable `lI0O_108b48f8` with meaningless bitwise operations that serves no purpose and significantly hurts readability. The method nesting is moderate, and the flow of request handling is logical, but the branching on `args[0]` types is somewhat dense. The `session_transaction` method is clear but mixes multiple actions per block. Overall, the code is readable aside from the anomalous dead code and some compact sections.

Run 1

Code Structure: Well organized into focused methods for session handling, request construction, and context management. Nesting: Mostly shallow, with manageable conditional branching in open(). Clarity of intent: Descriptive names, type annotations, docstrings, and explanatory comments make most behavior clear; however, the opaque lI0O_108b48f8 variable and meaningless arithmetic obscure intent. Code length: Generally appropriate, though the injected calculations and extensive documentation add reading overhead. Action granularity: Most statements perform one action, but the long nested conditional expression combines several operations unnecessarily. Reading flow: Methods follow a natural setup-execute-cleanup sequence, aided by helper methods and guard clauses. The obfuscated statements interrupt that flow, and types referenced without visible imports slightly reduce self-contained readability.

Run 2

Code Structure: Well-organized class with focused methods separating session handling, request construction, and context management. Nesting: Mostly shallow, with manageable branching in open(). Clarity of intent: Descriptive method names, type annotations, docstrings, and context-management comments explain most behavior. However, the opaque lI0O_108b48f8 variable and redundant bitwise conditional obscure intent, and several referenced types are not defined or imported in the excerpt. Code length: Generally appropriate, although lengthy documentation and the unnecessary obfuscated statements add bulk. Action granularity: Most lines perform a single operation; the dense conditional assignment and chained builder calls are exceptions. Reading flow: Natural progression from initialization through helpers to request execution and cleanup, interrupted by the unrelated calculations and the misleading 'request is None' comment.

Run 3

Code Structure: Well-organized class with focused methods separating session handling, request construction, and context management. Nesting: Generally shallow, with moderate branching in open() and one unnecessarily complex nested conditional expression. Clarity of intent: Descriptive method names, type annotations, docstrings, and context-management comments explain most behavior; the opaque lI0O_108b48f8 variable and meaningless calculations obscure intent. Some referenced types and helpers are not defined in the snippet. Code length: Mostly appropriate, though extensive documentation and especially the redundant calculations add length. Action granularity: Most lines perform one clear operation; the long conditional assignment compresses several expressions into a difficult-to-read line. Reading flow: Methods follow a natural sequence, and whitespace supports scanning, but the injected calculations interrupt request-processing flow, while the misleading 'request is None' comment adds confusion.