编写单元测试
blog\tests.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from datetime import datetime
from django.test.client import Client
from blog.models import BlogPost
# Create your tests here.
class BlogPostTest(TestCase):
def test_obj_create(self):
BlogPost.objects.create(title='raw title',
body='raw body', timestamp=datetime.now())
self.assertEqual(1, BlogPost.objects.count())
self.assertEqual('raw title', BlogPost.objects.get(id=1).title)
def test_home(self):
reponse = self.client.get('/blog/')
self.failUnlessEqual(reponse.status_code, 200)
def test_slash(self):
reponse = self.client.get('/')
self.assertIn(reponse.status_code, (301, 302))
def test_empty_create(self):
reponse = self.client.get('/blog/create/')
self.assertIn(reponse.status_code, (301, 302))
def test_post_create(self):
reponse = self.client.post('/blog/create/',{'title':'post title', 'body':'post body'})
self.assertIn(reponse.status_code, (301, 302))
self.assertEqual(1, BlogPost.objects.count())
self.assertEqual('post title', BlogPost.objects.get(id=1).title)
执行测试
>manage.py test
测试结果
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
GET
None
None
..C:\Python27\lib\site-packages\django-1.11.16-py2.7.egg\django\db\models\fields
\__init__.py:1451: RuntimeWarning: DateTimeField BlogPost.timestamp received a n
aive datetime (2019-05-14 11:00:35.700000) while time zone support is active.
RuntimeWarning)
.POST
post title
post body
C:\Python27\lib\site-packages\django-1.11.16-py2.7.egg\django\db\models\fields\_
_init__.py:1451: RuntimeWarning: DateTimeField BlogPost.timestamp received a nai
ve datetime (2019-05-14 11:00:35.707000) while time zone support is active.
RuntimeWarning)
..
----------------------------------------------------------------------
Ran 5 tests in 0.053s
OK
Destroying test database for alias 'default'...