Exemplo n.º 1
0
    def test_register(self, data_namedtuple):
        """
        测试注册功能
        :return:
        """
        url = do_config("api", "url") + data_namedtuple.url
        new_data = HandleContext().register_parameterization(data_namedtuple.data)

        do_log.info("\n正在运行的测试用例为:{}".format(data_namedtuple.title))
        response = self.send_request(method=data_namedtuple.method, url=url, data=new_data)

        # 判断服务器是否有异常
        try:
            self.assertEqual(200, response.status_code,
                             msg="测试【{}】失败,http请求状态码为【{}】".
                             format(data_namedtuple.title, response.status_code))
        except AssertionError as e:
            do_log.error("\n具体异常信息为:{}\n".format(e))
            raise e

        try:
            self.assertEqual(data_namedtuple.expected,
                             response.text,
                             msg="测试{}失败".format(data_namedtuple.title))
        except AssertionError as e:
            do_log.error("\n具体异常信息为:{}\n".format(e))

            self.do_excel.write_result(row=data_namedtuple.case_id+1,
                                       actual=response.text,
                                       result=do_config("msg", "fail_result"))
            raise e
        else:
            self.do_excel.write_result(row=data_namedtuple.case_id+1,
                                       actual=response.text,
                                       result=do_config("msg", "success_result"))
Exemplo n.º 2
0
    def __init__(self):
        self.case_logger = logging.getLogger(do_config("log", "logger_name"))

        self.case_logger.setLevel(do_config("log", "logger_level"))

        console_handle = logging.StreamHandler()
        # ConcurrentRotatingFileHandle,其它一样
        file_handle = RotatingFileHandler(
            os.path.join(LOGS_DIR, do_config("log", "logging_file")),
            maxBytes=do_config("log", "file_size") * 1024,
            backupCount=do_config("log", "backupCount"),
            encoding="utf8")

        console_handle.setLevel(do_config("log", "console_level"))
        file_handle.setLevel(do_config("log", "file_level"))

        simple_formatter = logging.Formatter(
            do_config("log", "simple_formatter"))  # 简单的日志格式
        complex_formatter = logging.Formatter(
            do_config("log", "complex_formatter"))
        console_handle.setFormatter(simple_formatter)
        file_handle.setFormatter(complex_formatter)

        self.case_logger.addHandler(console_handle)
        self.case_logger.addHandler(file_handle)
Exemplo n.º 3
0
def create_new_user(regname, pwd="Gl123456"):
    """
    创建一个用户
    :param pwd:
    :param regname:
    :return:
    """
    handle_mysql = HandleMysql()
    send_request = HandleRequest()
    url = do_config("api", "url") + "/member/register"
    sql = "SELECT Id FROM member WHERE MobilePhone=%s;"
    while True:
        mobilephone = handle_mysql.create_not_existed_tel()
        data = {"mobilephone": mobilephone, "pwd": pwd, "regname": regname}
        send_request(method="post", url=url, data=data)
        result = handle_mysql(sql=sql, args=(mobilephone,))

        if result:
            user_id = result["Id"]
            break

    user_dict = {
        regname: {
            "Id": user_id,
            "regname": regname,
            "mobilephone": mobilephone,
            "pwd": pwd
        }
    }

    handle_mysql.close()
    send_request.close()

    return user_dict
Exemplo n.º 4
0
    def test_invest(self, data_namedtuple):
        """
        测试投资功能
        :return:
        """
        do_log.info("\n正在运行的测试用例为:{}".format(data_namedtuple.title))
        method = data_namedtuple.method
        url = do_config("api", "url") + data_namedtuple.url
        print(url)
        new_data = HandleContext().invest_parameterization(data_namedtuple.data)
        print(new_data)
        response = self.send_request(method=method, url=url, data=new_data)
        print(response.text)
        # 判断服务器是否有异常
        try:
            self.assertEqual(200, response.status_code,
                             msg="测试【{}】失败,http请求状态码为【{}】".
                             format(data_namedtuple.title, response.status_code))
        except AssertionError as e:
            do_log.error("\n具体异常信息为:{}\n".format(e))
            raise e

        # 判断是否加标成功,加标成功,获取loan_id
        if response.json().get("msg") == "加标成功":
            check_sql = data_namedtuple.check_sql
            if check_sql:
                check_sql = HandleContext().invest_parameterization(check_sql)
                mysql_data = self.handle_mysql(sql=check_sql)  # 获取一条记录
                HandleContext.loan_id = mysql_data["Id"]  # 动态添加属性,获取标的Id
                # setattr(HandleContext, "loan_id", mysql_data["Id"])   # 动态创建类属性,获取标的Id

        # 验证预期结果是否与实际结果相同
        try:
            self.assertEqual(data_namedtuple.expected,
                             response.text,
                             msg="测试{}失败".format(data_namedtuple.title))

        except AssertionError as e:
            do_log.error("\n具体异常信息为:{}\n".format(e))
            self.do_excel.write_result(row=data_namedtuple.case_id+1,
                                       actual=response.text,
                                       result=do_config("msg", "fail_result"))
            raise e
        else:
            self.do_excel.write_result(row=data_namedtuple.case_id+1,
                                       actual=response.text,
                                       result=do_config("msg", "success_result"))
Exemplo n.º 5
0
    def write_result(self, row, actual, result):
        """
        将实际值与测试用例执行的结果保存到excel中
        :param row:行号
        :param actual:实际值
        :param result:测试结果
        :return:
        """
        other_wb = load_workbook(self.filename)
        other_ws = other_wb[self.sheetname]

        if isinstance(row, int) and (2 <= row <= self.ws.max_row):
            other_ws.cell(row=row,
                          column=do_config("excel", "actual_col"),
                          value=actual)
            other_ws.cell(row=row,
                          column=do_config("excel", "result_col"),
                          value=result)
            other_wb.save(self.filename)
Exemplo n.º 6
0
 def __init__(self):
     self.conn = pymysql.connect(host=do_config("mysql", "host"),
                                 user=do_config("mysql", "user"),
                                 password=do_config("mysql", "password"),
                                 port=do_config("mysql", "port"),
                                 db=do_config("mysql", "db"),
                                 charset=do_config("mysql", "charset"),
                                 cursorclass=pymysql.cursors.DictCursor)
     self.cursor = self.conn.cursor()
Exemplo n.º 7
0
    def test_add(self, data_namedtuple):
        """
        测试加标功能
        :return:
        """
        url = do_config("api", "url") + data_namedtuple.url
        new_data = HandleContext().add_parameterization(data_namedtuple.data)
        print(new_data)
        do_log.info("\n正在运行的测试用例为:{}".format(data_namedtuple.title))
        # 接口不支持json格式,只支持form表单,is_json=False, 使用data
        response = self.send_request(method=data_namedtuple.method, url=url, data=new_data)
        print(response.text)

        # 判断服务器是否有异常
        try:
            self.assertEqual(200, response.status_code,
                             msg="测试【{}】失败,请求状态码为【{}】"
                             .format(data_namedtuple.title, response.status_code))
        except AssertionError as e :  # 出现异常,后面代码不会执行
            do_log.error("{},执行结果:{}\n具体异常信息:{}\n".format(data_namedtuple.title, "fail", e))
            raise e

        try:
            self.assertEqual(data_namedtuple.expected,
                             response.text,
                             msg="测试{}失败".format(data_namedtuple.title))
        except AssertionError as e:
            do_log.error("\n具体异常信息为:{}\n".format(e))
            self.do_excel.write_result(row=data_namedtuple.case_id+1,
                                       actual=response.text,
                                       result=do_config("msg", "fail_result"))
            raise e
        else:
            self.do_excel.write_result(row=data_namedtuple.case_id+1,
                                       actual=response.text,
                                       result=do_config("msg", "success_result"))
Exemplo n.º 8
0
import os
import unittest
from datetime import datetime

from libs.HTMLTestRunnerNew import HTMLTestRunner  # 网上大佬修改的
# from HTMLTestRunner_PY3 import HTMLTestRunner  # 我自己搜的
from scripts.handle_config import do_config
from scripts.constants import CASES_DIR, REPORTS_DIR, USER_ACCOUNTS_FILE_PATH
from scripts.handle_user import generate_users_config

# 如果用户配置文件不存在,则新建
if not os.path.isfile(USER_ACCOUNTS_FILE_PATH):
    generate_users_config()

# 加载CASES_DIR目录下,以test*开头的模块
one_suite = unittest.defaultTestLoader.discover(CASES_DIR)
# 3.执行用例
report_html_name = os.path.join(REPORTS_DIR,
                                do_config("report", "report_html_name"))
report_html_name_full = report_html_name + "_" + datetime.strftime(
    datetime.now(), "%Y%m%d%H%M%S") + ".html"
with open(report_html_name_full, mode="wb") as save_to_file:
    one_runner = HTMLTestRunner(
        stream=save_to_file,
        verbosity=do_config("report", "verbosity"),  # 日志详细程度
        title=do_config("report", "title"),
        description=do_config("report", "description"),
        tester=do_config("report", "tester"))

    one_runner.run(one_suite)  # 批量执行套件中的用例
Exemplo n.º 9
0
    def test_recharge(self, data_namedtuple):
        """
        测试充值功能
        :return:
        """
        do_log.info("\n正在运行的测试用例为:{}".format(data_namedtuple.title))
        method = data_namedtuple.method
        url = do_config("api", "url") + data_namedtuple.url
        new_data = HandleContext().recharge_parameterization(
            data_namedtuple.data)
        check_sql = data_namedtuple.check_sql

        # 充值之前用户的剩余金额
        if check_sql:
            check_sql = HandleContext().recharge_parameterization(check_sql)
            mysql_data = self.handle_mysql(sql=check_sql)  # 获取一条记录
            amount_before_recharge = float(
                mysql_data["LeaveAmount"])  # decimal类型数据转换成float类型
            amount_before_recharge = round(amount_before_recharge, 2)  # 保留两位小数

        response = self.send_request(method=method, url=url, data=new_data)

        # 判断服务器是否有异常
        try:
            self.assertEqual(200,
                             response.status_code,
                             msg="测试【{}】失败,http请求状态码为【{}】".format(
                                 data_namedtuple.title, response.status_code))
        except AssertionError as e:
            do_log.error("\n具体异常信息为:{}\n".format(e))
            raise e

        response = response.text  # 获取json格式数据
        # 将复杂的数据赋值为空,之后单独验证
        if check_sql:
            response = json.loads(response, encoding="utf8")
            response["data"] = None
            response = json.dumps(
                response, ensure_ascii=False)  # ensure_ascii为False,可将乱码转换成中文

        # 验证预期结果是否与实际结果相同
        try:
            self.assertEqual(data_namedtuple.expected,
                             response,
                             msg="测试{}失败".format(data_namedtuple.title))

            # 充值之后用户的剩余金额
            if check_sql:
                check_sql = HandleContext().recharge_parameterization(
                    check_sql)
                mysql_data = self.handle_mysql(sql=check_sql)
                amount_after_recharge = float(mysql_data["LeaveAmount"])
                actual_amount = round(amount_after_recharge, 2)
                recharge_amount = float(
                    json.loads(new_data, encoding="utf8").get("amount"))
                excepted_amount = round(
                    amount_before_recharge + recharge_amount, 2)
                # 服务器返回复杂数据的验证,这里验证充值金额
                self.assertEqual(excepted_amount,
                                 actual_amount,
                                 msg="数据库中充值的金额有误")

        except AssertionError as e:
            do_log.error("\n具体异常信息为:{}\n".format(e))
            self.do_excel.write_result(row=data_namedtuple.case_id + 1,
                                       actual=response,
                                       result=do_config("msg", "fail_result"))
            raise e
        else:
            self.do_excel.write_result(row=data_namedtuple.case_id + 1,
                                       actual=response,
                                       result=do_config(
                                           "msg", "success_result"))