无法在Django测试中登录

问题描述 投票:0回答:1

[尝试为旧版Django 1.11项目编写测试。该项目正在使用unittest软件包(我不知道这是标准的还是选择的)。

我正在尝试使用django.test.Client.force_login测试带有LoginRequiredMixin的视图,但是它没有没有。我已经将print(self.request.user)添加到mixin的调度方法中。无论是否使用AnonymousUser,它都会输出force_login。为什么它不起作用?

该测试(为便于阅读而简化:):

class CheckoutTest(TestCase):
    def test_successful_payment(self):
        user = UserAccount.objects.create(email='[email protected]', is_owner=True, is_customer=True)

        self.client.force_login(user)

        self.client.post('/subscription/buy/' + str(package.id) + '/', {
            ... redacted ...
        })

视图:

class BuyPackageView(LoginRequiredMixin, View):
    def post(self, request, *args, **kwargs):
        ... redacted ...
python django django-1.11
1个回答
0
投票

我的测试代码片段看起来像:

from django.test import TestCase
from rest_framework.test import APIClient
from mainapp.tests.test_helper import TestsHelper


class ProjectViewSetTestCase(TestCase):

    def setUp(self):
        self._client = APIClient(enforce_csrf_checks=False)
        self._test_helper.prepare_data()

    def tearDown(self):
        # do some custom clean-up

    def testCreateProjectWithoutKeyWords(self):

        # prepare current test data ...
        self._client.force_authenticate(user=user)
        # interact with REST API, if you need to switch user use logout
        self._client.logout()

   _client = None
© www.soinside.com 2019 - 2024. All rights reserved.