mirror of
https://github.com/openswarm-ai/openswarm.git
synced 2026-09-22 09:34:53 +02:00
* [eric] ci: gitleaks-ignore the known historical secrets so our branch stops failing on leaks it didnt add * [eric] workflows: restore scheduled-tasks on the workflow line (revert removal, keep windows fixes + 1.1.69) * [eric] workflows: re-apply uncommitted scheduling wip (schedule pill, calendar view, slice) * [eric] ops: gitignore dev-team local state files * [eric] ops: backlog item for download-tracking visibility * [eric] ci: allowlist the cdp-routes redaction-test token in gitleaks * [aidan] feat/scheduled-tasks: keep step labels in sync on edit and show chevron on every step * [aidan] fix: schedule time in chat * [aidan] ux/workflows: add workflow step removal (#91) * [aidan] feat/scheduled-tasks: remember workflow tool permissions across runs * [aidan] feat/task-scheduling: add hourly and minute (15-min minimum) schedule intervals (#93) * [aidan] feat/scheduled-tasks: calendar, rename, and edit workflows (#94) * [aidan] bug: fix schedule button * [aidan] fix/agent-errors: surface provider rate limits * [aidan] ux/cards: click-to-rename for chat and workflow titles Single-click a card's title to enter edit mode inline. Commit on Enter/blur, cancel on Escape. Rename persists via PATCH for workflows and sessions. * [aidan] feat/workflows: seed build prompt for zero-step workflows When a new workflow has no steps, seed the agent with a prompt asking the user to describe what the workflow should do, rather than starting blank. * [aidan] feat/workflows: add-to-schedule popover for unscheduled workflows Clicking the "+" on an unscheduled workflow row opens a popover with two options: - Keep this schedule: enables the workflow's existing cadence and moves it to Scheduled - Change schedule: opens the scheduling editor to pick a different time * [aidan] ux/workflows: wire add-to-schedule popover and simplify New button - Made the "+" icon on unscheduled workflow rows clickable, opening a popover to keep or change the schedule - Removed AddIcon from toolbar "New" button (now reads "New" instead of "+ New") * [aidan] fix/scheduled-tasks: open schedule calendar when Schedule pill clicked Fixed the Schedule pill click being swallowed by the toolbar's dismiss handler. Exempted the toolbar pills via data-toolbar-pills so their click handlers fire. * [aidan] ux/workflows: open New workflow in agent build chat instead of empty card When creating a new workflow from the hub, open it in edit_agent view (with the agent builder chat) instead of a preview card. The workflow is created on the backend first so the embedded session has a real ID. * [aidan] feat/workflow-edit: add draft testing save flow * [aidan] ux/chat: remove continue chat button * [aidan] ux/workflows: polish workflow card interactions * [aidan] fix/workflow-scheduling: save unscheduled workflows as drafts * aidan ui: schedule naming changes * [aidan] ui: tool calling desc/naming * [aidan] ui: calendar sidebar naming * [aidan] ui: fix stop viewing closing chat * [aidan] feat/workflows: auto-name workflows and polish the build flow (#95) * [aidan] feat/workflow-auto-naming: auto-generate workflow titles from steps Generate a title + description from a workflow's steps (one aux call, reused for step labels) whenever it is still auto_named, so a workflow built in the Edit Agent names itself on commit instead of staying "New workflow". A manual rename sets auto_named=False and is never overwritten. Stream the aux call (non-streaming drops content on some 9router lanes) and fall back to a step-derived title when the model is unavailable. * [aidan] feat/workflows: hide unsaved new workflows until first save A brand-new "+ New" workflow is created with unsaved=true and kept out of the hub's scheduled/unscheduled lists while the user is still building it in the Edit Agent. The first commit (Save) clears the flag and the workflow appears. Every other create path stays visible immediately. * [aidan] ux/workflows: remove redundant save workflow button The Edit Agent already has Discard/Save controls in its strip, so the header "Save Workflow" button was a duplicate save path. Remove it and its pulse/edit-session-id wiring; the model/time subtitle stays. * [aidan] ux/workflows: animate title on auto-rename Wrap the workflow card title in the same Typewriter the chat card uses, so when the auto-generated name replaces the placeholder after Save it retypes letter-by-letter. Gated on a real (non-placeholder) title so it never animates on mount or for already-named workflows. * [aidan] ux/workflows: animate sidebar title on auto-rename Wrap the calendar hub's sidebar row title in the same Typewriter the workflow card uses, so a title that auto-renames retypes letter-by-letter in the sidebar too. Extract the placeholder/isRealTitle guard into the shared workflowVisuals so the card and sidebar stay in sync. * [aidan] fix/workflows: connect watch tether, keep watched chat open, wire draft run/history * [aidan] ui: grey out chat pill when not selected * [aidan] ui: fix running agent display * [aidan] feat/history-popover: add chat history and scheduled tasks run log tabs (#96) * [aidan] ux/schedule: toast when calendar view already open on expand * [aidan] ui: fix popover descs * [aidan] feat/workflow-runs: add pause, resume, and stop controls for live runs * [aidan] feat/schedule-calendar: add calendar occurrences endpoint and concrete timezones * [aidan] feat/workflows: require at least one step to save a workflow * [aidan] ux/edit-agent: hide Discard for an unsaved new workflow * [aidan] ux/edit-agent: move fix-prefix card below the step list * [aidan] feat/workflows: toast when an unattended scheduled run starts * [aidan] fix/dashboard-tethers: anchor workflow-sidecar tethers to measured card rects * [aidan] feat/workflows: validate steps before scheduling and keep chat tool memory * [aidan] feat/mcp-suggestions: dismissable integration banner with per-session cooldown * [aidan] feat/workflows: add scheduled-run "running now" toast with click-to-view (#97) * [aidan] ux/workflows: surface paused state on card, sidebar, and calendar; tidy run history * [aidan] feat/mcp-suggestions: suggest both Google and Microsoft when provider is ambiguous * [aidan] fix/agent-tokens: friendly out-of-tokens card across all agent surfaces * [aidan] feat/workflow-model: persist edit-agent model on save with switch notice and fresh drafts * [aidan] fix/workflow-chat: force stop on watched run mirrors workflow card stop * [aidan] fix/workflow-cards: keep watched run tethered on finish to avoid duplicate chat * [aidan] feat/schedule-calendar: mark current time with a now line in week view * [aidan] refactor/private-names: rename error and schedule classifiers from _ to p_ * [aidan] feat/scheduled-tasks: agent workflow scheduling and in-chat convert (#98) * [aidan] feat/workflow-suggest: nudge user to convert repeatable chat to workflow Add SuggestConvertToWorkflow MCP tool that agents call at the end of a task when they've completed something worth repeating (daily report, weekly check, recurring data pull). Frontend detects the tool call and glows the "Convert to workflow" button 3 times to draw the eye. When user clicks it, the suggested cadence (e.g. "every weekday at 9am") is stored in the draft and seeded into the scheduling agent's first prompt, so the agent can act on the suggestion rather than asking the user again. Tool is never auto-called — agents decide when a task is genuinely repeatable (not debugging, creative work, one-off lookup). Tool description emphasizes sparse, high-confidence use only (once per session max). Files changed: - backend/apps/agents/schedule_mcp_server.py: add SuggestConvertToWorkflow tool - frontend/src/shared/mcpToolMeta.ts: add label for new tool - frontend/src/app/pages/Dashboard/cards/AgentCard.tsx: detect suggestion in session messages, show+glow "Convert to workflow" button, pass cadence to draft - frontend/src/shared/state/workflowsSlice.ts: add suggested_cadence field to Workflow interface - frontend/src/app/pages/Workflows/SchedulingView.tsx: seed scheduling agent prompt with suggested cadence hint * [aidan] feat/agent-scheduling: route recurring asks through native workflows, deny claude cron skill * [aidan] feat/workflow-convert: in-chat convert popup and auto-open scheduled workflow card * [aidan] ux/calendar-page: schedule calendar restyle + popover fixes (#99) * [aidan] fix/dashboard-delete: remove workflows calendar panel on delete key * [aidan] ux/workflows-calendar: restyle hub, fix today highlight, add toolbar toggle * [aidan] ux/schedule-popover: compact density, fix sticky header bleed, add header spacing * [aidan] ux/schedule-calendar: hollow ring dot for past fires in month view * [aidan] ux/schedule-calendar: clickable +N more opens day's full run list * [aidan] feat/run-log-filters: add success and skipped pills to scheduled task history * [aidan] fix/convert-button: stop drag capture so convert-to-workflow click fires * [aidan] ux/calendar-card: match border color and radius to chat and workflow cards * [aidan] fix/minimap: render missed-runs card on the minimap * [aidan] ux/run-sparkline: simplify tooltip to plain run tally * [aidan] ux/run-history: collapse expanded run view to one clickable line * [aidan] ux/calendar-card: match corner radius to browser cards * [aidan] feat/workflows: launch-time scheduling UX and workflow-card polish (#101) * [aidan] feat/schedule-list: lazy-load list view via scroll sentinel * [aidan] feat/missed-runs: launch toast with per-workflow counts and pan-to-card * [aidan] fix/dashboard-tethers: keep watching line anchored on canvas zoom * [aidan] feat/scheduled-tasks: review missed runs at launch instead of auto-firing on_missed * [aidan] refactor/workflow-cards: use radius and status design tokens, polish card chrome * [aidan] ux/agent-card: keep convert-to-workflow visible during runs with mid-turn toast * [aidan] ux/mcp-bubble: drop redundant verb label when a workflow label is shown * [aidan] chore/backend: remove stale explanatory comments * [aidan] fix/workflows-hub: load workflows on hub mount so calendar fills at launch * [aidan] feat/workflows: generate title, description, step labels at convert time * [aidan] fix/tidy-layout: include workflows hub in tidy and fit-to-view * [aidan] feat/schedule-list: window long list via measured-height virtualizer * [aidan] ux/workflows-hub: remove time-saved badge from calendar header * [aidan] fix/types: add missing semantic-type labels and drop stray fade arg * [aidan] feat/schedule: pin monthly day-of-month and honor repeat-every intervals * [aidan] feat/schedule: inherit source-session tool surface for scheduled runs * [aidan] ux/calendar: restack hour-cell events as bars with overflow affordance * [aidan] feat/calendar: open the run card when clicking a scheduled occurrence * [aidan] ux/missed-runs: add per-group select-all toggle and rename skip action * [aidan] feat: new scheduled task design ported * [aidan] ui: sidebar reorder, repeat controls on schedule card * [aidan] ui: sidebar, scheduling time * [aidan] feat/schedule: pin monthly last-day-of-month * [aidan] feat/steps: per-step enable toggle * [aidan] feat/workflows: per-workflow color swatch * [aidan] feat/trash: soft-delete workflows with restore and purge * [aidan] feat/run-monitor: live run monitor card on the canvas * [aidan] feat/run-context: attach a run as removable chat context * [aidan] feat/compose: new-workflow landing page and auto-commit build flow * [aidan] ui/workflows: dark mode and design-system cohesion * [aidan] ui/calendar: overflow popover, condensed week view, scroll fix * [aidan] feat/home: ongoing runs, missed review, and accurate Coming-up counts * [aidan] fix/run-status: sync ongoing runs and heal stuck/interrupted runs * [aidan] ux/schedule: last-day-of-month UI, Run-at time typing, interval input * [aidan] ux/workflows: default window size and toolbar icon * [aidan] fix/schedule: measure ran_late from start and anchor recurrences to created_at * [aidan] feat/calendar: render fire times from backend, drop JS recurrence reimpl * [aidan] chore/dashboard: drop dead configure/missed-run cards, refetch on reconnect * [aidan] chore/agent-card: remove unreachable convert-to-workflow action * [aidan] fix/workflows: don't bump updated_at on a no-op draft commit so viewing a workflow doesn't reorder the sidebar * [aidan] feat/schedule: warn when scheduling a workflow that has no steps * [aidan] fix/selection-tool: never select the workflows app, and exit the tool on Escape without dropping selections * [aidan] ux/compose: diversify new-workflow starter prompts across personas * [aidan] ux/run-monitor: spawn the run card a bit farther right of the workflows app * [aidan] fix/schedule: harden run recovery and storage writes against crashes * [aidan] ux/compose: restyle new-workflow starters as a clean pill cluster with rich prompts * [aidan] fix/workflows: optimistically apply edits so the schedule banner updates instantly * [aidan] ui/workflows: three-tone surface depth so the window lifts off the canvas in both themes * [aidan] ui/workflows: close buttons turn red on hover, matching the chat card * [aidan] test/schedule: cover executor pipeline, storage durability, and recurrence gaps * [aidan] fix: remove package-lock json * [aidan] fix/workflows-compose: keep compose view until edit agent replies * [aidan] feat/workflows: auto-generate workflow + step titles with typewriter animation * [eric] deps: restore frontend/package-lock.json (PR #105 deletion broke npm ci) --------- Co-authored-by: Eric <ciregenz@berkeley.edu> Co-authored-by: cire <134991075+ciregenz@users.noreply.github.com>
572 lines
19 KiB
Python
572 lines
19 KiB
Python
# mypy: allow-untyped-defs
|
|
"""Basic collect and runtest protocol implementations."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import bdb
|
|
import dataclasses
|
|
import os
|
|
import sys
|
|
import types
|
|
from typing import Callable
|
|
from typing import cast
|
|
from typing import final
|
|
from typing import Generic
|
|
from typing import Literal
|
|
from typing import TYPE_CHECKING
|
|
from typing import TypeVar
|
|
|
|
from .reports import BaseReport
|
|
from .reports import CollectErrorRepr
|
|
from .reports import CollectReport
|
|
from .reports import TestReport
|
|
from _pytest import timing
|
|
from _pytest._code.code import ExceptionChainRepr
|
|
from _pytest._code.code import ExceptionInfo
|
|
from _pytest._code.code import TerminalRepr
|
|
from _pytest.config.argparsing import Parser
|
|
from _pytest.deprecated import check_ispytest
|
|
from _pytest.nodes import Collector
|
|
from _pytest.nodes import Directory
|
|
from _pytest.nodes import Item
|
|
from _pytest.nodes import Node
|
|
from _pytest.outcomes import Exit
|
|
from _pytest.outcomes import OutcomeException
|
|
from _pytest.outcomes import Skipped
|
|
from _pytest.outcomes import TEST_OUTCOME
|
|
|
|
|
|
if sys.version_info < (3, 11):
|
|
from exceptiongroup import BaseExceptionGroup
|
|
|
|
if TYPE_CHECKING:
|
|
from _pytest.main import Session
|
|
from _pytest.terminal import TerminalReporter
|
|
|
|
#
|
|
# pytest plugin hooks.
|
|
|
|
|
|
def pytest_addoption(parser: Parser) -> None:
|
|
group = parser.getgroup("terminal reporting", "Reporting", after="general")
|
|
group.addoption(
|
|
"--durations",
|
|
action="store",
|
|
type=int,
|
|
default=None,
|
|
metavar="N",
|
|
help="Show N slowest setup/test durations (N=0 for all)",
|
|
)
|
|
group.addoption(
|
|
"--durations-min",
|
|
action="store",
|
|
type=float,
|
|
default=0.005,
|
|
metavar="N",
|
|
help="Minimal duration in seconds for inclusion in slowest list. "
|
|
"Default: 0.005.",
|
|
)
|
|
|
|
|
|
def pytest_terminal_summary(terminalreporter: TerminalReporter) -> None:
|
|
durations = terminalreporter.config.option.durations
|
|
durations_min = terminalreporter.config.option.durations_min
|
|
verbose = terminalreporter.config.get_verbosity()
|
|
if durations is None:
|
|
return
|
|
tr = terminalreporter
|
|
dlist = []
|
|
for replist in tr.stats.values():
|
|
for rep in replist:
|
|
if hasattr(rep, "duration"):
|
|
dlist.append(rep)
|
|
if not dlist:
|
|
return
|
|
dlist.sort(key=lambda x: x.duration, reverse=True)
|
|
if not durations:
|
|
tr.write_sep("=", "slowest durations")
|
|
else:
|
|
tr.write_sep("=", f"slowest {durations} durations")
|
|
dlist = dlist[:durations]
|
|
|
|
for i, rep in enumerate(dlist):
|
|
if verbose < 2 and rep.duration < durations_min:
|
|
tr.write_line("")
|
|
tr.write_line(
|
|
f"({len(dlist) - i} durations < {durations_min:g}s hidden. Use -vv to show these durations.)"
|
|
)
|
|
break
|
|
tr.write_line(f"{rep.duration:02.2f}s {rep.when:<8} {rep.nodeid}")
|
|
|
|
|
|
def pytest_sessionstart(session: Session) -> None:
|
|
session._setupstate = SetupState()
|
|
|
|
|
|
def pytest_sessionfinish(session: Session) -> None:
|
|
session._setupstate.teardown_exact(None)
|
|
|
|
|
|
def pytest_runtest_protocol(item: Item, nextitem: Item | None) -> bool:
|
|
ihook = item.ihook
|
|
ihook.pytest_runtest_logstart(nodeid=item.nodeid, location=item.location)
|
|
runtestprotocol(item, nextitem=nextitem)
|
|
ihook.pytest_runtest_logfinish(nodeid=item.nodeid, location=item.location)
|
|
return True
|
|
|
|
|
|
def runtestprotocol(
|
|
item: Item, log: bool = True, nextitem: Item | None = None
|
|
) -> list[TestReport]:
|
|
hasrequest = hasattr(item, "_request")
|
|
if hasrequest and not item._request: # type: ignore[attr-defined]
|
|
# This only happens if the item is re-run, as is done by
|
|
# pytest-rerunfailures.
|
|
item._initrequest() # type: ignore[attr-defined]
|
|
rep = call_and_report(item, "setup", log)
|
|
reports = [rep]
|
|
if rep.passed:
|
|
if item.config.getoption("setupshow", False):
|
|
show_test_item(item)
|
|
if not item.config.getoption("setuponly", False):
|
|
reports.append(call_and_report(item, "call", log))
|
|
# If the session is about to fail or stop, teardown everything - this is
|
|
# necessary to correctly report fixture teardown errors (see #11706)
|
|
if item.session.shouldfail or item.session.shouldstop:
|
|
nextitem = None
|
|
reports.append(call_and_report(item, "teardown", log, nextitem=nextitem))
|
|
# After all teardown hooks have been called
|
|
# want funcargs and request info to go away.
|
|
if hasrequest:
|
|
item._request = False # type: ignore[attr-defined]
|
|
item.funcargs = None # type: ignore[attr-defined]
|
|
return reports
|
|
|
|
|
|
def show_test_item(item: Item) -> None:
|
|
"""Show test function, parameters and the fixtures of the test item."""
|
|
tw = item.config.get_terminal_writer()
|
|
tw.line()
|
|
tw.write(" " * 8)
|
|
tw.write(item.nodeid)
|
|
used_fixtures = sorted(getattr(item, "fixturenames", []))
|
|
if used_fixtures:
|
|
tw.write(" (fixtures used: {})".format(", ".join(used_fixtures)))
|
|
tw.flush()
|
|
|
|
|
|
def pytest_runtest_setup(item: Item) -> None:
|
|
_update_current_test_var(item, "setup")
|
|
item.session._setupstate.setup(item)
|
|
|
|
|
|
def pytest_runtest_call(item: Item) -> None:
|
|
_update_current_test_var(item, "call")
|
|
try:
|
|
del sys.last_type
|
|
del sys.last_value
|
|
del sys.last_traceback
|
|
if sys.version_info >= (3, 12, 0):
|
|
del sys.last_exc # type:ignore[attr-defined]
|
|
except AttributeError:
|
|
pass
|
|
try:
|
|
item.runtest()
|
|
except Exception as e:
|
|
# Store trace info to allow postmortem debugging
|
|
sys.last_type = type(e)
|
|
sys.last_value = e
|
|
if sys.version_info >= (3, 12, 0):
|
|
sys.last_exc = e # type:ignore[attr-defined]
|
|
assert e.__traceback__ is not None
|
|
# Skip *this* frame
|
|
sys.last_traceback = e.__traceback__.tb_next
|
|
raise
|
|
|
|
|
|
def pytest_runtest_teardown(item: Item, nextitem: Item | None) -> None:
|
|
_update_current_test_var(item, "teardown")
|
|
item.session._setupstate.teardown_exact(nextitem)
|
|
_update_current_test_var(item, None)
|
|
|
|
|
|
def _update_current_test_var(
|
|
item: Item, when: Literal["setup", "call", "teardown"] | None
|
|
) -> None:
|
|
"""Update :envvar:`PYTEST_CURRENT_TEST` to reflect the current item and stage.
|
|
|
|
If ``when`` is None, delete ``PYTEST_CURRENT_TEST`` from the environment.
|
|
"""
|
|
var_name = "PYTEST_CURRENT_TEST"
|
|
if when:
|
|
value = f"{item.nodeid} ({when})"
|
|
# don't allow null bytes on environment variables (see #2644, #2957)
|
|
value = value.replace("\x00", "(null)")
|
|
os.environ[var_name] = value
|
|
else:
|
|
os.environ.pop(var_name)
|
|
|
|
|
|
def pytest_report_teststatus(report: BaseReport) -> tuple[str, str, str] | None:
|
|
if report.when in ("setup", "teardown"):
|
|
if report.failed:
|
|
# category, shortletter, verbose-word
|
|
return "error", "E", "ERROR"
|
|
elif report.skipped:
|
|
return "skipped", "s", "SKIPPED"
|
|
else:
|
|
return "", "", ""
|
|
return None
|
|
|
|
|
|
#
|
|
# Implementation
|
|
|
|
|
|
def call_and_report(
|
|
item: Item, when: Literal["setup", "call", "teardown"], log: bool = True, **kwds
|
|
) -> TestReport:
|
|
ihook = item.ihook
|
|
if when == "setup":
|
|
runtest_hook: Callable[..., None] = ihook.pytest_runtest_setup
|
|
elif when == "call":
|
|
runtest_hook = ihook.pytest_runtest_call
|
|
elif when == "teardown":
|
|
runtest_hook = ihook.pytest_runtest_teardown
|
|
else:
|
|
assert False, f"Unhandled runtest hook case: {when}"
|
|
reraise: tuple[type[BaseException], ...] = (Exit,)
|
|
if not item.config.getoption("usepdb", False):
|
|
reraise += (KeyboardInterrupt,)
|
|
call = CallInfo.from_call(
|
|
lambda: runtest_hook(item=item, **kwds), when=when, reraise=reraise
|
|
)
|
|
report: TestReport = ihook.pytest_runtest_makereport(item=item, call=call)
|
|
if log:
|
|
ihook.pytest_runtest_logreport(report=report)
|
|
if check_interactive_exception(call, report):
|
|
ihook.pytest_exception_interact(node=item, call=call, report=report)
|
|
return report
|
|
|
|
|
|
def check_interactive_exception(call: CallInfo[object], report: BaseReport) -> bool:
|
|
"""Check whether the call raised an exception that should be reported as
|
|
interactive."""
|
|
if call.excinfo is None:
|
|
# Didn't raise.
|
|
return False
|
|
if hasattr(report, "wasxfail"):
|
|
# Exception was expected.
|
|
return False
|
|
if isinstance(call.excinfo.value, (Skipped, bdb.BdbQuit)):
|
|
# Special control flow exception.
|
|
return False
|
|
return True
|
|
|
|
|
|
TResult = TypeVar("TResult", covariant=True)
|
|
|
|
|
|
@final
|
|
@dataclasses.dataclass
|
|
class CallInfo(Generic[TResult]):
|
|
"""Result/Exception info of a function invocation."""
|
|
|
|
_result: TResult | None
|
|
#: The captured exception of the call, if it raised.
|
|
excinfo: ExceptionInfo[BaseException] | None
|
|
#: The system time when the call started, in seconds since the epoch.
|
|
start: float
|
|
#: The system time when the call ended, in seconds since the epoch.
|
|
stop: float
|
|
#: The call duration, in seconds.
|
|
duration: float
|
|
#: The context of invocation: "collect", "setup", "call" or "teardown".
|
|
when: Literal["collect", "setup", "call", "teardown"]
|
|
|
|
def __init__(
|
|
self,
|
|
result: TResult | None,
|
|
excinfo: ExceptionInfo[BaseException] | None,
|
|
start: float,
|
|
stop: float,
|
|
duration: float,
|
|
when: Literal["collect", "setup", "call", "teardown"],
|
|
*,
|
|
_ispytest: bool = False,
|
|
) -> None:
|
|
check_ispytest(_ispytest)
|
|
self._result = result
|
|
self.excinfo = excinfo
|
|
self.start = start
|
|
self.stop = stop
|
|
self.duration = duration
|
|
self.when = when
|
|
|
|
@property
|
|
def result(self) -> TResult:
|
|
"""The return value of the call, if it didn't raise.
|
|
|
|
Can only be accessed if excinfo is None.
|
|
"""
|
|
if self.excinfo is not None:
|
|
raise AttributeError(f"{self!r} has no valid result")
|
|
# The cast is safe because an exception wasn't raised, hence
|
|
# _result has the expected function return type (which may be
|
|
# None, that's why a cast and not an assert).
|
|
return cast(TResult, self._result)
|
|
|
|
@classmethod
|
|
def from_call(
|
|
cls,
|
|
func: Callable[[], TResult],
|
|
when: Literal["collect", "setup", "call", "teardown"],
|
|
reraise: type[BaseException] | tuple[type[BaseException], ...] | None = None,
|
|
) -> CallInfo[TResult]:
|
|
"""Call func, wrapping the result in a CallInfo.
|
|
|
|
:param func:
|
|
The function to call. Called without arguments.
|
|
:type func: Callable[[], _pytest.runner.TResult]
|
|
:param when:
|
|
The phase in which the function is called.
|
|
:param reraise:
|
|
Exception or exceptions that shall propagate if raised by the
|
|
function, instead of being wrapped in the CallInfo.
|
|
"""
|
|
excinfo = None
|
|
start = timing.time()
|
|
precise_start = timing.perf_counter()
|
|
try:
|
|
result: TResult | None = func()
|
|
except BaseException:
|
|
excinfo = ExceptionInfo.from_current()
|
|
if reraise is not None and isinstance(excinfo.value, reraise):
|
|
raise
|
|
result = None
|
|
# use the perf counter
|
|
precise_stop = timing.perf_counter()
|
|
duration = precise_stop - precise_start
|
|
stop = timing.time()
|
|
return cls(
|
|
start=start,
|
|
stop=stop,
|
|
duration=duration,
|
|
when=when,
|
|
result=result,
|
|
excinfo=excinfo,
|
|
_ispytest=True,
|
|
)
|
|
|
|
def __repr__(self) -> str:
|
|
if self.excinfo is None:
|
|
return f"<CallInfo when={self.when!r} result: {self._result!r}>"
|
|
return f"<CallInfo when={self.when!r} excinfo={self.excinfo!r}>"
|
|
|
|
|
|
def pytest_runtest_makereport(item: Item, call: CallInfo[None]) -> TestReport:
|
|
return TestReport.from_item_and_call(item, call)
|
|
|
|
|
|
def pytest_make_collect_report(collector: Collector) -> CollectReport:
|
|
def collect() -> list[Item | Collector]:
|
|
# Before collecting, if this is a Directory, load the conftests.
|
|
# If a conftest import fails to load, it is considered a collection
|
|
# error of the Directory collector. This is why it's done inside of the
|
|
# CallInfo wrapper.
|
|
#
|
|
# Note: initial conftests are loaded early, not here.
|
|
if isinstance(collector, Directory):
|
|
collector.config.pluginmanager._loadconftestmodules(
|
|
collector.path,
|
|
collector.config.getoption("importmode"),
|
|
rootpath=collector.config.rootpath,
|
|
consider_namespace_packages=collector.config.getini(
|
|
"consider_namespace_packages"
|
|
),
|
|
)
|
|
|
|
return list(collector.collect())
|
|
|
|
call = CallInfo.from_call(
|
|
collect, "collect", reraise=(KeyboardInterrupt, SystemExit)
|
|
)
|
|
longrepr: None | tuple[str, int, str] | str | TerminalRepr = None
|
|
if not call.excinfo:
|
|
outcome: Literal["passed", "skipped", "failed"] = "passed"
|
|
else:
|
|
skip_exceptions = [Skipped]
|
|
unittest = sys.modules.get("unittest")
|
|
if unittest is not None:
|
|
skip_exceptions.append(unittest.SkipTest)
|
|
if isinstance(call.excinfo.value, tuple(skip_exceptions)):
|
|
outcome = "skipped"
|
|
r_ = collector._repr_failure_py(call.excinfo, "line")
|
|
assert isinstance(r_, ExceptionChainRepr), repr(r_)
|
|
r = r_.reprcrash
|
|
assert r
|
|
longrepr = (str(r.path), r.lineno, r.message)
|
|
else:
|
|
outcome = "failed"
|
|
errorinfo = collector.repr_failure(call.excinfo)
|
|
if not hasattr(errorinfo, "toterminal"):
|
|
assert isinstance(errorinfo, str)
|
|
errorinfo = CollectErrorRepr(errorinfo)
|
|
longrepr = errorinfo
|
|
result = call.result if not call.excinfo else None
|
|
rep = CollectReport(collector.nodeid, outcome, longrepr, result)
|
|
rep.call = call # type: ignore # see collect_one_node
|
|
return rep
|
|
|
|
|
|
class SetupState:
|
|
"""Shared state for setting up/tearing down test items or collectors
|
|
in a session.
|
|
|
|
Suppose we have a collection tree as follows:
|
|
|
|
<Session session>
|
|
<Module mod1>
|
|
<Function item1>
|
|
<Module mod2>
|
|
<Function item2>
|
|
|
|
The SetupState maintains a stack. The stack starts out empty:
|
|
|
|
[]
|
|
|
|
During the setup phase of item1, setup(item1) is called. What it does
|
|
is:
|
|
|
|
push session to stack, run session.setup()
|
|
push mod1 to stack, run mod1.setup()
|
|
push item1 to stack, run item1.setup()
|
|
|
|
The stack is:
|
|
|
|
[session, mod1, item1]
|
|
|
|
While the stack is in this shape, it is allowed to add finalizers to
|
|
each of session, mod1, item1 using addfinalizer().
|
|
|
|
During the teardown phase of item1, teardown_exact(item2) is called,
|
|
where item2 is the next item to item1. What it does is:
|
|
|
|
pop item1 from stack, run its teardowns
|
|
pop mod1 from stack, run its teardowns
|
|
|
|
mod1 was popped because it ended its purpose with item1. The stack is:
|
|
|
|
[session]
|
|
|
|
During the setup phase of item2, setup(item2) is called. What it does
|
|
is:
|
|
|
|
push mod2 to stack, run mod2.setup()
|
|
push item2 to stack, run item2.setup()
|
|
|
|
Stack:
|
|
|
|
[session, mod2, item2]
|
|
|
|
During the teardown phase of item2, teardown_exact(None) is called,
|
|
because item2 is the last item. What it does is:
|
|
|
|
pop item2 from stack, run its teardowns
|
|
pop mod2 from stack, run its teardowns
|
|
pop session from stack, run its teardowns
|
|
|
|
Stack:
|
|
|
|
[]
|
|
|
|
The end!
|
|
"""
|
|
|
|
def __init__(self) -> None:
|
|
# The stack is in the dict insertion order.
|
|
self.stack: dict[
|
|
Node,
|
|
tuple[
|
|
# Node's finalizers.
|
|
list[Callable[[], object]],
|
|
# Node's exception and original traceback, if its setup raised.
|
|
tuple[OutcomeException | Exception, types.TracebackType | None] | None,
|
|
],
|
|
] = {}
|
|
|
|
def setup(self, item: Item) -> None:
|
|
"""Setup objects along the collector chain to the item."""
|
|
needed_collectors = item.listchain()
|
|
|
|
# If a collector fails its setup, fail its entire subtree of items.
|
|
# The setup is not retried for each item - the same exception is used.
|
|
for col, (finalizers, exc) in self.stack.items():
|
|
assert col in needed_collectors, "previous item was not torn down properly"
|
|
if exc:
|
|
raise exc[0].with_traceback(exc[1])
|
|
|
|
for col in needed_collectors[len(self.stack) :]:
|
|
assert col not in self.stack
|
|
# Push onto the stack.
|
|
self.stack[col] = ([col.teardown], None)
|
|
try:
|
|
col.setup()
|
|
except TEST_OUTCOME as exc:
|
|
self.stack[col] = (self.stack[col][0], (exc, exc.__traceback__))
|
|
raise
|
|
|
|
def addfinalizer(self, finalizer: Callable[[], object], node: Node) -> None:
|
|
"""Attach a finalizer to the given node.
|
|
|
|
The node must be currently active in the stack.
|
|
"""
|
|
assert node and not isinstance(node, tuple)
|
|
assert callable(finalizer)
|
|
assert node in self.stack, (node, self.stack)
|
|
self.stack[node][0].append(finalizer)
|
|
|
|
def teardown_exact(self, nextitem: Item | None) -> None:
|
|
"""Teardown the current stack up until reaching nodes that nextitem
|
|
also descends from.
|
|
|
|
When nextitem is None (meaning we're at the last item), the entire
|
|
stack is torn down.
|
|
"""
|
|
needed_collectors = nextitem and nextitem.listchain() or []
|
|
exceptions: list[BaseException] = []
|
|
while self.stack:
|
|
if list(self.stack.keys()) == needed_collectors[: len(self.stack)]:
|
|
break
|
|
node, (finalizers, _) = self.stack.popitem()
|
|
these_exceptions = []
|
|
while finalizers:
|
|
fin = finalizers.pop()
|
|
try:
|
|
fin()
|
|
except TEST_OUTCOME as e:
|
|
these_exceptions.append(e)
|
|
|
|
if len(these_exceptions) == 1:
|
|
exceptions.extend(these_exceptions)
|
|
elif these_exceptions:
|
|
msg = f"errors while tearing down {node!r}"
|
|
exceptions.append(BaseExceptionGroup(msg, these_exceptions[::-1]))
|
|
|
|
if len(exceptions) == 1:
|
|
raise exceptions[0]
|
|
elif exceptions:
|
|
raise BaseExceptionGroup("errors during test teardown", exceptions[::-1])
|
|
if nextitem is None:
|
|
assert not self.stack
|
|
|
|
|
|
def collect_one_node(collector: Collector) -> CollectReport:
|
|
ihook = collector.ihook
|
|
ihook.pytest_collectstart(collector=collector)
|
|
rep: CollectReport = ihook.pytest_make_collect_report(collector=collector)
|
|
call = rep.__dict__.pop("call", None)
|
|
if call and check_interactive_exception(call, rep):
|
|
ihook.pytest_exception_interact(node=collector, call=call, report=rep)
|
|
return rep
|