以前接口测试都是用postman或者浏览器手动搞,费时费力,最近重构,把测试方法也梳理一下。
项目主要功能就是对数据库的增删改查,还有调用openstack接口,对于另一套系统采用的方式是自己写一套mock系统对调用进行返回模拟,暂时忽略不表
1.TestCase 类的结构
from django.test import TestCase
class Demo(TestCase):
# 最先执行
def setUp(self):
print('setUp')
# 最后执行
def tearDown(self):
print('tearDown')
def test_demo(self):
print('test_demo')
def test_demo_2(self):
print('test_demo2')
输出:
setUp
test_demo
tearDown
.setUp
test_demo2
tearDown
测试过程中还会自动创建测试数据库,测试完成后自动销毁
2.利用TestCase测试接口
假设路由,视图函数,models等等都已经写好了
from django.test import TestCase
from django.urls import reverse
from account.models import User
from mixer.backend.django import mixer
class RuleViewApiTestCase(TestCase):
def setUp(self):
# mixer这个模块,这个模块会根据你定义的模型和模型的字段来随机生成测试数据,包括这个数据的外键数据。 这样在我们这种层级非常多的关系型数据就非常的方便,否则需要一层一层的去生成数据。
self.user = mixer.blend(User)
self.user.uuid = 'fsfasfsa'
self.user.save()
def test_user_query_api(self):
# django.urls.reverse函数和在路由设置的name来得到请求的地址
url = reverse('user_query')
# 发送请求
response = self.client.get(url)
self.assertEqual(response.status_code, 403)
data = {'login': 0}
# 如果需要携带参数只需要传入data参数
response = self.client.get(url, data)
# 检查响应内容是否正确
self.assertEqual(response.status_code, 200)
res_data = response.json().get('results')
print(res_data)
print(type(res_data))
self.assertEqual(len(res_data), 1)
def tearDown(self):
print()
more about testing in Django:https://docs.djangoproject.com/en/2.2/topics/testing/