当前位置:   article > 正文

Django 单元测试、全文检索_from django.test import testcase

from django.test import testcase

1.Django 单元测试

   Django 框架自带单元测试工具,在 Django 框架创建的应用中默认有一个用于单元测试的 test.py 文件,我们将单元测试代码写在 test.py 文件中。

(1)编写一个简单的测试案例

  1. from django.test import TestCase
  2. # Create your tests here.
  3. def add(a,b):
  4. return a + b
  5. if __name__ == '__main__':
  6. c = add(1,2)
  7. assert c == 3
  8. c = add(1.0,2)
  9. assert c == 3.0
  10. c = add(3,5)
  11. assert c == 9.0

   点击运行该文件,用例不通过会报错:

   

(2)使用 unittest 模块

  1. from django.test import TestCase
  2. import unittest
  3. # Create your tests here.
  4. def add(a,b):
  5. return a + b
  6. class AddTest(unittest.TestCase):
  7. def test_init(self):
  8. self.assertEqual(add(1,2),3)
  9. def test_float(self):
  10. self.assertEqual(add(1.0, 2), 3.0)
  11. def test_err(self):
  12. self.assertEqual(add(3,5),9.0)
  13. if __name__ == '__main__':
  14. unittest.main()

   点击运行: 

   

(3)使用 django 内置的单元测试

  1. from django.test import TestCase
  2. from .models import User
  3. # Create your tests here.
  4. class simpleTest(TestCase):
  5. # 测试前
  6. def setUp(self):
  7. User.objects.create(username='admin',password='123456',email='2309485764@qq.com',is_active=True)
  8. def test_createModelTest(self):
  9. user = User.objects.get(username='admin')
  10. print(user.username,user.password,user.email,user.is_active)
  11. self.assertIsNot(user,None)

   在项目目录下,运行:python manage.py test;

  

2.全文检索-搜索

   以之前做的博客项目为例,实现页面上方输入关键字搜索出相关的商品的功能。

(1)准备

   Haystack 是 django 的开源全文搜索框架(全文检索不同于特

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/44613
推荐阅读
相关标签
  

闽ICP备14008679号