import sys
from _ast import FunctionDef
path = ".\\tests"
dismiss_dir = [".pytest_cache", "assets"]
import os
import ast
import importlib
root = ""
test_files = []
def get_test_files(dir):
for ford in os.listdir(dir):
if ford.startswith(".") or ford.startswith("__") or ford in dismiss_dir:
continue
p = os.path.join(dir, ford)
if os.path.isdir(p):
get_test_files(p)
elif os.path.isfile(p) and ford.startswith("test_") and ford.endswith(".py"):
test_files.append(p)
def get_func2deco(file):
func2deco = {}
with open(file, "r", encoding="utf-8") as fo:
codes = fo.read()
codes_ast = ast.parse(codes)
body = codes_ast.body
for obj in body:
if isinstance(obj, FunctionDef):
print(obj.name)
func2deco[obj.name] = []
for deco in obj.decorator_list:
deco_name = deco.value.value.id + "." + deco.value.attr + "." + deco.attr
func2deco[obj.name].append(deco_name)
return func2deco
def add(a, b):
return a + b
import traceback
if __name__ == "__main__":
sys.path.append(path)
# f_module = importlib.import_module("tests.test_a")
# f_module.__getattribute__("test_a")()
get_test_files(path)
print(test_files)
for f in test_files:
func2deco = get_func2deco(f)
module_name = f[2:].replace("\\", ".")[:-3]
f_module = importlib.import_module(module_name)
for func, decos in func2deco.items():
try:
getattr(f_module, func)()
except:
print(traceback.print_exc())
# import yaml
# with open(r"E:\asome\mypytest\tests\datas\d.yaml", "r", encoding="utf-8") as f:
# data = yaml.load(f.read())
# print(data)
根据pytest原理实现的简单逻辑
最新推荐文章于 2023-04-17 17:00:40 发布