Download tasks/data/forward/agusdmb__autofake.19fffd2/instruction.md from Lego-X/ProgramGen: direct link, hf CLI and curl.
- Browser
- Download file 38.9 kB
-
https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/agusdmb__autofake.19fffd2/instruction.md
- Command line
-
hf download hf://datasets/Lego-X/ProgramGen/tasks/data/forward/agusdmb__autofake.19fffd2/instruction.md
-
curl -L -o instruction.md https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/agusdmb__autofake.19fffd2/instruction.md
agusdmb/autofake
Project Overview
AutoFake is a lightweight Python library (published on PyPI as autofake, version 0.5.0) for mocking functions in tests by recording and replaying real behavior rather than hand-writing stubs. Its purpose is to let developers run code normally once, capture the calls, arguments, and return values of selected functions into a storage backend, and then reproduce those results during testing instead of executing the real implementation. This isolates the code under test from external services, side effects, and long-running operations, and makes the tool especially well suited for adding tests to legacy code and for approval-testing style refactoring workflows.
The library's scope is deliberately small and dependency-free, targeting Python 3.8+ and packaged with Poetry. Primary functionality is exposed through the FakeIt object, used as a decorator. Decorated functions behave according to one of three modes: PRODUCTION (the default), where functions execute normally; RECORD, where they execute while their call, arguments, and result are persisted to the backend; and FAKE, where execution is skipped and the previously recorded result is retrieved for the given arguments. The mode can be set programmatically when constructing FakeIt or globally via the AUTOFAKE environment variable, e.g., AUTOFAKE=RECORD python example.py to capture, then AUTOFAKE=FAKE to replay.
Architecturally, the package is organized into a few focused modules: fakeit.py implements the central FakeIt class and its decorator, which also enforces unique names among decorated functions (raising NotUniqueName on duplicates); models.py defines the data structures representing recorded calls; backend.py provides pluggable persistence backends behind a simple Backend protocol—an InMemoryBackend used by default, plus PickleBackend and JSONBackend for storing recordings on disk (e.g., in an output.pickle file); and exceptions.py contains the library's error types, including RecordNotFound raised when a fake call has no matching recording. Users choose a backend when instantiating FakeIt and may name each decorated function for storage. Automated tests live in the tests directory, and quality tooling (pytest, mypy, pylint, black, coverage, bandit) plus a GitHub Actions test workflow round out the project.
Re-implement this repository from scratch so that the original test suite passes. The sections below document the language/environment, the project structure, the public API the tests exercise, and per-capability implementation guidance.
Submission Constraints (read carefully — the evaluation depends on these)
This is a closed-book task. The graded test suite is hidden and will be injected into the workspace at evaluation time. To be scored correctly you MUST follow these rules:
Do NOT create or modify any files under the test directories (e.g.
tests/,test/,testing/, or files namedtest_*.py/conftest.py). The grader injects its own test files at those paths; any file you place there will collide with the injected suite and cause the whole evaluation to score 0. Implement only the library/source code — never the tests.Your package MUST be importable by the name the tests use. The hidden tests
importyour package by its documented top-level name (see the Project Directory Structure and API Usage Guide below). Provide a validpyproject.toml/setup.py/setup.cfgand lay out your modules so thatpip install -e .succeeds and the package imports cleanly. If your package is not installable/importable, every test errors out and the reward is 0.Match the documented module paths and public API exactly (names, signatures, and any literal error/exception strings). Internal helpers not listed in the API guide may be implemented however you like.
Install / Reconstruction Contract
Follow this contract before implementing the documented APIs:
- Project root:
/workspace/repoat runtime; the submitted repository root is.. - Package/distribution name:
autofake - Package roots:
. - Install strategy:
editable-install - Import/entry: use the package and public entry points listed in the API Usage Guide; do not invent a different top-level package.
- Provision commands:
python3 -I -c 'import base64; from pathlib import Path; Path('"'"'/tmp/programgen-pip-compat-v1.py'"'"').write_bytes(base64.b64decode('"'"'aW1wb3J0IG9zCmZyb20gcGF0aGxpYiBpbXBvcnQgUGF0aAppbXBvcnQgc3VicHJvY2VzcwppbXBvcnQgc3lzCmltcG9ydCB0ZW1wZmlsZQoKZGVmIGNvbnN0cmFpbmVkX2J1aWxkX2luc3RhbGwoY29tbWFuZCwgcnVuKToKICAgIGNvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCgnUFJPR1JBTUdFTl9CVUlMRF9DT05TVFJBSU5UJykKICAgIGlmIG5vdCBjb25zdHJhaW50IG9yICctLW5vLWJ1aWxkLWlzb2xhdGlvbicgaW4gY29tbWFuZDoKICAgICAgICByZXR1cm4gTm9uZQogICAgaWYgc3lzLnZlcnNpb25faW5mb1s6Ml0gPCAoMywg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dC5mbHVzaCgpCiAgICBpZiByZXN1bHQucmV0dXJuY29kZSA9PSAwOgogICAgICAgIHJldHVybiAwCiAgICBsZWdhY3kgPSAnaW52YWxpZCBtZXRhZGF0YScgaW4gb3V0cHV0Lmxvd2VyKCkgYW5kICdwbGVhc2UgdXNlIHBpcDwyNC4xJyBpbiBvdXRwdXQubG93ZXIoKQogICAgaWYgbm90IGxlZ2FjeSBvciBub3QgKDMsIDgpIDw9IHN5cy52ZXJzaW9uX2luZm9bOjJdIDw9ICgzLCAxMik6CiAgICAgICAgcmV0dXJuIHJlc3VsdC5yZXR1cm5jb2RlCiAgICBwcmludCgnW3Byb2dyYW1nZW5dIGxlZ2FjeSBkaXN0cmlidXRpb24gbWV0YWRhdGE6IHJldHJ5aW5nIHRoZSB1bmNoYW5nZWQgcmVxdWlyZW1lbnRzIHdpdGggcGlwPDI0LjEnLCBmbHVzaD1UcnVlKQogICAgY2hhbmdlZCA9IHJ1bihbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICdwaXA8MjQuMSddKQogICAgaWYgY2hhbmdlZC5yZXR1cm5jb2RlOgogICAgICAgIHJldHVybiBjaGFuZ2VkLnJldHVybmNvZGUKICAgIHJldHVybiBydW4oY29tbWFuZCkucmV0dXJuY29kZQoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIHJhaXNlIFN5c3RlbUV4aXQoaW5zdGFsbChzeXMuYXJndlsxOl0pKQo='"'"'))' programgen_pip_install() { python3 -I /tmp/programgen-pip-compat-v1.py "$@"; } export -f programgen_pip_install programgen_pip_install python3 -m pip install -U pip 'setuptools<82' wheel programgen_pip_install python3 -m pip install 'poetry-core>=1.0.0' ( programgen_install_report="$(mktemp)" trap 'rm -f "$programgen_install_report"' EXIT SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 programgen_pip_install python3 -m pip install -e . --no-build-isolation --no-deps --report "$programgen_install_report" python3 -c 'exec("import json,subprocess,sys\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.utils import canonicalize_name\nreport=json.load(open(sys.argv[1], encoding='"'"'utf-8'"'"'))\n\nrequested={canonicalize_name(name) for name in ()}\nrequirements=[]\nfor item in report.get('"'"'install'"'"', []):\n metadata=item.get('"'"'metadata'"'"', {})\n name=canonicalize_name(metadata.get('"'"'name'"'"', '"'"''"'"'))\n provided={canonicalize_name(value) for value in metadata.get('"'"'provides_extra'"'"', [])}\n selected={'"'"''"'"'} | (provided & requested)\n parsed=[Requirement(value) for value in metadata.get('"'"'requires_dist'"'"', [])]\n while True:\n added=set()\n for requirement in parsed:\n if requirement.marker is not None and not any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n continue\n if canonicalize_name(requirement.name)==name:\n if requirement.url or (requirement.specifier and not requirement.specifier.contains(metadata.get('"'"'version'"'"', '"'"''"'"'), prereleases=True)):\n raise ValueError('"'"'local extra requires a different target distribution'"'"')\n extras={canonicalize_name(value) for value in requirement.extras}\n if not extras <= provided:\n raise ValueError('"'"'local extra refers to an undeclared extra'"'"')\n added.update(extras - selected)\n if not added:\n break\n selected.update(added)\n for requirement in parsed:\n if canonicalize_name(requirement.name)==name:\n continue\n if requirement.marker is None or any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n requirement.marker=None\n requirements.append(str(requirement))\nrequirements=list(dict.fromkeys(requirements))\nsubprocess.run([sys.executable, '"'"'-I'"'"', '"'"'/tmp/programgen-pip-compat-v1.py'"'"', sys.executable, '"'"'-m'"'"', '"'"'pip'"'"', '"'"'install'"'"', *requirements], check=True) if requirements else None\n")' "$programgen_install_report" ) - Runtime setup:
{ SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 SETUPTOOLS_SCM_WRITE_TO_SOURCE=1 python3 -m pip install -e "$PWD" --no-build-isolation --no-deps; } - Project root for installation:
. - Build-version environment:
SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0,PDM_BUILD_SCM_VERSION=0.0.0,POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0,UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 - Test directory:
tests - Test command:
bash -lc 'set -uo pipefail run=(python3 -m pytest -vv -o addopts= tests/test_backend.py tests/test_fakeit.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= tests/test_backend.py tests/test_fakeit.py); fi collect=(python3 -m pytest -q -o addopts= tests/test_backend.py tests/test_fakeit.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '"'"'/::/p'"'"' | sed '"'"'s/[[:space:]]*$//'"'"') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'"'"'::'"'"' -v limit=500 '"'"'{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}'"'"') fi "${run[@]}"; exit $?' - Test startup: run the exact test command above from the project root after installation; hidden tests are injected separately.
Environment & Project Structure
- Language: python
- Build system: python
- Test command:
bash -lc set -uo pipefail run=(python3 -m pytest -vv -o addopts= tests/test_backend.py tests/test_fakeit.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= tests/test_backend.py tests/test_fakeit.py); fi collect=(python3 -m pytest -q -o addopts= tests/test_backend.py tests/test_fakeit.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '/::/p' | sed 's/[[:space:]]*$//') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'::' -v limit=500 '{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}') fi "${run[@]}"; exit $?
Project Directory Structure
.github/workflows/tests.yml
.gitignore
LICENSE
README.md
autofake/__init__.py
autofake/backend.py
autofake/exceptions.py
autofake/fakeit.py
autofake/models.py
poetry.lock
pyproject.toml
API Usage Guide
Each capability below lists the components the tests exercise with their exact signatures and behavior. Re-create these so the tests pass; internal helpers not listed here may be implemented freely.
Capability: Configurable operating modes (PRODUCTION, RECORD, FAKE)
Configurable operating modes: PRODUCTION, RECORD, FAKE
What the mode controls
FakeIt is a decorator factory whose single behavioral switch is the operating mode. The mode is resolved once, at construction time, and pins down what every function decorated by that instance does at call time:
- PRODUCTION (default): the decorated function behaves exactly as if undecorated.
- RECORD: the real function still runs, but each successful call is persisted as a
Record(args, kwargs, result). - FAKE: the real function body never runs; the stored result for the given arguments is returned instead.
Mode resolution: precedence and timing
FakeIt(mode=None, backend=None) resolves the mode in strict precedence order:
- An explicitly passed
modealways wins; theAUTOFAKEenvironment variable is ignored in that case. - Otherwise the
AUTOFAKEenvironment variable is read. If it is set to a non-empty value, that value is fed toMode(value), so it must be one of the literal enum values"RECORD","FAKE", or"PRODUCTION"— case-sensitive. Any other non-empty string (e.g.record) raisesValueErrorduring construction, i.e. atFakeIt()instantiation, before any decoration. The empty string is the one exception: because resolution guards on a truthy env value,AUTOFAKE=""is treated exactly as unset and falls through toMode.PRODUCTIONrather than raising. - Otherwise the mode is
Mode.PRODUCTION.
Because resolution happens in __init__, mutating os.environ["AUTOFAKE"] after an instance exists has no effect on it. The env var is intended for whole-run switching: AUTOFAKE=RECORD python example.py to capture, AUTOFAKE=FAKE pytest to replay.
Decoration-time state changes and ordering
When FakeIt decorates a function, the function's __name__ is registered in the instance's set of decorated names before any mode dispatch. Consequences:
- Decorating two functions with the same name on the same
FakeItinstance raisesNotUniqueNameat decoration (import) time — in every mode, including PRODUCTION. Registration is per instance, so two separate instances may each decorate same-named functions. - The backend storage key is always the original function's
__name__; there is no way to alias it per decoration. - In PRODUCTION the decorator returns the original function object itself (no wrapper, identity preserved, backend untouched).
- In RECORD and FAKE the decorator returns a
functools.wraps-preserving wrapper, so__name__and metadata survive — which is precisely why the original name remains the lookup key.
Call-time semantics per mode
- PRODUCTION: no backend reads or writes ever occur.
- RECORD: the real function executes first. Only on a normal return is a
Record(args=args, kwargs=kwargs, result=result)appended to the backend, and the real result is then returned. If the function raises, nothing is recorded and the exception propagates unchanged. Side effects of the real call still happen — recording does not suppress execution. - FAKE: the wrapper immediately calls
backend.get_result(name, *args, **kwargs); the real function is not a fallback. A missing match raisesRecordNotFound("Record not found").
Argument matching (test-sensitive)
Replay matches records with == on both args and kwargs exactly as they were passed at record time:
- Call form matters:
f(1)does not satisfy a recordedf(x=1)and vice versa; the recordedargstuple andkwargsdict must both match. kwargscomparison is dict equality, so key insertion order is irrelevant.InMemoryBackendandPickleBackendcompare tuple args.JSONBackendcompareslist(args)against the JSON-decoded list, so the top-level positional container is a list on both sides and JSON-stable scalar arguments still match — but the JSON round trip rewrites arguments as well as results: nested tuple arguments, i.e. tuple entries ofargsor tuple values ofkwargs(e.g.f((1, 2))orf(x=(1, 2))), are serialized to lists at record time (json.dumpof the record), so the identical replayed call does not match and raisesRecordNotFound. Only JSON-stable argument values (str,int,float,bool,None,list,dict) round-trip to matching equality. Results are likewise coerced (tuples come back as lists), and non-JSON-serializable values are refused at record time.- When one name has several recordings, backends scan in call order and return the first record whose args and kwargs both match.
- Calling a FAKE-mode function with arguments that match no loaded record is the canonical
RecordNotFoundpath. That covers an emptyInMemoryBackend, an existing-but-empty backing file for either file backend (both load an empty store), and a loaded store where no record matches. A missing backing file is not this path: both file backends raiseFileNotFoundErroron the firstget_result, notRecordNotFound.
Cross-process replay and file backends
Mode is fixed per instance, so the standard capture/replay workflow uses either the env var or two instances sharing one backend:
PickleBackend(filename)appends each record and re-dumps the entire store to disk on everyrecord_call, so recordings survive process exit. Loading is lazy: the file is read on the firstget_resultonly when the in-memory store is empty. Pickle preserves result types exactly. An existing-but-empty file loads as an empty store (theEOFErrorfrom pickling nothing is swallowed), so replay then raisesRecordNotFound; a missing file at replay time raisesFileNotFoundError(onlyEOFErroris swallowed).JSONBackend(filename)appends one JSON line{name: {args, kwargs, result}}per recorded call and lazily loads the whole file on the firstget_result. A missing file raisesFileNotFoundError; an existing-but-empty file (zero lines) yields an empty store and thusRecordNotFound.- The default
backend=NoneisInMemoryBackend, which is process-local: FAKE mode in a fresh interpreter with no file backend always raisesRecordNotFound.
Defaults and edge cases
Recorddefaults areargs=(),kwargs={},result=None.- Mode selection and name-uniqueness checks are orthogonal: a duplicate name fails even when nothing would otherwise touch the backend.
- The
Backendprotocol declaresget_result(self, name, record), but every shipped backend — and the FAKE wrapper's actual call — usesget_result(name, *args, **kwargs); custom backends must accept that shape.
Exact API Reference
autofake.backend.InMemoryBackend
- Import Path:
from autofake.backend import InMemoryBackend - Signature:
class InMemoryBackend:
def record_call(self, name: str, record: Record)
def get_result(self, name: str, *args, **kwargs) -> Any
- Raises (implementation must reproduce these exact messages):
Record not found
autofake.backend.PickleBackend
- Import Path:
from autofake.backend import PickleBackend - Required Test Import Paths:
- autofake.backend.PickleBackend
- Exact Test Import Statements:
- from autofake.backend import JSONBackend, PickleBackend
- Kind: class
- Signature:
class PickleBackend:
def __init__(self, filename)
def record_call(self, name: str, record: Record)
def dump(self)
def get_result(self, name: str, *args, **kwargs) -> Any
def __repr__(self)
- Raises (implementation must reproduce these exact messages):
Record not found
autofake.backend.JSONBackend
- Import Path:
from autofake.backend import JSONBackend - Required Test Import Paths:
- autofake.backend.JSONBackend
- Exact Test Import Statements:
- from autofake.backend import JSONBackend, PickleBackend
- Kind: class
- Signature:
class JSONBackend:
def __init__(self, filename)
def record_call(self, name: str, record: Record)
def get_result(self, name: str, *args, **kwargs) -> Any
- Raises (implementation must reproduce these exact messages):
Record not found
autofake.fakeit.FakeIt
- Import Path:
from autofake.fakeit import FakeIt - Required Test Import Paths:
- autofake.FakeIt
- Exact Test Import Statements:
- from autofake import FakeIt, Mode
- from autofake import FakeIt, Mode, NotUniqueName, RecordNotFound
- Kind: class
- Signature:
class FakeIt:
def __init__(self, mode: Optional[Mode]=None, backend: Optional[Backend]=None)
def __call__(self, function: Callable)
_mode: Any
_backend: Any
autofake.models.Mode
- Import Path:
from autofake.models import Mode - Required Test Import Paths:
- autofake.Mode
- Exact Test Import Statements:
- from autofake import FakeIt, Mode
- from autofake import FakeIt, Mode, NotUniqueName, RecordNotFound
- Kind: class
- Signature:
class Mode(str, Enum):
RECORD: Mode
FAKE: Mode
PRODUCTION: Mode
autofake.models.Record
- Import Path:
from autofake.models import Record - Required Test Import Paths:
- autofake.models.Record
- Exact Test Import Statements:
- from autofake.models import Record
- Kind: class
- Signature:
class Record:
args: Tuple[Any, ...]
kwargs: dict[str, Any]
result: Any
Capability: Library exception reporting
Purpose
AutoFake reports its two failure modes through a dedicated exception hierarchy in autofake.exceptions instead of leaking KeyError, ValueError, or bare Exception. That lets test code distinguish "this replay has no recording" from "this decoration collided" and handle each explicitly, while still being able to catch both with one base class.
Hierarchy shape
FakeItException— abstract catch-all base; the library never raises it directly. It is the direct base of exactly the two leaves below, soexcept FakeItExceptioncovers preciselyRecordNotFoundandNotUniqueName— and nothing else. Environmental errors surfaced through library calls (e.g.,FileNotFoundErrorfrom a file backend) are not subclasses and escape it; see Catching guidance.RecordNotFound(FakeItException)— a FAKE-mode lookup found no matching recording.NotUniqueName(FakeItException)— the sameFakeItinstance decorated a second function with an already-used__name__.
Both leaves are direct subclasses of the base with no intermediate classes. All three names are re-exported from the package root, so from autofake import RecordNotFound, NotUniqueName and from autofake.exceptions import RecordNotFound bind the same class objects; except behavior is identical either way. The classes are plain Exception subclasses with no custom __init__, attributes, or __str__ — stock semantics for pickling, repr, and chaining.
NotUniqueName: decoration time, not call time
Raised synchronously from the decorator application (FakeIt.__call__), before any mode dispatch. Practical consequences:
- Timing. The error fires when the decorated
defstatement is evaluated — i.e., at module import / pytest collection time — never when the function is later called. A module containing a duplicate decoration fails to import at all. - Mode independence. Because the uniqueness check runs first, PRODUCTION mode raises too, even though PRODUCTION otherwise returns the raw function and never touches the backend.
- Per-instance scope. Each
FakeItinstance tracks its own set of seen names. Two instances may each decorate their ownfetch; the same instance may not. Re-decorating the same function object twice with one instance also collides, since the check is by name, not identity. - Name basis. Only
function.__name__is compared.__qualname__, defining class, and signature are irrelevant, so two same-named methods in different classes collide. - State on failure. The colliding name is already in the set, so a rejected duplicate leaves instance state unchanged apart from the raised error; earlier decorated functions keep working.
Message: the literal string There is already a decorated function called {name} with the colliding name interpolated. Asserting on str(exc) is safe here.
RecordNotFound: FAKE-mode replay misses
Only raised when a fake-decorated function is called and the configured backend holds no record matching (name, args, kwargs). In FAKE mode the wrapper calls backend.get_result(function.__name__, *args, **kwargs) and returns its result; the real body never executes (the FAKE test even decorates a body that raises, proving it is never reached). PRODUCTION never touches the backend; RECORD only writes via record_call, so neither mode can produce this error.
All built-in backends raise RecordNotFound with the same fixed literal message "Record not found", so str(exc) assertions are safe with built-in backends; custom backends are required to raise only the type, not any particular message. FakeIt itself never constructs the error — backends do — so a custom Backend implementation must raise RecordNotFound (not KeyError, and not return None) on a miss to stay drop-in compatible with user except clauses.
Match semantics per backend
A miss occurs when no stored record for the name equals the call exactly:
InMemoryBackend/PickleBackend:record.args == args(tuple equality) andrecord.kwargs == kwargs(dict equality).JSONBackend: same intent, but comparisons run after JSON round-tripping —record["args"] == list(args)andrecord["kwargs"] == kwargs.
Consequences:
- Different positional args, different/missing/extra kwargs, or a different decoration name all miss. Defaults are materialized into the recorded call, so the fake-mode call must produce an identical arg tuple.
JSONBackendtuple fragility: JSON serializes tuples as lists, and thelist(args)normalization covers only the outer positional container — it does not inspect individual arguments. A call containing a tuple anywhere — a top-level positional argument such asfetch((1, 2)), a tuple nested inside another value, or a tuple as a kwargs value — round-trips to a JSON list on the recorded side while remaining a tuple inside the comparison ([1, 2] == (1, 2)isFalse), so a replay that would hit onInMemoryBackendraisesRecordNotFoundonJSONBackend. Only JSON-native values (scalars, lists, plain dicts) match reliably across record/replay.- Records for a name are kept in append order and scanned linearly; the first equal
(args, kwargs)wins. Recording the same call twice is allowed and simply creates two entries. - File backends load lazily on the first
get_resultwhen their in-memory store is empty. An empty recording file is swallowed (EOFErrorfor pickle) and surfaces asRecordNotFound; a nonexistent recording file, however, raisesFileNotFoundErrorfrom the open call — notRecordNotFound. Point the backend at the file only after recording, or create it first.
State and ordering on a miss
A miss raises immediately from the call, propagates out of the wrapper with no state mutation and no body execution. Earlier fake calls in the same run already returned their recorded values; later calls are never attempted. There is no automatic fallback to the real function — for pass-through-on-miss, catch RecordNotFound around the call and invoke the original yourself: functools.wraps sets __wrapped__ on the wrapper, so inside the handler the undecorated function is invocable as fetch.__wrapped__(*args, **kwargs). Alternatively, capture a reference to the undecorated function before decoration (_fetch_impl first, then fetch = fakeit(_fetch_impl)) and call that reference from the handler.
Catching guidance
except FakeItExceptionis not a universal catch-all: it covers exactlyRecordNotFoundandNotUniqueName, which are mutually exclusive. Environmental errors raised by the file backends —FileNotFoundErrorfor a missing recording file and similar non-hierarchy errors — are not subclasses ofFakeItExceptionand escape the catch-all, so give them their own handler (e.g.,except (RecordNotFound, FileNotFoundError)) rather than relying on the base class.- In tests,
pytest.raises(RecordNotFound)around a wrong-args replay andpytest.raises(NotUniqueName)around a duplicate decoration are the canonical assertions (both patterns appear in the suite). - Because
NotUniqueNamefires at import time, sharing one module-levelFakeItacross test files that define same-named helpers breaks collection; use a fresh instance per module (the suite's fixture pattern) or unique names. FakeIt(Mode.FAKE)with the defaultInMemoryBackendand no prior recording always raisesRecordNotFoundon the first call — the backend's lookup inserts an empty list for an unseen name and finds no match, rather than raisingKeyError.
Exact API Reference
autofake.exceptions.RecordNotFound
- Import Path:
from autofake.exceptions import RecordNotFound - Required Test Import Paths:
- autofake.RecordNotFound
- autofake.exceptions.RecordNotFound
- Exact Test Import Statements:
- from autofake import FakeIt, Mode, NotUniqueName, RecordNotFound
- from autofake.exceptions import RecordNotFound
- Kind: exception
- Signature:
class RecordNotFound(FakeItException)
autofake.exceptions.NotUniqueName
- Import Path:
from autofake.exceptions import NotUniqueName - Required Test Import Paths:
- autofake.NotUniqueName
- Exact Test Import Statements:
- from autofake import FakeIt, Mode, NotUniqueName, RecordNotFound
- Kind: exception
- Signature:
class NotUniqueName(FakeItException)
Detailed Implementation Nodes
Node: Configurable operating modes (PRODUCTION, RECORD, FAKE)
Functional constraints
FakeIt(mode=None, backend=None)resolves the mode once at construction: explicitmode>AUTOFAKEenv var (a non-empty value must equal"RECORD","FAKE", or"PRODUCTION"exactly; any other non-empty value raisesValueErrorat construction;AUTOFAKE=""counts as unset and yieldsMode.PRODUCTION) >Mode.PRODUCTION. Later env changes do not affect an existing instance.- Decorating registers
function.__name__before mode dispatch; a duplicate name within oneFakeItinstance raisesNotUniqueNameat decoration time in all modes, including PRODUCTION. Names are per-instance. - PRODUCTION returns the original function object (identity preserved, no wrapper, zero backend interaction). RECORD/FAKE return
functools.wraps-preserving wrappers keyed by the original__name__. - RECORD: run the real function; on normal return append
Record(args, kwargs, result)and return the real result; on exception, record nothing. - FAKE: never run the real function; return
backend.get_result(name, *args, **kwargs); no match raisesRecordNotFound("Record not found")with no fallback. - Matching is exact
==on the recordedargs/kwargsas passed: positional vs keyword call forms are distinct records; kwargs key order is irrelevant; the first matching record (call order) wins. - Default backend is
InMemoryBackend(process-local; FAKE with no in-process recordings always raisesRecordNotFound). PickleBackend(filename): persists the whole store on everyrecord_call; lazily loads on the firstget_resultwhen empty; pickle preserves types; an existing-but-empty file loads as an empty store (EOFError swallowed) so replay raisesRecordNotFound, while a missing file at replay raisesFileNotFoundError.JSONBackend(filename): one JSON line per record; lazy load; JSON coercions apply — results have tuples become lists, and nested tuple arguments (positional entries or keyword values) are stored as lists, so a replayed call passing tuples does not match; values must be JSON-serializable; an existing-but-empty file yieldsRecordNotFound; a missing file raisesFileNotFoundError.- Capture/replay across processes: share one file backend and flip the mode (constructor arg or
AUTOFAKE), never the backend contents.
Usage example
from autofake import FakeIt, Mode
from autofake.backend import PickleBackend
api = FakeIt(backend=PickleBackend("output.pickle"))
@api
def fetch_price(symbol: str) -> int:
return 42 # stand-in for the expensive real implementation
assert fetch_price("ACME") == 42
# PRODUCTION (default): runs normally. AUTOFAKE=RECORD: runs and persists the call.
# AUTOFAKE=FAKE: replays 42 from output.pickle without executing the body.
# Equivalent constructor forms: FakeIt(mode=Mode.RECORD, ...) / FakeIt(mode=Mode.FAKE, ...).
Node: Library exception reporting
Functional constraints
autofake/exceptions.pydefines exactly:FakeItException(Exception),RecordNotFound(FakeItException),NotUniqueName(FakeItException). No custom__init__, attributes, or__str__. All three are re-exported fromautofake(package root), so both import paths bind identical class objects.FakeItExceptionis never raised by the library; it is the shared base for user-side catch-alls over exactlyRecordNotFoundandNotUniqueName— non-hierarchy errors such as file-backendFileNotFoundErrorare not subclasses and escapeexcept FakeItException.NotUniqueNameis raised inFakeIt.__call__→_record_decoratedat decoration time, before mode dispatch (so PRODUCTION raises too), when oneFakeItinstance decorates a second function whose__name__matches one already registered on that instance. Exact message:There is already a decorated function called {name}. Check is per-instance and name-only; re-decorating the same object also collides. Failure leaves the instance's name set unchanged and does not register the duplicate.RecordNotFoundis raised byBackend.get_resultimplementations when no stored record for the name hasargs/kwargsequal to the call.FakeItnever constructs it; custom backends must raise it on a miss (notKeyError, notNone) and are bound only to the type, not to any particular message.- Built-in backends all raise it with the literal message
"Record not found". Matching:InMemory/Pickleuse exact tuple/dict equality;JSONBackendcomparesrecord["args"] == list(args)andrecord["kwargs"] == kwargsafter JSON round-trip. Thelist(args)normalization covers only the outer container: any tuple value at any depth insideargs— including a top-level tuple argument — or inside kwargs values is stored as a JSON list and will miss, so only JSON-native values (scalars, lists, plain dicts) match reliably across record/replay. First matching record in append order wins. - Reachable only in FAKE mode (wrapper =
backend.get_result(name, *args, **kwargs); body never runs). PRODUCTION bypasses the backend; RECORD only writes. A miss propagates immediately with no state change and no fallback to the real function; the wrapper's__wrapped__(set byfunctools.wraps) still exposes the original function for manual pass-through. - File backends lazy-load on first
get_result: an empty file yieldsRecordNotFound(pickleEOFErroris swallowed); a missing file raisesFileNotFoundError, notRecordNotFound— a non-hierarchy error that escapesexcept FakeItException. - Catch by type:
FakeItExceptioncatches both leaves; the leaves are mutually exclusive.NotUniqueNamefires at import/collection time, so it can abort a whole test module's import — use oneFakeItper module or unique names.
Example
from autofake import FakeIt, Mode, NotUniqueName, RecordNotFound
fakeit = FakeIt(Mode.FAKE) # fresh instance, nothing recorded
@fakeit
def fetch(a, b):
return a + b
try:
fetch(3, b=4) # body never runs; no recording matches
except RecordNotFound as e:
assert str(e) == "Record not found"
try:
@fakeit
def fetch(a, b): # duplicate __name__, same instance
return a - b
except NotUniqueName as e:
assert str(e) == "There is already a decorated function called fetch"