testflows.machine 0.1.4__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.
@@ -0,0 +1,528 @@
1
+ # Copyright 2026 Katteli Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Checks and conversions of arguments, shared by the SDK's modules."""
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ from collections.abc import Sequence
20
+ from dataclasses import dataclass
21
+ from typing import Any, Callable, Generator, Optional, TypeVar
22
+
23
+ from testflows.machine._core import console_source
24
+ from testflows.machine._core import drive
25
+ from testflows.machine._core import ipc
26
+ from testflows.machine._core import log_lines
27
+ from testflows.machine._core import machines
28
+ from testflows.machine._core import parsers
29
+ from testflows.machine._core import poll
30
+ from testflows.machine._core import timespec
31
+ from testflows.machine._core import wait
32
+ from testflows.machine._core import wire
33
+
34
+ from .errors import InvalidArgument, _translated
35
+
36
+ T = TypeVar("T")
37
+ R = TypeVar("R")
38
+
39
+ #: The `lines` that selects none: the `-n` grammar has no spelling for it.
40
+ NO_LINES = "0"
41
+
42
+ #: The host CPUs a machine may be pinned to, the bounds the CLI holds
43
+ #: `--pin-cpu` to. -1 pins nowhere, which lets the machine pick.
44
+ MIN_PIN_CPU = -1
45
+ MAX_PIN_CPU = 1024
46
+
47
+
48
+ def watched(
49
+ read: Callable[[], R],
50
+ present: Callable[[R], T],
51
+ watch: bool,
52
+ timeout: Optional[float],
53
+ ) -> "T | Generator[T, None, None]":
54
+ """`present(read())`, or with `watch` that of each changed `read()` until
55
+ `timeout`.
56
+
57
+ Changes are judged on what `read` returns, not on what `present` makes of
58
+ it: a handle compares by identity, so a run whose state changed is the
59
+ same handle, and a watch over handles would never see the change.
60
+ """
61
+ if watch:
62
+ changes = poll.changes(read, interval=poll.WATCH_INTERVAL, timeout=timeout)
63
+ return (present(value) for value in changes)
64
+ return present(read())
65
+
66
+
67
+ def same(value: T) -> T:
68
+ """`value`: the `present` of a read whose values are what it returns."""
69
+ return value
70
+
71
+
72
+ def span(value: "int | str | None") -> Optional[parsers.Span]:
73
+ """A drawn value, `n` or `lo:hi[:strategy[:step]]`, or None."""
74
+ return None if value is None else parsers.span_type(str(value))
75
+
76
+
77
+ def timer_slack_span(value: "int | str | None") -> Optional[parsers.Span]:
78
+ """A drawn timer slack for `Run.run`, `2ms` or `0:2ms[:strategy[:step]]`,
79
+ at most a second, or None. InvalidArgument, naming the argument, when it
80
+ is not. `timer_slack` below is the run's own, one value for every run."""
81
+ if value is None:
82
+ return None
83
+ try:
84
+ return parsers.timer_slack_type(str(value))
85
+ except argparse.ArgumentTypeError as exc:
86
+ raise InvalidArgument(f"timer_slack: {exc}") from None
87
+
88
+
89
+ def irq_delay(value: Optional[str]) -> Optional[str]:
90
+ """`[target=]span,...`, each span at most a second, or None.
91
+ InvalidArgument, naming the argument, when it is not."""
92
+ if value is None:
93
+ return None
94
+ try:
95
+ return parsers.irq_delay_type(str(value))
96
+ except argparse.ArgumentTypeError as exc:
97
+ raise InvalidArgument(f"irq_delay: {exc}") from None
98
+
99
+
100
+ def text(value: "int | str | None") -> Optional[str]:
101
+ """A clause word's value as text, which the run's plan grammar checks
102
+ when the run sends it: a number of nanoseconds becomes its digits."""
103
+ return None if value is None else str(value)
104
+
105
+
106
+ def within(value: Optional[str]) -> Optional[int]:
107
+ """A bound in machine time, a duration such as `10s`, in nanoseconds;
108
+ None for none. InvalidArgument when it is no duration."""
109
+ if value is None:
110
+ return None
111
+ if not isinstance(value, str):
112
+ raise InvalidArgument(
113
+ f"within must be a duration as a str, such as '10s', got {value!r}."
114
+ )
115
+ try:
116
+ return drive.within(value)
117
+ except ValueError as exc:
118
+ raise InvalidArgument(str(exc)) from None
119
+
120
+
121
+ def limit_margin(value: Optional[int]) -> Optional[int]:
122
+ """Branches short of a stop where the branch counter interrupts; None for
123
+ the default. InvalidArgument outside 1 to the largest the run keeps."""
124
+ return bounded("limit_margin", value, 1, wire.LIMIT_MARGIN_MAX)
125
+
126
+
127
+ def timer_slack(value: Optional[str]) -> Optional[int]:
128
+ """How late a timer may be, `0` or a duration such as `20ms`, in
129
+ nanoseconds; None for the default. InvalidArgument when it is neither."""
130
+ if value is None:
131
+ return None
132
+ if not isinstance(value, str):
133
+ raise InvalidArgument(
134
+ f"timer_slack must be a duration as a str, such as '20ms', got {value!r}."
135
+ )
136
+ if value.strip() == "0":
137
+ return 0
138
+ try:
139
+ return parsers.parse_duration_ns(value)
140
+ except ValueError as exc:
141
+ raise InvalidArgument(str(exc)) from None
142
+
143
+
144
+ def dispatch_bound(value: Optional[str]) -> Optional[int]:
145
+ """The host time a fast dispatch may run, `0` for the default or a
146
+ duration such as `500ms` or `30s`, in nanoseconds; None for the default."""
147
+ if value is None:
148
+ return None
149
+ if not isinstance(value, str):
150
+ raise InvalidArgument(
151
+ f"dispatch_bound must be a duration as a str, such as '500ms', got {value!r}."
152
+ )
153
+ try:
154
+ return parsers.dispatch_bound_ns(value)
155
+ except ValueError as exc:
156
+ raise InvalidArgument(str(exc)) from None
157
+
158
+
159
+ def stop_count(name: str, value: Optional[int]) -> Optional[int]:
160
+ """An instruction margin or fast backstop, 0 for the default; None for
161
+ the default too. InvalidArgument past what the counter holds."""
162
+ return bounded(name, value, 0, wire.FAST_BACKSTOP_MAX)
163
+
164
+
165
+ def irq_wait(value: Optional[int]) -> Optional[int]:
166
+ """Branches a dispatch runs while an interrupt waits, 0 or None for the
167
+ default. InvalidArgument past what the counter holds."""
168
+ return bounded("irq_wait", value, 0, wire.IRQ_WAIT_MAX)
169
+
170
+
171
+ def bounded(
172
+ name: str, value: Optional[int], lo: int, hi: Optional[int] = None
173
+ ) -> Optional[int]:
174
+ """`value`, refused when it is outside the bounds the CLI holds it to.
175
+
176
+ One check, so a number the service would refuse is refused here with the
177
+ range in the message, rather than travelling to fail there.
178
+ """
179
+ if value is None:
180
+ return None
181
+ if value < lo or (hi is not None and value > hi):
182
+ limit = f"{lo}-{hi}" if hi is not None else f"{lo} or more"
183
+ raise InvalidArgument(f"{name} must be {limit}, got {value}.")
184
+ return value
185
+
186
+
187
+ def positive(name: str, value: float) -> float:
188
+ """`value`, refused when it is not above zero: an interval of 0 would spin
189
+ and a negative one names no time at all."""
190
+ if value <= 0:
191
+ raise InvalidArgument(f"{name} must be more than 0, got {value}.")
192
+ return value
193
+
194
+
195
+ def tid(value: int) -> int:
196
+ """A thread id, checked as the CLI checks it."""
197
+ with _translated():
198
+ return int(parsers.tid_type(str(value)))
199
+
200
+
201
+ def focus_entry(value: str) -> str:
202
+ """One focus entry, checked as the CLI checks it."""
203
+ with _translated():
204
+ return str(parsers.focus_entry_type(value))
205
+
206
+
207
+ def disk_ref(value: Any) -> str:
208
+ """A disk by name, from a name or from the `Disk` itself.
209
+
210
+ A run, a session and a disk are all named by their object wherever
211
+ their name is taken, so a program never has to remember which.
212
+ """
213
+ name = getattr(value, "name", None)
214
+ return str(value) if name is None else str(name)
215
+
216
+
217
+ def vcpus(value: "int | str | None") -> Optional[parsers.Span]:
218
+ """A vCPU or a span of them, `n`, `lo:hi`, `lo:` or `:hi`, or None."""
219
+ return None if value is None else parsers.vcpu_span_type(str(value))
220
+
221
+
222
+ def predicate(text: str, *, when: bool = False) -> wait.Predicate:
223
+ """The predicate `text` names; InvalidArgument naming the spelling to
224
+ use when it is not one. `when` refuses it as a state."""
225
+ try:
226
+ return wait.parse(text, when=when)
227
+ except wait.UseOn as exc:
228
+ raise InvalidArgument(f"{exc} Write {exc.replacement}") from None
229
+ except ValueError as exc:
230
+ raise InvalidArgument(str(exc)) from None
231
+
232
+
233
+ def check_choice(option: str, value: Optional[str], choices: tuple[str, ...]) -> None:
234
+ """InvalidArgument when `value` is given and not one of `choices`."""
235
+ if value is not None and value not in choices:
236
+ raise InvalidArgument(
237
+ f"{option} must be one of {', '.join(choices)}, got {value!r}."
238
+ )
239
+
240
+
241
+ @dataclass(frozen=True)
242
+ class OpFilters:
243
+ """The state and type filters an operations listing sends, None for all."""
244
+
245
+ states: Optional[list[str]]
246
+ types: Optional[list[str]]
247
+
248
+
249
+ def op_filters(
250
+ op_id: Optional[int],
251
+ states: Optional[list[str]],
252
+ types: Optional[list[str]],
253
+ type_choices: tuple[str, ...],
254
+ state_choices: tuple[str, ...] = machines.OP_STATE_CHOICES,
255
+ ) -> OpFilters:
256
+ """Check and resolve an operations listing's filters. An `op_id` names
257
+ one operation, so it sends neither."""
258
+ for term in states or []:
259
+ check_choice("state", term.removeprefix("^"), state_choices)
260
+ for kind in types or []:
261
+ check_choice("type", kind.removeprefix("^"), type_choices)
262
+ if op_id is not None:
263
+ return OpFilters(states=None, types=None)
264
+ return OpFilters(
265
+ states=machines.resolve_op_states(states, state_choices),
266
+ types=machines.resolve_op_types(types, type_choices),
267
+ )
268
+
269
+
270
+ def lines_spec(lines: "int | str | None") -> Optional[str]:
271
+ """`lines` in the range grammar: an int N is line N, -N the last N, and 0
272
+ `NO_LINES`, which starts at the end of the log."""
273
+ if lines is None:
274
+ return None
275
+ if isinstance(lines, int):
276
+ return NO_LINES if lines == 0 else str(lines)
277
+ return lines
278
+
279
+
280
+ def window(
281
+ read: log_lines.ReadFn, lines: "int | str | None", *, follow: bool = False
282
+ ) -> log_lines.Window:
283
+ """The lines `lines` selects, read; 0 is none, at the end of the log."""
284
+ spec = lines_spec(lines)
285
+ if spec == NO_LINES:
286
+ return log_lines.end(read)
287
+ return log_lines.read_window(read, spec, follow=follow)
288
+
289
+
290
+ def source(name: str) -> console_source.Source:
291
+ """The source of output `name` names: `console`, `all`, a serial port
292
+ such as `ttyS1`, `hvc0`, `debugcon`, or an output file or a directory
293
+ of them by its path."""
294
+ try:
295
+ return console_source.parse(name)
296
+ except ValueError:
297
+ raise InvalidArgument(
298
+ f"No such source: {name}. A source is one of {console_source.NAMES}."
299
+ ) from None
300
+
301
+
302
+ def point(name: str, value: Optional[str]) -> Optional[str]:
303
+ """A point given as text, as an argument named `name` takes one: a str,
304
+ or None for the argument's default. An int is refused, since a bare
305
+ number and an entry are different points: an entry is `"#300"`, and a
306
+ time is a `Point`."""
307
+ if isinstance(value, str) and not value.strip():
308
+ # Read as no point, an empty one forked here and now.
309
+ raise InvalidArgument(f"{name}: {timespec.EMPTY_POINT}.")
310
+ if value is None or isinstance(value, str):
311
+ return value
312
+ raise InvalidArgument(
313
+ f"{name} must be a point: a str such as '^booted' or '#300', a Point,"
314
+ f" a Place or a Checkpoint, got {value!r}."
315
+ )
316
+
317
+
318
+ def stored(
319
+ keep: "Sequence[str] | str | None", drop: "Sequence[str] | str | None"
320
+ ) -> ipc.Output:
321
+ """What a run stores of its output besides what the directories say:
322
+ the sources `keep` and `drop` name, each one name or several. None
323
+ leaves a list to the run this one comes from, and an empty list is a
324
+ list of none."""
325
+ kept = None if keep is None else _names(keep)
326
+ dropped = None if drop is None else _names(drop)
327
+ for name in (*(kept or ()), *(dropped or ())):
328
+ _stored_name(name)
329
+ try:
330
+ return ipc.Output.of(kept, dropped)
331
+ except ValueError as exc:
332
+ raise InvalidArgument(str(exc)) from None
333
+
334
+
335
+ def _stored_name(name: str) -> None:
336
+ """Check one name of what is kept or dropped: a source, or a pattern
337
+ that can match one, such as `/output/drop/*/*.log`. The word that is
338
+ a list of none on a command line is no name here: an empty list says
339
+ it."""
340
+ if name == console_source.STORED_NONE:
341
+ raise InvalidArgument(
342
+ f"No such source: {name}. An empty list keeps or drops none."
343
+ )
344
+ if not console_source.is_pattern(name):
345
+ source(name)
346
+ return
347
+ try:
348
+ console_source.check_stored(name)
349
+ except ValueError:
350
+ raise InvalidArgument(
351
+ f"No source matches: {name}. {console_source.PATTERNS}."
352
+ ) from None
353
+
354
+
355
+ def _names(value: "Sequence[str] | str | None") -> Sequence[str]:
356
+ """One name, several or none, as several."""
357
+ if value is None:
358
+ return ()
359
+ return (value,) if isinstance(value, str) else value
360
+
361
+
362
+ def line_text(line: str) -> str:
363
+ """A log line without the carriage return a serial console ends it with."""
364
+ return line.rstrip("\r")
365
+
366
+
367
+ def followed(
368
+ read: log_lines.ReadFn, lines: "int | str | None", timeout: Optional[float]
369
+ ) -> Generator[str, None, None]:
370
+ """The lines `lines` selects, then each line written after them."""
371
+ first = window(read, lines, follow=True)
372
+ yield from first.lines
373
+ yield from log_lines.follow(
374
+ read,
375
+ first.next_line,
376
+ first.partial,
377
+ interval=log_lines.FOLLOW_INTERVAL,
378
+ timeout=timeout,
379
+ )
380
+
381
+
382
+ #: How every reader of the SDK spells which entries it wants. One grammar, so
383
+ #: `entries`, `output` and `play` cannot come to mean different things by the
384
+ #: same words.
385
+ ENTRIES_GRAMMAR = (
386
+ "N or (a, b) for one entry or a range, `A:B` for A through B, `A:` from A"
387
+ " on, `:B` up to B, `:` for every entry, `-N` for the last N, `-A:-B` from"
388
+ " the Ath from the end through the Bth, and a Python slice, which is"
389
+ " half-open as Python's are"
390
+ )
391
+
392
+
393
+ def entries_spec(entries: "int | tuple[int, int] | str | slice") -> str:
394
+ """The entries `entries` names, in the one grammar every reader takes.
395
+
396
+ Returned in the form the machine's log reader takes, so the readers that
397
+ want a pair and the readers that want a selection parse one spelling.
398
+ """
399
+ if isinstance(entries, int):
400
+ return f"{entries}:{entries}"
401
+ if isinstance(entries, slice):
402
+ return _slice_spec(entries)
403
+ if isinstance(entries, tuple):
404
+ first, last = entries
405
+ return f"{int(first)}:{int(last)}"
406
+ text = entries.strip()
407
+ if not text:
408
+ raise InvalidArgument(f"Entries required: {ENTRIES_GRAMMAR}.")
409
+ if text.startswith("-"):
410
+ return _from_the_end(text)
411
+ if ":" not in text:
412
+ one = _count(text, text)
413
+ return f"{one}:{one}"
414
+ first_text, _, last_text = text.partition(":")
415
+ first = _count(first_text, text) if first_text else 0
416
+ if not last_text:
417
+ return f"{first}:"
418
+ return f"{first}:{_count(last_text, text)}"
419
+
420
+
421
+ def _from_the_end(text: str) -> str:
422
+ """`-A`, `-A:` and `-A:-B`: entries counted from the end, both ends
423
+ included, -1 the last."""
424
+ first_text, colon, last_text = text.partition(":")
425
+ first = _count(first_text[1:], text)
426
+ if not colon or not last_text:
427
+ return f"-{first}"
428
+ if not last_text.startswith("-"):
429
+ raise InvalidArgument(
430
+ f"Not entries: {text!r}. Both ends count from the end, as in"
431
+ " '-10:-2', or neither, as in '100:200'."
432
+ )
433
+ last = _count(last_text[1:], text)
434
+ if last > first:
435
+ raise InvalidArgument(f"Not entries: {text!r}. It ends before it starts.")
436
+ return f"-{first}:-{last}"
437
+
438
+
439
+ def _slice_spec(window: slice) -> str:
440
+ """A Python slice as the entries grammar spells it.
441
+
442
+ HALF-OPEN, the way every Python slice is: `slice(100, 200)` is 100 through
443
+ 199, where `(100, 200)` and `"100:200"` are 100 through 200. Each spelling
444
+ is right in its own convention -- the tuple and the string are the
445
+ machine's, which is what its messages and the CLI print, and the slice is
446
+ Python's, which is what `[100:200]` means in the language it is written in.
447
+
448
+ `slice(-N, None)` is the last N, as `[-N:]` is, and `slice(-A, -B)` stops
449
+ before the Bth from the end, as `[-A:-B]` does. A negative at one end only
450
+ names nothing the log reader can read without the run's length, and a
451
+ step asks for a stride it does not walk.
452
+ """
453
+ if window.step is not None and window.step != 1:
454
+ raise InvalidArgument(
455
+ f"A step of {window.step} is not an entry range: entries come one"
456
+ " after another."
457
+ )
458
+ start, stop = window.start, window.stop
459
+ if start is not None and start < 0:
460
+ if stop is None:
461
+ return f"{start}"
462
+ if stop >= 0:
463
+ raise InvalidArgument(
464
+ f"slice({start}, {stop}) counts one end from the end and the"
465
+ " other from the start: count both from the end, or neither."
466
+ )
467
+ if stop <= start:
468
+ raise InvalidArgument(
469
+ f"slice({start}, {stop}) names no entry: a range ends after"
470
+ " where it starts."
471
+ )
472
+ return f"{start}:{stop - 1}"
473
+ if stop is not None and stop < 0:
474
+ raise InvalidArgument(
475
+ f"slice({start}, {stop}) counts one end from the end and the other"
476
+ " from the start: count both from the end, or neither."
477
+ )
478
+ first = 0 if start is None else int(start)
479
+ if stop is None:
480
+ return f"{first}:"
481
+ last = int(stop) - 1
482
+ if last < first:
483
+ raise InvalidArgument(
484
+ f"slice({start}, {stop}) names no entry: a range ends at or after"
485
+ " where it starts."
486
+ )
487
+ return f"{first}:{last}"
488
+
489
+
490
+ def source_window(
491
+ entries: "int | tuple[int, int] | str | slice | None",
492
+ ) -> Optional[str]:
493
+ """A window of a source log by entry id, in the entries grammar."""
494
+ if entries is None:
495
+ return None
496
+ return entries_spec(entries)
497
+
498
+
499
+ def entry_pair(entries: "int | tuple[int, int] | str | slice") -> tuple[int, int]:
500
+ """The first and last entry `entries` names, both included.
501
+
502
+ `-N`, the last N, comes back as a negative first entry, and `-A:-B` as a
503
+ negative first and last, which the reader turns into ids against the
504
+ run's tip.
505
+ """
506
+ spec = entries_spec(entries)
507
+ if spec.startswith("-"):
508
+ first_text, _, last_text = spec.partition(":")
509
+ return int(first_text), int(last_text) if last_text else _LAST_ENTRY
510
+ first_text, _, last_text = spec.partition(":")
511
+ return int(first_text), int(last_text) if last_text else _LAST_ENTRY
512
+
513
+
514
+ #: The open end of a range, past any entry a run records.
515
+ _LAST_ENTRY = (1 << 63) - 1
516
+
517
+
518
+ def _count(text: str, whole: str) -> int:
519
+ """One number of the entries grammar, refused when it is not one."""
520
+ try:
521
+ value = int(text)
522
+ except ValueError:
523
+ raise InvalidArgument(
524
+ f"Not entries: {whole!r}. Name {ENTRIES_GRAMMAR}."
525
+ ) from None
526
+ if value < 0:
527
+ raise InvalidArgument(f"Not entries: {whole!r}. An entry is 0 or more.")
528
+ return value
@@ -0,0 +1,113 @@
1
+ # Copyright 2026 Katteli Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """The TestFlows Machine SDK Core this SDK runs on.
15
+
16
+ The SDK Core is one proprietary file, `_testflows_machine_core.abi3.so`,
17
+ licensed under the TestFlows Machine Client EULA and installed by the
18
+ client's installer into `~/.testflows/machine/sdk/`. It is not on PyPI. This module loads it under the
19
+ name `testflows.machine._core`, from the file `TESTFLOWS_MACHINE_CORE` names,
20
+ else an importable `testflows.machine._core`, else the installed file. It
21
+ refuses to import without a core of an interface version the SDK supports.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import importlib.util
27
+ import os
28
+ import sys
29
+ from types import ModuleType
30
+
31
+ import testflows.machine
32
+
33
+ #: The core interface versions this SDK works with.
34
+ CORE_API_VERSIONS = range(1, 2)
35
+ #: The least revision of that interface this SDK needs. A core from before
36
+ #: revisions has none and counts as 1.
37
+ CORE_API_REVISION = 2
38
+
39
+ #: The name the core is loaded under, and the file it ships as.
40
+ CORE_MODULE = "testflows.machine._core"
41
+ CORE_FILE = "_testflows_machine_core.abi3.so"
42
+ #: Where the client's installer puts the core.
43
+ CORE_DIR = os.path.join("~", ".testflows", "machine", "sdk")
44
+ #: A core file to load instead of the installed one.
45
+ CORE_ENV = "TESTFLOWS_MACHINE_CORE"
46
+
47
+ _INSTALLER = "curl https://testflows.com/machine/install -fsS | bash"
48
+ #: Modules whose absence means the core is not importable. Any other import
49
+ #: failure is a core that is present and cannot load, and keeps its own error.
50
+ _CORE_MODULES = ("testflows", "testflows.machine", CORE_MODULE)
51
+
52
+
53
+ def _load(path: str) -> ModuleType:
54
+ """The core file at `path`, loaded as `testflows.machine._core`."""
55
+ spec = importlib.util.spec_from_file_location(CORE_MODULE, path)
56
+ if spec is None or spec.loader is None:
57
+ raise ImportError(f"Not a TestFlows Machine SDK Core: {path}")
58
+ module = importlib.util.module_from_spec(spec)
59
+ sys.modules[CORE_MODULE] = module
60
+ try:
61
+ spec.loader.exec_module(module)
62
+ except BaseException:
63
+ del sys.modules[CORE_MODULE]
64
+ raise
65
+ setattr(testflows.machine, "_core", module)
66
+ return module
67
+
68
+
69
+ def _importable() -> ModuleType | None:
70
+ """An importable `testflows.machine._core`, or None."""
71
+ try:
72
+ import testflows.machine._core as core
73
+ except ModuleNotFoundError as error:
74
+ if error.name not in _CORE_MODULES:
75
+ raise
76
+ return None
77
+ return core
78
+
79
+
80
+ def _core() -> ModuleType:
81
+ """The core, from the first place that has one."""
82
+ named = os.environ.get(CORE_ENV)
83
+ if named:
84
+ if not os.path.isfile(named):
85
+ raise ImportError(f"{CORE_ENV} names no file: {named}")
86
+ return _load(named)
87
+ core = _importable()
88
+ if core is not None:
89
+ return core
90
+ installed = os.path.join(os.path.expanduser(CORE_DIR), CORE_FILE)
91
+ if os.path.isfile(installed):
92
+ return _load(installed)
93
+ raise ImportError(
94
+ "The TestFlows Machine SDK Core is not installed."
95
+ f" Install it with the TestFlows Machine client {_INSTALLER}"
96
+ )
97
+
98
+
99
+ _loaded = _core()
100
+ _found = getattr(_loaded, "API_VERSION", None)
101
+ if _found not in CORE_API_VERSIONS:
102
+ raise ImportError(
103
+ f"The TestFlows Machine SDK Core has interface version {_found};"
104
+ f" this SDK needs {CORE_API_VERSIONS.start} to"
105
+ f" {CORE_API_VERSIONS.stop - 1}."
106
+ f" Update it with the TestFlows Machine client {_INSTALLER}"
107
+ )
108
+ _revision = getattr(_loaded, "API_REVISION", 1)
109
+ if _revision < CORE_API_REVISION:
110
+ raise ImportError(
111
+ "The TestFlows Machine SDK Core is older than this SDK."
112
+ f" Update it with the TestFlows Machine client {_INSTALLER}"
113
+ )