[TIP] instantiate class and use in all tests
James
bjlockie at lockie.ca
Wed Oct 26 07:52:19 PDT 2016
Can I instantiate a class (DoStuff) and make it available to all my tests?
I get an error with the following code:
==================================== ERRORS
====================================
________________________ ERROR collecting testscript.py
________________________
testscript.py:14: in <module>
@pytest.mark.incremental
testscript.py:16: in TestAclass
ds=DoStuff(a,b)
E NameError: name 'a' is not defined
Even if I can't pass in a and b, can I still make a ds and use it in my
tests?
# conftest.py
import pytest
@pytest.fixture(scope='module')
def need_a(request):
value = request.config.getoption("A")
if not value:
pytest.skip('test needs -A option to run')
return value
@pytest.fixture(scope='module')
def a(request):
a = pytest.config.getoption("A")
return a
@pytest.fixture(scope='module')
def b(request):
b = pytest.config.getoption("B")
return b
def pytest_addoption(parser):
parser.addoption("--A", action="store", default=None, help="a option")
parser.addoption("--B", action="store", default=None, help="b option")
import pytest
# testscript.py
class DoStuff():
def __init__(a,b):
self.a=a
self.b=b
def log(self,msg):
# do logging stuff
pass
@pytest.mark.incremental
class TestAclass():
ds=DoStuff(a,b)
def test_1(self,request):
print 'inside {0}-{1}
step'.format(self.__class__.__name__,request.function.__name__)
print 'a={0}, b={1}'.format(ds.a,ds.b)
ds.log("we are here")
pass
def test_2(self,request):
print 'inside {0}-{1}
step'.format(self.__class__.__name__,request.function.__name__)
print 'a={0}, b={1}'.format(ds.a,ds.b)
ds.log("we are here2")
pass
More information about the testing-in-python
mailing list