I'm using pytest (version 7.1.2) to test a function foo()
written in Python 3.9. I'd like to add assertions within foo()
that depend on which test_foo()
function is calling foo()
. Something like this:
def foo(a):
...
if my_caller() == 'test_foo_1':
assert a == 0
elif my_caller() == 'test_foo_2':
assert a > 0
...
def test_foo_1():
assert foo(0)
def test_foo_2():
assert not foo(4)
Is there a more elegant solution than the following (perhaps using marks) that allows foo()
to identify its caller?
import inspect
def my_caller():
return inspect.stack()[2][3]