05、fixture scope介绍

fixture里面有个scope参数可以控制fixture的作用范围:session > module > class > function

fixture(scope="function", params=None, autouse=False, ids=None, name=None):
    """使用装饰器标记fixture的功能
     可以使用此装饰器(带或不带参数)来定义fixture功能。 fixture功能的名称可以在以后使用
     引用它会在运行测试之前调用它:test模块或类可以使用pytest.mark.usefixtures(fixturename标记。 
     测试功能可以直接使用fixture名称作为输入参数,在这种情况下,夹具实例从fixture返回功能将被注入。

    :arg scope: scope 有四个级别参数 "function" (默认), "class", "module" or "session".

    :arg params: 一个可选的参数列表,它将导致多个参数调用fixture功能和所有测试使用它

    :arg autouse:  如果为True,则为所有测试激活fixture func 可以看到它。 如果为False(默认值)则显式需要参考来激活fixture

    :arg ids: 每个字符串id的列表,每个字符串对应于params 这样他们就是测试ID的一部分。 如果没有提供ID它们将从params自动生成

    :arg name:   fixture的名称。 这默认为装饰函数的名称。 如果fixture在定义它的同一模块中使用,夹具的功能名称将被请求夹具的功能arg遮蔽; 解决这个问题的一种方法是将装饰函数命名
                       “fixture_ <fixturename>”然后使用”@ pytest.fixture(name ='<fixturename>')“”。
ScopeDesc
function每个test都运行,默认是function的scope
class每个class的所有test只运行一次
module每个module的所有test只运行一次
session每个session只运行一次
scope="function"

@pytest.fixture()如果不写参数,默认就是scope="function",它的作用范围是每个测试用例来之前运行一次,销毁代码在测试用例运行之后运行。

import pytest


@pytest.fixture()
def first():
    print("\n获取用户名")
    a = "Hero"
    return a


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


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


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

运行结果:

╰ pytest -v -s ./test_data.py
================= test session starts =================
platform darwin -- Python 3.7.4, pytest-4.4.0, py-1.8.0, pluggy-0.13.0 -- /Users/zhouwanghua/Code/Leyan/python/robocop/bin/python
cachedir: .pytest_cache
metadata: {'Python': '3.7.4', 'Platform': 'Darwin-18.6.0-x86_64-i386-64bit', 'Packages': {'pytest': '4.4.0', 'py': '1.8.0', 'pluggy': '0.13.0'}, 'Plugins': {'bdd': '3.1.0', 'html': '1.20.0', 'metadata': '1.8.0'}}
rootdir: /Users/zhouwanghua/Code/Leyan/robocop, inifile: pytest.ini
plugins: bdd-3.1.0, html-1.20.0, metadata-1.8.0
collected 2 items                                                                                                                  

test_data.py::test_1 
获取用户名
测试账号:Hero
PASSED
test_data.py::test_2 
获取密码
测试密码:123456
PASSED

================= 2 passed in 0.03 seconds =================

用例放到类里面也一样

import pytest

@pytest.fixture()
def first():
    print("\n获取用户名")
    a = "yoyo"
    return a

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

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

    def test_2(self, sencond):
        '''用例传fixture'''
        print("测试密码:%s" % sencond)
        assert sencond == "123456"

if __name__ == "__main__":
    pytest.main(["-s", "test_fixture7.py"])
scope="class"

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

import pytest


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


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

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

运行结果:

╰ pytest -v -s ./test_data.py
================= test session starts =================
platform darwin -- Python 3.7.4, pytest-4.4.0, py-1.8.0, pluggy-0.13.0 -- /Users/zhouwanghua/Code/Leyan/python/robocop/bin/python
cachedir: .pytest_cache
metadata: {'Python': '3.7.4', 'Platform': 'Darwin-18.6.0-x86_64-i386-64bit', 'Packages': {'pytest': '4.4.0', 'py': '1.8.0', 'pluggy': '0.13.0'}, 'Plugins': {'bdd': '3.1.0', 'html': '1.20.0', 'metadata': '1.8.0'}}
rootdir: /Users/zhouwanghua/Code/Leyan/robocop, inifile: pytest.ini
plugins: bdd-3.1.0, html-1.20.0, metadata-1.8.0
collected 2 items                                                                                                                  

test_data.py::TestCase::test_1 
获取用户名,scope为class级别只运行一次
测试账号:Hero
PASSED
test_data.py::TestCase::test_2 测试账号:Hero
first:Hero
PASSED

================= 2 passed in 0.03 seconds =================
scope="module"

fixture为module级别时,在当前.py脚本里面所有用例开始前只执行一次

import pytest


@pytest.fixture(scope="module")
def first():
    print("\n获取用户名,scope为module级别当前.py模块只运行一次")
    a = "Hero"
    return a


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


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

运行结果:

╰ pytest -v -s ./test_data.py
================= test session starts =================
platform darwin -- Python 3.7.4, pytest-4.4.0, py-1.8.0, pluggy-0.13.0 -- /Users/zhouwanghua/Code/Leyan/python/robocop/bin/python
cachedir: .pytest_cache
metadata: {'Python': '3.7.4', 'Platform': 'Darwin-18.6.0-x86_64-i386-64bit', 'Packages': {'pytest': '4.4.0', 'py': '1.8.0', 'pluggy': '0.13.0'}, 'Plugins': {'bdd': '3.1.0', 'html': '1.20.0', 'metadata': '1.8.0'}}
rootdir: /Users/zhouwanghua/Code/Leyan/robocop, inifile: pytest.ini
plugins: bdd-3.1.0, html-1.20.0, metadata-1.8.0
collected 2 items                                                                                                                  

test_data.py::test_1 
获取用户名,scope为module级别当前.py模块只运行一次
测试账号:Hero
PASSED
test_data.py::TestCase::test_2 测试账号:Hero
PASSED

================= 2 passed in 0.04 seconds =================
scope="session"

fixture为session级别是可以跨.py模块调用的,也就是当我们有多个.py文件的用例时候,如果多个用例只需调用一次fixture,那就可以设置为scope="session",并且写到conftest.py文件里 conftest.py文件名称是固定的,pytest会自动识别该文件。放到工程的根目录下,就可以全局调用了,如果放到某个package包下,那就只在该package内有效

conftest.py

import pytest

@pytest.fixture(scope="session")
def first():
    print("\n获取用户名,scope为session级别多个.py模块只运行一次")
    a = "Hero"
    return a

test_fixture11.py和test_fixture12.py用例脚本

# test_fixture11.py

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

# test_fixture12.py
import pytest

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

如果想同时运行test_fixture11.py和test_fixture12.py,在cmd执行

	pytest -s test_fixture11.py test_fixture12.py
============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-3.6.3, py-1.5.4, pluggy-0.6.0
rootdir: D:\YOYO\fixt, inifile:
plugins: rerunfailures-4.1, metadata-1.7.0, html-1.19.0, allure-adaptor-1.7.10
collected 2 items

test_fixture11.py .                                                      [ 50%]
test_fixture12.py .                                                      [100%]

========================== 2 passed in 0.03 seconds ===========================

D:\YOYO\fixt>pytest -s test_fixture11.py test_fixture12.py
============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-3.6.3, py-1.5.4, pluggy-0.6.0
rootdir: D:\YOYO\fixt, inifile:
plugins: rerunfailures-4.1, metadata-1.7.0, html-1.19.0, allure-adaptor-1.7.10
collected 2 items

test_fixture11.py
获取用户名,scope为session级别多个.py模块只运行一次
测试账号:Hero
.
test_fixture12.py 测试账号:Hero
.

========================== 2 passed in 0.03 seconds ===========================
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值