py.text
unittest集成文档中概述了一种技术,该技术可能对您有所帮助…使用内置
request夹具。否则,如果不提供命名的夹具作为方法参数,我将无法知道访问夹具返回值的方法。
@pytest.yield_fixture(scope="class") # <-- note class scopedef 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应该工作)访问中的as class属性。
需要注意的是,您的灯具必须使用
scope='class',否则
request对象将不具有
cls属性。
希望对您有所帮助!
更新
我还有一个类,在TestClassDemo中需要该对象,并且我需要将相同的驱动程序实例传递给该类。认为它是ABC类
没有更多上下文就很难知道,但是在我看来,您可以
ABC在实例化夹具中的
driver…的同时实例化对象
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实例,这就是您可以在类定义中使用固定装置的方式…
@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或类似的东西,它
oneTimeSetUp与驱动程序已经包装好的ABC实例完全分开并返回。
哪种方式最适合您?不确定。您需要根据所使用的内容进行决策。
对于后代,应该适当指出pytest装置只是糖和一点魔术。如果发现它们很困难,则根本不需要使用它们。pytest很高兴执行香草单元测试TestCases。
另外,请在答案中说明什么是代替yield driver实例的最佳使用方法。
这就是我的想法…
@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…请注意,这不会返回(或产生)驱动程序对象,这意味着将此固定装置作为函数/方法的命名参数提供不再有用,如果所有测试用例都是作为类编写(由您的示例建议)。
但是,如果要将夹具用作命名参数,则不要这样做。



