Search code examples
pythontddpytest

pytest option to output print/logging statements from tested code


  • Is there an option in pytest where the code that is being tested outputs it's logging.info(...) messages to the console
  • This would make developing my test cases much easier, as there is a lot of transforms of data taking place and I get lost in the transmutation
  • Once I am happy with the test case, I can turn-off the option so that the long winded logging statements disappear

  • I'm new to TDD and want to shift over to this practice, but not being able to see my print/logging statements causes me a lot of discomfort as I feel lost

    • I usually create an if __name__ == '__main__' that runs the main functions of the code
    • This at-least allows me to see the logging statements so that I can make sense of the code while it is running
    • But it seems like I'm duplicating efforts here

Solution

  • Pytest also has it's own implementation to show you whats happening as it captures your logging records. If you go to Live Logs on this page: https://docs.pytest.org/en/latest/logging.html it is explained pretty well. You need a pytest.ini file where you set:

    [pytest]
    log_cli = True
    

    This will make your logs show on the terminal as they are emitted. Then you can set the level that you want to see with your pytest call to for example DEBUG:

    pytest --log-cli-level DEBUG
    

    or you can specify it in your pytest.ini as well:

    [pytest]
    log_cli = True
    log_cli_level = DEBUG
    

    Where log_cli_level sets the level of what logs are shown. This approach does not make you change your own code which is nice. This off course also requires you to use logging in the first place but that's a good habit to have anyway.