0
点赞
收藏
分享

微信扫一扫

基于django的单元测试


1.【知道】认识单元测试

  • 单元测试:测类、方法、函数,测试最小单位
  • 由于django的特殊性,通过接口测单元,代码逻辑都放在类视图中
  • 单元测试好处
  • 消灭低级错误
  • 快速定位bug(有些分支走不到,通过单元测试提前测出问题)
  • 提高代码质量(测试后顺便优化代码)

2.【掌握】编写和运行django的单元测试

  • django环境
  • 数据库编码
  • 数据库用户权限(需要建临时数据库、删临时数据库)
  • 每个应用,自带tests.py
  • 类,继承django.test.TestCase
  • 前置、后置方法
  • test开头的测试用例
  • 集成在django的项目文件里,更多是开发人员写django自动的测试
  • 运行
  • 进入manage.py目录
  • 命令
  • python manage.py test 指定目录下的某个文件

3. TestCase类

3.1【知道】前后置方法运行特点

django.test.TestCase类主要由​​前、后置处理方法​​​ 和​​test开头的方法​​组成

  • ​test开头的方法​​ 是编写了测试逻辑的用例
  • ​setUp​​方法 (名字固定)在每一个测试方法执行之前被调用
  • ​tearDown​​方法(名字固定) 在每一个测试方法执行之前被调用
  • ​setUpClass​类方法(名字固定)在整个类运行前执行只执行一次
  • ​tearDownClass​类方法(名字固定)在调用整个类测试方法后执行一次

from django.test import TestCase

class MyTest(TestCase):
@classmethod
def setUpClass(cls):
print('setUpClass')

@classmethod
def tearDownClass(cls):
print('tearDownClass')

def setUp(self) -> None:
print('setUp')

def tearDown(self) -> None:
print('tearDown')

def test_xxx(self):
print('测试用例1')

def test_yyy(self):
print('测试用例2')

# python manage.py test meiduo_mall.apps.users.test_code

3.2【掌握】setUpClass 和 tearDownClass应用场景

  • 写测试代码:放在test开头的方法

# 定义 setUpClass: 用户登录
# 定义 tearDownClass: 用户退出
# 定义测试方法:获取用户信息、获取用户浏览器记录、获取用户地址列表

from django.test import TestCase
import requests


class MyTest(TestCase):
s = None # 类属性

@classmethod
def setUpClass(cls):
print('setUpClass')

user_info = {
"username": "mike123",
"password": "chuanzhi12345",
"remembered": True
}

# 1. 创建requests.Session()对象
# cls.s类属性的s对象
cls.s = requests.Session()

# 登陆
# json以json格式发送请求
r = cls.s.post('http://127.0.0.1:8000/login/', json=user_info)
print('登陆结果=', r.json())

@classmethod
def tearDownClass(cls):
print('tearDownClass')
r = cls.s.delete('http://127.0.0.1:8000/logout/')
print('登出结果=', r.json())


def test_1_info(self):
r = self.s.get('http://127.0.0.1:8000/info/')
print('用户结果=', r.json())

def test_2_browse_histories(self):
r = self.s.get('http://127.0.0.1:8000/browse_histories/')
print('浏览记录结果=', r.json())

def test_2_browse_addresses(self):
r = self.s.get('http://127.0.0.1:8000/addresses/')
print('地址结果=', r.json())

举报

相关推荐

0 条评论