Beispiel #1
0
def write_results_log():
    results = []
    yield results

    de = DealExcel(os.path.join(DealPath().DATA_PATH, 'cases.xlsx'), 'login')
    #将执行结果转换成字典
    de.write_all_excel(dict(enumerate(results)))
Beispiel #2
0
    def myLoger(self):

        #创建日志收集器
        my_logger =  logging.getLogger('zcg')
        my_logger.setLevel(conf.get('log','level'))

        #创建工作台输出流
        sh = logging.StreamHandler()
        sh.setLevel(conf.get('log','sh_level'))
        my_logger.addHandler(sh)

        #创建文件输出流
        fh = logging.FileHandler(os.path.join(DealPath().LOG_PATH,'logs.log'),encoding="utf-8")
        fh.setLevel(conf.get('log','fh_level'))
        my_logger.addHandler(fh)

        #设置输出格式
        formats = "%(asctime)s -- [%(filename)s-->line:%(lineno)d] - %(levelname)s: %(message)s"
        #添加输出格式
        fm = logging.Formatter(formats)
        #将输出格式添加到输出渠道
        sh.setFormatter(fm)
        fh.setFormatter(fm)

        return my_logger
Beispiel #3
0
class TestRegister:
    test_cases = DealExcel(os.path.join(DealPath().DATA_PATH, 'cases.xlsx'),
                           'register').read_excel()
    ds = DealSql()

    @pytest.mark.parametrize('case', test_cases)
    def test_register(self, case, write_results):
        rs = write_results

        phone = DealComm().create_phone()
        setattr(StoreData, 'phone', phone)

        headers = eval(conf.get('env', 'headers2'))
        method = case['method']
        url = conf.get('url', 'base_url') + case['url']
        case['data'] = DealComm().repalce_string(case['data'])
        data = eval(case['data'])
        expect = eval(case['expected'])

        try:
            if method == 'get' or method == 'GET':
                results = request(method=method,
                                  url=url,
                                  data=data,
                                  headers=headers)
            else:
                results = request(method=method,
                                  url=url,
                                  json=data,
                                  headers=headers)
        except Exception as e:
            rs.append('请求异常new')
            assert '请求异常' == '0'
        else:
            result = results.json()
            print(result)

            try:
                #assert (results.status_code,result['code'],result['msg']) == (200,expect['code'],expect['msg'])
                assert results.status_code == 200
                assert result['code'] == expect['code']
                assert result['msg'] == expect['msg']
                if case['query_sql']:
                    case['query_sql'] = DealComm().repalce_string(
                        case['query_sql'])
                    res = self.ds.get_count(case['query_sql'])
                    sql_res = self.ds.find_one(case['query_sql'])
                    assert res == 1
                    if '管理员用户' in case['title']:
                        setattr(StoreData, 'admin_phone', phone)
                    elif '普通用户' in case['title']:
                        setattr(StoreData, 'user_phone', phone)
                    setattr(StoreData, 'member_id', str(sql_res['id']))
            except AssertionError as e:
                rs.append('测试不通过new')
                raise e
            else:
                rs.append('测试通过new')
Beispiel #4
0
class TestLogin:
    test_cases = DealExcel(os.path.join(DealPath().DATA_PATH, 'cases.xlsx'),
                           'login').read_excel()
    ds = DealSql()

    @pytest.mark.parametrize('case', test_cases)
    def test_login(self, case, write_results_log):
        rs = write_results_log

        headers = eval(conf.get('env', 'headers2'))
        method = case['method']
        url = conf.get('url', 'base_url') + case['url']
        case['data'] = DealComm().repalce_string(case['data'])
        data = eval(case['data'])
        expect = eval(case['expected'])

        try:
            if method == 'get' or method == 'GET':
                results = request(method=method,
                                  url=url,
                                  data=data,
                                  headers=headers)
            else:
                results = request(method=method,
                                  url=url,
                                  json=data,
                                  headers=headers)
        except Exception as e:
            rs.append('请求异常new')
            assert '请求异常' == '0'
        else:
            result = results.json()
            print(result)

            try:
                #assert (results.status_code,result['code'],result['msg']) == (200,expect['code'],expect['msg'])
                assert results.status_code == 200
                assert result['code'] == expect['code']
                assert result['msg'] == expect['msg']
                if jsonpath(result, '$..token'):
                    if '管理员' in case['title']:
                        setattr(StoreData, 'admin_token',
                                'Bearer ' + jsonpath(result, '$..token')[0])
                        setattr(StoreData, 'admin_member_id',
                                str(jsonpath(result, '$..id')[0]))
                    elif '普通用户' in case['title']:
                        setattr(StoreData, 'user_token',
                                'Bearer ' + jsonpath(result, '$..token')[0])
                        setattr(StoreData, 'user_member_id',
                                str(jsonpath(result, '$..id')[0]))

            except AssertionError as e:
                rs.append('测试不通过new')
                raise e
            else:
                rs.append('测试通过new')
Beispiel #5
0
class TestAdd():

    test_cases = DealExcel(os.path.join(DealPath().DATA_PATH, 'cases.xlsx'),
                           'add').read_excel()
    ds = DealSql()

    @pytest.mark.parametrize('cases', test_cases)
    def test_add(self, cases, write_results_add):
        #准备测试数据
        results, token = write_results_add
        method = cases['method']
        url = conf.get('env', 'base_url') + cases['url']
        # if '#member_id#' in cases['data']:
        #     cases['data'] = cases['data'].replace('#member_id#',str(self.hl.user_id))
        cases['data'] = DealComm().repalce_string(cases['data'])
        test_datas = eval(cases['data'])
        headers = eval(conf.get('env', 'headers2'))
        cases_id = cases['case_id'] + 1
        headers['Authorization'] = token
        #headers['Authorization'] = getattr(StoreData,'token')
        expected = eval(cases['expected'])

        #调用请求
        try:
            res = request(method=method,
                          url=url,
                          json=test_datas,
                          headers=headers).json()

            self.assertEqual(expected['code'], res['code'])
            self.assertEqual(expected['msg'], res['msg'])
            if cases['query_sql']:
                # sql = cases['query_sql'].format(self.hl.user_id)
                sql = DealComm().repalce_string(cases['query_sql'])
                count = self.hm.count(sql)
                self.assertEqual(1, count)
                # sql_res = self.hm.find_one(sql)
                # setattr(StoreData,'pass_loin')

            results = "测试通过"

        except AssertionError as e:

            results = "测试不通过"
            raise e

        except Exception as e:
            results = "接口异常"

        finally:
            #记录测试结果
            myLog.error("测试案例:==={}==={}".format(cases['title'], results))
            self.he.write_excel(row=cases_id, col=8, text=results)
Beispiel #6
0
def write_results_add():
    results = []
    url = conf.get('env', 'base_url') + '/member/login'
    #datas ='{"mobile_phone":"{}","pwd":"12345678"}'.format(getattr(StoreData,'user_phone'))
    datas = '{"mobile_phone":"' + getattr(StoreData,
                                          'user_phone') + '","pwd":"12345678"}'
    datas = eval(datas)
    headers = eval(conf.get('env', 'headers2'))
    #调登陆接口
    res = requests.request(method='post', url=url, json=datas,
                           headers=headers).json()

    #cls.member_id = jsonpath.jsonpath(res,'$..id')[0]
    #print(cls.member_id,type(cls.member_id))
    token = "Bearer " + jsonpath.jsonpath(res, "$..token")[0]
    yield results, token

    de = DealExcel(os.path.join(DealPath().DATA_PATH, 'cases.xlsx'), 'add')
    #将执行结果转换成字典
    de.write_all_excel(dict(enumerate(results)))
Beispiel #7
0
    def read_conf(self):
        path = os.path.join(DealPath().CONF_PATH, 'config.ini')
        rd = RawConfigParser()
        rd.read(path, encoding='utf-8')

        return rd
Beispiel #8
0
            cont = []
            for i in item:
                cont.append(i.value)
            result.append(dict(zip(title, cont)))

        return result

    def write_one_excel(self, row, col, text):
        wb = openpyxl.load_workbook(self.filename)
        sh = wb[self.sheet]
        sh.cell(row=row, column=col, value=text)
        wb.save(self.filename)

    def write_all_excel(self, texts):
        wb = openpyxl.load_workbook(self.filename)
        sh = wb[self.sheet]
        for item in texts:
            row = item + 2
            col = 8
            text = texts[item]
            sh.cell(row=row, column=col, value=text)
        wb.save(self.filename)


if __name__ == '__main__':
    de = DealExcel(os.path.join(DealPath().DATA_PATH, 'cases.xlsx'),
                   'register')
    re = de.read_excel()

    print(re)