Example #1
0
class TestAdd(unittest.TestCase):

    logger.info('开始执行TestAdd测试类')

    testdata = DoExcel(case_file, 'add').read_data()

    @classmethod
    def setUpClass(cls):
        cls.session = HttpRequest2()
        cls.mysql = DoMysql()

    @data(*testdata)
    def testInvest(self, case):
        case.data = Context().replace(
            case.data)  #使用正则表达式,将Excel中参数化的值替换为配置文件中读取出来的值
        res = self.session.request(method=case.method,
                                   url=case.url,
                                   data=case.data)
        logger.info('执行用例是:{},请求url是:{}'.format(case.title, case.url))
        logger.info('请求数据是:{}'.format(case.data))
        try:
            self.assertEqual(case.expected, int(res.json()["code"]))
        except AssertionError as e:
            DoExcel(case_file, 'add').write_data(case.case_id + 1, res.text,
                                                 'failed')
            logger.error("断言失败,错误信息是:{}".format(e))
        else:
            DoExcel(case_file, 'add').write_data(case.case_id + 1, res.text,
                                                 'pass')
            logger.info('用例执行成功')
            if res.json()['msg'] == '加标成功':
                case.sql = Context().replace(case.sql)
                loadId = self.mysql.fetch_one(case.sql)['id']
                setattr(Context, 'loanId', str(loadId))
Example #2
0
    def test_register(self, case):  # 测试注册
        logger.info("开始执行第{}条用例: {}".format(case.case_id, case.title))
        logger.debug('url:{}'.format(case.url))
        logger.debug('data:{}'.format(case.data))
        logger.debug('method:{}'.format(case.method))
        logger.debug('expected:{}'.format(case.expected))
        data_dict = json.loads(case.data)
        if data_dict['mobilephone'] == '#@mobilephone':
            # 取最大电话号码+1
            data_dict['mobilephone'] = int(self.max) + 1
        # resp = self.request.request(case.method, case.url, data_dict)

        data_dict = json.dumps(data_dict)  # 把字典转换成字符串传入context进行转换
        # print(data_dict, type(data_dict))
        register_data_new = Context.replace_new(data_dict)
        resp = self.request.request(case.method, case.url, register_data_new)

        try:
            # self.assertEqual(case.expected, resp.text)
            self.assertEqual(case.expected, json.loads(resp.text)['code'])
            self.do_excel_regitser.write_excel('register', case.case_id + 1,
                                               resp.text,
                                               'PASS')  # 读取sheet,写入结果
            logger.info("第{0}用例执行结果:PASS".format(case.case_id))
        except AssertionError as e:
            self.do_excel_regitser.write_excel('register', case.case_id + 1,
                                               resp.text, 'FAIL')
            logger.error("第{0}用例执行结果:FAIL".format(case.case_id))
            logger.error("断言出错了".format(e))
            raise e
class TestLogin(unittest.TestCase):

    logger.info('开始执行TestLogin测试类')

    testdata = DoExcel(contants.case_file, 'login').read_data()

    @classmethod
    def setUpClass(cls):
        cls.session = HttpRequest2()

    @data(*testdata)
    def testLogin(self, case):
        case.data = Context().replace(case.data)
        res = self.session.request(method=case.method,
                                   url=case.url,
                                   data=case.data)
        logger.info('执行用例是:{},请求url是:{}'.format(case.title, case.url))
        logger.info('请求数据是:{}'.format(case.data))
        try:
            self.assertEqual(case.expected, res.text)
        except AssertionError as e:
            DoExcel(contants.case_file,
                    'login').write_data(case.case_id + 1, res.text, 'failed')
            logger.error('断言出错,错误信息是:{}'.format(e))
        else:
            DoExcel(contants.case_file,
                    'login').write_data(case.case_id + 1, res.text, 'pass')
            logger.info('用例执行成功')
Example #4
0
class TestInvest(unittest.TestCase):

    logger.info('开始执行TestInvest测试类')

    testdata = DoExcel(case_file, 'invest').read_data()

    @classmethod
    def setUpClass(cls):
        cls.session = HttpRequest2()
        cls.mysql = DoMysql()

    @data(*testdata)
    def testInvest(self, case):
        case.data = Context().replace(
            case.data)  #使用正则表达式,将Excel中参数化的值替换为配置文件中读取出来的值
        if case.sql is not None:
            case.sql = Context().replace(case.sql)
 def testSendMCode(self,case):
     logger.info('执行用例是:{},请求url是:{},请求数据是:{}'.format(case.title, case.url, case.data))
     try:
         case.data = Context().replace(case.data)
         res = Request('sendMCode').request(case.url,eval(case.data))
         try:
             self.assertEqual(res['retCode'],eval(case.expected)['retCode'])
             self.excel.write_data(case.case_id+1, str(res), 'pass')
             if res['retCode'] == '0' and res['retInfo'] == 'ok':
                 case.sql = Context().replace(case.sql)
                 mcode = self.mysql.fetch_one(case.sql)['Fverify_code']
                 if mcode:
                     logger.info('成功获取验证码:{}'.format(mcode))
                 else:
                     logger.info('获取验证码失败')
         except AssertionError as e:
             self.excel.write_data(case.case_id + 1, str(res), 'filed')
             logger.error('断言失败,错误是:{}'.format(e))
class TestRecharge(unittest.TestCase):

    logger.info('开始执行TestRecharge测试类')

    testdata = DoExcel(contants.case_file,'recharge').read_data()

    @classmethod
    def setUpClass(cls):
        cls.session = HttpRequest2()
        cls.mysql = DoMysql()

    @data(*testdata)
    def testRecharge(self,case):
        case.data = Context().replace(case.data)
        if case.title == '充值成功':
            case.sql = Context().replace(case.sql)
            before_leaveamount = self.mysql.fetch_one(case.sql)['leaveamount']
            logger.info('用例开始执行前,账户余额是:{}'.format(before_leaveamount))
Example #7
0
    def test_register(self, case):  # 测试注册
        logger.info("开始执行第{}条用例: {}".format(case.case_id, case.title))
        logger.debug('url:{}'.format(case.url))
        logger.debug('data:{}'.format(case.data))
        logger.debug('method:{}'.format(case.method))
        logger.debug('expected:{}'.format(case.expected))
        data_dict = json.loads(case.data)
        if data_dict['mobilephone'] == '#@mobilephone':
            # 取最大电话号码+1
            data_dict['mobilephone'] = int(self.max) + 1
        # resp = self.request.request(case.method, case.url, data_dict)

        data_dict = json.dumps(data_dict)  # 把字典转换成字符串传入context进行转换
        # print(data_dict, type(data_dict))
        register_data_new = Context.replace_new(data_dict)
        resp = self.request.request(case.method, case.url, register_data_new)

        try:
            self.assertEqual(case.expected, resp.text, 'register error')
            if resp.json()['msg'] == '注册成功':
                sql = 'select * from future.member where mobilephone = {0}'\
                    .format(json.loads(data_dict)['mobilephone'])
                results = self.mysql.fetch_all(sql)
                # 首先判断是否有成功插入数据
                self.assertEqual(1, len(results))
                member = results[0]  # 获取到这一条数据,是一个字典
                self.assertEqual(0, member['LeaveAmount'])  # 判断注册成功余额应该是0
                # print(member['LeaveAmount'],type(member['LeaveAmount']))
                self.assertEqual(1, member['Type'])  # 判断注册用户类型是1
                # print(member['Type'])
                self.assertNotEqual(
                    json.loads(register_data_new)['pwd'],
                    member['Pwd'])  # 判断密码是否加密
                if 'regname' in json.loads(register_data_new).keys():
                    self.assertEqual(
                        json.loads(register_data_new)['regname'],
                        member['RegName'])
                else:
                    self.assertEqual('小蜜蜂', member['RegName'])
            # 一致就写入Excel的结果为PASS,并且
            self.do_excel.write_excel('register', case.case_id + 1, resp.text,
                                      'PASS')  # 读取sheet,写入结果
            logger.info("第{0}用例执行结果:PASS".format(case.case_id))
        except AssertionError as e:
            self.do_excel.write_excel('register', case.case_id + 1, resp.text,
                                      'FAIL')
            logger.error("第{0}用例执行结果:FAIL".format(case.case_id))
            logger.error("断言出错了".format(e))
            raise e
Example #8
0
 def setUpClass(cls):
     cls.http_request = HttpSessions()
     warnings.simplefilter("ignore", ResourceWarning)
     cls.context = Context()
Example #9
0
import os
import sys
import time
from locust import FastHttpUser, task, between, constant, tag
from bs4 import BeautifulSoup
import locust_plugins

sys.path.append(os.path.dirname(__file__) + '/..')

from common.context import Context
from common.api import Api

context = Context()


class Imports(FastHttpUser):
    def on_start(self):
        self.api = Api(self.client, context)

    @task
    def call_api(self):
        self.api.import_products(10)


class Stocks(FastHttpUser):
    def on_start(self):
        self.api = Api(self.client, context)

    @task
    def call_api(self):
        self.api.update_stock(25)
Example #10
0
 def __init__(self, http_client_session=None):
     self.http_client_session = http_client_session
     self.context = Context()
Example #11
0
class Runner(object):
    def __init__(self, http_client_session=None):
        self.http_client_session = http_client_session
        self.context = Context()

    def init_config(self, config_dict, level):
        """ create/update context variables binds
        @param (dict) config_dict
            {
                "name": "description content",
                "requires": ["random", "hashlib"],
                "function_binds": {
                    "gen_random_string": \
                        "lambda str_len: ''.join(random.choice(string.ascii_letters + \
                        string.digits) for _ in range(str_len))",
                    "gen_md5": \
                        "lambda *str_args: hashlib.md5(''.join(str_args).\
                        encode('utf-8')).hexdigest()"
                },
                "import_module_functions": ["test.data.custom_functions"],
                "variable_binds": [
                    {"TOKEN": "debugtalk"},
                    {"random": "${gen_random_string(5)}"},
                ]
            }
        @param (str) context level, testcase or testset
        """
        self.context.init_context(level)

        requires = config_dict.get('requires', [])
        self.context.import_requires(requires)

        function_binds = config_dict.get('function_binds', {})
        self.context.bind_functions(function_binds, level)

        module_functions = config_dict.get('import_module_functions', [])
        self.context.import_module_functions(module_functions, level)

        variable_binds = config_dict.get('variable_binds', [])
        self.context.bind_variables(variable_binds, level)

        request_config = config_dict.get('request', {})
        if level == "testset":
            base_url = request_config.pop("base_url", None)
            self.http_client_session = self.http_client_session or HttpSession(
                base_url)
        else:
            # testcase
            self.http_client_session = self.http_client_session or requests.Session(
            )
        self.context.register_request(request_config, level)

    def run_test(self, testcase, runNum):
        """ run single testcase.
        @param (dict) testcase
            {
                "name": "testcase description",
                "times": 3,
                "requires": [],  # optional, override
                "function_binds": {}, # optional, override
                "variable_binds": {}, # optional, override
                "request": {
                    "url": "http://127.0.0.1:5000/api/users/1000",
                    "method": "POST",
                    "headers": {
                        "Content-Type": "application/json",
                        "authorization": "$authorization",
                        "random": "$random"
                    },
                    "body": '{"name": "user", "password": "******"}'
                },
                "extract_binds": {}, # optional
                "validators": []     # optional
            }
        @return (tuple) test result of single testcase
            (success, diff_content_list)
        """

        self.init_config(testcase, level="testcase")
        parsed_request = self.context.get_parsed_request()

        try:
            url = parsed_request.pop('url')
            method = parsed_request.pop('method')
        except KeyError:
            raise exception.ParamsError("URL or METHOD missed!")

        #print parsed_request
        if parsed_request.get("files"):
            for key in parsed_request.get("files"):
                parsed_request.get("files")[key] = [
                    None, parsed_request.get("files")[key]
                ]
        #print parsed_request

        run_times = int(testcase.get("times", 1))
        extract_binds = testcase.get("extract_binds", {})
        validators = testcase.get("validators", [])

        for _ in range(run_times):
            resp = self.http_client_session.request(url=url,
                                                    method=method,
                                                    **parsed_request)
            resp_obj = response.ResponseObject(resp)

            extracted_variables_mapping_list = resp_obj.extract_response(
                extract_binds)
            self.context.bind_variables(extracted_variables_mapping_list,
                                        level="testset")

            diff_content_list = resp_obj.validate(
                validators, self.context.get_testcase_variables_mapping())

            testResult = 0
            # mockid = mockid + 1
            diff = str(diff_content_list)
            casename = testcase.get("name")
            if not diff_content_list:
                diff = {""}
                testResult = 1

            sql = "insert into auto_result(mockid,name,testresult,reqmethod,rspcode,reqpath,reqhead,reqbody,rsphead,rspbody,diff,ts) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
            params = (runNum, casename, testResult, resp.request.method,
                      resp.status_code, resp.request.url, resp.request.headers,
                      resp.request.body, resp.headers, resp.content, diff,
                      datetime.datetime.now())

            count = db.updateByParam(sql, params)
            print count

        return resp_obj.success, diff_content_list

    def run_testset(self, testset):
        """ run single testset, including one or several testcases.
        @param (dict) testset
            {
                "name": "testset description",
                "config": {
                    "name": "testset description",
                    "requires": [],
                    "function_binds": {},
                    "variable_binds": [],
                    "request": {}
                },
                "testcases": [
                    {
                        "name": "testcase description",
                        "variable_binds": {}, # optional, override
                        "request": {},
                        "extract_binds": {},  # optional
                        "validators": {}      # optional
                    },
                    testcase12
                ]
            }
        @return (list) test results of testcases
            [
                (success, diff_content),    # testcase1
                (success, diff_content)     # testcase2
            ]
        """
        results = []

        config_dict = testset.get("config", {})
        self.init_config(config_dict, level="testset")
        testcases = testset.get("testcases", [])
        for testcase in testcases:
            result = self.run_test(testcase)
            results.append(result)

        return results

    def run_testsets(self, testsets):
        """ run testsets, including one or several testsets.
        @param testsets
            [
                testset1,
                testset2,
            ]
        @return (list) test results of testsets
            [
                [   # testset1
                    (success, diff_content),    # testcase11
                    (success, diff_content)     # testcase12
                ],
                [   # testset2
                    (success, diff_content),    # testcase21
                    (success, diff_content)     # testcase22
                ]
            ]
        """
        return [self.run_testset(testset) for testset in testsets]
     setattr(Context, 'register_phone', str(max_phone))
 elif case.data.__contains__(
         "user_id") and case.data["user_id"] == "name":
     name = RandomCreate().create_name()
     case.data["user_id"] = name
     setattr(Context, 'name', name)
 if case.title == '正常发送验证码':
     logger.info('执行用例是:{},请求url是:{},请求数据是:{}'.format(
         case.title, case.url, case.data))
     res = Request('sendMCode').request(case.url, case.data)
     try:
         self.assertEqual(res['retInfo'],
                          eval(case.expected)['retInfo'])
         self.excel.write_data(case.case_id + 1, str(res), 'pass')
         if res['retCode'] == '0' and res['retInfo'] == 'ok':
             case.sql = Context().replace(case.sql)
             verify_code = self.mysql.fetch_one(
                 case.sql)['Fverify_code']
             setattr(Context, 'verify_code', verify_code)
             logger.info("成功发送验证码,验证码为:{}".format(verify_code))
     except AssertionError as e:
         self.excel.write_data(case.case_id + 1, str(res), 'failed')
         logger.error("验证码发送失败,错误是:{}".format(e))
 elif case.title == '成功注册':
     case.data = Context().replace(str(case.data))
     logger.info('执行用例是:{},请求url是:{},请求数据是:{}'.format(
         case.title, case.url, case.data))
     res = Request('userRegister').request(case.url, eval(case.data))
     try:
         self.assertEqual(res['retInfo'],
                          eval(case.expected)['retInfo'])
Example #13
0
 def setUpClass(cls):
     cls.request = Request()  # 建立session会话,实例化对象
     cls.context = Context()
     cls.mysql = MysqlUtil()  #实例化mysql对象,实例化一次即可