-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgen_worker_tests.py
More file actions
105 lines (88 loc) · 3.71 KB
/
gen_worker_tests.py
File metadata and controls
105 lines (88 loc) · 3.71 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
#!/usr/bin/env python
# TODO: rewrite using MAKO
import os
import re
from pathlib import Path
output_script = "tests/workers/test_workers.py"
root_imports = [
"import asyncio\n",
"import pytest\n",
"from src.helper import redis_client\n",
]
def main():
if not os.path.exists("pyproject.toml"):
print("Нужно запускать из корня проекта!")
exit(-1)
pathlist = Path("src/workers").rglob("*.py")
workers_to_test: list[Path] = []
for path in pathlist:
with open(path) as worker_file:
if 'if __name__ == "__main__":' in worker_file.read():
workers_to_test.append(path)
# Проверка, существует ли директория, если нет - создаём её
os.makedirs(os.path.dirname(output_script), exist_ok=True)
try:
with open(output_script, "w"): # Создаём файл, если его нет
pass
except OSError as e:
print(f"Ошибка при создании файла: {e}")
exit(-1)
with open(output_script, "r+") as script_file:
script_content = script_file.read()
tests: list[str] = []
for import_ in root_imports:
if import_ not in script_content:
if import_ == "from src.helper import redis_client":
if not os.path.exists("src/helper.py"):
print("Не найден src/helper.py файл, его присутствие необходимо для импорта redis_client. ")
print("Пожалуйста, добавьте его и перезапустите скрипт")
exit(-1)
script_file.write(import_)
for worker_path in workers_to_test:
worker_name = worker_path.name[:-3]
if f"def test_{worker_name}" in script_content:
print(f"Тест для {worker_name} уже существует, пропускаю")
continue
with open(worker_path, "r+") as worker_file:
start_line = ""
lines = worker_file.readlines()
for index, line in enumerate(lines):
if 'if __name__ == "__main__":' in line:
start_line = lines[index + 1].strip()
break
else:
print(f"Не нашёл линии запуска у воркера {worker_path}")
exit(-1)
import_path = (
str(worker_path)
.replace(".py", "")
.replace("/", ".")
.replace("\\", ".")
)
class_name = re.search(pattern=r"\w+(?=\(.*\))", string=start_line)
if class_name is None:
print(
"Ошбика при поиске названия класса воркера (скорее всего не сработал регекс"
)
exit(-1)
class_name = class_name.group()
import_line = f"from {import_path} import {class_name}"
tests.append(
f"""{import_line}
@pytest.mark.asyncio
async def test_{worker_name}():
try:
async with asyncio.timeout(2):
{start_line}
await {start_line.split("=")[0].strip()}.start()
except asyncio.TimeoutError:
assert True
except Exception as e:
print(f"Тест провален: {{e}}")
assert False
"""
)
for test_ in tests:
script_file.write(test_ + "\n")
if __name__ == "__main__":
main()