目录
一、背景:
二、闭包与装饰器(可以跳过这一章)
2.1 、什么是闭包
2.2 闭包的用途
2.3 、装饰器(decorator)
三、pytest自定义注解@author
3.1 自定义注解@author
3.2 运行case时获取注解@author内容
一、背景:
pytest框架二次开发之机器人报警_傲娇的喵酱的博客-CSDN博客_基于pytest二次开发
在上一章,完成了机器人报警,但是当时报警信息没有获取对应case的作者信息。
本次的功能就是通过自定义注解@author获取对应报错case的作者,然后将信息发送出去。
我们是通过装饰器来实现的。
二、闭包与装饰器(可以跳过这一章)
想要写装饰器,需要了解一下闭包。
2.1 、什么是闭包
python中的闭包从表现形式上定义(解释)为:
如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure).
python中函数名是一个特殊的变量,它可以作为另一个函数的返回值,而闭包就是一个函数返回另一个函数后,其内部的局部变量还被另一个函数引用。
闭包的作用就是让一个变量能够常驻内存。
def func(name): # 定义外层函数
def inner_func(age): # 内层函数
print('name: ', name, ', age: ', age)
return inner_func # 注意此处要返回,才能体现闭包
if __name__ == '__main__':
bb = func('jayson') # 将字符串传给func函数,返回inner_func并赋值给变量
bb(28) # 通过变量调用func函数,传入参数,从而完成闭包
打印结果:
name: jayson , age: 28
2.2 闭包的用途
两个用处:① 可以读取函数内部的变量,②让这些变量的值始终保持在内存中。
②让函数内部的局部变量始终保持在内存中:
怎么来理解这句话呢?一般来说,函数内部的局部变量在这个函数运行完以后,就会被Python的垃圾回收机制从内存中清除掉。如果我们希望这个局部变量能够长久的保存在内存中,那么就可以用闭包来实现这个功能。
这里借用
@千山飞雪
的例子(来自于:千山飞雪:深入浅出python闭包)。请看下面的代码。
以一个类似棋盘游戏的例子来说明。假设棋盘大小为50*50,左上角为坐标系原点(0,0),我需要一个函数,接收2个参数,分别为方向(direction),步长(step),该函数控制棋子的运动。 这里需要说明的是,每次运动的起点都是上次运动结束的终点。
def create(pos=[0,0]):
def go(direction, step):
new_x = pos[0]+direction[0]*step
new_y = pos[1]+direction[1]*step
pos[0] = new_x
pos[1] = new_y
return pos
return go
player = create()
print(player([1,0],10))
print(player([0,1],20))
print(player([-1,0],10))
在这段代码中,player实际上就是闭包go函数的一个实例对象。
它一共运行了三次,第一次是沿X轴前进了10来到[10,0],第二次是沿Y轴前进了20来到 [10, 20],,第三次是反方向沿X轴退了10来到[0, 20]。
这证明了,函数create中的局部变量pos一直保存在内存中,并没有在create调用后被自动清除。
为什么会这样呢?原因就在于create是go的父函数,而go被赋给了一个全局变量,这导致go始终在内存中,而go的存在依赖于create,因此create也始终在内存中,不会在调用结束后,被垃圾回收机制(garbage collection)回收。
这个时候,闭包使得函数的实例对象的内部变量,变得很像一个类的实例对象的属性,可以一直保存在内存中,并不断的对其进行运算。
2.3 、装饰器(decorator)
装饰器就是为了不修改原函数的定义,并使原函数在运行时动态增加功能的方式,一般来说装饰器是一个返回函数的高阶函数。
简单地说:他们是修改其他函数的功能的函数。
装饰器让你在一个函数的前后去执行代码。
def hi(name="yasoob"):
def greet():
return "now you are in the greet() function"
def welcome():
return "now you are in the welcome() function"
if name == "yasoob":
return greet
else:
return welcome
a = hi()
print(a)
#outputs: <function greet at 0x7f2143c01500>
#上面清晰地展示了`a`现在指向到hi()函数中的greet()函数
#现在试试这个
print(a())
#outputs: now you are in the greet() function
在 if/else 语句中我们返回 greet 和 welcome,而不是 greet() 和 welcome()。
当你把一对小括号放在函数后面,这个函数就会执行;然而如果你不放括号在它后面,那它可以被到处传递,并且可以赋值给别的变量而不去执行它。
蓝本规范:
from functools import wraps
def decorator_name(f):
@wraps(f)
def decorated(*args, **kwargs):
if not can_run:
return "Function will not run"
return f(*args, **kwargs)
return decorated
@decorator_name
def func():
return("Function is running")
can_run = True
print(func())
# Output: Function is running
can_run = False
print(func())
# Output: Function will not run
1、将被装饰的函数,作为一个变量,传入了装饰函数里
2、装饰函数,只有一个传参,那就是被装饰的函数
3、开始执行最外层return的这个函数,里面的变量就是被装饰的函数(传进来的函数)
其实有用的代码就这一块,其他乱七八糟的都要忽略掉,里面的那个变量,就是被传入的函数
三、pytest自定义注解@author
3.1 自定义注解@author
# -*- coding:utf-8 -*-
# @Author: 喵酱
# @time: 2022 - 09 -19
# @File: custom_annotations.py
# 自定义注解
# 基类注解
def base(annotation):
def decorator_annos(*args, **kwargs):
# print(args,kwargs)
def decorator(fn):
sub_annos_name = annotation.__name__
if fn.__annotations__.get(sub_annos_name) is None:
# 以子类注解名作为key生成一个字典,用于区分注解
fn.__annotations__[sub_annos_name] = {}
# 放钩子,调用子类注解
annotation(fn, *args, **kwargs)
return fn
return decorator
return decorator_annos
@base
def author(fn, *args, **kwds):
if args != None and len(args) != 0:
if len(args) > 1:
raise RuntimeError("nums of @author parameter can only be one! eg. @author('功能A')")
fn.__annotations__["author"]["value"] = args[0]
elif len(kwds) != 1 or (not kwds.keys().__contains__("value")):
raise RuntimeError("If the form of @author parameter is k,v \
, then key can only be 'value' str! eg. @author(value='功能A')")
else:
for k, v in kwds.items():
fn.__annotations__["author"][k] = v
然后在case上使用注解@author
import pytest
from common.custom_annotations import author
def setup_function():
# print(u"setup_function:每个用例开始前都会执行")
pass
def teardown_function():
pass
# print(u"teardown_function:每个用例结束后都会执行")
def test_01():
""" 用例描述:用例1"""
print("用例1-------")
assert 1 == 1
@author("chenshuai")
def test_02():
""" 用例描述:用例2"""
print("用例2------")
assert 1 == 2
@author("zhangsan")
def test_03():
""" 用例描述:用例3"""
print("用例1-------")
assert 1 == 3
def test_04():
""" 用例描述:用例4"""
print("用例4------")
assert 1 == 2
def test_05():
""" 用例描述:用例5"""
print("用例5-------")
assert 1 == 1
def test_06():
""" 用例描述:用例6"""
print("用例6------")
assert 1 == 1
def test_07():
""" 用例描述:用例7"""
print("用例7-------")
assert 1 == 1
def test_08():
""" 用例描述:用例8"""
print("用例8------")
assert 1 == 1
if __name__ == '__main__':
pytest.main(["-s"])
3.2 运行case时获取注解@author内容
也是通过pytest hook函数实现的。
在conftest.py文件中,pytest_runtest_makereport 方法下,获取注解。
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call)-> Optional[TestReport]:
print('-------------------------------')
# 获取常规的钩子方法的调用结果,返回一个result对象
out = yield
# '用例的执行结果', out
# 获取调用结果的测试报告,返回一个report对象,report对象的属性
# 包括when(setup, call, teardown三个值)、nodeid(测试用例的名字)、
# outcome(用例执行的结果 passed, failed)
report = out.get_result()
# 只关注用例本身结果
if report.when == "call":
num = gol.get_value("total")
gol.set_value("total",num+1)
if report.outcome != "passed":
annos = item.function.__annotations__
if "author" in annos:
author = annos["author"]["value"]
else:
author = "未设置作者"
failnum = gol.get_value("fail_num")
gol.set_value("fail_num", failnum + 1)
single_fail_content = "{}.报错case名称:{},作者:{},{},失败原因:{}".format(gol.get_value("fail_num"), report.nodeid,
author,
str(item.function.__doc__),report.longrepr)
list_content:list = gol.get_value("fail_content")
list_content.append(single_fail_content)
@pytest.fixture(scope="session", autouse=True)
def fix_a():
gol._init()
gol.set_value("total",0)
gol.set_value("fail_num", 0)
# 失败内容
gol.set_value("fail_content", [])
yield
# 执行case总数
all_num = str(gol.get_value("total"))
# 失败case总数:
fail_num = str(gol.get_value("fail_num"))
if int(gol.get_value("fail_num")):
list_content: list = gol.get_value("fail_content")
final_alarm_content = "项目名称:{},\n执行case总数:{},失败case总数:{},\n详情:{}".format("陈帅的测试项目", all_num, fail_num,
str(list_content))
print(final_alarm_content )
AlarmUtils.default_alram(final_alarm_content, ['187xxxx'])