赞
踩
Django 框架自带单元测试工具,在 Django 框架创建的应用中默认有一个用于单元测试的 test.py 文件,我们将单元测试代码写在 test.py 文件中。
(1)编写一个简单的测试案例
- from django.test import TestCase
-
- # Create your tests here.
- def add(a,b):
- return a + b
-
- if __name__ == '__main__':
- c = add(1,2)
- assert c == 3
-
- c = add(1.0,2)
- assert c == 3.0
-
- c = add(3,5)
- assert c == 9.0
点击运行该文件,用例不通过会报错:

(2)使用 unittest 模块
- from django.test import TestCase
- import unittest
-
- # Create your tests here.
- def add(a,b):
- return a + b
-
- class AddTest(unittest.TestCase):
- def test_init(self):
- self.assertEqual(add(1,2),3)
-
- def test_float(self):
- self.assertEqual(add(1.0, 2), 3.0)
-
- def test_err(self):
- self.assertEqual(add(3,5),9.0)
-
- if __name__ == '__main__':
- unittest.main()

点击运行:
(3)使用 django 内置的单元测试
- from django.test import TestCase
- from .models import User
-
- # Create your tests here.
- class simpleTest(TestCase):
- # 测试前
- def setUp(self):
- User.objects.create(username='admin',password='123456',email='2309485764@qq.com',is_active=True)
-
- def test_createModelTest(self):
- user = User.objects.get(username='admin')
- print(user.username,user.password,user.email,user.is_active)
- self.assertIsNot(user,None)
在项目目录下,运行:python manage.py test;

以之前做的博客项目为例,实现页面上方输入关键字搜索出相关的商品的功能。
(1)准备
Haystack 是 django 的开源全文搜索框架(全文检索不同于特
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。