Exemplo n.º 1
0
    def wait_elementsPresent(self,
                             locator,
                             wait_times=20,
                             poll_frequency=0.5,
                             doc=""):
        '''

        :param locator: 元素定位,元祖形式
        :param times: 最长等待时间
        :param poll_frequency: 轮询间隔
        :param doc: 模块名_页面名称_操作名称
        :return:
        '''
        try:
            # 开始等待时间
            start = time.time()
            WebDriverWait(self.driver, wait_times, poll_frequency).until(
                EC.presence_of_all_elements_located((locator[1])))
            # 结束等待的时间点
            end = time.time()
            # 求差值
            wait_time = round(end - start, 3)
            Log().log_info("等待" + '"' + locator[0] +
                           '"加载成功,用时{}秒'.format(wait_time))
        except:
            Log().log_error("页面加载超时!判断依据:" + '"' + locator[0] + '"')
            # 截图
            self.save_screenshot(doc)
            raise
Exemplo n.º 2
0
 def cancel_readOnly(self, locator, doc=""):
     ele = self.get_element(locator, doc=doc)
     try:
         self.driver.execute_script("arguments[0].readOnly;", ele)
         Log.log_info('去除"' + locator[0] + '"只读属性')
     except:
         Log.log_error('去除"' + locator[0] + '"只读属性失败!')
         raise
Exemplo n.º 3
0
 def clear_text(self, locator, doc=""):
     try:
         ele = self.get_element(locator)
         ele.clear()
         Log().log_info('清空"' + locator[0] + '"文本')
     except:
         Log().log_info('清空"' + locator[0] + '"文本失败!')
         self.save_screenshot(doc)
         raise
Exemplo n.º 4
0
 def save_screenshot(self, doc=""):
     # 图片名称:模块名_页面名称_操作名称_年-月-日_时分秒.png
     filePath = dir_config.screenshot_dir + \
                "\\{0}_{1}.png".format(doc, time.strftime("%Y-%m-%d-%H-%M-%S"))
     try:
         self.driver.save_screenshot(filePath)
         Log().log_info("截屏成功,图片路径为{}".format(filePath))
     except:
         Log().log_info("截图失败")
         raise
Exemplo n.º 5
0
 def input_text(self, locator, text, doc=""):
     ele = self.get_element(locator, doc=doc)
     try:
         ele.send_keys(text)
         Log().log_info('向"' + locator[0] + '"输入内容:{}'.format(text))
     except:
         Log().log_info('向"' + locator[0] + '"输入内容:{}失败!'.format(text))
         #  截图
         self.save_screenshot(doc)
         raise
Exemplo n.º 6
0
 def click_element(self, locator, doc=""):
     ele = self.get_element(locator, doc=doc)
     try:
         ele.click()
         Log().log_info("点击:{0}".format(locator[0]))
     except:
         Log().log_error("点击" + locator[0] + "失败!")
         #  截图
         self.save_screenshot(doc)
         raise
Exemplo n.º 7
0
 def get_text(self, locator, doc=""):
     try:
         ele = self.get_element(locator, doc=doc)
         text = ele.text
         Log().log_info('获取"' + locator[0] + '"文本,内容为:{}'.format(text))
         return text
     except:
         Log().log_info('获取"' + locator[0] + '"文本内容失败!')
         #  截图
         self.save_screenshot(doc)
         raise
Exemplo n.º 8
0
 def __init__(self,
              host=host,
              port=int(port),
              user=user,
              passwd=passwd,
              db=dbname):
     self.log = Log().getlog()
     self.host = host
     self.port = port
     self.user = user
     self.passwd = passwd
     self.db = db
Exemplo n.º 9
0
 def get_elements(self, locator, doc=""):
     try:
         # 开始等待时间
         start = time.time()
         ele = self.driver.find_elements(*locator[1])
         # 结束等待的时间点
         end = time.time()
         # 求差值
         wait_time = round(end - start, 3)
         Log().log_info("定位" + '"' + locator[0] +
                        '"成功,用时{}秒'.format(wait_time))
         return ele
     except:
         Log().log_error("定位" + '"' + locator[0] + '"失败')
         # 截图
         self.save_screenshot(doc)
         raise
Exemplo n.º 10
0
 def get_element_attribute(self, locator, attr, doc=""):
     ele = self.get_element(locator, doc=doc)
     try:
         return ele.get_attribute(attr)
     except:
         Log().log_error("获取元素属性失败!定位:{}".format(locator))
         #  截图
         self.save_screenshot(doc)
         raise
Exemplo n.º 11
0
class Test(unittest.TestCase):
    log = Log()

    def test_01(self):
        self.log.info('------test------')
        url = 'http://www.baidu.com'
        self.log.info('测试url:%s' % url)
        r = requests.get(url)
        print(r.content.decode('utf8'))
        self.assertEqual(r.status_code, 200)
Exemplo n.º 12
0
class TestAuthenticateManage:
    log = Log().getlog()
    db = DB_config()
    allData = GetData(excelFileName='admin_api.xlsx', sheetName='Sheet1')
    selectContChannelConfigData = allData.getTestCaseData(menuName='认证管理', belongs='selectContChannelConfig')
    contChannelConfiginfoData = allData.getTestCaseData(menuName='认证管理', belongs='contChannelConfiginfo')
    test = Assertions()

    def setup_class(self):
        self.base = loginAdmin(usr=Config().adminuser, pwd=Config().adminpwd)  # 用同一个登录成功后的session

    @pytest.fixture(scope='class')
    def selectContChannelConfig(self, request):
        apiUrl = request.param['ApiUrl']
        requestsMethod = request.param['Method']
        sendData = json.loads(request.param['Data'])
        expected = json.loads(request.param['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        return r.json(), self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("查询认证服务项目列表")
    @pytest.mark.dependency(name='selectConfigInfo')
    @pytest.mark.parametrize("selectContChannelConfig", selectContChannelConfigData, indirect=True)
    def test_selectContChannelConfig(self, selectContChannelConfig):
        assert selectContChannelConfig[1]

    @allure.severity("normal")
    @allure.title("查询认证信息详情")
    @pytest.mark.dependency(depends=['selectConfigInfo'])
    @pytest.mark.parametrize("selectContChannelConfig", selectContChannelConfigData, indirect=True)
    @pytest.mark.parametrize("data", contChannelConfiginfoData)
    def test_contChannelConfiginfo(self, selectContChannelConfig, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        try:
            channelId = selectContChannelConfig[0]['data'][0]['id']
        except KeyError:
            raise Exception("认证通道id获取失败")
        except Exception as e:
            self.log.exception(e)
            raise
        else:
            sendData['id'] = channelId
            self.log.info('本次使用参数:%s' % sendData)
            r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
            self.log.info('接口返回值:%s' % r.json())
            print('接口返回值:%s' % r.json())
            self.test.verifyExpected(r.json(), expected)
class TestVisaInterviewRecord:
    log = Log().getlog()
    db = DB_config()
    allData = GetData(excelFileName='admin_api.xlsx', sheetName='Sheet1')
    uploadAndDownloadFilePath = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'UploadAndDownloadFile')
    PhoneRecordDate = allData.getTestCaseData(menuName='机构面签记录', belongs='getPhoneRecord')
    downloadPhoneRecordData = allData.getTestCaseData(menuName='机构面签记录', belongs='downloadPhoneRecord')
    test = Assertions()

    def setup_class(self):
        self.base = loginAdmin(usr=Config().adminuser, pwd=Config().adminpwd)  # 用同一个登录成功后的session

    @allure.severity("normal")
    @allure.title("查看机构下面签记录列表")
    @pytest.mark.parametrize("data", PhoneRecordDate, indirect=False)  # 参数化时以这种形式
    def test_getRecodList(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("下载面签记录视频")
    @pytest.mark.parametrize("data", downloadPhoneRecordData, indirect=False)  # 参数化时以这种形式
    def test_downloadRecodFile(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, param=sendData)
        self.test.assert_code(r.status_code, 200)
        try:
            print("接口返回值:{}".format(r.json()))
            self.log.info("接口返回值:{}".format(r.json()))
        except AttributeError:
            with open(os.path.join(self.uploadAndDownloadFilePath, 'video_single.zip'), 'wb') as f:
                f.write(r.content)
                self.test.verifyExpected(r.json(), expected)
                print('文件保存路径为{}'.format(os.path.join(self.uploadAndDownloadFilePath, 'video_single.zip')))
                self.log.info('文件保存路径为{}'.format(os.path.join(self.uploadAndDownloadFilePath, 'video_single.zip')))
        except Exception as e:
            self.log.exception(e)
            raise
        else:
            raise ValueError("下载接口返回值类型不应为dict")
Exemplo n.º 14
0
 def upload_file(self, file_path, doc):
     time.sleep(2)
     try:
         # 一级窗口(打开)
         open_win = win32gui.FindWindow("#32770", "打开")
         # 二级窗口
         combo_box_ex32 = win32gui.FindWindowEx(open_win, 0, "ComboBoxEx32",
                                                None)
         # 三级窗口
         combo_box = win32gui.FindWindowEx(combo_box_ex32, 0, "ComboBox",
                                           None)
         # 四级窗口(文件名)
         edit = win32gui.FindWindowEx(combo_box, 0, "Edit", None)
         # 二级窗口(打开)
         button = win32gui.FindWindowEx(open_win, 0, "Button", "打开(&O)")
         # 操作
         win32gui.SendMessage(edit, win32con.WM_SETTEXT, None, file_path)
         time.sleep(1)
         win32gui.SendMessage(open_win, win32con.WM_COMMAND, 1, button)
         Log().info("上传本地文书:{}".format(file_path))
     except:
         Log().exception("上传文书失败!路径:{}".format(file_path))
         self.save_screenshot(doc)
         raise
Exemplo n.º 15
0
class TestBusinessTypeAllot:
    log = Log().getlog()
    db = DB_config()
    allData = GetData(excelFileName='admin_api.xlsx', sheetName='Sheet1')
    test = Assertions()
    BusinessTypeSettingsPageDate = allData.getTestCaseData(
        menuName='业务类型分配', belongs='BusinessTypeSettingsPage')
    updateEnableFlagData = allData.getTestCaseData(menuName='业务类型分配',
                                                   belongs='updateEnableFlag')
    enableFlagids = [i['IDS'] for i in updateEnableFlagData]

    def setup_class(self):
        self.base = loginAdmin(usr=Config().adminuser,
                               pwd=Config().adminpwd)  # 用同一个登录成功后的session

    @allure.severity("normal")
    @allure.title("机构业务类型列表")
    @pytest.mark.parametrize("data", BusinessTypeSettingsPageDate)
    def test_BusinessTypeSettingsPage(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @pytest.mark.parametrize("data", updateEnableFlagData, ids=enableFlagids)
    def test_updateEnableFlag(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
Exemplo n.º 16
0
class TestBusinessTypeManage:
    log = Log().getlog()
    db = DB_config()
    allData = GetData(excelFileName='admin_api.xlsx', sheetName='Sheet1')
    odrProductTypePageDate = allData.getTestCaseData(
        menuName='业务类型管理', belongs='odrProductTypePage')
    odrProductFromFindListData = allData.getTestCaseData(
        menuName='业务类型管理', belongs='odrProductFromFindList')
    test = Assertions()

    def setup_class(self):
        self.base = loginAdmin(usr=Config().adminuser,
                               pwd=Config().adminpwd)  # 用同一个登录成功后的session

    @allure.severity("normal")
    @allure.title("查询业务类型列表")
    @pytest.mark.parametrize("data", odrProductTypePageDate)
    def test_odrProductTypePage(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("查询业务来源方列表")
    @pytest.mark.parametrize("data", odrProductFromFindListData)
    def test_odrProductFromFindList(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        expected = json.loads(data['expected'])
        r = self.base.sendRequest(apiUrl, requestsMethod)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
Exemplo n.º 17
0
 def scroll_to_element(self, locator, doc=""):
     Log.log_info("开始滚动条处理,拖动位置:{}".format(locator[0]))
     try:
         # 开始等待时间
         start = time.time()
         ele = self.get_element(locator, doc=doc)
         # 结束等待的时间点
         end = time.time()
         # 求差值
         wait_time = round(end - start, 3)
         Log.log_info("滚动条处理成功,用时{}秒".format(wait_time))
         self.driver.execute_script("arguments[0].scrollIntoView(false);",
                                    ele)
         time.sleep(1)
     except:
         Log.log_error("滚动条处理失败,定位:{}".format(locator))
         self.save_screenshot(doc)
         raise
Exemplo n.º 18
0
class TestAdvertiseManage:
    log = Log().getlog()
    db = DB_config()
    uploadAndDownloadFilePath = os.path.join(
        os.path.dirname(os.path.dirname(__file__)), 'UploadAndDownloadFile')
    allData = GetData(excelFileName='admin_api.xlsx', sheetName='Sheet1')
    selectTblAdData = allData.getTestCaseData(menuName='广告位管理',
                                              belongs='selectTblAd')
    insertTbData = allData.getTestCaseData(menuName='广告位管理',
                                           belongs='insertTb')
    deleteTbData = allData.getTestCaseData(menuName='广告位管理',
                                           belongs='deleteTb')
    test = Assertions()
    # 新增广告位中需要调用一下图片上传接口
    uploadFixtureData = [{
        "filepath":
        os.path.join(uploadAndDownloadFilePath, 'advertise.jpeg'),
        "base":
        ""
    }]

    def setup_class(self):
        self.base = loginAdmin(usr=Config().adminuser,
                               pwd=Config().adminpwd)  # 用同一个登录成功后的session
        self.uploadFixtureData[0]['base'] = self.base  # 把登录后的session给上传图片接口

    @allure.severity("normal")
    @allure.title("查询广告位列表")
    @pytest.mark.parametrize("data", selectTblAdData)
    def test_selectTblAdPage(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        expected = json.loads(data['expected'])
        r = self.base.sendRequest(apiUrl, requestsMethod)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("新增广告位")
    @pytest.mark.dependency(name='addTb')
    @pytest.mark.parametrize("uploadPic", uploadFixtureData, indirect=True)
    @pytest.mark.parametrize("data", insertTbData)
    def test_insertTb(self, uploadPic, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        sendData['data']['visitUrl'] = uploadPic['visitUrl']
        sendData['data'] = json.dumps(sendData['data'])
        expected = json.loads(data['expected'])
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("删除广告位")
    @pytest.mark.dependency(depends=['addTb'])
    @pytest.mark.parametrize("data", deleteTbData, indirect=False)  # 参数化时以这种形式
    def test_deleteTb(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        sql = "SELECT id FROM tbl_ad WHERE `name`='接口测试新建广告位'ORDER BY id LIMIT 0,1"
        self.db.excute(sql)
        try:
            id = self.db.get_one()[0]
        except TypeError:
            raise Exception("获取广告位id异常")
        except Exception as e:
            self.log.exception(e)
            raise
        else:
            sendData['id'] = id
            self.log.info('本次使用参数:%s' % sendData)
            r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
            self.log.info('接口返回值:%s' % r.json())
            print('接口返回值:%s' % r.json())
            self.test.verifyExpected(r.json(), expected)
Exemplo n.º 19
0
class TestEmployeeAccount:
    log = Log().getlog()
    db = DB_config()
    test = Assertions()
    allData = GetData(excelFileName='admin_api.xlsx', sheetName='Sheet1')
    RoleListDate = allData.getTestCaseData(menuName='员工账号管理',
                                           belongs='accountList')
    accountDetailData = allData.getTestCaseData(menuName='员工账号管理',
                                                belongs='accountDetail')
    addAccountData = allData.getTestCaseData(menuName='员工账号管理',
                                             belongs='addAccount')
    updateAccountData = allData.getTestCaseData(menuName='员工账号管理',
                                                belongs='updateAccount')
    resetAccountData = allData.getTestCaseData(menuName='员工账号管理',
                                               belongs='resetAccount')
    deleteAccountData = allData.getTestCaseData(menuName='员工账号管理',
                                                belongs='deleteAccount')
    transferUserListData = allData.getTestCaseData(menuName='员工账号管理',
                                                   belongs='transferUserList')
    countOrderByUserIdData = allData.getTestCaseData(
        menuName='员工账号管理', belongs='countOrderByUserId')
    selectAssurerConfigData = allData.getTestCaseData(
        menuName='员工账号管理', belongs='selectAssurerConfig')
    assureConfigUserListData = allData.getTestCaseData(
        menuName='员工账号管理', belongs='assureConfigUserList')
    transferOrderData = allData.getTestCaseData(menuName='员工账号管理',
                                                belongs='transferOrder')
    getClientRightByUserIdData = allData.getTestCaseData(
        menuName='员工账号管理', belongs='getClientRightByUserId')
    updateClientRightData = allData.getTestCaseData(
        menuName='员工账号管理', belongs='updateClientRight')

    fixtureData = []  # 新增角色接口时需要获取角色权限id的前置
    for i in addAccountData:
        fixtureData.append(json.loads(i['ExtraParam']))

    def setup_class(self):
        self.base = loginAdmin(usr=Config().adminuser,
                               pwd=Config().adminpwd)  # 用同一个登录成功后的session
        for i in self.fixtureData:
            i['base'] = self.base

    @allure.severity("normal")
    @allure.title("查看机构下员工账号列表接口")
    @pytest.mark.parametrize("data", RoleListDate, indirect=False)  # 参数化时以这种形式
    def test_getDeptUserPage(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("查看员工账号详情接口")
    @pytest.mark.parametrize("data", accountDetailData,
                             indirect=False)  # 参数化时以这种形式
    def test_getUserDetail(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("新建员工账号接口")
    @pytest.mark.dependency(name='addAccount')
    @pytest.mark.parametrize("getNewRoleId", fixtureData, indirect=True)
    @pytest.mark.parametrize("data", addAccountData,
                             indirect=False)  # 参数化时以这种形式
    def test_addNewAccount(self, getNewRoleId, data):
        recidList = getNewRoleId  # 先获取当前机构id下所有的角色权限列表
        if recidList == None:
            self.log.info('当前机构id下没有角色')
            print('当前机构id下没有角色,本次测试无效')
            raise ValueError('当前机构id下没有角色,本次测试无效')
        else:
            apiUrl = data['ApiUrl']
            requestsMethod = data['Method']
            sendData = json.loads(data['Data'])
            sendData['roleId'] = random.choice(recidList)
            expected = json.loads(data['expected'])
            self.log.info('本次使用参数:%s' % sendData)
            r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
            self.log.info('接口返回值:%s' % r.json())
            print('接口返回值:%s' % r.json())
            self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("修改员工账号详情接口")
    @pytest.mark.dependency(depends=['addAccount'])
    @pytest.mark.parametrize("data", updateAccountData,
                             indirect=False)  # 参数化时以这种形式
    def test_updateAccount(self, data):
        sql = "SELECT userId,roleId FROM pms_user WHERE realName='接口自动化测试' AND phone = 13524569871"
        self.db.excute(sql)
        sqldata = self.db.get_one()
        userId, roleId = sqldata[0], sqldata[1]  # 后几个接口都要用到
        if userId == None and roleId == None:
            raise ValueError('获取员工id错误')
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        sendData['userId'], sendData['roleId'] = userId, roleId
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("重置员工账号密码接口")
    @pytest.mark.dependency(depends=['addAccount'])
    @pytest.mark.parametrize("data", resetAccountData,
                             indirect=False)  # 参数化时以这种形式
    def test_resetAccount(self, data):
        sql = "SELECT userId FROM pms_user WHERE realName='接口自动化测试' AND phone = 13524569871"
        self.db.excute(sql)
        userId = self.db.get_one()[0]
        if userId == None:
            raise ValueError('获取员工id错误')
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        sendData['userId'] = userId
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("删除员工账号接口")
    @pytest.mark.dependency(depends=['addAccount'])
    @pytest.mark.parametrize("data", deleteAccountData,
                             indirect=False)  # 参数化时以这种形式
    def test_deleteAccount(self, data):
        sql = "SELECT userId FROM pms_user WHERE realName='接口自动化测试' AND phone = 13524569871"
        self.db.excute(sql)
        userId = int(self.db.get_one()[0])
        if userId == None:
            raise ValueError('获取员工id错误')
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        sendData['userId'] = userId
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("查询移交订单接受者列表接口")
    @pytest.mark.parametrize("data", transferUserListData,
                             indirect=False)  # 参数化时以这种形式
    def test_getTransferUserList(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("查询当前账号可移交订单数量统计")
    @pytest.mark.parametrize("data", countOrderByUserIdData,
                             indirect=False)  # 参数化时以这种形式
    def test_countOrderByUserId(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("查询当前账号是否可移交专属业务负责人")
    @pytest.mark.parametrize("data", selectAssurerConfigData,
                             indirect=False)  # 参数化时以这种形式
    def test_getAssurerConfigList(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("查询移交专属业务负责人列表")
    @pytest.mark.parametrize("data", assureConfigUserListData,
                             indirect=False)  # 参数化时以这种形式
    def test_getAssureConfigUserList(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("移交订单以及专属业务负责人")
    @pytest.mark.parametrize("data", transferOrderData,
                             indirect=False)  # 参数化时以这种形式
    def test_transferOrder(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        sendData['apiAssurerConfigs'] = json.dumps(
            sendData['apiAssurerConfigs'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("获取流程中我的客户权限列表")
    @pytest.mark.parametrize("data",
                             getClientRightByUserIdData,
                             indirect=False)  # 参数化时以这种形式
    def test_getClientRightByUserId(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, param=sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("修改流程中我的客户权限")
    @pytest.mark.parametrize("data", updateClientRightData,
                             indirect=False)  # 参数化时以这种形式
    def test_updataClientRightByProcessId(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        sql = "SELECT id FROM pms_user_client WHERE userId=%d" % sendData[
            'userId']
        self.db.excute(sql)
        try:
            clientId = int(self.db.get_one()[0])
        except TypeError as e:
            self.log.error(e)
        except Exception as e:
            self.log.exception(e)
            raise
        else:
            sendData['clientId'] = clientId
        print(sendData)
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, param=sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
Exemplo n.º 20
0
class DB_config:
    def __init__(self,
                 host=host,
                 port=int(port),
                 user=user,
                 passwd=passwd,
                 db=dbname):
        self.log = Log().getlog()
        self.host = host
        self.port = port
        self.user = user
        self.passwd = passwd
        self.db = db

    def connectDB(self):
        try:
            self.con = pymysql.connect(host=self.host,
                                       port=self.port,
                                       user=self.user,
                                       passwd=self.passwd,
                                       db=self.db,
                                       charset='utf8')
        except Exception as e:
            self.log.error("数据库连接失败%s" % e, exc_info=True)
        self.cur = self.con.cursor()

    def connectDB_otherdb(self, otherdbname):
        try:
            self.con = pymysql.connect(host=self.host,
                                       port=self.port,
                                       user=self.user,
                                       passwd=self.passwd,
                                       db=otherdbname,
                                       charset='gb2312')

        except Exception as e:
            self.log.error("数据库连接失败%s" % e, exc_info=True)
        self.cur = self.con.cursor()

    def excute_otherdb(self, sql, otherdbname):
        self.connectDB_otherdb(otherdbname)  # 连接不同的数据库名称
        try:
            self.cur.execute(sql)
            if 'INSERT' in sql.upper() or 'UPDATE' in sql.upper(
            ) or 'DELETE' in sql.upper():
                # print('需要进行commit操作')
                self.con.commit()
            else:
                pass
        except Exception as e:
            print('执行SQL语句失败', e)

    def excute(self, sql):
        self.connectDB()
        try:
            self.cur.execute(sql)
            if 'INSERT' in sql.upper() or 'UPDATE' in sql.upper(
            ) or 'DELETE' in sql.upper():
                # self.log.info('需要进行commit操作')
                self.con.commit()
            else:
                pass
        except Exception as e:
            print('执行SQL语句失败', e)

    def get_all(self):
        return self.cur.fetchall()

    def get_one(self):
        return self.cur.fetchone()

    def close(self):
        return self.con.close()
Exemplo n.º 21
0
class TestRepayModeManage:
    log = Log().getlog()
    db = DB_config()
    allData = GetData(excelFileName='admin_api.xlsx', sheetName='Sheet1')
    getRepayMethodListData = allData.getTestCaseData(
        menuName='还款方式管理', belongs='getRepayMethodList')
    inOrUpRepayModeData = allData.getTestCaseData(menuName='还款方式管理',
                                                  belongs='inOrUpRepayMode')
    inOrUpRepayModeIds = [i['IDS'] for i in inOrUpRepayModeData]
    infoData = allData.getTestCaseData(menuName='还款方式管理', belongs='info')
    infoIds = [i['IDS'] for i in infoData]
    enableOrProhibitData = allData.getTestCaseData(menuName='还款方式管理',
                                                   belongs='enableOrProhibit')
    enableOrProhibitIds = [i['IDS'] for i in enableOrProhibitData]
    test = Assertions()
    # 接口返回值sql校验文件路径
    yamlfilepath = os.path.join((os.path.dirname(os.path.dirname(__file__))),
                                'VerifyJsonAndSql', 'repayModeManage.yaml')
    jsonfilepath = os.path.join((os.path.dirname(os.path.dirname(__file__))),
                                'VerifyJsonAndSql', 'repayModeManage.json')

    def setup_class(self):
        self.base = loginAdmin(usr=Config().adminuser,
                               pwd=Config().adminpwd)  # 用同一个登录成功后的session
        # 删除添加的“自动化新增-按日计息”还款方式
        delteAlreadyExistSql = readYaml(
            self.yamlfilepath)['data']['setupsql']['delteAlreadyExistSql']
        self.db.excute(delteAlreadyExistSql)

        # 修改id=10的还款方式字段值到初始值
        resetStartSQL = readYaml(
            self.yamlfilepath)['data']['setupsql']['resetStartSQL']
        self.db.excute(resetStartSQL)

    @allure.severity("normal")
    @allure.title("查询还款方式列表")
    @pytest.mark.parametrize("data", getRepayMethodListData)
    def test_getRepayMethodList(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
        if r.json()['code'] == 200:  # 状态码200时再进行数据校验
            verifyJson = getApiJsonData(self.jsonfilepath,
                                        'getRepayMethodList')
            assert r.json() == verifyJson

    @allure.severity("normal")
    @allure.title("新建还款方式")
    @pytest.mark.parametrize("data",
                             inOrUpRepayModeData,
                             ids=inOrUpRepayModeIds)
    def test_inOrUpRepayMode(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
        # 状态码200时再进行数据库字段值校验
        if r.json()['code'] == 200:
            if sendData['id'] == '':  # 执行新增的数据校验
                verifySql = readYaml(
                    self.yamlfilepath)['data']['inOrUpRepayMode']['verifySql']
                self.db.excute(verifySql)
                dbresult = self.db.get_one()
                assert sendData['partnerId'] == dbresult[1], "接口传参与数据库实际值不匹配"
                assert sendData['name'] == dbresult[2], "接口传参与数据库实际值不匹配"
                assert sendData['calculateType'] == dbresult[
                    3], "接口传参与数据库实际值不匹配"
                assert sendData['partnerId'] == dbresult[1], "接口传参与数据库实际值不匹配"
                for i in range(12)[4:]:
                    assert dbresult[i] == ''
                assert sendData['allDayFormula'] == dbresult[
                    13], "接口传参与数据库实际值不匹配"
                assert sendData['principalDayFormula'] == dbresult[
                    14], "接口传参与数据库实际值不匹配"
                assert sendData['interestDayFormula'] == dbresult[
                    15], "接口传参与数据库实际值不匹配"
            else:  # 执行修改的校验
                updateSql = readYaml(
                    self.yamlfilepath)['data']['inOrUpRepayMode']['updateSql']
                self.db.excute(updateSql)
                dbresult = self.db.get_one()
                assert sendData['partnerId'] == dbresult[1], "接口传参与数据库实际值不匹配"
                assert sendData['name'] == dbresult[2], "接口传参与数据库实际值不匹配"
                assert sendData['calculateType'] == dbresult[
                    3], "接口传参与数据库实际值不匹配"
                assert sendData['partnerId'] == dbresult[1], "接口传参与数据库实际值不匹配"
                for i in range(12)[4:]:
                    assert dbresult[i] == ''
                assert sendData['allDayFormula'] == dbresult[
                    13], "接口传参与数据库实际值不匹配"
                assert sendData['principalDayFormula'] == dbresult[
                    14], "接口传参与数据库实际值不匹配"
                assert sendData['interestDayFormula'] == dbresult[
                    15], "接口传参与数据库实际值不匹配"

    @allure.severity("normal")
    # @allure.title("查询还款方式详情")
    @pytest.mark.parametrize("data", infoData, ids=infoIds)
    def test_info(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
        if r.json()['code'] == 200:  # 状态码200时再进行数据校验
            if sendData['id'] == 1:
                verifyJson = getApiJsonData(self.jsonfilepath, 'info')
                assert r.json() == verifyJson
            elif sendData['id'] == 2:
                verifyJson = getApiJsonData(self.jsonfilepath, 'info2')
                assert r.json() == verifyJson
            else:
                raise ValueError('sendData中的id与预期数据不匹配')

    @allure.severity("normal")
    # @allure.title("启用/禁用还款方式")
    @pytest.mark.parametrize("data",
                             enableOrProhibitData,
                             ids=enableOrProhibitIds)
    def test_enableOrProhibit(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
        # 状态码200时再进行数据库字段值校验
        if r.json()['code'] == 200:
            verifySql = readYaml(
                self.yamlfilepath)['data']['enableOrProhibit']['verifySql']
            self.db.excute(verifySql)
            dbresult = self.db.get_one()
            assert sendData['status'] == dbresult[0], "接口传参与数据库实际值不匹配"
Exemplo n.º 22
0
#!/usr/bin/env python
# encoding: utf-8
'''
@author: yanghong
@file: Config.py
@time: 2020/5/12 11:19
@desc:
'''

import configparser
import os

from Common.logger import Log

log = Log().getlog()


class Config:
    # titles:
    TITLE_ENVIRONMENT = "environment"
    TITLE_TEST = "test"
    TITLE_PRE = "pre"

    # values:
    # [environment]
    VALUE_SWITCH = "switch"

    # values:
    # [test]
    VALUE_ADMINURL = "adminurl"
    VALUE_DBHOST = "dbhost"
Exemplo n.º 23
0
class TestOrganizationManage:
    log = Log().getlog()
    db = DB_config()
    test = Assertions()
    allData = GetData(excelFileName='admin_api.xlsx', sheetName='Sheet1')
    companyListData = allData.getTestCaseData(menuName='组织机构管理',
                                              belongs='OrganizationList')
    companyInfoData = allData.getTestCaseData(menuName='组织机构管理',
                                              belongs='CompanyInfo')
    UpdateData = allData.getTestCaseData(menuName='组织机构管理',
                                         belongs='UpdateCompanyInfo')
    ChangeCompanyStatusData = allData.getTestCaseData(
        menuName='组织机构管理', belongs='ChangeCompanyStatus')
    adminBankTreeData = allData.getTestCaseData(menuName='组织机构管理',
                                                belongs='adminBankTree')

    def setup_class(self):
        self.base = loginAdmin(usr=Config().adminuser,
                               pwd=Config().adminpwd)  # 用同一个登录成功后的session

    @allure.severity("normal")  # blocker,critical,normal,minor,trivial 用例级别
    @pytest.mark.parametrize("data", companyListData)
    @allure.title("查看机构列表接口")
    def test_getCompanyList(self, data):
        """获取组织机构数据接口"""
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])  # test_getCompanyList接口的参数
        sendData['search'] = json.dumps({'name': ""})  # search参数需要重新处理一下
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @pytest.fixture(scope='class')
    def companyInfo(self, request):
        apiUrl = request.param['ApiUrl']
        requestsMethod = request.param['Method']
        sendData = json.loads(request.param['Data'])
        expected = json.loads(request.param['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        companyId = sendData['id']
        return r.json(), companyId, self.test.verifyExpected(
            r.json(), expected)

    @allure.severity("normal")
    @allure.title("查看机构详情信息接口")
    @pytest.mark.dependency(name='info')
    @pytest.mark.parametrize("companyInfo", companyInfoData,
                             indirect=True)  # 参数化时以这种形式
    def test_CompanyInfo(self, companyInfo):
        assert companyInfo[2]

    @allure.severity("normal")  # blocker,critical,normal,minor,trivial 用例级别
    @allure.title("修改机构详情接口")
    @pytest.mark.dependency(depends=['info'])
    @pytest.mark.parametrize("companyInfo", companyInfoData,
                             indirect=True)  # 参数化时以这种形式
    def test_updataInfo(self, companyInfo, data=UpdateData[0]):
        '''修改组织信息接口,数据依赖查看组织详情接口'''
        resultData = companyInfo[0]['data']
        apiUrl = data['ApiUrl']
        expected = json.loads(data['expected'])
        requestsMethod = data['Method']
        resultData['idNo'] = '111111111111111111'
        resultData['children'] = []
        resultData.pop('datasourceId')
        resultData.pop('basePartnerId')
        timeStamp = resultData['contractDate'] / 1000
        timeArray = time.localtime(timeStamp)
        resultData['contractDate'] = time.strftime("%Y-%m-%d", timeArray)
        sendData = {'data': json.dumps(resultData)}
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("修改机构状态接口")
    @pytest.mark.parametrize("data", ChangeCompanyStatusData,
                             indirect=False)  # 参数化时以这种形式
    def test_changeStatus(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        partnerId = sendData['id']
        sql = "SELECT statusFlag FROM qp_itfin2.pms_department WHERE id= %d" % partnerId
        self.db.excute(sql)
        try:
            statusFlag = int(self.db.get_one()[0])
        except Exception as e:
            self.log.info('执行sql获取数据失败')
            self.log.exception(e)
            raise
        self.log.info('机构id:%d当前状态为%d' % (partnerId, statusFlag))
        print('机构id:%d当前状态为%d' % (partnerId, statusFlag))
        if statusFlag == 1:
            self.log.info('当前状态为启用,修改成禁用状态')
            print('当前状态为启用,修改成禁用状态')
            sendData['statusFlag'] = 0
        elif statusFlag == 0:
            self.log.info('当前状态为禁用,修改成启用状态')
            print('当前状态为禁用,修改成启用状态')
            sendData['statusFlag'] = 1
        else:
            raise ValueError('组织机构状态获取错误')
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("查看银行列表树接口")
    @pytest.mark.parametrize("data", adminBankTreeData, indirect=False)
    def test_bankList(self, data):
        """查询银行列表树"""
        apiurl = data['ApiUrl']
        requestsMethod = data['Method']
        expected = json.loads(data['expected'])
        r = self.base.sendRequest(apiurl, requestsMethod)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
Exemplo n.º 24
0
class TestContractNoManage:
    log = Log().getlog()
    db = DB_config()
    uploadAndDownloadFilePath = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'UploadAndDownloadFile')
    allData = GetData(excelFileName='admin_api.xlsx', sheetName='Sheet1')
    contNumRulePageData = allData.getTestCaseData(menuName='合同编号管理', belongs='contNumRulePage')
    saveContNumRuleData = allData.getTestCaseData(menuName='合同编号管理', belongs='saveContNumRule')
    lookImportPageData = allData.getTestCaseData(menuName='合同编号管理', belongs='lookImportPage')
    contNumRuleInfoData = allData.getTestCaseData(menuName='合同编号管理', belongs='contNumRuleInfo')
    insertOrUpdateContNumData = allData.getTestCaseData(menuName='合同编号管理', belongs='insertOrUpdateContNum')
    enableOrProhibitData = allData.getTestCaseData(menuName='合同编号管理', belongs='enableOrProhibit')
    enableOrProhibitDataIds = [i['IDS'] for i in enableOrProhibitData]
    upImportstatusData = allData.getTestCaseData(menuName='合同编号管理', belongs='upImportstatus')
    upImportstatusDataIds = [i['IDS'] for i in upImportstatusData]
    importRuleDateData = allData.getTestCaseData(menuName='合同编号管理', belongs='importRuleDate')
    getCompanyTreeByBasePartnerIdData = allData.getTestCaseData(menuName='合同编号管理',
                                                                belongs='getCompanyTreeByBasePartnerId')
    departmentPageData = allData.getTestCaseData(menuName='合同编号管理', belongs='departmentPage')
    saveDepartmentCodeData = allData.getTestCaseData(menuName='合同编号管理', belongs='saveDepartmentCode')
    getAreaPageData = allData.getTestCaseData(menuName='合同编号管理', belongs='getAreaPage')
    updateCodeData = allData.getTestCaseData(menuName='合同编号管理', belongs='updateCode')
    exportConfigAreaData = allData.getTestCaseData(menuName='合同编号管理', belongs='exportConfigArea')
    importData = allData.getTestCaseData(menuName='合同编号管理', belongs='importData')  # 这两条会重置数值,影响其他的,所以不执行
    recoveryDefaultData = allData.getTestCaseData(menuName='合同编号管理', belongs='recoveryDefault')  # 这两条会重置数值,影响其他的,所以不执行
    getBankData = allData.getTestCaseData(menuName='合同编号管理', belongs='getBank')
    saveBankData = allData.getTestCaseData(menuName='合同编号管理', belongs='saveBank')
    partnerSpPageData = allData.getTestCaseData(menuName='合同编号管理', belongs='partnerSpPage')
    saveSpCodeData = allData.getTestCaseData(menuName='合同编号管理', belongs='saveSpCode')
    getProductTypeData = allData.getTestCaseData(menuName='合同编号管理', belongs='getProductType')
    saveProductTypeData = allData.getTestCaseData(menuName='合同编号管理', belongs='saveProductType')
    getProductFromData = allData.getTestCaseData(menuName='合同编号管理', belongs='getProductFrom')
    saveProductFromData = allData.getTestCaseData(menuName='合同编号管理', belongs='saveProductFrom')
    test = Assertions()
    # 接口返回值sql校验文件路径
    yamlfilepath = os.path.join((os.path.dirname(os.path.dirname(__file__))), 'VerifyJsonAndSql',
                                'contractNoManage.yaml')
    jsonfilepath = os.path.join((os.path.dirname(os.path.dirname(__file__))), 'VerifyJsonAndSql',
                                'contractNoManage.json')

    def setup_class(self):
        self.base = loginAdmin(usr=Config().adminuser, pwd=Config().adminpwd)  # 用同一个登录成功后的session

        addDeleteSql = readYaml(self.yamlfilepath)['data']['savecontNumRule']['deleteSql']  # 删除添加的“自动化新增”规则
        self.db.excute(addDeleteSql)
        # 修改接口数据重置到初始状态
        selectSql = readYaml(self.yamlfilepath)['data']['insertOrUpdateContNum']['resetSql']['selectSql']
        insertSql = readYaml(self.yamlfilepath)['data']['insertOrUpdateContNum']['resetSql']['insertSql']
        updateSql1 = readYaml(self.yamlfilepath)['data']['insertOrUpdateContNum']['resetSql']['updateSql1']
        updateSql2 = readYaml(self.yamlfilepath)['data']['insertOrUpdateContNum']['resetSql']['updateSql2']
        deleteSql = readYaml(self.yamlfilepath)['data']['insertOrUpdateContNum']['resetSql']['deleteSql']
        # 插入数据前先查询数据库里是否有该条记录
        self.db.excute(selectSql)
        if self.db.get_one() == None:  # 没有查到记录时,执行插入
            self.db.excute(insertSql)
        self.db.excute(updateSql1)
        self.db.excute(updateSql2)
        self.db.excute(deleteSql)

        # 修改公司及部门中的编码为null
        resetDeptmentSql = readYaml(self.yamlfilepath)['data']['setupsql']['resetDeptmentSql']
        self.db.excute(resetDeptmentSql)

        # 修改合作车商的编码为null
        resetSpSql = readYaml(self.yamlfilepath)['data']['setupsql']['resetSpSql']
        self.db.excute(resetSpSql)

        # 修改业务类型的编码为null
        resrtProductTypeSql = readYaml(self.yamlfilepath)['data']['setupsql']['resrtProductTypeSql']
        self.db.excute(resrtProductTypeSql)

        # 修改业务来源直客的编码为null
        resrtProductFromSql = readYaml(self.yamlfilepath)['data']['setupsql']['resrtProductFromSql']
        self.db.excute(resrtProductFromSql)

    def teardown_class(self):
        # 修改省市中北京的默认值
        updateAreaSql = readYaml(self.yamlfilepath)['data']['setupsql']['resetAreaSql']
        self.db.excute(updateAreaSql)
        # 修改合作银行中杭州万欧的默认值为null
        resetBankSql = readYaml(self.yamlfilepath)['data']['setupsql']['resetBankSql']
        self.db.excute(resetBankSql)

    @allure.severity("normal")
    @allure.title("合同编号规则列表")
    @pytest.mark.parametrize("data", contNumRulePageData)
    def test_contNumRulePage(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
        # assert r.json()['code'] == expected, '接口返回业务状态码不匹配'
        if r.json()['code'] == 200:  # 状态码200时再进行数据校验
            if r.json()['page']['list'] != []:  # list不为空时校验返回值
                verifySql = (readYaml(self.yamlfilepath)['data']['contNumRulePage']['verifySql']).format(
                    sendData['basePartnerId'],
                    sendData['basePartnerId'],
                    sendData['pageSize'])
                self.db.excute(verifySql)
                dbresult = self.db.get_all()
                for i in range(len(dbresult)):
                    assert dbresult[i][0] == r.json()['page']['list'][i]['id']
                    assert dbresult[i][1] == r.json()['page']['list'][i]['ruleName']
                    assert dbresult[i][2] == r.json()['page']['list'][i]['status']
                    assert dbresult[i][3] == r.json()['page']['list'][i]['applyNum']

    # 这里开始完全校验返回值或数据库中的数据
    @allure.severity("normal")
    @allure.title("新建合同编号规则")
    @pytest.mark.parametrize("data", saveContNumRuleData)
    def test_saveContNumRule(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
        # assert r.json()['code'] == expected, '接口返回业务状态码不匹配'
        if r.json()['code'] == 200:  # 状态码200时再进行数据校验
            verifySql = (readYaml(self.yamlfilepath)['data']['savecontNumRule']['verifySql']).format(
                sendData['basePartnerId'])
            self.db.excute(verifySql)
            dbresult = self.db.get_one()
            id, ruleName, ruleType = dbresult[0], dbresult[1], dbresult[2]
            assert r.json()['id'] == id, '接口返回的新增合同编号id与数据库中的最新id不一致'
            assert sendData['ruleName'] == ruleName, '新增的合同名称与数据库中的最新名称不一致'
            assert sendData['type'] == ruleType, '新增的合同类型与数据库中的最新类型不一致'

    @allure.severity("normal")
    @allure.title("查询导入的合同编号列表")
    @pytest.mark.parametrize("data", lookImportPageData)
    def test_lookImportPage(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = int(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
        # assert r.json()['code'] == expected, '接口返回业务状态码不匹配'
        if r.json()['code'] == 200:  # 状态码200时再进行数据校验
            verifyJson = getApiJsonData(self.jsonfilepath, 'lookImportPage')
            assert r.json() == verifyJson

    @allure.severity("normal")
    @allure.title("查询合同编号详情")
    @pytest.mark.parametrize("data", contNumRuleInfoData)
    def test_contNumRuleInfo(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
        # assert r.json()['code'] == expected, '接口返回业务状态码不匹配'
        if r.json()['code'] == 200:  # 状态码200时再进行数据校验
            verifyJson = getApiJsonData(self.jsonfilepath, 'contNumRuleInfo')
            assert r.json() == verifyJson, "接口返回值与预期不符合"

    @allure.severity("normal")
    @allure.title("修改合同编号详情")
    @pytest.mark.parametrize("data", insertOrUpdateContNumData)
    def test_insertOrUpdateContNum(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        sendDatapartnerIdList = [i['partnerId'] for i in sendData['data']['contNumRulePartner']]  # 接口传参中勾选的机构id
        # 接口传参中的合同编号名称,描述,自定义规则
        ruleName = sendData['data']['contNumRule']['ruleName']
        description = sendData['data']['contNumRule']['description']
        customRule = sendData['data']['contNumRule']['customRule']
        isInvalidContract = sendData['data']['contNumRule']['isInvalidContract']
        serialTypeLength = sendData['data']['cumRulePlaceholder'][0]['serialTypeLength']
        sendData['data'] = json.dumps(sendData['data'])
        sendData['placeHolderList'] = json.dumps(sendData['placeHolderList'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
        # assert r.json()['code'] == expected, '接口返回业务状态码不匹配'
        if r.json()['code'] == 200:  # 状态码200时再进行数据校验

            verifySql1 = readYaml(self.yamlfilepath)['data']['insertOrUpdateContNum']['verifySql1']
            self.db.excute(verifySql1)
            dbresult = self.db.get_all()
            partnerIdList = [i[4] for i in dbresult]  # 请求接口后,数据库中实际的机构id
            verifySql2 = readYaml(self.yamlfilepath)['data']['insertOrUpdateContNum']['verifySql2']
            self.db.excute(verifySql2)
            sql_serialTypeLength = self.db.get_one()[0]
            sql_ruleName, sql_description, sql_customRule, sql_isInvalidContract = dbresult[0][0], dbresult[0][1], \
                                                                                   dbresult[0][2], dbresult[0][3]
            assert sendDatapartnerIdList == partnerIdList and sql_ruleName == ruleName and sql_description == description and \
                   sql_customRule == customRule and sql_isInvalidContract == isInvalidContract, sql_serialTypeLength == serialTypeLength
            "接口传参与数据库实际值不匹配"

    @allure.severity("normal")
    # @allure.title("启用/禁用合同编号规则")
    @pytest.mark.parametrize("data", enableOrProhibitData, ids=enableOrProhibitDataIds)
    def test_enableOrProhibit(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
        # 状态码200时再进行数据库status字段值校验
        if r.json()['code'] == 200:
            verifySql = readYaml(self.yamlfilepath)['data']['enableOrProhibit']['verifySql']
            self.db.excute(verifySql)
            dbresult = self.db.get_one()[0]
            assert sendData['status'] == dbresult, "接口传参与数据库实际值不匹配"

    @allure.severity("normal")
    # @allure.title("作废/恢复导入的合同编号规则")
    @pytest.mark.parametrize("data", upImportstatusData, ids=upImportstatusDataIds)
    def test_upImportstatus(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
        # 状态码200时再进行数据库status字段值校验
        if r.json()['code'] == 200:
            verifySql = readYaml(self.yamlfilepath)['data']['upImportstatus']['verifySql']
            self.db.excute(verifySql)
            dbresult = self.db.get_one()[0]
            assert sendData['status'] == dbresult, "接口传参与数据库实际值不匹配"

    @allure.severity("normal")
    @allure.title("导入合同编号")
    @pytest.mark.parametrize("data", importRuleDateData)
    def test_importRuleDate(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads((data['expected']))
        file = {
            'file': ('合同编号模板.xlsx', open(os.path.join(self.uploadAndDownloadFilePath, '合同编号模板.xlsx'), 'rb'))
        }
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData, files=file)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        assert self.test.verifyExpected(r.json(), expected)
        if r.json()['code'] == 200:
            # 返回json值校验
            verifyJson = getApiJsonData(self.jsonfilepath, 'importRuleDate')
            assert r.json() == verifyJson, "接口返回值与预期不符合"

    @allure.severity("normal")
    @allure.title("设置-公司及部门,查询左侧机构树")
    @pytest.mark.parametrize("data", getCompanyTreeByBasePartnerIdData)
    def test_getCompanyTreeByBasePartnerId(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        assert self.test.verifyExpected(r.json(), expected)
        if r.json()['code'] == 200:
            # 返回json校验
            verifyJson = getApiJsonData(self.jsonfilepath, 'getCompanyTreeByBasePartnerId')
            assert r.json() == verifyJson, "接口返回值与预期不符合"

    @allure.severity("normal")
    @allure.title("设置-公司及部门,获取机构部门详情")
    @pytest.mark.parametrize("data", departmentPageData)
    def test_departmentPage(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        assert self.test.verifyExpected(r.json(), expected)
        if r.json()['code'] == 200:
            # 返回json校验
            verifyJson = getApiJsonData(self.jsonfilepath, 'departmentPage')
            assert r.json() == verifyJson, "接口返回值与预期不符合"

    @allure.severity("normal")
    @allure.title("设置-公司及部门,保存机构/部门代号")
    @pytest.mark.parametrize("data", saveDepartmentCodeData)
    def test_saveDepartmentCode(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        sendDataList = [(i['id'], str(i['depCode'])) for i in sendData['deptList']]
        sendData['deptList'] = json.dumps(sendData['deptList'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
        # 状态码200时再进行数据库status字段值校验
        if r.json()['code'] == 200:
            verifySql = readYaml(self.yamlfilepath)['data']['saveDepartmentCode']['verifySql'].format(
                tuple([i[0] for i in sendDataList]))
            self.db.excute(verifySql)
            dbresult = self.db.get_all()
            assert tuple(sendDataList) == dbresult, "接口传参与数据库实际值不匹配"

    @allure.severity("normal")
    @allure.title("设置-省市,查询省市代号设置列表")
    @pytest.mark.parametrize("data", getAreaPageData)
    def test_getAreaPage(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
        # 返回json校验
        if r.json()['code'] == 200:
            verifyJson = getApiJsonData(self.jsonfilepath, 'getAreaPage')

            assert r.json() == verifyJson, "接口返回值与预期不符合"

    @allure.severity("normal")
    @allure.title("设置-省市,修改省市代号设置")
    @pytest.mark.parametrize("data", updateCodeData)
    def test_updateCode(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
        # 状态码200时再进行数据库status字段值校验
        if r.json()['code'] == 200:
            verifySql = readYaml(self.yamlfilepath)['data']['updateCode']['verifySql'].format(sendData['id'],
                                                                                              sendData['code'])
            self.db.excute(verifySql)
            dbresult = self.db.get_one()
            assert sendData['id'] == dbresult[0] and sendData['code'] == dbresult[1], "接口传参与数据库实际值不匹配"

    @allure.severity("normal")
    @allure.title("设置-省市,下载数据")
    @pytest.mark.parametrize("data", exportConfigAreaData)
    def test_exportConfigArea(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, param=sendData)
        assert r.status_code == 200, '接口请求状态码匹配失败'
        try:
            self.log.info('接口返回值:%s' % r.json())
            print('接口返回值:%s' % r.json())
        except Exception:
            with open(os.path.join(self.uploadAndDownloadFilePath, '省市区下载.xls'), 'wb') as f:
                f.write(r.content)
                print('文件保存路径为{}'.format(os.path.join(self.uploadAndDownloadFilePath, '省市区下载.xls')))
                self.log.info('文件保存路径为{}'.format(os.path.join(self.uploadAndDownloadFilePath, '省市区下载.xls')))
        else:
            assert r.json()['code'] == 200, '下载接口返回值异常'

    # 会影响其他用例
    @allure.severity("normal")
    @allure.title("设置-省市,导入数据")
    @pytest.mark.skip("会重置数据库所有数据导致前面的会有问题,这里不执行了")
    @pytest.mark.parametrize("data", importData)
    def test_importData(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        file = {
            'file': ('省市区上传.xlsx', open(os.path.join(self.uploadAndDownloadFilePath, '省市区上传.xlsx'), 'rb'))
        }
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, param=sendData, files=file)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("设置-省市,恢复默认")
    @pytest.mark.skip("会重置数据库所有数据导致前面的会有问题,这里不执行了")
    @pytest.mark.parametrize("data", recoveryDefaultData)
    def test_recoveryDefault(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, data=sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("设置-合作银行,查询合作银行代号设置列表")
    @pytest.mark.parametrize("data", getBankData)
    def test_getBank(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
        # 返回json校验
        if r.json()['code'] == 200:
            verifyJson = getApiJsonData(self.jsonfilepath, 'getBank')
            assert r.json() == verifyJson, "接口返回值与预期不符合"

    @allure.severity("normal")
    @allure.title("设置-合作银行,修改合作银行代号设置")
    @pytest.mark.parametrize("data", saveBankData)
    def test_saveBank(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        bankCode = sendData['data'][0]['code']
        sendData['data'] = json.dumps(sendData['data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
        # 状态码200时再进行数据库status字段值校验
        if r.json()['code'] == 200:
            verifySql = readYaml(self.yamlfilepath)['data']['saveBank']['verifySql']
            self.db.excute(verifySql)
            dbresult = self.db.get_one()
            assert bankCode == dbresult[0], "接口传参与数据库实际值不匹配"

    @allure.severity("normal")
    @allure.title("设置-合作车商,查询合作车商代号设置列表")
    @pytest.mark.parametrize("data", partnerSpPageData)
    def test_partnerSpPage(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
        # 返回json校验
        if r.json()['code'] == 200:
            verifyJson = getApiJsonData(self.jsonfilepath, 'partnerSpPage')
            assert r.json() == verifyJson, "接口返回值与预期不符合"

    @allure.severity("normal")
    @allure.title("设置-合作车商,修改合作车商代号设置")
    @pytest.mark.parametrize("data", saveSpCodeData)
    def test_saveSpCode(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        spCode = sendData['spList'][0]['spCode']
        sendData['spList'] = json.dumps(sendData['spList'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
        # 状态码200时再进行数据库status字段值校验
        if r.json()['code'] == 200:
            verifySql = readYaml(self.yamlfilepath)['data']['saveSpCode']['verifySql']
            self.db.excute(verifySql)
            dbresult = self.db.get_one()
            assert spCode == dbresult[0], "接口传参与数据库实际值不匹配"

    @allure.severity("normal")
    @allure.title("设置-业务类型,查询业务类型代号设置列表")
    @pytest.mark.parametrize("data", getProductTypeData)
    def test_getProductType(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
        # 返回json校验
        if r.json()['code'] == 200:
            verifyJson = getApiJsonData(self.jsonfilepath, 'getProductType')
            assert r.json() == verifyJson, "接口返回值与预期不符合"

    @allure.severity("normal")
    @allure.title("设置-合作车商,修改合作车商代号设置")
    @pytest.mark.parametrize("data", saveProductTypeData)
    def test_saveProductType(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        productTypeCode = sendData['data'][0]['code']
        sendData['data'] = json.dumps(sendData['data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
        # 状态码200时再进行数据库status字段值校验
        if r.json()['code'] == 200:
            verifySql = readYaml(self.yamlfilepath)['data']['saveProductType']['verifySql']
            self.db.excute(verifySql)
            dbresult = self.db.get_one()
            assert productTypeCode == dbresult[0], "接口传参与数据库实际值不匹配"

    @allure.severity("normal")
    @allure.title("设置-业务来源,查询业务来源代号设置列表")
    @pytest.mark.parametrize("data", getProductFromData)
    def test_getProductFrom(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
        # 返回json校验
        if r.json()['code'] == 200:
            verifyJson = getApiJsonData(self.jsonfilepath, 'getProductFrom')
            assert r.json() == verifyJson, "接口返回值与预期不符合"

    @allure.severity("normal")
    @allure.title("设置-业务来源,修改业务来源代号设置")
    @pytest.mark.parametrize("data", saveProductFromData)
    def test_saveProductFrom(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        productFromCode = sendData['data'][0]['code']
        sendData['data'] = json.dumps(sendData['data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
        # 状态码200时再进行数据库status字段值校验
        if r.json()['code'] == 200:
            verifySql = readYaml(self.yamlfilepath)['data']['saveProductFrom']['verifySql']
            self.db.excute(verifySql)
            dbresult = self.db.get_one()
            assert productFromCode == dbresult[0], "接口传参与数据库实际值不匹配"
Exemplo n.º 25
0
class Email:
    log = Log()

    def __init__(self,
                 server,
                 sender,
                 password,
                 receiver,
                 title,
                 message=None,
                 path=None):
        """初始化Email
        :param title: 邮件标题,必填。
        :param message: 邮件正文,非必填。
        :param path: 附件路径,可传入list(多附件)或str(单个附件),非必填。
        :param server: smtp服务器,必填。
        :param sender: 发件人,必填。
        :param password: 发件人密码,必填。
        :param receiver: 收件人,多收件人用“;”隔开,必填。
        """
        self.title = title
        self.message = message
        self.files = path
        self.msg = MIMEMultipart('related')
        self.server = server
        self.sender = sender
        self.receiver = receiver
        self.password = password

    def _attach_file(self, att_file):
        """将单个文件添加到附件列表中"""
        att = MIMEText(open('%s' % att_file, 'rb').read(), 'plain', 'utf-8')
        att["Content-Type"] = 'application/octet-stream'
        file_name = re.split(r'[\\|/]', att_file)
        att["Content-Disposition"] = 'attachment; filename="%s"' % file_name[-1]
        self.msg.attach(att)
        self.log.info('attach file {}'.format(att_file))

    def send(self):
        self.msg['Subject'] = self.title
        self.msg['From'] = self.sender
        self.msg['To'] = self.receiver
        # 邮件正文
        if self.message:
            self.msg.attach(MIMEText(self.message))
        # 添加附件,支持多个附件(传入list),或者单个附件(传入str)
        if self.files:
            if isinstance(self.files, list):
                for f in self.files:
                    self._attach_file(f)
            elif isinstance(self.files, str):
                self._attach_file(self.files)

        # 连接服务器并发送
        try:
            smtp_server = smtplib.SMTP(self.server)  # 连接sever
        except (gaierror and error) as e:
            self.log.info('发送邮件失败,无法连接到SMTP服务器,检查网络以及SMTP服务器. %s', e)
        else:
            try:
                smtp_server.login(self.sender, self.password)  # 登录
            except smtplib.SMTPAuthenticationError as e:
                self.log.info('用户名密码验证失败!%s', e)
            else:
                smtp_server.sendmail(self.sender, self.receiver.split(';'),
                                     self.msg.as_string())  # 发送邮件
            finally:
                smtp_server.quit()  # 断开连接
                self.log.info('发送邮件"{0}"成功! 收件人:{1}。如果没有收到邮件,请检查垃圾箱,'
                              '同时检查收件人地址是否正确'.format(self.title,
                                                     self.receiver))
Exemplo n.º 26
0
class TestDiscountManage:
    log = Log().getlog()
    db = DB_config()
    uploadAndDownloadFilePath = os.path.join(
        os.path.dirname(os.path.dirname(__file__)), 'UploadAndDownloadFile')
    allData = GetData(excelFileName='admin_api.xlsx', sheetName='Sheet1')
    tblCouponPageData = allData.getTestCaseData(menuName='优惠券管理',
                                                belongs='tblCouponPage')
    addCouponData = allData.getTestCaseData(menuName='优惠券管理',
                                            belongs='addCoupon')
    historyPageData = allData.getTestCaseData(menuName='优惠券管理',
                                              belongs='historyPage')
    downloadCouponData = allData.getTestCaseData(menuName='优惠券管理',
                                                 belongs='downloadCoupon')
    deleteCouponData = allData.getTestCaseData(menuName='优惠券管理',
                                               belongs='deleteCoupon')
    deleteCouponids = [i['IDS'] for i in deleteCouponData]
    test = Assertions()

    def setup_class(self):
        self.base = loginAdmin(usr=Config().adminuser,
                               pwd=Config().adminpwd)  # 用同一个登录成功后的session
        sql = "DELETE FROM tbl_coupon WHERE `name`='接口自动化优惠券'  "  # 数据清理后再执行用例
        self.db.excute(sql)

    @allure.severity("normal")
    @allure.title("查看优惠券列表")
    @pytest.mark.parametrize("data", tblCouponPageData)
    def test_getTblCouponPage(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        sendData['search'] = json.dumps({"startDate": "", "endDate": ""})
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("新增优惠券")
    # @pytest.mark.dependency(name='addCoupon')
    @pytest.mark.parametrize("data", addCouponData)
    def test_addTblCoupon(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("查看优惠券详情")
    # @pytest.mark.dependency(depends=['addCoupon'])
    @pytest.mark.parametrize("data", historyPageData)
    def test_historyPage(self, data):
        sql = "SELECT id FROM tbl_coupon  ORDER BY id  DESC LIMIT 0,1"
        self.db.excute(sql)
        try:
            id = self.db.get_one()[0]
        except TypeError:
            raise Exception("获取优惠券id异常")
        except Exception as e:
            self.log.exception(e)
            raise
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        if sendData['couponId'] == '':
            sendData['couponId'] = id
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("导出激活码")
    # @pytest.mark.dependency(depends=['addCoupon'])
    @pytest.mark.parametrize("data", downloadCouponData)
    def test_downloadCoupon(self, data):
        sql = "SELECT id FROM tbl_coupon  ORDER BY id  DESC LIMIT 0,1"
        self.db.excute(sql)
        try:
            id = self.db.get_one()[0]
        except TypeError:
            raise Exception("获取优惠券id异常")
        except Exception as e:
            self.log.exception(e)
            raise
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        if sendData['id'] == '':
            sendData['id'] = id
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, param=sendData)
        self.test.assert_code(r.status_code, 200)
        try:
            self.log.info('接口返回值:%s' % r.json())
            print('接口返回值:%s' % r.json())
        except json.decoder.JSONDecodeError:
            with open(
                    os.path.join(self.uploadAndDownloadFilePath, '优惠券激活码.xls'),
                    'wb') as f:
                f.write(r.content)
                print('文件保存路径为{}'.format(
                    os.path.join(self.uploadAndDownloadFilePath,
                                 '优惠券激活码.xls')))
                self.log.info('文件保存路径为{}'.format(
                    os.path.join(self.uploadAndDownloadFilePath,
                                 '优惠券激活码.xls')))
        except Exception as e:
            self.log.exception(e)
            raise
        else:
            self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    # @allure.title("关闭优惠券")
    # @pytest.mark.dependency(depends=['addCoupon'])
    @pytest.mark.parametrize("data", deleteCouponData, ids=deleteCouponids)
    def test_deleteCoupon(self, data):
        sql = "SELECT id FROM tbl_coupon  ORDER BY id  DESC LIMIT 0,1"
        self.db.excute(sql)
        try:
            id = self.db.get_one()[0]
        except TypeError:
            raise Exception("获取优惠券id异常")
        except Exception as e:
            self.log.exception(e)
            raise
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        if sendData['id'] == '':
            sendData['id'] = id
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
Exemplo n.º 27
0
class TestCostManage:
    log = Log().getlog()
    db = DB_config()
    uploadAndDownloadFilePath = os.path.join(
        os.path.dirname(os.path.dirname(__file__)), 'UploadAndDownloadFile')
    allData = GetData(excelFileName='admin_api.xlsx', sheetName='Sheet1')
    consumeDetailData = allData.getTestCaseData(menuName='费用管理',
                                                belongs='consumeDetail')
    downloadConsumeData = allData.getTestCaseData(menuName='费用管理',
                                                  belongs='downloadConsume')
    downloadRechargeData = allData.getTestCaseData(menuName='费用管理',
                                                   belongs='downloadRecharge')
    test = Assertions()

    def setup_class(self):
        self.base = loginAdmin(usr=Config().adminuser,
                               pwd=Config().adminpwd)  # 用同一个登录成功后的session

    @allure.severity("normal")
    @allure.title("查看详情-消费明细")
    @pytest.mark.parametrize("data", consumeDetailData)
    def test_consumeDetail(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("查看详情-导出消费明细")
    @pytest.mark.parametrize("data", downloadConsumeData)
    def test_downloadConsume(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, param=sendData)
        self.test.assert_code(r.status_code, 200)
        try:
            self.log.info('接口返回值:%s' % r.json())
            print('接口返回值:%s' % r.json())
        except Exception:
            with open(os.path.join(self.uploadAndDownloadFilePath, '消费明细.xls'),
                      'wb') as f:
                f.write(r.content)
                print('文件保存路径为{}'.format(
                    os.path.join(self.uploadAndDownloadFilePath, '消费明细.xls')))
                self.log.info('文件保存路径为{}'.format(
                    os.path.join(self.uploadAndDownloadFilePath, '消费明细.xls')))
        else:
            self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("查看详情-导出充值明细")
    @pytest.mark.parametrize("data", downloadRechargeData)
    def test_downloadRecharge(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, param=sendData)
        self.test.assert_code(r.status_code, 200)
        try:
            self.log.info('接口返回值:%s' % r.json())
            print('接口返回值:%s' % r.json())
        except Exception:
            with open(os.path.join(self.uploadAndDownloadFilePath, '充值明细.xls'),
                      'wb') as f:
                f.write(r.content)
                print('文件保存路径为{}'.format(
                    os.path.join(self.uploadAndDownloadFilePath, '充值明细.xls')))
                self.log.info('文件保存路径为{}'.format(
                    os.path.join(self.uploadAndDownloadFilePath, '充值明细.xls')))
        else:
            self.test.verifyExpected(r.json(), expected)
Exemplo n.º 28
0
class TestRoleAuthority:
    log = Log().getlog()
    db = DB_config()
    test = Assertions()
    allData = GetData(excelFileName='admin_api.xlsx', sheetName='Sheet1')
    TreeData = allData.getTestCaseData(menuName='角色权限管理', belongs='adminCompanyAndDeptTree')
    RoleListDate = allData.getTestCaseData(menuName='角色权限管理', belongs='RoleList')
    addRoleData = allData.getTestCaseData(menuName='角色权限管理', belongs='addRole')
    updateData = allData.getTestCaseData(menuName='角色权限管理', belongs='updateRole')
    deleteData = allData.getTestCaseData(menuName='角色权限管理', belongs='deleteRole')
    addDeptData = allData.getTestCaseData(menuName='角色权限管理', belongs='addDept')
    delDeptData = allData.getTestCaseData(menuName='角色权限管理', belongs='delDept')

    def setup_class(self):
        self.base = loginAdmin(usr=Config().adminuser, pwd=Config().adminpwd)  # 用同一个登录成功后的session

    @allure.severity("normal")  # blocker,critical,normal,minor,trivial 用例级别
    @allure.title("查看机构部门列表树接口")
    @pytest.mark.parametrize("data", TreeData, indirect=False)  # 参数化时以这种形式
    def test_getTree(self, data):
        """查询组织机构列表树"""
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        expected = json.loads(data['expected'])
        r = self.base.sendRequest(apiUrl, requestsMethod)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("查看机构下角色列表接口")
    @pytest.mark.parametrize("data", RoleListDate, indirect=False)  # 参数化时以这种形式
    def test_getRoleList(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @pytest.fixture(scope='class')
    def getNewRoleId(self, request):
        apiUrl = request.param['ApiUrl']
        requestsMethod = request.param['Method']
        sendData = json.loads(request.param['Data'])
        expected = json.loads(request.param['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, param=sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        return r.json(), sendData, self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("机构下新建角色接口")
    @pytest.mark.dependency(name='addNewRole')
    @pytest.mark.parametrize("getNewRoleId", addRoleData, indirect=True)  # 参数化时以这种形式
    def test_addNewRole(self, getNewRoleId):
        assert getNewRoleId[2]

    @allure.severity("normal")
    @allure.title("更新角色信息接口")
    @pytest.mark.dependency(depends=['addNewRole'])
    @pytest.mark.parametrize("getNewRoleId", addRoleData, indirect=True)
    @pytest.mark.parametrize("data", updateData, indirect=False)
    def test_updatRole(self, getNewRoleId, data):
        lastSendData = getNewRoleId[1]
        departmentId = lastSendData['departmentId']
        roleName = lastSendData['rolename'] + "修改"
        roleId = getNewRoleId[0]['id']
        apiUrl = data['ApiUrl']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        sendData['departmentId'] = departmentId
        sendData['rolename'] = roleName
        sendData['roleId'] = roleId
        requestsMethod = data['Method']
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, param=sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("删除角色信息接口")
    @pytest.mark.dependency(depends=['addNewRole'])
    @pytest.mark.parametrize("getNewRoleId", addRoleData, indirect=True)  # 参数化时以这种形式
    @pytest.mark.parametrize("deleteData", deleteData, indirect=False)
    def test_deleteRole(self, getNewRoleId, deleteData):
        apiUrl = deleteData['ApiUrl']
        sendData = json.loads(deleteData['Data'])
        sendData['id'] = getNewRoleId[0]['id']
        requestsMethod = deleteData['Method']
        expected = json.loads(deleteData['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @pytest.fixture(scope='class')
    def getDeptId(self, request):
        apiUrl = request.param['ApiUrl']
        requestsMethod = request.param['Method']
        sendData = json.loads(request.param['Data'])
        sendData['data'] = json.dumps(sendData['data'])
        expected = json.loads(request.param['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        return r.json(), sendData, self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("新建部门接口")
    @pytest.mark.dependency(name='addDept')
    @pytest.mark.parametrize("getDeptId", addDeptData, indirect=True)
    def test_addDept(self, getDeptId):
        assert getDeptId[2]

    @allure.severity("normal")
    @allure.title("删除部门接口")
    @pytest.mark.dependency(depends=['addDept'])
    @pytest.mark.parametrize("getDeptId", addDeptData, indirect=True)
    @pytest.mark.parametrize("data", delDeptData, indirect=False)
    def test_delDept(self, getDeptId, data):
        SenddataToJson = json.loads(getDeptId[1]['data'])
        deptName = SenddataToJson['name']
        parentSeriesId = SenddataToJson['parentSeriesId']
        sql = "SELECT id FROM pms_department WHERE `name`='{}' AND parentSeriesId='{}' ORDER BY id DESC LIMIT 0,1".format(
            deptName, parentSeriesId)
        self.db.excute(sql)
        id = self.db.get_one()[0]
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        sendData['departmentId'] = int(id)
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
Exemplo n.º 29
0
class TestPayManage:
    log = Log().getlog()
    db = DB_config()
    uploadAndDownloadFilePath = os.path.join(
        os.path.dirname(os.path.dirname(__file__)), 'UploadAndDownloadFile')
    allData = GetData(excelFileName='admin_api.xlsx', sheetName='Sheet1')
    accountChargeData = allData.getTestCaseData(menuName='充值管理',
                                                belongs='accountCharge')
    rechargeDetailData = allData.getTestCaseData(menuName='充值管理',
                                                 belongs='rechargeDetail')
    rdids = [i['IDS'] for i in rechargeDetailData]
    couponChargeData = allData.getTestCaseData(menuName='充值管理',
                                               belongs='couponCharge')
    OverDrawTopLimitData = allData.getTestCaseData(menuName='充值管理',
                                                   belongs='OverDrawTopLimit')
    test = Assertions()

    uploadFixtureData = [{
        "filepath":
        os.path.join(uploadAndDownloadFilePath, 'rechargepic.jpg'),
        "base":
        ""
    }]

    def setup_class(self):
        self.base = loginAdmin(usr=Config().adminuser,
                               pwd=Config().adminpwd)  # 用同一个登录成功后的session
        self.uploadFixtureData[0]['base'] = self.base

    # @pytest.fixture(scope='class')  #用conftest中的
    # def uploadPic(self):
    #     apiUrl = 'adminApi/mdaMediaResourceInfo/upload'
    #     file = {
    #         'file': ('rechargepic.jpg', open('rechargepic.jpg', 'rb')),
    #         'data': None
    #     }
    #     r = self.base.sendRequest(apiUrl, 'post', files=file)
    #     self.test.assert_code(r.json()['code'], 200)
    #     return r.json()

    @allure.severity("normal")
    @allure.title("可用余额充值")
    @pytest.mark.parametrize("uploadPic", uploadFixtureData, indirect=True)
    @pytest.mark.parametrize("data", accountChargeData)
    def test_accountCharge(self, uploadPic, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        sendData['rechargeTime'] = time.strftime("%Y-%m-%d %H:%M:%S",
                                                 time.localtime())
        sendData['voucher'] = uploadPic['visitUrl']
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @pytest.fixture(scope='class')
    def getCouponCode(self):
        apiUrl = 'adminApi/tblCoupon/couponDown'
        sendData = {
            'id': 204,  # 这里写死导出为名称为:不删除的优惠券
            'num': 1
        }
        self.log.info('本次使用参数:%s' % sendData)
        try:
            r = self.base.sendRequest(apiUrl, 'get', param=sendData)
            print("接口返回内容:", r.json())
        except json.decoder.JSONDecodeError:
            couponContent = r.content.decode()
            self.log.info('优惠券充值码导出成功:%s' % couponContent)
            print('优惠券充值码导出成功:%s' % couponContent)
            return couponContent
        except Exception as e:
            self.log.exception(e)
            raise
        else:
            self.log.error("导出优惠券接口异常")
            self.test.assert_code(r.json()['code'], 200)

    @allure.severity("normal")
    @allure.title("优惠券余额充值")
    @pytest.mark.parametrize("data", couponChargeData)
    def test_couponCharge(self, getCouponCode, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        sendData['voucher'] = getCouponCode
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    # @allure.title() 这里不用title,因为只是参数不一样,所以用ids来区分用例
    @pytest.mark.parametrize("data", rechargeDetailData, ids=rdids)
    def test_rechargeDetail(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)

    @allure.severity("normal")
    @allure.title("可透资金额修改")
    @pytest.mark.parametrize("data", OverDrawTopLimitData)
    def test_updateOverDrawTopLimit(self, data):
        apiUrl = data['ApiUrl']
        requestsMethod = data['Method']
        sendData = json.loads(data['Data'])
        expected = json.loads(data['expected'])
        self.log.info('本次使用参数:%s' % sendData)
        r = self.base.sendRequest(apiUrl, requestsMethod, sendData)
        self.log.info('接口返回值:%s' % r.json())
        print('接口返回值:%s' % r.json())
        self.test.verifyExpected(r.json(), expected)
Exemplo n.º 30
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/5/21 11:12
# @Author  : wenq
# @File    : compare_dict.py

import json
from Common.logger import Log
logger = Log().getlog()


def recursive_json_loads(data):

    try:
        if isinstance(data, list):
            return [recursive_json_loads(i) for i in data]
        elif isinstance(data, tuple):
            return tuple([recursive_json_loads(i) for i in data])
        elif isinstance(data, dict):
            return Storage({
                recursive_json_loads(k): recursive_json_loads(data[k])
                for k in data.keys()
            })
        else:
            try:
                obj = json.loads(data)
                if obj == data:
                    return data
            except:
                return data
            return recursive_json_loads(obj)