I'm trying to use PyTest and I cannot obtain how to set 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 am getting "NameError: name 'a' is not defined".
Also the example from the official documentation doesn't work. What's wrong? I need functionality similar to setUp/tearDown . But I don't want to use unittest . Can someone provide me 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. Therefore me second question is for an working example of using fixture with classes/methods. I just need to see working examples of fixtures in Python.
Is there a different Python 3 unit testing framework with assertions as simple as in PyTest ?
Fixtures don't work like this. They cannot magically transfer the name a
from one function's ( setup
) local scope to another's ( test
). Instead, your setup
function must explicitly return the object that will be passed as the setup
argument to your test
function. 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()
More typically you'd do something like:
/usr/bin/env python
import pytest
import random
@pytest.fixture()
def my_rand_int():
return random.randint(0,10)
def test(my_rand_int):
assert 3 > my_rand_int
if __name__ == '__main__':
pytest.main()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.