Pytest学习之fixture作用范围(scope)

'''
fixture作用范围
fixture里面有个scope参数可以控制fixture的作用范围:session > module > class > function
- function 每一个函数或方法都会调用
- class  每一个类调用一次,一个类可以有多个方法
- module,每一个.py文件调用一次,该文件内又有多个function和class
- session 是多个文件调用一次,可以跨.py文件调用,每个.py文件就是module
'''

import pytest

'scope为function级别'
@pytest.fixture()
def first():
print(" 获取用户名")
a="nuo"
return a
@pytest.fixture(scope="function")
def second():
print(" 获取密码")
b="123455"
return b

def test_1(first):
'''用例传fixture'''
print("测试账号:%s"%first)
assert first=="nuo"

def test_2(second):
'''用例传fixture'''
print("测试密码:%s"%second)
assert second=="123455"

if __name__ == '__main__':
pytest.main(["-s","fixtureandscope.py"])


'fixture放到类里'
@pytest.fixture()
def first():
print(" 获取用户名")
a ="nuo"
return a

@pytest.fixture(scope="function")
def second():
print(" 获取密码")
b="123456"
return b

class TestCase():
def test_1(self,first):
'''用例传fixture'''
print("测试账号:%s"%first)
assert first =="nuo"
def test_2(self,second):
'''用例传fixture'''
print("测试密码:%s"%second)
assert second=="123456"

if __name__ == '__main__':
pytest.main(["-s","fixtureandscope.py"])


'scope=class'
'fixture为class级别的时候,如果一个class里面有多个用例,都调用了此fixture,那么此fixture只在该class里所有用例开始前执行一次'

@pytest.fixture(scope="class")
def first():
print(" 获取用户名,scope为class级别只运行一次")
a="nuo"
return a

class TestCase():
def test_1(self,first):
'用例传fixture'
print("测试账号:%s"%first)
assert first == "nuo"

def test_2(self,first):
'用例传fixture'
print("测试账号:%s"%first)
assert first == "nuo"

if __name__ == '__main__':
pytest.main(["-s","fixtureandscope.py"])


'scope=module'
'''fixture为module级别时在当前.py脚本里面所有用例开始前只执行一次'''
@pytest.fixture(scope="module")
def first():
print(" 获取用户名,scope为module级别当前.py模块只运行一次")
a = "yoyo"
return a

def test_1(first):
'''用例传fixture'''
print("测试账号:%s"%first)
assert first == "yoyo"

class TestCase():
def test_2(self,first):
'''用例传fixture'''
print("测试账号:%s"%first)
assert first == "yoyo"

if __name__ == '__main__':
pytest.main(["-s","fixtureandscope.py"])

'''scope=session'''
'''fixture为session级别是可以跨.py模块调用的,也就是当我们有多个.py文件的用例时候,如果多个用例只需调用一次fixture,那就可以设置为scope="session",并且写到conftest.py文件里'''
'''conftest.py文件名称是固定的,pytest会自动识别该文件。放到工程的根目录下,就可以全局调用了,如果放到某个package包下,那就只在该package内有效'''
'''如果想同时运行test_fixture11.py和test_fixture12.py,在cmd执行
> pytest -s test_fixture11.py test_fixture12.py
'''
原文地址:https://www.cnblogs.com/nuonuozhou/p/10429701.html