pytest 13 使用自定義標記mark
阿新 • • 發佈:2018-11-07
前言:
pytest可以規定那些要跑,那些不跑,跑特定的哪些?比如以下的這個例子:
#!/usr/bin/env/python # -*-coding:utf-8-*- import pytest @pytest.mark.runtest def test_run(): print("run") def test_not_run(): pass def test_not_run1(): pass class TestClass: def test_method(self): pass if __name__ == "__main__": pytest.main(["-s", "test_case.py", "-m=runtest"]) #代表只跑標識為runtest的case
執行結果:顯示一個執行,3個沒有被選擇
Testing started at 13:56 ... /usr/local/bin/python3.7 "/Applications/PyCharm CE.app/Contents/helpers/pycharm/_jb_pytest_runner.py" --path /Users/newcomer/gitByMyself/python_work_apple/pytest_package/mark/test_case.py -- -m=runtest Launching py.test with arguments-m=runtest /Users/newcomer/gitByMyself/python_work_apple/pytest_package/mark/test_case.py in /Users/newcomer/gitByMyself ============================= test session starts ============================== platform darwin -- Python 3.7.0, pytest-3.9.1, py-1.7.0, pluggy-0.8.0 rootdir: /Users/newcomer/gitByMyself, inifile: plugins: datadir-1.2.1, allure-adaptor-1.7.10collected 4 items / 3 deselected python_work_apple/pytest_package/mark/test_case.py .run [100%] ==================== 1 passed, 3 deselected in 0.01 seconds ====================
只執行用runcase標記的測試,cmd執行的時候,加個-m 引數,指定引數值runcase
如果不想執行runcase標記的case的時候,只需要在配置裡面新增一個not runcase,比如以下:
#!/usr/bin/env/python # -*-coding:utf-8-*- import pytest def test_run(): print("run") @pytest.mark.runtest def test_not_run(): print("run") def test_not_run1(): print("run") class TestClass: def test_method(self): pass
執行結果:三個執行完,一個沒有被選擇
Testing started at 14:11 ... /usr/local/bin/python3.7 "/Applications/PyCharm CE.app/Contents/helpers/pycharm/_jb_pytest_runner.py" --path /Users/newcomer/gitByMyself/python_work_apple/pytest_package/mark/test_case_01.py -- "-m=not runtest" Launching py.test with arguments -m=not runtest /Users/newcomer/gitByMyself/python_work_apple/pytest_package/mark/test_case_01.py in /Users/newcomer/gitByMyself ============================= test session starts ============================== platform darwin -- Python 3.7.0, pytest-3.9.1, py-1.7.0, pluggy-0.8.0 rootdir: /Users/newcomer/gitByMyself, inifile: plugins: datadir-1.2.1, allure-adaptor-1.7.10collected 4 items / 1 deselected python_work_apple/pytest_package/mark/test_case_01.py .run .run . [100%] ==================== 3 passed, 1 deselected in 0.02 seconds ==================== Process finished with exit code 0
cmd命令:pytest -v -m “not runtest”
-v 註定的函式節點id:
如果想指定執行某個.py模組下,類裡面的一個用例,如:TestClass裡面testmethod用例
每個test開頭(或_test結尾)的用例,函式(或方法)的名稱就是用例的節點id,指定節點id執行用-v 引數
$ pytest -v test_server.py::TestClass::test_method
當然也能選擇執行整個class
$ pytest -v test_server.py::TestClass
也能選擇多個節點執行,多個節點中間空格隔開
$ pytest -v test_server.py::TestClass test_server.py::test_send_http
-k配皮用例名稱
可以使用-k命令列選項指定在匹配用例名稱的表示式
pytest -v -k not_run
也可以執行所有的測試,根據用例名稱排除掉某些用例:
pytest -k “not not_run” -v
也可以同時選擇匹配 “run” 和“not not_run”
pytest -k “run and not not_run” -v