Django 2.2-Testcase-client.logout()方法不会注销用户

时间:2019-07-20 01:18:26

标签: python django unit-testing testing

我正在为我的简单Django Web应用程序编写测试,检查用户是否可以正确登录和注销。观看次数:user_loginuser_logout

def user_login(request):
    if request.method == 'POST':
        email = request.POST.get('email address')
        password = request.POST.get('password')
        user = authenticate(username=email, password=password)
        if user:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect(reverse('main_page:index'))
        else:
            print("\nWARNING: invalid login detected\n\nemail: {}\npassword: {}\n".format(email, password))
            messages.error(request, 'Ivalid email or password. Try again.')
            return HttpResponseRedirect(reverse('users:login'))
    else:
        return render(request, 'users/login.html', {})


@login_required
def user_logout(request):
    messages.add_message(request, messages.INFO, 'See you Space Cowboy!')
    logout(request)
    return HttpResponseRedirect(reverse('main_page:index'))

然后进行自我测试:

class LoginLogoutTests(TestCase):

    def setUp(self):
        User = get_user_model()
        self.user = User.objects.create_user(email='test_user@email.com', password='S6y4Mb9Aqfu79YcF')
        print("\nsetup")

    def tearDown(self):
        self.user
        print("teardown\n")

    def test_login(self):
        # test if email is equal
        self.assertEqual(self.user.email, 'test_user@email.com')
        # test authentication
        self.assertTrue(self.user.is_authenticated)
        self.assertFalse(self.user.is_anonymous)
        # test if login request index.html
        self.assertTrue(self.client.get('main_page.index.html'))
        # test login with valid credentials
        self.assertTrue(self.client.login(email='test_user@email.com', password='S6y4Mb9Aqfu79YcF'))
        # test login with invalid credentials
        self.assertFalse(self.client.login(email='test_user@email.com', password='password'))
        print("test login")

    def test_logout(self):
        self.client.logout()
        self.assertTrue(self.user.is_authenticated)
        self.assertFalse(self.user.is_anonymous)
        print("test logout\n")

测试返回以下输出:

(venv) [user@manjaro django-project]$ ./manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).

setup
test login
teardown

setup
test logout
teardown

..
----------------------------------------------------------------------
Ran 2 tests in 0.515s

OK
Destroying test database for alias 'default'...

不应该通过最后的测试,但矛盾的是,它是通过的。这里出了什么问题?

编辑: 我重建了使用电子邮件作为登录名的用户模型。我使用了本教程:https://testdriven.io/blog/django-custom-user-model/

1 个答案:

答案 0 :(得分:0)

您尚未测试您的应用,您提供的那些视图与所提供的测试没有共同之处。您已经尝试测试Django本身,其TestCase内部和无法正确测试它:注销后执行与登录测试类似的操作,然后断言客户端无法访问索引页。

测试视图的正确方法是将客户端指向其相应的URL,即AnonymousUser和已记录的URL。