pyathy 0.1.22__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.
- pyathy/__init__.py +1 -0
- pyathy/_boot.py +336 -0
- pyathy/check.py +224 -0
- pyathy/cli.py +535 -0
- pyathy/help.py +315 -0
- pyathy/lastrun.py +93 -0
- pyathy/lock.py +435 -0
- pyathy/program.py +562 -0
- pyathy/steps.py +902 -0
- pyathy-0.1.22.dist-info/METADATA +318 -0
- pyathy-0.1.22.dist-info/RECORD +14 -0
- pyathy-0.1.22.dist-info/WHEEL +4 -0
- pyathy-0.1.22.dist-info/entry_points.txt +2 -0
- pyathy-0.1.22.dist-info/licenses/LICENSE +21 -0
pyathy/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.22"
|
pyathy/_boot.py
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
"""Runs INSIDE the child process: starts the student's game with its input and randomness scripted.
|
|
2
|
+
|
|
3
|
+
You never run or import this file yourself: harness/scripted_game.py starts it as
|
|
4
|
+
|
|
5
|
+
python _game_boot.py <main.py> [args...]
|
|
6
|
+
|
|
7
|
+
with the environment variables SCRIPTED_GAME_ADDRESS, SCRIPTED_GAME_KEY and
|
|
8
|
+
SCRIPTED_GAME_SIDES set. Before the student's code loads it:
|
|
9
|
+
|
|
10
|
+
- connects to the test over multiprocessing.connection (a Unix socket on Linux/macOS,
|
|
11
|
+
a named pipe on Windows; no TCP port, no firewall prompt);
|
|
12
|
+
- replaces input() and sys.stdin (readline, read, readlines, iteration) with a call that
|
|
13
|
+
asks the test what to type and BLOCKS until the test answers;
|
|
14
|
+
- replaces the random calls a game draws with (randint, randrange, choice, choices,
|
|
15
|
+
random, uniform, sample, shuffle), on the random module AND on every random.Random /
|
|
16
|
+
SystemRandom instance, plus secrets.randbelow / secrets.choice. Each call asks the test
|
|
17
|
+
what it returns: a face for a die (exactly SIDES consecutive integers: randint(1, 6),
|
|
18
|
+
randrange(6)), or an exact value for anything else (choice(string.ascii_letters) -> "q");
|
|
19
|
+
- makes time.sleep return at once, telling the test how long it was asked to wait;
|
|
20
|
+
- replaces sys.stdout / sys.stderr with a writer that sends every write to the test as
|
|
21
|
+
it happens, so buffering never reorders anything, and os.system("clear") (which
|
|
22
|
+
writes to the real terminal, not to sys.stdout) cannot get mixed in;
|
|
23
|
+
- then runs the game like `python main.py` would: __name__ == "__main__", sys.argv set,
|
|
24
|
+
the game folder first on sys.path.
|
|
25
|
+
|
|
26
|
+
When the test is done it answers a waiting call with "stop", and this process ends with
|
|
27
|
+
os._exit(0) from inside that call, so no try/except in the student's code can catch it.
|
|
28
|
+
|
|
29
|
+
Stdlib only, Python 3.9+ (tested on 3.9, 3.10 and 3.14).
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
import builtins
|
|
33
|
+
import os
|
|
34
|
+
import random
|
|
35
|
+
import runpy
|
|
36
|
+
import sys
|
|
37
|
+
import threading
|
|
38
|
+
import traceback
|
|
39
|
+
from multiprocessing.connection import Client
|
|
40
|
+
|
|
41
|
+
APP = os.path.abspath(sys.argv[1])
|
|
42
|
+
FOLDER = os.path.dirname(APP)
|
|
43
|
+
SIDES = int(os.environ.get("SCRIPTED_GAME_SIDES", "6"))
|
|
44
|
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
45
|
+
|
|
46
|
+
conn = Client(os.environ["SCRIPTED_GAME_ADDRESS"], authkey=bytes.fromhex(os.environ["SCRIPTED_GAME_KEY"]))
|
|
47
|
+
send_lock = threading.Lock() # one message at a time on the wire
|
|
48
|
+
request_lock = threading.Lock() # one question (input or die) waiting for its answer at a time
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def send(message):
|
|
52
|
+
"""The test hung up (it is done with this game): end here, so nothing can catch it."""
|
|
53
|
+
with send_lock:
|
|
54
|
+
try:
|
|
55
|
+
conn.send(message)
|
|
56
|
+
except OSError:
|
|
57
|
+
os._exit(0)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def ask(message):
|
|
61
|
+
"""Send a request and block until the test answers. "stop" ends the process right here."""
|
|
62
|
+
with request_lock:
|
|
63
|
+
try:
|
|
64
|
+
send(message)
|
|
65
|
+
reply = conn.recv()
|
|
66
|
+
except (EOFError, OSError):
|
|
67
|
+
os._exit(0)
|
|
68
|
+
if reply[0] == "stop":
|
|
69
|
+
os._exit(0)
|
|
70
|
+
return reply
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
# ---- output -----------------------------------------------------------------
|
|
74
|
+
|
|
75
|
+
class Writer:
|
|
76
|
+
"""sys.stdout / sys.stderr: every write goes to the test at once."""
|
|
77
|
+
|
|
78
|
+
encoding = "utf-8"
|
|
79
|
+
errors = "replace"
|
|
80
|
+
|
|
81
|
+
def __init__(self, name):
|
|
82
|
+
self.name = name
|
|
83
|
+
|
|
84
|
+
def write(self, text):
|
|
85
|
+
text = str(text)
|
|
86
|
+
if text:
|
|
87
|
+
send(("out", text))
|
|
88
|
+
return len(text)
|
|
89
|
+
|
|
90
|
+
def writelines(self, lines):
|
|
91
|
+
for line in lines:
|
|
92
|
+
self.write(line)
|
|
93
|
+
|
|
94
|
+
def flush(self):
|
|
95
|
+
pass
|
|
96
|
+
|
|
97
|
+
def isatty(self):
|
|
98
|
+
return False
|
|
99
|
+
|
|
100
|
+
def fileno(self):
|
|
101
|
+
raise OSError("scripted output has no file descriptor")
|
|
102
|
+
|
|
103
|
+
def readable(self):
|
|
104
|
+
return False
|
|
105
|
+
|
|
106
|
+
def writable(self):
|
|
107
|
+
return True
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# ---- input ------------------------------------------------------------------
|
|
111
|
+
|
|
112
|
+
def typed(prompt, how):
|
|
113
|
+
reply = ask(("input", prompt, how))
|
|
114
|
+
return reply[1]
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def fake_input(prompt=""):
|
|
118
|
+
return typed(str(prompt), "input()")
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class Stdin:
|
|
122
|
+
"""sys.stdin: every line read is one question to the test."""
|
|
123
|
+
|
|
124
|
+
encoding = "utf-8"
|
|
125
|
+
errors = "replace"
|
|
126
|
+
|
|
127
|
+
def readline(self, size=-1):
|
|
128
|
+
return typed("", "sys.stdin.readline()") + "\n"
|
|
129
|
+
|
|
130
|
+
def read(self, size=-1):
|
|
131
|
+
return typed("", "sys.stdin.read()") + "\n"
|
|
132
|
+
|
|
133
|
+
def readlines(self, hint=-1):
|
|
134
|
+
return [self.readline()]
|
|
135
|
+
|
|
136
|
+
def __iter__(self):
|
|
137
|
+
return self
|
|
138
|
+
|
|
139
|
+
def __next__(self):
|
|
140
|
+
return self.readline()
|
|
141
|
+
|
|
142
|
+
def isatty(self):
|
|
143
|
+
return False
|
|
144
|
+
|
|
145
|
+
def readable(self):
|
|
146
|
+
return True
|
|
147
|
+
|
|
148
|
+
def fileno(self):
|
|
149
|
+
raise OSError("scripted input has no file descriptor")
|
|
150
|
+
|
|
151
|
+
def close(self):
|
|
152
|
+
pass
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
# ---- randomness ---------------------------------------------------------------
|
|
156
|
+
#
|
|
157
|
+
# Every random call asks the test: ("random", description, is_die, menu, kind).
|
|
158
|
+
# menu: the options as a range, or as a list of their repr()s (None when there are too many)
|
|
159
|
+
# kind: "pick" (one of the options), "float", "shuffle" or "sample"
|
|
160
|
+
# The test answers ("face", n): the n-th smallest option of a die; ("value", v): exactly v;
|
|
161
|
+
# ("index", i): options[i], in the program's own order;
|
|
162
|
+
# or ("first",): the first option (a suite that lets unscripted randomness through).
|
|
163
|
+
|
|
164
|
+
def is_die(options):
|
|
165
|
+
"""Exactly SIDES consecutive integers, in any order."""
|
|
166
|
+
if len(options) != SIDES:
|
|
167
|
+
return False
|
|
168
|
+
options = list(options)
|
|
169
|
+
if not all(type(o) is int for o in options):
|
|
170
|
+
return False
|
|
171
|
+
low = min(options)
|
|
172
|
+
return sorted(options) == list(range(low, low + SIDES))
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def menu(options):
|
|
176
|
+
if isinstance(options, range):
|
|
177
|
+
return options
|
|
178
|
+
return [repr(o) for o in options] if len(options) <= 500 else None
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def over(options):
|
|
182
|
+
"""'52 letters', "['Ann', 'Bob']", '30 items'."""
|
|
183
|
+
if isinstance(options, str) or all(isinstance(o, str) and len(o) == 1 for o in options):
|
|
184
|
+
letters = all(str(o).isalpha() for o in options)
|
|
185
|
+
return f"{len(options)} {'letters' if letters else 'characters'}"
|
|
186
|
+
if len(options) <= 6:
|
|
187
|
+
return repr(list(options))
|
|
188
|
+
return f"{len(options)} items"
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def describe(name, args, options=None):
|
|
192
|
+
if name in ("choice", "choices", "shuffle", "sample") and options is not None:
|
|
193
|
+
return f"random.{name} over {over(options)}"
|
|
194
|
+
return f"random.{name}({', '.join(repr(a) for a in args)})"
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def matching(options, value):
|
|
198
|
+
"""The option equal to `value` (so a scripted 3 returns the student's own object), else value."""
|
|
199
|
+
if not isinstance(options, range):
|
|
200
|
+
for option in options:
|
|
201
|
+
if option == value:
|
|
202
|
+
return option
|
|
203
|
+
return value
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def draw(name, args, options):
|
|
207
|
+
"""One random pick from `options`, as the test scripts it."""
|
|
208
|
+
if not isinstance(options, range):
|
|
209
|
+
options = list(options)
|
|
210
|
+
if not options:
|
|
211
|
+
raise IndexError("cannot choose from an empty sequence")
|
|
212
|
+
reply = ask(("random", describe(name, args, options), is_die(options), menu(options), "pick"))
|
|
213
|
+
if reply[0] == "face":
|
|
214
|
+
return sorted(options)[reply[1] - 1]
|
|
215
|
+
if reply[0] == "index": # the n-th option in the program's own order (0-based)
|
|
216
|
+
return options[reply[1]]
|
|
217
|
+
if reply[0] == "value":
|
|
218
|
+
return matching(options, reply[1])
|
|
219
|
+
return options[0]
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def p_randint(self, a, b):
|
|
223
|
+
return draw("randint", (a, b), range(a, b + 1))
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def p_randrange(self, start, stop=None, step=1):
|
|
227
|
+
args = (start,) if stop is None else (start, stop) if step == 1 else (start, stop, step)
|
|
228
|
+
choices = range(start) if stop is None else range(start, stop, step)
|
|
229
|
+
if not choices:
|
|
230
|
+
raise ValueError(f"empty range for randrange{args}")
|
|
231
|
+
return draw("randrange", args, choices)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def p_choice(self, seq):
|
|
235
|
+
return draw("choice", (seq,), seq)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def p_choices(self, population, weights=None, *, cum_weights=None, k=1):
|
|
239
|
+
population = list(population)
|
|
240
|
+
return [draw("choices", (population,), population) for _ in range(k)]
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def p_random(self):
|
|
244
|
+
reply = ask(("random", "random.random()", False, None, "float"))
|
|
245
|
+
return float(reply[1]) if reply[0] == "value" else 0.0
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def p_uniform(self, a, b):
|
|
249
|
+
reply = ask(("random", describe("uniform", (a, b)), False, None, "float"))
|
|
250
|
+
return float(reply[1]) if reply[0] == "value" else a
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def p_sample(self, population, k, *, counts=None):
|
|
254
|
+
population = list(population)
|
|
255
|
+
reply = ask(("random", describe("sample", (population, k), population), False, menu(population), "sample"))
|
|
256
|
+
if reply[0] == "value":
|
|
257
|
+
return [matching(population, v) for v in reply[1]]
|
|
258
|
+
return population[:k]
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def p_shuffle(self, x):
|
|
262
|
+
reply = ask(("random", describe("shuffle", (x,), x), False, menu(x), "shuffle"))
|
|
263
|
+
if reply[0] == "value":
|
|
264
|
+
x[:] = [matching(list(x), v) for v in reply[1]]
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
PATCHES = {
|
|
268
|
+
"randint": p_randint, "randrange": p_randrange, "choice": p_choice, "choices": p_choices,
|
|
269
|
+
"random": p_random, "uniform": p_uniform, "sample": p_sample, "shuffle": p_shuffle,
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def patch_random():
|
|
274
|
+
for cls in (random.Random, random.SystemRandom):
|
|
275
|
+
for name, fn in PATCHES.items():
|
|
276
|
+
setattr(cls, name, fn)
|
|
277
|
+
for name in PATCHES: # the module functions are bound methods of one hidden instance
|
|
278
|
+
setattr(random, name, getattr(random._inst, name))
|
|
279
|
+
import secrets
|
|
280
|
+
|
|
281
|
+
secrets.randbelow = lambda n: draw("randbelow", (n,), range(n))
|
|
282
|
+
secrets.choice = lambda seq: draw("choice", (seq,), seq)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def patch_sleep():
|
|
286
|
+
"""time.sleep returns at once (a countdown can't eat the step timeout); the test sees how long."""
|
|
287
|
+
import time
|
|
288
|
+
|
|
289
|
+
time.sleep = lambda seconds: send(("sleep", seconds))
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
# ---- run the game -----------------------------------------------------------
|
|
293
|
+
|
|
294
|
+
def student_traceback(error):
|
|
295
|
+
"""The traceback through the student's own files only, paths relative to the game folder."""
|
|
296
|
+
lines = ["Traceback (most recent call last):\n"]
|
|
297
|
+
for frame in traceback.extract_tb(error.__traceback__):
|
|
298
|
+
path = os.path.abspath(frame.filename)
|
|
299
|
+
if not frame.filename.startswith("<") and path.startswith(FOLDER + os.sep):
|
|
300
|
+
rel = os.path.relpath(path, FOLDER)
|
|
301
|
+
lines.append(f' File "{rel}", line {frame.lineno}, in {frame.name}\n')
|
|
302
|
+
if frame.line:
|
|
303
|
+
lines.append(f" {frame.line.strip()}\n")
|
|
304
|
+
lines += traceback.format_exception_only(type(error), error)
|
|
305
|
+
return "".join(lines)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def main():
|
|
309
|
+
patch_random()
|
|
310
|
+
patch_sleep()
|
|
311
|
+
builtins.input = fake_input
|
|
312
|
+
sys.stdin = sys.__stdin__ = Stdin()
|
|
313
|
+
sys.stdout = Writer("stdout")
|
|
314
|
+
sys.stderr = Writer("stderr")
|
|
315
|
+
sys.argv = [APP, *sys.argv[2:]]
|
|
316
|
+
sys.path[:] = [FOLDER] + [p for p in sys.path if os.path.abspath(p or ".") not in (HERE, FOLDER)]
|
|
317
|
+
os.chdir(FOLDER)
|
|
318
|
+
code = 0
|
|
319
|
+
try:
|
|
320
|
+
runpy.run_path(APP, run_name="__main__")
|
|
321
|
+
except SystemExit as stop:
|
|
322
|
+
if stop.code is None:
|
|
323
|
+
code = 0
|
|
324
|
+
elif isinstance(stop.code, int):
|
|
325
|
+
code = stop.code
|
|
326
|
+
else:
|
|
327
|
+
sys.stderr.write(f"{stop.code}\n")
|
|
328
|
+
code = 1
|
|
329
|
+
except BaseException as error: # noqa: BLE001 - report every crash to the test
|
|
330
|
+
send(("crash", student_traceback(error)))
|
|
331
|
+
os._exit(1)
|
|
332
|
+
send(("exit", code))
|
|
333
|
+
os._exit(0)
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
main()
|
pyathy/check.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""`pyathy check`: read the feature files without running the program, and list what would
|
|
2
|
+
stop a scenario before it starts: a line no step matches (with the closest step), a file that
|
|
3
|
+
is not valid Gherkin, indentation that differs from the rest of the file, and a file step whose
|
|
4
|
+
file pyathy cannot find in the program.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import pathlib
|
|
10
|
+
import re
|
|
11
|
+
from collections import Counter
|
|
12
|
+
|
|
13
|
+
from pytest_bdd.exceptions import GherkinParseError
|
|
14
|
+
from pytest_bdd.feature import get_feature
|
|
15
|
+
from pytest_bdd.parser import render_string
|
|
16
|
+
|
|
17
|
+
from . import __version__
|
|
18
|
+
from .help import STEPS, Styler, suggest
|
|
19
|
+
from .program import ProgramError, constant, save_file
|
|
20
|
+
|
|
21
|
+
STEP_LINE = re.compile(r"^(\s*)(Given|When|Then|And|But|\*)(\s+)(.*?)\s*$")
|
|
22
|
+
BLOCK_LINE = re.compile(r"^(\s*)(Scenario Outline|Scenario Template|Scenario|Example|Background|Rule):")
|
|
23
|
+
SAVED_GAME = re.compile(r"(?:a saved game:?|there is no saved game|the saved game holds:?|"
|
|
24
|
+
r"a saved game is written|no saved game is left)", re.IGNORECASE)
|
|
25
|
+
CONSTANT = re.compile(r'^(?:a file|there is no file|the file) ([A-Z][A-Z0-9_]*)\b')
|
|
26
|
+
OTHER_PROGRAM = re.compile(r"^the program ([\w./-]+\.py)$")
|
|
27
|
+
GHERKIN_HINT = "note: each line of a scenario starts with Given, When, Then, And or But (or # for a comment)"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Problem:
|
|
31
|
+
"""One thing found at one line of one file: `message` is what the report prints under it;
|
|
32
|
+
`start`/`end` (0-based columns) mark the step text and `suggestion` replaces it, for an editor."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, path, line, message, kind, start=0, end=0, suggestion=None):
|
|
35
|
+
self.path, self.line, self.message, self.kind = path, line, message, kind
|
|
36
|
+
self.start, self.end, self.suggestion = start, end, suggestion
|
|
37
|
+
|
|
38
|
+
def as_dict(self):
|
|
39
|
+
return {"file": self.path, "line": self.line, "start": self.start, "end": self.end,
|
|
40
|
+
"kind": self.kind, "message": self.message, "suggestion": self.suggestion}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def feature_files(targets):
|
|
44
|
+
"""The .feature files the targets name (a file, or every one in a folder), and the targets
|
|
45
|
+
that are neither."""
|
|
46
|
+
files, missing = [], []
|
|
47
|
+
for target in targets:
|
|
48
|
+
if os.path.isdir(target):
|
|
49
|
+
files += sorted(str(p) for p in pathlib.Path(target).rglob("*.feature"))
|
|
50
|
+
elif os.path.isfile(target):
|
|
51
|
+
files.append(target)
|
|
52
|
+
else:
|
|
53
|
+
missing.append(target)
|
|
54
|
+
return files, missing
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def own_patterns(folder):
|
|
58
|
+
"""The step patterns of every *steps.py next to the feature files of `folder`, loaded once."""
|
|
59
|
+
from . import steps
|
|
60
|
+
|
|
61
|
+
loaded = {file for _, file, _, _ in steps.REGISTERED}
|
|
62
|
+
for path in sorted(pathlib.Path(folder).glob("*steps.py")):
|
|
63
|
+
if str(path) not in loaded:
|
|
64
|
+
steps.load_own_steps(path)
|
|
65
|
+
return [pattern for pattern, file, _, _ in steps.REGISTERED if file != steps.__file__]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def matches(text):
|
|
69
|
+
from . import steps
|
|
70
|
+
|
|
71
|
+
return any(parser.is_matching(text) for _, _, parser, _ in steps.REGISTERED)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def check_file(path, app):
|
|
75
|
+
"""The problems of one feature file, in line order."""
|
|
76
|
+
rel = os.path.relpath(path)
|
|
77
|
+
with open(path, encoding="utf-8", errors="replace") as f:
|
|
78
|
+
lines = f.read().splitlines()
|
|
79
|
+
problems = indentation(rel, lines)
|
|
80
|
+
try:
|
|
81
|
+
feature = get_feature(os.path.dirname(os.path.abspath(path)), os.path.basename(path))
|
|
82
|
+
except GherkinParseError as e:
|
|
83
|
+
raw = lines[e.line - 1] if 0 < e.line <= len(lines) else ""
|
|
84
|
+
hint = "" if STEP_LINE.match(raw) or BLOCK_LINE.match(raw) else f"\n{GHERKIN_HINT}"
|
|
85
|
+
problems.append(Problem(rel, e.line, f"not valid Gherkin: {e.message}\n {raw.strip()}{hint}", "gherkin",
|
|
86
|
+
len(raw) - len(raw.lstrip()), len(raw)))
|
|
87
|
+
return sorted(problems, key=lambda p: p.line)
|
|
88
|
+
except Exception as e: # noqa: BLE001 - anything else the parser trips on
|
|
89
|
+
problems.append(Problem(rel, 1, f"not valid Gherkin: {e}", "gherkin"))
|
|
90
|
+
return problems
|
|
91
|
+
try:
|
|
92
|
+
own = own_patterns(os.path.dirname(os.path.abspath(path)))
|
|
93
|
+
except Exception as e: # noqa: BLE001 - a broken steps file is reported, not fatal
|
|
94
|
+
problems.append(Problem(rel, 1, f"could not load the steps next to it: {type(e).__name__}: {e}", "steps"))
|
|
95
|
+
own = []
|
|
96
|
+
seen = set()
|
|
97
|
+
for scenario in feature.scenarios.values():
|
|
98
|
+
contexts = [c for examples in scenario.examples for c in examples.as_contexts()] or [{}]
|
|
99
|
+
for step in scenario.steps:
|
|
100
|
+
if step.line_number in seen:
|
|
101
|
+
continue
|
|
102
|
+
for context in contexts:
|
|
103
|
+
text = render_string(step.name, context) if context else step.name
|
|
104
|
+
problem = step_problem(rel, lines, step, text, own, app)
|
|
105
|
+
if problem is not None:
|
|
106
|
+
seen.add(step.line_number)
|
|
107
|
+
problems.append(problem)
|
|
108
|
+
break
|
|
109
|
+
return sorted(problems, key=lambda p: p.line)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def step_problem(rel, lines, step, text, own, app):
|
|
113
|
+
"""None when `text` (a step's line, its outline values filled in) matches a step and names a
|
|
114
|
+
file the program has; else what is wrong with it."""
|
|
115
|
+
raw = lines[step.line_number - 1] if step.line_number <= len(lines) else ""
|
|
116
|
+
m = STEP_LINE.match(raw)
|
|
117
|
+
start = m.end(3) if m else 0
|
|
118
|
+
end = m.end(4) if m else len(raw)
|
|
119
|
+
if not matches(text):
|
|
120
|
+
closest = suggest(step.name, own)
|
|
121
|
+
hint = f"did you mean: {closest}" if closest else "run pyathy steps for the list"
|
|
122
|
+
return Problem(rel, step.line_number, f"pyathy has no step that matches\n {step.keyword} {step.name}\n{hint}",
|
|
123
|
+
"step", start, end, closest)
|
|
124
|
+
if not os.path.isfile(app): # no program yet: nothing to look the files up in
|
|
125
|
+
return None
|
|
126
|
+
try:
|
|
127
|
+
if SAVED_GAME.fullmatch(text.strip()):
|
|
128
|
+
save_file(app)
|
|
129
|
+
elif cm := CONSTANT.match(text):
|
|
130
|
+
constant(app, cm.group(1))
|
|
131
|
+
elif om := OTHER_PROGRAM.match(text):
|
|
132
|
+
other = os.path.join(os.path.dirname(app), om.group(1))
|
|
133
|
+
if not os.path.isfile(other):
|
|
134
|
+
raise ProgramError(f"there is no {om.group(1)} in this folder")
|
|
135
|
+
except ProgramError as e:
|
|
136
|
+
return Problem(rel, step.line_number, f"pyathy cannot find the file this step needs\n"
|
|
137
|
+
f" {step.keyword} {step.name}\n{e}", "file", start, end)
|
|
138
|
+
return None
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def indentation(rel, lines):
|
|
142
|
+
"""A tab in the indentation, or a scenario or step indented differently from most of its
|
|
143
|
+
kind in the file (lines inside \"\"\" blocks, tables and comments are left alone)."""
|
|
144
|
+
problems, kinds, inside = [], {"scenario": [], "step": []}, False
|
|
145
|
+
for number, line in enumerate(lines, 1):
|
|
146
|
+
stripped = line.strip()
|
|
147
|
+
if stripped.startswith(('"""', "```")):
|
|
148
|
+
inside = not inside
|
|
149
|
+
continue
|
|
150
|
+
if inside or not stripped or stripped.startswith(("#", "|")):
|
|
151
|
+
continue
|
|
152
|
+
lead = line[:len(line) - len(line.lstrip())]
|
|
153
|
+
if "\t" in lead:
|
|
154
|
+
problems.append(Problem(rel, number, "indented with a tab: use spaces", "indent", 0, len(lead)))
|
|
155
|
+
continue
|
|
156
|
+
if BLOCK_LINE.match(line):
|
|
157
|
+
kinds["scenario"].append((number, len(lead)))
|
|
158
|
+
elif STEP_LINE.match(line):
|
|
159
|
+
kinds["step"].append((number, len(lead)))
|
|
160
|
+
if "Rule:" in "\n".join(lines): # scenarios under a Rule sit deeper on purpose
|
|
161
|
+
return problems
|
|
162
|
+
names = {"scenario": "scenarios", "step": "steps"}
|
|
163
|
+
for kind, found in kinds.items():
|
|
164
|
+
if not found:
|
|
165
|
+
continue
|
|
166
|
+
usual = Counter(indent for _, indent in found).most_common(1)[0][0]
|
|
167
|
+
for number, indent in found:
|
|
168
|
+
if indent != usual:
|
|
169
|
+
problems.append(Problem(rel, number, f"indented {plural(indent, 'space')}, the other "
|
|
170
|
+
f"{names[kind]} {usual}", "indent", 0, indent, " " * usual))
|
|
171
|
+
return problems
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def plural(n, noun):
|
|
175
|
+
return f"{n} {noun}" if n == 1 else f"{n} {noun}s"
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def step_list(own):
|
|
179
|
+
"""The steps an editor offers while typing: the built-ins as `pyathy steps` writes them
|
|
180
|
+
({4} a value to replace), then the folder's own patterns."""
|
|
181
|
+
out = [{"step": step, "doc": " ".join(doc.splitlines()), "own": False}
|
|
182
|
+
for entries in STEPS.values() for step, doc in entries]
|
|
183
|
+
return out + [{"step": pattern, "doc": "", "own": True} for pattern in own]
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def run(args):
|
|
187
|
+
"""`pyathy check [--json] [targets]`: 0 when nothing is found, 1 when something is, 2 when a
|
|
188
|
+
target does not exist or has no feature files."""
|
|
189
|
+
from .cli import Report, title_line
|
|
190
|
+
|
|
191
|
+
as_json = "--json" in args
|
|
192
|
+
targets = [a for a in args if a != "--json"] or ["features"]
|
|
193
|
+
files, missing = feature_files(targets)
|
|
194
|
+
app = os.path.abspath(os.environ.get("PYATHY_APP", "main.py"))
|
|
195
|
+
if missing or not files:
|
|
196
|
+
problem = (f"no such file or folder: {missing[0]}" if missing
|
|
197
|
+
else f"no .feature files in {', '.join(targets)}")
|
|
198
|
+
if as_json:
|
|
199
|
+
print(json.dumps({"version": __version__, "error": problem, "problems": [], "steps": step_list([])}))
|
|
200
|
+
else:
|
|
201
|
+
print(f"pyathy: {problem}")
|
|
202
|
+
return 2
|
|
203
|
+
results = [(path, check_file(path, app)) for path in files]
|
|
204
|
+
if as_json:
|
|
205
|
+
own = sorted({p for path in files for p in own_patterns(os.path.dirname(os.path.abspath(path)))})
|
|
206
|
+
print(json.dumps({"version": __version__,
|
|
207
|
+
"problems": [p.as_dict() for _, found in results for p in found],
|
|
208
|
+
"steps": step_list(own)}, ensure_ascii=False))
|
|
209
|
+
return 1 if any(found for _, found in results) else 0
|
|
210
|
+
report = Report()
|
|
211
|
+
styler = Styler()
|
|
212
|
+
count = 0
|
|
213
|
+
for path, found in results:
|
|
214
|
+
mark = styler.style(31, "✘") if found else styler.style(32, "✔")
|
|
215
|
+
print(f"{mark} {os.path.relpath(path)}")
|
|
216
|
+
for i, problem in enumerate(found):
|
|
217
|
+
count += 1
|
|
218
|
+
print(("\n" if i else "") + report.reason(f"line {problem.line}: {problem.message}"))
|
|
219
|
+
bad = sum(1 for _, found in results if found)
|
|
220
|
+
summary = (f"{plural(count, 'problem')} in {bad} of {plural(len(files), 'file')}" if count
|
|
221
|
+
else f"no problems in {plural(len(files), 'file')}")
|
|
222
|
+
print(f"\n{styler.style(1, summary)}")
|
|
223
|
+
print(title_line(styler))
|
|
224
|
+
return 1 if count else 0
|