在之前的學習中,代碼中一直是傳入了fixture函數common_driver,又使用了pytest.mark.usefixtures:
@pytest.mark.usefixtures("common_driver") def test_welcome(self, common_driver): WelcomePage(common_driver).swipe_screen() WelcomePage(common_driver).get_spe_screenshot() image_text = WelcomePage(common_driver).identify_screenshot() assert image_text == "立即體驗"
今天看pytest官方文檔,發現可以不這么用,主要分為兩種情況
1. 當不需要使用fixture中的返回時,直接使用pytest.mark.usefixtures(funcname)。舉個例子:測試中需要創建空目錄,把空目錄作為當前目錄進行操作,但不用關心具體的空目錄,這時可以使用tempfile和pytest fixtures來實現:
conftest.py代碼
import os import shutil import tempfile import pytest @pytest.fixture def cleandir(): old_cwd = os.getcwd() #創建臨時目錄 newpath = tempfile.mkdtemp() #將當前路徑切換到臨時目錄 os.chdir(newpath) yield #將當前路徑切換到原來的目錄 os.chdir(old_cwd) #遞歸的刪除臨時目錄 shutil.rmtree(newpath)
test_setenv.py
import os import pytest @pytest.mark.usefixtures("cleandir") class TestDirectoryInit: def test_cwd_starts_empty(self): #斷言臨時目錄下的文件是不是空 assert os.listdir(os.getcwd()) == [] #新建一個file文件 with open("myfile", "w") as f: f.write("hello") def test_cwd_again_starts_empty(self): #由於pytest.mark.usefixtures作用在類上,表示這兩個測試方法都是要了cleandir fixture,所以會創建兩次新的臨時目錄,這個方法中,臨時目錄沒有新建文件,所以為空。另外,pytest的執行順序與a-zA-Z0-9無關 assert os.listdir(os.getcwd()) == []
2. 如果需要fixture中的返回值,在測試方法中直接傳入被fixture裝飾的方法名就行,例如:common_driver
def test_welcome(self, common_driver): WelcomePage(common_driver).swipe_screen() WelcomePage(common_driver).get_spe_screenshot() image_text = WelcomePage(common_driver).identify_screenshot() assert image_text == "立即體驗"
=========================4月18日更新======================
如果沒有返回值,fixture裝飾整個類時,只能使用@pytest.mark.usefixtures,比如這樣的:
conftest.py
#conftest.py import pytest @pytest.fixture def back_url(): print("環境准備") print("環境清理")
test_something.py
import pytest @pytest.mark.usefixtures("back_url") class TestSomething(): def test_1(self): print("test_1") def test_2(self): print("test_2")
如果有返回值,fixture裝飾整個類時,不能使用class TestSomething(back_url),因為這樣就被當作繼承。只能將back_url作為參數一個一個傳到每個測試方法中
