Skip to content

livery.forge.testing

livery.forge.testing

What every consumer tests against: the verified fake and the fixtures.

Three pieces, one purpose: forge-touching code proves itself without a forge.

  • livery.forge.testing.FakeForge answers the whole protocol from memory and injects known forge quirks deterministically through livery.forge.testing.Faults.
  • livery.forge.testing.SCENARIOS is the one conformance suite. It runs against the fake and against every real backend, unchanged, through a per-backend livery.forge.testing.ForgeDriver; the fake passing it is what makes the fake worth testing against.
  • livery.forge.testing.Cassette records real HTTP exchanges once and replays them forever, secrets scrubbed, so backend tests gate every merge without a network.

Classes:

Name Description
Cassette

An ordered recording of HTTP exchanges, loadable and savable as JSON.

CassetteError

Raised when replay and recording disagree.

Exchange

One recorded request and its response, secrets already scrubbed.

RecordingOpener

An opener that performs real requests and records each exchange.

ReplayOpener

An opener that answers from a cassette, in order, with no network.

UrlOpener

Anything that opens a urllib request: the one seam of this module.

ForgeDriver

What a backend's test rig supplies to run the shared scenarios.

Scenario

One conformance case: a name, its capability gates, and its body.

FakeDriver

The livery.forge.testing.ForgeDriver over a FakeForge.

FakeForge

A livery.forge.Forge that keeps everything in memory.

Faults

Deterministic fault injection, one attribute per known forge quirk.

Functions:

Name Description
shared_env_path

The machine's own shared env file: the one live read a test may make.

rig_record_path

The dev containers' own record of their URLs and tokens.

Attributes:

Name Type Description
FORMAT
REDACTED
VOLATILE
SCENARIOS tuple[Scenario, ...]

Every conformance scenario, in the order the groups are documented.

Outcome TypeAlias

What CI will do with a pushed commit.

RIG_RECORD

FORMAT module-attribute

FORMAT = 1

REDACTED module-attribute

REDACTED = 'REDACTED'

VOLATILE module-attribute

VOLATILE = 'VOLATILE'

SCENARIOS module-attribute

SCENARIOS: tuple[Scenario, ...] = (Scenario('identity', _identity), Scenario('repo-lifecycle', _repo_lifecycle), Scenario('branches', _branches), Scenario('tags', _tags), Scenario('addresses', _addresses), Scenario('governance-reads', _governance_reads), Scenario('configure-is-idempotent', _configure_is_idempotent), Scenario('configure-required-contexts', _configure_required_contexts, requires=('required_contexts',)), Scenario('configure-required-contexts-declined', _configure_required_contexts_declined, forbids=('required_contexts',)), Scenario('configure-secrets', _configure_secrets, requires=('ci_secrets',)), Scenario('configure-secrets-declined', _configure_secrets_declined, forbids=('ci_secrets',)), Scenario('pr-open-find-get', _pr_open_find_get), Scenario('pr-list', _pr_list), Scenario('pr-title-close-reopen', _pr_title_close_reopen), Scenario('pr-merge-now', _pr_merge_now), Scenario('pr-comment', _pr_comment), Scenario('pr-labels', _pr_labels), Scenario('arm-disarm', _arm_disarm, requires=('auto_merge',)), Scenario('arm-long-title', _arm_long_title, requires=('auto_merge',)), Scenario('armed-pr-merges-on-green', _armed_pr_merges_on_green, requires=('auto_merge',)), Scenario('status-progression', _status_progression), Scenario('runs-jobs-log', _runs_jobs_log), Scenario('rerun', _rerun), Scenario('cancel-run', _cancel_run), Scenario('cancel-run-forced', _cancel_run_forced, requires=('force_cancel',)), Scenario('cancel-run-force-declined', _cancel_run_force_declined, forbids=('force_cancel',)), Scenario('dispatch', _dispatch), Scenario('schedules', _schedules, requires=('pipeline_schedules',)), Scenario('schedules-declined', _schedules_declined, forbids=('pipeline_schedules',)), Scenario('release-by-tag', _release_by_tag), Scenario('release-assets', _release_assets), Scenario('issue-text-both-ways', _issue_text_both_ways), Scenario('issue-update', _issue_update), Scenario('issue-list-and-search', _issue_list_and_search), Scenario('issue-assign', _issue_assign), Scenario('issue-comment', _issue_comment), Scenario('issue-close', _issue_close), Scenario('issue-reopen', _issue_reopen), Scenario('governance-listings', _governance_listings), Scenario('configure-approvals', _configure_approvals, requires=('min_approvals',)), Scenario('approvals-declined', _approvals_declined, forbids=('min_approvals',)))

Every conformance scenario, in the order the groups are documented.

Outcome module-attribute

Outcome: TypeAlias = Literal['success', 'failure', 'hang', 'skipped']

What CI will do with a pushed commit.

success and failure are verdicts the run reaches once settled. hang is a held run: it stays live until the scenario either cancels it or settles it, and settling releases it to success. The held run is what makes the pending state, cancellation, and arming deterministic on every backend, however fast its runners are.

__all__ module-attribute

__all__ = ['FORMAT', 'REDACTED', 'RIG_RECORD', 'SCENARIOS', 'VOLATILE', 'Cassette', 'CassetteError', 'Exchange', 'FakeDriver', 'FakeForge', 'Faults', 'ForgeDriver', 'Outcome', 'RecordingOpener', 'ReplayOpener', 'Scenario', 'UrlOpener', 'rig_record_path', 'shared_env_path']

RIG_RECORD module-attribute

RIG_RECORD = '.forge-dev.env'

Cassette

Cassette(exchanges: Iterable[Exchange] = ())

An ordered recording of HTTP exchanges, loadable and savable as JSON.

Attributes:

Name Type Description
exchanges list[Exchange]

The exchanges, in the order they happened.

Hold exchanges, empty by default for a fresh recording.

Methods:

Name Description
load

Read the cassette at path.

save

Write the cassette to path, creating parent directories.

Source code in packages/forge/src/livery/forge/testing/_cassette.py
def __init__(self, exchanges: Iterable[Exchange] = ()) -> None:
    """Hold *exchanges*, empty by default for a fresh recording."""
    self.exchanges: list[Exchange] = list(exchanges)

exchanges instance-attribute

exchanges: list[Exchange] = list(exchanges)

load classmethod

load(path: Path) -> Cassette

Read the cassette at path.

Raises livery.forge.testing.CassetteError when the file's format number is not the one this module writes.

Source code in packages/forge/src/livery/forge/testing/_cassette.py
@classmethod
def load(cls, path: Path) -> Cassette:
    """Read the cassette at *path*.

    Raises livery.forge.testing.CassetteError when the file's
    format number is not the one this module writes.
    """
    data = json.loads(path.read_text("utf-8"))
    if data.get("format") != FORMAT:
        raise CassetteError(
            f"{path} has cassette format {data.get('format')!r}, and this"
            f" reader speaks format {FORMAT}: re-record the cassette"
        )
    return cls(Exchange(**raw) for raw in data["exchanges"])

save

save(path: Path) -> None

Write the cassette to path, creating parent directories.

Source code in packages/forge/src/livery/forge/testing/_cassette.py
def save(self, path: Path) -> None:
    """Write the cassette to *path*, creating parent directories."""
    path.parent.mkdir(parents=True, exist_ok=True)
    payload = {
        "format": FORMAT,
        "exchanges": [asdict(exchange) for exchange in self.exchanges],
    }
    path.write_text(json.dumps(payload, indent=2) + "\n", "utf-8")

CassetteError

Bases: Exception

Raised when replay and recording disagree.

The message names the request that arrived and the exchange the cassette holds, verbatim, so the drift is readable without re-running anything.

Exchange dataclass

Exchange(method: str, url: str, request_body: str, status: int, reason: str, content_type: str, response_body: str, location: str = '')

One recorded request and its response, secrets already scrubbed.

Attributes:

Name Type Description
method str

The HTTP method.

url str

The full URL, scrubbed.

request_body str

The request body as text, scrubbed. Empty when the request had none.

status int

The HTTP status code of the response.

reason str

The status line's reason phrase.

content_type str

The response's Content-Type header value.

response_body str

The response body as text, scrubbed.

location str

The Location header of a refused redirect, scrubbed. Empty for every other exchange. Carried so a caller that deliberately follows one refused redirect (a signed log URL) can do so from the replayed refusal too.

method instance-attribute

method: str

url instance-attribute

url: str

request_body instance-attribute

request_body: str

status instance-attribute

status: int

reason instance-attribute

reason: str

content_type instance-attribute

content_type: str

response_body instance-attribute

response_body: str

location class-attribute instance-attribute

location: str = ''

RecordingOpener

RecordingOpener(cassette: Cassette, *, secrets: tuple[str, ...] = (), volatile_bodies: tuple[str, ...] = (), scrub_fields: tuple[str, ...] = (), inner: UrlOpener | None = None)

An opener that performs real requests and records each exchange.

Wrap the opener a backend would use, run the operations once against the real server, then save the cassette. Every value in secrets is scrubbed from URLs and bodies before an exchange is stored, and request headers are never stored.

HTTP errors are recorded like any other exchange and re-raised, so the recording captures refusals as faithfully as successes.

Parameters:

Name Type Description Default
cassette Cassette

The cassette exchanges are appended to.

required
secrets tuple[str, ...]

The values that must never reach disk. Pass every token the recorded client holds.

()
scrub_fields tuple[str, ...]

JSON field names whose string values are redacted in stored response bodies: the secrets the server mints inside its answers, which no secret list can know in advance.

()
inner UrlOpener | None

The opener that actually talks to the network. The redirect-refusing default when omitted, never urllib's stock opener: following a redirect would forward the Authorization header to the new location, and a recording session holds real credentials.

None

Record through inner into cassette, scrubbing secrets.

A request whose URL contains any volatile_bodies substring has a nondeterministic body (an encrypted payload); it is stored as the VOLATILE marker and matched by method and URL alone on replay.

Methods:

Name Description
open

Send request, record the scrubbed exchange, answer as urllib does.

Attributes:

Name Type Description
cassette
Source code in packages/forge/src/livery/forge/testing/_cassette.py
def __init__(
    self,
    cassette: Cassette,
    *,
    secrets: tuple[str, ...] = (),
    volatile_bodies: tuple[str, ...] = (),
    scrub_fields: tuple[str, ...] = (),
    inner: UrlOpener | None = None,
) -> None:
    """Record through *inner* into *cassette*, scrubbing *secrets*.

    A request whose URL contains any *volatile_bodies* substring
    has a nondeterministic body (an encrypted payload); it is
    stored as the VOLATILE marker and matched by method and URL
    alone on replay.
    """
    self.cassette = cassette
    self._secrets = secrets
    self._volatile = volatile_bodies
    self._scrub_fields = scrub_fields
    self._inner: UrlOpener = inner if inner is not None else default_opener()

cassette instance-attribute

cassette = cassette

open

open(request: Request, /, *, timeout: float = 30.0) -> Any

Send request, record the scrubbed exchange, answer as urllib does.

Source code in packages/forge/src/livery/forge/testing/_cassette.py
def open(self, request: urllib.request.Request, /, *, timeout: float = 30.0) -> Any:
    """Send *request*, record the scrubbed exchange, answer as urllib does."""
    method = request.get_method()
    url = request.full_url
    body = _request_body(request)
    try:
        response = self._inner.open(request, timeout=timeout)
    except urllib.error.HTTPError as exc:
        detail = exc.read()
        exchange = self._record(
            method,
            url,
            body,
            status=exc.code,
            reason=exc.reason,
            content_type=exc.headers.get("Content-Type", ""),
            response_body=detail.decode("utf-8", errors="replace"),
            location=exc.headers.get("Location", ""),
        )
        raise _replay_error(exchange, url) from None
    raw = response.read()
    exchange = self._record(
        method,
        url,
        body,
        status=response.status,
        reason=getattr(response, "reason", "") or "",
        content_type=str(response.headers.get("Content-Type", "")),
        response_body=raw.decode("utf-8", errors="replace"),
    )
    return _response_for(exchange, url)

ReplayOpener

ReplayOpener(cassette: Cassette, *, secrets: tuple[str, ...] = ())

An opener that answers from a cassette, in order, with no network.

Each request must match the next recorded exchange on method, URL, and body, after the same scrubbing the recording applied. A mismatch or an exhausted cassette raises livery.forge.testing.CassetteError naming both sides, because a drifted request is the finding, not a nuisance.

Parameters:

Name Type Description Default
cassette Cassette

The recording to answer from.

required
secrets tuple[str, ...]

The values the replaying client holds where the recording held real ones. Scrubbed from incoming requests before matching, so a dummy token replays against a recording made with a real one.

()

Replay cassette, scrubbing secrets from incoming requests.

Methods:

Name Description
verify_exhausted

Raise unless every recorded exchange was replayed.

open

Answer request from the next recorded exchange.

Attributes:

Name Type Description
remaining int

How many recorded exchanges have not been replayed yet.

Source code in packages/forge/src/livery/forge/testing/_cassette.py
def __init__(self, cassette: Cassette, *, secrets: tuple[str, ...] = ()) -> None:
    """Replay *cassette*, scrubbing *secrets* from incoming requests."""
    self._exchanges = list(cassette.exchanges)
    self._secrets = secrets
    self._cursor = 0

remaining property

remaining: int

How many recorded exchanges have not been replayed yet.

verify_exhausted

verify_exhausted() -> None

Raise unless every recorded exchange was replayed.

A leftover exchange means the caller stopped making a request the recording made, which is drift in the quiet direction.

Source code in packages/forge/src/livery/forge/testing/_cassette.py
def verify_exhausted(self) -> None:
    """Raise unless every recorded exchange was replayed.

    A leftover exchange means the caller stopped making a request
    the recording made, which is drift in the quiet direction.
    """
    if self.remaining:
        nxt = self._exchanges[self._cursor]
        raise CassetteError(
            f"{self.remaining} recorded exchanges were never replayed;"
            f" the next one is {nxt.method} {nxt.url}"
        )

open

open(request: Request, /, *, timeout: float = 30.0) -> Any

Answer request from the next recorded exchange.

Source code in packages/forge/src/livery/forge/testing/_cassette.py
def open(self, request: urllib.request.Request, /, *, timeout: float = 30.0) -> Any:
    """Answer *request* from the next recorded exchange."""
    method = request.get_method()
    url = _scrub(request.full_url, self._secrets)
    body = _scrub(_request_body(request), self._secrets)
    if self._cursor >= len(self._exchanges):
        raise CassetteError(
            f"the cassette is exhausted and {method} {url} arrived:"
            " the caller makes a request the recording never made"
        )
    expected = self._exchanges[self._cursor]
    body_matches = (
        expected.request_body == VOLATILE or body == expected.request_body
    )
    if (method, url) != (expected.method, expected.url) or not body_matches:
        raise CassetteError(
            "replay mismatch:\n"
            f"  recorded: {expected.method} {expected.url}"
            f" body={expected.request_body!r}\n"
            f"  arrived:  {method} {url} body={body!r}\n"
            "Re-record the cassette if the new request is intended."
        )
    self._cursor += 1
    if expected.status >= 300:
        # Refused redirects (3xx) and refusals (4xx, 5xx) alike
        # replay as the errors the recording raised.
        raise _replay_error(expected, request.full_url)
    return _response_for(expected, request.full_url)

UrlOpener

Bases: Protocol

Anything that opens a urllib request: the one seam of this module.

urllib's own OpenerDirector satisfies it, and so do livery.forge.testing.RecordingOpener and livery.forge.testing.ReplayOpener, which is what lets a backend take its opener as a constructor argument and never know whether the network is real.

Methods:

Name Description
open

Open request and return a urllib response object.

open

open(request: Request, /, *, timeout: float = 30.0) -> Any

Open request and return a urllib response object.

Source code in packages/forge/src/livery/forge/testing/_cassette.py
def open(self, request: urllib.request.Request, /, *, timeout: float = 30.0) -> Any:
    """Open *request* and return a urllib response object."""
    ...

ForgeDriver

Bases: Protocol

What a backend's test rig supplies to run the shared scenarios.

The protocol under test only observes the forge; the driver moves the world the protocol observes. The fake moves dictionaries; a real driver creates commits, seeds workflow files, and polls. The scenarios cannot tell the difference, which is the point.

Methods:

Name Description
unused_repo_name

An owner and name no repository has yet.

fresh_repo

A new repository with an initialised default branch.

push

Push branch (creating it when new) and return its head sha.

create_tag

Create tag at the default branch's head.

settle

Return once every run for sha is terminal.

await_run

The one run matching the filters, once it exists.

comment_bodies

The comments on one pull request or issue, oldest first.

await_mergeable

Return once the forge has computed the pull request's mergeability.

await_merged

Return once the merge of number and its aftermath have landed.

await_branch

Return once branch's existence matches present.

await_issue

Return once listings serve issue number in its current state.

required_context

How this forge spells the seeded workflow's check context.

Attributes:

Name Type Description
forge Forge

The forge under test.

forge property

forge: Forge

The forge under test.

unused_repo_name

unused_repo_name() -> tuple[str, str]

An owner and name no repository has yet.

Source code in packages/forge/src/livery/forge/testing/_conformance.py
def unused_repo_name(self) -> tuple[str, str]:
    """An owner and name no repository has yet."""
    ...

fresh_repo

fresh_repo() -> Repository

A new repository with an initialised default branch.

The repository carries a dispatchable CI workflow the scenarios address as conf.yml, however the backend spells that underneath.

Source code in packages/forge/src/livery/forge/testing/_conformance.py
def fresh_repo(self) -> Repository:
    """A new repository with an initialised default branch.

    The repository carries a dispatchable CI workflow the
    scenarios address as ``conf.yml``, however the backend spells
    that underneath.
    """
    ...

push

push(repo_owner: str, repo_name: str, branch: str, *, outcome: Outcome = 'success') -> str

Push branch (creating it when new) and return its head sha.

CI starts on the pushed commit and will reach outcome once settled; a hang outcome stays live until cancelled. A real driver arranges this with the workflow it seeds (the branch or commit carries the outcome); the fake stores it on the run.

Source code in packages/forge/src/livery/forge/testing/_conformance.py
def push(
    self,
    repo_owner: str,
    repo_name: str,
    branch: str,
    *,
    outcome: Outcome = "success",
) -> str:
    """Push *branch* (creating it when new) and return its head sha.

    CI starts on the pushed commit and will reach *outcome* once
    settled; a ``hang`` outcome stays live until cancelled. A real
    driver arranges this with the workflow it seeds (the branch or
    commit carries the outcome); the fake stores it on the run.
    """
    ...

create_tag

create_tag(repo_owner: str, repo_name: str, tag: str) -> None

Create tag at the default branch's head.

Source code in packages/forge/src/livery/forge/testing/_conformance.py
def create_tag(self, repo_owner: str, repo_name: str, tag: str) -> None:
    """Create *tag* at the default branch's head."""
    ...

settle

settle(repo_owner: str, repo_name: str, sha: str) -> None

Return once every run for sha is terminal.

A held (hang) run is released and concludes success; the other outcomes conclude as pushed. The fake applies the outcome; a real driver releases its hold and polls.

Source code in packages/forge/src/livery/forge/testing/_conformance.py
def settle(self, repo_owner: str, repo_name: str, sha: str) -> None:
    """Return once every run for *sha* is terminal.

    A held (``hang``) run is released and concludes success; the
    other outcomes conclude as pushed. The fake applies the
    outcome; a real driver releases its hold and polls.
    """
    ...

await_run

await_run(repo_owner: str, repo_name: str, *, head_sha: str = '', event: str = '') -> Run

The one run matching the filters, once it exists.

Runs appear asynchronously on a real forge; this blocks until the matching run is listed. Exactly one run must match, and the run comes back as the listing named it.

Source code in packages/forge/src/livery/forge/testing/_conformance.py
def await_run(
    self, repo_owner: str, repo_name: str, *, head_sha: str = "", event: str = ""
) -> Run:
    """The one run matching the filters, once it exists.

    Runs appear asynchronously on a real forge; this blocks until
    the matching run is listed. Exactly one run must match, and
    the run comes back as the listing named it.
    """
    ...

comment_bodies

comment_bodies(repo_owner: str, repo_name: str, number: int, *, kind: Literal['pr', 'issue']) -> tuple[str, ...]

The comments on one pull request or issue, oldest first.

Source code in packages/forge/src/livery/forge/testing/_conformance.py
def comment_bodies(
    self,
    repo_owner: str,
    repo_name: str,
    number: int,
    *,
    kind: Literal["pr", "issue"],
) -> tuple[str, ...]:
    """The comments on one pull request or issue, oldest first."""
    ...

await_mergeable

await_mergeable(repo_owner: str, repo_name: str, number: int) -> None

Return once the forge has computed the pull request's mergeability.

A forge recomputes mergeability asynchronously after a pull request opens, and merging or arming inside that window is refused with a 405. Scenarios wait here before either verb; workflows retry on the 405 instead, which is the same contract from the other side.

Source code in packages/forge/src/livery/forge/testing/_conformance.py
def await_mergeable(self, repo_owner: str, repo_name: str, number: int) -> None:
    """Return once the forge has computed the pull request's mergeability.

    A forge recomputes mergeability asynchronously after a pull
    request opens, and merging or arming inside that window is
    refused with a 405. Scenarios wait here before either verb;
    workflows retry on the 405 instead, which is the same
    contract from the other side.
    """
    ...

await_merged

await_merged(repo_owner: str, repo_name: str, number: int) -> None

Return once the merge of number and its aftermath have landed.

A scheduled merge is performed by the forge after the checks go green, and even an immediate merge finishes its aftermath (the configured source branch deletion) asynchronously; the caller only ever observes both. This is the driver-side bound on that observation.

Source code in packages/forge/src/livery/forge/testing/_conformance.py
def await_merged(self, repo_owner: str, repo_name: str, number: int) -> None:
    """Return once the merge of *number* and its aftermath have landed.

    A scheduled merge is performed by the forge after the checks
    go green, and even an immediate merge finishes its aftermath
    (the configured source branch deletion) asynchronously; the
    caller only ever observes both. This is the driver-side bound
    on that observation.
    """
    ...

await_branch

await_branch(repo_owner: str, repo_name: str, branch: str, *, present: bool) -> None

Return once branch's existence matches present.

Branch reads are eventually consistent on github.com (a deleted branch answers for seconds afterwards); the fake is immediate, a real driver polls.

Source code in packages/forge/src/livery/forge/testing/_conformance.py
def await_branch(
    self, repo_owner: str, repo_name: str, branch: str, *, present: bool
) -> None:
    """Return once *branch*'s existence matches *present*.

    Branch reads are eventually consistent on github.com (a
    deleted branch answers for seconds afterwards); the fake is
    immediate, a real driver polls.
    """
    ...

await_issue

await_issue(repo_owner: str, repo_name: str, number: int, *, assignee: str = '') -> None

Return once listings serve issue number in its current state.

Issue listings are eventually consistent on some forges (about nine seconds behind on github.com), so a scenario that creates or assigns and then reads through a listing waits here first. When assignee is given, the served row must carry it.

Source code in packages/forge/src/livery/forge/testing/_conformance.py
def await_issue(
    self, repo_owner: str, repo_name: str, number: int, *, assignee: str = ""
) -> None:
    """Return once listings serve issue *number* in its current state.

    Issue listings are eventually consistent on some forges (about
    nine seconds behind on github.com), so a scenario that creates
    or assigns and then reads through a listing waits here first.
    When *assignee* is given, the served row must carry it.
    """
    ...

required_context

required_context() -> str

How this forge spells the seeded workflow's check context.

The string branch protection must name for the gate job: forges spell it differently (a bare job name, or workflow / job (event)), and the spelling is rig knowledge.

Source code in packages/forge/src/livery/forge/testing/_conformance.py
def required_context(self) -> str:
    """How this forge spells the seeded workflow's check context.

    The string branch protection must name for the gate job:
    forges spell it differently (a bare job name, or
    workflow / job (event)), and the spelling is rig knowledge.
    """
    ...

Scenario dataclass

Scenario(name: str, run: Callable[[ForgeDriver], None], requires: tuple[Capability, ...] = (), forbids: tuple[Capability, ...] = ())

One conformance case: a name, its capability gates, and its body.

Attributes:

Name Type Description
name str

The scenario's stable identifier, used as the test id.

run Callable[[ForgeDriver], None]

The body. Raises AssertionError when the backend breaks the contract.

requires tuple[Capability, ...]

Capabilities the forge must support for the scenario to apply.

forbids tuple[Capability, ...]

Capabilities the forge must NOT support: the scenario asserts the honest decline.

Methods:

Name Description
applies_to

Whether forge's capabilities put this scenario in scope.

name instance-attribute

name: str

run instance-attribute

run: Callable[[ForgeDriver], None]

requires class-attribute instance-attribute

requires: tuple[Capability, ...] = ()

forbids class-attribute instance-attribute

forbids: tuple[Capability, ...] = ()

applies_to

applies_to(forge: Forge) -> bool

Whether forge's capabilities put this scenario in scope.

Source code in packages/forge/src/livery/forge/testing/_conformance.py
def applies_to(self, forge: Forge) -> bool:
    """Whether *forge*'s capabilities put this scenario in scope."""
    return all(forge.supports(c) for c in self.requires) and not any(
        forge.supports(c) for c in self.forbids
    )

FakeDriver

FakeDriver(fake: FakeForge | None = None)

The livery.forge.testing.ForgeDriver over a FakeForge.

The reference driver: it makes the conformance scenarios runnable with no server at all, and shows a real backend's test rig what it must supply.

Parameters:

Name Type Description Default
fake FakeForge | None

The forge to drive. A fresh full-capability one when omitted.

None

Bind the driver to fake, creating one when omitted.

Methods:

Name Description
unused_repo_name

An owner and name no repository has yet.

fresh_repo

A new repository with an initialised default branch.

push

Push branch with outcome and return its new head sha.

create_tag

Create tag at the default branch's head.

settle

Apply every pushed outcome for sha; immediate on the fake.

await_run

The one run matching the filters; the fake never waits.

comment_bodies

The comments on one pull request or issue, oldest first.

await_mergeable

The fake computes mergeability synchronously: nothing to await.

await_merged

The fake merges inside settle: nothing to await.

await_branch

The fake is immediately consistent.

await_issue

The fake's listings are immediate: only verify the state.

required_context

The fake reports checks under the plain job name.

Attributes:

Name Type Description
fake FakeForge
forge FakeForge

The forge under test.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def __init__(self, fake: FakeForge | None = None) -> None:
    """Bind the driver to *fake*, creating one when omitted."""
    self.fake: FakeForge = fake if fake is not None else FakeForge()
    self._counter = 0

fake instance-attribute

fake: FakeForge = fake if fake is not None else FakeForge()

forge property

forge: FakeForge

The forge under test.

unused_repo_name

unused_repo_name() -> tuple[str, str]

An owner and name no repository has yet.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def unused_repo_name(self) -> tuple[str, str]:
    """An owner and name no repository has yet."""
    self._counter += 1
    return ("acme", f"repo-{self._counter}")

fresh_repo

fresh_repo() -> Repository

A new repository with an initialised default branch.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def fresh_repo(self) -> Repository:
    """A new repository with an initialised default branch."""
    owner, name = self.unused_repo_name()
    # An org shape for the listings: the caller is a member, as
    # on any real forge the scenarios run against.
    self.fake.set_members(owner, (self.fake.whoami(), "colleague"))
    self.fake.set_teams(owner, ("core",))
    return self.fake.create_repo(owner, name)

push

push(repo_owner: str, repo_name: str, branch: str, *, outcome: Outcome = 'success') -> str

Push branch with outcome and return its new head sha.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def push(
    self,
    repo_owner: str,
    repo_name: str,
    branch: str,
    *,
    outcome: Outcome = "success",
) -> str:
    """Push *branch* with *outcome* and return its new head sha."""
    return self.fake.push(repo_owner, repo_name, branch, outcome=outcome)

create_tag

create_tag(repo_owner: str, repo_name: str, tag: str) -> None

Create tag at the default branch's head.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def create_tag(self, repo_owner: str, repo_name: str, tag: str) -> None:
    """Create *tag* at the default branch's head."""
    self.fake.create_tag(repo_owner, repo_name, tag)

settle

settle(repo_owner: str, repo_name: str, sha: str) -> None

Apply every pushed outcome for sha; immediate on the fake.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def settle(self, repo_owner: str, repo_name: str, sha: str) -> None:
    """Apply every pushed outcome for *sha*; immediate on the fake."""
    self.fake.settle(repo_owner, repo_name, sha)

await_run

await_run(repo_owner: str, repo_name: str, *, head_sha: str = '', event: str = '') -> Run

The one run matching the filters; the fake never waits.

Raises AssertionError unless exactly one run matches, which is the driver contract.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def await_run(
    self, repo_owner: str, repo_name: str, *, head_sha: str = "", event: str = ""
) -> Run:
    """The one run matching the filters; the fake never waits.

    Raises AssertionError unless exactly one run matches, which is
    the driver contract.
    """
    runs = self.fake.repository(repo_owner, repo_name).checks.runs(
        head_sha=head_sha, event=event
    )
    assert len(runs) == 1, f"expected one matching run, found {len(runs)}"
    return runs[0]

comment_bodies

comment_bodies(repo_owner: str, repo_name: str, number: int, *, kind: Literal['pr', 'issue']) -> tuple[str, ...]

The comments on one pull request or issue, oldest first.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def comment_bodies(
    self,
    repo_owner: str,
    repo_name: str,
    number: int,
    *,
    kind: Literal["pr", "issue"],
) -> tuple[str, ...]:
    """The comments on one pull request or issue, oldest first."""
    return self.fake.comment_bodies(repo_owner, repo_name, number, kind=kind)

await_mergeable

await_mergeable(repo_owner: str, repo_name: str, number: int) -> None

The fake computes mergeability synchronously: nothing to await.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def await_mergeable(self, repo_owner: str, repo_name: str, number: int) -> None:
    """The fake computes mergeability synchronously: nothing to await."""
    self.fake._require_pr(self.fake._require_repo(repo_owner, repo_name), number)

await_merged

await_merged(repo_owner: str, repo_name: str, number: int) -> None

The fake merges inside settle: nothing to await.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def await_merged(self, repo_owner: str, repo_name: str, number: int) -> None:
    """The fake merges inside settle: nothing to await."""
    self.fake._require_pr(self.fake._require_repo(repo_owner, repo_name), number)

await_branch

await_branch(repo_owner: str, repo_name: str, branch: str, *, present: bool) -> None

The fake is immediately consistent.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def await_branch(
    self, repo_owner: str, repo_name: str, branch: str, *, present: bool
) -> None:
    """The fake is immediately consistent."""

await_issue

await_issue(repo_owner: str, repo_name: str, number: int, *, assignee: str = '') -> None

The fake's listings are immediate: only verify the state.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def await_issue(
    self, repo_owner: str, repo_name: str, number: int, *, assignee: str = ""
) -> None:
    """The fake's listings are immediate: only verify the state."""
    issue = self.fake._require_issue(
        self.fake._require_repo(repo_owner, repo_name), number
    )
    assert not assignee or assignee in issue.assignees

required_context

required_context() -> str

The fake reports checks under the plain job name.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def required_context(self) -> str:
    """The fake reports checks under the plain job name."""
    return "gate"

FakeForge

FakeForge(*, user: str = 'fake-user', version: str = '1.0.0', capabilities: tuple[Capability, ...] = _ALL_CAPABILITIES, token: str = '', dispatch_names_run: bool = True)

A livery.forge.Forge that keeps everything in memory.

The protocol half behaves as the conformance suite demands. The driver half simulates the world around the protocol: pushes, tags, and CI runs finishing. Faults are injected through the faults attribute; see livery.forge.testing.Faults.

Pull request and issue numbers count in separate spaces, as GitLab keeps them, so code that mixes the two fails here first.

Parameters:

Name Type Description Default
user str

What livery.forge.Forge.whoami answers.

'fake-user'
version str

What livery.forge.Forge.server_version answers.

'1.0.0'
capabilities tuple[Capability, ...]

What livery.forge.Forge.supports answers True for. Defaults to every known capability; pass a subset to model a forge that declines some by name.

_ALL_CAPABILITIES
dispatch_names_run bool

Whether livery.forge.Checks.dispatch returns the id of the run it started, as every backend's answer names it. False answers None, as a GitHub or Gitea server without the run's details does.

True

Build an empty forge for user with capabilities.

Methods:

Name Description
whoami

The configured user's login name.

server_version

The configured version string.

registry_url

A deterministic registry root per kind, for tests.

supports

Whether capability was granted at construction.

repository

The view onto one repository. Cheap, no existence check.

set_members

Test helper: what members(owner) answers for an org.

set_teams

Test helper: what teams(owner) answers for an org.

members

Configured members; a namespace nobody configured is a user.

teams

Configured teams; a namespace nobody configured has none.

codeowners

The fake's dialect: a root CODEOWNERS, GitHub-shaped.

user_url

The address of login's profile under the fake:// scheme.

set_protection

Test helper: what Repository.protection answers for branch.

review

Test helper: record a submitted review on a pull request.

create_repo

Create the repository with an initialised default branch.

get_repo

The repository's settings, or None when it does not exist.

delete_repo

Delete the repository; a repository already gone is success.

push

Simulate a git push: a new head sha on branch, CI starting.

branch_sha

What branch points at, empty when there is no such branch.

create_tag

Simulate a tag push: tag at the default branch's head.

start_runs

Simulate a runner taking every queued run for sha; none settles.

set_outcome

Change what CI will do with every run for sha that has not settled.

settle

Simulate CI settling: every run for sha reaches its outcome.

comment_bodies

The comments posted on one pull request or issue, oldest first.

Attributes:

Name Type Description
faults Faults
dispatch_names_run bool
budget RateBudget | None
token str

The credential this connection authenticates with; empty when anonymous.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def __init__(
    self,
    *,
    user: str = "fake-user",
    version: str = "1.0.0",
    capabilities: tuple[Capability, ...] = _ALL_CAPABILITIES,
    token: str = "",
    dispatch_names_run: bool = True,
) -> None:
    """Build an empty forge for *user* with *capabilities*."""
    self.faults: Faults = Faults()
    self.dispatch_names_run: bool = dispatch_names_run
    #: The API budget every repository view reports; None, as a forge
    #: that reports none, until a test sets one.
    self.budget: RateBudget | None = None
    self._token = token
    self._user = user
    self._version = version
    self._capabilities = frozenset(capabilities)
    self._repos: dict[tuple[str, str], _RepoState] = {}
    self._members: dict[str, tuple[str, ...]] = {}
    self._teams: dict[str, tuple[str, ...]] = {}
    self._next_sha = 1
    self._next_run = 1
    self._next_job = 1

faults instance-attribute

faults: Faults = Faults()

dispatch_names_run instance-attribute

dispatch_names_run: bool = dispatch_names_run

budget instance-attribute

budget: RateBudget | None = None

token property

token: str

The credential this connection authenticates with; empty when anonymous.

whoami

whoami() -> str

The configured user's login name.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def whoami(self) -> str:
    """The configured user's login name."""
    return self._user

server_version

server_version() -> str

The configured version string.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def server_version(self) -> str:
    """The configured version string."""
    return self._version

registry_url

registry_url(kind: RegistryKind, owner: str) -> str

A deterministic registry root per kind, for tests.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def registry_url(self, kind: RegistryKind, owner: str) -> str:
    """A deterministic registry root per kind, for tests."""
    if kind == "container":
        return f"registry.fake.example/{owner}"
    return f"https://fake.example/api/packages/{owner}/{kind}"

supports

supports(capability: Capability) -> bool

Whether capability was granted at construction.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def supports(self, capability: Capability) -> bool:
    """Whether *capability* was granted at construction."""
    return capability in self._capabilities

repository

repository(owner: str, name: str) -> Repository

The view onto one repository. Cheap, no existence check.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def repository(self, owner: str, name: str) -> Repository:
    """The view onto one repository. Cheap, no existence check."""
    return _FakeRepository(self, owner, name)

set_members

set_members(owner: str, members: tuple[str, ...]) -> None

Test helper: what members(owner) answers for an org.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def set_members(self, owner: str, members: tuple[str, ...]) -> None:
    """Test helper: what ``members(owner)`` answers for an org."""
    self._members[owner] = members

set_teams

set_teams(owner: str, teams: tuple[str, ...]) -> None

Test helper: what teams(owner) answers for an org.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def set_teams(self, owner: str, teams: tuple[str, ...]) -> None:
    """Test helper: what ``teams(owner)`` answers for an org."""
    self._teams[owner] = teams

members

members(owner: str) -> tuple[str, ...]

Configured members; a namespace nobody configured is a user.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def members(self, owner: str) -> tuple[str, ...]:
    """Configured members; a namespace nobody configured is a user."""
    return self._members.get(owner, (owner,))

teams

teams(owner: str) -> tuple[str, ...]

Configured teams; a namespace nobody configured has none.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def teams(self, owner: str) -> tuple[str, ...]:
    """Configured teams; a namespace nobody configured has none."""
    return self._teams.get(owner, ())

codeowners

codeowners(entries: tuple[CodeownersEntry, ...]) -> Codeowners

The fake's dialect: a root CODEOWNERS, GitHub-shaped.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def codeowners(self, entries: tuple[CodeownersEntry, ...]) -> Codeowners:
    """The fake's dialect: a root ``CODEOWNERS``, GitHub-shaped."""
    lines = []
    notes = []
    for entry in entries:
        owners = " ".join(f"@{name}" for name in entry.owners)
        lines.append(f"{entry.path} {owners}")
        if entry.min_approvals > 1:
            notes.append(
                f"{entry.path}: {entry.min_approvals} approvals wanted;"
                " the fake expresses one repository-wide count through"
                " protection, not per path"
            )
    return Codeowners(
        path="CODEOWNERS",
        content="\n".join(lines) + "\n" if lines else "",
        notes=tuple(notes),
    )

user_url

user_url(login: str) -> str

The address of login's profile under the fake:// scheme.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def user_url(self, login: str) -> str:
    """The address of *login*'s profile under the ``fake://`` scheme."""
    return f"fake://{login}"

set_protection

set_protection(owner: str, name: str, branch: str, protection: Protection) -> None

Test helper: what Repository.protection answers for branch.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def set_protection(
    self, owner: str, name: str, branch: str, protection: Protection
) -> None:
    """Test helper: what Repository.protection answers for *branch*."""
    self._require_repo(owner, name).protections[branch] = protection

review

review(owner: str, name: str, number: int, author: str, state: ReviewState) -> None

Test helper: record a submitted review on a pull request.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def review(
    self, owner: str, name: str, number: int, author: str, state: ReviewState
) -> None:
    """Test helper: record a submitted review on a pull request."""
    pr = self._require_pr(self._require_repo(owner, name), number)
    pr.reviews.append(Review(author=author, state=state))

create_repo

create_repo(owner: str, name: str, *, private: bool = True, description: str = '') -> Repository

Create the repository with an initialised default branch.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def create_repo(
    self,
    owner: str,
    name: str,
    *,
    private: bool = True,
    description: str = "",
) -> Repository:
    """Create the repository with an initialised default branch."""
    if (owner, name) in self._repos:
        raise ForgeError(
            f"repository {owner}/{name} already exists",
            status=409,
            method="POST",
            endpoint=f"/repos/{owner}/{name}",
        )
    state = _RepoState(
        owner=owner, name=name, private=private, description=description
    )
    state.branches[state.default_branch] = self._sha()
    self._repos[(owner, name)] = state
    return self.repository(owner, name)

get_repo

get_repo(owner: str, name: str) -> RepoInfo | None

The repository's settings, or None when it does not exist.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def get_repo(self, owner: str, name: str) -> RepoInfo | None:
    """The repository's settings, or None when it does not exist."""
    state = self._repos.get((owner, name))
    if state is None:
        return None
    return RepoInfo(
        owner=state.owner,
        name=state.name,
        default_branch=state.default_branch,
        private=state.private,
    )

delete_repo

delete_repo(owner: str, name: str) -> None

Delete the repository; a repository already gone is success.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def delete_repo(self, owner: str, name: str) -> None:
    """Delete the repository; a repository already gone is success."""
    self._repos.pop((owner, name), None)

push

push(owner: str, name: str, branch: str, *, outcome: Outcome = 'success', sha: str = '') -> str

Simulate a git push: a new head sha on branch, CI starting.

Creates the branch when it is new, moves its head to sha (a rig pairing the fake with a real repository passes the real commit, so sha-keyed reads agree across the seam) or a fresh deterministic one, and queues one run for that sha, as a push trigger would. The run stays queued until livery.forge.testing.FakeForge.settle applies outcome (a hang outcome is released to success there, or cancelled through the protocol). Returns the new head sha.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def push(
    self,
    owner: str,
    name: str,
    branch: str,
    *,
    outcome: Outcome = "success",
    sha: str = "",
) -> str:
    """Simulate a git push: a new head sha on *branch*, CI starting.

    Creates the branch when it is new, moves its head to *sha*
    (a rig pairing the fake with a real repository passes the
    real commit, so sha-keyed reads agree across the seam) or a
    fresh deterministic one, and queues one run for that sha, as
    a push trigger would. The run stays queued until
    livery.forge.testing.FakeForge.settle applies *outcome* (a
    ``hang`` outcome is released to success there, or cancelled
    through the protocol). Returns the new head sha.
    """
    state = self._require_repo(owner, name)
    sha = sha or self._sha()
    state.branches[branch] = sha
    self._start_run(
        state, sha, workflow="ci.yml", event="push", outcome=outcome, ref=branch
    )
    return sha

branch_sha

branch_sha(owner: str, name: str, branch: str) -> str

What branch points at, empty when there is no such branch.

The counterpart of livery.forge.testing.FakeForge.push, for a test that has to name a head it did not push: what a merge left on the base, which is the sha the base's own runs are filed under.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def branch_sha(self, owner: str, name: str, branch: str) -> str:
    """What *branch* points at, empty when there is no such branch.

    The counterpart of livery.forge.testing.FakeForge.push, for a
    test that has to name a head it did not push: what a merge
    left on the base, which is the sha the base's own runs are
    filed under.
    """
    return self._require_repo(owner, name).branches.get(branch, "")

create_tag

create_tag(owner: str, name: str, tag: str) -> None

Simulate a tag push: tag at the default branch's head.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def create_tag(self, owner: str, name: str, tag: str) -> None:
    """Simulate a tag push: *tag* at the default branch's head."""
    state = self._require_repo(owner, name)
    state.tags[tag] = state.branches[state.default_branch]

start_runs

start_runs(owner: str, name: str, sha: str) -> None

Simulate a runner taking every queued run for sha; none settles.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def start_runs(self, owner: str, name: str, sha: str) -> None:
    """Simulate a runner taking every queued run for *sha*; none settles."""
    state = self._require_repo(owner, name)
    for run_state in state.runs.values():
        if run_state.head_sha == sha and run_state.status == "queued":
            run_state.status = "running"
            run_state.started_at = _stamp(run_state.id * 60 + 3)

set_outcome

set_outcome(owner: str, name: str, sha: str, outcome: Outcome) -> None

Change what CI will do with every run for sha that has not settled.

A re-run reaches the outcome set here when it settles, so a rig can make the second attempt of a red run pass, as a flaky runner would.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def set_outcome(self, owner: str, name: str, sha: str, outcome: Outcome) -> None:
    """Change what CI will do with every run for *sha* that has not settled.

    A re-run reaches the outcome set here when it settles, so a
    rig can make the second attempt of a red run pass, as a
    flaky runner would.
    """
    state = self._require_repo(owner, name)
    for run_state in state.runs.values():
        if run_state.head_sha == sha and run_state.status != "completed":
            run_state.outcome = outcome

settle

settle(owner: str, name: str, sha: str) -> None

Simulate CI settling: every run for sha reaches its outcome.

A held (hang) run is released and concludes success, per the driver contract. While livery.forge.testing.Faults.wedge_status_queue holds, the results are silently dropped and the runs stay queued, which is what a wedged queue does to finished jobs. Settle again after clearing the fault.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def settle(self, owner: str, name: str, sha: str) -> None:
    """Simulate CI settling: every run for *sha* reaches its outcome.

    A held (``hang``) run is released and concludes success, per
    the driver contract. While
    livery.forge.testing.Faults.wedge_status_queue holds, the
    results are silently dropped and the runs stay queued, which
    is what a wedged queue does to finished jobs. Settle again
    after clearing the fault.
    """
    state = self._require_repo(owner, name)
    if self.faults.wedge_status_queue:
        return
    for run_state in state.runs.values():
        if run_state.head_sha != sha or run_state.status == "completed":
            continue
        conclusion: Conclusion = (
            "success" if run_state.outcome == "hang" else run_state.outcome
        )
        run_state.status = "completed"
        run_state.conclusion = conclusion
        run_state.log = f"job {run_state.job_id} concluded {conclusion}"
        # The settled run is timed like a real one: queued three
        # seconds, then a thirty-second job of one step.
        run_state.started_at = _stamp(run_state.id * 60 + 3)
        run_state.completed_at = _stamp(run_state.id * 60 + 33)
        run_state.steps = (
            Step("gate", conclusion, run_state.started_at, run_state.completed_at),
        )
    self._settle(state)

comment_bodies

comment_bodies(owner: str, name: str, number: int, *, kind: Literal['pr', 'issue']) -> tuple[str, ...]

The comments posted on one pull request or issue, oldest first.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def comment_bodies(
    self, owner: str, name: str, number: int, *, kind: Literal["pr", "issue"]
) -> tuple[str, ...]:
    """The comments posted on one pull request or issue, oldest first."""
    state = self._require_repo(owner, name)
    if kind == "pr":
        return tuple(self._require_pr(state, number).comments)
    return tuple(self._require_issue(state, number).comments)

Faults dataclass

Faults(lose_arm_schedule: int = 0, merge_405_window: int = 0, wedge_status_queue: bool = False, slow_status_reads: int = 0, drop_connections: int = 0, rate_limited: int = 0, rate_limit_reset: float | None = None)

Deterministic fault injection, one attribute per known forge quirk.

Counters arm a fault for the next N triggering calls and count down as they fire; a flag holds until cleared. Nothing here is random: a test arms exactly the fault it needs and the fake misbehaves exactly that often.

Attributes:

Name Type Description
lose_arm_schedule int

The next N calls to livery.forge.PullRequests.arm succeed silently without recording a schedule, so the pull request reads unarmed afterwards. The lost-auto-merge-schedule quirk.

merge_405_window int

The next N calls to livery.forge.PullRequests.merge_now or livery.forge.PullRequests.arm raise livery.forge.ForgeError with status 405, as a forge does while a mergeability recompute is in flight; the arm shares the merge endpoint, so the window refuses both.

wedge_status_queue bool

While True, runs never leave the queued state: a finished run is not recorded, so the combined status stays pending forever. Cancelling the run is the relief, as it is on a real wedged queue.

slow_status_reads int

The next N calls to livery.forge.Checks.status answer as if nothing had reported for the commit, as a forge does in the window after a push before statuses appear.

drop_connections int

The next N calls to livery.forge.Checks.status or livery.forge.Checks.runs raise livery.forge.ForgeError with no status, as the client does when the server closes the connection without a response mid-poll. The next call answers.

rate_limited int

The next N of those same calls raise livery.forge.RateLimited, as a forge does once the caller's API budget is spent; checked before drop_connections.

rate_limit_reset float | None

The reset time a rate_limited refusal names, as seconds since the epoch; None for a forge that does not say.

Methods:

Name Description
drop

Raise the armed poll fault: a spent budget first, then a dropped one.

lose_arm_schedule class-attribute instance-attribute

lose_arm_schedule: int = 0

merge_405_window class-attribute instance-attribute

merge_405_window: int = 0

wedge_status_queue class-attribute instance-attribute

wedge_status_queue: bool = False

slow_status_reads class-attribute instance-attribute

slow_status_reads: int = 0

drop_connections class-attribute instance-attribute

drop_connections: int = 0

rate_limited class-attribute instance-attribute

rate_limited: int = 0

rate_limit_reset class-attribute instance-attribute

rate_limit_reset: float | None = None

drop

drop(endpoint: str) -> None

Raise the armed poll fault: a spent budget first, then a dropped one.

Source code in packages/forge/src/livery/forge/testing/_fake.py
def drop(self, endpoint: str) -> None:
    """Raise the armed poll fault: a spent budget first, then a dropped one."""
    if self.rate_limited > 0:
        self.rate_limited -= 1
        raise RateLimited(
            f"HTTP 403 on GET {endpoint}: the forge's API rate limit is spent",
            reset_at=self.rate_limit_reset,
            status=403,
            method="GET",
            endpoint=endpoint,
        )
    if self.drop_connections > 0:
        self.drop_connections -= 1
        raise ForgeError(
            f"server unreachable on GET {endpoint}: Remote end closed"
            " connection without response",
            method="GET",
            endpoint=endpoint,
        )

shared_env_path

shared_env_path() -> Path

The machine's own shared env file: the one live read a test may make.

The dev containers' credentials live there. A test that needs them names this file by design and skips without it; every other read of the runner's directories goes through footman, whose pytest plugin points them at a temporary directory for the session.

Source code in packages/forge/src/livery/forge/testing/__init__.py
def shared_env_path() -> Path:
    """The machine's own shared env file: the one live read a test may make.

    The dev containers' credentials live there. A test that needs them
    names this file by design and skips without it; every other read of
    the runner's directories goes through footman, whose pytest plugin
    points them at a temporary directory for the session.
    """
    import os
    from pathlib import Path

    home = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
    return Path(home) / "footman" / ".repo.shared.env"

rig_record_path

rig_record_path() -> Path

The dev containers' own record of their URLs and tokens.

Their seed writes it, and nothing else does. The shared env file beside it names the cascade's current forge, which a local loop environment rewrites with its own Gitea's keys, so a test that drives the containers reads their credentials here, and skips without it.

Source code in packages/forge/src/livery/forge/testing/__init__.py
def rig_record_path() -> Path:
    """The dev containers' own record of their URLs and tokens.

    Their seed writes it, and nothing else does. The shared env file
    beside it names the cascade's current forge, which a local loop
    environment rewrites with its own Gitea's keys, so a test that
    drives the containers reads their credentials here, and skips
    without it.
    """
    return shared_env_path().parent / RIG_RECORD