pytest中fixture使用,控制使用域
pytest中使用fixture装饰器是来固定的工厂函数,fixture函数可以在测试执行前和执行后进行必要的准备和清理工作
1. fixture做为函数引用使用
比如以下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import pytest # fixture作为函数引用 @pytest .fixture() def before(): print ( "before执行啦。。。" ) #@pytest.mark.usefixtures("before") #在每个方法前运行 class Test_b(): def setup( self ): print ( "setup...." ) def test_a( self ): print ( "test a" ) def test_b( self ): print ( "test b" ) |
注释掉 pytest.mark.usefixtures("before") 执行效果
开启 pytest.mark.usefixtures("before") 执行效果
每个运行方法前都会打印before函数的内容
1.1设置自动执行
在before中设置自动执行,不用在每个类中进行执行,
@pytest.fixture(autouse=True)
def before():
print("before执行啦。。。")
class Test_b():
def setup(self):
print("setup....")
def test_a(self):
print("test a")
def test_b(self):
print("test b")
执行效果是如上图
2.做为函数使用
1 2 3 4 5 6 7 8 | @pytest .fixture def param_numbenr(): return 5 def test_cacult(param_numbenr): print (param_numbenr) assert 5 = = param_numbenr |
3.设置作用域为function
作用域:每个函数、类中的每个方法都运行一次
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | @pytest .fixture(scope = "function" ,autouse = True ) def before(): print ( "before执行啦。。。" ) class Test_b(): def setup( self ): print ( "setup...." ) def test_a( self ): print ( "test a" ) def test_b( self ): print ( "test b" ) class Test_c(): def test_c( self ): print ( "test c" ) |
4.设置作用域为class
一个类只运行一次
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | @pytest .fixture(scope = "class" ,autouse = True ) def before(): print ( "before执行啦。。。" ) class Test_b(): def setup( self ): print ( "setup...." ) def test_a( self ): print ( "test a" ) def test_b( self ): print ( "test b" ) class Test_c(): def test_c( self ): print ( "test c" ) |
5.设置作用域module
作用域:作用于整个模块,每个module的所有test只运行一次
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | @pytest .fixture(scope = "module" ,autouse = True ) def before(): print ( "before执行啦。。。" ) class Test_b(): def setup( self ): print ( "setup...." ) def test_a( self ): print ( "test a" ) def test_b( self ): print ( "test b" ) class Test_c(): def test_c( self ): print ( "test c" ) |
6.设置作用域session
作用于整个session,每个session只运行一次,比如以下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | @pytest .fixture(scope = "session" ,autouse = True ) def before(): print ( "before执行啦。。。" ) class Test_b(): def setup( self ): print ( "setup...." ) def test_a( self ): print ( "test a" ) def test_b( self ): print ( "test b" ) class Test_c(): def test_c( self ): print ( "test c" ) |
7.设置参数
1 2 3 4 5 6 7 8 9 10 | @pytest .fixture(params = [ 1 , 2 , 3 ]) #固定用法 def param_numbenr(request): return request.param #固定用法 def test_a(param_numbenr): print (param_numbenr) def test_b (param_numbenr): print (param_numbenr) |
作者:做梦的人(小姐姐) 出处:https://www.cnblogs.com/chongyou/ 本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。 如果文中有什么错误,欢迎指出。以免更多的人被误导。 微信号:18582559217 |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步