我曾经在我的pytest框架中使用 runner.py,以便通过组合标记和字符串参数来解决错误,例如:
-k 'foo' -m 'bar'
我还使用运行器来获取测试运行的开始时间戳并创建一个输出文件夹输出//,我将日志和html报告写入其中,保存任何屏幕截图等。
runner.py 摘录:
timestamp = time.strftime('%y%m%d-%H%M%S')
# the following are used by conftest.py
output_path = utils.generate_output_path(timestamp)
folder = utils.create_output_folder(output_path)
def main():
args = sys.argv[1:]
args.append('-v')
args.append('--timestamp=%s' % timestamp)
args.append('--output_target=%s' % folder)
args.append('--html=%s/results.html' % folder)
pytest.main(args, plugins=plgns)
if __name__ == "__main__":
main()
我想丢失 runner.py 并使用直接的 CLI 参数和夹具/钩子,但不手动传入时间戳、output_target或 html 报告路径,但到目前为止无法找到更改该配置的方法,例如通过修改 config.args。
如何动态写入时间戳、output_target和 html 路径,以便 pytest 在初始化期间使用它们?
这是我所做的:
在我的 pytest 中.ini我为 html 报告添加了一个默认的命令行选项,以便有一个我可以修改的配置属性:
addopts = --html=output/report.html
在我的 conftest.py 中,我添加了这个 pytest_configure(( 调用
def pytest_configure(config):
"""
Set up the output folder, logfile, and html report file;
this has to be done right after the command line options
are parsed, because we need to rewrite the pytest-html path.
:param config: pytest Config object
:return: None
"""
# set the timestamp for the start of this test run
timestamp = time.strftime('%y%m%d-%H%M%S')
# create the output folder for this test run
output_path = utils.generate_output_path(timestamp)
folder = utils.create_output_folder(output_path)
# start logging
filename = '%s/log.txt' % output_path
logging.basicConfig(filename=filename,
level=logging.INFO,
format='%(asctime)s %(name)s.py::%(funcName)s() [%(levelname)s] %(message)s')
initial_report_path = Path(config.option.htmlpath)
report_path_parts = list(initial_report_path.parts)
logger.info('Output folder created at "%s".' % folder)
logger.info('Logger started and writing to "%s".' % filename)
# insert the timestamp
output_index = report_path_parts.index('output')
report_path_parts.insert(output_index + 1, timestamp)
# deal with doubled slashes
new_report_path = Path('/'.join(report_path_parts).replace('//', '/'))
# update the pytest-html path
config.option.htmlpath = new_report_path
logger.info('HTML test report will be created at "%s".' % config.option.htmlpath)
这记录为:2018-03-03 14:07:39,632 welkin.tests.conftest.py::p ytest_configure(( [INFO] HTML测试报告将在"output/180303-140739/report.html"创建。
html 报告将写入相应的输出/<时间戳>/文件夹。这就是想要的结果。时间戳>