versionview.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. import datetime
  2. from django.db.models import Q
  3. from rest_framework.response import Response
  4. from rest_framework.views import APIView
  5. from django.http import HttpResponse
  6. from TestLaboratory.settings import SOFTWARE_ROOT, CASE_FILE_EXPORT
  7. from apps.file.models import FileManager
  8. from apps.log.models import get_log, gen_log
  9. from apps.software.models import Software, Version
  10. from apps.task.models import TestCase
  11. from apps.user.middleware.rolecontrol import RoleControl
  12. from util_xlsx import write_to_xlsx
  13. from utils.util_add_id import gen_next_id
  14. import os
  15. from utils.util_file.util_fileio import write_file
  16. import logging
  17. logger = logging.getLogger('django')
  18. class VersionView(APIView):
  19. authentication_classes = []
  20. # create version
  21. @staticmethod
  22. @RoleControl
  23. def post(request, software_id, *args, **kwargs):
  24. version_num = request.POST.get('version')
  25. file = request.FILES.get('file')
  26. # step1:判断版本所属软件是否存在
  27. software = Software.objects.filter(id=software_id, delete=False)
  28. if not software:
  29. logger.error("软件已删除或不存在")
  30. return HttpResponse(status=404, content='软件已删除或不存在')
  31. software = software[0]
  32. # step2:判断版本是否存在
  33. software_version = software.version_set.filter(number=version_num, delete=False)
  34. if software_version:
  35. logger.error("软件版本已存在,请修改版本号后重新上传")
  36. return HttpResponse(status=404, content='软件版本已存在,请修改版本号后重新上传')
  37. # step3:判断文件是否上传
  38. if not file:
  39. logger.error("软件上传失败")
  40. return HttpResponse(status=404, content='软件上传失败')
  41. # step4:创建版本id
  42. id_version = None
  43. if not Version.objects.order_by('create_time').last():
  44. id_version = "TestLaboratory_V1_Version_1"
  45. else:
  46. id_version = gen_next_id(Version.objects.order_by('create_time').last().id)
  47. # step5:设置创建时间和修改时间
  48. create_time = update_time = datetime.datetime.now()
  49. # step6:上传文件:
  50. file_dir = SOFTWARE_ROOT + software.id + "/" + id_version + "/" + str(create_time)
  51. if not os.path.exists(file_dir):
  52. os.makedirs(file_dir)
  53. file_path = file_dir + "/" + file.name
  54. with open(file_path, 'wb') as f:
  55. f.write(file.read())
  56. f.close()
  57. # step7:创建文件对象
  58. id_file = None
  59. if not FileManager.objects.last():
  60. id_file = "TestLaboratory_V1_File_1"
  61. else:
  62. id_file = gen_next_id(FileManager.objects.order_by('create_time').last().id)
  63. try:
  64. # step5:创建版本
  65. version = Version.objects.create(id=id_version, number=version_num, software=software,
  66. version_file=id_file,
  67. create_time=create_time,
  68. update_time=update_time)
  69. except:
  70. logger.error("软件版本创建失败")
  71. return HttpResponse(content='软件版本创建失败', status=500)
  72. try:
  73. file_new = FileManager.objects.create(id=id_file, category="software",
  74. path=software.id + "/" + version.id + "/" +
  75. str(create_time) + "/" + file.name,
  76. create_time=create_time, update_time=update_time)
  77. except:
  78. logger.error("文件数据创建失败")
  79. return HttpResponse(content='文件数据创建失败', status=500)
  80. executor, action, method = get_log(request)
  81. gen_log(action, "目标版本", software.name+"-"+version.number, method, executor)
  82. return Response({
  83. 'software_name': software.name,
  84. 'software_id': software.id,
  85. 'id': version.id,
  86. 'number': version.number,
  87. 'file_id': file_new.id,
  88. 'file_name': file_new.path.split('/')[-1],
  89. 'create_time': version.create_time,
  90. 'update_time': version.update_time,
  91. })
  92. # delete version
  93. @staticmethod
  94. @RoleControl
  95. def delete(request, software_id, *args, **kwargs):
  96. version_number = request.GET.get('version_number')
  97. software = Software.objects.filter(id=software_id, delete=False)
  98. if not software:
  99. logger.error("软件已删除或不存在")
  100. return HttpResponse(content='软件已删除或不存在', status=500)
  101. software = software[0]
  102. versions = len(list(software.version_set.filter(delete=False)))
  103. if versions == 0:
  104. logger.error("被测软件无版本信息,请检查错误")
  105. return HttpResponse(content='被测软件无版本信息,请检查错误', status=500)
  106. elif versions == 1:
  107. version = software.version_set.filter(number=version_number, delete=False)[0]
  108. version_fid = version.version_file
  109. version_file = FileManager.objects.filter(id=version_fid)[0]
  110. software.delete = True
  111. version.delete = True
  112. version_file.delete = True
  113. # 删除测试计划
  114. plan_set = software.testplan_set.filter(delete=False)
  115. if plan_set:
  116. for plan in plan_set:
  117. task_set = plan.testtask_set.filter(delete=False)
  118. if task_set:
  119. for task in task_set:
  120. task.delete = True
  121. task.save()
  122. plan.delete = True
  123. plan.save()
  124. software.save()
  125. version.save()
  126. version_file.save()
  127. return HttpResponse(status=200, content='软件及版本信息删除完成')
  128. else:
  129. version = software.version_set.filter(number=version_number, delete=False)[0]
  130. version_fid = version.version_file
  131. version_file = FileManager.objects.filter(id=version_fid)[0]
  132. version.delete = True
  133. version_file.delete = True
  134. # 删除测试计划
  135. plan_set = software.testplan_set.filter(delete=False)
  136. if plan_set:
  137. for plan in plan_set:
  138. task_set = plan.testtask_set.filter(delete=False)
  139. if task_set:
  140. for task in task_set:
  141. task.delete = True
  142. task.save()
  143. plan.delete = True
  144. plan.save()
  145. version.save()
  146. version_file.save()
  147. executor, action, method = get_log(request)
  148. gen_log(action, "目标版本", software.name + "-" + version.number, method, executor)
  149. return HttpResponse(status=200, content='删除完成')
  150. @staticmethod
  151. # @RoleControl
  152. def get(request, software_id, *args, **kwargs):
  153. export_type = request.GET.get('type')
  154. version_number = request.GET.get('version_number')
  155. software = Software.objects.filter(id=software_id, delete=False)
  156. if not software:
  157. logger.error("软件已删除或不存在")
  158. return HttpResponse(content='软件已删除或不存在', status=500)
  159. software = software[0]
  160. version = software.version_set.filter(number=version_number, delete=False)
  161. if not version:
  162. logger.error("软件版本已删除或不存在")
  163. return HttpResponse(status=404, content='软件版本已删除或不存在')
  164. version = version[0]
  165. cases = None
  166. file_name = None
  167. if export_type == '0':
  168. cases = TestCase.objects.filter(software=software, version=version_number, delete=False)
  169. file_name = '全部测试用例.xls'
  170. elif export_type == '1':
  171. cases = TestCase.objects.filter(~Q(state=0), software=software, version=version_number, delete=False)
  172. file_name = '已执行测试用例.xls'
  173. else:
  174. cases = TestCase.objects.filter(software=software, version=version_number, state=2, delete=False)
  175. file_name = '不合格测试用例.xls'
  176. if not cases:
  177. logger.error("无符合要求的测试用例")
  178. return HttpResponse(status=404, content='无符合要求的测试用例')
  179. update_time = datetime.datetime.now()
  180. file_dir = CASE_FILE_EXPORT + software_id + "/" + str(update_time)
  181. if not os.path.exists(file_dir):
  182. os.makedirs(file_dir)
  183. file_path = file_dir + "/" + file_name
  184. cases_info = [['被测软件ID:', software_id],
  185. ['被测软件名:', software.name],
  186. ['被测软件版本', version_number],
  187. ['编号', '名称', '前置条件', '优先级', '测试环境', '测试类型', '测试步骤', '预期结果', '实际结果', '状态',
  188. '编写人', '评审员', '执行人', '备注']]
  189. for case in cases:
  190. state = '未执行'
  191. if case.state == 1:
  192. state = '执行成功'
  193. elif case.state == 2:
  194. state = '执行失败'
  195. cases_info.append([case.id_in_task, case.name, case.requisite, case.priority, case.environment,
  196. case.type, case.process, case.expected_result, case.actual_result, state,
  197. case.writer, case.assessor, case.executor, case.remark])
  198. sio = write_to_xlsx(file_path, cases_info)
  199. sio.seek(0)
  200. response = HttpResponse(sio.getvalue(), content_type='multipart/form-data')
  201. response['Content-Disposition'] = 'attachment; filename="{0}"'.format(file_name).encode('utf-8')
  202. response.write(sio.getvalue())
  203. # executor, action, method = get_log(request)
  204. # gen_log(action, "目标版本", software.name + "-" + version.number, method, executor)
  205. return response
  206. class VersionEdit(APIView):
  207. authentication_classes = []
  208. # edit version
  209. # 版本号不能修改,本质上只能修改上传的文件
  210. @staticmethod
  211. @RoleControl
  212. def post(request, software_id, *args, **kwargs):
  213. file = request.FILES.get('file')
  214. version_number = request.POST.get('version_number')
  215. # 判断软件是否存在
  216. software = Software.objects.filter(id=software_id, delete=False)
  217. if not software:
  218. return HttpResponse(status=404, content='软件已删除或不存在')
  219. software = software[0]
  220. # 判断版本是否存在
  221. software_version = software.version_set.filter(number=version_number,
  222. delete=False)
  223. if not software_version:
  224. return HttpResponse(status=404,
  225. content='软件版本不存在或已删除,请重新选择需要编辑的软件版本')
  226. software_version = software_version[0]
  227. # 删除原版本文件
  228. version_fid = software_version.version_file
  229. version_file = FileManager.objects.filter(id=version_fid)
  230. if not version_file:
  231. logger.error("软件不存在,无法编辑")
  232. return HttpResponse(status=500, content='软件不存在,无法编辑')
  233. version_file = version_file[0]
  234. version_file.delete = True
  235. version_file.save()
  236. # step5:设置创建时间和修改时间
  237. create_time = update_time = datetime.datetime.now()
  238. # step6:上传文件:
  239. write_file(file,
  240. SOFTWARE_ROOT + software.id + "/" + software_version.id + "/" + str(
  241. create_time))
  242. # step7:创建文件对象
  243. id_file = None
  244. if not FileManager.objects.last():
  245. id_file = "TestLaboratory_V1_File_1"
  246. else:
  247. id_file = gen_next_id(
  248. FileManager.objects.order_by('create_time').last().id)
  249. software_version.version_file = id_file
  250. software_version.save()
  251. try:
  252. file_new = FileManager.objects.create(id=id_file,
  253. category="software",
  254. path=software.id + "/" + software_version.id + "/" +
  255. str(create_time) + "/" + file.name,
  256. create_time=create_time,
  257. update_time=update_time)
  258. except:
  259. logger.error("软件版本编辑失败,请重试")
  260. return HttpResponse(content='软件版本编辑失败,请重试', status=500)
  261. executor, action, method = get_log(request)
  262. gen_log(action, "目标版本", software.name + "-" + software_version.number,
  263. method, executor)
  264. return HttpResponse(status=200, content='修改已保存')