Skip to content

Commit 47c2fd5

Browse files
committed
tests/integration: uvx ruff format
1 parent a241892 commit 47c2fd5

File tree

6 files changed

+103
-74
lines changed

6 files changed

+103
-74
lines changed

tests/integration/test.py

Lines changed: 38 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -9,22 +9,44 @@
99

1010

1111
def get_args():
12-
parser = argparse.ArgumentParser(description='C2Rust testsuite.')
13-
parser.add_argument('--verbose', dest='verbose', action='store_true',
14-
default=False,
15-
help='Enable verbose output')
16-
parser.add_argument('--stages', dest='stages', action='store',
17-
nargs='*', type=str, default=None, choices=tests.Test.STAGES,
18-
help='Only test specified stage(s)')
19-
parser.add_argument('--print-requirements', metavar='PLATFORM',
20-
dest='requirements', choices=['ubuntu'],
21-
action='store', type=str, default=None,
22-
help='Print requirements for platform and exit')
23-
parser.add_argument('--ignore-requirements',
24-
action='store_true',
25-
help='Ignore test requirements')
26-
parser.add_argument('projects', metavar='project', type=str, nargs='*',
27-
help='Project to test (defaults to all projects if none specified)')
12+
parser = argparse.ArgumentParser(description="C2Rust testsuite.")
13+
parser.add_argument(
14+
"--verbose",
15+
dest="verbose",
16+
action="store_true",
17+
default=False,
18+
help="Enable verbose output",
19+
)
20+
parser.add_argument(
21+
"--stages",
22+
dest="stages",
23+
action="store",
24+
nargs="*",
25+
type=str,
26+
default=None,
27+
choices=tests.Test.STAGES,
28+
help="Only test specified stage(s)",
29+
)
30+
parser.add_argument(
31+
"--print-requirements",
32+
metavar="PLATFORM",
33+
dest="requirements",
34+
choices=["ubuntu"],
35+
action="store",
36+
type=str,
37+
default=None,
38+
help="Print requirements for platform and exit",
39+
)
40+
parser.add_argument(
41+
"--ignore-requirements", action="store_true", help="Ignore test requirements"
42+
)
43+
parser.add_argument(
44+
"projects",
45+
metavar="project",
46+
type=str,
47+
nargs="*",
48+
help="Project to test (defaults to all projects if none specified)",
49+
)
2850
return parser.parse_args()
2951

3052

tests/integration/tests/__init__.py

Lines changed: 32 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
from concurrent.futures import ThreadPoolExecutor
32
from dataclasses import dataclass
43
from datetime import timedelta
@@ -14,7 +13,6 @@
1413

1514

1615
class Test(object):
17-
1816
STAGES: dict[str, list[str]] = {
1917
"autogen": ["autogen.sh"],
2018
"configure": ["configure.sh"],
@@ -23,16 +21,22 @@ class Test(object):
2321
"cargo.transpile": ["cargo.transpile.gen.sh", "cargo.transpile.sh"],
2422
"refactor": ["refactor.gen.sh", "refactor.sh"],
2523
"cargo.refactor": ["cargo.refactor.gen.sh", "cargo.refactor.sh"],
26-
"check": ["check.sh", "test.sh"]
24+
"check": ["check.sh", "test.sh"],
2725
}
2826

2927
def __init__(self, directory: Path, generated_scripts: set[Path]):
3028
# We only want scripts that have been generated by us now,
3129
# but non `*.gen*` scripts we can search for.
32-
non_gen_script_paths = { f for f in directory.iterdir() if f.suffix == ".sh" and ".gen" not in f.suffixes }
33-
gen_script_paths = { path for path in generated_scripts if path.is_relative_to(directory) }
30+
non_gen_script_paths = {
31+
f
32+
for f in directory.iterdir()
33+
if f.suffix == ".sh" and ".gen" not in f.suffixes
34+
}
35+
gen_script_paths = {
36+
path for path in generated_scripts if path.is_relative_to(directory)
37+
}
3438
script_paths = non_gen_script_paths | gen_script_paths
35-
self.scripts = { str(script.relative_to(directory)) for script in script_paths }
39+
self.scripts = {str(script.relative_to(directory)) for script in script_paths}
3640
self.dir = str(directory)
3741
self.conf_file = str(directory / CONF_YML)
3842
self.name = directory.name
@@ -45,41 +49,43 @@ def run_script(self, stage, script, verbose=False, xfail=False) -> bool:
4549
def print_log_tail_on_fail(script_path):
4650
logfile = f"{script_path}.log"
4751
if os.path.isfile(logfile):
48-
grep_cmd = ['grep', '-i', '-A', '20', '-E', 'panicked|error', logfile]
52+
grep_cmd = ["grep", "-i", "-A", "20", "-E", "panicked|error", logfile]
4953
grep = subprocess.Popen(grep_cmd, stdout=subprocess.PIPE)
5054
assert grep.stdout is not None
5155
for line in grep.stdout:
5256
print(line.decode().rstrip())
5357

5458
# fall back to tail if grep didn't find anything
5559
if grep.returncode != 0:
56-
tail = subprocess.Popen(['tail', '-n', '20', logfile], stdout=subprocess.PIPE)
60+
tail = subprocess.Popen(
61+
["tail", "-n", "20", logfile], stdout=subprocess.PIPE
62+
)
5763
assert tail.stdout is not None
5864
for line in tail.stdout:
5965
print(line.decode().rstrip())
6066
else:
61-
print("{color}Missing log file: {logf}{nocolor}".format(
62-
color=Colors.WARNING,
63-
logf=logfile,
64-
nocolor=Colors.NO_COLOR)
67+
print(
68+
"{color}Missing log file: {logf}{nocolor}".format(
69+
color=Colors.WARNING, logf=logfile, nocolor=Colors.NO_COLOR
70+
)
6571
)
6672

6773
script_path = os.path.join(self.dir, script)
6874

6975
if not os.path.isfile(script_path):
70-
print("{color}Missing script: {script}{nocolor}".format(
71-
color=Colors.FAIL,
72-
script=script_path,
73-
nocolor=Colors.NO_COLOR)
76+
print(
77+
"{color}Missing script: {script}{nocolor}".format(
78+
color=Colors.FAIL, script=script_path, nocolor=Colors.NO_COLOR
7479
)
80+
)
7581
return False
7682

7783
if not os.access(script_path, os.X_OK):
78-
print("{color}Script is not executable: {script}{nocolor}".format(
79-
color=Colors.FAIL,
80-
script=script_path,
81-
nocolor=Colors.NO_COLOR)
84+
print(
85+
"{color}Script is not executable: {script}{nocolor}".format(
86+
color=Colors.FAIL, script=script_path, nocolor=Colors.NO_COLOR
8287
)
88+
)
8389
return False
8490

8591
if not verbose:
@@ -89,7 +95,8 @@ def print_log_tail_on_fail(script_path):
8995
name=self.name,
9096
nc=Colors.NO_COLOR,
9197
stage=stage,
92-
script=relpath)
98+
script=relpath,
99+
)
93100
else:
94101
line = ""
95102

@@ -192,7 +199,9 @@ def run(self, conf: Config) -> bool:
192199
requested_stages = ", ".join(conf.stages)
193200
stages = ", ".join(Test.STAGES.keys())
194201
y, nc = Colors.WARNING, Colors.NO_COLOR
195-
die(f"invalid stages: {y}{requested_stages}{nc}. valid stages: {stages}")
202+
die(
203+
f"invalid stages: {y}{requested_stages}{nc}. valid stages: {stages}"
204+
)
196205

197206
stages = conf.stages
198207

@@ -234,5 +243,5 @@ def run(test: Test) -> TestResult:
234243
for result in results:
235244
print(f"{result.test.name} took {result.time}")
236245
if not all(result.passed for result in results):
237-
print(f"projects failed: {" ".join(result.test.name for result in results)}")
246+
print(f"projects failed: {' '.join(result.test.name for result in results)}")
238247
exit(1)

tests/integration/tests/hostenv.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ def is_ubuntu_1804() -> bool:
2020
# def is_ubuntu_1404():
2121
# return 'Ubuntu-14.04-trusty' in platform()
2222

23+
2324
def is_centos() -> bool:
2425
return distro.name() == "CentOS"
2526

tests/integration/tests/requirements.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,10 @@ def check_apt_package(yaml: List[str]):
2121
last: str = output.splitlines()[-1]
2222
expected: str = f"ii {p}"
2323
if not last.startswith(expected):
24-
errors.append(f"package not (properly) installed: {p} (dpkg output: {output}) ")
25-
24+
errors.append(
25+
f"package not (properly) installed: {p} (dpkg output: {output}) "
26+
)
27+
2628
if errors:
2729
errors = "\n".join(errors)
2830
die(errors)
@@ -65,7 +67,7 @@ def check_host(host: str, yaml: Dict):
6567
return
6668
# print(f"{host} -> {reqs}")
6769

68-
for (key, val) in reqs.items():
70+
for key, val in reqs.items():
6971
if key == "apt":
7072
check_apt(val)
7173
elif key == "programs":
@@ -92,7 +94,7 @@ def check_file(file: str, yaml):
9294

9395

9496
def check(conf):
95-
for (cf, yaml) in conf.project_conf.items():
97+
for cf, yaml in conf.project_conf.items():
9698
check_file(cf, yaml)
9799

98100

tests/integration/tests/templates.py

Lines changed: 15 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@
9797
def render_script(template: str, out_path: str, params: Dict):
9898
out = Template(template).render(**params)
9999

100-
with open(out_path, 'w') as fh:
100+
with open(out_path, "w") as fh:
101101
fh.writelines(out)
102102
os.chmod(out_path, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
103103

@@ -107,11 +107,13 @@ def autogen_cargo(conf_file, yaml: Dict) -> Generator[Path]:
107107
Yield generated paths.
108108
"""
109109

110-
def render_stage(stage_conf: Mapping[str, Any] | None, filename: str) -> Generator[Path]:
110+
def render_stage(
111+
stage_conf: Mapping[str, Any] | None, filename: str
112+
) -> Generator[Path]:
111113
"""
112114
Yield generated paths.
113115
"""
114-
116+
115117
if not isinstance(stage_conf, Mapping):
116118
return
117119
if not stage_conf:
@@ -126,10 +128,7 @@ def render_stage(stage_conf: Mapping[str, Any] | None, filename: str) -> Generat
126128
if rustflags and isinstance(rustflags, str):
127129
params["extra_rustflags"] = rustflags
128130

129-
out_path = os.path.join(
130-
os.path.dirname(conf_file),
131-
filename
132-
)
131+
out_path = os.path.join(os.path.dirname(conf_file), filename)
133132
render_script(CARGO_SH, out_path, params)
134133
yield Path(out_path)
135134

@@ -144,7 +143,7 @@ def autogen_refactor(conf_file, yaml: Dict) -> Generator[str]:
144143
"""
145144
Yield generated paths.
146145
"""
147-
146+
148147
refactor = yaml.get("refactor")
149148
if refactor and isinstance(refactor, Dict):
150149
ag = refactor.get("autogen")
@@ -154,7 +153,9 @@ def autogen_refactor(conf_file, yaml: Dict) -> Generator[str]:
154153
# Get list of transformations from config
155154
transforms = refactor.get("transforms")
156155
if transforms and isinstance(transforms, list):
157-
lines = [t.strip() for t in transforms if isinstance(t, str) and t.strip()]
156+
lines = [
157+
t.strip() for t in transforms if isinstance(t, str) and t.strip()
158+
]
158159
if lines:
159160
params["transform_lines"] = "\n".join(lines)
160161
elif transforms and isinstance(transforms, str):
@@ -164,10 +165,7 @@ def autogen_refactor(conf_file, yaml: Dict) -> Generator[str]:
164165

165166
# Only generate script if we have transformations
166167
if params["transform_lines"]:
167-
out_path = os.path.join(
168-
os.path.dirname(conf_file),
169-
"refactor.gen.sh"
170-
)
168+
out_path = os.path.join(os.path.dirname(conf_file), "refactor.gen.sh")
171169
render_script(REFACTOR_SH, out_path, params)
172170
yield Path(out_path)
173171

@@ -176,7 +174,7 @@ def autogen_transpile(conf_file, yaml: Dict) -> Generator[Path]:
176174
"""
177175
Yield generated paths.
178176
"""
179-
177+
180178
transpile = yaml.get("transpile")
181179
if transpile and isinstance(transpile, Dict):
182180
ag = transpile.get("autogen")
@@ -199,11 +197,7 @@ def autogen_transpile(conf_file, yaml: Dict) -> Generator[Path]:
199197
tflags = " ".join(tflags)
200198
params["tflags"] = tflags
201199

202-
203-
out_path = os.path.join(
204-
os.path.dirname(conf_file),
205-
"transpile.gen.sh"
206-
)
200+
out_path = os.path.join(os.path.dirname(conf_file), "transpile.gen.sh")
207201
render_script(TRANSPILE_SH, out_path, params)
208202
yield Path(out_path)
209203

@@ -212,8 +206,8 @@ def autogen(conf: Config) -> Generator[Path]:
212206
"""
213207
Yield generated paths.
214208
"""
215-
216-
for (cf, yaml) in conf.project_conf.items():
209+
210+
for cf, yaml in conf.project_conf.items():
217211
yield from autogen_transpile(cf, yaml)
218212
yield from autogen_refactor(cf, yaml)
219213
yield from autogen_cargo(cf, yaml)

tests/integration/tests/util.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ class Config(object):
1515
def __init__(self, args):
1616
self.verbose = args.verbose
1717
self.projects = args.projects # projects filter
18-
self.stages = args.stages # stage filter
18+
self.stages = args.stages # stage filter
1919
self.ignore_requirements = args.ignore_requirements
2020
self.project_dirs = find_project_dirs(self)
2121
self.project_conf = {cf: get_yaml(cf) for cf in get_conf_files(self)}
@@ -39,14 +39,14 @@ def lookup(yaml, keys: Sequence[str]):
3939

4040
class Colors(object):
4141
# Terminal escape codes
42-
OKBLUE = '\033[94m'
43-
OKGREEN = '\033[92m'
44-
WARNING = '\033[93m'
45-
FAIL = '\033[91m'
46-
NO_COLOR = '\033[0m'
42+
OKBLUE = "\033[94m"
43+
OKGREEN = "\033[92m"
44+
WARNING = "\033[93m"
45+
FAIL = "\033[91m"
46+
NO_COLOR = "\033[0m"
4747

4848

49-
def die(emsg: str, status: int=errno.EINVAL) -> Never:
49+
def die(emsg: str, status: int = errno.EINVAL) -> Never:
5050
(red, nc) = (Colors.FAIL, Colors.NO_COLOR)
5151
print(f"{red}error:{nc} {emsg}", file=sys.stderr)
5252
exit(status)
@@ -81,8 +81,9 @@ def find_project_dirs(conf: Config) -> List[str]:
8181
subdirs = sorted(next(os.walk(script_dir))[1])
8282

8383
# filter out __pycache__ and anything else starting with `_`
84-
subdirs = list(filter(lambda d: not(d.startswith("_") or d.startswith(".")),
85-
subdirs))
84+
subdirs = list(
85+
filter(lambda d: not (d.startswith("_") or d.startswith(".")), subdirs)
86+
)
8687

8788
if len(conf.projects) > 0: # only test named project
8889
projects = list(filter(lambda d: d in conf.projects, subdirs))
@@ -100,7 +101,7 @@ def find_project_dirs(conf: Config) -> List[str]:
100101

101102

102103
def get_yaml(file: str) -> dict[str, Any]:
103-
with open(file, 'r') as stream:
104+
with open(file, "r") as stream:
104105
try:
105106
return yaml.safe_load(stream)
106107
except yaml.YAMLError as exc:

0 commit comments

Comments
 (0)