Example #1
0
    def test_0002_a_precisefind(self):
        """
        根据被保险人查询单子
        :return:
        """
        Con = Config()
        test = Assertions()
        allure = Allure()
        reques = Request.Request(self.evn)
        data = Basic()

        urls = data.url
        parms = data.data
        headers = data.header

        json_header = {'Authorization': 'bearer%s' % reques.get_session}

        host = Con.host_debug
        req_url = 'https://' + host

        test_data=Con.get_conf(Con.TITLE_DATA, Config.VALUE_insuredPerson)
        api_url = req_url + urls[0]['url_2']+ test_data
        response = reques.get_request(api_url,json_header)
        allure.allure_step('第一步','查询单子','根据被保险人,精准查询单子数量:%s'%response['jsons']['total'])
        print('根据被保险人,精准查询单子数量:%s'%response['jsons']['total'])
        assert test.assert_text(response['jsons']['total']>1,True)
Example #2
0
    def test_updatehierarchy_03(self):
        """
            用例描述:不变层级,名称重复
        """

        # 写log
        with allure.step("写入Log"):
            log = Log.MyLog()
            log.info('文件已开始执行')
            conf = Config()
            data = UpdateHierarchy()

        # 获取请求域名
        host = conf.host_debug
        req_url = 'http://' + host

        # 获取请求参数
        urls = data.url[2]
        header = data.header[2]
        param = data.data[2]
        responsecode = data.responsecode[2]
        sql_name = data.sqlname[2]
        env = conf.environment
        selectsql = data.selectsql[2]
        errorcode = data.errorcode[2]
        parentid = SqlResult(selectsql, env).get_sqlresult()

        sqlname = str(sql_name).replace('@sqlresult', str(parentid['parent_id']))
        pname = SqlResult(sqlname, env).get_sqlresult()

        # 参数化请求参数
        with allure.step("获取输入参数值"):
            try:
                param[0]['id'] = parentid['id']
                param[0]['name'] = pname['name']
                param[0]['parent_id'] = parentid['parent_id']
            except:
                log.info("获取参数失败:{0}".format(param[0]))

        # 请求接口
        api_url = req_url + urls
        print(api_url)

        print(param[0])

        # post请求
        request = Request.Request()
        with allure.step("开始请求接口,RUL: {0},header:{1},request:{2}".format(api_url, header, param[0])):
            response = request.post_request(api_url, json.dumps(param[0]), header)
            print(response)

            # 增加断言
            with allure.step("接口返回结果:{0}".format(response)):
                if response['code'] == responsecode:
                    assertbody = Assertions()
                    assertbody.assert_text(response['body'], errorcode)
Example #3
0
    def test_enablehierarchy_02(self):
        """
            用例描述:正常停用多个组织
        """

        # 写log
        with allure.step("写入Log"):
            log = Log.MyLog()
            log.info('文件已开始执行')
            conf = Config()
            data = EnableHierarchy()

        # 获取请求域名
        host = conf.host_debug
        req_url = 'http://' + host

        # 获取请求参数
        urls = data.url[1]
        header = data.header[1]
        param = data.data[1]
        selectsql = data.selectsql[1]
        responsecode = data.responsecode[1]
        env = conf.environment

        ids = SqlResult(selectsql, env).get_sqlresult_list()

        myid = []
        for i in range(len(ids)):
            for k, v in ids[i].items():
                myid.append(ids[i][k])
        print(myid)

        # 参数化请求参数
        with allure.step("获取输入参数值"):
            try:
                param[0]['ids'].extend(myid)
            except:
                log.info("获取参数失败:{0}".format(param[0]))

        # 请求接口
        api_url = req_url + urls

        # post请求
        request = Request.Request()
        with allure.step("开始请求接口,RUL: {0},header:{1},request:{2}".format(
                api_url, header, param[0])):
            response = request.post_request(api_url, json.dumps(param[0]),
                                            header)
            print(response)

        # 增加断言
        with allure.step("接口返回结果:{0}".format(response)):
            if response['code'] == responsecode:
                assertbody = Assertions()
                assertbody.assert_text(response['body'], True)
Example #4
0
    def test_deletehierarchy_01(self):
        """
            用例描述:正常删除一个层级
        """

        #写log
        with allure.step("写入Log"):
            log = Log.MyLog()
            log.info('文件已开始执行')
            conf = Config()
            data = DeleteHierarchy()

        #获取请求域名
        host = conf.host_debug
        req_url = 'http://' + host

        # 获取请求参数
        urls = data.url[0]
        header = data.header[0]
        param = data.data[0]
        my_param = param[0]['id']
        selectsql = data.selectsql[0]
        responsecode = data.responsecode[0]
        env = conf.environment

        ids = SqlResult(selectsql, env).get_sqlresult()

        # 参数化请求参数
        with allure.step("获取输入参数值"):
            try:
                param[0]['id'].append(ids['id'])
            except:
                log.info("获取参数失败:{0}".format(param[0]))

        #请求接口
        api_url = req_url + urls
        print(api_url)

        #post请求
        request = Request.Request()
        with allure.step("开始请求接口,RUL: {0},header:{1},request:{2}".format(
                api_url, header, param[0])):
            response = request.post_request(api_url, json.dumps(my_param),
                                            header)
            print(response)

        # 增加断言
        with allure.step("接口返回结果:{0}".format(response)):
            if response['code'] == responsecode:
                assertbody = Assertions()
                assertbody.assert_text(response['body'], True)
Example #5
0
    def test_demo3(self, driver):
        base = baseUI(driver)

        driver.get("http://192.168.60.132/login#/home")
        base.send_keys("输入用户名", "//input[@name='username']", "admin")
        base.send_keys("输入密码", "//input[@name='password']", "123456")
        # 点击登录
        base.click("点击登录", "//span[contains(text(),'登录')]")
        # 点击订单(//span[contains(text(),'订单')])[1]
        base.click("点击订单", "//span[contains(text(),'订单')]")
        # 点击订单列表(//span[contains(text(),'订单列表')]
        base.click("点击订单列表", "//span[contains(text(),'订单列表')]")
        # 点击订单状态//label[contains(text(),'订单状态:')]/following-sibling::div//input
        base.click(
            "点击订单状态",
            "//label[contains(text(),'订单状态:')]/following-sibling::div//input")
        # 点击待发货//span[contains(text(),'待发货')]
        base.click("点击代发货", "//span[contains(text(),'待发货')]")
        # 点击查询搜索//span[contains(text(),'查询搜索')]
        base.click("点击查询搜索", "//span[contains(text(),'查询搜索')]")
        # 点击勾选//div/div[2]/section/div/div[3]/div/div[2]/table/thead/tr/th[1]/div/label/span/span
        base.click("点击多选", "//section//div//thead//span/span")
        #批量发货//div[2]/section/div/div[4]/div/div[1]/input
        base.click("批量发货", "//div[2]/section/div/div[4]/div/div[1]/input")
        # 点击批量发货//span[contains(text(),'批量发货')]
        base.click("批量发货", "//span[contains(text(),'批量发货')]")
        # 点击确定//span[contains(text(),'确定')]
        base.click("点击确定", "//span[contains(text(),'确定')]")
        # 获取有几行
        rows = len(driver.find_elements_by_xpath("//tbody/tr"))
        # 选择物流公司//tbody/tr[1]/td[6]//input
        # 选择快递(//span[text()='顺丰快递'])[1]
        # 物流单号//tbody/tr[1]/td[7]//input
        for i in range(1, rows + 1):
            # 选择物流公司(//tbody/tr[1]/td[6]//input)
            base.click("选择物流公司", "//tbody/tr[{0}]/td[6]//input".format(i))
            # 选择快递(//span[text()='中通顺丰快递'])[10]
            base.click("选择快递",
                       "(//span[contains(text(),'顺丰快递')])[10]".format(i))
            # 物流单号//tbody/tr[1]/td[7]//input
            base.send_keys("物流单号", "//tbody/tr[{0}]/td[7]//input".format(i),
                           "1545648751454545")
        # 点击确定//span[contains(text(),'确定')]
        base.click("点击确定", "//span[contains(text(),'确定')]")
        # 点击确定(//span[contains(text(),'确定')])[2]
        base.click("点击确定", "(//span[contains(text(),'确定')])[2]")

        xpath = driver.find_element_by_xpath("//div[@role='alert']/p")
        assertions = Assertions()
        assertions.assert_in_text(xpath.text, '发货成功!')
Example #6
0
    def test_0001_add(self):
        """创建新单"""
        Con=Config()
        test=Assertions()
        allure=Allure()
        reques= Request.Request(self.evn)

        data=Basic()
        urls=data.url
        parms=data.data
        headers=data.header

        Con.set_item(Con.TITLE_DATA,Con.VALUE_policyNo,self.create_time() + '-' + self.create_unix())
        Con.set_item(Con.TITLE_DATA,Con.VALUE_reportNo,self.create_time() + '-' + self.create_unix())
        Con.set_item(Con.TITLE_DATA,Con.VALUE_reporttime,self.create_time())

        policyNo = Con.get_conf(Con.TITLE_DATA, Config.VALUE_policyNo)
        reportNo = Con.get_conf(Con.TITLE_DATA, Config.VALUE_reportNo)

        json_data ={'reportDate':self.create_now_time(),
                    "insuranceComName": Con.insuranceComName,
                    "insuredPerson": Con.insuredPerson,
                    "policyNo":policyNo,
                    "reportNo":reportNo,
                    }

        data_new =dict(parms[0],**json_data)

        json_header={'Authorization': 'bearer %s' % reques.get_session}
        header_new=dict(headers[0],**json_header)

        host = Con.host_debug
        req_url ='https://'+ host

        api_url = req_url + urls[0]['url_1']
        response = reques.post_request(api_url,json.dumps(data_new), header_new)

        allure.allure_step('第一步', '添加单子',(response['stats']))
        assert test.assert_code(response['code'], 200)
        assert test.assert_text((response['stats'])['success'],True)

        #查询事故号:
        req_url_1 = 'https://' + host
        url_find = req_url_1+ urls[0]['url_2']+'&policyNo='+ policyNo+'&reportDate='

        res = reques.get_request(url_find,json_header)
        Con.set_item(Con.TITLE_DATA, Con.VALUE_reporttid,res['jsons']['rows'][0]['id'])
        allure.allure_step('第二步', '查询单子','事故号id为:%s' %res['jsons']['rows'][0]['id'])
        print('事故号id为:%s' %res['jsons']['rows'][0]['id'])
Example #7
0
 def checkResult(self):
     """
     check test Log
     :return:
     """
     request_url = url + self.path
     headers = self.headers
     new_headers = json.loads(headers)
     info = RunMain().run_main(
         method=self.method, url=request_url, headers=new_headers
     )  # 根据Excel中的method调用run_main来进行requests请求,并拿到响应
     print('接口响应报文:{}'.format(info))  # 在report中打印响应报文
     # 对响应结果进行断言
     if self.case_name == 'header_pass':
         Assertions().assert_code(info['code'], 10200)
         Assertions().assert_in_text(info['message'], 'ok')
Example #8
0
    def test_demo(self, driver):
        base = baseUI(driver)

        driver.get("http://192.168.60.132/login#/home")
        base.send_keys("输入用户名", "//input[@name='username']", "admin")
        base.send_keys("输入密码", "//input[@name='password']", "123456")
        # 点击登录
        base.click("点击登录", "//span[contains(text(),'登录')]")
        #         点击营销//span[text()='营销']

        base.click("点击营销", "//span[text()='营销']")
        # 点击优惠券列表//span[text()='优惠券列表']
        base.click("点击优惠券列表", "//span[text()='优惠券列表']")
        # 点击编辑
        base.click("点击编辑", "(//span[contains(text(),'编辑')])[1]")
        #填写优惠券名称://label[contains(text(),'优惠券名称:')]/following-sibling::div//input
        base.send_keys(
            "填写优惠券名称",
            "//label[contains(text(),'优惠券名称:')]/following-sibling::div//input",
            "全场不通用")
        # 总发行量://label[contains(text(),'总发行量:')]/following-sibling::div//input
        base.send_keys(
            "填写总发行量",
            "//label[contains(text(),'总发行量:')]/following-sibling::div//input",
            "100")
        # 面额://label[contains(text(),'面额:')]/following-sibling::div//input
        base.send_keys(
            "填写面额",
            "//label[contains(text(),'面额:')]/following-sibling::div//input",
            "20")
        # 使用门槛://label[contains(text(),'使用门槛:')]/following-sibling::div//input
        base.send_keys(
            "填写使用门槛",
            "//label[contains(text(),'使用门槛:')]/following-sibling::div//input",
            "1000")
        # 点击提交//span[contains(text(),'提交')]
        base.click("点击提交", "//span[contains(text(),'提交')]")
        # 点击确定//span[contains(text(),'确定')]
        base.click("点击确定", "//span[contains(text(),'确定')]")
        # 断言
        # print(driver.page_source)
        xpath = driver.find_element_by_xpath("//div[@role='alert']/p")
        print(xpath)
        assertions = Assertions()
        # assertions.assert_in_text(driver.page_source, '修改成功')
        assertions.assert_in_text(xpath.text, '修改成功')
    def test_addhierarchy_07(self):
        """
            用例描述:name字段传空
        """
        # 写log
        with allure.step("写入Log"):
            log = Log.MyLog()
            log.info('文件已经开始执行')
            conf = Config()
            data = AddHierarchy()

        # 获取请求域名
        host = conf.host_debug
        req_url = 'http://' + host

        # 获取请求参数
        urls = data.url[4]
        header = data.header[4]
        param = data.data[4]
        env = conf.environment
        responsecode = data.responsecode[4]
        responsesql = data.responsesql[4]
        selectsql = data.selectsql[4]
        errorcode = data.errorcode[4]
        print(param[0])

        # 请求接口
        api_url = req_url + urls
        print(api_url)

        # post请求
        request = Request.Request()
        with allure.step("开始请求接口,RUL: {0},header:{1},request:{2}".format(
                api_url, header, param[0])):
            response = request.post_request(api_url, json.dumps(param[0]),
                                            header)
            print(response)

        # 增加断言
        with allure.step("接口返回结果:{0}".format(response)):
            if response['code'] == responsecode:
                assert response['body']
                assertbody = Assertions()
                assertbody.assert_text(response['header']['X-Api-Error-Code'],
                                       errorcode)
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)
Example #11
0
    def test_testdemo1(self):
        # 打开浏览器
        # 确定chromedriver.exe的位置
        driver_path = os.path.join(os.path.dirname(__file__), "../../chromedriver/chromedriver.exe")
        print(driver_path)
        driver = webdriver.Chrome(driver_path)
        driver.maximize_window()  # 最大化浏览器
        driver.implicitly_wait(8)  # 设置隐式时间等待
        time.sleep(2)
        driver.get("http://192.168.60.132/#/login")
        # 先输入用户名
        username = driver.find_element_by_xpath('//input[@name="username"]')
        username.clear()
        username.send_keys('admin')


        # 在输入密码
        password = driver.find_element_by_xpath('//input[@name="password"]')
        password.clear()
        password.send_keys('123456')

        # 最后点击登录
        login = driver.find_element_by_xpath('//span[contains(text(),"登录")]')
        login.click()


        time.sleep(2)
        # 添加断言
        assertions = Assertions()
        assertions.assert_in_text(driver.page_source, '首页')

        # 点击营销
        yingxiao = driver.find_element_by_xpath('//span[contains(text(),"营销")]')
        yingxiao.click()
        time.sleep(2)
        # 点击优惠券列表
        youhuiquan = driver.find_element_by_xpath('//span[contains(text(),"优惠券列表")]')
        youhuiquan.click()
        time.sleep(2)
        # 输入优惠券名称
    
        # 点击查询搜索
        sousuo = driver.find_element_by_xpath('//span[contains(text(),"查询搜索")]')
        sousuo.click()
        time.sleep(2)
        # 添加断言
        assertions = Assertions()
        assertions.assert_in_text(driver.page_source, '全品类通用券')
        driver.quit()

        pass
Example #12
0
    def test_demo(self,driver):
        base = baseUI(driver)
        # 打开网页
        driver.get("http://192.168.60.132/#/login")
        base.send_keys("输入用户名", "//input[@name='username']", "admin")
        base.send_keys("输入密码", "//input[@name='password']", "123456")
        # 点击登录
        base.click("点击登录","//span[contains(text(),'登录')]")

        # 点击营销
        base.click("点击营销", "(//span[contains(text(),'营销')])[1]")
        # 点击优惠券列表
        base.click("点击优惠券列表","(//span[contains(text(),'优惠券列表')])[1]")
        # 点击编辑编号为2的商品
        base.click("点击编辑", "(//span[contains(text(),'编辑')])[1]")
        # 点击优惠券类型
        base.click('点击优惠券类型',"(//label[contains(text(),'优惠券类型:')]/following-sibling::div//span)[1]")
        # 点击全场赠券
        base.click('点击全场赠券',"//span[contains(text(),'全场赠券')]")
        # 输入优惠券名称
        base.send_keys('输入优惠券名称',"//label[contains(text(),'优惠券名称:')]/following-sibling::div//input",'能看不能用')
        # 输入总发行量
        base.send_keys('输入总发行量',"//label[contains(text(),'总发行量:')]/following-sibling::div//input",'1')
        # 输入面额
        base.send_keys('输入面额',"//label[contains(text(),'面额:')]/following-sibling::div//input",'7')
        # 输入使用门槛
        base.send_keys('输入使用门槛',"//label[contains(text(),'使用门槛:')]/following-sibling::div//input","12")
        # 点击全场通用
        base.click('点击全场通用',"//label[contains(text(),'使用门槛:')]/following-sibling::div//input")
        # 点击提交
        base.click('点击提交',"//span[contains(text(),'提交')]")
        # 点击确定
        base.click('点击确定',"//span[contains(text(),'确定')]")
        # 添加断言
        # print(driver.page_source)打印,获取代码
        xpath = driver.find_element_by_xpath("//div[contains(@role,'alert')]/p")
        # print(xpath)  获取文字
        assertions = Assertions()
        assertions.assert_in_text(xpath.text,'修改成功')
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")
    def test_login_02(self, action):
        """
            用例描述:密码错误数据
        """

        # 写log
        with allure.step("写入Log"):
            log = Log.MyLog()
            log.info('文件已经开始执行')
            conf = Config()
            data = Login()

        request = Request.Request(action)

        #获取域名
        host = conf.host_debug
        req_url = 'http://' + host

        #获取请求参数
        urls = data.url
        params = data.data
        header = data.header
        requestsql = data.selectsql
        env = conf.environment
        responsecode = data.responsecode
        responsesql = data.responsesql
        casedescription = data.casedec

        #请求参数化
        with allure.step("获取输入参数值,{0}".format(requestsql[1])):
            try:
                sqlresult = SqlResult(requestsql[1], env).get_sqlresult()
                params[1][0]['auth'] = sqlresult['register_name']
            except:
                log.info("执行sql报错::" + requestsql[1])

        print(params[1][0])

        # 请求接口
        api_url = req_url + urls[1]
        with allure.step("开始请求接口,RUL: {0},header:{1},request:{2}".format(
                api_url, header[0], params[0][0])):
            response = request.post_request(api_url, json.dumps(params[1][0]),
                                            header[1])
            print(response)

        assertbody = Assertions()
        assertbody.assert_text(str(response['code']), str(responsecode[1]))
        with allure.step(
                "增加断言,ResponseCode:{0}=TestCode:{1},ResponseHeader:{2}".format(
                    response['code'], responsecode[1], response['header'])):
            if (response['code'] == responsecode[1]):
                #assertbody.assert_body(response['body'], 'message','密码错误')
                assertbody.assert_body(response['header'], 'X-Api-Error-Code',
                                       'ERR_LOGIN_FAILED')
            else:
                log.info("执行完成,Code不一致")
    def test_hierarchy_01(self):
        """
            用例描述:获取目录
        """

        #写log
        with allure.step("写入Log"):
            log = Log.MyLog()
            log.info('文件已开始执行')
            conf = Config()
            data = GetHierarchy()

        #获取请求域名
        host = conf.host_debug
        req_url = 'http://' + host
        env = conf.environment
        responsesql = data.responsesql
        responsecode = data.responsecode

        # 获取请求参数
        urls = data.url
        header = data.header

        #请求接口
        api_url = req_url + urls
        request = Request.Request()
        with allure.step("开始请求接口,RUL: {0},header:{1}".format(api_url, header)):
            response = request.get_request(api_url, None, header)
            print(response['body'])

        # 数据库查询结果
        try:
            # print(responsesql)
            responsesqlresult = SqlResult(responsesql, env).get_sqlresult_list()
            print(responsesqlresult)
            with allure.step("获取预期结果值成功"):
                log.info('查询结果数据库成功:' + responsesql)
        except:
            log.info('查询结果数据库失败:' + responsesql)

        print(responsecode)

        # 增加断言
        assertbody = Assertions()
        with allure.step("增加断言,接口返回结果:{0}".format(response)):
            assertbody.assert_text(str(response['code']), str(responsecode))
            if response['code'] == responsecode:
                for i in range(len(responsesqlresult)):
                    for k, v in responsesqlresult[i].items():
                        assertbody.assert_body(response['body'][i], k, responsesqlresult[i][k])
Example #16
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)
Example #17
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)
Example #18
0
 def checkResult(self):
     """
     check test Log
     :return:
     """
     request_url = url + self.path
     new_data = json.loads(self.data)  # 将Excel中提取的data从字符串转换成字典形式入参
     info = RunMain().run_main(
         method=self.method, url=request_url,
         data=new_data)  # 根据Excel中的method调用run_main来进行requests请求,并拿到响应
     print('接口响应报文:{}'.format(info))  # 在report中打印响应报文
     # 对响应结果进行断言
     if self.case_name == 'login_pass':
         Assertions().assert_code(info['code'], 10200)
         Assertions().assert_in_text(info['message'], 'success')
     if self.case_name == 'login_error':
         Assertions().assert_code(info['code'], 10104)
         Assertions().assert_in_text(info['message'], 'error')
     if self.case_name == 'login_null':
         Assertions().assert_code(info['code'], 10103)
         Assertions().assert_in_text(info['message'], 'null')
Example #19
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)
Example #20
0
    def test_0003_a_saveFirstTrackPojo(self):
        """
        诊疗类型:无治疗--暂存
        :return:
        """
        Con = Config()
        test = Assertions()

        allure = Allure()
        reques = Request.Request(self.evn)
        data = Basic()

        urls = data.url
        parms = data.data
        headers = data.header

        #不用初始化
        id = Con.get_conf(Con.TITLE_DATA, Config.VALUE_injureCaseId)  # 获取id
        policyNo = Con.get_conf(Con.TITLE_DATA, Config.VALUE_policyNo)  # 获取保单号
        reportNo = Con.get_conf(Con.TITLE_DATA, Config.VALUE_reportNo)  # 获取事故号

        #初始化
        # diagnoseType=Con.get_conf(Con.TITLE_DATA,Config.VALUE_diagnoseType)#人伤类型
        # licensePlate = Con.get_conf(Con.TITLE_DATA, Config.VALUE_licensePlate)  # 获取车牌
        # accidentdutytype = Con.get_conf(Con.TITLE_DATA, Config.VALUE_accidentDutyType)  # 事故责任类型


        Con.set_item(Con.TITLE_DATA,Config.VALUE_time,self.create_now_time())#获取时间

        createDate =Con.get_conf(Con.TITLE_DATA,Config.VALUE_time)#创建时间

        injuredName =Con.get_conf(Con.TITLE_DATA,Config.VALUE_injuredName)#人伤姓名
        injuredCertificateNum = Con.get_conf(Con.TITLE_DATA, Config.VALUE_injuredCertificateNum)  # 身份证
        injuredCertificateType =Con.get_conf(Con.TITLE_DATA,Config.VALUE_injuredCertificateType)#证件类型
        injuredPhone =Con.get_conf(Con.TITLE_DATA,Config.VALUE_injuredPhone)#联系号码
        livingStatus =Con.get_conf(Con.TITLE_DATA,Config.VALUE_livingStatus)#生存状态
        # injuredBirthday =Con.get_conf(Con.TITLE_DATA,Config.VALUE_injuredBirthday)#伤者出生日期
        # injuredAge =Con.get_conf(Con.TITLE_DATA,Config.VALUE_injuredAge)#伤者年龄

        detailAddress =Con.get_conf(Con.TITLE_DATA,Config.VALUE_detailAddress)#常住地址
        injuredSex =Con.get_conf(Con.TITLE_DATA,Config.VALUE_injuredSex)#常住地址

        #赔偿标准信息
        compensateBasis =Con.get_conf(Con.TITLE_DATA,Config.VALUE_compensateBasis)#赔偿依据
        compensateYear =Con.get_conf(Con.TITLE_DATA,Config.VALUE_compensateYear)#赔偿年度
        industry =Con.get_conf(Con.TITLE_DATA,Config.VALUE_industry)#从事行业

        #案件处理信息
        trackRecord=Con.get_conf(Con.TITLE_DATA,Config.VALUE_trackRecord)#案件处理信息


        taskType = '01'  # 01-首次跟踪,02-后续跟踪,03-跟踪审核
        taskState = '1'  # 0-未开始,1-处理中,2-已完成

        #important info 单号重点
        check_json_value(parms[1], 'id', id)  # id
        check_json_value(parms[1], "policyNo", policyNo)  # 保单号
        check_json_value(parms[1], 'reportNo', reportNo, )  # 事故号
        #base info 基本信息
        check_json_value(parms[1], 'diagnoseType', Con.diagnoseType)#人伤类型0一般损伤,1残疾,2死亡
        check_json_value(parms[1], 'injureCaseId',id)#id
        check_json_value(parms[1], 'reportDate',self.create_now_time())#创建时间
        check_json_value(parms[1], 'createDate',self.create_now_time())#流入时间
        check_json_value(parms[1], "licensePlate","粤A12345")#c车牌号
        check_json_value(parms[1], "accidentDutyType",Con.accidentDutyType)#车牌号

        #user info 用户信息
        check_json_value(parms[1], "injuredName",injuredName)#伤亡人员
        check_json_value(parms[1], "injuredCertificateType",injuredCertificateType)#证件类型
        check_json_value(parms[1], "injuredCertificateNum",injuredCertificateNum)#身份证号码
        check_json_value(parms[1], "injuredPhone",injuredPhone,)#身份证电话
        check_json_value(parms[1], "livingStatus",livingStatus,)#生存状态

        res = count_data(injuredCertificateNum)
        check_json_value(parms[1], "injuredBirthday", res['data'])  # 伤者出生日期
        check_json_value(parms[1], "injuredAge", res['age'])  # 伤者年龄
        check_json_value(parms[1], "injuredSex", injuredSex)  # 伤者性别

        check_json_value(parms[1], "accidentSite","福建省-泉州市")#事故地
        check_json_value(parms[1], "accidentSiteId","350500")#事故地
        check_json_value(parms[1], "domicilePlace","福建省-泉州市")#户籍所在地
        check_json_value(parms[1], "domicilePlaceId","360100")#户籍所在地
        check_json_value(parms[1], "habitualResidence","江西省-南昌市")#经常居住地
        check_json_value(parms[1], "habitualResidenceId","360100")#经常居住地
        check_json_value(parms[1], "detailAddress",detailAddress)#常住地址

        #赔偿标准信息
        check_json_value(parms[1], "compensateBasis", compensateBasis)  # 赔偿标准
        check_json_value(parms[1], "compensateYear", compensateYear)  # 赔偿年度
        check_json_value(parms[1], "industry", industry)  # 赔偿年度
        #案件处理信息

        check_json_value(parms[1], "trackRecord", trackRecord)  # 赔偿年度

        #重点在这
        check_json_value(parms[1]['hidTrackInjureDiagnose'][0], 'injureCaseId', id)
        check_json_value(parms[1]['hidTrackCompensateFee'][0], 'injureCaseId', id)
        check_json_value(parms[1]['hidTrackCompensateFee'][0]['hidTrackCompensateDetail'][0], 'injureCaseId', id)



        json_header = {'Authorization': 'bearer%s' % reques.get_session}
        header_new = dict(headers[1], **json_header)



        # print(parms[1]['hidTrackInjureDiagnose'])
        print(parms[1])



        host = Con.host_debug
        req_url = 'https://' + host
        api_url = req_url + urls[1]

        response = reques.post_request(api_url,json.dumps(parms[1]), header_new)
        print(response['jsons'])
        # assert test.assert_in_text(response['jsons']['success'],True)
        print(parms[1])
Example #21
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)
Example #22
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)
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)
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)
Example #25
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], "接口传参与数据库实际值不匹配"
Example #26
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)
Example #27
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)
Example #28
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], "接口传参与数据库实际值不匹配"
    def test_addhierarchy_02(self):
        """
            用例描述:创建三级组织
        """

        #写log
        with allure.step("写入Log"):
            log = Log.MyLog()
            log.info('文件已开始执行')
            conf = Config()
            data = AddHierarchy()

        #获取请求域名
        host = conf.host_debug
        req_url = 'http://' + host

        # 获取请求参数
        urls = data.url[1]
        header = data.header[1]
        param = data.data[1]
        env = conf.environment
        responsecode = data.responsecode[1]
        responsesql = data.responsesql[1]
        selectsql = data.selectsql[1]
        print(param[0])

        parentid = SqlResult(selectsql, env).get_sqlresult()

        # 参数化请求参数
        with allure.step("获取输入参数值"):
            try:
                param[0]['name'] = '国联信息' + str(int(time.time()))
                param[0]['parent_id'] = parentid['id']
            except:
                log.info("获取参数失败:{0}".format(param[0]))

        #请求接口
        api_url = req_url + urls
        print(api_url)

        #post请求
        request = Request.Request()
        with allure.step("开始请求接口,RUL: {0},header:{1},request:{2}".format(
                api_url, header, param[0])):
            response = request.post_request(api_url, json.dumps(param[0]),
                                            header)
            print(response)

        # 数据库查询结果
        try:
            responsesql = str(responsesql).replace('@sqlresult',
                                                   str(parentid['id']))
            responsesqlresult = SqlResult(responsesql,
                                          env).get_sqlresult_list()
            with allure.step("获取预期结果值成功,查询Sql:{0},查询结果:{1}".format(
                    responsesql, responsesqlresult)):
                log.info('查询结果数据库成功:' + responsesql)
        except:
            log.info('查询结果数据库失败:' + responsesql)

        actual = []
        for i in range(len(responsesqlresult)):
            for k, v in responsesqlresult[i].items():
                actual.append(responsesqlresult[i][k])

        # 增加断言
        assertbody = Assertions()
        with allure.step("接口返回结果:{0}".format(response)):
            assertbody.assert_text(str(response['code']), str(responsecode))
            if response['code'] == responsecode:
                assert param[0]['name'] in actual
    def test_addhierarchy_09(self):
        """
            用例描述:同一层级不同上级name重复
        """
        # 写log
        with allure.step("写入Log"):
            log = Log.MyLog()
            log.info('文件已经开始执行')
            conf = Config()
            data = AddHierarchy()

        # 获取请求域名
        host = conf.host_debug
        req_url = 'http://' + host

        # 获取请求参数
        urls = data.url[6]
        header = data.header[6]
        param = data.data[6]
        env = conf.environment
        responsecode = data.responsecode[6]
        responsesql = data.responsesql[6]
        sqlparentid = data.sqlpid[6]
        sqlname = data.sqlname[6]
        selectsql = data.selectsql[6]

        parentid = SqlResult(selectsql, env).get_sqlresult()

        # 参数化请求参数
        with allure.step("获取输入参数值"):
            try:
                param[0]['parent_id'] = parentid['id']
                param[0]['name'] = '同层级不同上级' + str(int(time.time()))
            except:
                log.info("获取参数失败:{0}".format(param[0]))

        # 请求接口
        api_url = req_url + urls
        print(api_url)
        print(param[0])
        request = Request.Request()
        addname = request.post_request(api_url, json.dumps(param[0]), header)

        # dsqlname = str(sqlname).replace('@sqlresult', str(parentid['id']))
        sqlid = str(sqlparentid).replace('@sqlresult', str(parentid['id']))
        # param[0]['name'] = SqlResult(dsqlname, env).get_sqlresult()['name']
        param[0]['parent_id'] = SqlResult(sqlid, env).get_sqlresult()['id']

        ############################
        print(param[0])

        # post请求

        with allure.step("开始请求接口,RUL: {0},header:{1},request:{2}".format(
                api_url, header, param[0])):
            response = request.post_request(api_url, json.dumps(param[0]),
                                            header)
            print(response)

        # 增加断言
        with allure.step("接口返回结果:{0}".format(response)):
            if response['code'] == responsecode:
                assertbody = Assertions()
                assertbody.assert_text(response['body'], True)