gpt4 book ai didi

python - Django 测试登录/注销

转载 作者:太空宇宙 更新时间:2023-11-03 11:28:13 25 4
gpt4 key购买 nike

我正在测试本教程中的一个 Django 应用程序:http://tutorial.djangogirls.org/en/django_admin/README.html

我已经根据示例创建了一个测试:

from django.test import TestCase, Client, LiveServerTestCase
from django.utils import timezone
from .models import Post
from django.contrib.auth.models import User

####Lines removed for brevity####

class AdminTest(LiveServerTestCase):
fixtures = ['users.json']

def setUp(self):
self.client = Client()

def test_login(self):
# Get login page
response = self.client.get('/admin/')

# Check response code
self.assertEquals(response.status_code, 200)

# Check 'Log in' in response
self.assertTrue('Log in' in response.content)

# Log the user in
self.client.login(username='XXX', password="XXX")

# Check response code
response = self.client.get('/admin/')
self.assertEquals(response.status_code, 200)

# Check 'Log out' in response
self.assertTrue('Log out' in response.content)

def test_logout(self):
# Log in
self.client.login(username='XXX', password="XXX")

# Check response code
response = self.client.get('/admin/')
self.assertEquals(response.status_code, 200)

# Check 'Log out' in response
self.assertTrue('Log out' in response.content)

# Log out
self.client.logout()

# Check response code
response = self.client.get('/admin/')
self.assertEquals(response.status_code, 200)

# Check 'Log in' in response
self.assertTrue('Log in' in response.content)

然而,当运行 python manage.py test 时,我得到了这个输出:

Creating test database for alias 'default'...
.FE
======================================================================
ERROR: test_logout (blog.tests.AdminTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\shenk\Documents\Programming\django_projects\djangogirls\blog\tests.py", line 80, in test_logout
self.assertTrue('Log out' in response.content)
TypeError: Type str doesn't support the buffer API

======================================================================
FAIL: test_login (blog.tests.AdminTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\shenk\Documents\Programming\django_projects\djangogirls\blog\tests.py", line 56, in test_login
self.assertEquals(response.status_code, 200)
AssertionError: 302 != 200

----------------------------------------------------------------------

我得到了这个 302 响应代码,也就是重定向,我该如何调整这两个测试才能使它们通过并实际可用?

还有一个附带问题...我如何打印/检查 response.content 中的数据,因为打印到 STDOUT 似乎在测试中不起作用?

我在测试登录时发现了一个类似的问题,但问题是他们在创建没有密码的用户时,我的用户已经通过 createsuperuser 创建了。

最佳答案

看起来问题是我在注销后测试 200 代码,当时它将我重定向到另一个页面。要解决这个问题,我应该为 304 断言 Equals,然后再次为重定向页面上的 200 断言。这似乎已经解决了。

关于python - Django 测试登录/注销,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29569676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com