遇一山,过一山,处处有风景;只要勇敢向前,一路尽是繁花盛开。 | (点击查看→)【测试干货】python/java自动化、持续集成、性能、测开、简历、笔试面试等

pytest简易教程(07):fixture跨模块共享(conftest.py)

 

pytest简易教程汇总,详见https://www.cnblogs.com/uncleyong/p/17982846

关于conftest.py

如果多个模块使用的fixture相同,那么,我们可以将fixture写在conftest.py中(通过conftest.py管理共享的fixture),这样达到跨模块和文件的效果

conftest的特点:

1、文件名称默认为conftest.py,是pytest里面固定的名字,不能随意更改,通常在里面写用例执行前的一些初始化操作

2、conftest.py文件可以有多个(全局、局部),搜索优先级自底而上(从和模块同级目录开始找,一直到项目根目录),遵循就近原则

3、conftest.py中的fixture可以跨文件调用,支持函数引用、通过装饰器调用,也可以自动适配(此时autouse要改为True;如果就近的一个都是False,远的一个都是True,此时还是会自动适配近的,详见文末示例)

4、conftest.py文件作用范围是它同级test文件,或者下面的test文件

5、不需要import导入conftest.py,pytest用例会自动识别该文件,放到项目的根目录下就可以全局目录调用

6、conftest.py文件不能被其他文件导入

 

示例

仅局部conftest.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
# @wx :ren168632201
# @Blog :https://www.cnblogs.com/uncleyong/

import pytest
@pytest.fixture()
def login():
    print("---登录")


@pytest.fixture()
def fun(login):
    print("---fun")

 

test_qzcsbj.py 

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
# @wx :ren168632201
# @Blog :https://www.cnblogs.com/uncleyong/
import pytest

def test_a(fun):
    print("--------------test_a")

  

结果:

 

添加全局conftest.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
# @wx :ren168632201
# @Blog :https://www.cnblogs.com/uncleyong/

import pytest


@pytest.fixture(autouse=True, scope="function")
def f():
    print("---fixture : function-前")
    yield
    print("---fixture : function-后")

@pytest.fixture(autouse=True, scope="class")
def f2():
    print("---fixture : class-前")
    yield
    print("---fixture : class-后")

@pytest.fixture(autouse=True, scope="module")
def f3():
    print("---fixture : module-前")
    yield
    print("---fixture : module-后")

@pytest.fixture(autouse=True, scope="package")
def f4():
    print("---fixture : package-前")
    yield
    print("---fixture : package-后")

@pytest.fixture(autouse=True, scope="session")
def f5():
    print("---fixture : session-前")
    yield
    print("---fixture : session-后")

 

结果:

 

全局和局部有同名的fixture

全局添加:

@pytest.fixture(autouse=True, scope="function")
def f0():
    print("---fixture : function-前(全局)")
    yield
    print("---fixture : function-后(全局)")

 

局部添加:

@pytest.fixture(autouse=False, scope="function")
def f0():
    print("---fixture : function-前(局部)")
    yield
    print("---fixture : function-后(局部)")

 

结果:调用的fixture是局部的f0,虽然是False,但是全局是True,所以哪怕没调用,也会执行这个局部fixture

 

如果

全局添加:

@pytest.fixture(autouse=False, scope="function")
def f0():
    print("---fixture : function-前(全局)")
    yield
    print("---fixture : function-后(全局)")

 

局部添加:

@pytest.fixture(autouse=True, scope="function")
def f0():
    print("---fixture : function-前(局部)")
    yield
    print("---fixture : function-后(局部)")

 

结果:

 

指定引用全局fixture

用例中可以通过@pytest.mark.usefixtures()指定引用全局autouse=False的fixture

 

posted @ 2024-02-23 20:56  全栈测试笔记  阅读(271)  评论(0编辑  收藏  举报
浏览器标题切换
浏览器标题切换end