I have a tool that returns a value similar to this:
import pytest
@pytest.yield_fixture(scope="module")
def oneTimeSetUp(browser):
print("Running one time setUp")
if browser == 'firefox':
driver = webdriver.Firefox()
print("Running tests on FF")
else:
driver = webdriver.Chrome()
print("Running tests on chrome")
yield driver
print("Running one time tearDown")
This device receives a browser value from another device that reads a command line parameter.
Then I have a test class where I have several test methods, and they all want to use the same return value driver to continue the tests.
import pytest
@pytest.mark.usefixtures("oneTimeSetUp")
class TestClassDemo():
def test_methodA(self):
self.driver.get("https://www.google.com")
self.driver.find_element(By.ID, "some id")
print("Running method A")
def test_methodB(self):
print("Running method B")
Using self.driver fails with an error message
self = <test_class_demo.TestClassDemo object at 0x102fb6c18>
def test_methodA(self):
> self.driver.get("https://www.google.com")
E AttributeError: 'TestClassDemo' object has no attribute 'driver'
I know that I can pass the device as an argument for each method where I want to use it, but this is not the best way, because I need it in each method, and I can pass it to a class and then use it in all testing methods .
- ?
1:
conftest.py,
@pytest.yield_fixture(scope="class") # <-- note class scope
def oneTimeSetUp(request, browser):
print("Running one time setUp")
if browser == 'firefox':
driver = webdriver.Firefox()
driver.maximize_window()
driver.implicitly_wait(3)
print("Running tests on FF")
else:
driver = webdriver.Chrome()
print("Running tests on chrome")
if request.cls is not None:
request.cls.driver = driver
yield driver
print("Running one time tearDown")
, TestClassDemo, . ABC
class ABC():
def __init(self, driver):
self.driver = driver
def enterName(self):
TestClassDemo
@pytest.mark.usefixtures("oneTimeSetUp", "setUp")
class TestClassDemo(unittest.TestCase):
@pytest.fixture(scope="class", autouse=True)
def setup(self):
self.abc = ABC(self.driver)
def setup_module(self):
self.abc = ABC(self.driver)
def test_methodA(self):
self.driver.get("https://google.com")
self.abc.enterName("test")
print("Running method A")
def test_methodB(self):
self.abc.enterName("test")
print("Running method B")
abc test_.
, .py.
, yield.
2:
, oneTimeTearDown? tearDown
@pytest.fixture(scope="class")
def oneTimeSetUp(request, browser):
print("Running one time setUp")
if browser == 'firefox':
driver = webdriver.Firefox()
driver.maximize_window()
driver.implicitly_wait(3)
print("Running tests on FF")
else:
driver = webdriver.Chrome()
print("Running tests on chrome")
if request.cls is not None:
request.cls.driver = driver
UnitTest, def setUpClass (cls), , test_. , .
, , unittest, . , . .
stackoverflow, . ?
Python unittest