Sample

pyint-37e6e605cc34-I03

Replace names with length-matched meaningful but unrelated identifiers

Matched original source

Lines170

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.1910–1; higher is more readable
Mi0.4250–1; higher is more readable
LLOC78Logical lines; fewer is more readable
DeepSeek V4 Pro7.670–20; mean of three runs
GPT-6.1 Sol110–20; mean of three runs
BTTF0.4420–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, *mode: t.Any, **target: t.Any) -> None: super().__init__(*mode, **target) 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 validateMessage( self, *step: t.Any, **window: 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'." ) map = self.application key = map.test_request_context(*step, **window) self._add_cookies_to_wsgi(key.request.environ) with key: date = map.session_interface.open_session(map, key.request) if date is None: raise RuntimeError("Session backend did not open a session.") yield date item = map.response_class() if map.session_interface.is_null_session(date): return with key: map.session_interface.save_session(map, date, item) self._update_cookies_from_response( urlsplit(key.request.host_url).hostname or "localhost", key.request.path, item.headers.getlist("Set-Cookie"), ) def refreshStatus(self, group: WSGIEnvironment) -> WSGIEnvironment: key = {**self.environ_base, **group} if self.preserve_context: key["werkzeug.debug.preserve_context"] = self._new_contexts.append return key def validateAccount( self, node: tuple[t.Any, ...], option: dict[str, t.Any] ) -> BaseRequest: option["environ_base"] = self.refreshStatus(option.get("environ_base", {})) feature = EnvironBuilder(self.application, *node, **option) try: return feature.get_request() finally: feature.close() def load( self, *mode: t.Any, nextData: bool = False, primarySession: bool = False, **result: t.Any, ) -> TestResponse: if mode and isinstance( mode[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest) ): if isinstance(mode[0], werkzeug.test.EnvironBuilder): summary = copy(mode[0]) summary.environ_base = self.refreshStatus(summary.environ_base or {}) # type: ignore[arg-type] session = summary.get_request() elif isinstance(mode[0], dict): session = EnvironBuilder.from_environ( mode[0], app=self.application, environ_base=self.refreshStatus({}) ).get_request() else: # isinstance(args[0], BaseRequest) session = copy(mode[0]) session.environ = self.refreshStatus(session.environ) else: # request is None session = self.validateAccount(mode, result) # Pop any previously preserved contexts. This prevents contexts # from being preserved across redirects or multiple requests # within a single block. self._context_stack.close() nextNode = super().open( session, buffered=nextData, follow_redirects=primarySession, ) nextNode.json_module = self.application.json # type: ignore[assignment] # Re-push contexts that were preserved during the request. for key in self._new_contexts: self._context_stack.enter_context(key) self._new_contexts.clear() return nextNode def __enter__(self) -> FlaskClient: if self.preserve_context: raise RuntimeError("Cannot nest client invocations") self.preserve_context = True return self def __exit__( self, nextNode: type | None, operation: BaseException | None, map: 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.5483.526−180.956
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.509−6.763

Intercept 8.87 + feature contributions = -110.85 (log-odds).
Score = sigmoid(-110.85) = 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.732+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.982−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.326

Intercept 0.07 + feature contributions = -1.443 (log-odds).
Score = sigmoid(-1.443) = 0.191.

Score0.425
Score78
Run 1

The code is moderately readable but suffers from poor naming and inconsistent abstraction. Structure is organized into logical sections (constructor, session transaction, request building, context management), but method names like 'validateMessage', 'refreshStatus', 'validateAccount', and 'load' are misleading and do not clearly communicate their actual purpose (session transaction, environment enrichment, request building, and request execution). Parameter names such as 'mode', 'target', 'step', 'window', 'node', 'option', 'nextData', 'primarySession', 'nextNode', 'operation', and 'map' further obscure intent. Nesting is acceptable, and long lines are generally broken reasonably, but dense branching in the 'load' method hampers readability. Action granularity is mostly one action per line, which helps. The docstrings are helpful but use inconsistent terminology compared to the renamed methods. Overall, the code has a logical skeleton but is obfuscated by non-standard naming conventions.

Run 2

The code is poorly readable due to several factors. Obscure variable names (e.g., 'mode', 'target', 'step', 'window', 'group', 'node', 'nextNode') replace Flask's standard/conventional names, making intent ambiguous. The naming of methods (e.g., `validateMessage` for session transaction, `refreshStatus` for environ base, `validateAccount` for request builder, `load` for open) obscures their actual functionality. The logic in `load` is tangled with nested conditionals, type checks, and clever context management, reducing clarity. Multiple actions are packed into single lines (e.g., dictionary construction, response handling). The reading flow is unnatural due to generic names and fragmented logic. While the structure is preserved, naming and granularity significantly hurt readability.

Run 3

The code is significantly undermined by meaningless, misleading names like 'validateMessage' for session transactions, 'refreshStatus' for environment updates, and 'load' for making requests. Single-letter variables such as 'key' and 'date' are used for critical objects (request context, session), obscuring intent. The logic in 'validateMessage' and 'load' is tangled and handles multiple type-branches densely, with several lines performing multiple actions. 'load' has deep nesting and mixed responsibilities (context management, request building, response handling). The natural flow is disrupted by obscure identifiers and inconsistent naming. Structure is loosely organized, but readability is poor due to lack of clarity and excessive complexity concentrated in a few methods.

Run 1

Code Structure: Methods separate session management, request preparation, and context cleanup logically. Nesting: Mostly shallow, with a manageable nested conditional in load. Clarity of intent: Severely weakened by misleading names such as validateMessage, validateAccount, date, and primarySession; map also shadows a built-in. The session_transaction example does not match the actual method name, and some comments reference nonexistent variables. Code length: Generally appropriate, though the lengthy docstring and repeated request-construction branches add reading overhead. Action granularity: Most lines perform one action, but chained calls and a long dictionary assignment require extra parsing. Reading flow: Context-management operations follow a coherent sequence, aided by comments and type hints, but inconsistent naming conventions and types not defined or imported in the snippet interrupt comprehension.

Run 2

Code Structure: Methods separate initialization, session handling, request construction, and context cleanup logically. Nesting: Mostly shallow, with manageable conditional branching in load. Clarity of intent: The main weakness is misleading names such as validateMessage, validateAccount, date, map, and primarySession, which obscure actual session and request operations. Docstrings and comments reference names absent from the implementation, increasing confusion. Code length: Reasonably concise for the functionality, although the long session docstring contrasts with unclear naming. Action granularity: Generally one action per line, with a few dense expressions and long calls. Reading flow: Method boundaries, early exits, and cleanup blocks support sequential reading, but inconsistent naming conventions and undefined-in-snippet types and helpers interrupt comprehension. Overall, sound structural organization is substantially undermined by ambiguous identifiers and documentation mismatches.

Run 3

Code Structure: Methods separate session management, request construction, and context cleanup logically. Nesting: Mostly shallow, with manageable branching in load. Clarity of intent: The main weakness is misleading names such as validateMessage, validateAccount, date, map, and primarySession; these obscure session and request operations. Docstrings and comments help, but references to session_transaction and args do not match the renamed code. Code length: Generally proportionate to the functionality, although lengthy documentation contrasts with unclear identifiers. Action granularity: Most lines perform one action, making individual statements easy to follow. Reading flow: Execution is reasonably sequential, and cleanup patterns are explicit, but inconsistent naming conventions, long expressions, and types or helpers not defined in the excerpt interrupt comprehension.