from django.test import TestCase class ExampleTest(TestCase): def test_addition(self): def addition(x,y): return x+y self.assertEqual(addition(1,1),2,'ass is failed') #断言函数加和运算
from index.models import Book, PubName def test_model(self): pub1=PubName.objects.create(pubname="程序帮出版社") #创建pubname实例, book=Book.objects.create(title='Servlet',price='35.00', retail_price='35.00',pub=pub1) self.assertTrue(book is not None) self.assertNotEqual(Book.objects.count(),8)#使用断言判断 self.assertEqual(Book.objects.count(),9)上述代码,我门做一下简单剖析,我们定义了 test_model 函数,并创建了普通用户以及书籍类实例对象,之后还是和之前操作一样,我们是使用断言的方式对今天的测试代码进行了有效的测试。
虽然这里涉及到了数据库操作,但是该操作并不会影响数据库中原有数据。这些测试用例是相互隔离的,每一个测试用例都运行在一个事务中。
from index.models import Book, PubName def test_view(self): pub1=PubName.objects.create(pubname="机械工业出版社") book=Book.objects.create(title='Jsp',price='25.00', retail_price='25.00',pub=pub1) response=self.client.get('/index/update_book/%d/'% book.id) response['X-Token']='C语言中文网' #自定义响应头 self.assertEqual(response.status_code,200) self.assertEqual(response[X-Token],'C语言中文网','it is not same')我们使用 self.client.get 方法实现了对相应视图函数的访问,然后使用断言的方法,并调用 response 响应对象的方法或者属性进行了相关的测试。
python manage.py test
我们可以在项目的 manage.py 文件目录下直接执行此命令,但是该命令会将所有的测试结果都输出,如果你的每个应用下都做了单元测试,这显然会给你造成很错乱的感觉,所以我们可以使用下面的命令进行相关的测试输出:python manage.py test -v 1 index.tests
如何你启动测试命令后,出现如下错误:django.db.utils.InternalError: (1366, "Incorrect...
这就们还需要在 settings.py 的 DATABASES 选项中添加如下配置:'TEST': { 'CHARSET': 'utf8', 'COLLATION': 'utf8_general_ci'}最后我们执行测试命令可得到如下的输出结果:
C:\Users\Administrator\Book\BookStore>python manage.py test index.tests Creating test database for alias 'default'... System check identified no issues (0 silenced). .PubName object (1) 增加了新的书籍 F增加了新的书籍 F ====================================================================== FAIL: test_model (index.tests.ExampleTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\Administrator\Book\BookStore\index\tests.py", line 26, in test_model self.assertEqual(Book.objects.count(),9) AssertionError: 1 != 9 ====================================================================== FAIL: test_view (index.tests.ExampleTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\Administrator\Book\BookStore\index\tests.py", line 34, in test_view self.assertEqual(response['X-Token'],'C语言中文网','it is not same') AssertionError: '=?utf-8?b?Q+ivreiogOS4reaWh+e9kQ==?=' != 'C语言中文网' - =?utf-8?b?Q+ivreiogOS4reaWh+e9kQ==?= + C语言中文网 : it is not same ---------------------------------------------------------------------- Ran 3 tests in 0.033s FAILED (failures=2) Destroying test database for alias 'default'...Django 项目的单元测试到这里就讲解完毕了,我们通过三节知识的讲解,让大家认识了什么是单元测试、单元测试模块 unittest 是如何应用的以及 Python unittest 模块如何在 Django 中进行使用,希望大家通过这些介绍掌握知识的精髓。
Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有