1. 程式人生 > >pytest高級用法,參數、函數、自動、返回值引用(九)

pytest高級用法,參數、函數、自動、返回值引用(九)

方法 down selenium def teardown 一次函數 信息 調用 clas

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])

pytest高級用法,參數、函數、自動、返回值引用(九)