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>
627 lines
22 KiB
Python
627 lines
22 KiB
Python
# mypy: allow-untyped-defs
|
|
"""Implementation of the cache provider."""
|
|
|
|
# This plugin was not named "cache" to avoid conflicts with the external
|
|
# pytest-cache version.
|
|
from __future__ import annotations
|
|
|
|
import dataclasses
|
|
import errno
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import tempfile
|
|
from typing import final
|
|
from typing import Generator
|
|
from typing import Iterable
|
|
|
|
from .pathlib import resolve_from_str
|
|
from .pathlib import rm_rf
|
|
from .reports import CollectReport
|
|
from _pytest import nodes
|
|
from _pytest._io import TerminalWriter
|
|
from _pytest.config import Config
|
|
from _pytest.config import ExitCode
|
|
from _pytest.config import hookimpl
|
|
from _pytest.config.argparsing import Parser
|
|
from _pytest.deprecated import check_ispytest
|
|
from _pytest.fixtures import fixture
|
|
from _pytest.fixtures import FixtureRequest
|
|
from _pytest.main import Session
|
|
from _pytest.nodes import Directory
|
|
from _pytest.nodes import File
|
|
from _pytest.reports import TestReport
|
|
|
|
|
|
README_CONTENT = """\
|
|
# pytest cache directory #
|
|
|
|
This directory contains data from the pytest's cache plugin,
|
|
which provides the `--lf` and `--ff` options, as well as the `cache` fixture.
|
|
|
|
**Do not** commit this to version control.
|
|
|
|
See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information.
|
|
"""
|
|
|
|
CACHEDIR_TAG_CONTENT = b"""\
|
|
Signature: 8a477f597d28d172789f06886806bc55
|
|
# This file is a cache directory tag created by pytest.
|
|
# For information about cache directory tags, see:
|
|
# https://bford.info/cachedir/spec.html
|
|
"""
|
|
|
|
|
|
@final
|
|
@dataclasses.dataclass
|
|
class Cache:
|
|
"""Instance of the `cache` fixture."""
|
|
|
|
_cachedir: Path = dataclasses.field(repr=False)
|
|
_config: Config = dataclasses.field(repr=False)
|
|
|
|
# Sub-directory under cache-dir for directories created by `mkdir()`.
|
|
_CACHE_PREFIX_DIRS = "d"
|
|
|
|
# Sub-directory under cache-dir for values created by `set()`.
|
|
_CACHE_PREFIX_VALUES = "v"
|
|
|
|
def __init__(
|
|
self, cachedir: Path, config: Config, *, _ispytest: bool = False
|
|
) -> None:
|
|
check_ispytest(_ispytest)
|
|
self._cachedir = cachedir
|
|
self._config = config
|
|
|
|
@classmethod
|
|
def for_config(cls, config: Config, *, _ispytest: bool = False) -> Cache:
|
|
"""Create the Cache instance for a Config.
|
|
|
|
:meta private:
|
|
"""
|
|
check_ispytest(_ispytest)
|
|
cachedir = cls.cache_dir_from_config(config, _ispytest=True)
|
|
if config.getoption("cacheclear") and cachedir.is_dir():
|
|
cls.clear_cache(cachedir, _ispytest=True)
|
|
return cls(cachedir, config, _ispytest=True)
|
|
|
|
@classmethod
|
|
def clear_cache(cls, cachedir: Path, _ispytest: bool = False) -> None:
|
|
"""Clear the sub-directories used to hold cached directories and values.
|
|
|
|
:meta private:
|
|
"""
|
|
check_ispytest(_ispytest)
|
|
for prefix in (cls._CACHE_PREFIX_DIRS, cls._CACHE_PREFIX_VALUES):
|
|
d = cachedir / prefix
|
|
if d.is_dir():
|
|
rm_rf(d)
|
|
|
|
@staticmethod
|
|
def cache_dir_from_config(config: Config, *, _ispytest: bool = False) -> Path:
|
|
"""Get the path to the cache directory for a Config.
|
|
|
|
:meta private:
|
|
"""
|
|
check_ispytest(_ispytest)
|
|
return resolve_from_str(config.getini("cache_dir"), config.rootpath)
|
|
|
|
def warn(self, fmt: str, *, _ispytest: bool = False, **args: object) -> None:
|
|
"""Issue a cache warning.
|
|
|
|
:meta private:
|
|
"""
|
|
check_ispytest(_ispytest)
|
|
import warnings
|
|
|
|
from _pytest.warning_types import PytestCacheWarning
|
|
|
|
warnings.warn(
|
|
PytestCacheWarning(fmt.format(**args) if args else fmt),
|
|
self._config.hook,
|
|
stacklevel=3,
|
|
)
|
|
|
|
def _mkdir(self, path: Path) -> None:
|
|
self._ensure_cache_dir_and_supporting_files()
|
|
path.mkdir(exist_ok=True, parents=True)
|
|
|
|
def mkdir(self, name: str) -> Path:
|
|
"""Return a directory path object with the given name.
|
|
|
|
If the directory does not yet exist, it will be created. You can use
|
|
it to manage files to e.g. store/retrieve database dumps across test
|
|
sessions.
|
|
|
|
.. versionadded:: 7.0
|
|
|
|
:param name:
|
|
Must be a string not containing a ``/`` separator.
|
|
Make sure the name contains your plugin or application
|
|
identifiers to prevent clashes with other cache users.
|
|
"""
|
|
path = Path(name)
|
|
if len(path.parts) > 1:
|
|
raise ValueError("name is not allowed to contain path separators")
|
|
res = self._cachedir.joinpath(self._CACHE_PREFIX_DIRS, path)
|
|
self._mkdir(res)
|
|
return res
|
|
|
|
def _getvaluepath(self, key: str) -> Path:
|
|
return self._cachedir.joinpath(self._CACHE_PREFIX_VALUES, Path(key))
|
|
|
|
def get(self, key: str, default):
|
|
"""Return the cached value for the given key.
|
|
|
|
If no value was yet cached or the value cannot be read, the specified
|
|
default is returned.
|
|
|
|
:param key:
|
|
Must be a ``/`` separated value. Usually the first
|
|
name is the name of your plugin or your application.
|
|
:param default:
|
|
The value to return in case of a cache-miss or invalid cache value.
|
|
"""
|
|
path = self._getvaluepath(key)
|
|
try:
|
|
with path.open("r", encoding="UTF-8") as f:
|
|
return json.load(f)
|
|
except (ValueError, OSError):
|
|
return default
|
|
|
|
def set(self, key: str, value: object) -> None:
|
|
"""Save value for the given key.
|
|
|
|
:param key:
|
|
Must be a ``/`` separated value. Usually the first
|
|
name is the name of your plugin or your application.
|
|
:param value:
|
|
Must be of any combination of basic python types,
|
|
including nested types like lists of dictionaries.
|
|
"""
|
|
path = self._getvaluepath(key)
|
|
try:
|
|
self._mkdir(path.parent)
|
|
except OSError as exc:
|
|
self.warn(
|
|
f"could not create cache path {path}: {exc}",
|
|
_ispytest=True,
|
|
)
|
|
return
|
|
data = json.dumps(value, ensure_ascii=False, indent=2)
|
|
try:
|
|
f = path.open("w", encoding="UTF-8")
|
|
except OSError as exc:
|
|
self.warn(
|
|
f"cache could not write path {path}: {exc}",
|
|
_ispytest=True,
|
|
)
|
|
else:
|
|
with f:
|
|
f.write(data)
|
|
|
|
def _ensure_cache_dir_and_supporting_files(self) -> None:
|
|
"""Create the cache dir and its supporting files."""
|
|
if self._cachedir.is_dir():
|
|
return
|
|
|
|
self._cachedir.parent.mkdir(parents=True, exist_ok=True)
|
|
with tempfile.TemporaryDirectory(
|
|
prefix="pytest-cache-files-",
|
|
dir=self._cachedir.parent,
|
|
) as newpath:
|
|
path = Path(newpath)
|
|
|
|
# Reset permissions to the default, see #12308.
|
|
# Note: there's no way to get the current umask atomically, eek.
|
|
umask = os.umask(0o022)
|
|
os.umask(umask)
|
|
path.chmod(0o777 - umask)
|
|
|
|
with open(path.joinpath("README.md"), "x", encoding="UTF-8") as f:
|
|
f.write(README_CONTENT)
|
|
with open(path.joinpath(".gitignore"), "x", encoding="UTF-8") as f:
|
|
f.write("# Created by pytest automatically.\n*\n")
|
|
with open(path.joinpath("CACHEDIR.TAG"), "xb") as f:
|
|
f.write(CACHEDIR_TAG_CONTENT)
|
|
|
|
try:
|
|
path.rename(self._cachedir)
|
|
except OSError as e:
|
|
# If 2 concurrent pytests both race to the rename, the loser
|
|
# gets "Directory not empty" from the rename. In this case,
|
|
# everything is handled so just continue (while letting the
|
|
# temporary directory be cleaned up).
|
|
# On Windows, the error is a FileExistsError which translates to EEXIST.
|
|
if e.errno not in (errno.ENOTEMPTY, errno.EEXIST):
|
|
raise
|
|
else:
|
|
# Create a directory in place of the one we just moved so that
|
|
# `TemporaryDirectory`'s cleanup doesn't complain.
|
|
#
|
|
# TODO: pass ignore_cleanup_errors=True when we no longer support python < 3.10.
|
|
# See https://github.com/python/cpython/issues/74168. Note that passing
|
|
# delete=False would do the wrong thing in case of errors and isn't supported
|
|
# until python 3.12.
|
|
path.mkdir()
|
|
|
|
|
|
class LFPluginCollWrapper:
|
|
def __init__(self, lfplugin: LFPlugin) -> None:
|
|
self.lfplugin = lfplugin
|
|
self._collected_at_least_one_failure = False
|
|
|
|
@hookimpl(wrapper=True)
|
|
def pytest_make_collect_report(
|
|
self, collector: nodes.Collector
|
|
) -> Generator[None, CollectReport, CollectReport]:
|
|
res = yield
|
|
if isinstance(collector, (Session, Directory)):
|
|
# Sort any lf-paths to the beginning.
|
|
lf_paths = self.lfplugin._last_failed_paths
|
|
|
|
# Use stable sort to prioritize last failed.
|
|
def sort_key(node: nodes.Item | nodes.Collector) -> bool:
|
|
return node.path in lf_paths
|
|
|
|
res.result = sorted(
|
|
res.result,
|
|
key=sort_key,
|
|
reverse=True,
|
|
)
|
|
|
|
elif isinstance(collector, File):
|
|
if collector.path in self.lfplugin._last_failed_paths:
|
|
result = res.result
|
|
lastfailed = self.lfplugin.lastfailed
|
|
|
|
# Only filter with known failures.
|
|
if not self._collected_at_least_one_failure:
|
|
if not any(x.nodeid in lastfailed for x in result):
|
|
return res
|
|
self.lfplugin.config.pluginmanager.register(
|
|
LFPluginCollSkipfiles(self.lfplugin), "lfplugin-collskip"
|
|
)
|
|
self._collected_at_least_one_failure = True
|
|
|
|
session = collector.session
|
|
result[:] = [
|
|
x
|
|
for x in result
|
|
if x.nodeid in lastfailed
|
|
# Include any passed arguments (not trivial to filter).
|
|
or session.isinitpath(x.path)
|
|
# Keep all sub-collectors.
|
|
or isinstance(x, nodes.Collector)
|
|
]
|
|
|
|
return res
|
|
|
|
|
|
class LFPluginCollSkipfiles:
|
|
def __init__(self, lfplugin: LFPlugin) -> None:
|
|
self.lfplugin = lfplugin
|
|
|
|
@hookimpl
|
|
def pytest_make_collect_report(
|
|
self, collector: nodes.Collector
|
|
) -> CollectReport | None:
|
|
if isinstance(collector, File):
|
|
if collector.path not in self.lfplugin._last_failed_paths:
|
|
self.lfplugin._skipped_files += 1
|
|
|
|
return CollectReport(
|
|
collector.nodeid, "passed", longrepr=None, result=[]
|
|
)
|
|
return None
|
|
|
|
|
|
class LFPlugin:
|
|
"""Plugin which implements the --lf (run last-failing) option."""
|
|
|
|
def __init__(self, config: Config) -> None:
|
|
self.config = config
|
|
active_keys = "lf", "failedfirst"
|
|
self.active = any(config.getoption(key) for key in active_keys)
|
|
assert config.cache
|
|
self.lastfailed: dict[str, bool] = config.cache.get("cache/lastfailed", {})
|
|
self._previously_failed_count: int | None = None
|
|
self._report_status: str | None = None
|
|
self._skipped_files = 0 # count skipped files during collection due to --lf
|
|
|
|
if config.getoption("lf"):
|
|
self._last_failed_paths = self.get_last_failed_paths()
|
|
config.pluginmanager.register(
|
|
LFPluginCollWrapper(self), "lfplugin-collwrapper"
|
|
)
|
|
|
|
def get_last_failed_paths(self) -> set[Path]:
|
|
"""Return a set with all Paths of the previously failed nodeids and
|
|
their parents."""
|
|
rootpath = self.config.rootpath
|
|
result = set()
|
|
for nodeid in self.lastfailed:
|
|
path = rootpath / nodeid.split("::")[0]
|
|
result.add(path)
|
|
result.update(path.parents)
|
|
return {x for x in result if x.exists()}
|
|
|
|
def pytest_report_collectionfinish(self) -> str | None:
|
|
if self.active and self.config.get_verbosity() >= 0:
|
|
return f"run-last-failure: {self._report_status}"
|
|
return None
|
|
|
|
def pytest_runtest_logreport(self, report: TestReport) -> None:
|
|
if (report.when == "call" and report.passed) or report.skipped:
|
|
self.lastfailed.pop(report.nodeid, None)
|
|
elif report.failed:
|
|
self.lastfailed[report.nodeid] = True
|
|
|
|
def pytest_collectreport(self, report: CollectReport) -> None:
|
|
passed = report.outcome in ("passed", "skipped")
|
|
if passed:
|
|
if report.nodeid in self.lastfailed:
|
|
self.lastfailed.pop(report.nodeid)
|
|
self.lastfailed.update((item.nodeid, True) for item in report.result)
|
|
else:
|
|
self.lastfailed[report.nodeid] = True
|
|
|
|
@hookimpl(wrapper=True, tryfirst=True)
|
|
def pytest_collection_modifyitems(
|
|
self, config: Config, items: list[nodes.Item]
|
|
) -> Generator[None]:
|
|
res = yield
|
|
|
|
if not self.active:
|
|
return res
|
|
|
|
if self.lastfailed:
|
|
previously_failed = []
|
|
previously_passed = []
|
|
for item in items:
|
|
if item.nodeid in self.lastfailed:
|
|
previously_failed.append(item)
|
|
else:
|
|
previously_passed.append(item)
|
|
self._previously_failed_count = len(previously_failed)
|
|
|
|
if not previously_failed:
|
|
# Running a subset of all tests with recorded failures
|
|
# only outside of it.
|
|
self._report_status = "%d known failures not in selected tests" % (
|
|
len(self.lastfailed),
|
|
)
|
|
else:
|
|
if self.config.getoption("lf"):
|
|
items[:] = previously_failed
|
|
config.hook.pytest_deselected(items=previously_passed)
|
|
else: # --failedfirst
|
|
items[:] = previously_failed + previously_passed
|
|
|
|
noun = "failure" if self._previously_failed_count == 1 else "failures"
|
|
suffix = " first" if self.config.getoption("failedfirst") else ""
|
|
self._report_status = (
|
|
f"rerun previous {self._previously_failed_count} {noun}{suffix}"
|
|
)
|
|
|
|
if self._skipped_files > 0:
|
|
files_noun = "file" if self._skipped_files == 1 else "files"
|
|
self._report_status += f" (skipped {self._skipped_files} {files_noun})"
|
|
else:
|
|
self._report_status = "no previously failed tests, "
|
|
if self.config.getoption("last_failed_no_failures") == "none":
|
|
self._report_status += "deselecting all items."
|
|
config.hook.pytest_deselected(items=items[:])
|
|
items[:] = []
|
|
else:
|
|
self._report_status += "not deselecting items."
|
|
|
|
return res
|
|
|
|
def pytest_sessionfinish(self, session: Session) -> None:
|
|
config = self.config
|
|
if config.getoption("cacheshow") or hasattr(config, "workerinput"):
|
|
return
|
|
|
|
assert config.cache is not None
|
|
saved_lastfailed = config.cache.get("cache/lastfailed", {})
|
|
if saved_lastfailed != self.lastfailed:
|
|
config.cache.set("cache/lastfailed", self.lastfailed)
|
|
|
|
|
|
class NFPlugin:
|
|
"""Plugin which implements the --nf (run new-first) option."""
|
|
|
|
def __init__(self, config: Config) -> None:
|
|
self.config = config
|
|
self.active = config.option.newfirst
|
|
assert config.cache is not None
|
|
self.cached_nodeids = set(config.cache.get("cache/nodeids", []))
|
|
|
|
@hookimpl(wrapper=True, tryfirst=True)
|
|
def pytest_collection_modifyitems(self, items: list[nodes.Item]) -> Generator[None]:
|
|
res = yield
|
|
|
|
if self.active:
|
|
new_items: dict[str, nodes.Item] = {}
|
|
other_items: dict[str, nodes.Item] = {}
|
|
for item in items:
|
|
if item.nodeid not in self.cached_nodeids:
|
|
new_items[item.nodeid] = item
|
|
else:
|
|
other_items[item.nodeid] = item
|
|
|
|
items[:] = self._get_increasing_order(
|
|
new_items.values()
|
|
) + self._get_increasing_order(other_items.values())
|
|
self.cached_nodeids.update(new_items)
|
|
else:
|
|
self.cached_nodeids.update(item.nodeid for item in items)
|
|
|
|
return res
|
|
|
|
def _get_increasing_order(self, items: Iterable[nodes.Item]) -> list[nodes.Item]:
|
|
return sorted(items, key=lambda item: item.path.stat().st_mtime, reverse=True)
|
|
|
|
def pytest_sessionfinish(self) -> None:
|
|
config = self.config
|
|
if config.getoption("cacheshow") or hasattr(config, "workerinput"):
|
|
return
|
|
|
|
if config.getoption("collectonly"):
|
|
return
|
|
|
|
assert config.cache is not None
|
|
config.cache.set("cache/nodeids", sorted(self.cached_nodeids))
|
|
|
|
|
|
def pytest_addoption(parser: Parser) -> None:
|
|
group = parser.getgroup("general")
|
|
group.addoption(
|
|
"--lf",
|
|
"--last-failed",
|
|
action="store_true",
|
|
dest="lf",
|
|
help="Rerun only the tests that failed "
|
|
"at the last run (or all if none failed)",
|
|
)
|
|
group.addoption(
|
|
"--ff",
|
|
"--failed-first",
|
|
action="store_true",
|
|
dest="failedfirst",
|
|
help="Run all tests, but run the last failures first. "
|
|
"This may re-order tests and thus lead to "
|
|
"repeated fixture setup/teardown.",
|
|
)
|
|
group.addoption(
|
|
"--nf",
|
|
"--new-first",
|
|
action="store_true",
|
|
dest="newfirst",
|
|
help="Run tests from new files first, then the rest of the tests "
|
|
"sorted by file mtime",
|
|
)
|
|
group.addoption(
|
|
"--cache-show",
|
|
action="append",
|
|
nargs="?",
|
|
dest="cacheshow",
|
|
help=(
|
|
"Show cache contents, don't perform collection or tests. "
|
|
"Optional argument: glob (default: '*')."
|
|
),
|
|
)
|
|
group.addoption(
|
|
"--cache-clear",
|
|
action="store_true",
|
|
dest="cacheclear",
|
|
help="Remove all cache contents at start of test run",
|
|
)
|
|
cache_dir_default = ".pytest_cache"
|
|
if "TOX_ENV_DIR" in os.environ:
|
|
cache_dir_default = os.path.join(os.environ["TOX_ENV_DIR"], cache_dir_default)
|
|
parser.addini("cache_dir", default=cache_dir_default, help="Cache directory path")
|
|
group.addoption(
|
|
"--lfnf",
|
|
"--last-failed-no-failures",
|
|
action="store",
|
|
dest="last_failed_no_failures",
|
|
choices=("all", "none"),
|
|
default="all",
|
|
help="With ``--lf``, determines whether to execute tests when there "
|
|
"are no previously (known) failures or when no "
|
|
"cached ``lastfailed`` data was found. "
|
|
"``all`` (the default) runs the full test suite again. "
|
|
"``none`` just emits a message about no known failures and exits successfully.",
|
|
)
|
|
|
|
|
|
def pytest_cmdline_main(config: Config) -> int | ExitCode | None:
|
|
if config.option.cacheshow and not config.option.help:
|
|
from _pytest.main import wrap_session
|
|
|
|
return wrap_session(config, cacheshow)
|
|
return None
|
|
|
|
|
|
@hookimpl(tryfirst=True)
|
|
def pytest_configure(config: Config) -> None:
|
|
config.cache = Cache.for_config(config, _ispytest=True)
|
|
config.pluginmanager.register(LFPlugin(config), "lfplugin")
|
|
config.pluginmanager.register(NFPlugin(config), "nfplugin")
|
|
|
|
|
|
@fixture
|
|
def cache(request: FixtureRequest) -> Cache:
|
|
"""Return a cache object that can persist state between testing sessions.
|
|
|
|
cache.get(key, default)
|
|
cache.set(key, value)
|
|
|
|
Keys must be ``/`` separated strings, where the first part is usually the
|
|
name of your plugin or application to avoid clashes with other cache users.
|
|
|
|
Values can be any object handled by the json stdlib module.
|
|
"""
|
|
assert request.config.cache is not None
|
|
return request.config.cache
|
|
|
|
|
|
def pytest_report_header(config: Config) -> str | None:
|
|
"""Display cachedir with --cache-show and if non-default."""
|
|
if config.option.verbose > 0 or config.getini("cache_dir") != ".pytest_cache":
|
|
assert config.cache is not None
|
|
cachedir = config.cache._cachedir
|
|
# TODO: evaluate generating upward relative paths
|
|
# starting with .., ../.. if sensible
|
|
|
|
try:
|
|
displaypath = cachedir.relative_to(config.rootpath)
|
|
except ValueError:
|
|
displaypath = cachedir
|
|
return f"cachedir: {displaypath}"
|
|
return None
|
|
|
|
|
|
def cacheshow(config: Config, session: Session) -> int:
|
|
from pprint import pformat
|
|
|
|
assert config.cache is not None
|
|
|
|
tw = TerminalWriter()
|
|
tw.line("cachedir: " + str(config.cache._cachedir))
|
|
if not config.cache._cachedir.is_dir():
|
|
tw.line("cache is empty")
|
|
return 0
|
|
|
|
glob = config.option.cacheshow[0]
|
|
if glob is None:
|
|
glob = "*"
|
|
|
|
dummy = object()
|
|
basedir = config.cache._cachedir
|
|
vdir = basedir / Cache._CACHE_PREFIX_VALUES
|
|
tw.sep("-", f"cache values for {glob!r}")
|
|
for valpath in sorted(x for x in vdir.rglob(glob) if x.is_file()):
|
|
key = str(valpath.relative_to(vdir))
|
|
val = config.cache.get(key, dummy)
|
|
if val is dummy:
|
|
tw.line(f"{key} contains unreadable content, will be ignored")
|
|
else:
|
|
tw.line(f"{key} contains:")
|
|
for line in pformat(val).splitlines():
|
|
tw.line(" " + line)
|
|
|
|
ddir = basedir / Cache._CACHE_PREFIX_DIRS
|
|
if ddir.is_dir():
|
|
contents = sorted(ddir.rglob(glob))
|
|
tw.sep("-", f"cache directories for {glob!r}")
|
|
for p in contents:
|
|
# if p.is_dir():
|
|
# print("%s/" % p.relative_to(basedir))
|
|
if p.is_file():
|
|
key = str(p.relative_to(basedir))
|
|
tw.line(f"{key} is a file of length {p.stat().st_size:d}")
|
|
return 0
|