在
py.text unittest integration documentation
这可能会对您有所帮助……使用内置
request
固定装置否则,我不知道如何在不将命名fixture作为方法参数提供的情况下访问fixtures的返回值。
@pytest.yield_fixture(scope="class") # <-- note class scope
def oneTimeSetUp(request, browser): # <-- note the additional `request` param
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")
## add `driver` attribute to the class under test -->
if request.cls is not None:
request.cls.driver = driver
## <--
yield driver
print("Running one time tearDown")
现在您可以访问
driver
作为中的类属性
TestClassDemo
,如您在示例中所述(即。
self.driver
应该有效)。
警告是您的固定装置必须使用
scope='class'
,否则为
要求
对象不会拥有
cls
属性
我希望这有帮助!
更新
我还有一个类,它是TestClassDemo中需要的对象,我需要将相同的驱动程序实例传递给该类。将其视为ABC类
没有更多的上下文很难知道,但在我看来,您可能可以通过实例化
ABC
在实例化
驾驶员
…在
oneTimeSetUp
固定装置例如
@pytest.yield_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
request.cls.abc = ABC(driver) # <-- here
yield driver
print("Running one time tearDown")
但是如果您只需要一个或两个测试类的ABC实例,那么可以在类定义中使用fixture。。。
@pytest.mark.usefixtures("oneTimeSetUp", "setUp")
class TestClassDemo(unittest.TestCase):
@pytest.fixture(autouse=True)
def build_abc(self, oneTimeSetUp): # <-- note the oneTimeSetup reference here
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")
我对第二个例子不会特别满意。第三种选择是使用另一个yield_fixture或类似的,它与
一次性设置
并返回已包装驱动程序的ABC实例。
哪条路最适合你?不确定。你需要根据你在做什么来决定。
值得后人注意的是,pytest装置只是糖和一点魔法。如果你觉得很难,你根本不需要使用它们。pytest很乐意执行vanilla unittest TestCases。
另外,请在回答中解释什么是最好的使用方法,而不是给出驱动程序实例。
这是我的想法。。。
@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
…请注意,这不会返回(或产生)驱动程序对象,这意味着将此fixture作为命名参数提供给函数/方法不再有用,如果您的所有测试用例都是作为类编写的(示例中建议的),这应该很好。
但是,如果要将fixture用作命名参数,请不要这样做。