2017-10-13 153 views
1

我使用pytest和pytest-html模块来生成HTML测试报告。Pytest HTML报告:如何获取报告文件的名称?

在拆卸阶段,我会自动在浏览器中使用webbrowser.open('file:///path_to_report.html')打开生成的HTML报告 - 这工作正常,但我运行不同的参数和每组参数的测试,我通过设置不同的报告文件命令行参数:

pytest -v mytest.py::TestClassName --html=report_localhost.html 

我拆除代码如下所示:

@pytest.fixture(scope='class') 
def config(request): 
    claz = request.cls 
    claz.host = request.config.getoption("--host", default=HOST_DEFAULT) 
    ... 

    def teardown_env(): 
     print('destroying test harness') 
     webbrowser.open("file:///path_to_report_localhost.html") 

    request.addfinalizer(teardown_env) 

    return "prepare_env" 

的问题是如何从拆除钩在测试访问报告文件名,这样的代替硬编码它我可以无论通过哪个路径作为命令行参数,即--html=report_for_host_xyz.html

回答

1

您可以在夹具中放置一个断点,并查看request.config.option对象 - 这是pytest放置所有argparsed键的位置。

你要找的是request.config.option.htmlpath

@pytest.fixture(scope='class') 
def config(request): 
    claz = request.cls 
    claz.host = request.config.getoption("--host", default=HOST_DEFAULT) 

    yield 100 # a value of the fixture for the tests 

    print('destroying test harness') 
    webbrowser.open("file:///{}".format(request.config.option.htmlpath)) 

或者你也可以做同样的作为--host键:

@pytest.fixture(scope='class') 
def config(request): 
    claz = request.cls 
    claz.host = request.config.getoption("--host", default=HOST_DEFAULT) 

    yield 100 # a value of the fixture for the tests 

    print('destroying test harness') 
    webbrowser.open("file:///{}".format(request.config.getoption("--html"))) 
+0

太谢谢你了!由于我只在命令行上传递了一个相对路径('--html = report_localhost.html'),我不得不预先设置绝对文件夹:'html_report_path = os.path.join(os.path.dirname(os.path .realpath(__ file__)),request.config.option.htmlpath); webbrowser.open(“file:// {path}”.format(path = html_report_path))' – ccpizza

+0

@ccpizza在这种情况下,您可能需要'os.path.join(request.config.invocation_dir,filename)'。在极少数情况下,'os.path.join(request.config.rootdir,filename)'。但是根目录是所有找到的测试的共同父项,而调用目录则来自您开始pytest过程的地方。考虑:'cd〜/ proj; pytest ./some/dir1/。/ some/dir2/t.py' - 调用目录是〜/ proj,但rootdir将是〜/ proj/some。 –

+0

非常干净!非常感激! – ccpizza