自动化测试中-装饰器的引用实例

1、你是否经常需要统计一个函数的运行时间,姿势可以这样

import time
# 统计程序运行时间装饰器
def timer(func):
    def wrapper(*args, **kw):
        start_time = time.time()
        # 这是函数真正执行的地方
        func(*args, **kw)
        end_time = time.time()
        t = end_time - start_time
        print("花费时间:{}秒".format(t))
        return t
    return wrapper

2、你是否经常需要查询数据库中某个表的的字段是否状态等于某个值,然后才能走后续流程,比如还款订单状态,一般需要订单状态校验通过,然后才可以进行后续的还款,因此我们需要去查询数据库,但是运气不一定那么好,正好查一次就是符合预期结果,因此需要多次重试,这样的问题也可以借助装饰器来解决

import pymysql,random
from retrying import retry
@retry(stop_max_attempt_number=3,wait_fixed = 10000)  #引用了装饰器,最大尝试次数为3次,每次间隔时间为10s
def query_repayment_order():
    # 打开数据库连接,不需要指定数据库,因为需要创建数据库
    conn = pymysql.connect('localhost', user="root", passwd="123456",db = "dtest_post_loan")
    # 获取游标
    cursor = conn.cursor()
    # 创建pythonBD数据库
    result=cursor.execute("SELECT * FROM repayment_order where order_uuid='9e958b6315944a5f841d754b2d4a1e41' and order_check_status=1")
    if result!=1:   #order_check_status=1 是订单状态校验通过的意思order_check_status=0 是待校验的意思
        raise Exception('your current repayment_order\'s order_check_status !=1 ')
    cursor.close()  # 先关闭游标
    conn.close()  # 再关闭数据库连接
#a=query_repayment_order()
#print(a)

3、你的接口是否经常遇见依赖访问第三方接口,比如银行查询账户流水,但是第三方接口未必是稳定的,

@retry(stop_max_attempt_number=3,wait_fixed = 10000)  #引用了装饰器,最大尝试次数为3次,每次间隔时间为10s
def query_account_balance(productCode,accountNo):
    url= "http://guangda.net/fn/api/query"
    headers={"request-source":"127.0.0.1"}
    data = {"productCode": productCode, "accountNo": accountNo}
    p=os.popen("ping guangda.net")
    x = p.read()
    print(x.count)
    p.close()
    if  x.count('timeout'):
        print("ping不通")
    else:
     rp=requests.post(url,data=json.dumps(data),headers=headers)
     print(rp.text)
query_account_balance("guangdaPPD","11005749366303")
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值