今日状态:保持学习 | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
打卡学习 | 星期一 | 星期二 | 星期三 | 星期四 | 星期五 | 星期六 | 星期日 | ||||
成功 | 成功 | 成功 | 成功 |
from django.db import models
# Create your models here.
from django.db import models
from utils.base_models import BaseModel
class Testcases(BaseModel):
name = models.CharField('用例名称', max_length=50, unique=True, help_text='用例名称')
interface = models.ForeignKey('interfaces.Interfaces', on_delete=models.CASCADE,
help_text='所属接口')
include = models.TextField('前置', null=True, help_text='用例执行前置顺序')
author = models.CharField('编写人员', max_length=50, help_text='编写人员')
request = models.TextField('请求信息', help_text='请求信息')
class Meta:
db_table = 'tb_testcases'
verbose_name = '用例信息'
verbose_name_plural = verbose_name
ordering = ('id',)
def __str__(self):
return self.name
根据列表页面知需要输出用例id、用例名称、所属项目、所属接口、测试人员
根据增加用例页面需要输入项目id、接口id、前置用例、请求信息、测试人员、接口信息、用例名称
1、项目表和用例表没有直接的关系,五福直接关联,需要用接口表去关联
2、当一个序列化器类中需要另一个序列化器中的某些字段,需要自定义序列化器类作为另外一个序列化器中的字段来使用
3、注意pid和iid,输出的是项目名称和接口名称,输入的是项目id和接口id
4、需要校验pid和iid(a、通过iid校验接口表中有没有这条数据,通过pid校验项目表中有没有这条数据;b、需要校验接口表中id=iid和project_id=pid是否存在)
def test_pid(value):
num=Projects.objects.filter(id=value).count()
if not num:
raise serializers.ValidationError('所传的项目id不存在')
return value
def test_iid(value):
num=Interfaces.objects.filter(id=value).count()
if not num:
raise serializers.ValidationError('所传的接口id不存在')
return value
class InterfacesProjectsModelSerializer(serializer.ModelSerializer):
project=serializers.CharField(label='接口所属项目',help_text='接口所属项目',read_only=True)
pid=serializers.IntegerField(label='项目id',help_text='项目id',write_only=True,validators=[test_pid])
iid=serializers.IntegerField(label='接口id',help_text='接口id',write_only=True,validators=[test_iid])
class Meta:
model=Interfaces
fields=['name','project','pid','iid']
extra_kwargs={
'name':{
'read_only':True
}
}
def validate(self,attrs):
result=Interfaces.objects.filter(id=attrs.get('iid'),project_id=attrs.get('pid')).exists()
if not result:
raise serializers.ValidationError('所属项目id和接口id不匹配')
return attrs
class TestcasesSerializer(serializers.ModelSerializer)
interface=InterfacesProjectsModelSerializer(label='用例所属接口信息',help_text='用例所属接口信息')
class Meta:
model=Testcases
exclude=['create_time','update_time']
extra_kwargs={
'include':{
'write_only':True
},
'request':{
'write_only':True
}
}
def to_internal_value(self,data):
response=super().to_internal_value(data)
iid=data.get('interface').get('iid')
response['interface']=Interfaces.objects.get(id=iid)
return response
1、校验通过后,data为
{data:{‘interface’:{‘pid’:1,‘iid’:2}},......
}
2、创建数据时,会报错;因为创建用例模型对象需要传入接口的模型对象或者是接口的id
3、重写to_interval_value(data)方法;
def to_internal_value(self,data):
response=super().to_internal_value(data)
iid=data.get('interface').get('iid')
response['interface']=Interfaces.objects.get(id=iid)
return response
或者
def to_internal_value(self, data):
response=super().to_internal_value(data)
iid = data.get('interface').get('iid')
response['interface'] = Interfaces.objects.get(id=iid)
return response
import json
import os
from datetime import datetime
from django.shortcuts import render
# Create your views here.
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from django.conf import settings
from envs.models import Envs
from testcases.models import Testcases
from testcases.serializers import TestcasesModelSerializer, TestcasesRunSerializer
from utils import handle_datas, common
from utils.mixins import RunMixin
from utils.pagination import PageNumberPagination
class TestcasesViewSet(ModelViewSet,RunMixin):
queryset = Testcases.objects.filter(is_delete=False)
serializer_class = TestcasesModelSerializer
pagination_class = PageNumberPagination
def retrieve(self, request, *args, **kwargs):
instance=self.get_object()
try:
testcase_include=json.loads(instance.include,encoding='utf-8')
except Exception:
testcase_include =dict()
try:
testcase_request=json.loads(instance.request,encoding='utf-8')
except Exception:
return Response({'msg':'用例格式有误','status':400},status=status.HTTP_400_BAD_REQUEST)
testcase_request_data = testcase_request.get('test').get('request')
# 获取json参数
json_data = testcase_request_data.get('json')
json_data_str = json.dumps(json_data, ensure_ascii=False)
# 获取extract参数
extract_data = testcase_request.get('test').get('extract')
extract_data = handle_datas.handle_data3(extract_data)
# 获取validate参数
validate_data = testcase_request.get('test').get('validate')
validate_data = handle_datas.handle_data1(validate_data)
# 获取variables参数
variables_data = testcase_request.get('test').get('variables')
variables_data = handle_datas.handle_data2(variables_data)
# 获取parameters参数
parameters_data = testcase_request.get('test').get('parameters')
parameters_data = handle_datas.handle_data3(parameters_data)
# 获取setup_hooks参数
setup_hooks_data = testcase_request.get('test').get('setup_hooks')
setup_hooks_data = handle_datas.handle_data5(setup_hooks_data)
# 获取teardown_hooks参数
teardown_hooks_data = testcase_request.get('test').get('teardown_hooks')
teardown_hooks_data = handle_datas.handle_data5(teardown_hooks_data)
data = {
"author": instance.author,
"testcase_name": instance.name,
"selected_configure_id": testcase_include.get('config'),
"selected_interface_id": instance.interface_id,
"selected_project_id": instance.interface.project_id,
"selected_testcase_id": testcase_include.get('testcases', []),
"method": testcase_request_data.get('method'),
"url": testcase_request_data.get('url'),
"param": handle_datas.handle_data4(testcase_request_data.get('params')),
"header": handle_datas.handle_data4(testcase_request_data.get('headers')),
"variable": handle_datas.handle_data2(testcase_request_data.get('data')),
"jsonVariable": json_data_str,
"extract": extract_data,
"validate": validate_data,
# 用例的当前配置(variables)
"globalVar": variables_data,
"parameterized": parameters_data,
"setupHooks": setup_hooks_data,
"teardownHooks": teardown_hooks_data
}
return Response(data,status=200)
def perform_destroy(self, instance):
instance.is_delete=True #软删除,没有真正的删除
instance.save()
def get_serializer_class(self):
if self.action=='run':
return TestcasesRunSerializer
else:
return super().get_serializer_class()
def get_testcase_qs(self):
return [self.get_object()]
from django.urls import path, include
from rest_framework import routers
from testcases.views import TestcasesViewSet
router=routers.SimpleRouter()
router.register(r'testcases',TestcasesViewSet)
urlpatterns=[
path('',include(router.urls))
]