-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathrun_tests.py
More file actions
209 lines (186 loc) · 7.75 KB
/
run_tests.py
File metadata and controls
209 lines (186 loc) · 7.75 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
"""
Example command
<python> run_tests.py generate <java> <utbot-cli-python.jar> <path to UTBotJava/utbot-python/samples> -c test_configuration.json
-p <python> -o <path to UTBotJava/utbot-python/samples/cli_test_dir or another directory>
<python> run_tests.py run -p <python> -t <path to UTBotJava/utbot-python/samples/cli_test_dir or another directory>
-c <path to UTBotJava/utbot-python/samples>
"""
import argparse
import contextlib
import json
import os
import shutil
from subprocess import Popen, PIPE
import sys
import threading
import typing
import tqdm
from tqdm.contrib import DummyTqdmFile
import pathlib
def parse_arguments():
parser = argparse.ArgumentParser(
prog="UtBot Python test", description="Generate tests for example files"
)
subparsers = parser.add_subparsers(dest="command")
parser_generate = subparsers.add_parser("generate", help="Generate tests")
parser_generate.add_argument("java")
parser_generate.add_argument("jar")
parser_generate.add_argument("path_to_test_dir")
parser_generate.add_argument("-c", "--config_file", required=True)
parser_generate.add_argument("-p", "--python_path", required=True)
parser_generate.add_argument("-o", "--output_dir", required=True)
parser_generate.add_argument("-i", "--coverage_output_dir", required=True)
parser_run = subparsers.add_parser("run", help="Run tests")
parser_run.add_argument("-p", "--python_path", required=True)
parser_run.add_argument("-t", "--test_directory", required=True)
parser_run.add_argument("-c", "--code_directory", required=True)
parser_coverage = subparsers.add_parser("check_coverage", help="Check coverage")
parser_coverage.add_argument("-i", "--coverage_output_dir", required=True)
parser_coverage.add_argument("-c", "--config_file", required=True)
return parser.parse_args()
def parse_config(config_path: str):
with open(config_path, "r") as fin:
return json.loads(fin.read())
@contextlib.contextmanager
def std_out_err_redirect_tqdm():
orig_out_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = map(DummyTqdmFile, orig_out_err)
yield orig_out_err[0]
# Relay exceptions
except Exception as exc:
raise exc
# Always restore sys.stdout/err if necessary
finally:
sys.stdout, sys.stderr = orig_out_err
def generate_tests(
java: str,
jar_path: str,
sys_paths: list[str],
python_path: str,
file_under_test: str,
timeout: int,
output: str,
coverage_output: str,
class_names: typing.Optional[list[str]] = None,
method_names: typing.Optional[list[str]] = None,
):
command = f"{java} -jar {jar_path} generate_python {file_under_test}.py -p {python_path} -o {output} -s {' '.join(sys_paths)} --timeout {timeout * 1000} --install-requirements --runtime-exception-behaviour PASS --coverage={coverage_output}"
if class_names is not None:
command += f" -c {','.join(class_names)}"
if method_names is not None:
command += f" -m {','.join(method_names)}"
tqdm.tqdm.write("\n" + command)
def stdout_printer(p):
for line in p.stdout:
tqdm.tqdm.write(line.rstrip().decode())
p = Popen(command.split(), stdout=PIPE)
t = threading.Thread(target=stdout_printer, args=(p,))
t.run()
def run_tests(
python_path: str,
tests_dir: str,
samples_dir: str,
):
command = f'{python_path} -m coverage run --source={samples_dir} -m unittest discover -p "utbot_*" {tests_dir}'
tqdm.tqdm.write(command)
code = os.system(command)
return code
def check_coverage(
config_file: str,
coverage_output_dir: str,
):
config = parse_config(config_file)
report: typing.Dict[str, bool] = {}
coverage: typing.Dict[str, typing.Tuple[float, float]] = {}
for part in config["parts"]:
for file in part["files"]:
for i, group in enumerate(file["groups"]):
if i > 0:
suffix = f"_{i}"
else:
suffix = ""
expected_coverage = group.get("coverage", 0)
file_suffix = f"{part['path'].replace('/', '_')}_{file['name']}{suffix}"
coverage_output_file = pathlib.Path(
coverage_output_dir, f"coverage_{file_suffix}.json"
)
if coverage_output_file.exists():
with open(coverage_output_file, "rt") as fin:
actual_coverage_json = json.loads(fin.readline())
actual_covered = sum(
lines["end"] - lines["start"] + 1
for lines in actual_coverage_json["covered"]
)
actual_not_covered = sum(
lines["end"] - lines["start"] + 1
for lines in actual_coverage_json["notCovered"]
)
if actual_covered + actual_not_covered == 0:
actual_coverage = 0
else:
actual_coverage = round(
actual_covered / (actual_not_covered + actual_covered) * 100
)
else:
actual_coverage = 0
coverage[file_suffix] = (actual_coverage, expected_coverage)
report[file_suffix] = actual_coverage >= expected_coverage
if all(report.values()):
return True
print("-------------")
print("Bad coverage:")
print("-------------")
for file, good_coverage in report.items():
if not good_coverage:
print(f"{file}: {coverage[file][0]}/{coverage[file][1]}")
return False
def main_test_generation(args):
config = parse_config(args.config_file)
if pathlib.Path(args.coverage_output_dir).exists():
shutil.rmtree(args.coverage_output_dir)
with std_out_err_redirect_tqdm() as orig_stdout:
for part in tqdm.tqdm(
config["parts"], file=orig_stdout, dynamic_ncols=True, desc="Progress"
):
for file in tqdm.tqdm(
part["files"], file=orig_stdout, dynamic_ncols=True, desc=part["path"]
):
for i, group in enumerate(file["groups"]):
if i > 0:
suffix = f"_{i}"
else:
suffix = ""
full_name = pathlib.PurePath(
args.path_to_test_dir, part["path"], file["name"]
)
output_file = pathlib.PurePath(
args.output_dir,
f"utbot_tests_{part['path'].replace('/', '_')}_{file['name']}{suffix}.py",
)
coverage_output_file = pathlib.PurePath(
args.coverage_output_dir,
f"coverage_{part['path'].replace('/', '_')}_{file['name']}{suffix}.json",
)
generate_tests(
args.java,
args.jar,
[args.path_to_test_dir],
args.python_path,
str(full_name),
group["timeout"],
str(output_file),
str(coverage_output_file),
group["classes"],
group["methods"],
)
if __name__ == "__main__":
arguments = parse_arguments()
if arguments.command == "generate":
main_test_generation(arguments)
elif arguments.command == "run":
run_tests(
arguments.python_path, arguments.test_directory, arguments.code_directory
)
elif arguments.command == "check_coverage":
check_coverage(arguments.config_file, arguments.coverage_output_dir)