【发布时间】:2018-02-20 09:43:20
【问题描述】:
我正在尝试在 Django 项目中将unit-test 写入我的create function。这是我第一次创建单元测试的经验。为什么我不能创建新数据?从错误中我了解到测试数据库中没有文章。我哪里做错了?
tests.py:
class ArticleViewTestCase(TestCase):
def setUp(self):
self.user = User.objects.create(
username='user',
email='user@gmail.com',
password='password'
)
self.client = Client()
def test_article_create(self):
self.assertTrue(self.user)
self.client.login(username='user', password='password')
response = self.client.get('/article/create/')
self.assertEquals(response.status_code, 200)
with open('/home/nurzhan/Downloads/planet.jpg', 'rb') as image:
imageStringIO = StringIO(image.read()) # <-- ERROR HERE
response = self.client.post(
'/article/create/',
content_type='multipart/form-data',
data={
'head': 'TEST',
'opt_head': 'TEST',
'body': 'TEST',
'location': 1,
'public': True,
'idx': 0,
'image': (imageStringIO, 'image.jpg')
},
follow=True
)
self.assertEqual(response.status_code, 200)
self.assertEqual(Article.objects.all().count(), 1)
错误:
Traceback (most recent call last):
File "/home/nurzhan/CA/article/tests.py", line 26, in test_article_create
imageStringIO = StringIO(image.read())
TypeError: 'module' object is not callable
【问题讨论】:
-
默认reposne创建返回
201状态,看看你的回复,为什么是200? -
你的意思是我需要使用
self.assertEquals(response.status_code, 201)? -
是的,你是对的
-
在控制台中我注意到
post method返回200。看:[12/Sep/2017 06:36:07] "POST /article/create/ HTTP/1.1" 200 1866所以我认为 200 状态是正确的。最后2行有问题。你对此有什么想法吗? -
有时
200状态返回错误消息。
标签: python django python-2.7 unit-testing django-1.11