gpt4 book ai didi

python - 如何将@pytest.mark 与基类一起使用?

转载 作者:太空狗 更新时间:2023-10-29 18:24:30 24 4
gpt4 key购买 nike

我使用的是 py.test 2.2.4,我的测试用例组织如下:

import pytest 

class BaseTests():
def test_base_test(self):
pass

@pytest.mark.linuxonly
class TestLinuxOnlyLocal(BaseTests):
pass

@pytest.mark.windowsonly
class TestWindowsOnly(BaseTests):
pass

class TestEverywhere(BaseTests):
pass

此设置的问题是第一个类的装饰器泄漏到第二个类中。当我如下创建 conftest.py 时:

import pytest
import sys

def pytest_runtest_setup(item):
print "\n %s keywords: %s" % (item.getmodpath(), item.keywords)
skip_message = None
if 'windowsonly' in item.keywords and not sys.platform.startswith('win'):
skip_message = "Skipped: Windows only test"

if 'linuxonly' in item.keywords and not sys.platform.startswith('linux'):
skip_message = "Skipped: Linux only test"

if skip_message is not None:
print skip_message
pytest.skip(skip_message)

当我执行此设置时,输出显示标记似乎堆叠起来:

$ py.test  --capture=no
========================================== test session starts ===========================================
platform linux2 -- Python 2.7.3 -- pytest-2.2.4
collected 3 items

test_cases.py
TestLinuxOnlyLocal.test_base_test keywords: {'linuxonly': <MarkInfo 'linuxonly' args=() kwargs={}>, 'test_base_test': True}
.
TestWindowsOnly.test_base_test keywords: {'linuxonly': <MarkInfo 'linuxonly' args=() kwargs={}>, 'test_base_test': True, 'windowsonly': <MarkInfo 'windowsonly' args=() kwargs={}>}
Skipped: Windows only test
s
TestEverywhere.test_base_test keywords: {'linuxonly': <MarkInfo 'linuxonly' args=() kwargs={}>, 'test_base_test': True, 'windowsonly': <MarkInfo 'windowsonly' args=() kwargs={}>}
Skipped: Windows only test
s

================================== 1 passed, 2 skipped in 0.01 seconds ===================================

所以我想了解这些标记如何在子类之间泄漏,以及如何修复/解决这个问题(测试用例将存在于基类中,但子类将设置必要的平台抽象)。

最佳答案

与其他 Python 测试框架(例如 unittest)相比,pytest 采用更面向功能的测试方法,因此类主要被视为组织测试的一种方式。

特别是,应用于类(或模块)的标记被转移到测试函数本身,并且由于未覆盖的派生类方法与基类方法是相同的对象,这意味着标记被应用于基类方法。

(技术细节:目前这发生在 _pytest.python.transfer_markers() 中,但不要依赖它。)

考虑使用 fixtures 而不是类继承封装特定于平台的测试设置。


一个更简单的解决方案可能是与类名进行比较,因为 py.test 将直接包含的类添加到项目关键字中:

if 'TestWindowsOnly' in item.keywords and not sys.platform.startswith('win'):
skip_message = "Skipped: Windows only test"

if 'TestLinuxOnly' in item.keywords and not sys.platform.startswith('linux'):
skip_message = "Skipped: Linux only test"

关于python - 如何将@pytest.mark 与基类一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18055439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com