quality-loop 0.4.1__tar.gz → 0.5.0__tar.gz

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.
Files changed (62) hide show
  1. {quality_loop-0.4.1/quality_loop.egg-info → quality_loop-0.5.0}/PKG-INFO +3 -2
  2. {quality_loop-0.4.1 → quality_loop-0.5.0}/README.md +2 -1
  3. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/__init__.py +1 -1
  4. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/drive/terminal.py +8 -2
  5. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/guest/__init__.py +129 -17
  6. quality_loop-0.5.0/quality_loop/guest/boot/pytest_main.py +29 -0
  7. quality_loop-0.5.0/quality_loop/guest/suite.py +106 -0
  8. quality_loop-0.5.0/quality_loop/pytest_plugin.py +64 -0
  9. {quality_loop-0.4.1 → quality_loop-0.5.0/quality_loop.egg-info}/PKG-INFO +3 -2
  10. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop.egg-info/SOURCES.txt +4 -0
  11. {quality_loop-0.4.1 → quality_loop-0.5.0}/tests/test_drive.py +19 -0
  12. {quality_loop-0.4.1 → quality_loop-0.5.0}/tests/test_guest.py +109 -0
  13. quality_loop-0.5.0/tests/test_pytest_plugin.py +67 -0
  14. {quality_loop-0.4.1 → quality_loop-0.5.0}/LICENSE +0 -0
  15. {quality_loop-0.4.1 → quality_loop-0.5.0}/pyproject.toml +0 -0
  16. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/OPERATOR.md +0 -0
  17. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/__main__.py +0 -0
  18. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/adapter.py +0 -0
  19. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/audit.py +0 -0
  20. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/awake.py +0 -0
  21. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/cli.py +0 -0
  22. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/compare.py +0 -0
  23. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/config.py +0 -0
  24. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/drive/__init__.py +0 -0
  25. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/drive/_mac.py +0 -0
  26. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/drive/_windows.py +0 -0
  27. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/drive/keys.py +0 -0
  28. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/guest/boot/__init__.py +0 -0
  29. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/guest/boot/launch.py +0 -0
  30. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/guest/boot/screen_agent.py +0 -0
  31. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/guest/screens.py +0 -0
  32. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/install.py +0 -0
  33. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/mcp.py +0 -0
  34. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/operator.py +0 -0
  35. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/pages.py +0 -0
  36. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/processes.py +0 -0
  37. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/progress.py +0 -0
  38. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/report.py +0 -0
  39. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/room.py +0 -0
  40. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/runner.py +0 -0
  41. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/scenario.py +0 -0
  42. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/screens/__init__.py +0 -0
  43. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/screens/_mac.py +0 -0
  44. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/screens/_windows.py +0 -0
  45. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/session.py +0 -0
  46. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/skill/SKILL.md +0 -0
  47. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/skill/references/filing.md +0 -0
  48. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/skill/references/setup.md +0 -0
  49. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/standin.py +0 -0
  50. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop/transcript.py +0 -0
  51. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop.egg-info/dependency_links.txt +0 -0
  52. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop.egg-info/entry_points.txt +0 -0
  53. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop.egg-info/requires.txt +0 -0
  54. {quality_loop-0.4.1 → quality_loop-0.5.0}/quality_loop.egg-info/top_level.txt +0 -0
  55. {quality_loop-0.4.1 → quality_loop-0.5.0}/setup.cfg +0 -0
  56. {quality_loop-0.4.1 → quality_loop-0.5.0}/tests/test_awake.py +0 -0
  57. {quality_loop-0.4.1 → quality_loop-0.5.0}/tests/test_core.py +0 -0
  58. {quality_loop-0.4.1 → quality_loop-0.5.0}/tests/test_loop.py +0 -0
  59. {quality_loop-0.4.1 → quality_loop-0.5.0}/tests/test_mcp.py +0 -0
  60. {quality_loop-0.4.1 → quality_loop-0.5.0}/tests/test_operator.py +0 -0
  61. {quality_loop-0.4.1 → quality_loop-0.5.0}/tests/test_scenario_report.py +0 -0
  62. {quality_loop-0.4.1 → quality_loop-0.5.0}/tests/test_screens.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quality-loop
3
- Version: 0.4.1
3
+ Version: 0.5.0
4
4
  Summary: Measure what a product teaches - its skill, tools or manual - with isolated agent runs of real tasks, reported by an operator agent
5
5
  Author: craftware
6
6
  License-Expression: MIT
@@ -111,7 +111,8 @@ under a policy the person sets. See [Running the loop](https://github.com/crftwr
111
111
  - [Reports](https://github.com/crftwr/quality-loop/blob/main/docs/reports.md): problems, severities, kinds and ids, the
112
112
  reproduction record, and `FINDINGS.md` / `findings.json`.
113
113
  - [Running the app in a VM](https://github.com/crftwr/quality-loop/blob/main/docs/guests.md): one image per OS,
114
- the guest over SSH, a clean machine every run, screens in the guest.
114
+ the guest over SSH or a container, a clean machine every run, screens in
115
+ the guest, a test suite run there.
115
116
  - [Isolation and permissions](https://github.com/crftwr/quality-loop/blob/main/docs/isolation.md): what keeps the room, the
116
117
  operator and the conductor in bounds, why each rule exists, and the known limits.
117
118
  - [Development](https://github.com/crftwr/quality-loop/blob/main/docs/development.md): tests, live tests, releasing.
@@ -80,7 +80,8 @@ under a policy the person sets. See [Running the loop](https://github.com/crftwr
80
80
  - [Reports](https://github.com/crftwr/quality-loop/blob/main/docs/reports.md): problems, severities, kinds and ids, the
81
81
  reproduction record, and `FINDINGS.md` / `findings.json`.
82
82
  - [Running the app in a VM](https://github.com/crftwr/quality-loop/blob/main/docs/guests.md): one image per OS,
83
- the guest over SSH, a clean machine every run, screens in the guest.
83
+ the guest over SSH or a container, a clean machine every run, screens in
84
+ the guest, a test suite run there.
84
85
  - [Isolation and permissions](https://github.com/crftwr/quality-loop/blob/main/docs/isolation.md): what keeps the room, the
85
86
  operator and the conductor in bounds, why each rule exists, and the known limits.
86
87
  - [Development](https://github.com/crftwr/quality-loop/blob/main/docs/development.md): tests, live tests, releasing.
@@ -12,4 +12,4 @@ room is handed, putting the user's machine back - is code here, not an
12
12
  agent's discretion.
13
13
  """
14
14
 
15
- __version__ = "0.4.1"
15
+ __version__ = "0.5.0"
@@ -87,6 +87,7 @@ class PtyApp:
87
87
  os.close(slave)
88
88
  self._lock = threading.Lock()
89
89
  self._changed = self._sent = time.monotonic()
90
+ self._drawn = False
90
91
  self._closed = False
91
92
  self._reader = threading.Thread(target=self._read, daemon=True)
92
93
  self._reader.start()
@@ -105,6 +106,7 @@ class PtyApp:
105
106
  with self._lock:
106
107
  self.stream.feed(data)
107
108
  self._changed = time.monotonic()
109
+ self._drawn = True
108
110
 
109
111
  def _write(self, data: bytes) -> None:
110
112
  if not self._closed:
@@ -146,13 +148,17 @@ class PtyApp:
146
148
  Quiet is counted from the last key sent as well as the last output: a
147
149
  key the app answers with nothing would otherwise be "settled" at once,
148
150
  on the silence from before it - the first live check recorded
149
- ``waited: 0.0`` exactly there.
151
+ ``waited: 0.0`` exactly there. And nothing is settled before the app
152
+ has written anything: an app still importing is silent too, and a
153
+ slow start (a container with no bytecode cache, xefm#843) was read
154
+ as an empty screen.
150
155
  """
151
156
  deadline = time.monotonic() + patience
152
157
  while time.monotonic() < deadline:
153
158
  with self._lock:
154
159
  since = time.monotonic() - max(self._changed, self._sent)
155
- if since >= quiet or self.process.poll() is not None:
160
+ drawn = self._drawn
161
+ if (drawn and since >= quiet) or self.process.poll() is not None:
156
162
  return True
157
163
  time.sleep(min(quiet / 4, 0.1))
158
164
  return False
@@ -45,7 +45,17 @@ in ``~/.config/quality-loop/guests.toml`` (``QUALITY_LOOP_GUESTS`` moves it):
45
45
  smb = "//<user>@<guest>/<share>" # remounted on the share's host side
46
46
  smb_password = "keychain:<service>"
47
47
 
48
+ [qa-linux]
49
+ share = "~/.cache/qa-guest=/qa" # a bind mount
50
+ python = "/usr/local/bin/python3"
51
+ docker = "python:3.13-slim" # a container per run, removed after
52
+
48
53
  Without a VM named, the run uses the guest as it is, already running.
54
+
55
+ A Docker guest is no VM and has no SSH: its commands go through `docker
56
+ exec`, and its share is a bind mount. It has no desktop, so it runs what
57
+ needs none - a test suite, a terminal app - through the same stage, venv and
58
+ runner as a VM (:mod:`quality_loop.guest.suite`).
49
59
  """
50
60
 
51
61
  from __future__ import annotations
@@ -70,6 +80,11 @@ GUESTS = pathlib.Path("~/.config/quality-loop/guests.toml")
70
80
 
71
81
  HERE = pathlib.Path(__file__).resolve().parent
72
82
 
83
+ #: Set, to the guest's alias, for a test suite a guest runs
84
+ #: (:func:`quality_loop.guest.suite.run_pytest`); the pytest plugin skips the
85
+ #: ``host_only`` tests where it is.
86
+ IN_GUEST = "QUALITY_LOOP_IN_GUEST"
87
+
73
88
 
74
89
  class GuestError(Exception):
75
90
  """The guest could not be reached, started or used."""
@@ -119,6 +134,9 @@ class Guest:
119
134
  self.host_share = pathlib.Path(host_share).resolve()
120
135
  self.guest_share = guest_share
121
136
  self.settings = settings or {}
137
+ self._system: str | None = None
138
+ #: What a caller may set instead of asking (tests do): True is
139
+ #: Windows, False macOS.
122
140
  self._windows: bool | None = None
123
141
  #: Set while a run's clone is up: its address, which the alias's
124
142
  #: HostName does not know.
@@ -155,18 +173,23 @@ class Guest:
155
173
  from another process: JSON, no secrets."""
156
174
  return {"alias": self.alias, "hostname": self.hostname,
157
175
  "host_share": str(self.host_share), "guest_share": self.guest_share,
158
- "windows": self.windows, "python": self.python}
176
+ "windows": self.windows, "system": self.system, "python": self.python}
159
177
 
160
178
  @classmethod
161
179
  def from_screen_settings(cls, settings: dict) -> "Guest":
162
180
  guest = cls(settings["alias"], pathlib.Path(settings["host_share"]),
163
181
  settings["guest_share"], {"python": settings.get("python")})
164
- guest._windows = settings["windows"]
182
+ guest._system = "Windows" if settings["windows"] else settings.get("system", "Darwin")
165
183
  guest.hostname = settings.get("hostname")
166
184
  return guest
167
185
 
168
186
  # --- talking to it ---------------------------------------------------------
169
187
 
188
+ @property
189
+ def docker(self) -> bool:
190
+ """Whether the guest is a container rather than a VM over SSH."""
191
+ return "docker" in self.settings
192
+
170
193
  def ssh_options(self) -> list[str]:
171
194
  if self.hostname is None:
172
195
  return []
@@ -174,11 +197,20 @@ class Guest:
174
197
  return ["-o", f"HostName={self.hostname}", "-o", f"HostKeyAlias={self.alias}",
175
198
  "-o", "StrictHostKeyChecking=accept-new"]
176
199
 
200
+ def argv(self, command: str) -> list[str]:
201
+ """What runs the shell command ``command`` in the guest, from the
202
+ host: SSH to a VM, `docker exec` into a container."""
203
+ if self.docker:
204
+ if self.hostname is None:
205
+ raise GuestError(f"the container for {self.alias!r} is not up: "
206
+ "run inside guest.machine()")
207
+ return ["docker", "exec", self.hostname, "sh", "-c", command]
208
+ return ["ssh", "-o", "BatchMode=yes", *self.ssh_options(), self.alias, command]
209
+
177
210
  def ssh(self, command: str, timeout: float = 60) -> subprocess.CompletedProcess:
178
- return subprocess.run(["ssh", "-o", "BatchMode=yes", *self.ssh_options(),
179
- self.alias, command],
180
- capture_output=True, text=True, timeout=timeout,
181
- stdin=subprocess.DEVNULL)
211
+ """Run ``command`` in the guest's shell (over SSH, or `docker exec`)."""
212
+ return subprocess.run(self.argv(command), capture_output=True, text=True,
213
+ timeout=timeout, stdin=subprocess.DEVNULL)
182
214
 
183
215
  def reachable(self, patience: float) -> bool:
184
216
  """Whether SSH gets in within ``patience`` seconds."""
@@ -195,6 +227,8 @@ class Guest:
195
227
  def machine(self):
196
228
  """A context manager for the run: the VM up from a clean state, and
197
229
  put away afterwards, when the settings name one."""
230
+ if self.docker:
231
+ return DockerMachine(self)
198
232
  if "tart" in self.settings:
199
233
  return TartMachine(self)
200
234
  if "vmx" in self.settings:
@@ -202,20 +236,27 @@ class Guest:
202
236
  return contextlib.nullcontext()
203
237
 
204
238
  @property
205
- def windows(self) -> bool:
206
- """Whether the guest is Windows - asked once. A Windows guest's shell
207
- is PowerShell, where `uname` is no command."""
208
- if self._windows is None:
239
+ def system(self) -> str:
240
+ """``Darwin``, ``Linux`` or ``Windows`` - asked once. A Windows
241
+ guest's shell is PowerShell, where `uname` is no command."""
242
+ if self._system is None and self._windows is not None:
243
+ return "Windows" if self._windows else "Darwin"
244
+ if self._system is None:
209
245
  said = self.ssh("uname -s")
210
246
  if said.returncode == 255:
211
247
  raise GuestError(f"cannot reach the VM as {self.alias!r}:\n{said.stderr}")
212
- self._windows = said.stdout.strip() != "Darwin"
213
- return self._windows
248
+ answer = said.stdout.strip()
249
+ self._system = answer if answer in ("Darwin", "Linux") else "Windows"
250
+ return self._system
251
+
252
+ @property
253
+ def windows(self) -> bool:
254
+ return self.system == "Windows"
214
255
 
215
256
  @property
216
257
  def platform(self) -> str:
217
258
  """``sys.platform`` as the guest's own Python would say it."""
218
- return "win32" if self.windows else "darwin"
259
+ return {"Windows": "win32", "Darwin": "darwin", "Linux": "linux"}[self.system]
219
260
 
220
261
  @property
221
262
  def python(self) -> str:
@@ -252,6 +293,8 @@ class Guest:
252
293
  return self._tunnel("-R", port, start_new_session=True)
253
294
 
254
295
  def _tunnel(self, direction: str, port: int, **popen) -> subprocess.Popen:
296
+ if self.docker:
297
+ raise GuestError(f"{self.alias!r} is a container: no SSH tunnels")
255
298
  return subprocess.Popen(
256
299
  ["ssh", "-N", "-o", "BatchMode=yes", "-o", "ExitOnForwardFailure=yes",
257
300
  *self.ssh_options(), direction, f"{port}:127.0.0.1:{port}", self.alias],
@@ -480,11 +523,54 @@ class TartMachine:
480
523
  return False
481
524
 
482
525
 
526
+ class DockerMachine:
527
+ """A container from ``docker`` (an image) for this run, removed after it.
528
+
529
+ It sleeps until the run is done, under ``--init``, which reaps what a
530
+ test orphans as a real system's init does (a zombie answers ``kill(pid,
531
+ 0)`` as if it ran). Every command is a `docker exec` into it
532
+ (:meth:`Guest.argv`), as root; the share is a bind mount, at the
533
+ share's guest side. The container's name stands in :attr:`Guest.hostname`
534
+ while it is up. Nothing in it outlives the run: what a product needs
535
+ beyond the image - an OS package - it installs on every run, as a VM's
536
+ venv is.
537
+ """
538
+
539
+ def __init__(self, guest: Guest):
540
+ self.guest = guest
541
+ self.image = guest.settings["docker"]
542
+ self.name = f"ql-{guest.alias}-{os.getpid()}"
543
+
544
+ def __enter__(self):
545
+ said = subprocess.run(
546
+ ["docker", "run", "-d", "--rm", "--init", "--name", self.name,
547
+ "-v", f"{self.guest.host_share}:{self.guest.guest_share}",
548
+ "--entrypoint", "sleep", self.image, "infinity"],
549
+ capture_output=True, text=True, stdin=subprocess.DEVNULL)
550
+ if said.returncode != 0:
551
+ raise GuestError(f"docker run {self.image}: {said.stderr.strip()}")
552
+ self.guest.hostname = self.name
553
+ print(f"vm: container {self.name} from {self.image}")
554
+ return self
555
+
556
+ def __exit__(self, *exc):
557
+ subprocess.run(["docker", "rm", "-f", self.name], capture_output=True)
558
+ self.guest.hostname = None
559
+ print(f"vm: container {self.name} removed")
560
+ return False
561
+
562
+
483
563
  class VMwareMachine:
484
564
  """A VMware Fusion VM reverted to a snapshot before the run.
485
565
 
486
- A snapshot taken while the VM was running comes back running, signed in
487
- and with SSH up, after `vmrun start`. The SMB share that was mounted on
566
+ Take the snapshot with the VM shut down, so that every run boots it. A
567
+ snapshot taken while it ran comes back running, signed in and with SSH
568
+ up, in seconds - and with whatever was half done at that moment, every
569
+ time: Keyhac's image came back with Notepad's hand-off to its packaged
570
+ app broken, so `notepad.exe` started the inbox one, which crashed within
571
+ seconds on every run, while the same VM booted was fine. On Windows, the
572
+ run waits for the automatic sign-in, which the image must have. The SMB
573
+ share that was mounted on
488
574
  the host does not survive the revert, so it is mounted again. The VM is
489
575
  shut down afterwards, its share unmounted first: the next run reverts it
490
576
  anyway, and a VM `vmrun` left running headless is one the Fusion app
@@ -495,8 +581,7 @@ class VMwareMachine:
495
581
  Learnt on Fusion 26 with a vTPM-encrypted Windows 11 VM: `vmrun` cannot
496
582
  linked-clone it ("Cannot read the virtual machine configuration file"),
497
583
  nor snapshot it while it runs ("Authentication for encrypted virtual
498
- machine failed") - take a running-state snapshot in the Fusion app, after
499
- `vmrun suspend` (a headless VM does not show there).
584
+ machine failed"). Shut down, `vmrun -vp <password> snapshot` takes it.
500
585
  """
501
586
 
502
587
  VMRUN = "/Applications/VMware Fusion.app/Contents/Library/vmrun"
@@ -533,9 +618,36 @@ class VMwareMachine:
533
618
  f"to {self.snapshot!r}")
534
619
  self._mount()
535
620
  self._wait_for_the_clock()
621
+ if self.guest.windows:
622
+ self._wait_for_the_desktop()
536
623
  print(f"vm: {self.guest.alias} reverted to {self.snapshot!r}")
537
624
  return self
538
625
 
626
+ def _wait_for_the_desktop(self, settle: float = 15.0) -> None:
627
+ """Wait until the guest's user is signed in, and has been for
628
+ ``settle`` seconds.
629
+
630
+ A booted VM answers SSH before the automatic sign-in has made the
631
+ desktop session `launch` starts programs in, and that session's
632
+ first seconds are its startup programs; the run starts after both.
633
+ A running-state snapshot is past them at once.
634
+ """
635
+ deadline = time.monotonic() + self.patience
636
+ while time.monotonic() < deadline:
637
+ said = self.guest.ssh(
638
+ "$e = Get-Process explorer -ErrorAction SilentlyContinue | "
639
+ "Where-Object { $_.SessionId -gt 0 } | Select-Object -First 1; "
640
+ "if ($e) { [int]((Get-Date) - $e.StartTime).TotalSeconds } else { -1 }")
641
+ try:
642
+ up = int(said.stdout.strip())
643
+ except ValueError:
644
+ up = -1
645
+ if up >= settle:
646
+ return
647
+ time.sleep(settle - up if up >= 0 else 3.0)
648
+ raise GuestError(f"{self.guest.alias}: no signed-in desktop after "
649
+ f"{self.patience:.0f}s - is automatic sign-in set up?")
650
+
539
651
  def _mount(self) -> None:
540
652
  url = self.guest.settings.get("smb")
541
653
  if not url:
@@ -0,0 +1,29 @@
1
+ """A product's test suite, run in a guest - never on the host.
2
+
3
+ `quality_loop.guest.suite.run_pytest` stages the product and starts this in
4
+ the guest:
5
+
6
+ pytest_main.py <exit-code file> <pytest args...>
7
+
8
+ On Windows it runs from a scheduled task through ``launch.py``, with
9
+ python.exe - a console of its own, which the tests that run a console program
10
+ inherit - and its output goes to the log on the share. When pytest is done it
11
+ writes pytest's exit code to the file, which is how the host knows the run is
12
+ over. Written whole, then renamed: the host polls for the name.
13
+ """
14
+
15
+ import os
16
+ import sys
17
+
18
+ import pytest
19
+
20
+ done, args = sys.argv[1], sys.argv[2:]
21
+ try:
22
+ code = int(pytest.main(args))
23
+ except BaseException as error: # noqa: BLE001 - the host must hear of any end
24
+ print(f"pytest_main: {error!r}", flush=True)
25
+ code = 3
26
+ sys.stdout.flush()
27
+ with open(done + ".partial", "w", encoding="utf-8") as f:
28
+ f.write(str(code))
29
+ os.replace(done + ".partial", done)
@@ -0,0 +1,106 @@
1
+ """A product's test suite in a guest: pytest run there, its output here.
2
+
3
+ The product stages itself and builds the venv (:meth:`Guest.stage`,
4
+ :meth:`Guest.venv`); :func:`run_pytest` does the rest the same way for every
5
+ guest, which Keyhac and XeFM each used to carry a copy of:
6
+
7
+ - **Windows:** pytest runs in the signed-in desktop session, from a scheduled
8
+ task through ``boot/launch.py``, with ``python.exe`` - a console of its
9
+ own, which a test that runs a console program needs to inherit (under
10
+ pythonw such a test saw code page 0, empty child output, and standard
11
+ handles that could not be duplicated). Its output is a log on the share,
12
+ printed here as it grows.
13
+ - **macOS over SSH, and a container:** the output comes back on the command's
14
+ own stdout, and is printed and logged as it comes.
15
+
16
+ Either way ``boot/pytest_main.py`` writes pytest's exit code to a file on the
17
+ share when it is done; that is the run's answer. The log and the JUnit XML
18
+ are copied to ``results``. :data:`IN_GUEST` is set for the suite, which is how
19
+ :mod:`quality_loop.pytest_plugin` knows to skip the ``host_only`` tests.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import pathlib
25
+ import shutil
26
+ import subprocess
27
+ import sys
28
+ import time
29
+
30
+ from quality_loop.guest import IN_GUEST, Guest, sh_quote
31
+
32
+
33
+ def follow(log: pathlib.Path, done: pathlib.Path, patience: float) -> int:
34
+ """Print ``log`` as it grows until ``done`` holds an exit code; 3 when
35
+ nothing ends within ``patience`` seconds."""
36
+ position, deadline, finished_at = 0, time.monotonic() + patience, None
37
+ while True:
38
+ finished = done.exists()
39
+ chunk = ""
40
+ if log.exists():
41
+ with log.open("r", encoding="utf-8", errors="replace") as f:
42
+ f.seek(position)
43
+ chunk = f.read()
44
+ position = f.tell()
45
+ if chunk:
46
+ sys.stdout.write(chunk)
47
+ sys.stdout.flush()
48
+ if finished:
49
+ # Over SMB the log's last writes can show up after the exit code
50
+ # does: read on until it has stopped growing.
51
+ if chunk or (time.monotonic() - finished_at if finished_at else 0) < 3:
52
+ finished_at = finished_at or time.monotonic()
53
+ time.sleep(1)
54
+ continue
55
+ return int(done.read_text(encoding="utf-8").strip() or 3)
56
+ if time.monotonic() > deadline:
57
+ print(f"\nvm: no end within {patience:.0f}s", flush=True)
58
+ return 3
59
+ time.sleep(1)
60
+
61
+
62
+ def run_pytest(guest: Guest, stage: pathlib.Path, python: str, args: list[str], *,
63
+ cwd: str, results: pathlib.Path, environ: dict | None = None,
64
+ path: list[str] | None = None, patience: float = 3600.0,
65
+ task: str = "ql-test") -> int:
66
+ """pytest with ``args`` in the guest, from ``cwd`` (a guest path) with
67
+ ``python`` (the venv's); returns its exit code, 3 when it never told.
68
+
69
+ ``environ`` is set for the suite, :data:`IN_GUEST` with it; ``path`` goes
70
+ in front of ``sys.path`` too on Windows, where the scheduled task has no
71
+ shell to set PYTHONPATH in. The log and ``junit.xml`` land in
72
+ ``results``, made if need be."""
73
+ log, done, junit = stage / "pytest.log", stage / "exit-code", stage / "junit.xml"
74
+ environ = {**(environ or {}), IN_GUEST: guest.alias}
75
+ argv = [guest.path(done), "-p", "no:cacheprovider", f"--junitxml={guest.path(junit)}",
76
+ *args]
77
+ runner = guest.path(guest.boot_script(stage, "pytest_main.py"))
78
+ task = f"{task}-{stage.name}"
79
+ code = 3
80
+ try:
81
+ if guest.windows:
82
+ guest.launch(stage, task, python, script=runner, log=log, environ=environ,
83
+ path=path, cwd=cwd, argv=argv)
84
+ code = follow(log, done, patience)
85
+ else:
86
+ command = (f"cd {sh_quote(cwd)} && "
87
+ + " ".join(f"{name}={sh_quote(value)}" for name, value in environ.items())
88
+ + f" {sh_quote(python)} {sh_quote(runner)} "
89
+ + " ".join(sh_quote(a) for a in argv))
90
+ with log.open("w", encoding="utf-8") as out:
91
+ process = subprocess.Popen(guest.argv(command), stdin=subprocess.DEVNULL,
92
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
93
+ text=True, errors="replace")
94
+ for line in process.stdout:
95
+ sys.stdout.write(line)
96
+ out.write(line)
97
+ process.wait()
98
+ code = int(done.read_text().strip()) if done.exists() else 3
99
+ finally:
100
+ results.mkdir(parents=True, exist_ok=True)
101
+ for kept in (log, junit):
102
+ if kept.exists():
103
+ shutil.copy2(kept, results / kept.name)
104
+ if guest.windows:
105
+ guest.forget_task(task)
106
+ return code
@@ -0,0 +1,64 @@
1
+ """Two marks for where a product's test may run, shared by Keyhac and XeFM.
2
+
3
+ Load it from the product's pytest configuration (``-p
4
+ quality_loop.pytest_plugin`` in ``addopts``); quality-loop does not register
5
+ it for every pytest that happens to have it installed.
6
+
7
+ - ``desktop`` - the test takes the foreground, opens, moves or resizes
8
+ windows, sends real keys or mouse events, or changes the clipboard, the
9
+ trash or the input source. It gets in the way of whatever the person at the
10
+ machine is doing, and what they do gets in the way of it, so it is skipped
11
+ unless pytest is given ``--desktop`` - which a run in a VM is. A test that
12
+ only reads the OS stays unmarked.
13
+ - ``host_only`` - the test is of the product's host-side tooling: what stages
14
+ a guest, what reviews a release. It needs the developer's checkout (git,
15
+ the packages as installed there), and means nothing in a guest, where it
16
+ is skipped (:data:`quality_loop.guest.IN_GUEST` is set there).
17
+ ``--host-only`` runs these and nothing else, which is the host's share of a
18
+ release's tests once the suite itself runs in the guests.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import os
24
+
25
+ import pytest
26
+
27
+ from quality_loop.guest import IN_GUEST
28
+
29
+
30
+ def pytest_addoption(parser):
31
+ group = parser.getgroup("quality-loop")
32
+ group.addoption("--desktop", action="store_true",
33
+ help="also run the tests marked desktop, which take focus, move windows, "
34
+ "send input or change the clipboard - for a VM")
35
+ group.addoption("--host-only", action="store_true",
36
+ help="run only the tests marked host_only (the host-side tooling)")
37
+
38
+
39
+ def pytest_configure(config):
40
+ config.addinivalue_line(
41
+ "markers", "desktop: touches the live desktop (focus, windows, input, clipboard, "
42
+ "trash); runs only with --desktop, which is for a VM")
43
+ config.addinivalue_line(
44
+ "markers", "host_only: tests the host-side tooling; skipped in a guest")
45
+
46
+
47
+ def pytest_collection_modifyitems(config, items):
48
+ guest = os.environ.get(IN_GUEST)
49
+ if config.getoption("--host-only"):
50
+ if guest:
51
+ raise pytest.UsageError(f"--host-only in a guest ({guest}): the host_only tests "
52
+ "are the ones a guest skips")
53
+ kept = [item for item in items if "host_only" in item.keywords]
54
+ config.hook.pytest_deselected(items=[item for item in items if item not in kept])
55
+ items[:] = kept
56
+ desktop = config.getoption("--desktop")
57
+ skip_desktop = pytest.mark.skip(reason="touches the live desktop: run it in a VM, "
58
+ "or pass --desktop")
59
+ skip_host = pytest.mark.skip(reason=f"tests the host's tooling; this is the guest {guest}")
60
+ for item in items:
61
+ if "desktop" in item.keywords and not desktop:
62
+ item.add_marker(skip_desktop)
63
+ if "host_only" in item.keywords and guest:
64
+ item.add_marker(skip_host)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quality-loop
3
- Version: 0.4.1
3
+ Version: 0.5.0
4
4
  Summary: Measure what a product teaches - its skill, tools or manual - with isolated agent runs of real tasks, reported by an operator agent
5
5
  Author: craftware
6
6
  License-Expression: MIT
@@ -111,7 +111,8 @@ under a policy the person sets. See [Running the loop](https://github.com/crftwr
111
111
  - [Reports](https://github.com/crftwr/quality-loop/blob/main/docs/reports.md): problems, severities, kinds and ids, the
112
112
  reproduction record, and `FINDINGS.md` / `findings.json`.
113
113
  - [Running the app in a VM](https://github.com/crftwr/quality-loop/blob/main/docs/guests.md): one image per OS,
114
- the guest over SSH, a clean machine every run, screens in the guest.
114
+ the guest over SSH or a container, a clean machine every run, screens in
115
+ the guest, a test suite run there.
115
116
  - [Isolation and permissions](https://github.com/crftwr/quality-loop/blob/main/docs/isolation.md): what keeps the room, the
116
117
  operator and the conductor in bounds, why each rule exists, and the known limits.
117
118
  - [Development](https://github.com/crftwr/quality-loop/blob/main/docs/development.md): tests, live tests, releasing.
@@ -16,6 +16,7 @@ quality_loop/operator.py
16
16
  quality_loop/pages.py
17
17
  quality_loop/processes.py
18
18
  quality_loop/progress.py
19
+ quality_loop/pytest_plugin.py
19
20
  quality_loop/report.py
20
21
  quality_loop/room.py
21
22
  quality_loop/runner.py
@@ -36,8 +37,10 @@ quality_loop/drive/keys.py
36
37
  quality_loop/drive/terminal.py
37
38
  quality_loop/guest/__init__.py
38
39
  quality_loop/guest/screens.py
40
+ quality_loop/guest/suite.py
39
41
  quality_loop/guest/boot/__init__.py
40
42
  quality_loop/guest/boot/launch.py
43
+ quality_loop/guest/boot/pytest_main.py
41
44
  quality_loop/guest/boot/screen_agent.py
42
45
  quality_loop/screens/__init__.py
43
46
  quality_loop/screens/_mac.py
@@ -52,5 +55,6 @@ tests/test_guest.py
52
55
  tests/test_loop.py
53
56
  tests/test_mcp.py
54
57
  tests/test_operator.py
58
+ tests/test_pytest_plugin.py
55
59
  tests/test_scenario_report.py
56
60
  tests/test_screens.py
@@ -201,6 +201,8 @@ def test_a_lone_esc_is_not_glued_to_the_next_key(tmp_path):
201
201
  script.write_text(textwrap.dedent('''
202
202
  import os, sys, time, tty
203
203
  tty.setraw(0)
204
+ sys.stdout.write("ready\\r\\n")
205
+ sys.stdout.flush()
204
206
  last, out = time.monotonic(), []
205
207
  while len(out) < 2:
206
208
  data = os.read(0, 16)
@@ -221,3 +223,20 @@ def test_a_lone_esc_is_not_glued_to_the_next_key(tmp_path):
221
223
  app.stop()
222
224
  assert [hex_ for hex_, _gap in seen] == ["1b", "14"], "two reads, not one ESC+key burst"
223
225
  assert seen[1][1] >= terminal.ESC_SETTLE - 0.05
226
+
227
+
228
+ @posix_only
229
+ def test_a_slow_start_is_waited_for_not_read_as_an_empty_screen(tmp_path):
230
+ """XeFM in a container took longer to import than the quiet spell, and its
231
+ first screen was recorded empty (xefm#843)."""
232
+ pytest.importorskip("pyte")
233
+ from quality_loop.drive import terminal
234
+ script = tmp_path / "slow.py"
235
+ script.write_text("import sys, time\ntime.sleep(1.0)\nprint('drawn', flush=True)\n"
236
+ "time.sleep(5)\n")
237
+ app = terminal.PtyApp([sys.executable, str(script)], rows=5, cols=60)
238
+ try:
239
+ assert app.wait_quiet(quiet=0.3, patience=5)
240
+ assert "drawn" in app.text()
241
+ finally:
242
+ app.stop()
@@ -208,8 +208,117 @@ def test_a_terminal_script_is_staged_and_run_with_the_guest_python(share, monkey
208
208
  assert (stage / "scripts" / "deploy.py").exists()
209
209
 
210
210
 
211
+ def test_a_booted_windows_guest_is_waited_for_until_its_desktop_has_settled(share, monkeypatch):
212
+ """A powered-off snapshot boots: SSH answers before the automatic sign-in
213
+ has made the desktop, and then its startup programs run."""
214
+ guest = _guest(share, windows=True, vmx="/v.vmx", snapshot="s")
215
+ answers = iter(["-1", "-1", "4", "16"])
216
+ ssh = FakeSSH(lambda c: (next(answers) + "\n", 0))
217
+ monkeypatch.setattr(guest, "ssh", ssh)
218
+ slept = []
219
+ monkeypatch.setattr(guests.time, "sleep", slept.append)
220
+ guests.VMwareMachine(guest)._wait_for_the_desktop(settle=15)
221
+ assert len(ssh.commands) == 4 and "explorer" in ssh.commands[0]
222
+ assert slept == [3.0, 3.0, 11]
223
+
224
+
225
+ def test_no_desktop_is_an_error_that_names_automatic_sign_in(share, monkeypatch):
226
+ guest = _guest(share, windows=True, vmx="/v.vmx", snapshot="s")
227
+ monkeypatch.setattr(guest, "ssh", FakeSSH(lambda c: ("-1\n", 0)))
228
+ clock = iter(range(0, 1000, 50))
229
+ monkeypatch.setattr(guests.time, "monotonic", lambda: next(clock))
230
+ monkeypatch.setattr(guests.time, "sleep", lambda s: None)
231
+ with pytest.raises(GuestError, match="automatic sign-in"):
232
+ guests.VMwareMachine(guest, patience=120)._wait_for_the_desktop()
233
+
234
+
211
235
  def test_machine_follows_the_settings(share):
212
236
  assert isinstance(_guest(share, tart="base").machine(), guests.TartMachine)
213
237
  assert isinstance(_guest(share, vmx="/v.vmx", snapshot="s").machine(), guests.VMwareMachine)
214
238
  with _guest(share).machine():
215
239
  pass
240
+
241
+
242
+ # --- Linux, and a container --------------------------------------------------------
243
+
244
+ def test_the_system_is_asked_once_and_linux_is_not_windows(share, monkeypatch):
245
+ for answer, platform in (("Linux", "linux"), ("Darwin", "darwin"), ("", "win32")):
246
+ guest = Guest("qa-test", share, str(share), {"python": "python3"})
247
+ fake = FakeSSH(lambda command, a=answer: (a + "\n", 0))
248
+ monkeypatch.setattr(guest, "ssh", fake)
249
+ assert guest.platform == platform and guest.platform == platform
250
+ assert guest.windows == (platform == "win32")
251
+ assert fake.commands == ["uname -s"]
252
+
253
+
254
+ def test_a_docker_guest_runs_its_commands_through_docker_exec(share):
255
+ guest = _guest(share, docker="python:3.13-slim")
256
+ assert isinstance(guest.machine(), guests.DockerMachine)
257
+ with pytest.raises(GuestError, match="not up"):
258
+ guest.argv("true")
259
+ guest.hostname = "ql-qa-test-1"
260
+ assert guest.argv("echo hi") == ["docker", "exec", "ql-qa-test-1", "sh", "-c", "echo hi"]
261
+ with pytest.raises(GuestError, match="no SSH tunnels"):
262
+ guest.forward(8000)
263
+
264
+
265
+ def test_the_container_mounts_the_share_and_is_removed_after(share, monkeypatch):
266
+ calls = []
267
+
268
+ def run(argv, **kwargs):
269
+ calls.append(argv)
270
+ return subprocess.CompletedProcess(argv, 0, "id\n", "")
271
+
272
+ monkeypatch.setattr(guests.subprocess, "run", run)
273
+ guest = _guest(share, docker="python:3.13-slim")
274
+ with guest.machine() as machine:
275
+ assert guest.hostname == machine.name
276
+ started = calls[0]
277
+ assert started[:2] == ["docker", "run"] and f"{share}:{share}" in started
278
+ assert started[started.index("--entrypoint") + 1] == "sleep"
279
+ assert calls[-1] == ["docker", "rm", "-f", machine.name]
280
+ assert guest.hostname is None
281
+
282
+
283
+ # --- the suite runner ---------------------------------------------------------------
284
+
285
+ class LocalGuest(Guest):
286
+ """A POSIX guest that is this machine: its shell commands run here."""
287
+
288
+ def argv(self, command):
289
+ return ["sh", "-c", command]
290
+
291
+
292
+ def test_run_pytest_runs_the_suite_in_the_guest_and_keeps_its_log_and_junit(share, tmp_path):
293
+ from quality_loop.guest import suite
294
+ guest = LocalGuest("qa-local", share, str(share), {"python": sys.executable})
295
+ guest._system = "Linux"
296
+ stage = guest.stage("ql-suite-")
297
+ tree = stage / "tree"
298
+ tree.mkdir()
299
+ (tree / "test_here.py").write_text(
300
+ "import os\n"
301
+ "def test_sees_the_guest():\n"
302
+ " assert os.environ['QUALITY_LOOP_IN_GUEST'] == 'qa-local'\n"
303
+ " assert os.environ['EXTRA'] == 'yes'\n", encoding="utf-8")
304
+ results = tmp_path / "results"
305
+ code = suite.run_pytest(guest, stage, sys.executable, ["-q", "test_here.py"],
306
+ cwd=guest.path(tree), results=results, environ={"EXTRA": "yes"})
307
+ assert code == 0
308
+ assert "1 passed" in (results / "pytest.log").read_text()
309
+ assert "testcase" in (results / "junit.xml").read_text()
310
+
311
+
312
+ def test_run_pytest_answers_3_when_the_runner_never_reports(share, tmp_path):
313
+ from quality_loop.guest import suite
314
+
315
+ class Silent(LocalGuest):
316
+ def argv(self, command):
317
+ return ["sh", "-c", "echo gone"]
318
+
319
+ guest = Silent("qa-local", share, str(share), {"python": sys.executable})
320
+ guest._system = "Darwin"
321
+ stage = guest.stage("ql-suite-")
322
+ assert suite.run_pytest(guest, stage, sys.executable, [], cwd=str(stage),
323
+ results=tmp_path / "r") == 3
324
+ assert "gone" in (tmp_path / "r" / "pytest.log").read_text()
@@ -0,0 +1,67 @@
1
+ """The desktop and host_only marks, run in a pytest of their own."""
2
+
3
+ import os
4
+ import subprocess
5
+ import sys
6
+
7
+
8
+ SUITE = """
9
+ import pytest
10
+
11
+ def test_plain():
12
+ pass
13
+
14
+ @pytest.mark.desktop
15
+ def test_on_the_desktop():
16
+ pass
17
+
18
+ @pytest.mark.host_only
19
+ def test_of_the_tooling():
20
+ pass
21
+ """
22
+
23
+
24
+ def _run(tmp_path, *args, guest=None):
25
+ (tmp_path / "test_marks.py").write_text(SUITE, encoding="utf-8")
26
+ environ = {k: v for k, v in os.environ.items() if k != "QUALITY_LOOP_IN_GUEST"}
27
+ if guest:
28
+ environ["QUALITY_LOOP_IN_GUEST"] = guest
29
+ said = subprocess.run([sys.executable, "-m", "pytest", "-p", "quality_loop.pytest_plugin",
30
+ "-p", "no:cacheprovider", "--strict-markers", "-rs", "-v",
31
+ *args, "test_marks.py"],
32
+ cwd=tmp_path, capture_output=True, text=True, env=environ)
33
+ return said.returncode, said.stdout + said.stderr
34
+
35
+
36
+ def _outcomes(out):
37
+ return {name: outcome for name in ("plain", "on_the_desktop", "of_the_tooling")
38
+ for line in out.splitlines() if f"test_{name} " in line
39
+ for outcome in ("PASSED", "SKIPPED") if outcome in line}
40
+
41
+
42
+ def test_on_the_host_desktop_tests_wait_for_a_vm(tmp_path):
43
+ code, out = _run(tmp_path)
44
+ assert code == 0, out
45
+ assert _outcomes(out) == {"plain": "PASSED", "on_the_desktop": "SKIPPED",
46
+ "of_the_tooling": "PASSED"}
47
+ assert "run it in a VM" in out
48
+
49
+
50
+ def test_in_a_guest_with_desktop_the_tooling_tests_are_skipped(tmp_path):
51
+ code, out = _run(tmp_path, "--desktop", guest="qa-mac")
52
+ assert code == 0, out
53
+ assert _outcomes(out) == {"plain": "PASSED", "on_the_desktop": "PASSED",
54
+ "of_the_tooling": "SKIPPED"}
55
+ assert "this is the guest qa-mac" in out
56
+
57
+
58
+ def test_host_only_runs_just_the_tooling_tests(tmp_path):
59
+ code, out = _run(tmp_path, "--host-only")
60
+ assert code == 0, out
61
+ assert _outcomes(out) == {"of_the_tooling": "PASSED"}
62
+ assert "2 deselected" in out
63
+
64
+
65
+ def test_host_only_is_refused_in_a_guest(tmp_path):
66
+ code, out = _run(tmp_path, "--host-only", guest="qa-win")
67
+ assert code != 0 and "--host-only in a guest" in out
File without changes
File without changes