1.通过参数引用
@pytest.fixture() def init_xx(): print(".....初始化测试数据") with open("./test.txt", "w") as f: f.write("1") class Test_xx: # 通过参数引用 def test_xx(self, init_xx): with open("./test.txt", "r") as f: assert f.read() == "2"
2.通过函数引用
@pytest.fixture() def init_xx(): print(".....初始化测试数据") with open("./test.txt", "w") as f: f.write("1") # 通过函数引用 @pytest.mark.usefixtures("init_xx") class Test_xx: def setup_class(self): print("...setup_class") def teardown_class(self): print("...teardown_class") def test_xx(self): with open("./test.txt", "r") as f: assert f.read() == "2" def test_yy(self): assert True
3.设置自动运行,测试类内的每个方法都调用一次函数
# 设置自动运行,测试类内的每个方法都调用一次函数 @pytest.fixture(scope="function", autouse="True") # 设置自动运行,测试类内的只调用一次工厂函数 @pytest.fixture(scope="class", autouse="True") def init__xx(): print("...初始化测试数据") class Test_yy: def test_xx(self): print("...test_xx") def test_yy(self): print("...test_yy")
4.使用返回值,参数列表
# 使用返回值,参数列表 @pytest.fixture(params=[1, 2, 3]) def init_xx(request): return request.param class Test_zz: # 开始 def setup_class(self): print("...setup_class") # 结束 def teardown_class(self): print("...teardown_class") # 参数引用 def test_a(self, init_xx): assert init_xx == 4
练习:
from init_driver.Init_driver import init_driver from selenium.webdriver.support.wait import WebDriverWait import pytest # 练习(一) class Test_SZ: # 开始 def setup_class(self): self.driver = init_driver() # 结束 def teardown_class(self): self.driver.quit() # 显示等待 def wait_ele(self, type, xpt): if type == "id": return WebDriverWait(self.driver, 5, 1) .until(lambda x: x.find_element_by_id(xpt)) if type == "xpath": return WebDriverWait(self.driver, 5, 1) .until(lambda x: x.find_element_by_xpath(xpt)) @pytest.fixture() def t_index(self): # 进入设置,由声音和振动滑动到飞行模式 s_1 = self.wait_ele("xpath", "//*[contains(@text, ‘声音和振动‘)]") e_1 = self.wait_ele("xpath", "//*[contains(@text, ‘飞行模式‘)]") self.driver.drag_and_drop(s_1, e_1) # 点击勿扰模式 self.wait_ele("xpath", "//*[contains(@text, ‘勿扰模式‘)]").click() @pytest.mark.usefixtures("t_index") # 业务一 def test_001(self): # 改变勿扰规则 off_on = self.wait_ele("id", "android:id/switchWidget") # 点击开关 off_on.click() # 点击勿扰规则 self.wait_ele("xpath", "//*[contains(@text, ‘勿扰规则‘)]").click() # 选择仅限闹钟 self.wait_ele("xpath", "//*[contains(@text, ‘仅限闹钟‘)]").click() # 取改变后的概要信息 summary_text = self.wait_ele("id", "android:id/summary") assert "仅限闹钟" in summary_text.text, "失败了..." if __name__ == ‘__main__‘: pytest.main([‘-s‘, ‘test_10.py‘, ‘--html=../report/report.html‘])
原文:https://www.cnblogs.com/zhaoquanmo/p/10768638.html