mirror of
https://github.com/openswarm-ai/openswarm.git
synced 2026-09-22 17:44: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>
610 lines
20 KiB
Python
610 lines
20 KiB
Python
# mypy: allow-untyped-defs
|
|
"""Utilities for assertion debugging."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import collections.abc
|
|
import os
|
|
import pprint
|
|
from typing import AbstractSet
|
|
from typing import Any
|
|
from typing import Callable
|
|
from typing import Iterable
|
|
from typing import Literal
|
|
from typing import Mapping
|
|
from typing import Protocol
|
|
from typing import Sequence
|
|
from unicodedata import normalize
|
|
|
|
from _pytest import outcomes
|
|
import _pytest._code
|
|
from _pytest._io.pprint import PrettyPrinter
|
|
from _pytest._io.saferepr import saferepr
|
|
from _pytest._io.saferepr import saferepr_unlimited
|
|
from _pytest.config import Config
|
|
|
|
|
|
# The _reprcompare attribute on the util module is used by the new assertion
|
|
# interpretation code and assertion rewriter to detect this plugin was
|
|
# loaded and in turn call the hooks defined here as part of the
|
|
# DebugInterpreter.
|
|
_reprcompare: Callable[[str, object, object], str | None] | None = None
|
|
|
|
# Works similarly as _reprcompare attribute. Is populated with the hook call
|
|
# when pytest_runtest_setup is called.
|
|
_assertion_pass: Callable[[int, str, str], None] | None = None
|
|
|
|
# Config object which is assigned during pytest_runtest_protocol.
|
|
_config: Config | None = None
|
|
|
|
|
|
class _HighlightFunc(Protocol):
|
|
def __call__(self, source: str, lexer: Literal["diff", "python"] = "python") -> str:
|
|
"""Apply highlighting to the given source."""
|
|
|
|
|
|
def format_explanation(explanation: str) -> str:
|
|
r"""Format an explanation.
|
|
|
|
Normally all embedded newlines are escaped, however there are
|
|
three exceptions: \n{, \n} and \n~. The first two are intended
|
|
cover nested explanations, see function and attribute explanations
|
|
for examples (.visit_Call(), visit_Attribute()). The last one is
|
|
for when one explanation needs to span multiple lines, e.g. when
|
|
displaying diffs.
|
|
"""
|
|
lines = _split_explanation(explanation)
|
|
result = _format_lines(lines)
|
|
return "\n".join(result)
|
|
|
|
|
|
def _split_explanation(explanation: str) -> list[str]:
|
|
r"""Return a list of individual lines in the explanation.
|
|
|
|
This will return a list of lines split on '\n{', '\n}' and '\n~'.
|
|
Any other newlines will be escaped and appear in the line as the
|
|
literal '\n' characters.
|
|
"""
|
|
raw_lines = (explanation or "").split("\n")
|
|
lines = [raw_lines[0]]
|
|
for values in raw_lines[1:]:
|
|
if values and values[0] in ["{", "}", "~", ">"]:
|
|
lines.append(values)
|
|
else:
|
|
lines[-1] += "\\n" + values
|
|
return lines
|
|
|
|
|
|
def _format_lines(lines: Sequence[str]) -> list[str]:
|
|
"""Format the individual lines.
|
|
|
|
This will replace the '{', '}' and '~' characters of our mini formatting
|
|
language with the proper 'where ...', 'and ...' and ' + ...' text, taking
|
|
care of indentation along the way.
|
|
|
|
Return a list of formatted lines.
|
|
"""
|
|
result = list(lines[:1])
|
|
stack = [0]
|
|
stackcnt = [0]
|
|
for line in lines[1:]:
|
|
if line.startswith("{"):
|
|
if stackcnt[-1]:
|
|
s = "and "
|
|
else:
|
|
s = "where "
|
|
stack.append(len(result))
|
|
stackcnt[-1] += 1
|
|
stackcnt.append(0)
|
|
result.append(" +" + " " * (len(stack) - 1) + s + line[1:])
|
|
elif line.startswith("}"):
|
|
stack.pop()
|
|
stackcnt.pop()
|
|
result[stack[-1]] += line[1:]
|
|
else:
|
|
assert line[0] in ["~", ">"]
|
|
stack[-1] += 1
|
|
indent = len(stack) if line.startswith("~") else len(stack) - 1
|
|
result.append(" " * indent + line[1:])
|
|
assert len(stack) == 1
|
|
return result
|
|
|
|
|
|
def issequence(x: Any) -> bool:
|
|
return isinstance(x, collections.abc.Sequence) and not isinstance(x, str)
|
|
|
|
|
|
def istext(x: Any) -> bool:
|
|
return isinstance(x, str)
|
|
|
|
|
|
def isdict(x: Any) -> bool:
|
|
return isinstance(x, dict)
|
|
|
|
|
|
def isset(x: Any) -> bool:
|
|
return isinstance(x, (set, frozenset))
|
|
|
|
|
|
def isnamedtuple(obj: Any) -> bool:
|
|
return isinstance(obj, tuple) and getattr(obj, "_fields", None) is not None
|
|
|
|
|
|
def isdatacls(obj: Any) -> bool:
|
|
return getattr(obj, "__dataclass_fields__", None) is not None
|
|
|
|
|
|
def isattrs(obj: Any) -> bool:
|
|
return getattr(obj, "__attrs_attrs__", None) is not None
|
|
|
|
|
|
def isiterable(obj: Any) -> bool:
|
|
try:
|
|
iter(obj)
|
|
return not istext(obj)
|
|
except Exception:
|
|
return False
|
|
|
|
|
|
def has_default_eq(
|
|
obj: object,
|
|
) -> bool:
|
|
"""Check if an instance of an object contains the default eq
|
|
|
|
First, we check if the object's __eq__ attribute has __code__,
|
|
if so, we check the equally of the method code filename (__code__.co_filename)
|
|
to the default one generated by the dataclass and attr module
|
|
for dataclasses the default co_filename is <string>, for attrs class, the __eq__ should contain "attrs eq generated"
|
|
"""
|
|
# inspired from https://github.com/willmcgugan/rich/blob/07d51ffc1aee6f16bd2e5a25b4e82850fb9ed778/rich/pretty.py#L68
|
|
if hasattr(obj.__eq__, "__code__") and hasattr(obj.__eq__.__code__, "co_filename"):
|
|
code_filename = obj.__eq__.__code__.co_filename
|
|
|
|
if isattrs(obj):
|
|
return "attrs generated eq" in code_filename
|
|
|
|
return code_filename == "<string>" # data class
|
|
return True
|
|
|
|
|
|
def assertrepr_compare(
|
|
config, op: str, left: Any, right: Any, use_ascii: bool = False
|
|
) -> list[str] | None:
|
|
"""Return specialised explanations for some operators/operands."""
|
|
verbose = config.get_verbosity(Config.VERBOSITY_ASSERTIONS)
|
|
|
|
# Strings which normalize equal are often hard to distinguish when printed; use ascii() to make this easier.
|
|
# See issue #3246.
|
|
use_ascii = (
|
|
isinstance(left, str)
|
|
and isinstance(right, str)
|
|
and normalize("NFD", left) == normalize("NFD", right)
|
|
)
|
|
|
|
if verbose > 1:
|
|
left_repr = saferepr_unlimited(left, use_ascii=use_ascii)
|
|
right_repr = saferepr_unlimited(right, use_ascii=use_ascii)
|
|
else:
|
|
# XXX: "15 chars indentation" is wrong
|
|
# ("E AssertionError: assert "); should use term width.
|
|
maxsize = (
|
|
80 - 15 - len(op) - 2
|
|
) // 2 # 15 chars indentation, 1 space around op
|
|
|
|
left_repr = saferepr(left, maxsize=maxsize, use_ascii=use_ascii)
|
|
right_repr = saferepr(right, maxsize=maxsize, use_ascii=use_ascii)
|
|
|
|
summary = f"{left_repr} {op} {right_repr}"
|
|
highlighter = config.get_terminal_writer()._highlight
|
|
|
|
explanation = None
|
|
try:
|
|
if op == "==":
|
|
explanation = _compare_eq_any(left, right, highlighter, verbose)
|
|
elif op == "not in":
|
|
if istext(left) and istext(right):
|
|
explanation = _notin_text(left, right, verbose)
|
|
elif op == "!=":
|
|
if isset(left) and isset(right):
|
|
explanation = ["Both sets are equal"]
|
|
elif op == ">=":
|
|
if isset(left) and isset(right):
|
|
explanation = _compare_gte_set(left, right, highlighter, verbose)
|
|
elif op == "<=":
|
|
if isset(left) and isset(right):
|
|
explanation = _compare_lte_set(left, right, highlighter, verbose)
|
|
elif op == ">":
|
|
if isset(left) and isset(right):
|
|
explanation = _compare_gt_set(left, right, highlighter, verbose)
|
|
elif op == "<":
|
|
if isset(left) and isset(right):
|
|
explanation = _compare_lt_set(left, right, highlighter, verbose)
|
|
|
|
except outcomes.Exit:
|
|
raise
|
|
except Exception:
|
|
repr_crash = _pytest._code.ExceptionInfo.from_current()._getreprcrash()
|
|
explanation = [
|
|
f"(pytest_assertion plugin: representation of details failed: {repr_crash}.",
|
|
" Probably an object has a faulty __repr__.)",
|
|
]
|
|
|
|
if not explanation:
|
|
return None
|
|
|
|
if explanation[0] != "":
|
|
explanation = ["", *explanation]
|
|
return [summary, *explanation]
|
|
|
|
|
|
def _compare_eq_any(
|
|
left: Any, right: Any, highlighter: _HighlightFunc, verbose: int = 0
|
|
) -> list[str]:
|
|
explanation = []
|
|
if istext(left) and istext(right):
|
|
explanation = _diff_text(left, right, verbose)
|
|
else:
|
|
from _pytest.python_api import ApproxBase
|
|
|
|
if isinstance(left, ApproxBase) or isinstance(right, ApproxBase):
|
|
# Although the common order should be obtained == expected, this ensures both ways
|
|
approx_side = left if isinstance(left, ApproxBase) else right
|
|
other_side = right if isinstance(left, ApproxBase) else left
|
|
|
|
explanation = approx_side._repr_compare(other_side)
|
|
elif type(left) is type(right) and (
|
|
isdatacls(left) or isattrs(left) or isnamedtuple(left)
|
|
):
|
|
# Note: unlike dataclasses/attrs, namedtuples compare only the
|
|
# field values, not the type or field names. But this branch
|
|
# intentionally only handles the same-type case, which was often
|
|
# used in older code bases before dataclasses/attrs were available.
|
|
explanation = _compare_eq_cls(left, right, highlighter, verbose)
|
|
elif issequence(left) and issequence(right):
|
|
explanation = _compare_eq_sequence(left, right, highlighter, verbose)
|
|
elif isset(left) and isset(right):
|
|
explanation = _compare_eq_set(left, right, highlighter, verbose)
|
|
elif isdict(left) and isdict(right):
|
|
explanation = _compare_eq_dict(left, right, highlighter, verbose)
|
|
|
|
if isiterable(left) and isiterable(right):
|
|
expl = _compare_eq_iterable(left, right, highlighter, verbose)
|
|
explanation.extend(expl)
|
|
|
|
return explanation
|
|
|
|
|
|
def _diff_text(left: str, right: str, verbose: int = 0) -> list[str]:
|
|
"""Return the explanation for the diff between text.
|
|
|
|
Unless --verbose is used this will skip leading and trailing
|
|
characters which are identical to keep the diff minimal.
|
|
"""
|
|
from difflib import ndiff
|
|
|
|
explanation: list[str] = []
|
|
|
|
if verbose < 1:
|
|
i = 0 # just in case left or right has zero length
|
|
for i in range(min(len(left), len(right))):
|
|
if left[i] != right[i]:
|
|
break
|
|
if i > 42:
|
|
i -= 10 # Provide some context
|
|
explanation = [
|
|
f"Skipping {i} identical leading characters in diff, use -v to show"
|
|
]
|
|
left = left[i:]
|
|
right = right[i:]
|
|
if len(left) == len(right):
|
|
for i in range(len(left)):
|
|
if left[-i] != right[-i]:
|
|
break
|
|
if i > 42:
|
|
i -= 10 # Provide some context
|
|
explanation += [
|
|
f"Skipping {i} identical trailing "
|
|
"characters in diff, use -v to show"
|
|
]
|
|
left = left[:-i]
|
|
right = right[:-i]
|
|
keepends = True
|
|
if left.isspace() or right.isspace():
|
|
left = repr(str(left))
|
|
right = repr(str(right))
|
|
explanation += ["Strings contain only whitespace, escaping them using repr()"]
|
|
# "right" is the expected base against which we compare "left",
|
|
# see https://github.com/pytest-dev/pytest/issues/3333
|
|
explanation += [
|
|
line.strip("\n")
|
|
for line in ndiff(right.splitlines(keepends), left.splitlines(keepends))
|
|
]
|
|
return explanation
|
|
|
|
|
|
def _compare_eq_iterable(
|
|
left: Iterable[Any],
|
|
right: Iterable[Any],
|
|
highlighter: _HighlightFunc,
|
|
verbose: int = 0,
|
|
) -> list[str]:
|
|
if verbose <= 0 and not running_on_ci():
|
|
return ["Use -v to get more diff"]
|
|
# dynamic import to speedup pytest
|
|
import difflib
|
|
|
|
left_formatting = PrettyPrinter().pformat(left).splitlines()
|
|
right_formatting = PrettyPrinter().pformat(right).splitlines()
|
|
|
|
explanation = ["", "Full diff:"]
|
|
# "right" is the expected base against which we compare "left",
|
|
# see https://github.com/pytest-dev/pytest/issues/3333
|
|
explanation.extend(
|
|
highlighter(
|
|
"\n".join(
|
|
line.rstrip()
|
|
for line in difflib.ndiff(right_formatting, left_formatting)
|
|
),
|
|
lexer="diff",
|
|
).splitlines()
|
|
)
|
|
return explanation
|
|
|
|
|
|
def _compare_eq_sequence(
|
|
left: Sequence[Any],
|
|
right: Sequence[Any],
|
|
highlighter: _HighlightFunc,
|
|
verbose: int = 0,
|
|
) -> list[str]:
|
|
comparing_bytes = isinstance(left, bytes) and isinstance(right, bytes)
|
|
explanation: list[str] = []
|
|
len_left = len(left)
|
|
len_right = len(right)
|
|
for i in range(min(len_left, len_right)):
|
|
if left[i] != right[i]:
|
|
if comparing_bytes:
|
|
# when comparing bytes, we want to see their ascii representation
|
|
# instead of their numeric values (#5260)
|
|
# using a slice gives us the ascii representation:
|
|
# >>> s = b'foo'
|
|
# >>> s[0]
|
|
# 102
|
|
# >>> s[0:1]
|
|
# b'f'
|
|
left_value = left[i : i + 1]
|
|
right_value = right[i : i + 1]
|
|
else:
|
|
left_value = left[i]
|
|
right_value = right[i]
|
|
|
|
explanation.append(
|
|
f"At index {i} diff:"
|
|
f" {highlighter(repr(left_value))} != {highlighter(repr(right_value))}"
|
|
)
|
|
break
|
|
|
|
if comparing_bytes:
|
|
# when comparing bytes, it doesn't help to show the "sides contain one or more
|
|
# items" longer explanation, so skip it
|
|
|
|
return explanation
|
|
|
|
len_diff = len_left - len_right
|
|
if len_diff:
|
|
if len_diff > 0:
|
|
dir_with_more = "Left"
|
|
extra = saferepr(left[len_right])
|
|
else:
|
|
len_diff = 0 - len_diff
|
|
dir_with_more = "Right"
|
|
extra = saferepr(right[len_left])
|
|
|
|
if len_diff == 1:
|
|
explanation += [
|
|
f"{dir_with_more} contains one more item: {highlighter(extra)}"
|
|
]
|
|
else:
|
|
explanation += [
|
|
"%s contains %d more items, first extra item: %s"
|
|
% (dir_with_more, len_diff, highlighter(extra))
|
|
]
|
|
return explanation
|
|
|
|
|
|
def _compare_eq_set(
|
|
left: AbstractSet[Any],
|
|
right: AbstractSet[Any],
|
|
highlighter: _HighlightFunc,
|
|
verbose: int = 0,
|
|
) -> list[str]:
|
|
explanation = []
|
|
explanation.extend(_set_one_sided_diff("left", left, right, highlighter))
|
|
explanation.extend(_set_one_sided_diff("right", right, left, highlighter))
|
|
return explanation
|
|
|
|
|
|
def _compare_gt_set(
|
|
left: AbstractSet[Any],
|
|
right: AbstractSet[Any],
|
|
highlighter: _HighlightFunc,
|
|
verbose: int = 0,
|
|
) -> list[str]:
|
|
explanation = _compare_gte_set(left, right, highlighter)
|
|
if not explanation:
|
|
return ["Both sets are equal"]
|
|
return explanation
|
|
|
|
|
|
def _compare_lt_set(
|
|
left: AbstractSet[Any],
|
|
right: AbstractSet[Any],
|
|
highlighter: _HighlightFunc,
|
|
verbose: int = 0,
|
|
) -> list[str]:
|
|
explanation = _compare_lte_set(left, right, highlighter)
|
|
if not explanation:
|
|
return ["Both sets are equal"]
|
|
return explanation
|
|
|
|
|
|
def _compare_gte_set(
|
|
left: AbstractSet[Any],
|
|
right: AbstractSet[Any],
|
|
highlighter: _HighlightFunc,
|
|
verbose: int = 0,
|
|
) -> list[str]:
|
|
return _set_one_sided_diff("right", right, left, highlighter)
|
|
|
|
|
|
def _compare_lte_set(
|
|
left: AbstractSet[Any],
|
|
right: AbstractSet[Any],
|
|
highlighter: _HighlightFunc,
|
|
verbose: int = 0,
|
|
) -> list[str]:
|
|
return _set_one_sided_diff("left", left, right, highlighter)
|
|
|
|
|
|
def _set_one_sided_diff(
|
|
posn: str,
|
|
set1: AbstractSet[Any],
|
|
set2: AbstractSet[Any],
|
|
highlighter: _HighlightFunc,
|
|
) -> list[str]:
|
|
explanation = []
|
|
diff = set1 - set2
|
|
if diff:
|
|
explanation.append(f"Extra items in the {posn} set:")
|
|
for item in diff:
|
|
explanation.append(highlighter(saferepr(item)))
|
|
return explanation
|
|
|
|
|
|
def _compare_eq_dict(
|
|
left: Mapping[Any, Any],
|
|
right: Mapping[Any, Any],
|
|
highlighter: _HighlightFunc,
|
|
verbose: int = 0,
|
|
) -> list[str]:
|
|
explanation: list[str] = []
|
|
set_left = set(left)
|
|
set_right = set(right)
|
|
common = set_left.intersection(set_right)
|
|
same = {k: left[k] for k in common if left[k] == right[k]}
|
|
if same and verbose < 2:
|
|
explanation += [f"Omitting {len(same)} identical items, use -vv to show"]
|
|
elif same:
|
|
explanation += ["Common items:"]
|
|
explanation += highlighter(pprint.pformat(same)).splitlines()
|
|
diff = {k for k in common if left[k] != right[k]}
|
|
if diff:
|
|
explanation += ["Differing items:"]
|
|
for k in diff:
|
|
explanation += [
|
|
highlighter(saferepr({k: left[k]}))
|
|
+ " != "
|
|
+ highlighter(saferepr({k: right[k]}))
|
|
]
|
|
extra_left = set_left - set_right
|
|
len_extra_left = len(extra_left)
|
|
if len_extra_left:
|
|
explanation.append(
|
|
"Left contains %d more item%s:"
|
|
% (len_extra_left, "" if len_extra_left == 1 else "s")
|
|
)
|
|
explanation.extend(
|
|
highlighter(pprint.pformat({k: left[k] for k in extra_left})).splitlines()
|
|
)
|
|
extra_right = set_right - set_left
|
|
len_extra_right = len(extra_right)
|
|
if len_extra_right:
|
|
explanation.append(
|
|
"Right contains %d more item%s:"
|
|
% (len_extra_right, "" if len_extra_right == 1 else "s")
|
|
)
|
|
explanation.extend(
|
|
highlighter(pprint.pformat({k: right[k] for k in extra_right})).splitlines()
|
|
)
|
|
return explanation
|
|
|
|
|
|
def _compare_eq_cls(
|
|
left: Any, right: Any, highlighter: _HighlightFunc, verbose: int
|
|
) -> list[str]:
|
|
if not has_default_eq(left):
|
|
return []
|
|
if isdatacls(left):
|
|
import dataclasses
|
|
|
|
all_fields = dataclasses.fields(left)
|
|
fields_to_check = [info.name for info in all_fields if info.compare]
|
|
elif isattrs(left):
|
|
all_fields = left.__attrs_attrs__
|
|
fields_to_check = [field.name for field in all_fields if getattr(field, "eq")]
|
|
elif isnamedtuple(left):
|
|
fields_to_check = left._fields
|
|
else:
|
|
assert False
|
|
|
|
indent = " "
|
|
same = []
|
|
diff = []
|
|
for field in fields_to_check:
|
|
if getattr(left, field) == getattr(right, field):
|
|
same.append(field)
|
|
else:
|
|
diff.append(field)
|
|
|
|
explanation = []
|
|
if same or diff:
|
|
explanation += [""]
|
|
if same and verbose < 2:
|
|
explanation.append(f"Omitting {len(same)} identical items, use -vv to show")
|
|
elif same:
|
|
explanation += ["Matching attributes:"]
|
|
explanation += highlighter(pprint.pformat(same)).splitlines()
|
|
if diff:
|
|
explanation += ["Differing attributes:"]
|
|
explanation += highlighter(pprint.pformat(diff)).splitlines()
|
|
for field in diff:
|
|
field_left = getattr(left, field)
|
|
field_right = getattr(right, field)
|
|
explanation += [
|
|
"",
|
|
f"Drill down into differing attribute {field}:",
|
|
f"{indent}{field}: {highlighter(repr(field_left))} != {highlighter(repr(field_right))}",
|
|
]
|
|
explanation += [
|
|
indent + line
|
|
for line in _compare_eq_any(
|
|
field_left, field_right, highlighter, verbose
|
|
)
|
|
]
|
|
return explanation
|
|
|
|
|
|
def _notin_text(term: str, text: str, verbose: int = 0) -> list[str]:
|
|
index = text.find(term)
|
|
head = text[:index]
|
|
tail = text[index + len(term) :]
|
|
correct_text = head + tail
|
|
diff = _diff_text(text, correct_text, verbose)
|
|
newdiff = [f"{saferepr(term, maxsize=42)} is contained here:"]
|
|
for line in diff:
|
|
if line.startswith("Skipping"):
|
|
continue
|
|
if line.startswith("- "):
|
|
continue
|
|
if line.startswith("+ "):
|
|
newdiff.append(" " + line[2:])
|
|
else:
|
|
newdiff.append(line)
|
|
return newdiff
|
|
|
|
|
|
def running_on_ci() -> bool:
|
|
"""Check if we're currently running on a CI system."""
|
|
env_vars = ["CI", "BUILD_NUMBER"]
|
|
return any(var in os.environ for var in env_vars)
|