-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathpytest_plugin.py
More file actions
599 lines (501 loc) · 19.7 KB
/
pytest_plugin.py
File metadata and controls
599 lines (501 loc) · 19.7 KB
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
# -*- coding: utf-8 -*-
# pylint: disable=no-member, unused-wildcard-import
"""
Created on Mon Sep 1 12:44:36 2014.
@author: Morten
"""
import os
import re
import ast
import time
import shutil
import warnings
import argparse
import itertools
import contextlib
import collections
from pathlib import Path
from traceback import format_list, extract_tb
import pytest
# from _pytest.fixtures import FixtureRequest
# from _pytest.fixtures import TopRequest
from pytest import TempPathFactory
from anypytools import AnyPyProcess, macro_commands
from anypytools.tools import (
ON_WINDOWS,
get_anybodycon_path,
replace_bm_constants,
get_bm_constants,
anybodycon_version,
find_ammr_path,
get_ammr_version,
winepath,
wraptext,
AMSVersion,
)
__all__ = [
"AnyTestFile",
"AnyTestItem",
"AnyException",
"AnyTestSession",
]
DEFAULT_ANYTEST_OUTPUT = Path.cwd() / "anytest-output"
LOAD_TIME_VARIABLE = "Global.System.LoadedModel.LoadDurationCPUThread"
RUN_TEST_TIME_VARIABLE = "Main.RunTest.RunDurationCPUThread"
def _is_load_duration_supported():
return AMSVersion.from_string(pytest.anytest.ams_version) >= (7, 5, 0, 10759)
class AnyTestSession(object):
"""Class for storing configuation of the AnyTest plugin to pytest."""
def __init__(self):
self.ammr_version = ""
self.ams_version = ""
self.save_basefolder = ""
self.anytest_compare_dir = ""
self.last_number = None
self.last_session = None
def configure(self, config):
"""Configure the AnyTestSession object.
This can't be in __init__()
since it is instantiated and added to the pytest namespace very
early in the pytest startup.
"""
ammr_path = find_ammr_path(config.getoption("--ammr") or config.rootdir)
self.ammr_version = get_ammr_version(ammr_path)
self.ams_path = config.getoption("--anybodycon") or get_anybodycon_path()
self.ams_path = os.path.abspath(self.ams_path) if self.ams_path else ""
self.ams_version = anybodycon_version(self.ams_path)
major_ammr_ver = 1 if self.ammr_version.startswith("1") else 2
self.bm_constants_map = get_bm_constants(
ammr_path=ammr_path, ammr_version=major_ammr_ver
)
def _limited_traceback(excinfo):
"""Return a formatted traceback with this frame up removed.
The function removes all the stack from this frame up
(i.e from __file__ and up)
"""
tb = extract_tb(excinfo.tb)
try:
idx = [__file__ in e for e in tb].index(True)
return format_list(tb[idx + 1 :])
except ValueError:
return format_list(tb)
def _read_header(fpath):
"""Read the commented header of anyscript test file.
The function remvoes any leading '//' comments.
"""
code = ""
with open(fpath) as f:
for line in f.readlines():
if line.startswith("//"):
line = line.strip("//")
code += line
else:
break
return code
@contextlib.contextmanager
def change_dir(path):
"""Context manager for changing directories."""
path = Path(path)
prev_cwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(prev_cwd)
def pytest_collect_file(parent, file_path):
"""Collect AnyScript test files."""
if file_path.suffix.lower() == ".any" and file_path.stem.lower().startswith(
"test_"
):
return AnyTestFile.from_parent(parent, path=file_path)
def _format_switches(defs):
if isinstance(defs, dict):
defs = [defs]
elif isinstance(defs, tuple):
combinations = list(itertools.product(*defs))
defs = []
for elem in combinations:
defs.append({k: v for d in elem for k, v in d.items()})
elif isinstance(defs, list):
pass
else:
defs = [dict()]
if len(defs) == 0:
defs = [dict()]
return defs
def _as_absolute_paths(d, start=os.getcwd()):
import ntpath as os_path
start = str(start)
out = {}
start = start if ON_WINDOWS else winepath(start, "-w")
for key, val in d.items():
val = val if ON_WINDOWS else winepath(val, "-w")
out[key] = os_path.abspath(os_path.relpath(val, start))
return out
HEADER_ENSURES = (
("define", (dict, collections.abc.Sequence)),
("path", (dict, collections.abc.Sequence)),
("ignore_errors", (collections.abc.Sequence,)),
("warnings_to_include", (collections.abc.Sequence,)),
("fatal_warnings", (bool, collections.abc.Sequence)),
("keep_logfiles", (bool,)),
("logfile_prefix", (str,)),
("expect_errors", (collections.abc.Sequence,)),
("save_study", (str, collections.abc.Sequence, type(None))),
("pytest_markers", (collections.abc.Sequence,)),
("use_gui", (bool,)),
)
def _parse_header(header, test_file):
ns = {"self": test_file}
try:
exec(header, globals(), ns)
except SyntaxError:
pass
# Remove test-file object from namespace since it should not be passed on
ns.pop("self", None)
for name, types in HEADER_ENSURES:
if name in ns and not isinstance(ns[name], types):
typestr = ", ".join([t.__name__ for t in types])
msg = f"{name} must be one of the following type(s) ({typestr})"
raise TypeError(msg)
return ns
def _write_macro_file(path, name, macro):
filename = os.path.join(path, name + ".anymcr")
with open(filename, "w") as f:
f.writelines([str(mcr) + "\n" for mcr in macro])
return filename
def _print_version_info():
"""Print the AnyBodyCon executable used in the test."""
print("\nUsing:")
print(" AnyBodyCon: ", pytest.anytest.ams_path)
print(" ", anybodycon_version(pytest.anytest.ams_path))
def pytest_collection_finish(session):
print()
_print_version_info()
print()
class DeferPlugin(object):
"""Simple plugin to defer pytest-xdist hook functions."""
def pytest_xdist_setupnodes(self, config, specs):
"""called before any remote node is set up."""
_print_version_info()
def pytest_configure(config):
"""Configure the AnyTest framework."""
pytest.anytest = AnyTestSession()
pytest.anytest.configure(config)
if config.pluginmanager.hasplugin("xdist"):
config.pluginmanager.register(DeferPlugin())
def pytest_collection_modifyitems(items, config):
selected_items = []
deselected_items = []
if (
config.getoption("--anytest-deselect")
and config.getoption("--anytest-output") is not None
):
# Deselect all test items which doesn't save data.
for item in items:
if getattr(item, "hdf5_outputs", False):
selected_items.append(item)
else:
deselected_items.append(item)
config.hook.pytest_deselected(items=deselected_items)
items[:] = selected_items
class AnyTestFile(pytest.File):
"""pytest.File subclass for AnyScript files."""
def collect(self):
"""Yield test cases from a AnyScript test file."""
# Collect define statements from the header
strheader = _read_header(self.path)
header = _parse_header(strheader, test_file=self)
def_list = _format_switches(header.pop("define", None))
def_list = [
replace_bm_constants(d, pytest.anytest.bm_constants_map) for d in def_list
]
path_list = _format_switches(header.pop("path", None))
combinations = itertools.product(def_list, path_list)
# Run though the defines an create a test case for each
for i, (any_defs, any_paths) in enumerate(combinations):
if isinstance(any_defs, dict) and isinstance(any_paths, dict):
yield AnyTestItem.from_parent(
name=self.path.stem,
id=i,
parent=self,
any_defs=any_defs,
any_paths=any_paths,
**header,
)
else:
raise ValueError("Malformed input: ", header)
class AnyTestItem(pytest.Item):
"""pytest.Item subclass representing individual collected tests."""
def __init__(self, name, id, parent, any_defs, any_paths, **kwargs):
test_name = f"{name}_{id}"
super().__init__(test_name, parent)
self.any_defs = any_defs
for k, v in self.config.getoption("define_kw") or {}:
self.any_defs[k] = v
self.any_defs["TEST_NAME"] = f'"{test_name}"'
if self.config.getoption("--ammr"):
any_paths["AMMR_PATH"] = self.config.getoption("--ammr")
any_paths["ANYBODY_PATH_AMMR"] = self.config.getoption("--ammr")
self.any_paths = _as_absolute_paths(any_paths, start=self.config.rootdir)
self.name = test_name
self.expect_errors = kwargs.get("expect_errors", [])
for marker in kwargs.get("pytest_markers", []):
self.add_marker(marker)
self.timeout = self.config.getoption("--timeout")
self.errors = []
mainfile = self.path
if not ON_WINDOWS:
mainfile = winepath(mainfile, "-w")
self.macro = [
macro_commands.Load(mainfile, self.any_defs, self.any_paths),
]
if _is_load_duration_supported():
self.macro += [
macro_commands.Dump(LOAD_TIME_VARIABLE),
]
fatal_warnings = kwargs.get("fatal_warnings", False)
warnings_to_include = kwargs.get("warnings_to_include", None)
if warnings_to_include:
warnings.warn(
f"\n{name}:`warnings_to_include` is deprecated. \nSpecify the `fatal_warnings` variable as "
"a list to select specific warnings",
DeprecationWarning,
)
if not isinstance(fatal_warnings, collections.abc.Sequence):
fatal_warnings = warnings_to_include
if not isinstance(fatal_warnings, collections.abc.Sequence):
fatal_warnings = ["WARNING"] if fatal_warnings else []
self.app_opts = {
"silent": True,
"debug_mode": self.config.getoption("--anybody_debug_mode"),
"anybodycon_path": pytest.anytest.ams_path,
"timeout": self.timeout,
"ignore_errors": kwargs.get("ignore_errors", []),
"warnings_to_include": fatal_warnings,
"fatal_warnings": bool(fatal_warnings),
"keep_logfiles": kwargs.get("keep_logfiles", True),
"logfile_prefix": kwargs.get("logfile_prefix", None),
"use_gui": kwargs.get("use_gui", False),
}
if not self.config.getoption("--only-load"):
self.macro += [macro_commands.RunOperation("Main.RunTest")]
if _is_load_duration_supported():
self.macro += [
macro_commands.Dump(RUN_TEST_TIME_VARIABLE),
]
self.hdf5_outputs = []
save_study = kwargs.get("save_study", None)
if save_study and self.config.getoption("--anytest-output") is not None:
save_study = [save_study] if isinstance(save_study, str) else save_study
for study in save_study:
fname = f"{study}.anydata.h5"
self.macro.append(
f'classoperation {study}.Output "Save data" --type="Deep" --file="{fname}"'
)
self.hdf5_outputs.append(fname)
return
# def setup(self) -> None:
# def func() -> None:
# pass
# self.funcargs = {} # type: ignore[attr-defined]
# fm = self.session._fixturemanager
# self._fixtureinfo = fm.getfixtureinfo( # type: ignore[attr-defined]
# node=self, func=func, cls=None, funcargs=False
# )
# self.fixture_request = FixtureRequest(self, _ispytest=True)
# self.fixture_request._fillfixtures()
def runtest(self):
"""Run an AnyScript test item."""
tmpdir = TempPathFactory.from_config(self.config, _ispytest=True).mktemp(
self.name
)
with change_dir(tmpdir):
self.app = AnyPyProcess(**self.app_opts)
if ON_WINDOWS:
result = self.app.start_macro(
self.macro, logfile=Path(self.name).with_suffix(".txt")
)[0]
else:
# Disable caputure on linux due to a bug when AMS lauches it own python
capmanager = self.config.pluginmanager.getplugin("capturemanager")
with capmanager.global_and_fixture_disabled():
result = self.app.start_macro(
self.macro, logfile=Path(self.name).with_suffix(".txt")
)[0]
if _is_load_duration_supported():
load_time = result.get(LOAD_TIME_VARIABLE, None)
if load_time is not None:
self.user_properties.append(("Load time", load_time))
run_test_time = result.get(RUN_TEST_TIME_VARIABLE, None)
if run_test_time is not None:
self.user_properties.append(("Run time", run_test_time))
# Ignore error due to missing Main.RunTest
if "ERROR" in result:
runtest_missing = any("Main.RunTest" in err for err in result["ERROR"])
if runtest_missing:
runtest_errros = (
"Main.RunTest : Unresolved",
"Main.RunTest : Select Operation",
"run : command unexpected while",
"Main.RunTest.RunDurationCPUThread : Unresolved object",
)
result["ERROR"][:] = [
err
for err in result["ERROR"]
if not any(s in err for s in runtest_errros)
]
# Check that the expected errors are present
error_list = result.get("ERROR", [])
if self.expect_errors:
for xerr in self.expect_errors:
xerr_found = False
for error in error_list[:]:
if xerr in error:
xerr_found = True
error_list.remove(error)
if not xerr_found:
self.errors.append(
f'TEST ERROR: Expected error not found: "{xerr}"'
)
# Add remaining errors to item's error list
if error_list:
self.errors.extend(error_list)
if self.errors:
self.logfile = Path(result["task_work_dir"]) / result["task_logfile"]
# Add info to the hdf5 file if compare output was set
if self.hdf5_outputs:
base = Path(
self.config.getoption("--anytest-output") or DEFAULT_ANYTEST_OUTPUT
)
subfolder = Path(self.config.getoption("--anytest-name"))
target = base / subfolder / self.name
self.save_output_files(tmpdir, target, result, self.hdf5_outputs)
if self.errors and self.config.getoption("--create-macros"):
logfile = Path(result["task_logfile"])
shutil.copy(logfile, self.path.parent)
shutil.copy(logfile.with_suffix(".anymcr"), self.path.parent)
# shutil.rmtree(tmpdir, ignore_errors=True)
if len(self.errors) > 0:
raise AnyException(self)
return
def save_output_files(self, src_folder, target_folder, result, hdf5files):
"""Saves hdf5, macro, and log files from a test run
and copy it to the target_folder
"""
import h5py
target_folder = Path(target_folder)
src_folder = Path(src_folder)
src_log = src_folder / Path(result["task_logfile"]).name
if target_folder.exists():
shutil.rmtree(target_folder)
os.makedirs(target_folder)
for fn in hdf5files:
if (src_folder / fn).exists():
shutil.copyfile(src_folder / fn, target_folder / fn)
f = h5py.File(target_folder / fn, "a")
f.attrs["anytest_processtime"] = result["task_processtime"]
f.attrs["anytest_macro"] = "\n".join(result["task_macro"][:-1])
f.attrs["anytest_ammr_version"] = pytest.anytest.ammr_version
f.attrs["anytest_ams_version"] = pytest.anytest.ams_version
f.close()
else:
self.errors.append(f"ERROR: No HDF5 data were saved: {fn}")
target_log = target_folder / "logfile.txt"
shutil.copyfile(src_log, target_log)
def repr_failure(self, excinfo):
"""Print a representation when a test failes."""
if isinstance(excinfo.value, AnyException):
rtn = "Main file:\n"
rtn += wraptext(self.path, initial_indent=" ")
rtn += "\nSpecial model configuration:"
for k, v in self.any_defs.items():
rtn += f"\n #define {k} {v}"
for k, v in self.any_paths.items():
rtn += f"\n #path {k} {v}"
rtn += "\nErrors:"
for elem in self.errors:
rtn += "\n"
rtn += wraptext(elem, initial_indent="> ", subsequent_indent=" ")
rtn += f'\nFull logfile: "{self.logfile.absolute()}"'
return rtn
else:
return str(excinfo.value)
def reportinfo(self):
""" """
return self.path, 0, f"AnyBody Simulation: {self.name}"
class AnyException(Exception):
"""Custom exception for error reporting."""
def split_string_eq_1(kv):
return kv.split("=", 1)
def pytest_addoption(parser):
group = parser.getgroup("anypytools", "testing AnyBody models")
group.addoption(
"--anybodycon",
action="store",
metavar="path",
help="anybodycon.exe used in test: default or " "path-to-anybodycon",
)
group.addoption(
"--anybody_debug_mode",
default=0,
type=int,
help="Sets the debug mode for the anybody console application. This can be used to enable crash dumps.",
)
group.addoption(
"--only-load",
action="store_true",
help="Only run a load test. I.e. do not run the " "'RunTest' macro",
)
group.addoption(
"--ammr",
action="store",
metavar="path",
help="Can be used to specify which AnyBody Managed Model "
"Repository (AMMR) to use. Setting this will pass a "
"'AMMR_PATH' path statement for all models",
)
group.addoption(
"--define",
action="append",
type=split_string_eq_1,
dest="define_kw",
help="Add custom define statements parse to all AnyScript models. "
"Must be given in the form: --define MYDEF=6",
)
group._addoption(
"--timeout",
default=3600,
type=int,
help="terminate tests after a certain timeout period",
)
group.addoption(
"--create-macros",
action="store_true",
help="Create a macro file if the test fails. This makes it "
"easy to re-run the failed test in the gui application.",
)
group.addoption(
"--anytest-name",
nargs="?",
default=time.strftime("%Y_%m_%d-%H.%M.%S"),
help="Specify the subfolder where test output is stored. This defaults to a time stamp, but can overriden with a specific name",
)
group.addoption(
"--anytest-deselect",
dest="anytest_deselect",
default=True,
action=argparse.BooleanOptionalAction,
help="Will deselect any test which does not produce hdf5 output.",
)
group.addoption(
"--anytest-output",
metavar="path",
nargs="?",
default=None,
const=str(DEFAULT_ANYTEST_OUTPUT),
help=(
"Specify if hdf5 files are saved from the tests. Can be assined a value to specify the base "
"folder where data will be saved. Default save directory is %(const)r."
),
)