首页 > 解决方案 > 如何模拟在类属性中调用的函数?

问题描述

我有一个具有调用函数的属性的类:

users.mixins.py

from django.contrib import messages    
from ..utils.services import redirect_to_previous

class AdminRightsMixin:

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_admin:
            messages.warning(
                request, 'You must have administrator rights to view this page.'
            )
            redirect_to_previous(request)
        return super().dispatch(request, *args, **kwargs)

我想测试那个redirect_to_previous叫做,但我不知道如何在我的测试中模拟它。

例如:

@patch.object(AdminRightsMixin.dispatch, 'redirect_to_previous')
def test_admin_mixin(self, mock_class):
    // code

结果是AttributeError: <function AdminRightsMixin.dispatch at 0x000001D54FDB6430> does not have the attribute 'redirect_to_previous'

标签: pythonmockingpytestdjango-testingpython-unittest.mock

解决方案


推荐阅读