我正在使用 pytest 测试嵌入式系统的 python 模型。要测试的功能因平台而异。 (我在此上下文中使用“平台”来表示嵌入式系统类型,而不是操作系统类型)。
组织我的测试最直接的方法是根据平台类型将它们分配到目录。
/platform1
/platform2
/etc.
pytest/platform1
由于许多功能跨平台重叠,这很快就变得难以支持。从那以后,我将我的测试移到了一个目录中,每个功能区域的测试分配给一个文件名(例如 test_functionalityA.py)。 然后,我使用 pytest 标记来指示文件中的哪些测试适用于给定平台。
@pytest.mark.all_platforms
def test_some_functionalityA1():
...
@pytest.mark.platform1
@pytest.mark.platform2
def test_some_functionlityA2():
...
虽然我喜欢让“conftest”自动检测平台类型并只运行适当的测试,但我已经听天由命地指定要在命令行上运行哪些测试。
pytest -m "(platform1 or all_platforms)"
问题:(终于!)
有没有办法简化事情并让 pytest 默认运行所有未标记的测试,另外所有测试都通过命令行上的“-m”传递?
例如: pytest -m "platform1"
是否会运行标记为@pytest.mark.platform1 的测试以及所有标记为@pytest.mark.all_platforms 的测试,甚至所有根本没有@pytest.mark 的测试?
考虑到大量的共享功能,能够删除 @pytest.mark.all_platforms 行将是一个很大的帮助。
最佳答案
让我们来解决整个问题。我认为您可以将 conftest.py 文件与您的测试一起放置,它会小心跳过所有不匹配的测试(未标记的测试将始终匹配,因此永远不会被跳过)。我在这里使用 sys.platform,但我相信您有不同的方法来计算您的平台值(value)。
# content of conftest.py
#
import sys
import pytest
ALL = set("osx linux2 win32".split())
def pytest_runtest_setup(item):
if isinstance(item, item.Function):
plat = sys.platform
if not hasattr(item.obj, plat):
if ALL.intersection(set(item.obj.__dict__)):
pytest.skip("cannot run on platform %s" %(plat))
有了这个你可以像这样标记你的测试::
# content of test_plat.py
import pytest
@pytest.mark.osx
def test_if_apple_is_evil():
pass
@pytest.mark.linux2
def test_if_linux_works():
pass
@pytest.mark.win32
def test_if_win32_crashes():
pass
def test_runs_everywhere_yay():
pass
如果你运行::
$ py.test -rs
然后你可以运行它并且会看到至少有两个测试被跳过并且总是 至少执行了一项测试::
然后你会看到两个测试被跳过,两个测试按预期执行::
$ py.test -rs # this option reports skip reasons
=========================== test session starts ============================
platform linux2 -- Python 2.7.3 -- pytest-2.2.5.dev1
collecting ... collected 4 items
test_plat.py s.s.
========================= short test summary info ==========================
SKIP [2] /home/hpk/tmp/doc-exec-222/conftest.py:12: cannot run on platform linux2
=================== 2 passed, 2 skipped in 0.01 seconds ====================
请注意,如果您通过这样的标记命令行选项指定平台::
$ py.test -m linux2
=========================== test session starts ============================
platform linux2 -- Python 2.7.3 -- pytest-2.2.5.dev1
collecting ... collected 4 items
test_plat.py .
=================== 3 tests deselected by "-m 'linux2'" ====================
================== 1 passed, 3 deselected in 0.01 seconds ==================
那么未标记的测试将不会运行。因此,这是一种将运行限制为特定测试的方法。
关于python - pytest 是否支持 "default"标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10906817/