import datetime from django.db.models import Q from rest_framework.response import Response from rest_framework.views import APIView from django.http import HttpResponse from TestLaboratory.settings import SOFTWARE_ROOT, CASE_FILE_EXPORT from apps.file.models import FileManager from apps.log.models import get_log, gen_log from apps.software.models import Software, Version from apps.task.models import TestCase from apps.user.middleware.rolecontrol import RoleControl from util_xlsx import write_to_xlsx from utils.util_add_id import gen_next_id import os from utils.util_file.util_fileio import write_file import logging logger = logging.getLogger('django') class VersionView(APIView): authentication_classes = [] # create version @staticmethod @RoleControl def post(request, software_id, *args, **kwargs): version_num = request.POST.get('version') file = request.FILES.get('file') # step1:判断版本所属软件是否存在 software = Software.objects.filter(id=software_id, delete=False) if not software: logger.error("软件已删除或不存在") return HttpResponse(status=404, content='软件已删除或不存在') software = software[0] # step2:判断版本是否存在 software_version = software.version_set.filter(number=version_num, delete=False) if software_version: logger.error("软件版本已存在,请修改版本号后重新上传") return HttpResponse(status=404, content='软件版本已存在,请修改版本号后重新上传') # step3:判断文件是否上传 if not file: logger.error("软件上传失败") return HttpResponse(status=404, content='软件上传失败') # step4:创建版本id id_version = None if not Version.objects.order_by('create_time').last(): id_version = "TestLaboratory_V1_Version_1" else: id_version = gen_next_id(Version.objects.order_by('create_time').last().id) # step5:设置创建时间和修改时间 create_time = update_time = datetime.datetime.now() # step6:上传文件: file_dir = SOFTWARE_ROOT + software.id + "/" + id_version + "/" + str(create_time) if not os.path.exists(file_dir): os.makedirs(file_dir) file_path = file_dir + "/" + file.name with open(file_path, 'wb') as f: f.write(file.read()) f.close() # step7:创建文件对象 id_file = None if not FileManager.objects.last(): id_file = "TestLaboratory_V1_File_1" else: id_file = gen_next_id(FileManager.objects.order_by('create_time').last().id) try: # step5:创建版本 version = Version.objects.create(id=id_version, number=version_num, software=software, version_file=id_file, create_time=create_time, update_time=update_time) except: logger.error("软件版本创建失败") return HttpResponse(content='软件版本创建失败', status=500) try: file_new = FileManager.objects.create(id=id_file, category="software", path=software.id + "/" + version.id + "/" + str(create_time) + "/" + file.name, create_time=create_time, update_time=update_time) except: logger.error("文件数据创建失败") return HttpResponse(content='文件数据创建失败', status=500) executor, action, method = get_log(request) gen_log(action, "目标版本", software.name+"-"+version.number, method, executor) return Response({ 'software_name': software.name, 'software_id': software.id, 'id': version.id, 'number': version.number, 'file_id': file_new.id, 'file_name': file_new.path.split('/')[-1], 'create_time': version.create_time, 'update_time': version.update_time, }) # delete version @staticmethod @RoleControl def delete(request, software_id, *args, **kwargs): version_number = request.GET.get('version_number') software = Software.objects.filter(id=software_id, delete=False) if not software: logger.error("软件已删除或不存在") return HttpResponse(content='软件已删除或不存在', status=500) software = software[0] versions = len(list(software.version_set.filter(delete=False))) if versions == 0: logger.error("被测软件无版本信息,请检查错误") return HttpResponse(content='被测软件无版本信息,请检查错误', status=500) elif versions == 1: version = software.version_set.filter(number=version_number, delete=False)[0] version_fid = version.version_file version_file = FileManager.objects.filter(id=version_fid)[0] software.delete = True version.delete = True version_file.delete = True # 删除测试计划 plan_set = software.testplan_set.filter(delete=False) if plan_set: for plan in plan_set: task_set = plan.testtask_set.filter(delete=False) if task_set: for task in task_set: task.delete = True task.save() plan.delete = True plan.save() software.save() version.save() version_file.save() return HttpResponse(status=200, content='软件及版本信息删除完成') else: version = software.version_set.filter(number=version_number, delete=False)[0] version_fid = version.version_file version_file = FileManager.objects.filter(id=version_fid)[0] version.delete = True version_file.delete = True # 删除测试计划 plan_set = software.testplan_set.filter(delete=False) if plan_set: for plan in plan_set: task_set = plan.testtask_set.filter(delete=False) if task_set: for task in task_set: task.delete = True task.save() plan.delete = True plan.save() version.save() version_file.save() executor, action, method = get_log(request) gen_log(action, "目标版本", software.name + "-" + version.number, method, executor) return HttpResponse(status=200, content='删除完成') @staticmethod # @RoleControl def get(request, software_id, *args, **kwargs): export_type = request.GET.get('type') version_number = request.GET.get('version_number') software = Software.objects.filter(id=software_id, delete=False) if not software: logger.error("软件已删除或不存在") return HttpResponse(content='软件已删除或不存在', status=500) software = software[0] version = software.version_set.filter(number=version_number, delete=False) if not version: logger.error("软件版本已删除或不存在") return HttpResponse(status=404, content='软件版本已删除或不存在') version = version[0] cases = None file_name = None if export_type == '0': cases = TestCase.objects.filter(software=software, version=version_number, delete=False) file_name = '全部测试用例.xls' elif export_type == '1': cases = TestCase.objects.filter(~Q(state=0), software=software, version=version_number, delete=False) file_name = '已执行测试用例.xls' else: cases = TestCase.objects.filter(software=software, version=version_number, state=2, delete=False) file_name = '不合格测试用例.xls' if not cases: logger.error("无符合要求的测试用例") return HttpResponse(status=404, content='无符合要求的测试用例') update_time = datetime.datetime.now() file_dir = CASE_FILE_EXPORT + software_id + "/" + str(update_time) if not os.path.exists(file_dir): os.makedirs(file_dir) file_path = file_dir + "/" + file_name cases_info = [['被测软件ID:', software_id], ['被测软件名:', software.name], ['被测软件版本', version_number], ['编号', '名称', '前置条件', '优先级', '测试环境', '测试类型', '测试步骤', '预期结果', '实际结果', '状态', '编写人', '评审员', '执行人', '备注']] for case in cases: state = '未执行' if case.state == 1: state = '执行成功' elif case.state == 2: state = '执行失败' cases_info.append([case.id_in_task, case.name, case.requisite, case.priority, case.environment, case.type, case.process, case.expected_result, case.actual_result, state, case.writer, case.assessor, case.executor, case.remark]) sio = write_to_xlsx(file_path, cases_info) sio.seek(0) response = HttpResponse(sio.getvalue(), content_type='multipart/form-data') response['Content-Disposition'] = 'attachment; filename="{0}"'.format(file_name).encode('utf-8') response.write(sio.getvalue()) # executor, action, method = get_log(request) # gen_log(action, "目标版本", software.name + "-" + version.number, method, executor) return response class VersionEdit(APIView): authentication_classes = [] # edit version # 版本号不能修改,本质上只能修改上传的文件 @staticmethod @RoleControl def post(request, software_id, *args, **kwargs): file = request.FILES.get('file') version_number = request.POST.get('version_number') # 判断软件是否存在 software = Software.objects.filter(id=software_id, delete=False) if not software: return HttpResponse(status=404, content='软件已删除或不存在') software = software[0] # 判断版本是否存在 software_version = software.version_set.filter(number=version_number, delete=False) if not software_version: return HttpResponse(status=404, content='软件版本不存在或已删除,请重新选择需要编辑的软件版本') software_version = software_version[0] # 删除原版本文件 version_fid = software_version.version_file version_file = FileManager.objects.filter(id=version_fid) if not version_file: logger.error("软件不存在,无法编辑") return HttpResponse(status=500, content='软件不存在,无法编辑') version_file = version_file[0] version_file.delete = True version_file.save() # step5:设置创建时间和修改时间 create_time = update_time = datetime.datetime.now() # step6:上传文件: write_file(file, SOFTWARE_ROOT + software.id + "/" + software_version.id + "/" + str( create_time)) # step7:创建文件对象 id_file = None if not FileManager.objects.last(): id_file = "TestLaboratory_V1_File_1" else: id_file = gen_next_id( FileManager.objects.order_by('create_time').last().id) software_version.version_file = id_file software_version.save() try: file_new = FileManager.objects.create(id=id_file, category="software", path=software.id + "/" + software_version.id + "/" + str(create_time) + "/" + file.name, create_time=create_time, update_time=update_time) except: logger.error("软件版本编辑失败,请重试") return HttpResponse(content='软件版本编辑失败,请重试', status=500) executor, action, method = get_log(request) gen_log(action, "目标版本", software.name + "-" + software_version.number, method, executor) return HttpResponse(status=200, content='修改已保存')