Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can pytest enable print() in src code?

Here's my code

in module.py:

def myFunc():
    print('aaa')

in test_module.py:

def test_myFunc():
    print('bbb')
    myFunc()

If I run pytest -s test_module.py then I can see printout bbb; but I can't see printout aaa. Actually I also tried to import logging to play with logger, also no luck.

So basically my question is, when triggering pytest, how can we see printout from the src code?

like image 407
LookIntoEast Avatar asked Sep 11 '26 17:09

LookIntoEast


1 Answers

I can confirm that pytest -s does the job.

pytest -s test_module.py

# test_module.py bbb
# aaa

However it may be a better idea to use Python logging module for debugging purpose. You just need to import logging and to replace the print by appropriate level call to logging.info() for example.

# module.py
import logging

def myFunc():
    logging.info('aaa')

# test_module.py
from module import myFunc
import logging

def test_myFunc():
    logging.info('bbb')
    myFunc() 

And here is the output.

pytest --log-cli-level=INFO test_module.py 

# INFO     root:test_module.py:6 bbb
# INFO     root:module.py:4 aaa

More information in the Pytest doc dedicated to logging.

like image 136
Romain Avatar answered Sep 14 '26 09:09

Romain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!