-
Notifications
You must be signed in to change notification settings - Fork 46
/
tasks.py
411 lines (337 loc) · 11.1 KB
/
tasks.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
"""
Tasks to run using Invoke.
Ref https://docs.pyinvoke.org/en/stable/index.html
Samples:
invoke lint
invoke coverage --html
invoke --list # list all tasks
invoke --help <cmd> # See docstrings and help notes
"""
import os
import sys
import subprocess
import threading
import time
from datetime import datetime
import requests
from invoke import task, Collection
from lute.config.app_config import AppConfig
@task
def lint(c):
"Run pylint on lute/ and tests/."
# Formats: https://pylint.pycqa.org/en/latest/user_guide/usage/output.html
msgfmt = [
"--ignore-patterns='zz_.*.py'",
"--msg-template='{path} ({line:03d}): {msg} ({msg_id} {symbol})'",
]
c.run(f"pylint {' '.join(msgfmt)} tasks.py lute/ tests/")
@task
def todos(c):
"""
Print code TODOs.
"""
c.run("python utils/todos.py")
@task(help={"port": "optional port to run on; default = 5001"})
def start(c, port=5001):
"""
Start the dev server, using script dev.py.
"""
c.run(f"python -m devstart --port {port}")
@task
def search(c, search_for):
"""
Search the code for a string.
"""
thisdir = os.path.dirname(os.path.realpath(__file__))
devscript = os.path.join(thisdir, "utils", "findstring.sh")
c.run(f'{devscript} "{search_for}"')
@task
def _ensure_test_db(c): # pylint: disable=unused-argument
"Quits if not a test db. (Hidden task)"
ac = AppConfig(AppConfig.default_config_filename())
if ac.is_test_db is False:
print(
f"""
QUITTING TASK FOR NON-TEST DB.
Your database name must start with test_ to run this task.
Your config.yml file has dbname = {ac.dbname}.
"""
)
sys.exit(1)
@task(pre=[_ensure_test_db])
def test(c):
"""
Unit tests only.
"""
c.run("pytest --ignore=./tests/acceptance")
def _site_is_running(useport=None):
"""
Return true if site is running on port, or default 5001.
"""
if useport is None:
useport = 5001
url = f"http://localhost:{useport}"
try:
print(f"checking for site at {url} ...")
resp = requests.get(url, timeout=5)
if resp.status_code != 200:
raise RuntimeError(f"Got code {resp.status_code} ... ???")
print("Site running, using that for tests.")
print()
return True
except requests.exceptions.ConnectionError:
print(f"URL {url} not reachable, will start new server at that port.")
print()
return False
def _wait_for_running_site(port):
"Wait until the site is running."
url = f"http://localhost:{port}"
is_running = False
attempt_count = 0
print(f"Wait until site is running at {url}.", flush=True)
while attempt_count < 10 and not is_running:
attempt_count += 1
try:
print(f" Attempt {attempt_count}", flush=True)
requests.get(url, timeout=5)
is_running = True
except requests.exceptions.ConnectionError:
time.sleep(1)
if not is_running:
raise Exception("Site didn't start?") # pylint: disable=broad-exception-raised
def _run_browser_tests(c, port, run_test):
"Start server on port if necessary, and run tests."
tests_failed = False
if _site_is_running(port):
c.run(" ".join(run_test))
else:
def print_subproc_output(pipe, label):
"""Prints output from a given pipe with a label."""
for line in iter(pipe.readline, b""):
print(f"[{label}] {line.decode().strip()}", flush=True)
pipe.close()
cmd = ["python", "-m", "tests.acceptance.start_acceptance_app", f"{port}"]
with subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
) as app_process:
_wait_for_running_site(port)
stdout_thread = threading.Thread(
target=print_subproc_output, args=(app_process.stdout, "STDOUT")
)
stderr_thread = threading.Thread(
target=print_subproc_output, args=(app_process.stderr, "STDERR")
)
stdout_thread.start()
stderr_thread.start()
try:
subprocess.run(run_test, check=True)
except subprocess.CalledProcessError:
# This just means a test failed. We don't need to see
# a stack trace, the assert failures are already displayed.
tests_failed = True
finally:
app_process.terminate()
stdout_thread.join()
stderr_thread.join()
if tests_failed:
raise RuntimeError("tests failed")
@task(
pre=[_ensure_test_db],
help={
"port": "optional port to run on; creates server if needed.",
"show": "print data",
"noheadless": "run as non-headless (default is headless, i.e. not shown)",
"kflag": "optional -k flag argument",
"exitfirst": "exit on first failure",
"verbose": "make verbose",
},
)
def accept( # pylint: disable=too-many-arguments
c,
port=5001,
show=False,
noheadless=False,
kflag=None,
exitfirst=False,
verbose=False,
):
"""
Start lute, run tests/acceptance tests, screenshot fails.
If no port specified, use default 5001.
If Lute's not running on specified port, start a server.
"""
run_test = [
"pytest",
"tests/acceptance",
"--splinter-screenshot-dir=tests/acceptance/failure_screenshots",
"--splinter-webdriver=chrome",
f"--port={port}",
]
if show:
run_test.append("-s")
if not noheadless:
run_test.append("--headless")
if kflag:
run_test.append("-k")
run_test.append(kflag)
if exitfirst:
run_test.append("--exitfirst")
if verbose:
run_test.append("-vv")
_run_browser_tests(c, 5001, run_test)
@task(pre=[_ensure_test_db])
def playwright(c):
"""
Start lute, run playwright tests. export SHOW=true env var to run non-headless.
Only uses port 5001.
If Lute's not running on specified port, start a server.
"""
run_test = ["pytest", "tests/playwright/playwright.py", "-s"]
_run_browser_tests(c, 5001, run_test)
@task(pre=[_ensure_test_db], help={"html": "open html report"})
def coverage(c, html=False):
"""
Run coverage (using non-acceptance tests only), open report if needed.
Running tests including the acceptance tests is slow,
and doesn't affect the coverage stats enough to justify it.
"""
c.run("coverage run -m pytest tests/")
if html:
c.run('coverage html --omit="tests/*"')
c.run("open htmlcov/index.html")
else:
cmd = 'coverage report --sort=cover --show-missing --omit="tests/*"'
c.run(cmd)
@task
def black(c):
"black-format things."
c.run("python -m black .")
@task(pre=[test, accept, playwright])
def fulltest(c): # pylint: disable=unused-argument
"""
Run full tests check.
"""
print("Done.")
@task(pre=[fulltest, black, lint])
def full(c): # pylint: disable=unused-argument
"""
Run full check and lint.
"""
print("Done.")
ns = Collection()
ns.add_task(fulltest)
ns.add_task(full)
ns.add_task(lint)
ns.add_task(test)
ns.add_task(accept)
ns.add_task(playwright)
ns.add_task(coverage)
ns.add_task(todos)
ns.add_task(start)
ns.add_task(search)
ns.add_task(black)
##############################
# DB tasks
@task(pre=[_ensure_test_db])
def db_wipe(c):
"""
Wipe the data from the testing db; factory reset settings. :-)
Can only be run on a testing db.
"""
c.run("pytest -m dbwipe")
print("ok")
@task(pre=[_ensure_test_db])
def db_reset(c):
"""
Reset the database to the demo data.
Can only be run on a testing db.
"""
c.run("pytest -m dbdemoload")
print("ok")
def _schema_dir():
"Return full path to schema dir."
thisdir = os.path.dirname(os.path.realpath(__file__))
return os.path.join(thisdir, "lute", "db", "schema")
def _do_schema_export(c, destfile, header_notes, taskname):
"""
Generate the dumpfile at destfile.
"""
destfile = os.path.join(_schema_dir(), destfile)
tempfile = f"{destfile}.temp"
commands = f"""
echo "-- ------------------------------------------" > {tempfile}
echo "-- {header_notes}" >> {tempfile}
echo "-- Migrations tracked in _migrations, settings reset." >> {tempfile}
echo "-- Generated from 'inv {taskname}'" >> {tempfile}
echo "-- ------------------------------------------" >> {tempfile}
echo "" >> {tempfile}
sqlite3 data/test_lute.db .dump >> {tempfile}
"""
c.run(commands)
os.rename(tempfile, destfile)
print(f"{destfile} updated (git diff follows):")
print("DIFF START " + "-" * 38)
# -U0 = no context before or after changes.
c.run(f"git diff -U0 -- {destfile}")
print("DIFF END " + "-" * 40)
print()
@task
def db_export_baseline(c):
"""
Reset the db, and create a new baseline db file from the current db.
"""
# Running the delete task before this one as a pre- step was
# causing problems (sqlite file not in correct state), so this
# asks the user to verify.
text = input("Have you reset the db? (y/n): ")
if text != "y":
print("quitting.")
return
_do_schema_export(
c, "baseline.sql", "Baseline db with demo data.", "db.export.baseline"
)
fname = os.path.join(_schema_dir(), "baseline.sql")
print(f"Verifying {fname}")
with open(fname, "r", encoding="utf-8") as f:
checkstring = "Tutorial follow-up"
if checkstring in f.read():
print(f'"{checkstring}" found, likely ok.')
else:
print(f'"{checkstring}" NOT FOUND, SOMETHING LIKELY WRONG.')
raise RuntimeError(f'Missing "{checkstring}" in exported file.')
@task
def db_export_empty(c):
"""
Create a new empty db file from the current db.
This assumes that the current db is in data/test_lute.db.
"""
# Running the delete task before this one as a pre- step was
# causing problems (sqlite file not in correct state), so this
# asks the user to verify.
text = input("Have you **WIPED** the db? (y/n): ")
if text != "y":
print("quitting.")
return
_do_schema_export(c, "empty.sql", "EMPTY DB.", "db.export.empty")
@task(help={"suffix": "suffix to add to filename."})
def db_newscript(c, suffix): # pylint: disable=unused-argument
"""
Create a new migration, <datetime>_suffix.sql
"""
now = datetime.now()
fnow = now.strftime("%Y%m%d")
filename = f"{fnow}_{suffix}.sql"
destfile = os.path.join(_schema_dir(), "migrations", filename)
with open(destfile, "w", encoding="utf-8") as f:
f.write("-- TODO - fill this in.")
print("migration created:")
print(destfile)
dbtasks = Collection("db")
dbtasks.add_task(db_reset, "reset")
dbtasks.add_task(db_wipe, "wipe")
dbtasks.add_task(db_newscript, "newscript")
dbexport = Collection("export")
dbexport.add_task(db_export_baseline, "baseline")
dbexport.add_task(db_export_empty, "empty")
dbtasks.add_collection(dbexport)
ns.add_collection(dbtasks)