- 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
- I usually create an
-
What are you testing? Is it code which happens to log stuff, or is it some transformations, the result of which is logged?quamrana– quamrana2019-12-06 16:11:00 +00:00Commented Dec 6, 2019 at 16:11
-
It's code that happens to log stuff... but eventually returns a result. I assert that the result and my expected value is True. I'm really looking for a way to output said logs in the console while those tests are being run...Karun– Karun2019-12-06 16:16:05 +00:00Commented Dec 6, 2019 at 16:16
-
If you are testing code that happens to log, then you don't need the logs when you are unit testing. Switch them off.quamrana– quamrana2019-12-06 16:18:06 +00:00Commented Dec 6, 2019 at 16:18
-
Correct, that is the default setting for pytest. I however, would like to have them turned ON turning test-development and not sure how...Karun– Karun2019-12-06 16:22:49 +00:00Commented Dec 6, 2019 at 16:22
2 Answers
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.
1 Comment
pyproject.toml, under [tool.pytest.ini_options], use log_cli = true and log_cli_level = "DEBUG".There is an excellent article on this subject: https://pythontesting.net/framework/pytest/pytest-logging-real-time/
- I converted all my print statements to logging statements in my underlying code
- To the module containing my
test_transform()function I added
`
import logging
logging.basicConfig(level=logging.DEBUG)
def test_transform()
...