Python学习自动化测试

Django test.py 正确解锁方式

2022-03-09  本文已影响0人  Kewings
  1. 首先Django的test也是直接调用的unittest规则,所以,建议在有顺序执行的TestCase中使用0-9, a-z这样的顺序进行一些排序
    例如:
test_01_registerEquip_get
test_02_registerEquip_post_rightdata
test_03_registerEquip_post_errordata
  1. setUpClass/tearDownClass会被调用一次,setUp/tearDown每个函数执行的时候都会被调用
    所以需要一开始就初始化的数据内容,建议放在setUpClass,并且做好保护,譬如设置已存在就不再create数据
    @classmethod
    def setUpClass(cls) -> None:
        eType_num = EquipType.objects.filter(equip_type='TestType1').count()
        if eType_num == 0:
            eType = EquipType.objects.create(equip_type='TestType1')
        else:
            eType = EquipType.objects.get(equip_type='TestType1')
        eqs_num = Equip.objects.filter(name='TestDevice1', equip_type=eType).count()
        if eqs_num == 0:
            eqs = Equip.objects.create(name='TestDevice1', equip_type=eType, status='free')
        else:
            eqs = Equip.objects.get(name='TestDevice1')
  1. HttpResponse和JsonResponse不能直接判断,需要做一些转换读取
def test_01_registerEquip_get(self):
    res = self.client.get('/equip/API/RegisterEquip/', format='json')
    res_dict = json.loads(str(res.content,'utf-8'))
    self.assertEqual(res_dict['ReturnCode'], 200)
  1. 每个测试函数运行的数据都会被建立及被摧毁,所以如果函数间存在依赖关系的话,得在有依赖的函数中再次引用被依赖函数的数据构建方法
def test_05_updateEquipStatus_post_rightdata(self):
    res = self.client.post('/equip/API/UpdateEquipStatus/', data=self.equipStatus_data)
    res_dict = json.loads(str(res.content,'utf-8'))
    self.assertEqual(res_dict['ReturnCode'], 200)

def test_08_updateTaskInfo_post_rightdata(self):
    res1 = self.client.post('/equip/API/UpdateEquipStatus/', data=self.equipStatus_data)
    res = self.client.post('/equip/API/UpdateTaskInfo/', data=self.taskInfo_data)
    res_dict = json.loads(str(res.content,'utf-8'))
    self.assertEqual(res_dict['ReturnCode'], 200)
  1. 注意点:构建原变量的错误变量时,记得用.copy的方式构建,避免直接赋值,会改变原来的引用变量中的结果
# 正确的赋值方式
reg_errordata = self.register_data.copy()
reg_errordata['equipType'] = 'TestType2'

# 错误的赋值方式,self.register_data被改变了
reg_errordata = self.register_data
reg_errordata['equipType'] = 'TestType2'
上一篇 下一篇

猜你喜欢

热点阅读