gpt4 book ai didi

python - 我可以创建一个 `pytest.mark.failif` 吗?

转载 作者:行者123 更新时间:2023-12-04 15:26:24 25 4
gpt4 key购买 nike

pytest 允许您在某些情况下(即在平台上)跳过测试:

@pytest.mark.skipif(sys.platform == "win32")
def test_foo(fixture):
assert bar(fixture)

有没有办法创建一个标记,使测试在特定条件下失败

@pytest.mark.failif(sys.platform == "win32")
def test_foo(fixture):
assert bar(fixture)

最佳答案

即使没有 pytest,您也可以编写一个简单的装饰器来执行此操作:

def failif(condition: bool, *, reason: str) -> Callable[[T], T]:
def failif_decorator(func: T) -> T:
@functools.wraps(func)
def failif_decorator_inner(*args: Any, **kwargs: Any) -> Any:
assert not condition, reason
return func(*args, **kwargs)
return cast(T, failif_decorator_inner)
return failif_decorator

用法是

@failif(sys.platform == 'win32', reason='we do not support windows')
def test():
...

对于特定于 pytest 的解决方案,您可以使用 hooks for registering marks 之一-- 尽管这涉及更多内容

关于python - 我可以创建一个 `pytest.mark.failif` 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62160217/

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