Setting dynamic folder and report name in pytest

后端 未结 1 1795
醉酒成梦
醉酒成梦 2021-01-21 00:37

I have a problem with setting report name and folder with it dynamically in Python\'s pytest. For example: I\'ve run all pytest\'s tests @ 2020-03-06 21:50 so I\'d like to have

相关标签:
1条回答
  • 2021-01-21 01:33

    You can customize the plugin options in a custom impl of the pytest_configure hook. Put this example code in a conftest.py file in your project root dir:

    from datetime import datetime
    from pathlib import Path
    import pytest
    
    
    @pytest.hookimpl(tryfirst=True)
    def pytest_configure(config):
        # set custom options only if none are provided from command line
        if not config.option.htmlpath:
            now = datetime.now()
            # create report target dir
            reports_dir = Path('reports', now.strftime('%Y%m%d'))
            reports_dir.mkdir(parents=True, exist_ok=True)
            # custom report file
            report = reports_dir / f"report_{now.strftime('%H%M')}.html"
            # adjust plugin options
            config.option.htmlpath = report
            config.option.self_contained_html = True
    

    If you want to completely ignore what's passed from command line, remove the if not config.option.htmlpath: condition.

    If you want to stick with your current impl, notice that on fixtures teardown, pytest-html hasn't written the report yet. Move the code from cleanup_report to a custom impl of the pytest_sessionfinish hook to ensure pytest-html has already written the default report file:

    @pytest.hookimpl(trylast=True)
    def pytest_sessionfinish(session, exitstatus):
        shutil.move(...)
    
    0 讨论(0)
提交回复
热议问题