我正在测试本教程中的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创建。
答案 0 :(得分:0)
看起来问题是我在注销后测试200代码,当它将我重定向到另一个页面时。要修复我应该断言304的断言,然后再次重定向页面上的200。这似乎已经解决了。
答案 1 :(得分:0)
登录时..
# Get login page
response = self.client.get('/admin/login/')
# Check response code
self.assertEquals(response.status_code, 200)
当网址设置为'admin/'
时,它始终会重定向到admin/login/
。因此将response.status_code
返回为302(这意味着重定向)。这对Django Version 1.8.4来说是正确的