前面介紹的是在cmd中執行pytest,平常我們一般都是通過編譯器(如pycharm)來編寫用例的,寫完用例后,需要調試看看是否能運行,如果每次都切換到cmd中執行,太麻煩。
因此,這一節來說下怎么在代碼中執行pytest。
需要先導入pytest,並通過pytest.main()來執行。
import pytest class TestClass(object): def test_one(self): x = "this" assert 'h' in x def test_two(self): x = "hello" assert hasattr(x, 'check') if __name__ == '__main__': pytest.main()
默認是執行當前腳本所在目錄下的所有用例。
當然,也可以加參數來指定運行規則,參數必須放在列表或元組中
import pytest class TestClass(object): def test_one(self): x = "this" assert 'h' in x def test_two(self): x = "hello" assert hasattr(x, 'check') def test_three(self): assert 3 == 5 if __name__ == '__main__': pytest.main(['-q','--maxfail=1','test_class.py'])