コード例 #1
0
 def coresyslogin(self):
     '''
     :return: 核心系统登录session
     '''
     print("核心系统登录")
     self.rwf = ReadAndWriteFiles()
     self.coreurlbase = self.rwf.ini_read(self.rwf.pathhosturl,
                                          "qwt_core_url")
     self.core = requests.Session()
     url1 = self.coreurlbase + "/random"
     data1 = {"cacheid": "0.49101218522027756"}
     header1 = {"Content-Type": "application/json"}
     self.core.get(url1, params=data1, headers=header1)
     url2 = self.coreurlbase + "/rest/user/back/accountLogin"
     data2 = {
         'callback':
         'jQuery17209220007142597262_1541401333724',
         'jsonParams':
         ''
         '{"method":"login","params":{"userAccount":"sysadmin","password":"******","randnumber":'
         '"0000","randnumKey":"0.49101218522027756","autoLogin":"******","serviceUrl":null}}',
         '_':
         '1541401341903'
     }
     resl = self.core.get(url2, params=data2, headers=header1)
     print(resl.text)
コード例 #2
0
ファイル: generatecase.py プロジェクト: jsj1jsj/UI_code_all
def Run(startIndex, endIndex):
    a = ReadAndWriteFiles()
    path = a.pathcasesource
    # x1 = xlrd.open_workbook(path)
    # test_dir = a.path_casedir()
    test_report = a.path_testreport()
    # globalB.CsheetRows = x1.sheet_by_name("control").nrows
    datalist = a.read_case()
    globalB.CsheetRows = len(datalist)
    now = time.strftime("%Y-%m-%d_%H_%M_%S")
    filename = test_report + '\\' + 'result.html'
    # filename = test_report + '\\' + now + 'result.html'
    globalB.Gdriver = filename
    fp = open(filename, 'wb')
    runner = HTMLTestRunner(stream=fp, title='测试报告', description='用例执行情况:')
    testunit = unittest.TestSuite()
    loader = unittest.defaultTestLoader
    # for i in range(test_11.IndexSet.aIndex, globalB.CsheetRows):
    # for i in range( test_11.IndexSet.aIndex, 10 ):
    test_11.IndexSet.set(startIndex)
    for i in range(startIndex, endIndex):
        new_cls = type("用例" + str(i + 1), (test_11.Request1, ), {})
        new_cls.__doc__ = datalist[i]['用例描述']
        test_cases = loader.loadTestsFromTestCase(new_cls)
        if (test_cases != None):
            testunit.addTests(test_cases)
    runner.run(testunit)
    fp.close()
コード例 #3
0
    def initRD(self, conf_redis="qtw_Redis"):
        # ===========读取RedisDB.ini文件===========
        rwf = ReadAndWriteFiles()

        self.host = rwf.ini_read(rwf.pathredis, "redis_host")
        self.port = int(rwf.ini_read(rwf.pathredis, "redis_port"))

        # host是redis主机,需要redis服务端和客户端都启动 redis默认端口是6379
        self.red = redis.Redis(host=self.host,
                               port=self.port,
                               decode_responses=True)
コード例 #4
0
 def loansyslogin(self,username,password):
     '''
     :return: 借贷系统登录session
     '''
     print("借贷系统登录")
     self.loan = requests.Session()
     self.rwf = ReadAndWriteFiles()
     self.loanurlbase =  self.rwf.ini_read( self.rwf.pathhosturl, "qwt_loan_url")
     url_deb = self.loanurlbase + "/operate/user/login"
     headers = {"Content-Type": "application/x-www-form-urlencoded"}
     data = {"account": username, "password": password, "system":"" }
     resl = self.loan.post(url_deb, data=data, headers=headers)
     print(resl.text)
コード例 #5
0
def reportscreenshot():
    options = webdriver.ChromeOptions()
    options.add_argument('headless')
    options.add_argument('--disable-gpu')
    driver = webdriver.Chrome(options=options)  # 打开谷歌浏览器
    driver.maximize_window()
    js_height = "return document.body.clientHeight"
    driver.get(globalB.Gdriver)
    k = 1
    height = driver.execute_script(js_height)
    while True:
        if k * 500 < height:
            js_move = "window.scrollTo(0,{})".format(k * 500)
            print(js_move)
            driver.execute_script(js_move)
            time.sleep(0.2)
            height = driver.execute_script(js_height)
            k += 1
        else:
            break
    scroll_width = driver.execute_script(
        'return document.body.parentNode.scrollWidth')
    scroll_height = driver.execute_script(
        'return document.body.parentNode.scrollHeight')
    driver.set_window_size(scroll_width + 500, scroll_height)

    time.sleep(test_case_time_manager.TIME_SCREENSHOT_WAIT_TIME)
    now = datetime.datetime.now().strftime("%Y%m%d%H%S%M")
    globalB.Gpng = ReadAndWriteFiles().path_screenshotreport(
    ) + "\\" + now + 'result.png'
    driver.get(globalB.Gdriver)
    time.sleep(test_case_time_manager.TIME_SCREENSHOT_WAIT_TIME)
    driver.get_screenshot_as_file(globalB.Gpng)
コード例 #6
0
    def readx(self, path):
        '''
        :param path:
        :return: xml文件的测试结果
        '''
        rwf = ReadAndWriteFiles()
        print(rwf.pathreportxml)
        doc = parse(rwf.pathreportxml)
        # 获取根节点
        root = doc.getroot()

        # 获取根节点下面的下一节点
        # 初始化result的值
        result = {"base": {}, "func": {}}
        list1 = []
        for data in root.findall('statistics'):
            for report in data.findall('suite'):
                for targets in report.findall('stat'):
                    if targets.attrib['id'].count("-") == 3:
                        if targets.attrib['id'][0:5] == "s1-s1":
                            if targets.attrib['fail'] == "0":
                                res_fail = 0
                                res_pass = 1
                            else:
                                res_fail = 1
                                res_pass = 0
                            result["func"][".".join(
                                targets.text.split(".")[-2:])] = [
                                    res_pass, res_fail
                                ]
                        else:
                            if targets.attrib['fail'] == "0":
                                res_fail = 0
                                res_pass = 1
                            else:
                                res_fail = 1
                                res_pass = 0
                            result["base"][targets.text.split(".")[-1]] = [
                                res_pass, res_fail
                            ]

        count_fail = 0
        count_pass = 0
        for k, v in result["base"].items():
            if v[0] == 1:
                count_pass += 1
            if v[1] == 1:
                count_fail += 1
        for k, v in result["func"].items():
            if v[0] == 1:
                count_pass += 1
            if v[1] == 1:
                count_fail += 1
        result["pass"] = count_pass
        result["fail"] = count_fail
        return result
コード例 #7
0
    def func():
        # 如果需要循环调用,就要添加以下方法
        delePG = deleteOperate()
        deleHb = deleteHbase()
        a1 = generatecase.Run()
        time.sleep(5)

        # 替换服务器html,json
        a = ReadAndWriteFiles()
        shutil.copy(
            os.path.join(a.path_testreport(), "result" + ".json"),
            os.path.join(globalB.Gdjango_static_path, "report" + ".json"))
        path = shutil.copy(
            os.path.join(a.path_testreport(), "result" + ".html"),
            os.path.join(globalB.Gdjango_templates_path, "report" + ".html"))
        # 替换服务器脚本
        new_str = '{% load static %}<script type="text/javascript" src="{% static "report.json" %}" charset="gbk"></script>'
        old_str = '<script type="text/javascript" src="result.json" charset="gbk"></script>'
        alter_text(path, old_str, new_str)

        # 截图
        b = reportscreenshot()
        # 发邮件
        EmailSend.sendmail(globalB.Gpng)
        # 获取现在时间
        now_time = datetime.datetime.now()
        # 获取明天时间
        next_time = now_time + datetime.timedelta(days=+1)
        next_year = next_time.date().year
        next_month = next_time.date().month
        next_day = next_time.date().day
        # 获取明天3点时间
        next_time = datetime.datetime.strptime(
            str(next_year) + "-" + str(next_month) + "-" + str(next_day) +
            " 08:00:00", "%Y-%m-%d %H:%M:%S")

        # 获取距离明天3点时间,单位为秒
        timer_start_time = (next_time - now_time).total_seconds()
        print(timer_start_time)
        timer = threading.Timer(timer_start_time, TimerLM.func)
        timer.start()
コード例 #8
0
def roberror():
    rx = ReadXML()
    list1 = rx.report_error_txt()
    print(list1 == [])
    if list1 == []:
        print("report目录下面的报告中没有报错的文件,所以不需要执行")
    else:
        rwf = ReadAndWriteFiles()
        cmd = "pybot -d %s/reporterror" % rwf.pathrob
        for i in list1:
            cmd = cmd + " " + i
        print(cmd)
        os.system(cmd)
コード例 #9
0
    def getdistrictcode(self):
        codelist = []
        codecity = []
        RWF = ReadAndWriteFiles()
        file = open(RWF.idcard_path, "r", encoding="utf-8")
        lines = file.readlines()  # 逐行读取
        for line in lines:
            if line.lstrip().rstrip().strip() != '' and (
                    line.lstrip().rstrip().strip())[:6][-2:] != '00':
                # 如果每行中去重后不为空,并且6位数字中最后两位不为00,则添加到列表里。(最后两位为00时为省份或地级市代码)
                codelist.append(line[:6])
                codecity.append(line[10:])

        return codelist, codecity
コード例 #10
0
ファイル: TimerLC.py プロジェクト: jsj1jsj/UI_code_all
    def func():
        # 如果需要循环调用,就要添加以下方法
        # deleHb = deleteHbase()
        # delePG = deleteOperate()
        a1 = generatecase.Run(0, 2)
        # a1 = generatecase.Run(0, 150)
        # 替换服务器html,json
        a = ReadAndWriteFiles()
        shutil.copy(
            os.path.join(a.path_testreport(), "result" + ".json"),
            os.path.join(globalB.Gdjango_static_path, "report" + ".json"))
        path = shutil.copy(
            os.path.join(a.path_testreport(), "result" + ".html"),
            os.path.join(globalB.Gdjango_templates_path, "report" + ".html"))
        # 替换服务器脚本
        new_str = '{% load static %}<script type="text/javascript" src="{% static "report.json" %}" charset="gbk"></script>'
        old_str = '<script type="text/javascript" src="result.json" charset="gbk"></script>'
        alter_text(path, old_str, new_str)

        # 截图
        b = reportscreenshot()
        # 发邮件
        EmailSend.sendmail(globalB.Gpng)
コード例 #11
0
    def report_error_txt(self):
        '''
        :return: report报告中所有发生错误txt的集合
        '''
        rwf = ReadAndWriteFiles()
        print(rwf.pathreportxml)
        doc = parse(rwf.pathreportxml)
        # 获取根节点
        root = doc.getroot()

        # 获取根节点下面的下一节点
        # 获取total的值
        list1 = []
        for data in root.findall('statistics'):
            for report in data.findall('suite'):
                for targets in report.findall('stat'):
                    if targets.attrib['id'].count(
                            "-") == 3 and targets.attrib['fail'] != "0":
                        list1.append(rwf.pathrob + "/qutouwang/" +
                                     targets.text.replace(".", "/").replace(
                                         "Api", "api") + ".txt")
                        # print(targets.text)
        return list1
コード例 #12
0
 def __init__(self):
     self.reques = requests.Session()
     rwf = ReadAndWriteFiles()
     self.urlbase = rwf.ini_read(rwf.pathhosturl, "qwt_app_url")
コード例 #13
0
def send_mail(subject):
    rwf = ReadAndWriteFiles()
    rx = ReadXML()
    result = rx.readx(rwf.pathreportxml)

    to_addrs = str(rwf.ini_read(
        rwf.pathemailini, "email_to_addrs")).strip(',').split(',')  # 收件人地址
    from_addr = str(rwf.ini_read(rwf.pathemailini,
                                 "email_from_addr"))  # 发件人人地址
    smtp_addr = str(rwf.ini_read(rwf.pathemailini, "email_smtp_addr"))  # 邮件服务器
    password = str(rwf.ini_read(rwf.pathemailini, "email_password"))  # 发件人密码
    mail_msg = MIMEMultipart()  # 初始化邮件内容

    str5 = ""
    str0 = '<div class="heading"><h1>去投网2.0接口测试报告</h1><p class="attribute"><strong>Start Time:</strong> %s</p><p class="attribute"><strong>Duration:</strong> ———</p><p class="attribute"><strong>Status:</strong> Pass %s Fail %s</p><p class="description">去投网2.0接口测试</p></div>' % (
        datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), result["pass"],
        result["fail"])
    str1 = '<table border="1" cellspacing="0" style="width: 80%;border-collapse: collapse;border: 1px solid #777;"><tbody>'
    str2 = '<tr style="font-weight: bold;color: white;background-color: #777;"><td>去投网2.0api接口测试</td><td>Count</td><td>Pass</td><td>Fail</td></tr>'
    if int(result["fail"]) > 0:
        str3 = '<tr style="background-color: #c60;"><td>test_result</td><td>%s</td><td>%s</td><td>%s</td></tr>' % (
            result["pass"] + result["fail"], result["pass"], result["fail"])
    else:
        str3 = '<tr style="background-color: #6c6;"><td>test_result</td><td>%s</td><td>%s</td><td>%s</td></tr>' % (
            result["pass"] + result["fail"], result["pass"], result["fail"])
    i = 1
    for key in result["base"].keys():
        if int(result["base"][key][1]) > 0:
            str5 = str5 + '<tr style="background-color: #c60;"><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>' % (
                i, key, result["base"][key][0], result["base"][key][1])
        else:
            str5 = str5 + '<tr style="background-color: #6c6;"><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>' % (
                i, key, result["base"][key][0], result["base"][key][1])
        i = i + 1

    #=============================主要流程=============================
    str50 = ""
    str20 = '<tr style="font-weight: bold;color: white;background-color: #777;"><td>去投网2.0主要流程测试</td><td>Count</td><td>Pass</td><td>Fail</td></tr>'
    i = 1
    for key in result["func"].keys():
        if int(result["func"][key][1]) > 0:
            str50 = str50 + '<tr style="background-color: #c60;"><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>' % (
                i, key, result["func"][key][0], result["func"][key][1])
        else:
            str50 = str50 + '<tr style="background-color: #6c6;"><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>' % (
                i, key, result["func"][key][0], result["func"][key][1])
        i = i + 1

    str6 = '</tbody></table>'
    str7 = "<a href ='http://192.168.1.31:8090/jenkins/job/qtw_interfacetest_autoenv_SendEmail/'><button type='button'>" \
           "<h4>点击查看详细报告</h4></button></a>"
    str1 = str0 + str1 + str2 + str3 + str5 + str20 + str50 + str6 + str7

    test = str1.encode('utf-8')
    mail_body = test

    MIMEText(mail_body, 'plain', 'utf-8')

    html_report = MIMEText(mail_body, _subtype='html', _charset='utf-8')
    mail_msg.attach(html_report)  # 读取的报告写在邮件内容中
    mail_msg['Subject'] = subject
    mail_msg['From'] = from_addr
    mail_msg['To'] = ','.join(to_addrs)
    s = smtplib.SMTP()
    s.connect(smtp_addr)
    s.login(from_addr, password)
    s.sendmail(from_addr, to_addrs, mail_msg.as_string())
    s.quit()
コード例 #14
0
class LoanSystem(object):
    '''
    去投网借款系统基本功能
    '''
    def loansyslogin(self,username,password):
        '''
        :return: 借贷系统登录session
        '''
        print("借贷系统登录")
        self.loan = requests.Session()
        self.rwf = ReadAndWriteFiles()
        self.loanurlbase =  self.rwf.ini_read( self.rwf.pathhosturl, "qwt_loan_url")
        url_deb = self.loanurlbase + "/operate/user/login"
        headers = {"Content-Type": "application/x-www-form-urlencoded"}
        data = {"account": username, "password": password, "system":"" }
        resl = self.loan.post(url_deb, data=data, headers=headers)
        print(resl.text)

    def loaninfodebt(self,name,phone,idcard,rate,month,money,jkname,type = None):
        '''
        :param name: 借款人姓名
        :param phone: 借款人手机号
        :param idcard: 借款人身份证号
        :param rate: 产品利率
        :param month: 产品期限
        :param money: 金额
        :type money: 默认是False,True代表推送智享
        :return:进件列表导入债权
        '''
       #生成债权
        wb = load_workbook(filename=self.rwf.pathloansysinto)
        ws = wb['Sheet1']
        ws['J2'] = name
        ws['C2'] = jkname
        ws['W2'] = phone
        ws['B2'] = idcard
        ws['F2'] = rate
        ws['G2'] = month
        ws['D2'] = money
        wb.save(self.rwf.pathloansysinto)
        wb.close()
        # 借款管理—进件列表—导入
        url_into = self.loanurlbase + "/operate/entrylist/upLoadDataDaoRu"
        # head_into = {"Content-Type":"multipart/form-data_testenv"}   #有header失败,没有header却成功了
        files = {'file': open(self.rwf.pathloansysinto, 'rb')}
        resl = self.loan.post(url_into, files=files)
        # 获取进件编号,并存储在resourse中
        debtcode = json.loads(resl.text)["list"]["list"][0]["debtcode"]
        print("进件编号为%s" % debtcode)
        if type == "True":
            self.rwf.update_resourse("resourse","${debtCode_zx}", debtcode)
        else:
            self.rwf.update_resourse("resourse","${debtCode}", debtcode)

    def debitcheck(self,debtCode,cifname,third):
        '''
        :param debtCode: 债权编号
        :param cifname: 垫付机构
        :param third: 编号
        :return: 在进件列表对债权进行编辑,在审核列表审核
        '''
        print("进件列表—编辑")
        print("债权编号%s"%debtCode)
        url_che = self.loanurlbase + "/operate/entrylist/entryList"
        data_che = json.dumps({"page": 1, "rows": 10, "offset": 0, "debtcode": debtCode, "borrowername": "", "loanmode": "","status": "", "beginDate": "", "endDate": ""})
        head_che = {"Content-Type": "application/json"}
        resl = self.loan.post(url_che, data=data_che, headers=head_che)
        resl_dic = json.loads(resl.text)
        a = resl_dic["rows"][0]["oid"]
        # oid编辑债权的主键信息
        url_tj = self.loanurlbase + "/operate/entrylist/updateSubmitEntryList"
        data_tj = json.dumps({"oid": a,"cusMask": "尽管借款人能够履行合同,但存在一些可能对偿还产生不利影响的因素,如这些因素继续下去,借款人的偿还能力受到影响。还款意愿正常,收入、稳定性等各方面状况正常",
                              "firstRepaymentSource": "借款企业主管业务收入偿还","loanFinanceInfo": "经营良好","loanRepaymentInfo": "企业经营状况良好,无异常","overdueReport": "良好",
                              "repaymentGuarantee": "信用资质良好,有车有房可抵押","twoRepaymentSource": "抵押房产车产变现"})

        head_tj = {"Content-Type": "application/json"}
        resl = self.loan.post(url_tj, data=data_tj, headers=head_tj)
        # print(resl.text)
        if '"errorCode":0' in resl.text:
            print("qtw借款端登编辑成功")
        else:
            raise Exception("qtw借款端登编辑失败")
        print("审核列表—审核")
        url_sh = self.loanurlbase + "/operate/entryAuditlist/updateAudit"
        data_sh = json.dumps({"oid": a, "description": "同意", "grtpaymentaccountname": cifname, "grtpaymentaccountno": third})
        head_sh = {"Content-Type": "application/json"}
        resl = self.loan.post(url_sh, data=data_sh, headers=head_sh)
        if '"errorCode":0' in resl.text:
            pass
        else:
            raise Exception("审核失败")

    def lendingbid(self,debtCode):
        '''
        :param debtCode: 债权编号
        :return: 满标后放款
        '''
        print("=======================第一步,查询放款列表的债权%s=========================" % debtCode)
        url_check = self.loanurlbase + "/operate/makelist/MakeList"
        header2 = {"Content-Type": "application/json"}
        data2 = {"page": 1, "rows": 10, "offset": 0, "loanNo": debtCode, "cifName": "", "returnMethod": "",
                 "loanStatus": "", "beginDate": "", "endDate": "", "pactissueNo": "", "cifPhone": ""}
        data2 = json.dumps(data2)
        resl = self.loan.post(url_check, data=data2, headers=header2)
        print(resl.text)
        oid = json.loads(resl.text)["rows"][0]["oid"]

        print("======================第二步,债权放款==========================")
        url_loan = self.loanurlbase + "/operate/makelist/loan"
        header3 = {"Content-Type": "application/x-www-form-urlencoded"}
        data3 = {'oid': oid}
        resl = self.loan.post(url_loan, data=data3, headers=header3)
        print(resl.text)
        print("======================第三步,判断债权状态为放款成功==========================")
        for i in range(10):
            time.sleep(20)
            url_check = self.loanurlbase + "/operate/makelist/MakeList"
            header2 = {"Content-Type": "application/json"}
            data2 = {"page": 1, "rows": 10, "offset": 0, "loanNo": debtCode, "cifName": "", "returnMethod": "",
                     "loanStatus": "", "beginDate": "", "endDate": "", "pactissueNo": "", "cifPhone": ""}
            data2 = json.dumps(data2)
            resl = self.loan.post(url_check, data=data2, headers=header2)
            # print(resl.text)
            rels = json.loads(resl.text)["rows"][0]["loanStatus"]
            print(rels)
            if "00" == rels:
                print("放款成功")
                break
        bidNocore = self.rwf.read_resourse("resourse","${bidNocore}")
        db = MysqlDB()
        script = "SELECT order_id FROM p2p_invest_order WHERE pactissue_no = '%s' LIMIT 1;" % bidNocore
        result = db.select_return_A_data(script)
        self.rwf.update_resourse("resourse", "${order_id}", str(result[0]))

    def overdueoneday(self,debtCode,term_num):
        '''
        :param debtCode: 债权编号
        :param term_num: 逾期期数
        :return: 逾期一天
        '''
        print("==========逾期1天申请垫付===========")
        #读取当天时间
        should_date = time.strftime('%Y-%m-%d', time.localtime())
        #时间更改为1天前
        should_ymd = should_date.split("-")
        should_date_1 = self.getday(y=int(should_ymd[0]), m=int(should_ymd[1]), d=int(should_ymd[2]), n=-1)
        print("还款日期向今天前推1天的时间%s"%should_date_1)
        #更改数据,使还款计划的第二期逾期
        db = MysqlDB()
        db.sql_update('UPDATE qtw_loan_db.p2p_borrower_return_plan SET should_date = "%s" WHERE debtcode = "%s" AND term_num = "%s"'%(should_date_1,debtCode,term_num))
        print("==================第一步,逾期申请==================")
        self.croundjob()
        # 根据债权信息查询【申请列表】oid
        oid = 0
        for i in range(10):
            oid = db.select_return_A_data('SELECT oid FROM qtw_loan_db.p2p_exceed_time_return WHERE debtcode = "%s"' % debtCode)
            if oid != None:
                oid = str(oid[0])
                print("在第%s分钟生产oid的值"%i)
                break
            time.sleep(10)


        # 借贷系统登录,申请垫付
        header = {"Content-Type": "application/x-www-form-urlencoded"}
        data = {"oid": oid}
        url_1 = self.loanurlbase + "/operate/advances/applyReport"
        rslt = self.loan.post(url_1, data=data, headers=header)
        print(rslt.text)
        if 'success' in rslt.text:
            print("申请垫付成功")
        else:
            raise Exception("申请垫付失败")

        print("==================第二步,机构垫付==================")
        time.sleep(20)
        url_2 = self.loanurlbase +  "/operate/makelist/padPay"
        rslt = self.loan.post(url_2, data=data, headers=header)
        print(rslt.text)
        if '操作成功' in rslt.text:
            print("逾期垫付成功")
        else:
            raise Exception("逾期垫付失败")
        time.sleep(10)

    def overduemanyday(self,debtCode,term_num):
        print("==================借款人逾期8天,生成罚息数据==================")
        # 时间更改为8天前
        should_date = time.strftime('%Y-%m-%d', time.localtime())
        should_ymd = should_date.split("-")
        should_date_8 = self.getday(y=int(should_ymd[0]), m=int(should_ymd[1]), d=int(should_ymd[2]), n=-8)
        print("第二期还款日期向今天前推8天的时间%s" % should_date_8)
        # 更改数据,使还款计划的第二期逾期8天
        db = MysqlDB()
        db.sql_update('UPDATE qtw_loan_db.p2p_borrower_return_plan SET should_date = "%s" WHERE debtcode = "%s" AND term_num = "%s"' % (should_date_8, debtCode, term_num))
        db.sql_update("UPDATE qtw_loan_db.p2p_exceed_time_return SET expect_back_date = '%s',exceed_date = '%s' WHERE debtcode = '%s' AND term_num = %s;" % (should_date_8,should_date,debtCode, term_num))
        self.croundjob()
        punish_amt = 0
        for i in range(10):
            # 查询罚息的值
            punish_amt = db.select_return_A_data('SELECT punish_amt FROM qtw_loan_db.p2p_exceed_time_return WHERE debtcode = "%s" AND term_num = "2"' % debtCode)
            punish_amt = str(punish_amt[0])
            print("逾期罚息的金额为%s" % punish_amt)
            if int(punish_amt) > 0:
                print("逾期之后生成罚息,耗时%s分钟"%i)
                break
            time.sleep(10)
        if int(punish_amt) == 0:
                raise Exception("逾期之后没有生成罚息")

    def getday(self,y=2017,m=8,d=15,n=0):
        the_date = datetime.datetime(y,m,d)
        result_date = the_date + datetime.timedelta(days=n)
        d = result_date.strftime('%Y-%m-%d')
        return d
    def croundjob(self):
        '''
        :return: 执行借款系统的定时任务
        '''
        url_croundjob = self.rwf.ini_read( self.rwf.pathhosturl, "qwt_loan_cround_url")
        loan_cround = requests.Session()
        #未还款逾期处理
        url_unRepay = url_croundjob + "/activeTuning/unRepaymentBeoverdueHandleJob"
        # 罚息计算
        url_beoverdueMoney = url_croundjob + "/activeTuning/beoverdueMoneyCalculationJob"
        r1 = loan_cround.post(url_unRepay)
        r2 = loan_cround.post(url_beoverdueMoney)
        print(url_unRepay)
        print(url_beoverdueMoney)
        print(r1)
        print(r2)
コード例 #15
0
class CoreSystem(object):
    '''
    去投网核心系统基本功能
    '''
    def coresyslogin(self):
        '''
        :return: 核心系统登录session
        '''
        print("核心系统登录")
        self.rwf = ReadAndWriteFiles()
        self.coreurlbase = self.rwf.ini_read(self.rwf.pathhosturl,
                                             "qwt_core_url")
        self.core = requests.Session()
        url1 = self.coreurlbase + "/random"
        data1 = {"cacheid": "0.49101218522027756"}
        header1 = {"Content-Type": "application/json"}
        self.core.get(url1, params=data1, headers=header1)
        url2 = self.coreurlbase + "/rest/user/back/accountLogin"
        data2 = {
            'callback':
            'jQuery17209220007142597262_1541401333724',
            'jsonParams':
            ''
            '{"method":"login","params":{"userAccount":"sysadmin","password":"******","randnumber":'
            '"0000","randnumKey":"0.49101218522027756","autoLogin":"******","serviceUrl":null}}',
            '_':
            '1541401341903'
        }
        resl = self.core.get(url2, params=data2, headers=header1)
        print(resl.text)

    def querydebtId(self, debtCode, type=None):
        '''
        :param debtCode: 债权编号
        :return: 债权的主键
        '''
        url3 = self.coreurlbase + "/rest/debt/queryAll"
        data3 = {
            't':
            '1541756027711\n',
            'callback':
            'jQuery172011043902518311977_1541756012872\n',
            'jsonParams':
            '{"method":"queryAll","params":{"page":{"conditions":"{\\"debtCode\\":\\"%s\\"}","pageNum":1,"pageSize":10}}}\n'
            % debtCode,
            '_':
            '1541756027711'
        }
        header1 = {"Content-Type": "application/json"}
        resl = self.core.get(url3, params=data3, headers=header1)
        # print(resl.text)
        if "SUCCESS" in resl.text:
            pass
        else:
            raise Exception("借款端推送债权到核心失败")
        print(resl.text)
        debtIdcore = self.regular('"debtId":(.+?),', resl.text, 1)
        if type == "True":
            self.rwf.update_resourse("resourse", "${debtIdcore_zx}",
                                     debtIdcore)
        else:
            self.rwf.update_resourse("resourse", "${debtIdcore}", debtIdcore)
        print("债权主键为%s" % debtIdcore)

    def corecheckandfabiao(self, debtIdcore):
        '''
        :param debtIdcore: 债权主键
        :return: 发标
        '''
        print("创建散标=================")
        url3 = self.coreurlbase + "/rest/debt/batchCreate"
        data3 = {
            '_':
            '1543739780142',
            't':
            '1543739780141\n',
            'jsonParams':
            '{"method":'
            '"batchCreate","params":{"debtIds":"%s","type":"submit","param":"{\\"box\\":\\'
            '"52600043652\\",\\"effectTime\\":\\"5\\",\\"effectTimeUnit\\":\\"d\\",\\"minAmount'
            '\\":\\"100\\",\\"incrementalAmt\\":\\"100\\",\\"pubTime\\":\\"2018-12-02 16:36:05\\"}"}}\n'
            % debtIdcore,
            'callback':
            'jQuery172024506418937789642_1543739601832\n'
        }
        header1 = {"Content-Type": "application/json"}
        res2 = self.core.get(url3, params=data3, headers=header1)
        print(res2.text)
        print("=====================审核散标并发标========================")
        # 通过债权主键debtIdcore,查询标的的主键bidcore和标的的编号bidNocore
        db = MysqlDB()
        script = "select id,bidNo from qtw_core_db.core_product_scattered where debtId=%s" % debtIdcore
        result = db.select_return_A_data(script)
        self.rwf.update_resourse("resourse", "${bidcore}", str(result[0]))
        self.rwf.update_resourse("resourse", "${bidNocore}", str(result[1]))
        print("债权对应的标的主键", result[0])
        print("标的的编号", result[1])
        # ===============
        url4 = self.coreurlbase + "/rest/standardProd/batchApprovalSubmit"
        print(url4)
        data4 = {
            't':
            '1542696230010\n',
            '_':
            '1542696230011',
            'jsonParams':
            '{"method":"batchApprovalSubmit","params":{"debtIds":%s,"param":"{\\"bidId\\":\\"20000024408\\",\\"approval\\":\\"1\\"}"}}\n'
            % result[0],
            'callback':
            'jQuery17206732644502681546_1542694420296\n'
        }
        res2 = self.core.get(url4, params=data4, headers=header1)
        print(res2.text)
        if "SUCCESS" in res2.text:
            print("核心发标成功")
        else:
            raise Exception("核心发标失败")
        time.sleep(5)

    def corereturnedmoney(self, debtCode, term_num):
        '''
        :param debtCode: 债权
        :param term_num: 回款期数
        :return: 回款
        '''
        db = MysqlDB()
        should_date = db.select_return_A_data(
            'SELECT should_date FROM qtw_loan_db.p2p_borrower_return_plan WHERE debtcode = "%s" AND term_num = %s'
            % (debtCode, term_num))
        should_date = str(should_date[0])
        print("=================跑手工任务给回款第%s期,给出借人,时间%s====================" %
              (term_num, should_date))
        url3 = self.coreurlbase + "/rest/testCrontabJob/testAutoCashBack"
        header1 = {"Content-Type": "application/json"}
        data3 = {
            'jsonParams':
            '{"method":"testAutoCashBack","params":{"cashBackDate":%s,"debtCode":"%s"}}\n'
            % (should_date, debtCode),
            '_':
            '1542807282908',
            'callback':
            'jQuery17204517549754820951_1542806876216\n',
            't':
            '1542807282907\n'
        }
        print(data3)
        rels = self.core.get(url3, params=data3, headers=header1)
        print(rels.text)
        if "SUCCESS" in rels.text:
            print("核心交易执行手工正常回款任务成功")
        else:
            raise Exception("核心交易执行手工正常回款任务失败")
        print("================查询还款状态====================")
        repayStatus = "0"
        for i in range(10):
            time.sleep(15)
            url4 = self.coreurlbase + "/rest/settle/queryDebtRepayPage"
            header1 = {"Content-Type": "application/json"}
            data4 = {
                'callback':
                'jQuery17206316655256710433_1562162797078\n',
                '_':
                '1562162810402',
                't':
                '1562162810402\n',
                'jsonParams':
                '{"method":"queryDebtRepayPage","params":{"page":{"conditions":"{\\"debtCode\\":\\"%s\\"}","pageNum":1,"pageSize":10}}}\n'
                % debtCode
            }
            rels = self.core.get(url4, params=data4, headers=header1)
            # print(rels.text)
            rStatus = self.regular(
                'periodSeq":%s,"planRepayDate(.+?)}' % term_num, rels.text)
            repayStatus = self.regular('repayStatus":"(.+?)"', rStatus)
            print(repayStatus)
            if repayStatus == "10":
                print("回款成功")
                break
        if repayStatus != "10":
            raise Exception("回款失败")

    def financialsave_zx(self, money):
        '''
        :return: 智享服务发标
        '''
        print("第一步:创建智享标")
        url4 = self.coreurlbase + "/rest/financial/save"
        header1 = {"Content-Type": "application/json"}
        data4 = {
            'jsonParams':
            '{"method":"saveFinancial","params":{"param":"{\\"categoryId\\":\\"1000000001\\",\\"expectTol\\":\\"%s\\",\\"startTime\\":\\"2018-11-24 20:02:58\\",\\"endTime\\":\\"2020-11-24 20:03:13\\"}","type":"submit"}}\n'
            % money,
            't':
            '1543061018937\n',
            'callback':
            'jQuery17208713135843824564_1543056651820\n',
            '_':
            '1543061018937'
        }
        res2 = self.core.get(url4, params=data4, headers=header1)
        print(res2.text)
        if "SUCCESS" in res2.text:
            print("核心智享服务标创建成功")
        else:
            raise Exception("核心智享服务标创建失败")

        print("第二步:智享服务标审核通过,发标")
        db = MysqlDB()
        ts = time.strftime("%Y-%m-%d", time.localtime())
        script = "SELECT id,productNo FROM qtw_core_db.core_product_b WHERE insertTime LIKE '%s" % ts + "%' ORDER BY productNo DESC LIMIT 1;"
        result = db.select_return_A_data(script)
        bidcore_zx = str(result[0])  # 智享标的主键
        bidNocore_zx = str(result[1])  # 智享标的编号

        print("智享标的主键%s" % bidcore_zx)
        print("智享标的编号%s" % bidNocore_zx)

        self.rwf.update_resourse("resourse", "${bidcore_zx}", bidcore_zx)
        self.rwf.update_resourse("resourse", "${bidNocore_zx}", bidNocore_zx)

        url5 = self.coreurlbase + "/rest/financial/audit"
        header1 = {"Content-Type": "application/json"}
        data5 = {
            '_':
            '1543061778984',
            'callback':
            'jQuery17208713135843824564_1543056651873\n',
            'jsonParams':
            '{"method":"auditFinancial","params":{"param":"{\\"id\\":\\"%s\\",\\"bidStatus\\":\\"1\\"}"}}\n'
            % bidcore_zx,
            't':
            '1543061778983\n'
        }
        res2 = self.core.get(url5, params=data5, headers=header1)
        print(res2.text)
        if "SUCCESS" in res2.text:
            print("核心智享服务标发标成功")
        else:
            raise Exception("核心智享服务标发标失败")

    def cuohejiesuan_zx(self, debtCode, bidNocore):
        '''
        :param debtCode: 债权编号
        :param bidNocore: 标的编号
        :return: 撮合结算
        '''
        db = MysqlDB()
        script = 'SELECT debtId FROM qtw_core_db.core_loan_debt_info WHERE debtCode = "%s"' % debtCode
        result = db.select_return_A_data(script)
        debtId = str(result[0])
        script = 'SELECT id FROM qtw_core_db.core_loan_unmatch_debt WHERE debtId = "%s"' % debtId
        result = db.select_return_A_data(script)
        undebtId = str(result[0])  # 未匹配所有债权的主键
        print("未匹配所有债权的主键%s" % undebtId)
        # 查询订单的主键
        url3 = self.coreurlbase + "/rest/invest/query"
        header1 = {"Content-Type": "application/json"}
        data3 = {
            '_':
            '1543066226060',
            'callback':
            'jQuery17208713135843824564_1543056652065\n',
            't':
            '1543066226060\n',
            'jsonParams':
            '{"method":"queryOrderList","params":{"page":{"conditions":"{\\"bidNo\\":\\"%s\\"}","pageNum":1,"pageSize":10}}}\n'
            % bidNocore
        }
        res2 = self.core.get(url3, params=data3, headers=header1)
        print(res2.text)
        orderNo = self.regular('"orderNo":"(.+?)"', res2.text, 1)
        script = 'SELECT id FROM qtw_core_db.core_biz_invest_order WHERE orderNo = "%s"' % orderNo
        result = db.select_return_A_data(script)
        orderNo = str(result[0])  # 订单的主键
        print("订单的主键%s" % orderNo)

        print("============撮合,一条债权撮合一条订单")
        url4 = self.coreurlbase + "/rest/unMatchDebt/handMatch"
        header1 = {"Content-Type": "application/json"}
        data4 = {
            'jsonParams':
            '{"method":"handMatch","params":{"id":%s,"orders":[{"orderId":"%s","matchAmt":1000000}]}}\n'
            % (undebtId, orderNo),
            't':
            '1543064261829\n',
            '_':
            '1543064261829',
            'callback':
            'jQuery17208713135843824564_1543056651993\n'
        }
        res2 = self.core.get(url4, params=data4, headers=header1)
        print(res2.text)
        if "SUCCESS" in res2.text:
            print("核心系统撮合成功")
        else:
            raise Exception("核心系统撮合失败")

        print("============结算管理,系统结算=======")
        url4 = self.coreurlbase + "/rest/unMatchDebt/autoSettle"
        header1 = {"Content-Type": "application/json"}
        data4 = {
            '_': '1543067738322',
            'callback': 'jQuery17208713135843824564_1543056652137\n',
            'jsonParams': '{"method":"autoSettle"}\n',
            't': '1543067738322\n'
        }
        res2 = self.core.get(url4, params=data4, headers=header1)
        print(res2.text)
        if "SUCCESS" in res2.text:
            print("核心系统结算成功")
        else:
            raise Exception("核心系统结算失败")

    def regular(self, regex, content, index=1):
        regex = str(regex)
        content = str(content)
        '''
        :param regex: ex,正则表达式,ex,验证码:(.+?),
        :param content: 字符串
        :param index:
        :return: 根据正则表达式的值提取的内容
        '''
        search_result = '0'
        search = re.compile(regex)
        message = search.search(content)
        if message:
            search_result = message.group(index)
        return search_result
コード例 #16
0
class HttpApiLib(BaseObject):
    def regular(self, regex, content, index=1):
        regex = str(regex)
        content = str(content)
        '''
        :param regex: ex,正则表达式,ex,验证码:(.+?),
        :param content: 字符串
        :param index:
        :return: 根据正则表达式的值提取的内容
        '''
        search_result = '0'
        search = re.compile(regex)
        message = search.search(content)
        if message:
            search_result = message.group(index)
        return search_result

    def phone_aes(self, phone):
        '''
        :param phone:
        :return: 加密后的手机号
        '''
        pc = PrpCrypt('hqtw-%s' % phone)  # 初始化密钥
        phone_aes = pc.encrypt("%s" % phone)  # 加密
        return phone_aes

    def password_aes(self, phone, passwoed):
        '''
        :param phone:
        :param passwoed:
        :return: 加密后的密码
        '''
        print(phone, passwoed)
        pc = PrpCrypt('hqtw-%s' % phone)  # 初始化密钥
        password_aes = pc.encrypt("%s" % passwoed)  # 加密
        return password_aes

    def phone_time(self):
        '''
        :return: 生成类手机号字符串
        '''
        pt = str(time.time())
        pt = pt.split(".")
        phone_time = pt[0] + pt[1][0]
        print(phone_time)
        return phone_time

    def createid(self):
        '''
        :return: 按照规则生成的身份证号码
        '''
        CIC = CreateIdCard()
        idcard = CIC.gennerator()
        return idcard

    def update_resourse_orderidzx(self, par1):
        '''
        :return: 更新resourse.txt中${order_id_zx}的值
        '''
        self.rwf = ReadAndWriteFiles()
        self.rwf.update_resourse("resourse", "${order_id_zx}", par1)

    def assert_invest(self):
        print(self.r.text)

    def tesx(self):
        self.tx = 1111
        return self.tx

    def tesy(self):
        print(self.tx)
コード例 #17
0
 def update_resourse_orderidzx(self, par1):
     '''
     :return: 更新resourse.txt中${order_id_zx}的值
     '''
     self.rwf = ReadAndWriteFiles()
     self.rwf.update_resourse("resourse", "${order_id_zx}", par1)
コード例 #18
0
def main(argv):
    try:
        # 初始化方法,检查系统能否正常登录
        # func_init()
        #获取rob参数
        inputfile = ''
        outputfile = ''
        opt_p = ''
        opt_f = ''
        opt_d = ''
        opt_t = ''
        opt_tag = ''
        opt_email = ''
        opt_env = ''
        try:
            opts, args = getopt.getopt(argv, "hi:o:e:m:p:f:d:g:",
                                       ["ifile=", "ofile="])
        except getopt.GetoptError:
            print('获取参数异常')
            sys.exit(2)
        # 获取参数列表包括email,pybot,以及pybot的参数
        for opt, arg in opts:
            if opt == '-h':  # help,显示命令行格式
                print('te.py -i <inputfile> -o <outputfile>')
                sys.exit()
            elif opt in ("-i", "--ifile"):
                inputfile = arg
            elif opt in ("-o", "--ofile"):
                outputfile = arg
            elif opt == "-e":  # 选择环境,可以使用test和auto
                opt_env = arg
            elif opt == "-m":  # 发送邮件,参数必须YES
                opt_email = arg
            elif opt == "-p":  # 选择解释器,可以使用pybot和robot
                opt_p = arg
            elif opt == "-f":  # 测试用例文件的目录
                opt_f = arg
            elif opt == "-d":  # 测试报告的目录
                opt_d = "-d " + arg
            # elif opt == "-t":  # 测试用例文件的目录
            #     opt_t = " -t " + arg
            elif opt == "-g":  # 测试用例tag
                opt_tag = "--include " + arg
            cmd = opt_p + " " + opt_d + " " + opt_tag + " " + opt_f + opt_t
            # 执行一整个项目(或测试用例集)ex,python rob.py -e test -m YES -p pybot -d ../report -f ../qutouwang/App/api  【设置环境】【发送邮件】
            # 执行一整个项目(或测试用例集)下面的某些个用例,ex,python rob.py -e test -p pybot -d ../report -t *2 ../qutouwang/App/api 【按测试用例名称执行】【已废弃】
            # 执行一整个项目,按照标签来执行,ex,python rob.py -e test -p pybot -d ../report -g Level1 -f ../qutouwang/App/api【按标签执行】
            #python rob.py -e test  -p pybot -d ../report -f ../qutouwang/App/api/登录相关  【设置环境
        #设置环境变量
        env = ["test", "auto"]
        if opt_env not in env:
            raise Exception(
                "字段-e 写入的参数值错误,请填写test或auto,test表示在测试环境进行测试,auto表示在自动化环境进行测试")

        rwf = ReadAndWriteFiles()
        rwf.update_resourse("Data", "${data_env}", "data_%senv" % opt_env)
        rwf.ini_write(rwf.pathenv, "environment", "env", opt_env)

        print(cmd)
        os.system(cmd)
        if opt_email == "YES":
            print("发送邮件")
            # 在下面编写发送邮件的功能
            if opt_env == "test":
                send_mail("去投网2.0接口测试—测试环境")
            else:
                send_mail("去投网2.0接口测试—自动化环境")
    except Exception as msg:
        print("错误信息:%s" % msg)