简体   繁体   English

Hot to pytest 装饰器被分配给多个函数

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

I read somewhere on SO that you should not test the decorator but the functionality of the wrapped function.我在某处读到 SO,您不应测试装饰器,而应测试包装函数的功能。 Nevertheless there might be a shorter way of testing whether a certain decorator is assigned to multiple functions.然而,可能有一种更短的方法来测试某个装饰器是否被分配给多个函数。

I have this decorator:我有这个装饰器:

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):
    ...

I have some tests to test the decorator function itself, eg:我有一些测试来测试装饰器函数本身,例如:

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."

Now I have about 20 FastAPI endpoints where I assigned this decorator.现在我有大约 20 个FastAPI端点,我在其中分配了这个装饰器。 I want to avoid to repeat the same tests (see example above and other tests) for each function.我想避免对每个函数重复相同的测试(参见上面的示例和其他测试)。 So something like this would be great:所以这样的事情会很棒:

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

You should be able to modify and parametrize test_check_user to check the same assert for every decorated function in one test.您应该能够修改和参数化 test_check_user 以检查一个测试中每个装饰函数的相同断言。 This is superior to just checking if a decorator is applied because, it validates the actual functional requirement of preventing non-admins from changing userId.这优于仅检查是否应用了装饰器,因为它验证了防止非管理员更改 userId 的实际功能需求。 Remember the goal of writing good tests is to protect you from your future self.请记住,编写好的测试的目标是保护您免受未来的自我影响。 While you currently feel you can infer a security feature from the presence of this decorator, can you be sure that this inference will always be true for the rest of the project's lifetime?虽然您目前认为您可以从这个装饰器的存在推断出一个安全特性,但您能确定这个推断在项目的剩余生命周期中总是正确的吗? Better to make sure that your security features actually behave as intended.最好确保您的安全功能实际上按预期运行。

@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