1.前言概述
pytest.fixtrue()是把setUp()、setUpClass()、tearDown()、tearDownClass()整合到了一起。灵活度增加了,可以自定义函数名字放进方法里面去执行。对于用习惯了testNg的来说,难免有些不适应。不过存在就有道理,fixtrue也是有它的优势的。
各属性含义:
-
scope 作用范围
@pytest.fixture()
默认是scope='function'
@pytest.fixture(scope='function')
在测试用例之前执行一次(def aaa)@pytest.fixture(scope='class')
每个测试类之前执行一次(class A)@pytest.fixture(scope='module')
每个测试模块执行一次(*.py)@pytest.fixture(scope='session')
多个测试模块执行一次
-
autouse 自动调用
- @pytest.fixture(scope=‘function’,autouse=“true”) 默认是false,不想再每个方法中添加设置的函数名,可以把该值设置为true。带来的问题就是每个用例执行的时候都会调用该方法。根据实际场景使用。
-
params传入参数
- 暂未考虑到使用场景
-
ids
- 待完善
2.fixtrue实现setUp()
- setUp() 每个用例执行前,执行一次。场景:UI自动化的登陆,每个用例执行前都需要去登陆
# contest.py
@pytest.fixture(scope='function')
def login(self):
print('++++++++++++++++++++++++++this is a fixture+++++++++++++++++++++++++++++')
把login放到测试类的上面。保证每个测试方法执行前都会调用。
# test_cgi,py
@pytest.mark.usefixtures('login')
class TestMyClass:
def test_one(self):
x = "this"
assert "" in x
def test_two(self):
x = "hello"
assert x in 'hello'
如果只想某个方法使用,把login以入参的形式传入。或者@pytest.mark.usefixtures('login')
放到某个方法的上面
# 方法一:
def test_two(self,login):
x = "hello"
assert x in 'hello'
# 方法二
@pytest.mark.usefixtures('login')
def test_two(self,login):
x = "hello"
assert x in 'hello'
3.fixtrue实现tearDown()
- **tearDown()**每个用例执行完,执行一次。
@pytest.fixture(scope="function",autouse=True)
def open():
print("打开浏览器,并且打开百度首页")
yield
print("执行teardown!")
想如上操作,把open传入类的上面、方法上面、入参形式传入。可实现yield之前是setUp操作,之后是teardown操作。