In pytest I'm trying to figure out if its possible to pass an object or variable to a "function scope" fixture from a test function(either to the fixture setup or teardown)
2
votes
1 Answers
0
votes
You might interact with the fixture as follows, but it's not in the setup or teardown:
Code
import pytest
class FixtureStack():
def __init__(self):
self.messages = []
def __str__(self):
return f'messages={self.messages}'
def push(self, msg):
self.messages.append(msg)
@pytest.fixture(scope='function')
def stack():
yield FixtureStack()
def test_1(stack):
print(stack)
stack.push('msg_1')
print(stack)
assert stack.messages == ['msg_1']
def test_2(stack):
print(stack)
stack.push('msg_2')
print(stack)
assert stack.messages == ['msg_2']
Pytest execution:
$ pytest -v driver.py -s
=============================================== test session starts ================================================
platform linux -- Python 3.7.1, pytest-5.0.1, py-1.7.0, pluggy-0.12.0 -- /home/backend/venvs/py3.7.1/bin/python3.7
cachedir: .pytest_cache
rootdir: /home/backend/backend, inifile: pytest.ini
plugins: mock-1.10.4
collected 2 items
driver.py::test_1 messages=[]
messages=['msg_1']
PASSED
driver.py::test_2 messages=[]
messages=['msg_2']
PASSED
============================================= 2 passed in 0.01 seconds =============================================