代码之家  ›  专栏  ›  技术社区  ›  Super Kai - Kazuya Ito

@pytest中pytest.mark.skip与@pytest.mark.xfail的比较

  •  0
  • Super Kai - Kazuya Ito  · 技术社区  · 2 年前

    我有 @pytest.mark.skip s test1() @pytest.mark.xfail s test2() 两者都是 True 如下图所示:

    import pytest
    
    @pytest.mark.skip
    def test1():
        assert True
    
    @pytest.mark.xfail
    def test2():
        assert True
    

    然后,我跑了 pytest ,则输出如下:

    $ pytest
    =================== test session starts ===================
    platform win32 -- Python 3.9.13, pytest-7.4.0, pluggy-1.2.0
    django: settings: core.settings (from ini)
    rootdir: C:\Users\kai\test-django-project2
    configfile: pytest.ini
    plugins: django-4.5.2
    collected 2 items                                 
    
    tests\test_store.py sX                               [100%]
    
    ============== 1 skipped, 1 xpassed in 0.10s ============== 
    

    接下来,我有 @pytest.mark.skip s 测试1() @pytest.mark.xfail s test2() 两者都是 False 如下图所示:

    import pytest
    
    @pytest.mark.skip
    def test1():
        assert False
    
    @pytest.mark.xfail
    def test2():
        assert False
    

    然后,我跑了 pytest ,则输出如下:

    $ pytest
    =================== test session starts ===================
    platform win32 -- Python 3.9.13, pytest-7.4.0, pluggy-1.2.0
    django: settings: core.settings (from ini)
    rootdir: C:\Users\kai\test-django-project2
    configfile: pytest.ini
    plugins: django-4.5.2
    collected 2 items
    
    tests\test_store.py sx                               [100%]
    
    ============== 1 skipped, 1 xfailed in 0.24s ==============
    

    那么,两者之间有什么区别呢 @pytest.mark.skip @pytest.mark.xfail ?

    1 回复  |  直到 2 年前
        1
  •  0
  •   MrBean Bremen    2 年前

    这些标记做不同的事情,有不同的目的,输出只是 你的小案子也是如此。

    测试与 xfail 标记是 expected to fail ,同时使用 skip 标记是 not executed 完全。

    目的不同。跳过的测试通常不会执行,因为某些条件目前尚未满足。更常见的是使用 skipif mark,这是有条件的,并且是自我解释的,但是 跳过 例如,标记可用于标记将来可能通过的测试。
    一个常见的原因是跳过因无法轻松修复的错误而失败的测试——在这种情况下,最好用相应的注释(可以在测试执行过程中显示)跳过测试,而不是仅仅将其注释掉。有时,测试是为尚未实现的未来功能编写的——基于同样的推理,以表明仍然缺少一些东西,并作为一种规范。

    预计会失败的测试可能使用频率较低。您的简单案例:

    @pytest.mark.xfail
    def test():
        assert False
    

    def test():
        assert True
    

    所以这真的没有意义。然而,在某些情况下,您希望显示特定测试将失败(而不是仅仅反转条件使其通过)。一个例子是回归测试,它表明如果某个参数没有设置,测试就会失败,而在正确设置后测试就会成功。 我自己的代码中的一个例子(in pyfakefs )这些测试表明 pyfakefs 如果不使用某些附加参数,则无法正确修补模块(例如,行为不符合预期)。

    我见过其他案例 xfail 已经为失败但应该成功的测试设置了标记-这是上述场景的另一个版本 跳过 。如果行为因修复而发生变化,这将使其更加明显——在这种情况下,测试将失败,因此变化更加明显。

    这两种标记还有其他用例,也取决于开发人员的偏好,但我希望你能理解要点。。。