예제 #1
0
def insert_test_result(cassid,status,runtime="",result="",validate=""):
    '''
    将测试结果存入到数据库
    '''
    sql = "INSERT INTO `t_reports` (`cassid`, `status`, `runtime`, `result`, `validate`) VALUES ('%s', '%s', '%s', '%s', '%s')" % (cassid,status,runtime,result,validate)
    dbres = excute(sql)
    if dbres != True:
        Logger.error("保存测试结果到数据库出错,错误信息 --> %s" % dbres)
예제 #2
0
def run_validata_test(testname, validatelist):
    '''
    测试用例的检查点执行
    '''
    if len(validatelist) != 0:
        for validatekey in validatelist:
            res = eval(validatekey)
            if res == True:
                Logger.info("测试用例[%s]检查点执行成功,检查点信息为 --> %s" % (testname, validatekey))
            else:
                Logger.war("测试用例[%s]检查点执行失败,检查点信息为 --> %s" % (testname, validatekey))
예제 #3
0
def collect_db_cass(jsoncasss):
    '''
    读取json并执行用例。
    '''
    # 获取当前用例测试结果的最大版本号
    version = get_reports_max_version()
    for test in jsoncasss:
        if not test:
            Logger().error("没有发现测试用例,结束用例执行!")
        try:
            runner = Runner(test)
            yield runner.run_test(version)
        except Exception as e:
            Logger().error("测试用例[%s]执行失败,失败原因 --> %s"  % (test["testname"], e))
예제 #4
0
def collect_db_cass(jsoncasss):
    '''
    读取json并执行用例。
    '''
    # all_tests = json.loads(jsoncasss)
    for test in jsoncasss:
        if not test:
            Logger().error("没有发现测试用例,结束用例执行!")
        try:
            runner = Runner(test)
            yield runner.run_test()
        except Exception as e:
            # raise e
            Logger().error("测试用例[%s]执行失败,失败原因 --> %s" % (test["testname"], e))
예제 #5
0
def query(sql=""):
    """
        ex: 根据sql查询结果
        args: sql
        return: results
    """
    results = []
    db = pymysql.connect(**db_config)
    cur = db.cursor()
    try:
        cur.execute(sql)  # 执行sql语句
        # 获得列名
        descs = []
        for desc in cur.description:
            descs.append(desc[0])
        # 构造键值对{"列名":数据}
        results = []
        for res in cur.fetchall():
            row = {}
            for i in range(len(descs)):
                row[descs[i]] = res[i]
            results.append(row)
    except Exception as e:
        Logger().error("sql语句[%s]执行失败,错误信息为 --> %s" % (sql, e))
        raise e
    finally:
        cur.close()
        db.close()  # 关闭连接
        return results
예제 #6
0
def insert_test_result(cassid,
                       status="成功",
                       runtime="",
                       result="",
                       validate="",
                       version=-1):
    '''
    将测试结果存入到数据库
    '''
    from app.utils.common import get_current_time
    sql = "INSERT INTO `t_reports` " \
          "(`cassid`, `status`, `runtime`, `result`, `validate`, `createtime`, `version`) " \
          "VALUES ('%s', '%s', '%s', '%s', '%s', '%s', %d)" % (cassid,status,runtime,result,validate, get_current_time(), version)
    dbres = excute(sql)
    if dbres != True:
        Logger.error("保存测试结果到数据库出错,错误信息 --> %s" % dbres)
예제 #7
0
def jsonfile(filename):
    '''
    判断导入的json文件格式是否合法
    '''
    filetype = filename.split(".")
    # print(filetype[-1])
    if filetype[-1] == "json" and filename.startswith("test"):
        return filename
    else:
        Logger().error("导入的JSON文件格式不正确,请检查JSON格式!")
        return None
예제 #8
0
def runproduct():
    '''
    按产品执行所有用例
    {"idlist":"1,2"}
    '''
    dictdata = request.get_json()
    idlist = dictdata["idlist"]
    sql = "SELECT\
        t_testcass.id\
    FROM\
        t_product\
    LEFT JOIN t_project ON t_product.id = t_project.productid\
    LEFT JOIN t_modules ON t_project.id = t_modules.projectid\
    LEFT JOIN t_testcass ON t_modules.id = t_testcass.moduleid\
    WHERE t_product.id in (%s);" % idlist
    res = dbfucs.query(sql)
    jsoncasss = []
    for test in res:
        jsoncasss.append(test)
    # print(jsoncasss)
    for i in collect.collect_db_cass(jsoncasss):
        Logger.info("*" * 90)
    Logger.info("共计[%d]条测试用例执行完成!" % len(jsoncasss))
    Logger.info("*" * 90)
    response = {}
    response["code"] = 200
    response["msg"] = "成功!!!"
    return jsonify(response)
예제 #9
0
def runmodule():
    '''
    按模块执行所有用例
    {"idlist":"1,2"}
    '''
    dictdata = request.get_json()
    idlist = dictdata["idlist"]
    ids = ''
    for i in idlist:
        ids += str(i) + ","
    sql = "SELECT * FROM t_testcass WHERE moduleid in (%s)" % ids[:-1]
    res = dbfucs.query(sql)
    if len(res) == 0:
        response = {}
        response["code"] = 200
        response["msg"] = "没有可用用例执行"
        return jsonify(response)
    jsoncasss = []
    for test in res:
        jsoncasss.append(test)
    # print(jsoncasss)
    for i in collect.collect_db_cass(jsoncasss):
        Logger.info("*" * 90)
    Logger.info("共计[%d]条测试用例执行完成!" % len(jsoncasss))
    Logger.info("*" * 90)
    response = {}
    response["code"] = 200
    response["msg"] = "成功!!!"
    return jsonify(response)
예제 #10
0
def collect_file_cass(filename):
    '''
    读取json并执行用例。
    '''
    with open(filename, 'r') as f:
        all_tests = json.load(f)
        # print(all_tests)
    for test in all_tests:
        if not test:
            Logger().error("没有发现测试用例,结束用例执行!")
        # try:
        runner = Runner(test)
        yield runner.run_test()
예제 #11
0
def excute(sql=""):
    '''
        ex: 根据sql插入或更新数据
        args: sql
        return: is_success,true:成功 false:失败
    '''
    is_success = True
    db = pymysql.connect(**db_config)
    cur = db.cursor()
    try:
        cur.execute(sql)
        db.commit()
    except Exception as e:
        db.rollback()
        Logger().error("sql语句[%s]执行失败,错误信息为 --> %s" % (sql, e))
        is_success = "%s" % e
    finally:
        cur.close()
        db.close()
        return is_success
예제 #12
0
def runproduct():
    '''
    按产品执行所有用例
    {"idlist":"1,2"}
    '''
    dictdata = request.get_json()
    idlist = dictdata["idlist"]
    ids = ''
    for i in idlist:
        ids += str(i) + ","
    sql = "SELECT\
        t_testcass.id\
    FROM\
        t_product\
    LEFT JOIN t_project ON t_product.id = t_project.productid\
    LEFT JOIN t_modules ON t_project.id = t_modules.projectid\
    LEFT JOIN t_testcass ON t_modules.id = t_testcass.moduleid\
    WHERE t_product.id in (%s);" % ids[:-1]
    # print(sql)
    res = dbfucs.query(sql)
    # print(res)
    if len(res) == 0:
        response = {}
        response["code"] = 200
        response["msg"] = "没有可用用例执行"
        return jsonify(response)
    idlist = []
    for i in res:
        idlist.append(i['id'])
    ids = ''
    for i in idlist:
        ids += str(i) + ","
    sql = "select id,testname,testtype,request,validate,extract from t_testcass where id in(%s);" % ids[:
                                                                                                        -1]
    res = dbfucs.query(sql)
    jsoncasss = []
    for test in res:
        jsoncasss.append(test)
    # print(jsoncasss)
    for i in collect.collect_db_cass(jsoncasss):
        Logger.info("*" * 90)
    Logger.info("共计[%d]条测试用例执行完成!" % len(jsoncasss))
    Logger.info("*" * 90)
    response = {}
    response["code"] = 200
    response["msg"] = "共计[%d]条测试用例执行完成!" % len(jsoncasss)
    return jsonify(response)
예제 #13
0
 def run_test(self):
     cassid = self.cassid
     testname = self.testname
     testtype = self.testtype
     request = eval(self.request)
     validates = eval(self.validates)
     extract = eval(self.extract)
     global extracts
     try:
         if testtype == "testsuite":
             execlist = get_global_values(request)
             if len(execlist) != 0:
                 for execkey in execlist:
                     # print("execkey:",execkey)
                     exec(execkey)
             r = run_http_test(testname, request)
             execlist = extract_global_values(extract)
             if len(execlist) != 0:
                 for execkey in execlist:
                     # print("execkey:",execkey)
                     exec(execkey)
         else:
             r = run_http_test(testname, request)
         runtime = r.elapsed.total_seconds()
         result = r.text
         print(result)
         validatelist = get_validata_test(validates)
         if len(validatelist) != 0:
             for validatekey in validatelist:
                 res = eval(validatekey)
                 if res == True:
                     status = 0
                     Logger.info("测试用例[%s]检查点执行成功,检查点信息为 --> %s" %
                                 (testname, validatekey))
                 else:
                     status = 1
                     Logger.war("测试用例[%s]检查点执行失败,检查点信息为 --> %s" %
                                (testname, validatekey))
         insert_test_result(cassid,
                            status,
                            runtime=runtime,
                            result=result,
                            validate=",".join(validatelist))
     except Exception as e:
         status = 2
         Logger.error("测试用例[%s]在执行过程中出现异常,错误信息为 --> %s" % (testname, e))
         insert_test_result(cassid, status)
예제 #14
0
    def run_test(self, version):
        # version是t_reports表中的version字段,表示当前测试用例的执行结果版本
        # vesion越大,版本越靠前
        cassid = self.cassid
        testname = self.testname
        testtype = self.testtype
        request = eval(self.request)
        validates = eval(self.validates)
        extract = eval(self.extract)
        global extracts
        try:
            if testtype == "testsuite":
                execlist = get_global_values(request)
                if len(execlist) != 0:
                    for execkey in execlist:
                        # print("execkey:",execkey)
                        exec(execkey)
                r = run_http_test(testname, request)
                execlist = extract_global_values(extract)
                if len(execlist) != 0:
                    for execkey in execlist:
                        # print("execkey:",execkey)
                        exec(execkey)
            else:
                r = run_http_test(testname, request)
            runtime = r.elapsed.total_seconds()
            result = r.text
            validatelist = get_validata_test(validates)
            # run_validata_test(testname, validatelist)
            if len(validatelist) != 0:
                for validatekey in validatelist:
                    # assert  eval(validatekey) ,"%s" % str(eval(validatekey))
                    # Logger.info("测试用例[%s]检查点执行成功,检查点信息为 --> %s" % (testname, validatekey))
                    res = eval(validatekey)
                    if res == True:
                        status = "成功"
                        Logger.info("测试用例[%s]检查点执行成功,检查点信息为 --> %s" % (testname, validatekey))
                    else:
                        status = "失败"
                        Logger.war("测试用例[%s]检查点执行失败,检查点信息为 --> %s" % (testname, validatekey))

            insert_test_result(cassid, status, runtime=runtime, result=result, validate=validatekey, version=version)
        except Exception as e:
            status = "报错"
            Logger.error("测试用例[%s]在执行过程中出现异常,错误信息为 --> %s" % (testname, e))
            insert_test_result(cassid, status, version=version)
예제 #15
0
def runtests():
    '''{"idlist":"1,2"}'''
    dictdata = request.get_json()
    idlist = dictdata["idlist"]
    sql = "select id,testname,testtype,request,validate,extract from t_testcass where id in(%s);" % idlist
    res = dbfucs.query(sql)
    jsoncasss = []
    for test in res:
        jsoncasss.append(test)
    for i in collect.collect_db_cass(jsoncasss):
        Logger.info("*" * 90)
    Logger.info("共计[%d]条测试用例执行完成!" % len(jsoncasss))
    Logger.info("*" * 90)
    response = {}
    response["code"] = 200
    response["msg"] = "用例执行完成!"
    return jsonify(response)
예제 #16
0
from math import sqrt

from tortoise import fields
from tortoise.models import Model

from app.utils.exceptions import SubZeroKarma
from app.utils.log import Logger
from .chat import Chat
from .db import karma_filters
from .user import User

logger = Logger(__name__)
DEFAULT_KARMA = 50


class UserKarma(Model):
    """
    information about (karma) (user) in (chat)
    """
    uc_id = fields.IntField(pk=True)
    user: fields.ForeignKeyRelation[User] = fields.ForeignKeyField(
        'models.User', related_name='karma')
    chat: fields.ForeignKeyRelation[Chat] = fields.ForeignKeyField(
        'models.Chat', related_name='user_karma')
    karma = fields.FloatField(default=DEFAULT_KARMA)

    class Meta:
        table = 'user_karma'
        unique_together = ('user', 'chat')

    def __str__(self):
예제 #17
0
# -*- coding:utf-8 -*-
__author__ = 'snake'

import os, json
from app import bp
from flask import jsonify, request
from app.utils.log import Logger
from app.utils.common import get_current_time
from app.utils.dbfucs import excute
from app.utils.jsonfuc import validate_req_by_file
Logger = Logger()


def _upload_files(file):
    """
    上传图片公共方法
    :param file: 上传的file文件
    :return: True:成功;False失败
    """
    try:
        upload_path = os.path.join("./app/uploads/",
                                   file.filename)  # 注意:没有的文件夹一定要先创建,不然会提示没有该路径
        file.save(upload_path)
        return True
    except:
        return False


@bp.route("/uploadtestcase", methods=['POST'])
def uploadtestcase():
    file = request.files['file']
예제 #18
0
def run_http_test(testname, request):
    '''
    对HTTP接口发送请求
    '''
    Logger.info("开始执行测试用例[%s]" % testname)
    Logger.info("接口请求地址为 --> %s" % request["url"])
    Logger.info("接口请求方法为 --> %s" % request["method"])
    Logger.info("接口请求header --> %s" % request["headers"])
    Logger.info("接口请求数据为 --> %s" % request["json"])
    try:
        r = requests.request(**request)
    except (requests.exceptions.Timeout,
            requests.exceptions.ConnectionError) as timeout:
        Logger.error("测试用例[%s]在执行过程中出现异常,错误信息为 --> %s" % (testname, timeout))
    Logger.info("接口响应时间为 --> %ss" % r.elapsed.total_seconds())
    Logger.info("接口响应状态为 --> %s" % r.status_code)
    Logger.info("接口响应内容为 --> %s" % r.text)
    if r.status_code == 200:
        return r
    else:
        # Logger.error("测试用例[%s]在执行过程中出现异常,错误信息为 --> [code:%s],[error:%s]" % (testname, r.status_code, r.text))
        raise Exception()