Sample

pyint-bf7e10b68ef6-SRC

Unmodified source class

Lines170

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.1920–1; higher is more readable
Mi0.4250–1; higher is more readable
LLOC78Logical lines; fewer is more readable
DeepSeek V4 Pro14.670–20; mean of three runs
GPT-6.1 Sol170–20; mean of three runs
BTTF0.4750–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: 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.5435.556−179.373
Source linesThe number of non-empty source lines.170+68
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.515−6.773

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.171−5.018
Indentation frequencyHow rapidly indentation changes from line to line.136+3.967
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.136−2.7
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.169.777+1.963
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.988−1.036
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.110.959+0.986
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.063+0.329

Intercept 0.07 + feature contributions = -1.439 (log-odds).
Score = sigmoid(-1.439) = 0.192.

Score0.425
Score78
Run 1

The code is well-structured and readable. It uses clear class naming, type hints, and docstrings. Methods are focused and maintain flat, logical flow within each function. The `open` method has a moderate level of branching but uses comments to clarify intent. Context managers and ExitStack are used appropriately to manage resources. Some complex logic around request building and state management slightly reduces clarity, but overall action granularity and reading flow are strong.

Run 2

The code is generally readable but has areas that could be improved. It has a clear class structure and docstrings, which help with intent. However, the `open` method contains a long if-elif-else block with multiple actions per line and nested type checks, reducing clarity. The `session_transaction` method mixes context management and session logic, which hurts the reading flow. Type hints are helpful, but some lines are dense and the action granularity is uneven. Variable names are descriptive, but overall flow could be more linear.

Run 3

The code is relatively readable but has moderate issues. Structure follows logical class methods and type hints improve clarity, but docstring length and some comments feel excessive. Nesting is acceptable, mostly within `open` and `session_transaction`, though the `if args and isinstance(...)` block in `open` creates multi-branch logic that is somewhat dense. Intent is generally clear due to naming and docstrings, but `_copy_environ` has a cryptic side effect (assigning a method to a debug environ key). Code length is reasonable but could be shorter; some comments repeat code logic. Action granularity is mostly one action per line, except in `_copy_environ` where dictionary merging and conditional assignment occur tightly. Reading flow is mostly linear but gets interrupted by the large `if/elif/else` in `open` and mixed responsibilities in methods like `session_transaction` (cookie checks, context handling, session save). Overall, the code is maintainable but not exemplary for readability.

Run 1

Code Structure: Methods logically separate session handling, environment preparation, request creation, and context management. Nesting: Mostly shallow, with modest nested branching in open(). Clarity of intent: Descriptive method names, type annotations, docstrings, and lifecycle comments explain the purpose well; abbreviated variables and externally defined types slightly reduce standalone clarity. Code length: Appropriately sized methods and reusable helpers keep implementation concise, although documentation is lengthy and some imports appear unused in this excerpt. Action granularity: Statements generally perform one action per line, with a few chained calls and a long assignment increasing reading effort. Reading flow: Initialization, helper methods, request execution, and context-manager methods follow a natural progression. Session and preserved-context lifecycles require careful attention, and the 'request is None' comment is misleading because it does not describe an actual check.

Run 2

Code Structure: Cohesive class with well-separated methods and helper functions, although some imports are unused and referenced types are not defined in the snippet. Nesting: Generally shallow, with moderate branching in open() to support multiple input types. Clarity of intent: Descriptive names, type annotations, docstrings, and context-management comments explain most behavior; abbreviated variables and the misleading 'request is None' comment slightly reduce clarity. Code length: Reasonably concise for the functionality, though documentation is lengthy and some request-building logic repeats. Action granularity: Statements generally perform one action per line, with a few dense chained calls and dictionary expressions. Reading flow: Methods follow a natural initialization, session handling, request construction, and context cleanup progression. Specialized context-preservation behavior requires careful reading, but overall organization remains easy to follow.

Run 3

Code Structure: Cohesive class with well-separated methods for sessions, request construction, and context management; some unused imports and externally defined types distract. Nesting: Generally shallow, with modest branching in open() and effective early exits. Clarity of intent: Descriptive method names, type annotations, docstrings, and lifecycle comments explain most behavior; abbreviated variables and subtle context preservation require framework knowledge. Code length: Mostly appropriate, though lengthy documentation and repeated request-type handling slightly increase reading effort. Action granularity: Statements generally perform one action per line, with a few chained calls and a long assignment reducing scanability. Reading flow: Methods follow a natural progression, and cleanup logic is clearly marked; limited spacing between import groups and the class, plus the misleading 'request is None' comment, slightly weaken readability.