我想为每个测试方法创建一个单独的日志文件 . 我想在conftest.py文件中执行此操作,并将日志文件实例传递给测试方法 . 这样,每当我在测试方法中记录某些东西时,它都会记录到一个单独的日志文件中,并且很容易分析 .
我尝试了以下内容 . 在conftest.py文件中我添加了这个:
logs_dir = pkg_resources.resource_filename("test_results", "logs")
def pytest_runtest_setup(item):
test_method_name = item.name
testpath = item.parent.name.strip('.py')
path = '%s/%s' % (logs_dir, testpath)
if not os.path.exists(path):
os.makedirs(path)
log = logger.make_logger(test_method_name, path) # Make logger takes care of creating the logfile and returns the python logging object.
这里的问题是pytest_runtest_setup无法向测试方法返回任何内容 . 至少,我不知道 .
所以,我想在conftest.py文件中使用scope =“function”创建一个fixture方法,并从测试方法中调用这个fixture . 但是,fixture方法不知道Pytest.Item对象 . 在pytest_runtest_setup方法的情况下,它接收item参数并使用它我们能够找到测试方法名称和测试方法路径 .
请帮忙!
1 回答
我找到了我正在寻找的答案 . 我能够使用像这样的函数作用域夹具来实现它: