一、前言
fixture里面有个scope参数可以控制fixture的作用范围:
session > module > class > function
二、fixture作用范围
- function:每一个函数或方法都会调用
- class:每一个类调用一次,一个类可以有多个方法
- module:每一个.py文件调用一次,该文件内又有多个function和class
- session:是多个文件调用一次,可以跨.py文件调用,每个.py文件就是module
三、scope="function"
@pytest.fixture()如果不写参数,默认就是scope="function",它的作用范围是每个测试用例来之前运行一次,销毁代码在测试用例运行之后运行
#!encoding=utf-8
import pytest
#fixture配置
@pytest.fixture()
def first():
print('\n获取用户名')
a='abc'
return a
@pytest.fixture(scope="function")
def second():
print('\n获取密码')
b='7777'
return b
#测试用例
def test_1(first):
print('测试账号:{}'.format(first))
assert first=='abc'
def test_2(second):
print('测试密码:{}'.format(second))
assert second=='7777'
if __name__=='__main__':
pytest.main(['-s','test_002.py'])
运行结果:
Testing started at 4:04 PM ...
/usr/local/bin/python3.6 /Applications/PyCharm.app/Contents/helpers/pycharm/_jb_pytest_runner.py --path /Users/luozelin/Desktop/pytest/pytest_demo2/test_002.py
Launching py.test with arguments /Users/luozelin/Desktop/pytest/pytest_demo2/test_002.py in /Users/luozelin/Desktop/pytest/pytest_demo2
============================= test session starts ==============================
platform darwin -- Python 3.6.3, pytest-5.2.0, py-1.8.0, pluggy-0.12.0
rootdir: /Users/luozelin/Desktop/pytest/pytest_demo2
plugins: forked-1.0.2, allure-pytest-2.8.5, rerun-0.0.1, html-1.21.1, rerunfailures-7.0, metadata-1.8.0, xdist-1.23.2collected 2 items
test_002.py
获取用户名
.测试账号:abc
获取密码
.测试密码:7777
[100%]
==============================