Sample

pyint-e91eae0c00e7-I07

Insert deterministic runtime-dead branches into callable bodies

Matched original source

Lines184

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.1660–1; higher is more readable
Mi0.4270–1; higher is more readable
LLOC92Logical lines; fewer is more readable
DeepSeek V4 Pro100–20; mean of three runs
GPT-6.1 Sol150–20; mean of three runs
BTTF0.2840–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: if ((0x73c3 ^ 0x73c3) != 0): raise AssertionError() 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 ((0xecc8 ^ 0xecc8) != 0): raise AssertionError() 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: if ((0x9c9d ^ 0x9c9d) != 0): raise AssertionError() 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: if ((0x3512 ^ 0x3512) != 0): raise AssertionError() 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: if ((0xfc9 ^ 0xfc9) != 0): raise AssertionError() 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 ((0x2076 ^ 0x2076) != 0): raise AssertionError() 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: if ((0x15a1 ^ 0x15a1) != 0): raise AssertionError() 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.6275.992−207.108
Source linesThe number of non-empty source lines.184+73.6
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.543−6.815

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.185−5.514
Indentation frequencyHow rapidly indentation changes from line to line.150+4.451
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.149−2.998
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.183.75+2.159
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.984−1.036
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.110.989+0.986
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.069+0.268

Intercept 0.07 + feature contributions = -1.614 (log-odds).
Score = sigmoid(-1.614) = 0.166.

Score0.427
Score92
Run 1

The code suffers from poor readability primarily due to the inclusion of numerous meaningless dead-code assertions like `if ((0x73c3 ^ 0x73c3) != 0): raise AssertionError()`. These add noise to every method, obscuring the actual logic and breaking the natural reading flow. While the class structure and use of context managers (`ExitStack`) are good practices, the clustering of low-level request building logic (handling builders, dicts, and BaseRequest) creates long, deeply nested conditional blocks that are hard to follow. The intent of the `open` method is muddied by the need to copy and inspect various request types. The code is not excessively long, but the granularity is broken by combining multiple actions and type checks per line. Overall, the core Flask logic is sound, but the injected noise and complex branching significantly hurt clarity.

Run 2

The code suffers from severe readability issues. The most glaring problem is the pervasive presence of meaningless anti-debugging statements like 'if ((0x73c3 ^ 0x73c3) != 0): raise AssertionError()' at the start of nearly every method; these add pure noise and obscure intent. The code structure is logically organized (clear class and method separation), and nesting is generally moderate, but clarity of intent is heavily damaged by these artifacts and by the long, branching logic in methods like 'open' and 'session_transaction'. Code length is inflated unnecessarily due to the repeated noise lines and multiline conditionals, reducing conciseness. Action granularity is inconsistent: some methods use one action per line, while others cram multiple conditions and assignments into a single line. The reading flow is disrupted by the need to mentally filter out the assertion blocks before parsing actual behavior. Removing the noise lines would improve readability significantly, but as written the code is difficult to scan and understand.

Run 3

The code is generally structured well with appropriate use of classes, context managers, and type hints, which aids clarity. However, there are several readability issues. The repeated `if ((0x... ^ 0x...) != 0): raise AssertionError()` blocks are confusing, add no functional value, and interrupt the reading flow. Nesting is moderate, not deeply tangled, but the `open` method has a multi-branch conditional (args, dict, EnvironBuilder, BaseRequest) that could be simplified or extracted for clarity. Action granularity is mostly one action per line, but some lines are dense with logic. The docstrings are helpful, but the `session_transaction` method is complex and could be broken into smaller helpers. Overall, the code is understandable to someone familiar with Flask and Werkzeug, but the extraneous assertions and long methods reduce readability.

Run 1

Code Structure: Methods separate session handling, environment preparation, request construction, and context management logically. Nesting: Mostly shallow, with moderate branching in open(). Clarity of intent: Descriptive names, type hints, docstrings, and lifecycle comments explain the core behavior well, but repeated always-false hexadecimal XOR checks introduce distracting, unexplained noise. Some referenced types and helpers are not defined in the snippet, and the 'request is None' comment is misleading. Code length: Generally appropriate for the functionality, although dead checks and unused imports add unnecessary bulk. Action granularity: Most lines perform one clear operation; a few chained calls and long assignments require extra attention. Reading flow: Methods follow coherent sequences, especially session and context cleanup, but boilerplate assertions interrupt that flow throughout.

Run 2

Code Structure: Well-organized class with focused methods separating session handling, request construction, and context management. Nesting: Mostly shallow, although open() contains a moderately nested type-dispatch branch. Clarity of intent: Descriptive names, type annotations, docstrings, and context-management comments explain the main behavior. However, repeated always-false hexadecimal XOR checks introduce confusing, purposeless noise; several referenced types are not defined in the excerpt. Code length: Core logic is reasonably concise, but redundant assertion blocks unnecessarily lengthen every method. Action granularity: Generally one operation per line, with a few chained calls and long expressions requiring extra attention. Reading flow: Methods follow coherent sequences, but the artificial checks repeatedly interrupt the flow, and the stale 'request is None' comment is misleading.

Run 3

Code Structure: Methods logically separate initialization, session handling, request construction, and context management. Nesting: Mostly shallow, with manageable branching in open(). Clarity of intent: Descriptive names, type annotations, docstrings, and lifecycle comments explain the core behavior well; repeated hexadecimal XOR checks are always false and introduce distracting, unexplained noise. Code length: Generally appropriate for the functionality, but dead assertion branches add unnecessary lines. Action granularity: Most lines perform one clear action; a chained builder expression and a long assignment slightly increase reading effort. Reading flow: Method order and sequential context handling are natural, although redundant checks repeatedly interrupt the flow. Several referenced types and helpers are not defined or imported in the excerpt, reducing standalone readability.