簡體   English   中英

Hot to pytest 裝飾器被分配給多個函數

[英]Hot to pytest that a decorator is assigned to multiple functions

我在某處讀到 SO,您不應測試裝飾器,而應測試包裝函數的功能。 然而,可能有一種更短的方法來測試某個裝飾器是否被分配給多個函數。

我有這個裝飾器:

def check_user(func):
    """Only allow admins to change the user_id in the annotated function.

    Use as decorator: @check_user
    """

    @wraps(func)
    def wrapper(*args, **kwargs):
    ...

我有一些測試來測試裝飾器函數本身,例如:

def test_check_user(self):
    """Test the check user decorator if a non admin wants to overwrite the user."""
    with pytest.raises(ValueError) as ex:

        @check_user
        def foo(login: str, userId: str):
            return True

        foo(login="Foo", userId="Bar")

    assert ex.value.args[0] == "Only admin users may overwrite the userId."

現在我有大約 20 個FastAPI端點,我在其中分配了這個裝飾器。 我想避免對每個函數重復相同的測試(參見上面的示例和其他測試)。 所以這樣的事情會很棒:

@pytest.mark.parametrize("method", ["foo", "bar", "gaga", ....])
def test_decorated_methods(self, method):
    assert assigned(check_user, method)  # or so

您應該能夠修改和參數化 test_check_user 以檢查一個測試中每個裝飾函數的相同斷言。 這優於僅檢查是否應用了裝飾器,因為它驗證了防止非管理員更改 userId 的實際功能需求。 請記住,編寫好的測試的目標是保護您免受未來的自我影響。 雖然您目前認為您可以從這個裝飾器的存在推斷出一個安全特性,但您能確定這個推斷在項目的剩余生命周期中總是正確的嗎? 最好確保您的安全功能實際上按預期運行。

@pytest.mark.parametrize("method,args,kwargs", [("myfunc", ["Foo"], {})])
def test_cant_change_id_if_not_admin(func, args, kwargs):
    kwargs["userId"]="Bar"
    with pytest.raises(ValueError) as ex:
        func(*args, **kwargs)
    assert ex.value.args[0] == "Only admin users may overwrite the userId."

暫無
暫無

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

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