一、fixture裡面有個引數scope,通過scope可以控制fixture的作用範圍,根據作用範圍大小劃分:session>module>class>function,具體作用範圍如下:
1.function 函式或者方法級別都會被呼叫
2.class 類級別呼叫一次
3.module 模組級別呼叫一次
4.session 是個多檔案呼叫一次(可以跨 .py 檔案呼叫,每個.py檔案就是 module)
例如整個模組有多條測試用例,需要在全部用例執行之前開啟瀏覽器,全部執行完之後去關閉瀏覽器,開啟和關閉操作只執行一次,如果每次都要重新執行開啟操作,會非常佔用系統資源,這種場景除了 setup——module,teardown_module 可以實現,還可以通過設定模組級別的 fixture裝飾器【@pytst.fixture(scope="module")】來實現
scope='module'
fixture 引數 scope=‘module’ ,module作用是整個模組都會生效
#!/usr/bin/env python # _*_coding: utf-8 _*_ import pytest @pytest.fixture(scope='module') def open(): print("開啟瀏覽器") yield print("執行teardown !") print("最後關閉瀏覽器") @pytest.mark.usefixtures("open") def test_search1(): print("test_search1") raise NameError pass def test_search2(): print("test_search2") pass def test_search3(): print("test_search3") pass
程式碼解析:@pytest.fixture()如果不寫引數,引數預設scope=‘function’。當scope='module'時,在當前 .py指令碼里面所有的用例開始前只執行一次。scope巧妙與yield組合使用,相當於setup和teardown方法。還可以使用@pytest.mark.usefixtures裝飾器,傳入前置函式名作為引數
執行結果如下:
Testing started at 12:03 ... C:\Python\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1\helpers\pycharm\_jb_pytest_runner.py" --path C:/Users/wanwen/PycharmProjects/vigo/xuexi/20210123/test_fixture_scope.py Launching pytest with arguments C:/Users/wanwen/PycharmProjects/vigo/xuexi/20210123/test_fixture_scope.py in C:\Users\wanwen\PycharmProjects\vigo\xuexi\20210123 ============================= test session starts ============================= platform win32 -- Python 3.8.0, pytest-5.4.3, py-1.9.0, pluggy-0.13.1 rootdir: C:\Users\wanwen\PycharmProjects\vigo\xuexi\20210123 plugins: html-2.1.1, metadata-1.11.0, ordering-0.6collected 3 items test_fixture_scope.py 開啟瀏覽器 Ftest_search1 test_fixture_scope.py:14 (test_search1) @pytest.mark.usefixtures("open") def test_search1(): print("test_search1") > raise NameError E NameError test_fixture_scope.py:18: NameError .test_search2 .test_search3 執行teardown ! 最後關閉瀏覽器 [100%] ================================== FAILURES =================================== ________________________________ test_search1 _________________________________ @pytest.mark.usefixtures("open") def test_search1(): print("test_search1") > raise NameError E NameError test_fixture_scope.py:18: NameError ---------------------------- Captured stdout setup ---------------------------- 開啟瀏覽器 ---------------------------- Captured stdout call ----------------------------- test_search1 =========================== short test summary info =========================== FAILED test_fixture_scope.py::test_search1 - NameError ========================= 1 failed, 2 passed in 0.19s ========================= Process finished with exit code 0 Assertion failed Assertion failed
從上面執行結果可以看出scope=‘module’ 和yield結合,相當於setup_module 和teardown_module方法,整個模組執行之前呼叫open()方法中的yield前面列印輸出 的開啟瀏覽器 ,整個執行之後呼叫了yield後面的列印語句執行teardown與關閉瀏覽器,yield來喚醒teardown的執行,如果用例出現異常,不影響yield後面teardown執行
可以使用 @pytest.mark.usefixtures裝飾器來進行方法的傳入