Search code examples
pythonpython-3.xloggingpytestpython-logging

How to create new log file for each run of tests in pytest?


I have created a pytest.ini file,

addopts = --resultlog=log.txt

This creates a log file, but I would like to create a new log file everytime I run the tests.


Solution

  • Answering my own question. As hoefling mentioned --result-log is deprecated, I had to find a way to do it without using that flag. Here's how I did it,

    conftest.py

    from datetime import datetime
    import logging
    
    log = logging.getLogger(__name__)
    
    def pytest_assertrepr_compare(op, left, right):
        """ This function will print log everytime the assert fails"""
        log.error('Comparing Foo instances:    vals: %s != %s \n' % (left, right))
        return ["Comparing Foo instances:", " vals: %s != %s" % (left, right)]
    
    def pytest_configure(config):
        """ Create a log file if log_file is not mentioned in *.ini file"""
        if not config.option.log_file:
            timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d_%H-%M-%S')
            config.option.log_file = 'log.' + timestamp
    

    pytest.ini

    [pytest]
    log_cli = true
    log_cli_level = CRITICAL
    log_cli_format = %(message)s
    log_file_level = DEBUG
    log_file_format = %(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)
    log_file_date_format=%Y-%m-%d %H:%M:%S
    

    test_my_code.py

    import logging
    log = logging.getLogger(__name__)
    
    def test_my_code():
        ****test code