示例#1
0
def testInterface():
    list_pass = 0
    list_fail = 0
    list_json = []
    listresult = []
    list_unkown = []
    list_exception = []
    for i in range(len(listurl)):
        api = TestHttpAPI(url=listurl[i],key=listkey[i],params=listparams[i],method=listmethod[i])
        apijson = api.getjson()
        if apijson['code']==0:
            LOG.info('inputdata>参数:%s,url:%s,返回:%s,预期:%s'%(listparams[i],listurl[i],apijson,listexpect[i]))
            assert_re = assert_in(assert_expect=listexpect[i],response_json=apijson)
            if assert_re['code']==0:
                list_json.append(apijson['result'])
                listresult.append('pass')
                list_pass +=1
            elif assert_re['code']==1:
                list_fail +=1
                listresult.append('fail')
                list_json.append(apijson['result'])
            elif assert_re['code']==2:
                list_exception +=1
                listresult.append('exception')
                list_json.append(assert_re['result'])
            else:
                list_unkown +=1
                listresult.append('unkown')
                list_json.append(assert_re['unkown'])
        else:
            list_exception +=1
            listresult.append('exception')
            list_json.append(apijson['result'])
            continue
    return listresult,list_fail,list_pass,list_exception,list_unkown
示例#2
0
 def activation_code(self, code):
     data = {"code": code}
     url = self.host + 'owner/user/' + str(
         Util().get_user_id()) + '/activation_code'
     LOG.info("请求url:%s" % url)
     req = requests.post(url=url, json=data, headers=Util().get_token())
     return req.json()
示例#3
0
 def user_device(self):
     data = {}
     url = self.host + "user/" + str(Util().get_user_id()) + "/device"
     LOG.info("请求url:%s" % url)
     LOG.info("请求参数:%s" % data)
     req = requests.get(url=url, data=data, headers=Util().get_token())
     return req.json()
示例#4
0
    def contruct_transaction(self,
                             invoker,
                             contract,
                             method,
                             args,
                             key,
                             gwei_coef=None,
                             gasLimit=4500000):
        """"""
        try:
            # pre-check the transaction
            estimate_gas = contract.functions[method](*args).estimateGas(
                {'from': checksum_encode(invoker)})
            gasLimit = estimate_gas + 5000 + randint(1, 10000)
        except Exception as error:
            LOG.debug('Failed to execute {}. Exception: {}'.format(
                method, error))
            LOG.info('the parameters are : {}'.format(args))
        finally:
            LOG.debug('Estimated to spend {} gas'.format(gasLimit))
            tx_dict = contract.functions[method](*args).buildTransaction({
                'gas':
                gasLimit,
                'gasPrice':
                pow(10, 9) * gwei_coef,
                'nonce':
                self.web3.eth.getTransactionCount(checksum_encode(invoker)),
            })
            signed = self.web3.eth.account.signTransaction(tx_dict, key)
            tx_id = self.web3.eth.sendRawTransaction(signed.rawTransaction)

            return binascii.hexlify(tx_id).decode()
示例#5
0
def getxls(xlsname):

    try:
        filepath = '.\\test_case\\' + xlsname + ".xlsx"
        file = xlrd.open_workbook(filepath)
        me = file.sheets()[0]
        # me = file.sheet_by_name('login')
        nrows = me.nrows
        listname = []
        listfangshi = []
        listUsername = []
        listpassword = []
        listqiwang = []
        listmsg = []
        for i in range(1, nrows):
            listname.append(me.cell(i, 0).value)
            listfangshi.append(me.cell(i, 1).value)
            listUsername.append(me.cell(i, 2).value)
            pw = str(me.cell(i, 3).value)
            listpassword.append(hashlib.md5(
                pw.encode("utf-8")).hexdigest())  #md5加密
            listqiwang.append(me.cell(i, 4).value)
            listmsg.append(me.cell(i, 5).value)
        return listname, listfangshi, listUsername, listpassword, listqiwang, listmsg
    except:
        LOG.info('打开测试用例失败,原因是:%s' % Exception)
        print(Exception)
示例#6
0
def datacel():
    # filepath = '..\\test_case\\case.xlsx'#路径问题
    # file = xlrd.open_workbook(filepath)
    try:
        filepath = '.\\test_case\\case.xlsx'
        file = xlrd.open_workbook(filepath)
        me = file.sheets()[2]
        nrows = me.nrows
        listid = []
        listToken = []
        listconeent = []
        listurl = []
        listfangshi = []
        listqiwang = []
        # listrelut=[]
        listname = []
        for i in range(1, nrows):
            listid.append(me.cell(i, 0).value)
            listToken.append(me.cell(i, 2).value)
            # xx = me.cell(i, 3).value
            # print(xx)
            # if xx != '':
            #     listconeent.append(eval(xx))
            # else:
            #     listconeent.append(None)
            # listconeent.append(json.load(me.cell(i,3).value))
            listconeent.append(me.cell(i, 3).value)
            listurl.append(me.cell(i, 4).value)
            listname.append(me.cell(i, 1).value)
            listfangshi.append((me.cell(i, 5).value))
            listqiwang.append((me.cell(i, 6).value))
        return listid, listToken, listconeent, listurl, listfangshi, listqiwang, listname
    except:
        LOG.info('打开测试用例失败,原因是:%s' % Exception)
        print(Exception)
示例#7
0
def getdataByName(xlsname, sheet):
    try:
        filepath = '.\\test_case\\' + xlsname + ".xlsx"
        file = xlrd.open_workbook(filepath)
        me = file.sheets()[sheet - 1]
        nrows = me.nrows
        # listname = []
        # listmethod = []
        # listparams = []
        # listcode = []
        # listmsg = []
        get_data = []
        for i in range(1, nrows):
            get_data.append({
                "casename": me.cell(i, 0).value,
                "method": me.cell(i, 1).value,
                "params": me.cell(i, 2).value,
                "code": int(me.cell(i, 3).value),
                "msg": me.cell(i, 4).value
            })
            i += 1
            # listname.append(me.cell(i,0).value)
            # listmethod.append(me.cell(i,1).value)
            # listparams.append(me.cell(i,2).value)
            # listcode.append(me.cell(i,3).value)
            # listmsg.append(me.cell(i,4).value)
        return get_data
    except:
        LOG.info('打开测试用例失败,原因是:%s' % Exception)
        print(Exception)
示例#8
0
 def get_organizations(self):
     data = {}
     # url = self.host + 'owner/organizations'
     url = urljoin(self.host, 'owner/organizations')
     LOG.info("请求url:%s" % url)
     res = requests.get(url=url, json=data, headers=Util().get_token())
     return res.json()
示例#9
0
 def test_user_password_old(self):
     u"""恢复成原始密码"""
     data = {
         "sign_in_method": 'username_password',
         "username": '******',
         "hashed_password":
         '******',
         "seed": 'a123'
     }
     url = urljoin(self.host, 'signin')
     result = requests.post(url=url,
                            json=data,
                            headers=Util().get_authorization())
     req = result.json()['data']['user_id']
     data_pwd = {
         "old_hashed_password":
         '******',
         "new_plain_password": '******',
         "seed": 'a123'
     }
     url_pwd = self.host + 'user/' + str(req) + '/password'
     LOG.info("请求url:%s" % url)
     res = requests.put(url=url_pwd,
                        json=data_pwd,
                        headers=Util().get_token())
     LOG.info("获取测试结果:%s" % res.json())
示例#10
0
    def notify_rcode_to_next_peer(self, next_channel):
        """

        :param next_channel:
        :return:
        """
        peer = None
        try:
            # original payer is found
            if not next_channel:
                LOG.info('HTLC Founder with HashR<{}> received the R-code<{}>'.
                         format(self.hashcode, self.rcode))
                return

            htlc_trade = self.get_htlc_trade_by_hashr(next_channel,
                                                      self.hashcode)
            if next_channel != htlc_trade.channel:
                LOG.error('Why the channel is different. next_channel<{}>, stored channel<{}>' \
                          .format(next_channel, htlc_trade.channel))

            # notify the previous node the R-code
            LOG.debug('Payment get channel {}/{}'.format(
                next_channel, self.hashcode))
            channel = Channel(next_channel)
            peer = channel.peer_uri(self.wallet.url)
            nonce = channel.latest_nonce(next_channel)
            LOG.info("Next peer: {}".format(peer))
            self.create(next_channel, self.asset_type, nonce, self.wallet.url,
                        peer, self.hashcode, self.rcode, self.comments)
        except Exception as error:
            LOG.error('Failed to notify RCode<{}> to peer<{}>'.format(
                self.rcode, peer))
示例#11
0
 def sign_out(self):
     data = {}
     url = urljoin(self.host, 'user/signout')
     LOG.info("请求url:%s" % url)
     LOG.info("请求参数:%s" % data)
     res = requests.post(url=url, json=data, headers=Util().get_token())
     return res.json()
示例#12
0
 def put_profile(self, nickname, birthday, gender, height, weight, phone, email, remark, user_defined_code,
                 state, city, street, country):
     data = {
         "profile":
             {
                 "nickname": nickname,
                 "birthday": birthday,
                 "gender": gender,
                 "height": height,
                 "weight": weight,
                 "phone": phone,
                 "email": email,
                 "remark": remark,
                 "user_defined_code": user_defined_code,
                 "state": state,
                 "city": city,
                 "street": street,
                 "country": country
             }
     }
     url = self.host + 'owner/users/' + str(Util().get_user_id()) + '/profile'
     LOG.info("请求url:%s" % url)
     res = requests.put(url=url, json=data, headers=Util().get_token())
     LOG.info("请求参数:%s" % data)
     return res.json()
    def prepare(self, block_height, address='', deposit=0.0, key=''):
        super(ChannelDepositEvent, self).prepare(block_height)

        # if this transaction id is approved, it means successful by eth block chain
        if self.approved_tx_id:
            checked = self.check_transaction_success(self.approved_tx_id)
            if checked:
                LOG.debug('Approved asset by address<{}:{}>'.format(address, deposit))
                Channel.update_channel(self.channel_name, state=EnumChannelState.OPENING.name)
                LOG.info('Start to create channel<{}>. State: OPENING.'.format(self.channel_name))
                console_log.info('Channel<{}> is opening'.format(self.channel_name))
                # go to next stage
                self.next_stage()
                return True
            elif checked is False:
                return False
            else:
                # new transaction is pushed to chain
                self.approved_tx_id = None
        else:
            approved_deposit = self.contract_event_api.get_approved_asset(address)
            if approved_deposit >= int(deposit):
                LOG.debug('Has already approved: {}'.format(approved_deposit))
                # go to next stage
                self.next_stage()
                return True
            
        # make transaction to chain
        result = self.contract_event_api.approve(address, int(deposit), key, gwei_coef=self.gwei_coef)
        if result:
            self.approved_tx_id = '0x'+result.strip()

        return False
示例#14
0
 def resource(self):
     data = {}
     url = urljoin(self.host, "resource")
     LOG.info("请求url:%s" % url)
     req = requests.get(url=url, data=data)
     LOG.info(req.json())
     return req.json()
示例#15
0
 def test_user_questions_error_paramters(self):
     u"""只有两上密保问题"""
     LOG.info('------设置/修改密保:start!---------')
     data = {
         "old_secure_questions": [{
             "question_key": 1,
             "answer": "a"
         }, {
             "question_key": 3,
             "answer": "a"
         }],
         "new_secure_questions": [{
             "question_key": 1,
             "answer": "b"
         }, {
             "question_key": 2,
             "answer": "a"
         }]
     }
     url = self.host + "user/" + str(
         Util().get_user_id()) + "/modify_secure_question"
     LOG.info("请求url:%s" % url)
     LOG.info("请求参数:%s" % data)
     result = requests.post(url=url,
                            data=json.dumps(data),
                            headers=Util().get_token())
     LOG.info("请求参数:%s" % result.json())
     self.assertErrorResult(result.json(), const.ErrParsingRequestFailed)
     LOG.info('------pass!---------')
示例#16
0
 def user_language(self):
     data = {}
     url = self.host + "user/" + str(Util().get_user_id()) + "/language"
     LOG.info("请求url:%s" % url)
     LOG.info("请求参数:%s" % data)
     res = requests.get(url=url, json=data, headers=Util().get_token())
     return res.json()
示例#17
0
 def signup(self, client_id, password, register_type, nickname, birthday, gender, height, weight, phone, email,
            remark, user_defined_code, state, city, street, country):
     data = {
         "client_id": client_id,
         "password": password,
         "register_type": register_type,
         "profile":
             {
                 "nickname": nickname,
                 "birthday": birthday,
                 "gender": gender,
                 "height": height,
                 "weight": weight,
                 "phone": phone,
                 "email": email,
                 "remark": remark,
                 "user_defined_code": user_defined_code,
                 "state": state,
                 "city": city,
                 "street": street,
                 "country": country
             }
     }
     # url = self.host + "owner/users/signup"
     url = urljoin(self.host, 'owner/users/signup')
     LOG.info("请求url:%s" % url)
     print(url)
     res = requests.post(url=url, json=data, headers=Util().get_token())
     LOG.info("请求参数:%s" % data)
     return res.json()
示例#18
0
    def run_testsuite(self, job_id):
        """
        run test
        :return:
        """
        try:
            suit = self.load_testsuite()
            if suit is not None:
                # LOG.info("********TEST START********")
                now = time.strftime("%Y_%m_%d_%H_%M_%S")
                result_path = os.path.join(CUR_DIR, "report")
                if not os.path.exists(result_path):
                    os.mkdir(result_path)

                if job_id == '':
                    report_abspath = os.path.join(result_path,
                                                  now + "_result.html")
                else:
                    report_abspath = os.path.join(result_path,
                                                  job_id + "_result.html")
                print("report path:%s" % report_abspath)
                report = open(report_abspath, "wb")
                runner = Htmlrunner(stream=report,
                                    title=u'自动化测试报告,测试结果如下:',
                                    description=u'用例执行情况:')

                runner.run(suit)
            else:
                LOG.info("Have no case to test.")
        except Exception as ex:
            LOG.error(str(ex))
示例#19
0
def setup_events():
    if FILE_PATH is not None:
        logger.info("Event Definitions configuration file: %s"
                    % FILE_PATH.split('/')[-1])

        with open(FILE_PATH) as cf:
            config = cf.read()
        try:
            events_config = yaml.safe_load(config)
        except yaml.YAMLError as err:
            if hasattr(err, 'problem_mark'):
                mark = err.problem_mark
                errmsg = ("Invalid YAML syntax in Event Definitions file "
                          "%(file)s at line: %(line)s, column: %(column)s."
                          % dict(file=FILE_PATH.split('/')[-1],
                                 line=mark.line + 1,
                                 column=mark.column + 1))
            else:
                errmsg = ("YAML error reading Event Definitions file: %s"
                          % FILE_PATH.split('/')[-1])
            logger.error(errmsg)
            raise
        else:
            return EventConverter(events_config)
    else:
        logger.error("No Event Definitions configuration file found!")
示例#20
0
 def user_subscription(self):
     data = {}
     url = self.host + "user/" + str(Util().get_user_id()) + "/preferences"
     LOG.info("请求url:%s" % url)
     LOG.info("请求参数:%s" % data)
     req = requests.get(url=url, data=data, headers=Util().get_token())
     return req.json()
示例#21
0
    def __init__(self):

        self.caseListFile = os.path.join(CUR_DIR, "caselist")
        LOG.info(self.caseListFile)
        self.caseFile = os.path.join(CUR_DIR, "testCase")
        # self.caseFile = None
        self.caseList = []
示例#22
0
 def username(self, username):
     data = {"username": username}
     url = self.host + 'user/' + str(Util().get_user_id()) + '/username'
     LOG.info("请求url:%s" % url)
     res = requests.post(url=url, json=data, headers=Util().get_token())
     LOG.info("请求参数:%s" % data)
     return res.json()
示例#23
0
 def secure_question_to_modify(self):
     data = {}
     url = self.host + "user/" + str(
         Util().get_user_id()) + "/secure_question_to_modify"
     LOG.info("请求url:%s" % url)
     req = requests.get(url=url, json=data, headers=Util().get_token())
     return req.json()
示例#24
0
 def user_region(self, user_id, region):
     data = {"user_id": user_id, "region": region}
     url = self.host + 'user/region'
     LOG.info("请求url:%s" % url)
     res = requests.post(url=url, json=data, headers=Util().get_token())
     LOG.info("请求参数:%s" % data)
     return res.json()
示例#25
0
 def modify_password_via_question(self, validation_type, username, phone, nation_code, password, question_key1,
                                  answer1,
                                  question_key2, answer2, question_key3, answer3):
     data = {
         "validation_type": validation_type,
         "username": username,
         "phone": phone,
         "nation_code": nation_code,
         "password": password,
         "secure_questions": [
             {
                 "question_key": question_key1,
                 "answer": answer1
             },
             {
                 "question_key": question_key2,
                 "answer": answer2
             },
             {
                 "question_key": question_key3,
                 "answer": answer3
             }
         ]
     }
     url = self.host + "user/modify_password_via_question"
     LOG.info("请求url:%s" % url)
     LOG.info("请求参数:%s" % data)
     req = requests.post(url=url, json=data, headers=Util().get_authorization())
     return req.json()
示例#26
0
 def get_profile(self):
     data = {}
     url = self.host + 'user/' + str(Util().get_user_id()) + '/profile'
     LOG.info("请求url:%s" % url)
     res = requests.get(url=url, json=data, headers=Util().get_token())
     LOG.info("请求参数:%s" % data)
     return res.json()
    def _set_up(self):
        # TODO: Create test project and test user, now can use fiptest
        # that already be created before

        self.pets = []
        # Get all compute nodes
        compute_services = \
            self.novac.services.list(binary='nova-compute')
        for srv in compute_services:
            LOG.info('compute service: %s', srv.__dict__)
            if srv.status == 'disabled' or \
                    srv.state == 'down':
                LOG.info('host %s not ok for boot vm', srv.host)
                continue
            cmp = srv.host

            vm_name = 'ckpet-' + ''.join(random.sample(
                string.ascii_letters + string.digits, 8
            ))
            flavor = CONF.get('DEFAULT', 'flavor')
            image = CONF.get('DEFAULT', 'image')
            nics = [{'net-id':  CONF.get('DEFAULT', 'network')}]
            availability_zone = ':' + cmp + ':'
            vm = self.novac.servers.create(
                name=vm_name,
                flavor=flavor,
                image=image,
                nics=nics,
                availability_zone=availability_zone
            )

            # Wait for vm OK
            vm_ip = None
            vm_uuid = None
            while True:
                vm_info = self.novac.servers.get(vm.id)
                if vm_info.status != 'ACTIVE' and vm_info.status != 'ERROR':
                    time.sleep(3)
                elif vm_info.status == 'ERROR':
                    LOG.info('vm %s %s on %s is ERROR', vm.id, vm_name, cmp)
                    break
                else:
                    LOG.info('vm %s %s is ACTIVE', vm.id, vm_name)
                    vm_uuid = vm.id
                    for key, value in vm_info.addresses.items():
                        for add_id in iter(value):
                            if add_id.get('OS-EXT-IPS:type') == 'fixed':
                                vm_ip = add_id.get('addr')
                                break
                    self.pets.append(CheckPet(cmp, ip=vm_ip, uuid=vm_uuid))
                    break

        index = 0
        with open('iplist', 'a+') as f:
            for pt in self.pets:
                LOG.info("%s: vm %s %s on %s", index, pt.vm_uuid,
                         pt.vm_ip, pt.cmp_node)
                f.write(pt.vm_ip)
                index += 1
示例#28
0
 def version(self):
     data = {}
     # url = self.host + "/version"
     url = urljoin(self.host, "version")
     LOG.info("请求url:%s" % url)
     req = requests.get(url=url, data=data)
     # LOG.info(req.json())
     return req.json()
示例#29
0
 def users(self, user_id_list):
     data = {"user_id_list": [user_id_list]}
     url = self.host + 'owner/organizations/' + Util().get_organization_id(
     ) + '/users'
     LOG.info("请求url:%s" % url)
     res = requests.get(url=url, json=data, headers=Util().get_token())
     LOG.info("请求参数:%s" % data)
     return res.json()
示例#30
0
 def deletemeasurements(self, record_id_list):
     data = {"record_id_list": record_id_list}
     url = self.host + 'user/measurements/' + str(
         Util().get_user_id()) + '/delete'
     LOG.info("请求url:%s" % url)
     LOG.info("请求参数:%s" % data)
     res = requests.post(url=url, json=data, headers=Util().get_token())
     return res.json()