sim86 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sim86/pytest_plugin.py ADDED
@@ -0,0 +1,137 @@
1
+ """pytest plugin: a `board` fixture that is a live cloud run of your board file.
2
+
3
+ def test_boots(board):
4
+ board["mcu"].serial.wait_for("ready", ms=500)
5
+
6
+ Pick the file with `--sim86-board path`, `sim86_board = …` in pytest.ini,
7
+ or per test with `@pytest.mark.board("other.json", scenario="s.json", duration="20s")`.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import time
14
+ from pathlib import Path
15
+ from typing import Any, Iterator
16
+
17
+ import pytest
18
+
19
+ from .api import IS_DEV_BUILD, TARGETS, Client, Sim86Error
20
+ from .board import check_board, load_board
21
+
22
+ DEFAULT_TEST_DURATION = "60s" # simulated; per test via @pytest.mark.board(duration=…)
23
+ DEFAULT_TEST_REALTIME = "10m"
24
+ OPEN_GRACE_S = 3.0 # wall time for a browser to open the page and attach
25
+
26
+
27
+ def pytest_addoption(parser: pytest.Parser) -> None:
28
+ group = parser.getgroup("sim86")
29
+ group.addoption("--sim86-board", dest="sim86_board", help="board JSON for the `board` fixture")
30
+ group.addoption("--sim86-firmware", dest="sim86_firmware", action="append", default=[], metavar="ID=PATH",
31
+ help="use another firmware image for one chip")
32
+ # --open, as on `sim86 run`; --sim86-open is the older name and still works.
33
+ group.addoption("--open", "--sim86-open", dest="sim86_open", action="store_true",
34
+ help="watch each test live: open its run page and hold the board until the page is up")
35
+ group.addoption("--sim86-linger", dest="sim86_linger", type=float, default=None, metavar="SECONDS",
36
+ help="keep each run going this long after its test, so a viewer sees the end (default 3 with --open)")
37
+ if IS_DEV_BUILD:
38
+ group.addoption("--sim86-target", dest="sim86_target", choices=sorted(TARGETS), default=None,
39
+ help="servers to use (dev build only)")
40
+ parser.addini("sim86_board", "board JSON for the `board` fixture", default="board.json")
41
+
42
+
43
+ def pytest_configure(config: pytest.Config) -> None:
44
+ config.addinivalue_line("markers", "board(path=None, *, scenario=None, duration=None, seed=None, "
45
+ "firmware=None): which board / plan a test runs")
46
+
47
+
48
+ @pytest.fixture(scope="session")
49
+ def sim86_client(pytestconfig: pytest.Config) -> Client:
50
+ return Client(target=pytestconfig.getoption("sim86_target", None) if IS_DEV_BUILD else None)
51
+
52
+
53
+ @pytest.fixture
54
+ def board(request: pytest.FixtureRequest, sim86_client: Client) -> Iterator[Any]:
55
+ from .run import Run
56
+
57
+ marker = request.node.get_closest_marker("board")
58
+ kw = dict(marker.kwargs) if marker else {}
59
+ cfg = request.config
60
+ path = (marker.args[0] if marker and marker.args else None) or cfg.getoption("sim86_board") or cfg.getini(
61
+ "sim86_board")
62
+ path = Path(path)
63
+ if not path.is_absolute():
64
+ path = Path(cfg.rootpath) / path
65
+ overrides = dict(x.split("=", 1) for x in cfg.getoption("sim86_firmware") or [])
66
+ overrides.update(kw.get("firmware") or {})
67
+ b = load_board(path, overrides)
68
+ problems = check_board(b, sim86_client)
69
+ if problems:
70
+ pytest.fail(f"{path.name} can't run:\n - " + "\n - ".join(problems), pytrace=False)
71
+ scenario = kw.get("scenario")
72
+ if isinstance(scenario, (str, Path)):
73
+ sp = Path(scenario)
74
+ scenario = json.loads((sp if sp.is_absolute() else path.parent / sp).read_text())
75
+ try:
76
+ run = Run.start(b, sim86_client,
77
+ duration=kw.get("duration") or b.limits.get("duration") or DEFAULT_TEST_DURATION,
78
+ realtime=kw.get("realtime") or b.limits.get("realtime") or DEFAULT_TEST_REALTIME,
79
+ scenario=scenario, seed=kw.get("seed"))
80
+ except Sim86Error as e:
81
+ pytest.fail(f"sim86: {e}", pytrace=False)
82
+ request.node.sim86_run = run
83
+ # On the item: pytest copies item properties into the reports JUnit reads.
84
+ request.node.user_properties.append(("sim86_run", run.url))
85
+ watching = cfg.getoption("sim86_open")
86
+ if watching:
87
+ # Hold simulated time while the page opens, so it sees the test from the start.
88
+ try:
89
+ run.pause()
90
+ sim86_client.open_live(run.url)
91
+ time.sleep(OPEN_GRACE_S)
92
+ except Sim86Error:
93
+ pass
94
+ run.note(f"▶ {request.node.name}")
95
+ if watching:
96
+ try:
97
+ run.resume()
98
+ except Sim86Error:
99
+ pass
100
+ try:
101
+ yield run
102
+ finally:
103
+ report = getattr(request.node, "sim86_report", None)
104
+ try:
105
+ if report is not None and report.failed:
106
+ reason = str(report.longrepr.reprcrash.message if hasattr(report.longrepr, "reprcrash") else report.longrepr)
107
+ run.note(f"✗ {request.node.name}: {reason.splitlines()[0] if reason else 'failed'}")
108
+ elif report is not None and report.skipped:
109
+ run.note(f"– {request.node.name} skipped")
110
+ elif report is not None:
111
+ run.note(f"✓ {request.node.name}")
112
+ except Exception:
113
+ pass
114
+ linger = cfg.getoption("sim86_linger")
115
+ if linger is None and watching:
116
+ linger = 3.0
117
+ if linger:
118
+ time.sleep(linger)
119
+ run.stop()
120
+
121
+
122
+ @pytest.hookimpl(hookwrapper=True)
123
+ def pytest_runtest_makereport(item: pytest.Item, call: pytest.CallInfo) -> Iterator[None]:
124
+ outcome = yield
125
+ report = outcome.get_result()
126
+ run = getattr(item, "sim86_run", None)
127
+ if run is None or report.when != "call":
128
+ return
129
+ item.sim86_report = report
130
+ if report.failed:
131
+ lines = [f"run: {run.url}"]
132
+ if run.faults:
133
+ lines.append("faults still applied: " + "; ".join(run.faults.values()))
134
+ tail = run.serial.lines[-40:]
135
+ lines.append("last output:" if tail else "nothing printed")
136
+ lines += [f" {l}" for l in tail]
137
+ report.sections.append(("sim86", "\n".join(lines)))