コード例 #1
0
ファイル: writeCaseYml.py プロジェクト: Leozhanggg/ApiTesting
def init_api_conf(har_ct):
    host = har_ct["host"]
    port = har_ct["actualPort"]
    headers = har_ct["request"]["header"]['headers']
    # 定义项目api通过配置
    proj_conf = dict()
    proj_conf['timeout'] = 10
    proj_conf['scheme'] = har_ct["scheme"]
    proj_conf['host'] = host + ':' + str(port)
    simp_header = dict()
    for header in headers:
        # 去除基础请求头
        base_header = [
            'Host', 'Content-Length', 'User-Agent', 'Origin', 'Referer',
            'Connection', 'Accept', 'Accept-Encoding', 'Accept-Language'
        ]
        if header['name'] not in base_header:
            simp_header[header['name']] = header['value']

    # 判断是否存在自定义消息头
    if simp_header:
        proj_conf['headers'] = simp_header
    else:
        proj_conf['headers'] = None

    # 检查是否已存在项目配置信息,没有则写入
    run_conf = read_yaml_data(API_CONFIG)
    if run_conf:
        if PROJECT_NAME not in run_conf:
            run_conf[PROJECT_NAME] = proj_conf
            write_yaml_file(API_CONFIG, run_conf)
    else:
        api_conf = dict()
        api_conf[PROJECT_NAME] = proj_conf
        write_yaml_file(API_CONFIG, api_conf)
コード例 #2
0
def save_cookie(headers,
                address,
                mime_type,
                timeout=8,
                data=None,
                files=None,
                cookies=None):
    """
    保存cookie信息
    :param headers: 请求头
    :param address: 请求地址
    :param mime_type: 请求参数格式(form_data,raw)
    :param timeout: 超时时间
    :param data: 请求参数
    :param files: 文件路径
    :param cookies:
    :return:
    """
    if 'data' in mime_type:
        response = requests.post(url=address,
                                 data=data,
                                 headers=headers,
                                 timeout=timeout,
                                 files=files,
                                 cookies=cookies,
                                 verify=False)
    else:
        response = requests.post(url=address,
                                 json=data,
                                 headers=headers,
                                 timeout=timeout,
                                 files=files,
                                 cookies=cookies,
                                 verify=False)
    try:
        cookies = response.cookies.get_dict()
        # 读取api配置并写入最新的cookie结果
        aconfig = read_yaml_data(API_CONFIG)
        aconfig[PROJECT_NAME]['cookies'] = cookies
        write_yaml_file(API_CONFIG, aconfig)
        logging.debug("cookies已保存,结果为:{}".format(cookies))
    except json.decoder.JSONDecodeError:
        return response.status_code, None
    except simplejson.errors.JSONDecodeError:
        return response.status_code, None
    except Exception as e:
        logging.exception('ERROR')
        logging.error(e)
        raise
コード例 #3
0
# -*- coding:utf-8 -*-
# @Time    : 2021/2/2
# @Author  : Leo Zhang
# @File    : test_initCanSelInfo.py
# ****************************
import os
import allure
import pytest
from comm.utils.readYaml import read_yaml_data
from comm.unit.initializePremise import init_premise
from comm.unit.apiSend import send_request
from comm.unit.checkResult import check_result

file_path = os.path.realpath(__file__).replace('\\', '/')
case_yaml = file_path.replace('/testcase/', '/page/').replace('.py', '.yaml')
test_case = read_yaml_data(case_yaml)


@allure.feature(test_case["test_info"]["title"])
class TestRegister:
    @pytest.mark.parametrize("test_case", test_case["test_case"])
    @allure.story("test_initCanSelInfo")
    def test_initCanSelInfo(self, test_case):
        # 初始化请求:执行前置接口+替换关联变量
        test_info, test_case = init_premise(test_case["test_info"], test_case,
                                            case_yaml)
        # 发送当前接口
        code, data = send_request(test_info, test_case)
        # 校验接口返回
        check_result(test_case, code, data)
コード例 #4
0
# -*- coding:utf-8 -*-
# @Time    : 2021/03/09
# @Author  : Leo Zhang
# @File    : queryDatabase.py
# **************************
from comm.utils.readYaml import read_yaml_data
from config import DB_CONFIG, PROJECT_NAME
from comm.db import *
import logging
import time
import re

dbcfg = read_yaml_data(DB_CONFIG)[PROJECT_NAME]


def query_mysql(sql):
    """查询MySQL数据

    :param sql: sql查询语句
    :return:
    """
    # 获取配置信息
    timeout = dbcfg['timeout']
    address = dbcfg['mysql_info']['address']
    user = dbcfg['mysql_info']['user']
    auth = dbcfg['mysql_info']['auth']
    db = dbcfg['mysql_info']['db']
    # 初始化MySQL
    host, port = address.split(':')
    mysql = MysqlServer(host, int(port), db, user, auth)
    logging.info('执行查询>>> {}'.format(sql))
コード例 #5
0
# -*- coding:utf-8 -*-
# @Time    : 2021/2/2
# @Author  : Leo Zhang
# @File    : test_template.py
# ****************************
import os
import allure
import pytest
from comm.utils.readYaml import read_yaml_data
from comm.unit.initializePremise import init_premise
from comm.unit.apiSend import send_request
from comm.unit.checkResult import check_result
file_path = os.path.realpath(__file__).replace('\\', '/')
case_yaml = file_path.replace('/testcase/', '/page/').replace('.py', '.yaml')
case_data = read_yaml_data(case_yaml)


@allure.feature(case_data["test_info"]["title"])
class TestTemplate:
    @pytest.mark.parametrize("test_case", case_data["test_case"])
    @allure.story("test_template")
    def test_template(self, test_case):
        # 初始化请求:执行前置接口+替换关联变量
        test_info, test_case = init_premise(case_data["test_info"], test_case,
                                            case_yaml)
        # 发送当前接口
        code, data = send_request(test_info, test_case)
        # 校验接口返回
        check_result(test_case, code, data)
コード例 #6
0
def init_premise(test_info, case_data, case_path):
    """用例前提条件执行,提取关键值

    :param test_info: 测试信息
    :param case_data: 用例数据
    :param case_path: 用例路径
    :return:
    """
    # 获取项目公共关联值
    aconfig = readYaml.read_yaml_data(API_CONFIG)
    __relevance = aconfig[PROJECT_NAME]
    # 处理测试信息
    test_info = replaceRelevance.replace(test_info, __relevance)
    logging.debug("测试信息处理结果:{}".format(test_info))
    # 处理Cookies
    if test_info['cookies']:
        cookies = aconfig[PROJECT_NAME]['cookies']
        logging.debug("请求Cookies处理结果:{}".format(cookies))

    # 判断是否存在前置接口
    pre_case_path = test_info["premise"]
    if pre_case_path:
        # 获取前置接口用例
        logging.info("获取前置接口测试用例:{}".format(pre_case_path))
        pre_case_yaml = PAGE_DIR + pre_case_path
        pre_case_path = os.path.dirname(pre_case_yaml)
        pre_case_dict = readYaml.read_yaml_data(pre_case_yaml)
        pre_test_info = pre_case_dict['test_info']
        pre_case_data = pre_case_dict['test_case'][0]
        # 判断前置接口是否也存在前置接口
        if pre_test_info["premise"]:
            init_premise(pre_test_info, pre_case_data, pre_case_path)

        for i in range(3):
            # 处理前置接口测试信息
            pre_test_info = replaceRelevance.replace(pre_test_info,
                                                     __relevance)
            logging.debug("测试信息处理结果:{}".format(pre_test_info))
            # 处理前置接口Cookies
            if pre_test_info['cookies']:
                cookies = aconfig[PROJECT_NAME]['cookies']
                logging.debug("请求Cookies处理结果:{}".format(cookies))
            # 处理前置接口入参:获取入参-替换关联值-发送请求
            pre_parameter = read_json(pre_case_data['summary'],
                                      pre_case_data['parameter'],
                                      pre_case_path)
            pre_parameter = replaceRelevance.replace(pre_parameter,
                                                     __relevance)
            pre_case_data['parameter'] = pre_parameter
            logging.debug("请求参数处理结果:{}".format(pre_parameter))
            logging.info("执行前置接口测试用例:{}".format(pre_test_info))
            code, data = apiSend.send_request(pre_test_info, pre_case_data)

            # 检查接口是否调用成功
            if data:
                # 处理当前接口入参:获取入参-获取关联值-替换关联值
                parameter = read_json(case_data['summary'],
                                      case_data['parameter'], case_path)
                __relevance = readRelevance.get_relevance(
                    data, parameter, __relevance)
                parameter = replaceRelevance.replace(parameter, __relevance)
                case_data['parameter'] = parameter
                logging.debug("请求参数处理结果:{}".format(parameter))

                # 获取当前接口期望结果:获取期望结果-获取关联值-替换关联值
                expected_rs = read_json(
                    case_data['summary'],
                    case_data['check_body']['expected_result'], case_path)
                parameter['data'] = data
                __relevance = readRelevance.get_relevance(
                    parameter, expected_rs, __relevance)
                expected_rs = replaceRelevance.replace(expected_rs,
                                                       __relevance)
                case_data['check_body']['expected_result'] = expected_rs
                logging.debug("期望返回处理结果:{}".format(case_data))
                break
            else:
                time.sleep(1)
                logging.error("前置接口请求失败!等待1秒后重试!")
        else:
            logging.info("前置接口请求失败!尝试三次失败!")
            raise Exception("获取前置接口关联数据失败!")
    else:
        # 处理当前接口入参:获取入参-获取关联值-替换关联值
        parameter = read_json(case_data['summary'], case_data['parameter'],
                              case_path)
        parameter = replaceRelevance.replace(parameter, __relevance)
        case_data['parameter'] = parameter
        logging.debug("请求参数处理结果:{}".format(parameter))

        # 获取当前接口期望结果:获取期望结果-获取关联值-替换关联值
        expected_rs = read_json(case_data['summary'],
                                case_data['check_body']['expected_result'],
                                case_path)
        __relevance = readRelevance.get_relevance(parameter, expected_rs,
                                                  __relevance)
        expected_rs = replaceRelevance.replace(expected_rs, __relevance)
        case_data['check_body']['expected_result'] = expected_rs
        logging.debug("期望返回处理结果:{}".format(case_data))

    return test_info, case_data
コード例 #7
0
# -*- coding:utf-8 -*-
# @Time    : 2020/12/03
# @Author  : Leo Zhang
# @File    : __init__.py
# ***********************
from comm.utils.readYaml import read_yaml_data
import os

# 获取主目录路径
ROOT_DIR = str(os.path.realpath(__file__)).split('config')[0].replace(
    '\\', '/')

# 获取配置文件路径
API_CONFIG = ROOT_DIR + 'config/apiConfig.yml'
RUN_CONFIG = ROOT_DIR + 'config/runConfig.yml'
DB_CONFIG = ROOT_DIR + 'config/dbConfig.yml'

# 获取运行配置信息
RC = read_yaml_data(RUN_CONFIG)
INTERVAL = RC['interval']
PROJECT_NAME = RC['project_name']

# 接口数据目录(.chlsj文件)
DATA_DIR = ROOT_DIR + PROJECT_NAME + '/data'
# 测试数据目录(test.yaml)
PAGE_DIR = ROOT_DIR + PROJECT_NAME + '/page'
# 测试脚本目录(test.py)
TEST_DIR = ROOT_DIR + PROJECT_NAME + '/testcase'
# 测试报告目录(xml|html)
REPORT_DIR = ROOT_DIR + PROJECT_NAME + '/report'