Search code examples
pythonautomated-testspytest

How to set unchangeable path for log file


I have test files with different nesting level. For example:

/project/tests/flows/test_flow_1.py

/project/tests/orders/reports/test_reports.py

My setting for log path in pytest.ini is log_file = logs/tests.log

But pytest creates the directory 'logs' in each test directory.

Also I tried to set it in conftest.py file but then the log file just is not created:

def logs_path(request):
    path = request.config.rootdir
    logging.basicConfig(filename=os.path.join(path, 'tests.log'))

How can I set this creating only one time in the root project directory?


Solution

  • I tried to duplicate your tests with this directory structure:

    ├── flow
    │   └── test_flow.py
    ├── logs
    │   └── my.log
    ├── orders
    │   └── reports
    │       └── test_reports.py
    └── pytest.ini
    

    pytest.ini:

    [pytest]
    log_cli = 1
    log_cli_level = INFO
    log_file = logs/my.log
    log_file_level = DEBUG
    

    At the level where pyest.ini is, I invoke pytest:

    $ pytest
    ...
    collected 2 items
    
    flow/test_flow.py::test_flow
    ------------------------------------ live log call -------------------------------------
    INFO     root:test_flow.py:3 in test flow
    PASSED                                                                           [ 50%]
    orders/reports/test_reports.py::test_reports
    ------------------------------------ live log call -------------------------------------
    INFO     root:test_reports.py:5 in test reports
    PASSED                                                                           [100%]
    
    ================================== 2 passed in 0.01s ===================================
    

    With these settings, I only see a single logs/my.log file and its content is:

    INFO     root:test_flow.py:3 in test flow
    INFO     root:test_reports.py:5 in test reports
    

    Please check your settings, how you invoke the tests, and where you invoke it.