I want to trace the functions called and their return values for a test in python. I am using pytest module to call the test and sys.settrace for tracing the functions. However, this doesn't work and no functions are traced when I use pytest. It works when I use a locally defined function.
filename="../tests/models/reading_comprehension/naqanet_test.py::NumericallyAugmentedQaNetTest::test_model_can_train_save_and_load"
sys.settrace(trace_calls_and_returns)
sys.gettrace()
pytest.cmdline.main(filename.split(" "))
This is what I get:
============================= test session starts ==============================
platform linux -- Python 3.6.8, pytest-5.3.1, py-1.8.0, pluggy-0.13.1
plugins: flaky-3.6.1, cov-2.8.1
collected 1 item
.../tests/models/reading_comprehension/naqanet_test.py . [100%]
============================== 1 passed in 5.43s ===============================
Is there a way to use trace with pytest? Or some other way to handle it? I would like to handle this programmatically.
=============EDIT 1 ===============
Minimum reproducible example:
mytest.py
from unittest import TestCase
class MyTest(TestCase):
def testMe(self):
a=5
b=6
k=self.m(5,6)
def m(self, a, b):
return max(a,b)
tracetest.py
import sys
import pytest
def trace_calls(frame, event, arg):
if event != 'call':
return
co = frame.f_code
func_name = co.co_name
caller = frame.f_back
caller_line_no = caller.f_lineno if caller is not None else None
caller_filename = caller.f_code.co_filename if caller is not None else None
print('Call to %s on line %s of %s from line %s of %s' % \
(func_name, func_line_no, func_filename,
caller_line_no, caller_filename))
return
sys.settrace(trace_calls)
pytest.main(["mytest.py"])
The output does not have the function "m" in "mytest.py"
=================== EDIT 2 ===================
Found the solution:
Just need to add this option to pytest:
pytest.main(["--capture=no", "mytest.py"])
Thats it! :)
I got the hint from here