zoukankan      html  css  js  c++  java
  • Excel上传、下载、models 自定义字段、批量执行(可选)

    readme

    平台分析

    页面模板

    adminlte
    bootstrap
    jquery
    

    django

      • 接口表

        • 接口title
        • 描述
        • 接口数量
        • 通过数量
      • 接口用例表

        • 所属接口,外键
        • 用例title
        • 用例描述
        • 预期值
        • url
        • 参数
        • 请求类型
        • 用例报告
        • 执行状态: 执行和未执行
        • 通过:已通过和未通过

    Excel上传

    import xlrd
    from django.shortcuts import render, redirect, HttpResponse
    from django.db import transaction
    

    def import_case(request, pk):
    """ 为接口批量导入用例, pk:接口的pk """
    if request.method == "POST":
    try:
    with transaction.atomic(): # 事务
    # 读取Excel表格
    book = xlrd.open_workbook(file_contents=request.FILES.get('excel').read())
    sheet = book.sheet_by_index(0)

                title = sheet.row_values(0)
                '''
                ['cnodejs项目', 'get /topics 主题首页', 'https://cnodejs.org/api/v1/topics', 'get', '', '{"success":true}']
                '''
                for row in range(1, sheet.nrows):
                    row = sheet.row_values(row)
                    # break
                    models.Case.objects.create(
                        case_API_id=pk,
                        case_title=row[0],
                        case_desc=row[1],
                        case_url=row[2],
                        case_method=row[3],
                        case_params=row[4],
                        case_expect=row[-1],
                    )
                return redirect('/case_list/{}'.format(pk))
        except Exception as e:
            return render(request, 'import_case.html', {"error": "文件格式不对,只能上传 xls/xlsx 的 {}".format(e)})
    else:
        return render(request, 'import_case.html',{"error": ""})
    

    下载

    from utils.execute_case import execute
    from django.http import JsonResponse
    from django.http import FileResponse
    def case_execute(request, pk):
        """ 执行用例 PK:要执行用例的pk"""
        if request.method == "POST":
            pass
        else:
            # 1. 从前端获取要执行的用例id,然后从数据库取出这个用例对象
            case_obj = models.Case.objects.filter(pk=pk).first()
            # 2. 从用例对象中,提取相关字段,执行这个用例
            file_path = execute(case_obj)
            response = FileResponse(open(file_path, 'rb'))
            response['Content-Type'] = 'application/octet-stream'
            # filename的名称不能含有中文
            response['Content-Disposition'] = 'attachment;filename="{}.html"'.format('report')
            # print(111111, case_obj.case_title)
            return response
    

    models 自定义字段

    from django.db import models
    class API(models.Model):
        """ 接口表 """
        api_title = models.CharField(max_length=32, verbose_name='接口名称')
        api_desc = models.CharField(max_length=128, verbose_name='接口描述')
    
    def __str__(self):
        return self.api_title
    
    def xxoo(self):
        if self.case_set.count():
            a = "%s%% " % (self.case_set.filter(case_pass_status=1).count() / self.case_set.count() * 100)
            return a
        else:
            return 0
    

    前端调用:

    {% for foo in api_obj %}
        <tr>
            <td>{{ forloop.counter }}</td>
            <td>{{ foo.api_title }}</td>
            <td>{{ foo.api_desc }}</td>
            <td>{{ foo.case_set.count }}</td> <!--  接口下面有多少用例 -->
            <td>{{ foo.xxoo }} </td> <!--  接口下面的用例有多少通过的,计算公式: 通过/总数*100 -->
            <td>
                <a href="{% url 'api_edit' foo.pk %}" class="btn btn-success btn-sm">编辑接口</a>
                <a href="{% url 'api_del' foo.pk %}" class="btn btn-success btn-sm">删除接口</a>
                <a href="{% url 'case_add' foo.pk %}" class="btn btn-success btn-sm">添加用例</a>
                <a href="{% url 'import_case' foo.pk %}" class="btn btn-success btn-sm">批量导入</a>
                <a href="{% url 'case_list' foo.pk %}" class="btn btn-success btn-sm">查看用例</a>
            </td>
        </tr>
    {% endfor %}
    

    执行用例的思路

    第一种,执行单个用例

    1. 点击执行

    2. 后台过滤出来当前的用例,将用例对象返回

    3. unittest/pytest框架做

      1. 从用例对象中,提取各个参数,发请求

      2. 校验请求结果

      3. 断言

      4. 生成测试报告

      5. 将该测试报告存储到数据库

        1. 将HTML文件存储都某个目录下,数据库存储文件的路径
        2. 直接将HTML文本存储数据的字段
      6. 用例的执行状态,通过状态,都要改

    4. 如何将测试报告返回给前端

      1. 直接将报告下载到本地

    批量执行(可选)

    定时任务

    定时任务,https://www.cnblogs.com/Neeo/p/10435059.html 发邮件:https://www.cnblogs.com/Neeo/articles/11199085.html

    1. 每天检查接口表,检查有没有当天要结束的接口
    2. 如果检查到有当天要结束的接口
    3. 就把该接口下的所有用例执行一遍
    4. 生成测试报告

    实现步骤

    1. 接口表,添加字段,接口的开始/结束时间
    2. 每天固定的时间,读取接口表,判断结束时间是否为当天
    3. 如果为当天要结束的,把该接口下的用例执行一遍
    4. 生成测试报告,保存到数据库
    5. 前端能查询该条执行记录
    6. 下载这个记录的测试报告

    datetime

    import os
    import datetime
    import django
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MB.settings")
    django.setup()
    from app01 import models
    

    if name == 'main':
    print(datetime.datetime.now())
    today = datetime.date.today()
    print(today.year, today.month)

  • 相关阅读:
    npm 5.4.2 更新后就不能用了
    Node.js 被分叉出一个项目 — Ayo.js,肿么了
    页面缓存之Meta http-equiv属性详解
    Javascript 浮点计算问题分析与解决
    详解 Cookie 纪要(vue.cookie,jquery.cookie简化)
    Cookie 基本操作
    HTML5上传图片预览
    location.href跳转测试
    ios中iframe的scroll滚动事件替代方法
    JS数组API
  • 原文地址:https://www.cnblogs.com/g15009428458/p/12168754.html
Copyright © 2011-2022 走看看