[Python] 選擇性的執行 pytest 的 Unit-test case

[Python] 選擇性的執行 pytest 的 Unit-test case

算是受到昨天 [Google Test] 選擇性的執行某些 Unit-test case 的啟發吧,

今天在跑 pytest 寫的 unit-test case 時,

突然也想到是不是有選項可以單跑某一個 test case…

 

當然如果是直接執行 py.test 的話,肯定是有選項的,

但我們的專案是自己寫一個 testproject.py,裡面呼叫了 pytest.main(args=sys.argv[1:]),

因此我從來沒有想過這個 testproject.py 其實繼承了 pytest 的命令列參數~

直接執行 testproject.py -h,果真跑出了 pytest 的選項:

testuser@localhost ~ $ python testproject.py -h
usage: testproject.py [options] [file_or_dir] [file_or_dir] [...]
positional arguments:
file_or_dir
general:
-k EXPRESSION         only run tests which match the given substring
expression. An expression is a python evaluatable
expression where all names are substring-matched
against test names and their parent classes. Example:
-k 'test_method or test other' matches all test
functions and classes whose name contains
'test_method' or 'test_other'. Additionally keywords
are matched to classes and functions containing extra
names in their 'extra_keyword_matches' set, as well as
functions which have names assigned directly to them.
-m MARKEXPR           only run tests matching given mark expression.
example: -m 'mark1 and not mark2'.
--markers             show markers (builtin, plugin and per-project ones).
-x, --exitfirst       exit instantly on first error or failed test.
--maxfail=num         exit after first num failures or errors.
--strict              run pytest in strict mode, warnings become errors.
-c file               load configuration from `file` instead of trying to
locate one of the implicit configuration files.
--fixtures, --funcargs
show available fixtures, sorted by plugin appearance
--pdb                 start the interactive Python debugger on errors.
--capture=method      per-test capturing method: one of fd|sys|no.
-s                    shortcut for --capture=no.
--runxfail            run tests even if they are marked xfail

 

像我想要單跑 test_set_data 這個 test case,可以加上 -k 選項:

testuser@localhost ~ python testproject.py -k test_set_data
========================= test session starts ==========================
collected 101 items
cmd/test_set.py::test_set_data[None-None-0] PASSED
cmd/test_set.py::test_set_data[not_exist-None-123] PASSED
=========== 99 tests deselected by '-ktest_set_data' ============
=============== 2 passed, 99 deselected in 0.88 seconds ===============

 

-k 選項裡面放的是部分字串,因此 -k set_data 可以跑所有名稱裡有 set_data 的 test case,

像是 test_set_data, test_set_data_aaa, test_bbb_set_data_ccc 都會跑到~

它還支援 or 的功能,例如 -k “aaa or bbb” 就可以去比對名稱中有 aaa 或是 bbb 的 test case,

蠻方便的喔~^^

 

(本頁面已被瀏覽過 1,121 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料