pytest之@pytest.mark.fail

看官方的介绍不是太能理解,做了个demo

@pytest.mark.xfail
def test_mark_xfail():
    assert 1==1

if __name__ == '__main__':
    pytest.main(['-s','test_01.py'])

输出是 1 xpassed in 0.03 seconds

@pytest.mark.xfail
def test_mark_xfail():
    assert 1==2

if __name__ == '__main__':
    pytest.main(['-s','test_01.py'])

输出是1 xfailed in 0.08 seconds =====

可以看到 mark.faild的用例 ,当用例执行true的时候,会返回xpassed,用例执行出现异常的时候,会返回xfailed.

总结下来就是结果当预期为失败,结果成功的,输出xpassed,预期为失败,实际也失败的,返回xfailed.

 

### pytest框架中的Mark用法 pytest提供了一种灵活的方式通过`mark`来标记测试函数,这使得可以对特定条件下的测试执行不同的操作。例如,在某些情况下可能只想运行带有特定标签的测试,或者跳过一些不适合当前环境配置的测试。 #### 基本语法 要给一个测试加上标志,可以在其定义前使用装饰器形式的应用程序接口(API)。最常用的内置marks包括`skip`, `skipif`, 和 `xfail`. 下面是一个简单的例子展示如何应用这些: ```python import pytest @pytest.mark.skip(reason="no way of currently testing this") def test_the_unknown(): pass ``` 对于更复杂的场景,比如基于条件决定是否应该跳过某个测试,则可利用`skipif`: ```python import sys import pytest @pytest.mark.skipif(sys.version_info < (3, 7), reason="requires python3.7 or higher") def test_functionality_only_on_python_37_and_above(): assert True ``` 当预期失败但仍希望记录下来以便后续审查时,`xfail`非常有用: ```python import pytest @pytest.mark.xfail(strict=True) def test_feature_that_is_broken(): # This will be marked as expected to fail. raise ValueError("This is a known issue.") ``` 除了上述预设外,还可以创建自定义的marks用于分类目的或其他用途: ```python import pytest @pytest.mark.webtest def test_example_website_response(): response = requests.get('http://example.com') assert response.status_code == 200 ``` 为了确保所有使用的非标准marks都被注册到pytest环境中,可以在项目的根目录下创建名为`conftest.py`文件,并在里面声明它们: ```python # content of conftest.py import pytest def pytest_configure(config): config.addinivalue_line( "markers", "webtest: mark tests that require web access." ) ``` 这样做的好处是可以让其他开发者清楚哪些是特殊的测试类别,并且有助于防止拼写错误造成的误解。 最后值得注意的是,可以通过命令行参数指定只运行具有某种特性的测试案例。例如,如果想要仅限于那些被标记为`webtest`的测试,那么就可以这样做: ```bash pytest -v -m webtest ``` 此命令会告诉pytest只挑选含有`@pytest.mark.webtest`修饰符的方法来进行验证[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值