Sunday, September 18, 2022

[FIXED] How can pytest enable print() in src code?

Issue

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?


Solution

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.



Answered By - Romain
Answer Checked By - Terry (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.