Pytest fixtures not working - why?
I am trying to use PyTest and I cannot get how to set the fixtures. I've tried the following code:
import pytest
import random
@pytest.fixture()
def setup():
a = random.randint(0,10)
def test(setup):
assert 3 > a
if __name__ == '__main__':
pytest.main()
And i get "NameError: name 'a' is not defined".
Also example from official documentation doesn't work. What's wrong? I need functionality similar to setUp / tearDown . But I don't want to use unittest. Can anyone provide me with an example with working fixtures (both setUp type and tearDown type)? I want to write some test as functions and some test as methods inside classes, so the second question is a working example of using fixture with classes / methods. I just need to see working examples of fixtures in python.
Is there another framework in python3 testing unit with assertions as simple as in PyTest ?
source to share
Fixtures don't work like that. They cannot magically pass a name a
from one setup
local scope function ( ) to another ( test
). Instead, your function setup
must explicitly return an object that will be passed as an argument to setup
your function test
. For example:
import pytest
import random
class TestSetup:
def __init__(self):
self.a = random.randint(0, 10)
@pytest.fixture()
def setup():
return TestSetup()
def test(setup):
assert 0 <= setup.a <= 10
if __name__ == '__main__':
pytest.main()
source to share