Sample

pyint-a6b81c2c6f29-I06

Invert eligible conditions and exchange their branches

Matched original source

Lines180

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.1760–1; higher is more readable
Mi0.4250–1; higher is more readable
LLOC83Logical lines; fewer is more readable
DeepSeek V4 Pro13.670–20; mean of three runs
GPT-6.1 Sol14.330–20; mean of three runs
BTTF0.4580–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 not (self._cookies is None): pass else: 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 not (sess is None): pass else: raise RuntimeError("Session backend did not open a session.") yield sess resp = app.response_class() if not (app.session_interface.is_null_session(sess)): pass else: 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 not (self.preserve_context): pass else: 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: 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 not (self.preserve_context): pass else: 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.5668.043−187.045
Source linesThe number of non-empty source lines.180+72
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.477−6.716

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.181−5.372
Indentation frequencyHow rapidly indentation changes from line to line.146+4.313
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.146−2.929
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.179.821+2.104
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.994−1.036
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.110.994+0.986
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.064+0.322

Intercept 0.07 + feature contributions = -1.543 (log-odds).
Score = sigmoid(-1.543) = 0.176.

Score0.425
Score83
Run 1

The code is generally readable with clear structure and documentation. It benefits from type hints, docstrings, and logical grouping of methods. However, several factors lower the score. First, unnatural `if not (condition): pass else: raise` patterns are used repeatedly instead of standard `if condition: raise` or guard clauses, which hurts readability. Second, some helper methods like `_copy_environ` and `open` contain nested conditionals that increase cognitive load. Third, `open` handles multiple input types (builder, dict, Request) in one method, mixing parsing, request building, context management, and dispatching. This reduces action granularity and makes the method longer than ideal. While the class is well-organized and follows consistent patterns, the verbose conditionals and occasional deep branching prevent a higher score. Overall, it remains maintainable for experienced developers but could be simplified for clarity.

Run 2

The code has clear structure, type hints, and docstrings, but suffers from several readability issues. The inverted conditionals (e.g., `if not (self._cookies is None): pass else: raise`) are particularly detrimental — they require mental inversion and occupy twice the lines of a straightforward guard clause. Multiple conditions are crammed into single lines, violating action granularity. The `open()` method has deep branching with three nested `isinstance` checks and inline comments awkwardly interleaved. Import organization is reasonable, and class responsibilities are coherent, but the intentional preservation/deferred-cleanup logic adds cognitive complexity without sufficient helper extraction. Overall the code is maintainable for experienced Flask developers but unnecessarily verbose and awkward in spots.

Run 3

The code is moderately readable but has several issues. The inverted conditionals like `if not (self._cookies is None): pass else: raise TypeError(...)` are unnecessarily awkward and hurt clarity — a simple `if self._cookies is None: raise ...` would be much cleaner. The class has a clear purpose and docstrings help, but some methods mix multiple responsibilities (e.g., `open` handles argument parsing, context management, and response processing). Nesting is mostly flat, which is good, but the use of `pass` in inverted conditions adds visual noise. Type hints improve readability, and action granularity is generally one action per line. The reading flow is disrupted by the surprising conditional structures and the large `open` method. Overall, the code is maintainable but would benefit from simplifying logic, removing redundant `pass` branches, and breaking overly long methods into smaller helpers.

Run 1

Code Structure: Methods separate session handling, request construction, and context management logically. Nesting: Mostly shallow, although open contains a moderately nested type-dispatch branch. Clarity of intent: Descriptive names, type hints, docstrings, and lifecycle comments communicate purpose well; repeated inverted conditions with empty pass branches obscure straightforward checks. Code length: Generally appropriate, but these redundant branches add unnecessary lines. Action granularity: Nearly every line performs one action, making operations easy to track. Reading flow: Request creation, execution, and cleanup follow a natural sequence, but awkward conditionals, a misleading 'request is None' comment, and a long assignment interrupt readability. Some referenced types and helpers are not defined in the excerpt, limiting standalone comprehension.

Run 2

Code Structure: Well-organized class with focused methods separating session handling, request construction, and context management. Nesting: Generally shallow, although open() has a moderately nested type-dispatch branch and several unnecessary if/pass/else blocks. Clarity of intent: Descriptive names, type annotations, docstrings, and lifecycle comments clarify behavior; repeated negated conditions obscure otherwise straightforward guards. Referenced types and helpers are not defined or imported in the snippet, reducing self-contained clarity. Code length: Mostly justified, but redundant pass branches and verbose documentation add reading overhead. Action granularity: Usually one action per line, with a few chained expressions requiring closer inspection. Reading flow: Methods follow a coherent request lifecycle, but inverted conditions interrupt the natural flow, and the comment 'request is None' is misleading. Direct guard clauses would substantially improve readability.

Run 3

Code Structure: Methods logically separate session management, request construction, and context cleanup. Nesting: Mostly shallow, although open() has a moderately nested type-dispatch branch. Clarity of intent: Descriptive names, type annotations, docstrings, and lifecycle comments help, but repeated inverted conditions with empty pass branches obscure simple checks. Several referenced types and helpers are not defined or imported in the snippet, and some imports are unused. Code length: Reasonable for the functionality, but redundant if/pass/else patterns add unnecessary lines. Action granularity: Statements generally perform one action per line, with a few dense chained calls and a long assignment. Reading flow: Methods follow a coherent operational sequence, but awkward conditionals, the misleading 'request is None' comment, and tightly spaced imports and class declaration interrupt otherwise clear reading.