-
Notifications
You must be signed in to change notification settings - Fork 130
/
Copy pathtest.py
424 lines (349 loc) · 12.3 KB
/
test.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
412
413
414
415
416
417
418
419
420
421
422
423
424
import logging
import os
import subprocess
import sys
import tempfile
import time
import json
from itertools import chain
from pathlib import Path
from utils import Plugin, configure_git, enumerate_plugins
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
global_dependencies = [
"pytest",
"pytest-xdist",
"pytest-timeout",
"poetry-plugin-export",
]
pip_opts = ["-qq"]
def prepare_env(p: Plugin, directory: Path, env: dict, workflow: str) -> bool:
"""Returns whether we can run at all. Raises error if preparing failed."""
subprocess.check_call(["python3", "-m", "venv", "--clear", directory])
os.environ["PATH"] += f":{directory}"
if p.framework == "pip":
return prepare_env_pip(p, directory, workflow)
elif p.framework == "poetry":
return prepare_env_poetry(p, directory, workflow)
elif p.framework == "generic":
return prepare_generic(p, directory, env, workflow)
else:
raise ValueError(f"Unknown framework {p.framework}")
def prepare_env_poetry(p: Plugin, directory: Path, workflow: str) -> bool:
logging.info("Installing a new poetry virtualenv")
pip3 = directory / "bin" / "pip3"
poetry = directory / "bin" / "poetry"
python3 = directory / "bin" / "python3"
subprocess.check_call(["which", "python3"])
subprocess.check_call(
[pip3, "install", "-U", *pip_opts, "pip", "wheel", "poetry"], cwd=p.path.parent
)
# Install pytest (eventually we'd want plugin authors to include
# it in their requirements-dev.txt, but for now let's help them a
# bit).
subprocess.check_call(
[pip3, "install", "-U", "-qq", *global_dependencies],
stderr=subprocess.STDOUT,
)
# We run all commands in the plugin directory so poetry remembers its settings
workdir = p.path.resolve()
logging.info(f"Using poetry at {poetry} ({python3}) to run tests in {workdir}")
# Now we can proceed with the actual implementation
logging.info(
f"Exporting poetry {poetry} dependencies from {p.details['pyproject']}"
)
subprocess.check_call(
[
poetry,
"export",
"--with=dev",
"--without-hashes",
"-f",
"requirements.txt",
"--output",
"requirements.txt",
],
cwd=workdir,
)
subprocess.check_call(
[
pip3,
"install",
*pip_opts,
"-r",
str(workdir) + "/requirements.txt",
],
stderr=subprocess.STDOUT,
)
if workflow == "nightly":
install_dev_pyln_testing(pip3)
else:
install_pyln_testing(pip3)
subprocess.check_call([pip3, "freeze"])
return True
def prepare_env_pip(p: Plugin, directory: Path, workflow: str) -> bool:
print("Installing a new pip virtualenv")
pip_path = directory / "bin" / "pip3"
# Now install all the requirements
print(f"Installing requirements from {p.details['requirements']}")
subprocess.check_call(
[pip_path, "install", *pip_opts, "-r", p.details["requirements"]],
stderr=subprocess.STDOUT,
)
if p.details["devrequirements"].exists():
print(f"Installing requirements from {p.details['devrequirements']}")
subprocess.check_call(
[pip_path, "install", *pip_opts, "-r", p.details["devrequirements"]],
stderr=subprocess.STDOUT,
)
if workflow == "nightly":
install_dev_pyln_testing(pip_path)
else:
install_pyln_testing(pip_path)
subprocess.check_call([pip_path, "freeze"])
return True
def prepare_generic(p: Plugin, directory: Path, env: dict, workflow: str) -> bool:
print("Installing a new generic virtualenv")
pip_path = directory / "bin" / "pip3"
# Now install all the requirements
if p.details["requirements"].exists():
print(f"Installing requirements from {p.details['requirements']}")
subprocess.check_call(
[pip_path, "install", *pip_opts, "-r", p.details["requirements"]],
stderr=subprocess.STDOUT,
)
if workflow == "nightly":
install_dev_pyln_testing(pip_path)
else:
install_pyln_testing(pip_path)
if p.details["setup"].exists():
print(f"Running setup script from {p.details['setup']}")
subprocess.check_call(
["bash", p.details["setup"], f"TEST_DIR={directory}"],
env=env,
stderr=subprocess.STDOUT,
)
subprocess.check_call([pip_path, "freeze"])
return True
def install_pyln_testing(pip_path):
# Many plugins only implicitly depend on pyln-testing, so let's help them
cln_path = os.environ["CLN_PATH"]
# Install pytest (eventually we'd want plugin authors to include
# it in their requirements-dev.txt, but for now let's help them a
# bit).
subprocess.check_call(
[pip_path, "install", *pip_opts, *global_dependencies],
stderr=subprocess.STDOUT,
)
subprocess.check_call(
[pip_path, "install", "-U", *pip_opts, "pip", "wheel"],
stderr=subprocess.STDOUT,
)
subprocess.check_call(
[
pip_path,
"install",
*pip_opts,
cln_path + "/contrib/pyln-client",
cln_path + "/contrib/pyln-testing",
"MarkupSafe>=2.0",
"itsdangerous>=2.0",
],
stderr=subprocess.STDOUT,
)
def install_dev_pyln_testing(pip_path):
# Many plugins only implicitly depend on pyln-testing, so let's help them
cln_path = os.environ["CLN_PATH"]
subprocess.check_call(
[
pip_path,
"install",
*pip_opts,
"-r",
cln_path + "/requirements.txt",
],
stderr=subprocess.STDOUT,
)
def run_one(p: Plugin, workflow: str) -> bool:
print("Running tests on plugin {p.name}".format(p=p))
if not p.testfiles:
print("No test files found, skipping plugin {p.name}".format(p=p))
return True
print(
"Found {ctestfiles} test files, creating virtualenv and running tests".format(
ctestfiles=len(p.testfiles)
)
)
print("::group::{p.name}".format(p=p))
# Create a virtual env
vdir = tempfile.TemporaryDirectory()
vpath = Path(vdir.name)
bin_path = vpath / "bin"
pytest_path = vpath / "bin" / "pytest"
env = os.environ.copy()
env.update(
{
# Need to customize PATH so lightningd can find the correct python3
"PATH": "{}:{}".format(bin_path, os.environ["PATH"]),
# Some plugins require a valid locale to be set
"LC_ALL": "C.UTF-8",
"LANG": "C.UTF-8",
}
)
try:
if not prepare_env(p, vpath, env, workflow):
# Skipping is counted as a success
return True
except Exception as e:
print(f"Error creating test environment: {e}")
print("::endgroup::")
return False
logging.info(f"Virtualenv at {vpath}")
cmd = [
str(pytest_path),
"-vvv",
"--timeout=600",
"--timeout-method=thread",
"--color=yes",
"-n=5",
]
logging.info(f"Running `{' '.join(cmd)}` in directory {p.path.resolve()}")
try:
subprocess.check_call(
cmd,
stderr=subprocess.STDOUT,
env=env,
cwd=p.path.resolve(),
)
return True
except Exception as e:
logging.warning(f"Error while executing: {e}")
return False
finally:
print("::endgroup::")
# gather data
def collect_gather_data(results: list, success: bool) -> dict:
gather_data = {}
for t in results:
p = t[0]
if p.testfiles:
if success or t[1]:
gather_data[p.name] = "passed"
else:
gather_data[p.name] = "failed"
return gather_data
def push_gather_data(data: dict, workflow: str, python_version: str):
print("Pushing gather data...")
configure_git()
subprocess.run(["git", "fetch"])
subprocess.run(["git", "checkout", "badges"])
filenames_to_add = []
for plugin_name, result in data.items():
filename = write_gather_data_file(plugin_name, result, workflow, python_version)
filenames_to_add.append(filename)
output = subprocess.check_output(
list(chain(["git", "add", "-v"], filenames_to_add))
).decode("utf-8")
print(f"output from git add: {output}")
if output != "":
output = subprocess.check_output(
[
"git",
"commit",
"-m",
f"Update test result for Python{python_version} to ({workflow} workflow)",
]
).decode("utf-8")
print(f"output from git commit: {output}")
for _ in range(10):
subprocess.run(["git", "pull", "--rebase"])
output = subprocess.run(
["git", "push", "origin", "badges"], capture_output=True, text=True
)
if output.returncode == 0:
print("Push successful")
break
else:
print(
f"Push failed with return code {output.returncode}, retrying in 2 seconds..."
)
print(f"Push failure message: {output.stderr}")
time.sleep(2)
print("Done.")
def write_gather_data_file(
plugin_name: str, result, workflow: str, python_version: str
) -> str:
_dir = f".badges/gather_data/{workflow}/{plugin_name}"
filename = os.path.join(_dir, f"python{python_version}.txt")
os.makedirs(_dir, exist_ok=True)
with open(filename, "w") as file:
print(f"Writing {filename}")
file.write(result)
return filename
def gather_old_failures(old_failures: list, workflow: str):
print("Gather old failures...")
configure_git()
subprocess.run(["git", "fetch"])
subprocess.run(["git", "checkout", "badges"])
directory = ".badges"
for filename in os.listdir(directory):
if filename.endswith(f"_{workflow}.json"):
file_path = os.path.join(directory, filename)
plugin_name = filename.rsplit(f"_{workflow}.json", 1)[0]
with open(file_path, "r") as file:
data = json.load(file)
if data["color"] == "red":
old_failures.append(plugin_name)
print(f"Old failures: {old_failures}")
print("Done.")
def run_all(
workflow: str, python_version: str, update_badges: bool, plugin_names: list
):
root_path = (
subprocess.check_output(["git", "rev-parse", "--show-toplevel"])
.decode("ASCII")
.strip()
)
root = Path(root_path)
plugins = list(enumerate_plugins(root))
if plugin_names != []:
plugins = [p for p in plugins if p.name in plugin_names]
print(
"Testing the following plugins: {names}".format(
names=[p.name for p in plugins]
)
)
else:
print("Testing all plugins in {root}".format(root=root))
results = [(p, run_one(p, workflow)) for p in plugins]
success = all([t[1] for t in results])
old_failures = []
if not success and plugin_names == []:
gather_old_failures(old_failures, workflow)
if update_badges:
push_gather_data(
collect_gather_data(results, success), workflow, python_version
)
if not success:
print("The following tests failed:")
has_new_failure = False
for t in filter(lambda t: not t[1], results):
if t[0].name not in old_failures:
has_new_failure = True
print(" - {p.name} ({p.path})".format(p=t[0]))
if has_new_failure:
sys.exit(1)
else:
print("All tests passed.")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Plugins test script")
parser.add_argument("workflow", type=str, help="Name of the GitHub workflow")
parser.add_argument("python_version", type=str, help="Python version")
parser.add_argument(
"--update-badges",
action="store_true",
help="Whether badges data should be updated",
)
parser.add_argument("plugins", nargs="*", default=[], help="List of plugins")
args = parser.parse_args()
run_all(args.workflow, args.python_version, args.update_badges, args.plugins)