How to use pytest fixture and sharing variable between each testcase
我需要用python3和Selenium WebDriver编写一些UI测试。对于以下测试用例,测试运行良好。然而,我的问题是什么是更好的方法来编写测试用例,以及如何在每个测试用例和pytest fixture函数之间传递"base"变量。我需要1:在每个测试用例之前打开主页,2:在每个测试用例之后重新加载主页,并通过在每个测试用例和pytest fixture函数之间共享变量"base"来减少代码。导入Pytest从modules.base导入主页
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | class TestLogin(object): def setup_method(self, method): self.driver = WebDriver(desired_capabilities=desired_capabilities, command_executor=command_executor) self.current_method_name = method.__name__ def teardown_method(self, method): self.driver.close() self.driver.quit() @pytest.fixture(scope="function") def loadpage(): self.base = Home(self.driver).open() def loadLogin(): base.loadLogin() def test_a(self): base = Home(self.driver).open() assert True == base.dotesta() base.loadLogin() def test_b(self): base = Home(self.driver).open() assert True == base.dotestb() base.loadLogin() def test_c(self): base = Home(self.driver).open() assert True == base.dotestc() base.loadLogin() def test_d(self): base = Home(self.driver).open() assert True == base.dotestd() base.loadLogin() |
对于您当前的需求,您不需要使用夹具。这是你的密码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class TestLogin(object): def setup_method(self, method): self.driver = WebDriver(desired_capabilities=desired_capabilities, command_executor=command_executor) self.current_method_name = method.__name__ self.base = Home(self.driver).open() def teardown_method(self, method): self.base.loadLogin() self.driver.close() self.driver.quit() def test_a(self): assert True == self.base.dotesta() def test_b(self): assert True == self.base.dotestb() def test_c(self): assert True == self.base.dotestc() def test_d(self): assert True == self.base.dotestd() |
编辑:如果只打开一次页面,请将设置和拆卸替换为
1 2 3 4 5 6 7 8 9 | def setup_class(cls): cls.driver = WebDriver(desired_capabilities=desired_capabilities, command_executor=command_executor) cls.current_method_name = method.__name__ cls.base = Home(self.driver).open() def teardown_method(cls): cls.base.loadLogin() cls.driver.close() cls.driver.quit() |
号
有关CLS的详细信息。