Exemplo n.º 1
0
class adminUser:
    """
    系统管理-后台用户管理
    """
    def __init__(self):
        self.log = Log()
        self.test_data = get_test_data('bms_test_data.xlsx',
                                       'systemManagement', 0)
        self.url = get_host('test') + self.test_data['url']
        self.payload = json.loads(self.test_data['data'])
        self.header = json.loads(self.test_data['header'])
        self.header['authorization'] = getBmsToken().get_token()
        self.method = self.test_data['method']

    def get_admin_user(self):
        """
        获取bms后台管理用户列表
        :return:
        """
        try:
            resp = get_response(self.url,
                                self.method,
                                data=json.dumps(self.payload),
                                headers=self.header)  # 未解密接口返回
            resp_str = getJsonStr(
                resp.json()['data']).get_json_str()  # 解密接口返回数据
            resp = resp.json()
            resp['data'] = resp_str['data']
            return resp
        except Exception as e:
            self.log.error('获取bms后台用户接口异常:{},请检查'.format(str(e)))
Exemplo n.º 2
0
class addAdminUser:
    """
    系统管理-新增后台管理用户
    """

    def __init__(self):
        self.log = Log()
        self.test_data = get_test_data('bms_test_data.xlsx', 'systemManagement', 1)
        self.url = get_host('test') + self.test_data['url']
        self.payload = json.loads(self.test_data['data'])
        self.header = json.loads(self.test_data['header'])
        self.header['authorization'] = getBmsToken().get_token()
        self.method = self.test_data['method']

    def add_admin_user(self):
        """
        新增bms后台管理用户
        :return:
        """
        if databaseOperations().select_user('sys_user', 'username'):
            databaseOperations().delete_user('sys_user', 'username')
        try:
            resp = get_response(self.url, self.method, data=json.dumps(self.payload), headers=self.header)  # 未解密接口返回
            resp_str = getJsonStr(resp.json()['data']).get_json_str()  # 解密接口返回数据
            resp = resp.json()
            resp['data'] = resp_str['data']
            return resp
        except Exception as e:
            self.log.error('新增bms后台管理用户接口异常:{},请检查'.format(str(e)))
Exemplo n.º 3
0
class getBmsToken(object):
    def __init__(self):
        self.test_data = get_test_data('bms_test_data.xlsx', 'login', 0)
        self.log = Log()
        self.url = get_host('test') + self.test_data['url']
        self.method = self.test_data['method']
        self.payload = self.test_data['data']
        self.header = json.loads(self.test_data['header'])

    def get_token(self):
        """
        获取bms登录token
        :return:token.txt
        """
        try:
            while True:
                resp = get_response(self.url,
                                    self.method,
                                    data=self.payload,
                                    headers=self.header)
                if resp.json().get('access_token'):
                    token = resp.json()['token_type'] + ' ' + resp.json(
                    )['access_token']
                    return token
        except Exception as e:
            self.log.error('获取token出现异常:{},请检查登录接口请求'.format(str(e)))
Exemplo n.º 4
0
class userBetDetails:
    """
    会员中心--回去会员注单详情
    """
    def __init__(self):
        self.log = Log()
        self.test_data = get_test_data('bms_test_data.xlsx', 'memberCentre', 7)
        self.user_id = getUserInfo().get_user_info()['data']['userId']
        self.url = get_host('test') + self.test_data['url']
        self.data = self.test_data['data']
        self.header = json.loads(self.test_data['header'])
        self.header['authorization'] = getBmsToken().get_token()
        self.method = self.test_data['method']

    def get_user_bet_details(self):
        """
        bms后台获取会员注单详情
        :return:
        """
        try:
            resp = get_response(self.url,
                                self.method,
                                data=self.data,
                                headers=self.header)  # 未解密接口返回
            resp_str = getJsonStr(
                resp.json()['data']).get_json_str()  # 解密接口返回数据
            resp = resp.json()
            resp['data'] = resp_str['data']
            return resp
        except Exception as e:
            self.log.error('bms后台获取会员注单详情接口异常:{},请检查'.format(str(e)))
Exemplo n.º 5
0
class memberExpensesList:
    """
    会员出款列表
    """
    def __init__(self):
        self.log = Log()
        self.test_data = get_test_data('bms_test_data.xlsx', 'financialCenter',
                                       2)
        self.url = get_host('test') + self.test_data['url']
        self.data = json.loads(self.test_data['data'])
        self.header = json.loads(self.test_data['header'])
        self.header['authorization'] = getBmsToken().get_token()
        self.method = self.test_data['method']

    def get_member_expenses_list(self):
        """
        bms-获取会员出款列表
        :return:
        """
        try:
            resp = get_response(self.url,
                                self.method,
                                data=json.dumps(self.data),
                                headers=self.header)  # 未解密接口返回
            resp_str = getJsonStr(
                resp.json()['data']).get_json_str()  # 解密接口返回数据
            resp = resp.json()
            resp['data'] = resp_str['data']
            return resp
        except Exception as e:
            self.log.error('bms后台获取会员出款列表接口异常:{},请检查'.format(str(e)))
Exemplo n.º 6
0
class userLoginLog:
    """
    会员中心-会员登录日志
    """
    def __init__(self):
        self.log = Log()
        self.test_data = get_test_data('bms_test_data.xlsx', 'memberCentre',
                                       20)
        self.url = get_host('test') + self.test_data['url']
        self.data = self.test_data['data']
        self.header = json.loads(self.test_data['header'])
        self.header['authorization'] = getBmsToken().get_token()
        self.method = self.test_data['method']

    def login_log(self):
        """
        会员登录日志
        :return:
        """
        try:
            resp = get_response(self.url,
                                self.method,
                                data=self.data,
                                headers=self.header)  # 未解密接口返回
            resp_str = getJsonStr(
                resp.json()['data']).get_json_str()  # 解密接口返回数据
            resp = resp.json()
            resp['data'] = resp_str['data']
            return resp
        except Exception as e:
            self.log.error('bms后台会员登录日志列表接口异常:{},请检查'.format(str(e)))
class resetUserPassword:
    """
    会员中心--修改会员登录密码
    """
    def __init__(self):
        self.log = Log()
        self.test_data = get_test_data('bms_test_data.xlsx', 'memberCentre', 4)
        self.user_id = getUserInfo().get_user_info()['data']['userId']
        self.url = get_host('test') + self.test_data['url'] + str(
            self.user_id) + '&passwordNew=123456'
        self.data = self.test_data['data']
        self.header = json.loads(self.test_data['header'])
        self.header['authorization'] = getBmsToken().get_token()
        self.method = self.test_data['method']

    def reset_user_password(self):
        """
        bms后台修改会员登录密码
        :return:
        """
        try:
            resp = get_response(self.url,
                                self.method,
                                data=self.data,
                                headers=self.header)  # 未解密接口返回
            resp_str = getJsonStr(
                resp.json()['data']).get_json_str()  # 解密接口返回数据
            resp = resp.json()
            resp['data'] = resp_str['data']
            return resp
        except Exception as e:
            self.log.error('bms后台修改会员登录密码接口异常:{},请检查'.format(str(e)))
Exemplo n.º 8
0
class fundFreeze:
    """
    会员中心--资金冻结
    """
    def __init__(self):
        self.log = Log()
        self.test_data = get_test_data('bms_test_data.xlsx', 'memberCentre',
                                       13)
        self.url = get_host('test') + self.test_data['url']
        self.header = json.loads(self.test_data['header'])
        self.header['authorization'] = getBmsToken().get_token()
        self.method = self.test_data['method']

    def fund_freeze(self):
        """
        资金冻结
        :return:
        """
        try:
            resp = get_response(self.url, self.method,
                                headers=self.header)  # 未解密接口返回
            resp_str = getJsonStr(
                resp.json()['data']).get_json_str()  # 解密接口返回数据
            resp = resp.json()
            resp['data'] = resp_str['data']
            return resp
        except Exception as e:
            self.log.error('bms后台资金冻结接口异常:{},请检查'.format(str(e)))
Exemplo n.º 9
0
class AddLearnRecord(unittest.TestCase):
    def setUp(self):
        self.s = requests.session()
        self.lgin = LG(self.s)  #实例化登录类
        self.uid_token = self.lgin.login()  #直接取第二部登录
        self.header = {
            'User-Agent': 'LanTingDoctor/1.3.1 (iPad; iOS 10.1.1; Scale/2.00)',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-Hans-CN;q=1',
            'Content-Type': 'application/json',
            'requestApp': '3',
            'requestclient': '2',
            'versionForApp': '2.0',
            'Authorization':
            'Basic YXBpTGFudGluZ0BtZWRsYW5kZXIuY29tOkFwaVRobWxkTWxkQDIwMTM=',
            'Connection': 'keep-alive'
        }
        self.log = Log()

    def test_addlearn_record(self):
        u'测试增加学习记录接口'
        self.log.info('--------开始测试增加学习记录接口---------')
        url = 'http://api.lesson.sunnycare.cc/v1/learn/chapadd'
        L = ['J00201']
        for i in L:
            #加入nonce
            json_data = {
                "chap_code": i,
                "timestamp": str(int(time.time())),
                "token": self.uid_token,
                "nonce": get_digit()
            }
            #加入sign
            json_data['sign'] = get_sign(json_data)
            r = self.s.post(url, headers=self.header, json=json_data)
            try:
                self.log.info('请求返回的数据是%s' % r.json())
                self.assertEqual('请求成功', r.json()['note'])
            except Exception as e:
                raise AssertionError
                self.log.error('增加章节学习记录请求失败,原因是:%s' % e)
        '''
        #数据库查询出章节code,循环加入学习
        i = 0
        while i < len(chapters):

            json_data = {"chap_code":chapters[i][0].__str__(),
                         "timestamp":str(time.time()),
                         "token":self.uid_token}
            r = self.s.post(url,headers = self.header,json=json_data)
            try:
                self.log.info('请求返回的数据是%s' % r.json())
                self.assertEqual('请求成功',r.json()['note'])
            except Exception as e:
                self.log.error('增加'+ chapters[i][0].__str__() +'章节学习记录请求失败,原因是:%s' % e )
            i += 1
        '''

    def tearDown(self):
        self.s.close()
Exemplo n.º 10
0
class Common():
    def __init__(self):

        #打开用例获取login_sheet 中的第一行用例
        self.login_case = Read_Excel('../data/smile_tasks.xlsx', 'login')
        self.login_case.open_excel()
        self.table = self.login_case.get_sheet_table()
        self.ncols = self.login_case.get_ncols(self.table)
        self.login_case_data = self.login_case.get_test_case(
            self.table, self.ncols)
        #定义一个request
        self.request = Request()
        #定义log
        self.log = Log()

    def login(self):

        #request所需要的参数
        method = self.login_case_data['method']
        url = self.login_case_data['url']
        username = self.login_case_data['username']
        password = self.login_case_data['password']
        param = {'username': username, 'password': password}

        #发送请求
        try:
            r = self.request.request(method, url, param)
            r_json = r.json()
            token = r_json['token']
        except:
            self.log.error('get token failed')

        return token
Exemplo n.º 11
0
class getAppToken(object):
    def __init__(self):
        self.test_data = get_test_data('test_data.xlsx', 'login', 0)
        # print(self.test_data)
        self.log = Log()
        self.url = self.test_data['url']
        self.method = self.test_data['method']
        self.payload = self.test_data['data']
        self.header = json.loads(self.test_data['header'])

    # @staticmethod
    def get_token(self):
        """
        获取app登录token
        :return:token
        """
        try:
            resp = get_response(self.url,
                                self.method,
                                data=self.payload,
                                headers=self.header)
            token = resp.json()['token_type'] + ' ' + resp.json(
            )['access_token']
            return token
        except Exception as e:
            self.log.error('获取token出现异常:{},请检查登录接口请求'.format(str(e)))
class ConnectSqLServer:
    """连接SqlServer数据库封装"""
    def __init__(self):
        self.log = Log()
        """判断是否连接成功"""
        try:
            self.conn = pymssql.connect(host=read_config.SQLServer_host,
                                        user=read_config.SQLServer_user,
                                        password=read_config.SQLServer_pwd,
                                        port=read_config.SQLServer_port,
                                        database='sharebuy_test',
                                        charset='utf8')
            self.log.info('数据库连接成功')
        except Exception as e:
            self.log.error('数据库链接异常! {}'.format(e))

    def execute_sql(self, sql):
        """
        执行查询语句
        返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段
        """
        cur = self.conn.cursor()
        with cur as cur:
            try:
                cur.execute(sql)
            except Exception as e:
                self.log.error('执行SQL语句出现异常:{}'.format(e))
                return False
            else:
                if 'select' in sql:  # 查询
                    resList = cur.fetchall()
                    return resList
                else:
                    self.conn.commit()
Exemplo n.º 13
0
class getUserInfo:
    """
    会员中心--获取用户资料
    """
    def __init__(self):
        self.log = Log()
        self.test_data = get_test_data('bms_test_data.xlsx', 'memberCentre', 2)
        self.url = get_host('test') + self.test_data['url'] + str(
            databaseOperations().select_userid('test10000'))
        self.data = self.test_data['data']
        self.header = json.loads(self.test_data['header'])
        self.header['authorization'] = getBmsToken().get_token()
        self.method = self.test_data['method']

    def get_user_info(self):
        """
        获取bms后台获取用户资料
        :return:
        """
        try:
            resp = get_response(self.url,
                                self.method,
                                data=self.data,
                                headers=self.header)  # 未解密接口返回
            resp_str = getJsonStr(
                resp.json()['data']).get_json_str()  # 解密接口返回数据
            resp = resp.json()
            resp['data'] = resp_str['data']
            return resp
        except Exception as e:
            self.log.error('bms后台获取用户资料接口异常:{},请检查'.format(str(e)))
Exemplo n.º 14
0
class addMemberUser:
    """
    系统管理-新增会员账户
    """

    def __init__(self):
        self.log = Log()
        self.test_data = get_test_data('bms_test_data.xlsx', 'memberCentre', 1)
        self.url = get_host('test') + self.test_data['url']
        self.payload = self.test_data['data']
        self.header = json.loads(self.test_data['header'])
        self.header['authorization'] = getBmsToken().get_token()
        self.method = self.test_data['method']

    def add_member_user(self):
        """
        bms-新增会员账户
        :return:
        """
        # 如果存在这个auto_test就先删除
        if databaseOperations().select_user('sys_user', 'username'):
            databaseOperations().delete_user('sys_user', 'username')
            print(databaseOperations().delete_user('sys_user', 'username'))
        if databaseOperations().select_user('zx_user_invite_code', 'code_val'):
            databaseOperations().delete_user('zx_user_invite_code', 'code_val')
        try:
            resp = get_response(self.url, self.method, data=self.payload, headers=self.header)  # 未解密接口返回
            resp_str = getJsonStr(resp.json()['data']).get_json_str()  # 解密接口返回数据
            resp = resp.json()
            resp['data'] = resp_str['data']
            return resp
        except Exception as e:
            self.log.error('新增会员账户接口异常:{},请检查'.format(str(e)))
Exemplo n.º 15
0
class ReadExcel:
    """读取excel数据,返回[{},{}...]"""
    def __init__(self, excel_path, sheet_name="Sheet1"):
        self.data = xlrd.open_workbook(excel_path)
        self.table = self.data.sheet_by_name(sheet_name)
        self.keys = self.table.row_values(0)  # 获取第一行作为key值
        self.rowNum = self.table.nrows  # 获取总行数
        self.colNum = self.table.ncols  # 获取总列数
        self.log = Log()

    def dict_data(self, make=True):
        if self.rowNum <= 1:
            self.log.error("总行数小于1")
        else:
            r = []
            j = 1
            if make:
                for i in list(range(self.rowNum - 1)):  # 去掉行首 self.rowNum - 1
                    s = {'rowNum': i + 2}
                    values = self.table.row_values(j)  # 从第二行取对应values值
                    for x in list(range(self.colNum)):
                        s[self.keys[x]] = values[x]
                    r.append(s)
                    j += 1
                return r  # 返回list包含的dict数据
            else:
                for i in list(range(self.rowNum - 1)):  # 去掉行首 self.rowNum - 1
                    s = {}
                    values = self.table.row_values(j)  # 从第二行取对应values值
                    s[self.keys[1]] = values[1]
                    r.append(s)
                    j += 1
                return r  # 返回list包含的dict数据
Exemplo n.º 16
0
class resetGoogle:
    """
    系统管理-重置谷歌验证码
    """
    def __init__(self):
        self.log = Log()
        self.test_data = get_test_data('bms_test_data.xlsx',
                                       'systemManagement', 2)
        self.url = get_host('test') + self.test_data['url'] + str(
            databaseOperations().select_userid('admin'))
        self.header = json.loads(self.test_data['header'])
        self.header['authorization'] = getBmsToken().get_token()
        self.method = self.test_data['method']

    def reset_google(self):
        """
        重置谷歌验证码
        :return:
        """
        try:
            resp = get_response(self.url, self.method,
                                headers=self.header)  # 未解密接口返回
            resp_str = getJsonStr(
                resp.json()['data']).get_json_str()  # 解密接口返回数据
            resp = resp.json()
            resp['data'] = resp_str['data']
            return resp
        except Exception as e:
            self.log.error('bms后台用户重置接口异常:{},请检查'.format(str(e)))
Exemplo n.º 17
0
class roleList:
    """
    系统管理-获取角色列表
    """
    def __init__(self):
        self.log = Log()
        self.test_data = get_test_data('bms_test_data.xlsx',
                                       'systemManagement', 4)
        self.url = get_host('test') + self.test_data['url']
        self.header = json.loads(self.test_data['header'])
        self.header['authorization'] = getBmsToken().get_token()
        self.method = self.test_data['method']

    def get_role_list(self):
        """
        获取bms后台角色列表
        :return:
        """
        try:
            resp = get_response(self.url, self.method,
                                headers=self.header)  # 未解密接口返回
            resp_str = getJsonStr(
                resp.json()['data']).get_json_str()  # 解密接口返回数据
            resp = resp.json()
            resp['data'] = resp_str['data']
            return resp
        except Exception as e:
            self.log.error('bms后台获取角色列表接口异常:{},请检查'.format(str(e)))
Exemplo n.º 18
0
class ConnectMySqL:
    """
    连接mysql数据库封装

    """
    def __init__(self):
        self.log = Log()
        """判断是否连接成功"""
        try:
            self.conn = pymysql.connect(host=read_config.MySQL_host,
                                        database=read_config.MySQL_database,
                                        user=read_config.MySQL_user,
                                        password=read_config.MySQL_pwd,
                                        port=int(read_config.MySQL_port),
                                        charset='utf8')
            self.log.info('数据库连接成功')
        except Exception as e:
            self.log.error('数据库链接异常! {}'.format(e))

    def execute_sql(self, sql, dict_type=False, num=1):
        """返回查询结果集
            sql: 执行的sql语句;
            dict_type: 是否返回的数据是字典类型;
            num: 返回的数据是一个还是多个
        """
        if dict_type:  # 返回数据字典类型
            cur = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
        else:
            cur = self.conn.cursor()
        try:
            with cur as cur:
                cur.execute(sql)  # 执行sql
            if 'delete' in sql:
                self.conn.commit()  # 提交
            else:
                if num == 1:  # 返回一条数据
                    data = cur.fetchone()
                    if dict_type:
                        return data
                    else:
                        return data[0]
                else:  # 返回多条数据
                    data_str = ''
                    data = cur.fetchall()
                    if dict_type:
                        return data
                    else:
                        for i in data:
                            for j in i:
                                data_str += str(j) + ','  # 拼接返回数据
                        return data_str
        except Exception as e:
            self.conn.rollback()
            self.log.error('执行SQL语句出现异常:{}'.format(e))
            return None

    def __del__(self):
        self.conn.close()
Exemplo n.º 19
0
 def validate(self, instance):
     log = Log()
     with open(self.file_path, 'r', encoding='utf-8') as f:
         schema = json.load(f)
     validator = Draft4Validator(schema)
     result = validator.is_valid(instance)
     for error in sorted(validator.iter_errors(instance), key=str):
         log.error(error)
     return result
Exemplo n.º 20
0
class MyRequestMethod(object):
    def __init__(self):
        self.log = Log()

    def get(self, url, **kwargs):
        """
        封装get方法
        :param url:
        :param kwargs:
        :return:
        """
        params = kwargs.get("params")
        headers = kwargs.get("headers")
        try:
            res = requests.get(url, params=params, headers=headers)
            # self.log.info("响应的内容:%s" %res.json())
            # self.log.info("返回的状态码:%s" % res.status_code)
            return res
        except Exception as e:
            self.log.error("get请求错误: %s" % e)

    def post(self, url, **kwargs):
        """
        封装post方法
        :param url:
        :param kwargs:
        :return:
        """
        params = kwargs.get("params")
        data = kwargs.get("data")
        json = kwargs.get("json")
        files = kwargs.get("files")
        header = kwargs.get("headers")
        try:
            res = requests.post(url,
                                params=params,
                                data=data,
                                json=json,
                                files=files,
                                headers=header)
            # self.log.info("响应的内容:%s" %res.json())
            # self.log.info("返回的状态码:%s" % res.status_code)
            return res
        except Exception as e:
            self.log.error("post请求错误: %s" % e)
Exemplo n.º 21
0
class getPcToken(object):
    def __init__(self):
        self.log = Log()

    # @staticmethod
    def get_token(self):
        """
        获取PC登录token
        :return:token
        """
        try:
            test_data = get_test_data('/fresh_data.xlsx', 'pc', 0)
            # data_dict = dict(zip(test_data[0], test_data[1][0]))
            res = get_response(test_data.get('route'), test_data.get('method'),
                               data=test_data.get('data'), headers=eval(test_data.get('header')))
            token = res.json()['result']['loginToken']
            return token
        except Exception as e:
            self.log.error('出现异常:{}'.format(str(e)))
Exemplo n.º 22
0
class TestRunner():
    def __init__(self, cases, title, description):

        self.cases = cases
        self.title = title
        self.description = description
        self.log = Log()

    def run(self):

        #定义discover
        discover = unittest.defaultTestLoader.discover(self.cases,
                                                       pattern="*.py")

        #定义测试报告的文件名
        now = time.strftime('%Y-%m-%d_%H_%M_')
        filename = "../report/" + now + "report.html"
        #打开测试报告写文件
        fp = open(filename, "wb")

        #运行并生成测试报告
        try:
            runner = HTMLTestRunner(stream=fp,
                                    title=self.title,
                                    description=self.description)
            runner.run(discover)
        except:
            self.log.error('create testreport error!')

        fp.close()
        '''发送邮件'''
        #从配置文件读取邮箱的相关信息
        server = read_config.mail_server
        username = read_config.mail_username
        password = read_config.mail_password
        receiver = read_config.mail_receiver

        #发送邮件
        try:
            mail = SendMail(server, username, password, receiver)
            #mail.sendmail(filename)
        except:
            self.log.error('send mail error!')
Exemplo n.º 23
0
class getAppToken(object):
    def __init__(self):
        self.log = Log()

    # @staticmethod
    def get_token(self):
        """
        获取app登录token
        :return:token
        """
        try:
            test_data = get_test_data('/fresh_data.xlsx', 'app', 0)
            res = get_response(test_data['route'],
                               test_data['method'],
                               data=test_data['data'],
                               headers=eval(test_data['header']))
            return res.json()['response']['token']
        except Exception as e:
            self.log.error('获取token出现异常:{}'.format(str(e)))
Exemplo n.º 24
0
class ColumnInfo(unittest.TestCase):
    def setUp(self):
        self.s = requests.session()
        self.lgin = LG(self.s)  #实例化登录类
        self.uid_token = self.lgin.login()  #直接取第二部登录
        self.header = {
            'User-Agent': 'LanTingDoctor/1.3.1 (iPad; iOS 10.1.1; Scale/2.00)',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-Hans-CN;q=1',
            'Content-Type': 'application/json',
            'requestApp': '3',
            'requestclient': '2',
            'versionForApp': '2.0',
            'Authorization':
            'Basic YXBpTGFudGluZ0BtZWRsYW5kZXIuY29tOkFwaVRobWxkTWxkQDIwMTM=',
            'Connection': 'keep-alive'
        }
        self.log = Log()  #实例化日志的类

    def testAvailabelCoupon(self):
        u'测试可领用优惠券列表接口'
        self.log.info('-----开始测试可领的优惠券列表接口-------')
        url = 'http://api.lesson.sunnycare.cc/v1/coupon/canget'
        json_DATA = {
            "where_code": "K00112",
            "timestamp": str(int(time.time())),
            "for_where": "2",
            "token": self.uid_token,
            "nonce": get_digit()
        }
        json_DATA['sign'] = get_sign(json_DATA)
        r = self.s.post(url, headers=self.header, json=json_DATA)
        try:
            self.log.info('开始断言请求该接口返回的状态是否成功')
            self.assertEqual('请求成功.', r.json()['note'])
        except Exception as e:
            raise AssertionError
            self.log.error('请求接口返回不成功,原因:%s' % e)
        self.log.info('---------------测试接口结束--------------------')
        print(r.json())

    def tearDown(self):
        self.s.close()
Exemplo n.º 25
0
class SendMail:

    def __init__(self):
        self.config = Config()
        self.log = Log()

    def sendMail(self):
        msg = MIMEMultipart()
        # body = """
        # <h3>Hi,all</h3>
        # <p>本次接口自动化测试报告如下。</p>
        # """ arset='utf-8')
        stress_body = []
        result_body = []
        body2 = 'Hi,all\n本次接口自动化测试报告如下:\n   接口响应时间集:%s\n   接口运行结果集:%s' % (stress_body, result_body)
        mail_body2 = MIMEText(body2, _subtype='plain', _charset='utf-8')
        tm = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        msg['Subject'] = Header("接口自动化测试报告"+"_"+tm, 'utf-8')
        msg['From'] = self.config.get('email','sender')
        receivers = self.config.get('email','receiver')
        toclause = receivers.split(',')
        msg['To'] = ",".join(toclause)
        # msg.attach(mail_body)

        msg.attach(mail_body2)

        try:
            smtp = smtplib.SMTP()
            smtp.connect(self.config.get('email','smtpserver'))
            smtp.login(self.config.get('email','username'), self.config.get('email','password'))
            smtp.sendmail(self.config.get('email','sender'), toclause, msg.as_string())
        except Exception as e:
            print(e)
            print("发送失败")
            self.log.error("邮件发送失败,请检查邮件配置")

        else:
            print("发送成功")
            self.log.info("邮件发送成功")
        finally:
            smtp.quit()
Exemplo n.º 26
0
class MyInvitation(unittest.TestCase):
    def setUp(self):
        self.s = requests.session()
        self.lgin = LG(self.s) #实例化登录类
        self.uid_token = self.lgin.login() #登录
        self.header = {'User-Agent': 'LanTingDoctor/1.3.1 (iPad; iOS 10.1.1; Scale/2.00)',
                       'Accept-Encoding': 'gzip, deflate',
                       'Accept-Language': 'zh-Hans-CN;q=1',
                       'Content-Type': 'application/json',
                       'requestApp': '3',
                       'requestclient': '2',
                       'versionForApp': '2.0',
                       'Authorization': 'Basic YXBpTGFudGluZ0BtZWRsYW5kZXIuY29tOkFwaVRobWxkTWxkQDIwMTM=',
                       'Connection': 'keep-alive'}
        self.log = Log()

    def test_my_invitation(self):
        u'测试我的邀请接口'
        self.log.info('--------开始测试我的邀请接口--------')
        url = 'http://api.lesson.sunnycare.cc/v1/invite/mine'
        json_data = {
            "token":self.uid_token,
            "time":"0",
            "timestamp": str(int(time.time())),
            "nonce": get_digit()
        }
        json_data['sign'] = get_sign(json_data)
        r = self.s.post(url,headers = self.header,json=json_data)
        try:
            self.assertEqual('请求成功.',r.json()['note'])
            self.assertEqual(200,r.json()['code'])
            self.log.info('我的邀请接口请求成功!')
        except Exception as e:
            raise AssertionError
            print(e)
            self.log.error('我的邀请接口请求失败,原因:%s' % e)
        self.log.info('--------我的邀请接口测试结束!--------')

    def tearDown(self):
        self.s.close()
Exemplo n.º 27
0
class editUserInfo:
    """
    会员中心--修改用户资料
    """
    def __init__(self):
        self.log = Log()
        self.test_data = get_test_data('bms_test_data.xlsx', 'memberCentre', 3)
        self.url = get_host('test') + self.test_data['url']
        self.data = json.dumps(getUserInfo().get_user_info()['data'])
        self.header = json.loads(self.test_data['header'])
        self.header['authorization'] = getBmsToken().get_token()
        self.method = self.test_data['method']

    def edit_user_info(self):
        """
        bms后台修改用户资料
        :return:
        """
        if 'false' not in self.data:
            self.data.replace('true', 'false')
        else:
            self.data.replace('false', 'true')
        try:
            resp = get_response(self.url,
                                self.method,
                                data=self.data,
                                headers=self.header)  # 未解密接口返回
            resp_str = getJsonStr(
                resp.json()['data']).get_json_str()  # 解密接口返回数据
            resp = resp.json()
            resp['data'] = resp_str['data']
            return resp
        except Exception as e:
            self.log.error('bms后台获取用户资料接口异常:{},请检查'.format(str(e)))


# if __name__ == '__main__':
#     res = editUserInfo().edit_user_info()
#     print(res)
Exemplo n.º 28
0
class addMemberGroup:
    """
    会员中心-新增会员分组
    """
    def __init__(self):
        self.log = Log()
        self.test_data = get_test_data('bms_test_data.xlsx', 'memberCentre',
                                       22)
        self.url = get_host('test') + self.test_data['url']
        self.payload = self.test_data['data']
        self.header = json.loads(self.test_data['header'])
        self.header['authorization'] = getBmsToken().get_token()
        self.method = self.test_data['method']
        self.databaseOperations = databaseOperations()

    def add_member_group(self):
        """
        bms-新增会员分组
        :return:
        """
        # 如果存在这个auto_test分组就先删除
        for i in self.databaseOperations.select_member_group():
            if 'auto_test' in i:
                self.databaseOperations.delete_member_group()
        try:
            resp = get_response(self.url,
                                self.method,
                                data=self.payload,
                                headers=self.header)  # 未解密接口返回
            resp_str = getJsonStr(
                resp.json()['data']).get_json_str()  # 解密接口返回数据
            resp = resp.json()
            resp['data'] = resp_str['data']
            return resp
        except Exception as e:
            self.log.error('新增会员账户接口异常:{},请检查'.format(str(e)))
Exemplo n.º 29
0
class addUserIncome:
    """
    新增会员入款
    """
    def __init__(self):
        self.log = Log()
        self.test_data = get_test_data('bms_test_data.xlsx', 'financialCenter',
                                       1)
        self.url = get_host('test') + self.test_data['url']
        self.data = json.loads(self.test_data['data'])
        self.header = json.loads(self.test_data['header'])
        self.header['authorization'] = getBmsToken().get_token()
        self.method = self.test_data['method']

    def add_user_income(self):
        """
        bms-新增会员入款
        :return:
        """
        try:
            resp = get_response(self.url,
                                self.method,
                                data=json.dumps(self.data),
                                headers=self.header)  # 未解密接口返回
            resp_str = getJsonStr(
                resp.json()['data']).get_json_str()  # 解密接口返回数据
            resp = resp.json()
            resp['data'] = resp_str['data']
            return resp
        except Exception as e:
            self.log.error('bms后台新增会员入款接口异常:{},请检查'.format(str(e)))


# if __name__ == '__main__':
#     res = addUserIncome().add_user_income()
#     print(res)
Exemplo n.º 30
0
class registerCodeList:
    """
    会员中心--注册码管理列表
    """
    def __init__(self):
        self.log = Log()
        self.test_data = get_test_data('bms_test_data.xlsx', 'memberCentre',
                                       18)
        self.url = get_host('test') + self.test_data['url']
        self.data = self.test_data['data']
        self.header = json.loads(self.test_data['header'])
        self.header['authorization'] = getBmsToken().get_token()
        self.method = self.test_data['method']

    def register_code_list(self):
        """
        注册码管理列表
        :return:
        """
        try:
            resp = get_response(self.url,
                                self.method,
                                data=self.data,
                                headers=self.header)  # 未解密接口返回
            resp_str = getJsonStr(
                resp.json()['data']).get_json_str()  # 解密接口返回数据
            resp = resp.json()
            resp['data'] = resp_str['data']
            return resp
        except Exception as e:
            self.log.error('bms后台获取注册码列表接口异常:{},请检查'.format(str(e)))


# if __name__ == '__main__':
#     res = registerCodeList().register_code_list()
#     print(res)
Exemplo n.º 31
0
class Client:
	cursor_default = None
	cursor_capture = None

	def __init__(self, resolution, host, port, username, password, split="\n"):
		global network_log
		
		self.log = Log('client')
		network_log = Log('network')

		# must have at least one handler
		self.log.logger.addHandler(logging.NullHandler())
		network_log.logger.addHandler(logging.NullHandler())
		
		# opengl must be initialized first
		self.log.info("Initializing display (windowed at %(resolution)s)", dict(resolution='%dx%d'%resolution))
		self._screen = pygame.display.set_mode(resolution, OPENGL|DOUBLEBUF)
		pygame.display.set_caption('yamosg')

		self.log.debug("OpenGL setup (version=\"%(version)s\", vendor=\"%(vendor)s\")", dict(version=glGetString(GL_VERSION), vendor=glGetString(GL_VENDOR)))
		setup_opengl()

		Client.cursor_default = pygame.cursors.arrow
		Client.cursor_capture = pygame.cursors.diamond
		
		self._resolution = Vector2i(resolution)
		self._username = username
		self._password = password
		self._split = split
		self._running = False
		self._state = StateManager()
		self._game = GameWidget(self, self._resolution)
		self._container = Composite(Vector2i(0,0), self._resolution, children=[self._game])
		self._toolbar = Toolbar(self._game)
		self._window = VBox()
		self._window.add(self._toolbar, size=LayoutAttachment(Vector2i(1,0), Vector2i(0,25)))
		self._window.add(self._container)
		self._state.push(GameState(self._resolution, self._window))
		self._network = Network(self, host, port)
		self._command_store = {}
		self._command_queue = []
		self._command_lock = threading.Lock()
		self._playerid = None
		self._players = {}
		self._capture_position = None
		self._timer = 0

		# resizing must be done after state has been created so the event is propagated proper.
		self._resize(self._resolution)
	
	def add_window(self, win):
		self._container.add(win)
	
	@event(pygame.QUIT)
	def quit(self, event=None):
		self._running = False
	
	def is_running(self):
		return self._running	

	def resolution(self):
		return self._resolution

	def run(self):
		self._running = True
		self._network.start()
		
		while self._running:
			try:
				self._flush_queue()
				self._logic()
				self._render()
			except GLError:
				traceback.print_exc()
				self.quit()
			except:
				traceback.print_exc()
	
	@event(pygame.VIDEORESIZE, lambda event: Vector2i(event.w, event.h))
	def _resize(self, resolution):
		self.log.debug("Resolution changed to %dx%d", resolution.x, resolution.y)
		#self._screen = pygame.display.set_mode(resolution.xy(), OPENGL|DOUBLEBUF|RESIZABLE)
		setup_opengl()

		self._resolution = resolution
		glMatrixMode(GL_PROJECTION)
		glLoadIdentity()
		glOrtho(0, resolution.x, 0, resolution.y, -1.0, 1.0);
		glMatrixMode(GL_MODELVIEW)
		glLoadIdentity()

		self._state.resize(resolution)
		self._game.on_resize(resolution, True)
	
	def _flush_queue(self):
		while True:
			self._command_lock.acquire()
			if len(self._command_queue) == 0:
				self._command_lock.release()
				break
		
			command, args = self._command_queue.pop(0)
			self._command_lock.release()
		
			try:
				self._dispatch(command, args)
			except:
				traceback.print_exc()
		
	def _logic(self):
		global event_table
		for event in pygame.event.get():
			func, adapter = event_table.get(event.type, (None,None))
			if func is None:
				continue
			func(self, adapter(event))
		t = time()
		if t-self._timer > 1.0:
			self._toolbar.invalidate()
			self._timer = t

	@event(pygame.MOUSEMOTION)
	def _mousemotion(self, event):
		pos = Vector2i(event.pos)
		pos.y = self._resolution.y - pos.y
		self._state.on_mousemove(pos)
	
	@event(pygame.MOUSEBUTTONDOWN)
	def _mousebuttondown(self, event):
		pos = Vector2i(event.pos)
		pos.y = self._resolution.y - pos.y

		if self._capture_position is not None:
			if event.button == 1:
				callback, args, kwargs = self._capture_position
				try:
					callback(pos, *args, **kwargs)
				except:
					traceback.print_exc()
					
			self._capture_position = None
			pygame.mouse.set_cursor(*Client.cursor_default)
			return
		self._state.on_buttondown(pos, event.button)

	@event(pygame.MOUSEBUTTONUP)
	def _mousebuttonup(self, event):
		pos = Vector2i(event.pos)
		pos.y = self._resolution.y - pos.y
		self._state.on_buttonup(pos, event.button)
	
	def _render(self):
		glClearColor(1,0,0,0)
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
		self._state.render()
		
		pygame.display.flip()
	
	def _dispatch(self, cmd, args):
		""" Run command """
		global network_log
		network_log.debug('got %s(%s)', cmd, ', '.join([str(x) for x in args]))
		try:
			# Try to get function
			func = getattr(self, cmd)
			
			# See if it is exposed, so a malicious cannot run any func.
			if not getattr(func, 'exposed'):
				raise AttributeError # raised to get same handling as a non-existing func.
			
		except AttributeError:
			print 'Malformed or bad command:', cmd, args
			return
		except:
			print 'Unhandled exception when running command:', cmd, args
			traceback.print_exc()
			return
		
		func(*args)

	def push_command(self, line):
		# Run from network thread
		
		try:
			self._command_lock.acquire()
			
			tokens = parse_tokens(line)
			id = tokens[0]
			if id == 'UNICAST' or id == 'BROADCAST':
				id, command, args = parse(line)
				self._command_queue.append((command, args))
			elif id in self._command_store:
				status = tokens[1]
				args = tuple(tokens[2:])
				data = line[len(id)+len(status)+2:]

				self._command_store[id].reply(status, args, data)
			else:
				raise RuntimeError, 'Got a reply for ID ' + id + ' but no matching request'
		except:
			traceback.print_exc()
		finally:
			self._command_lock.release()
	
	def call(self, command, *args):
		"""
			Synchronously call and get reply
		"""
		cmd = Command(command, *args)
		
		# send command
		with self._command_lock:
			self._command_store[cmd.id] = cmd
			self._network.send(str(cmd) + self._split)
		
		# await reply
		reply = cmd.wait()
		
		# delete command
		with self._command_lock:
			del self._command_store[cmd.id]
		
		return reply
	
	@server_call('LIST_OF_ENTITIES', decode=True)
	def list_of_entities(self, descriptions):
		self._game.set_entities([Entity(**x) for x in descriptions])

	@expose
	def NEWENT(self, data):
		decoded = json.loads(data)
		self._game.add_entity(Entity(**decoded))
	
	@server_call('ENTINFO', 'id', decode=True)
	def entity_info(self, info):
		return info

	@server_call('ENTACTION', 'id', 'action', decode=True)
	def entity_action(self, info):
		return info

	@server_call('PLAYERINFO', 'id', decode=True)
	def playerinfo(self, info):
		self._toolbar.set_cash(info['cash'])

	@expose
	def CASH(self, amount):
		self._toolbar.set_cash(int(amount))
	
	@server_call('LOGIN', 'username', 'password', decode=True)
	def login(self, info):
		self.playerid = info['id']
		self.log.debug('player id is %s', self.playerid)
		self.playerinfo(self.playerid)
	
	@server_call('PLAYERS', decode=True)
	def players(self, players):
		return players

	def player_by_id(self, id):
		return self._players.get(unicode(id), None)

	@expose
	def Hello(self):
		self.call('SET', 'ENCODER', 'json')
		try:
			self.login(username=self._username, password=self._password)
		except RuntimeError, e:
			self.log.error(e)
			self.quit()
			return
		self._players = self.players()
		self.list_of_entities()