2017-10-13 149 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