簡體   English   中英

在用 pytest 編寫的測試中執行不應該發生的斷言

[英]Performing an assertion in a test written with pytest that should not have occurred

下面是執行每個斷言的完整測試代碼。 出於一個原因,這對我來說是不直觀的。 如果變量 k 的值為 None 則 function t 拋出異常,因此不應執行調用 t 之后的代碼,並且應由上下文管理器捕獲異常。 但是,這不會發生,我不知道為什么。 並不是說它困擾我,它以這種方式執行甚至很棒,但我想知道為什么。

from contextlib import nullcontext as does_not_raise

import pytest


def t(k):
    if k:
        return k
    else:
        raise ValueError("Value")


@pytest.mark.parametrize("k, cntxt", [(None, pytest.raises(ValueError)), ("Value", does_not_raise())])
def test_t(k, cntxt):
    with cntxt as ex:
        kk = t(k)

        if k:
            assert kk == k
            assert ex is None
        else:
            assert kk is None
            assert str(ex.value) == "Value"

如果變量 k 的值為 None 則 function t 拋出異常,因此不應執行調用 t 之后的代碼,並且應由上下文管理器捕獲異常。

除非我誤解了你,否則我相信這正是正在發生的事情。 kNone的情況下,不會執行這些行:

            assert kk is None
            assert str(ex.value) == "Value"

為確保是這種情況,您可以將測試 function 更改為:

@pytest.mark.parametrize("k, cntxt", [(None, pytest.raises(ValueError)), ("Value", does_not_raise())])
def test_t(k, cntxt):
    with cntxt as ex:
        kk = t(k)

        if k is None:
            assert False

它不會失敗。

您可能希望像這樣將斷言移出上下文管理器

@pytest.mark.parametrize("k, cntxt", [(None, pytest.raises(ValueError)), ("Value", does_not_raise())])
def test_t(k, cntxt):
    with cntxt as ex:
        kk = t(k)

    if k:
        print("one")
        assert kk == k
        assert ex is None
    else:
        print("two")
        # Can't do this as kk was never assigned to anything
        # assert kk is None
        assert str(ex.value) == "Value"
$ pytest -s myfile.py
...
two
.
one
.
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM