【问题标题】:pytest-monkeypatch a decorator (not using mock / patch)pytest-monkeypatch 一个装饰器(不使用模拟/补丁)
【发布时间】:2018-12-30 04:26:01
【问题描述】:

我正在使用带有 monkeypatch 夹具的 pytest 编写一些测试。按照规则,我从正在使用它们的模块中导入要模拟的类和方法,而不是从源中。

我正在为其编写测试的应用程序是一个使用标准环境的 Google App Engine 应用程序。因此我必须使用 python 2.7,我使用的实际版本是 2.7.15 - pytest 版本是 3.5.0

到目前为止,一切都运行良好,但是在尝试模拟装饰器函数时遇到了问题。

从顶部开始。在一个名为 decorators.py 的 py 文件中,包含所有 auth 装饰器,包括我要模拟的装饰器。有问题的装饰器是一个模块函数,而不是类的一部分。

def user_login_required(handler):
    def is_authenticated(self, *args, **kwargs):
        u = self.auth.get_user_by_session()
        if u.access == '' or u.access is None:
            # return the response
            self.redirect('/admin', permanent=True)
        else:
            return handler(self, *args, **kwargs)
    return is_authenticated

装饰器应用于网络请求功能。在名为 handlers (handlers.UserDetails) 的文件夹中名为 UserDetails.py 的文件中的基本示例

from decorators import user_login_required

class UserDetailsHandler(BaseHandler):
    @user_login_required
    def get(self):
        # Do web stuff, return html, etc

在一个测试模块中,我正在这样设置测试:

from handlers.UserDetails import user_login_required

@pytest.mark.parametrize('params', get_params, ids=get_ids)
def test_post(self, params, monkeypatch):

    monkeypatch.setattr(user_login_required, mock_user_login_required_func)

问题在于monkeypatch 不允许我将单个函数作为目标。它希望目标是一个类,然后是要替换的方法名称,然后是模拟方法....

monkeypatch.setattr(WouldBeClass, "user_login_required", mock_user_login_required_func)

我试图调整代码,看看是否可以通过改变装饰器的导入和使用方式来绕过它:

import decorators

class UserDetailsHandler(BaseHandler):
    @decorators.user_login_required
    def get(self):
        # Do web stuff, return html, etc

然后在测试中我尝试像这样修补函数名称.....

from handlers.UserDetails import decorators

@pytest.mark.parametrize('params', get_params, ids=get_ids)
def test_post(self, params, monkeypatch):

    monkeypatch.setattr(decorators, "user_login_required" , mock_user_login_required_func)

虽然这段代码没有抛出任何错误,但当我逐步完成测试时,代码永远不会进入 mock_user_login_required_func。它总是进入现场装饰器。

我做错了什么?这是一个尝试对一般的装饰器进行修补的问题,或者模块中的单独功能可以不被修补吗?

【问题讨论】:

  • 修补装饰器的典型问题是,一旦导入模块,装饰器就会运行,修改函数并且永远不会为该函数再次运行。之后修补它没有效果。
  • 解释清楚,谢谢克劳斯。看起来我需要直接在装饰器中做一些事情来检测是否正在运行测试。我有一个想法......将进一步调查。

标签: python pytest monkeypatching


【解决方案1】:

看起来这里的快速答案只是移动您的处理程序导入,以便它在补丁之后发生。装饰器和被装饰的函数必须在单独的模块中,这样 python 在你修补它之前不会执行装饰器。

from decorators import user_login_required

@pytest.mark.parametrize('params', get_params, ids=get_ids)
def test_post(self, params, monkeypatch):

    monkeypatch.setattr(decorators, "user_login_required" , mock_user_login_required_func)
    from handlers.UserDetails import UserDetailsHandler

您可能会发现使用内置 unittest.mock 模块中的补丁功能更容易完成此操作。

【讨论】:

  • 将此标记为已接受的答案,因为它解决了手头的问题。
【解决方案2】:

由于这里提到的导入/修改陷阱,我决定避免尝试对这个特定的装饰器使用模拟。

目前我已经创建了一个夹具来设置环境变量:

@pytest.fixture()
def enable_fake_auth():
    """ Sets the "enable_fake_auth"  then deletes after use"""
    import os
    os.environ["enable_fake_auth"] = "true"
    yield
    del os.environ["enable_fake_auth"]

然后在装饰器中我修改了is_authenticated方法:

def is_authenticated(self, *args, **kwargs):
    import os
    env = os.getenv('enable_fake_auth')
    if env:
        return handler(self, *args, **kwargs)
    else:
        # get user from session
        u = self.auth.get_user_by_session()
        if u:
            access = u.get("access", None)
            if access == '' or access is None:
                # return the response
                self.redirect('/admin', permanent=True)
            else:
                return handler(self, *args, **kwargs)
        else:
            self.redirect('/admin?returnPath=' + self.request.path, permanent=True)

return is_authenticated

它没有回答我最初提出的问题,但我已将我的解决方案放在这里,以防它可以帮助其他人。正如 hoefling 所指出的,像这样修改生产代码通常是个坏主意,因此使用风险自负!

我在此之前的原始解决方案没有修改或模拟任何代码。它涉及创建一个虚假的安全 cookie,然后将其发送到测试请求的标头中。这将使对 self.auth.get_user_by_session() 的调用返回具有访问集的有效对象。我可能会回到这个。

【讨论】:

  • 提醒未来的读者:让生产代码在测试模式下表现不同是一个坏主意,也是一条非常危险的进入途径。请永远不要那样做。
【解决方案3】:

我有一个类似的问题,并通过在夹具中使用补丁来修补装饰器延迟的代码来解决它。为了提供一些上下文,我对一个 Django 项目有一个看法,该项目在视图函数上使用了一个装饰器来强制进行身份验证。有点像:

# myproject/myview.py

@user_authenticated("some_arg")
def my_view():
    ... normal view code ...

user_authenticated 的代码位于单独的文件中:

# myproject/auth.py

def user_authenticated(argument):
    ... code for the decorator at some point had a call to:
    actual_auth_logic()
    
    
def actual_auth_logic():
    ... the actual logic around validating auth ...

为了测试,我写了类似的东西:

import pytest
from unittest.mock import patch

@pytest.fixture
def mock_auth():
    patcher = patch("myproject.auth")
    mock_auth = patcher.start()
    mock_auth.actual_auth_logic.return_value = ... a simulated "user is logged in" value
    yield
    patcher.stop()

然后任何想要有效地跳过身份验证(即假设用户已登录)的视图测试都可以使用该夹具:

def test_view(client, mock_auth):
    response = client.get('/some/request/path/to/my/view')

    assert response.content == "what I expect in the response content when user is logged in"

当我想测试说未经身份验证的用户看不到经过身份验证的内容时,我只是省略了身份验证装置:

def test_view_when_user_is_unauthenticated(client):
    response = client.get('/some/request/path/to/my/view')

    assert response.content == "content when user is not logged in"

这有点脆弱,因为现在视图的测试与身份验证机制的内部相关(即,如果 actual_auth_logic 方法被重命名/重构,那将是糟糕的时期),但至少它被隔离为夹具。

【讨论】:

    猜你喜欢
    • 2022-11-11
    • 2021-11-21
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多