Auto-format via black

This commit is contained in:
xross
2022-07-21 13:10:47 +01:00
parent 36dedc494c
commit a0f5591e0b
2 changed files with 88 additions and 60 deletions

View File

@@ -6,16 +6,17 @@ import os.path
import pytest import pytest
import subprocess import subprocess
target = os.environ.get('TARGET', 'all_possible') target = os.environ.get("TARGET", "all_possible")
print("target = ", target) print("target = ", target)
def pytest_collect_file(parent, path): def pytest_collect_file(parent, path):
if(path.ext == ".xe"): if path.ext == ".xe":
if(target == 'all_possible'): if target == "all_possible":
return UnityTestSource.from_parent(parent, fspath=path) return UnityTestSource.from_parent(parent, fspath=path)
if(target == 'XCOREAI' and ('xcoreai' in path.basename)): if target == "XCOREAI" and ("xcoreai" in path.basename):
return UnityTestSource.from_parent(parent, fspath=path) return UnityTestSource.from_parent(parent, fspath=path)
if(target == 'XCORE200' and ('xcore200' in path.basename)): if target == "XCORE200" and ("xcore200" in path.basename):
return UnityTestSource.from_parent(parent, fspath=path) return UnityTestSource.from_parent(parent, fspath=path)
@@ -31,7 +32,7 @@ class UnityTestSource(pytest.File):
# |-- src/ <- Unity test functions # |-- src/ <- Unity test functions
# `-- wscript <- Build system file used to generate/build runners # `-- wscript <- Build system file used to generate/build runners
xe_name = ((os.path.basename(self.name)).split("."))[0] + ".xe" xe_name = ((os.path.basename(self.name)).split("."))[0] + ".xe"
test_bin_path = os.path.join('bin', xe_name) test_bin_path = os.path.join("bin", xe_name)
yield UnityTestExecutable.from_parent(self, name=self.name) yield UnityTestExecutable.from_parent(self, name=self.name)
@@ -46,12 +47,16 @@ class UnityTestExecutable(pytest.Item):
simulator_fail = False simulator_fail = False
test_output = None test_output = None
try: try:
if('xcore200' in self.name): if "xcore200" in self.name:
print("run axe for executable ", self.name) print("run axe for executable ", self.name)
test_output = subprocess.check_output(['axe', self.name], text=True) test_output = subprocess.check_output(["axe", self.name], text=True)
else: else:
print("run xrun for executable ", self.name) print("run xrun for executable ", self.name)
test_output = subprocess.check_output(['xrun', '--io', '--id', '0', self.name], text=True, stderr=subprocess.STDOUT) test_output = subprocess.check_output(
["xrun", "--io", "--id", "0", self.name],
text=True,
stderr=subprocess.STDOUT,
)
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
# Unity exits non-zero if an assertion fails # Unity exits non-zero if an assertion fails
simulator_fail = True simulator_fail = True
@@ -59,10 +64,10 @@ class UnityTestExecutable(pytest.Item):
# Parse the Unity output # Parse the Unity output
unity_pass = False unity_pass = False
test_output = test_output.split('\n') test_output = test_output.split("\n")
for line in test_output: for line in test_output:
if 'test' in line: if "test" in line:
test_report = line.split(':') test_report = line.split(":")
# Unity output is as follows: # Unity output is as follows:
# <test_source>:<line_number>:<test_case>:PASS # <test_source>:<line_number>:<test_case>:PASS
# <test_source>:<line_number>:<test_case>:FAIL:<failure_reason> # <test_source>:<line_number>:<test_case>:FAIL:<failure_reason>
@@ -71,34 +76,43 @@ class UnityTestExecutable(pytest.Item):
test_case = test_report[2] test_case = test_report[2]
result = test_report[3] result = test_report[3]
failure_reason = None failure_reason = None
print(('\n {}()'.format(test_case)), end=' ') print(("\n {}()".format(test_case)), end=" ")
if result == 'PASS': if result == "PASS":
unity_pass = True unity_pass = True
continue continue
if result == 'FAIL': if result == "FAIL":
failure_reason = test_report[4] failure_reason = test_report[4]
print('') # Insert line break after test_case print print("") # Insert line break after test_case print
raise UnityTestException(self, {'test_source': test_source, raise UnityTestException(
'line_number': line_number, self,
'test_case': test_case, {
'failure_reason': "test_source": test_source,
failure_reason}) "line_number": line_number,
"test_case": test_case,
"failure_reason": failure_reason,
},
)
if simulator_fail: if simulator_fail:
raise Exception(self, "Simulation failed.") raise Exception(self, "Simulation failed.")
if not unity_pass: if not unity_pass:
raise Exception(self, "Unity test output not found.") raise Exception(self, "Unity test output not found.")
print('') # Insert line break after final test_case which passed print("") # Insert line break after final test_case which passed
def repr_failure(self, excinfo): def repr_failure(self, excinfo):
if isinstance(excinfo.value, UnityTestException): if isinstance(excinfo.value, UnityTestException):
return '\n'.join([str(self.parent).strip('<>'), return "\n".join(
'{}:{}:{}()'.format( [
excinfo.value[1]['test_source'], str(self.parent).strip("<>"),
excinfo.value[1]['line_number'], "{}:{}:{}()".format(
excinfo.value[1]['test_case']), excinfo.value[1]["test_source"],
'Failure reason:', excinfo.value[1]["line_number"],
excinfo.value[1]['failure_reason']]) excinfo.value[1]["test_case"],
),
"Failure reason:",
excinfo.value[1]["failure_reason"],
]
)
else: else:
return str(excinfo.value) return str(excinfo.value)

View File

@@ -5,36 +5,39 @@ import os.path
import subprocess import subprocess
import sys import sys
UNITY_TEST_DIR = 'src' UNITY_TEST_DIR = "src"
UNITY_TEST_PREFIX = 'test_' UNITY_TEST_PREFIX = "test_"
UNITY_RUNNER_DIR = 'runners' UNITY_RUNNER_DIR = "runners"
UNITY_RUNNER_SUFFIX = '_Runner' UNITY_RUNNER_SUFFIX = "_Runner"
project_root = os.path.join('..', '..', '..') project_root = os.path.join("..", "..", "..")
def get_ruby(): def get_ruby():
""" """
Check ruby is avaliable and return the command to invoke it. Check ruby is avaliable and return the command to invoke it.
""" """
interpreter_name = 'ruby' interpreter_name = "ruby"
try: try:
dev_null = open(os.devnull, 'w') dev_null = open(os.devnull, "w")
# Call the version command to check the interpreter can be run # Call the version command to check the interpreter can be run
subprocess.check_call([interpreter_name, '--version'], subprocess.check_call(
stdout=dev_null, [interpreter_name, "--version"], stdout=dev_null, close_fds=True
close_fds=True) )
except OSError as e: except OSError as e:
print("Failed to run Ruby interpreter: {}".format(e), file=sys.stderr) print("Failed to run Ruby interpreter: {}".format(e), file=sys.stderr)
exit(1) # TODO: Check this is the correct way to kill xwaf on error exit(1) # TODO: Check this is the correct way to kill xwaf on error
return interpreter_name return interpreter_name
def get_unity_runner_generator(project_root_path): def get_unity_runner_generator(project_root_path):
""" """
Check the Unity generate_test_runner script is avaliable, and return the Check the Unity generate_test_runner script is avaliable, and return the
path to it. path to it.
""" """
unity_runner_generator = os.path.join( unity_runner_generator = os.path.join(
project_root_path, 'Unity', 'auto', 'generate_test_runner.rb') project_root_path, "Unity", "auto", "generate_test_runner.rb"
)
if not os.path.exists(unity_runner_generator): if not os.path.exists(unity_runner_generator):
print("Unity repo not found in workspace", file=sys.stderr) print("Unity repo not found in workspace", file=sys.stderr)
exit(1) # TODO: Check this is the correct way to kill xwaf on error exit(1) # TODO: Check this is the correct way to kill xwaf on error
@@ -52,32 +55,41 @@ def get_file_type(filename):
""" """
Return the extension from the filename. Return the extension from the filename.
""" """
return filename.rsplit('.')[-1:][0] return filename.rsplit(".")[-1:][0]
def generate_unity_runner(project_root_path, unity_test_path, unity_runner_dir, def generate_unity_runner(
unity_runner_suffix): project_root_path, unity_test_path, unity_runner_dir, unity_runner_suffix
):
""" """
Invoke the Unity runner generation script for the given test file, and Invoke the Unity runner generation script for the given test file, and
return the path to the generated file. The output directory will be created return the path to the generated file. The output directory will be created
if it does not already exist. if it does not already exist.
""" """
runner_path = os.path.join(os.path.join(unity_runner_dir, get_test_name(unity_test_path))) runner_path = os.path.join(
os.path.join(unity_runner_dir, get_test_name(unity_test_path))
)
if not os.path.exists(runner_path): if not os.path.exists(runner_path):
os.makedirs(runner_path) os.makedirs(runner_path)
unity_runner_path = os.path.join( unity_runner_path = os.path.join(
runner_path, get_test_name(unity_test_path) + unity_runner_suffix runner_path, get_test_name(unity_test_path) + unity_runner_suffix + "." + "c"
+ '.' + 'c') )
try: try:
subprocess.check_call([get_ruby(), subprocess.check_call(
get_unity_runner_generator(project_root_path), [
unity_test_path, get_ruby(),
unity_runner_path]) get_unity_runner_generator(project_root_path),
unity_test_path,
unity_runner_path,
]
)
except OSError as e: except OSError as e:
print("Ruby generator failed for {}\n\t{}".format(unity_test_path, e), print(
file=sys.stderr) "Ruby generator failed for {}\n\t{}".format(unity_test_path, e),
file=sys.stderr,
)
exit(1) # TODO: Check this is the correct way to kill xwaf on error exit(1) # TODO: Check this is the correct way to kill xwaf on error
@@ -86,7 +98,7 @@ def find_unity_test_paths(unity_test_dir, unity_test_prefix):
Return a list of all file paths with the unity_test_prefix found in the Return a list of all file paths with the unity_test_prefix found in the
unity_test_dir. unity_test_dir.
""" """
return glob.glob(os.path.join(unity_test_dir, unity_test_prefix+'*')) return glob.glob(os.path.join(unity_test_dir, unity_test_prefix + "*"))
def find_unity_tests(unity_test_dir, unity_test_prefix): def find_unity_tests(unity_test_dir, unity_test_prefix):
@@ -95,25 +107,27 @@ def find_unity_tests(unity_test_dir, unity_test_prefix):
unity_test_prefix found in the unity_test_dir. unity_test_prefix found in the unity_test_dir.
""" """
unity_test_paths = find_unity_test_paths(unity_test_dir, unity_test_prefix) unity_test_paths = find_unity_test_paths(unity_test_dir, unity_test_prefix)
print('unity_test_paths = ', unity_test_paths) print("unity_test_paths = ", unity_test_paths)
return {get_test_name(path): get_file_type(path) return {get_test_name(path): get_file_type(path) for path in unity_test_paths}
for path in unity_test_paths}
def find_unity_test_paths(unity_test_dir, unity_test_prefix): def find_unity_test_paths(unity_test_dir, unity_test_prefix):
""" """
Return a list of all file paths with the unity_test_prefix found in the Return a list of all file paths with the unity_test_prefix found in the
unity_test_dir. unity_test_dir.
""" """
return glob.glob(os.path.join(unity_test_dir, unity_test_prefix+'*')) return glob.glob(os.path.join(unity_test_dir, unity_test_prefix + "*"))
def generate_runners(): def generate_runners():
UNITY_TESTS = find_unity_tests(UNITY_TEST_DIR, UNITY_TEST_PREFIX) UNITY_TESTS = find_unity_tests(UNITY_TEST_DIR, UNITY_TEST_PREFIX)
print('UNITY_TESTS = ',UNITY_TESTS) print("UNITY_TESTS = ", UNITY_TESTS)
unity_test_paths = find_unity_test_paths(UNITY_TEST_DIR, UNITY_TEST_PREFIX) unity_test_paths = find_unity_test_paths(UNITY_TEST_DIR, UNITY_TEST_PREFIX)
print('unity_test_paths = ',unity_test_paths) print("unity_test_paths = ", unity_test_paths)
for unity_test_path in unity_test_paths: for unity_test_path in unity_test_paths:
generate_unity_runner(project_root, unity_test_path, UNITY_RUNNER_DIR, UNITY_RUNNER_SUFFIX) generate_unity_runner(
project_root, unity_test_path, UNITY_RUNNER_DIR, UNITY_RUNNER_SUFFIX
)
if __name__ == "__main__": if __name__ == "__main__":