2

我正在使用django- webtest (v1.5.6) 来测试装饰器是否限制了对经过身份验证的用户的视图访问。

我的看法很简单:

@active_account_required
def homepage(request):
    return render(request, 'accounts/account_homepage.html', {
        'user': request.user,
        })  

active_account_required装饰器是:

def active_account_required(function = None):
    """ 
    Check the user is both logged in and has a valid, activated user account.

    If a user tries to access a view protected by this decorator, they will be
    redirected accordingly.

    See http://passingcuriosity.com/2009/writing-view-decorators-for-django/
    """

    def _dec(view_func):
        def _view(request, *args, **kwargs):
            if request.user.is_anonymous():
                return HttpResponseRedirect(reverse_lazy('auth_login'))
            if not request.user.get_profile().is_activated():
                return HttpResponseRedirect(reverse_lazy('registration_activation_incomplete'))
            return view_func(request, *args, **kwargs)

        _view.__name__ = view_func.__name__
        _view.__dict__ = view_func.__dict__
        _view.__doc__ = view_func.__doc__

        return _view

    if function is None:
        return _dec
    else:
        return _dec(function)

我的测试方法是

class AccountViewsTests(WebTest):
    def test_activated_user_can_access_account_homepage(self):
        """ 
        Test an activated user can access the account homepage
        """
        user = G(User)
        user.get_profile().datetime_activated = timezone.now()
        res = self.app.get(reverse('account_homepage'), user = user)
        pdb.set_trace()
        self.assertTemplateUsed(res, 'accounts/account_homepage.html',
                'Activated account did not access account homepage correctly')

(用户对象是使用G来自django-dynamic-fixture的函数创建的)

运行测试时,装饰器阻止访问homepage视图。

你可以看到我pdb用来检查对象。User 是一个有效的用户对象,应该通过active_account_required装饰器中的所有测试:

(Pdb) user
<User: 2>
(Pdb) user.is_anonymous()
False
(Pdb) user.get_profile().is_activated()
True

尽管用户是正确的,但根据装饰器代码,响应self.app.get(reverse('account_homepage'), user = user)是 302 重定向到URL:registration_activation_incomplete

(Pdb) res
<302 FOUND text/html location: http://localhost:80/accounts/registration/activate/incomplete/ no body>

在 WebTest 请求中似乎未正确发送用户对象,但这与django-webtest 文档相匹配。我也尝试通过用户名传递用户,user='2'但得到相同的结果。

有任何想法吗?

4

1 回答 1

0

糟糕 - 问题是我在设置激活时间戳后忘记保存我的用户配置文件!

将测试代码更改为:

user = G(User)
user.get_profile().datetime_activated = timezone.now()
user.get_profile().save()
res = self.app.get(reverse('account_homepage'), user = user)

即添加user.get_profile().save()让它工作:)

对不起,噪音。

于 2013-02-24T17:51:57.817 回答