Skip to content

Commit a347665

Browse files
committed
Improvements to Arm backend pytest setup
* Add pytest fixture to ensure randomness on tests * Move pytest setup to conftest.py to separate pytest commonalities from general ones * Minor error catching improvements * Removed pytest dependency in ArmTester Change-Id: I9132681d705c1501391f3d4603f5d6f0786db873
1 parent 1c9abfa commit a347665

29 files changed

+283
-247
lines changed

backends/arm/test/common.py

Lines changed: 14 additions & 166 deletions
Original file line numberDiff line numberDiff line change
@@ -4,156 +4,33 @@
44
# This source code is licensed under the BSD-style license found in the
55
# LICENSE file in the root directory of this source tree.
66

7-
import logging
7+
88
import os
9-
import platform
10-
import shutil
11-
import subprocess
12-
import sys
9+
1310
import tempfile
1411
from datetime import datetime
15-
from enum import auto, Enum
1612
from pathlib import Path
17-
from typing import Any
18-
19-
import pytest
2013

21-
import torch
14+
from conftest import is_option_enabled
2215

2316
from executorch.backends.arm.arm_backend import ArmCompileSpecBuilder
2417
from executorch.exir.backend.compile_spec_schema import CompileSpec
2518

2619

27-
class arm_test_options(Enum):
28-
quantize_io = auto()
29-
corstone300 = auto()
30-
dump_path = auto()
31-
date_format = auto()
32-
fast_fvp = auto()
33-
34-
35-
_test_options: dict[arm_test_options, Any] = {}
36-
37-
# ==== Pytest hooks ====
38-
39-
40-
def pytest_addoption(parser):
41-
parser.addoption("--arm_quantize_io", action="store_true")
42-
parser.addoption("--arm_run_corstone300", action="store_true")
43-
parser.addoption("--default_dump_path", default=None)
44-
parser.addoption("--date_format", default="%d-%b-%H:%M:%S")
45-
parser.addoption("--fast_fvp", action="store_true")
46-
47-
48-
def pytest_configure(config):
49-
if config.option.arm_quantize_io:
50-
load_libquantized_ops_aot_lib()
51-
_test_options[arm_test_options.quantize_io] = True
52-
if config.option.arm_run_corstone300:
53-
corstone300_exists = shutil.which("FVP_Corstone_SSE-300_Ethos-U55")
54-
if not corstone300_exists:
55-
raise RuntimeError(
56-
"Tests are run with --arm_run_corstone300 but corstone300 FVP is not installed."
57-
)
58-
_test_options[arm_test_options.corstone300] = True
59-
if config.option.default_dump_path:
60-
dump_path = Path(config.option.default_dump_path).expanduser()
61-
if dump_path.exists() and os.path.isdir(dump_path):
62-
_test_options[arm_test_options.dump_path] = dump_path
63-
else:
64-
raise RuntimeError(
65-
f"Supplied argument 'default_dump_path={dump_path}' that does not exist or is not a directory."
66-
)
67-
_test_options[arm_test_options.date_format] = config.option.date_format
68-
_test_options[arm_test_options.fast_fvp] = config.option.fast_fvp
69-
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
70-
71-
72-
def pytest_collection_modifyitems(config, items):
73-
if not config.option.arm_quantize_io:
74-
skip_if_aot_lib_not_loaded = pytest.mark.skip(
75-
"u55 tests can only run with quantize_io=True."
76-
)
77-
78-
for item in items:
79-
if "u55" in item.name:
80-
item.add_marker(skip_if_aot_lib_not_loaded)
81-
82-
83-
def pytest_sessionstart(session):
84-
pass
85-
86-
87-
def pytest_sessionfinish(session, exitstatus):
88-
if get_option(arm_test_options.dump_path):
89-
_clean_dir(
90-
get_option(arm_test_options.dump_path),
91-
f"ArmTester_{get_option(arm_test_options.date_format)}.log",
92-
)
93-
94-
95-
# ==== End of Pytest hooks =====
96-
97-
# ==== Custom Pytest decorators =====
98-
99-
100-
def expectedFailureOnFVP(test_item):
101-
if is_option_enabled("corstone300"):
102-
test_item.__unittest_expecting_failure__ = True
103-
return test_item
104-
105-
106-
# ==== End of Custom Pytest decorators =====
107-
108-
109-
def load_libquantized_ops_aot_lib():
110-
so_ext = {
111-
"Darwin": "dylib",
112-
"Linux": "so",
113-
"Windows": "dll",
114-
}.get(platform.system(), None)
115-
116-
find_lib_cmd = [
117-
"find",
118-
"cmake-out-aot-lib",
119-
"-name",
120-
f"libquantized_ops_aot_lib.{so_ext}",
121-
]
122-
res = subprocess.run(find_lib_cmd, capture_output=True)
123-
if res.returncode == 0:
124-
library_path = res.stdout.decode().strip()
125-
torch.ops.load_library(library_path)
126-
127-
128-
def is_option_enabled(
129-
option: str | arm_test_options, fail_if_not_enabled: bool = False
130-
) -> bool:
131-
"""
132-
Returns whether an option is successfully enabled, i.e. if the flag was
133-
given to pytest and the necessary requirements are available.
134-
Implemented options are:
135-
- corstone300.
136-
- quantize_io.
137-
138-
The optional parameter 'fail_if_not_enabled' makes the function raise
139-
a RuntimeError instead of returning False.
20+
def get_time_formatted_path(path: str, log_prefix: str) -> str:
14021
"""
141-
if isinstance(option, str):
142-
option = arm_test_options[option.lower()]
143-
144-
if option in _test_options and _test_options[option]:
145-
return True
146-
else:
147-
if fail_if_not_enabled:
148-
raise RuntimeError(f"Required option '{option}' for test is not enabled")
149-
else:
150-
return False
22+
Returns the log path with the current time appended to it. Used for debugging.
15123
24+
Args:
25+
path: The path to the folder where the log file will be stored.
26+
log_prefix: The name of the test.
15227
153-
def get_option(option: arm_test_options) -> Any | None:
154-
if option in _test_options:
155-
return _test_options[option]
156-
return None
28+
Example output:
29+
'./my_log_folder/test_BI_artifact_28-Nov-14:14:38.log'
30+
"""
31+
return str(
32+
Path(path) / f"{log_prefix}_{datetime.now().strftime('%d-%b-%H:%M:%S')}.log"
33+
)
15734

15835

15936
def maybe_get_tosa_collate_path() -> str | None:
@@ -303,35 +180,6 @@ def get_u85_compile_spec_unbuilt(
303180
return compile_spec
304181

305182

306-
def current_time_formated() -> str:
307-
"""Return current time as a formated string"""
308-
return datetime.now().strftime(get_option(arm_test_options.date_format))
309-
310-
311-
def _clean_dir(dir: Path, filter: str, num_save=10):
312-
sorted_files: list[tuple[datetime, Path]] = []
313-
for file in dir.iterdir():
314-
try:
315-
creation_time = datetime.strptime(file.name, filter)
316-
insert_index = -1
317-
for i, to_compare in enumerate(sorted_files):
318-
compare_time = to_compare[0]
319-
if creation_time < compare_time:
320-
insert_index = i
321-
break
322-
if insert_index == -1 and len(sorted_files) < num_save:
323-
sorted_files.append((creation_time, file))
324-
else:
325-
sorted_files.insert(insert_index, (creation_time, file))
326-
except ValueError:
327-
continue
328-
329-
if len(sorted_files) > num_save:
330-
for remove in sorted_files[0 : len(sorted_files) - num_save]:
331-
file = remove[1]
332-
file.unlink()
333-
334-
335183
def get_target_board(compile_spec: list[CompileSpec]) -> str | None:
336184
for spec in compile_spec:
337185
if spec.key == "compile_flags":

0 commit comments

Comments
 (0)