深入理解Python测试框架pytest中的fixtures机制

深入理解Python测试框架pytest中的fixtures机制

learn-python3 Jupyter notebooks for teaching/learning Python 3 learn-python3 项目地址: https://gitcode.com/gh_mirrors/le/learn-python3

前言

在Python测试领域,pytest是最受欢迎的测试框架之一。它提供了强大而灵活的fixtures机制,可以极大地简化测试代码的编写和维护。本文将深入探讨pytest fixtures的各种高级用法,帮助开发者编写更高效、更可维护的测试代码。

环境准备

在开始使用pytest fixtures之前,我们需要确保环境配置正确。特别是在Jupyter notebook中使用pytest时,需要安装必要的依赖包:

import sys

!{sys.executable} -m pip install pytest
!{sys.executable} -m pip install ipytest

import ipytest
ipytest.autoconfig()
import pytest

这里我们安装了pytest框架本身以及ipytest包,它允许我们在Jupyter notebook中直接运行pytest测试。

参数化fixtures

pytest允许我们像参数化测试函数一样参数化fixtures,这在我们需要对同一测试逻辑使用不同输入数据时非常有用。

PATHS = ["/foo/bar.txt", "/bar/baz.txt"]

@pytest.fixture(params=PATHS)
def executable(request):
    return request.param

在这个例子中,我们创建了一个名为executable的fixture,它会依次返回PATHS列表中的每个路径。当我们在测试中使用这个fixture时,pytest会自动为每个参数运行一次测试:

%%ipytest -s

def test_something_with_executable(executable):
    print(executable)

这将输出两个测试结果,分别对应两个不同的路径。

使用usefixtures标记

pytest.mark.usefixtures装饰器特别适用于那些需要fixture但不关心其返回值的情况。这在测试类中尤其有用,可以避免在每个测试方法中重复声明相同的fixture。

%%ipytest -s

@pytest.fixture
def my_fixture():
    print("\nmy_fixture is used")
  
@pytest.fixture
def other_fixture():
    return "FOO"

@pytest.mark.usefixtures('my_fixture')
class TestMyStuff:
    def test_somestuff(self):
        pass
    
    def test_some_other_stuff(self, other_fixture):
        print(f'here we use also other_fixture which returns: {other_fixture}')

在这个例子中,my_fixture会被自动应用到TestMyStuff类的所有测试方法中,而other_fixture则只在需要它的测试方法中被使用。

pytest内置fixtures

pytest提供了许多有用的内置fixtures,我们可以通过运行pytest --fixtures命令查看所有可用的fixtures。

monkeypatch fixture

monkeypatchfixture允许我们在测试期间临时修改环境变量或对象的属性,类似于标准库中的unittest.mock功能。

修改环境变量示例:

import os

def get_env_var_or_none(var_name):
    return os.environ.get(var_name, None)

测试代码:

%%ipytest -s

def test_get_env_var_or_none_with_valid_env_var(monkeypatch):
    monkeypatch.setenv('MY_ENV_VAR', 'secret')
    res = get_env_var_or_none('MY_ENV_VAR')
    assert res == 'secret'
    
def test_get_env_var_or_none_with_missing_env_var():
    res = get_env_var_or_none('NOT_EXISTING')
    assert res is None

修改对象属性示例:

class SomeClass:
    some_value = "some value"

    @staticmethod
    def tell_the_truth():
        print("This is the original truth")

我们可以创建一个fixture来修改这个类的行为:

def fake_truth():
    print("This is modified truth")

@pytest.fixture
def fake_some_class(monkeypatch):
    monkeypatch.setattr("__main__.SomeClass.some_value", "fake value")
    monkeypatch.setattr("__main__.SomeClass.tell_the_truth", fake_truth)

然后在测试中使用这个fixture:

%%ipytest -s

def test_some_class(fake_some_class):
    print(SomeClass.some_value)
    SomeClass.tell_the_truth()

tmpdir fixture

tmpdirfixture提供了创建临时文件和目录的功能,非常适合需要文件系统操作的测试。

def word_count_of_txt_file(file_path):
    with open(file_path) as f:
        content = f.read()
        return len(content.split())

测试代码:

%%ipytest -s

def test_word_count(tmpdir):
    test_file = tmpdir.join('test.txt')
    test_file.write('This is example content of seven words')
    res = word_count_of_txt_file(str(test_file)) # str返回文件路径
    assert res == 7

Fixture作用域

pytest fixtures支持不同级别的作用域,可以控制fixture的初始化和销毁时机:

  • function(默认):每个测试函数运行一次
  • module:每个测试模块运行一次
  • session:整个测试会话运行一次
@pytest.fixture(scope="function")
def func_fixture():
    print("\nfunc")

@pytest.fixture(scope="module")
def module_fixture():
    print("\nmodule")

@pytest.fixture(scope="session")
def session_fixture():
    print("\nsession")

测试代码:

%%ipytest -s

def test_something(func_fixture, module_fixture, session_fixture):
    pass

def test_something_else(func_fixture, module_fixture, session_fixture):
    pass

设置-清理行为

fixtures可以使用yield语句实现设置和清理逻辑,yield之前的代码是设置部分,之后的代码是清理部分。

@pytest.fixture
def some_fixture():
    print("some_fixture is run now")
    yield "some magical value"
    print("\nthis will be run after test execution, you can do e.g. some clean up here")

测试代码:

%%ipytest -s

def test_something(some_fixture):
    print('running test_something')
    assert some_fixture == 'some magical value'
    print('test ends here')

自动使用fixtures

通过设置autouse=True,我们可以让fixture自动应用于所有测试,而不需要在测试函数中显式声明。

@pytest.fixture(autouse=True)
def my_fixture():
    print("\nusing my_fixture")

测试代码:

%%ipytest -s

def test_1():
    pass
    
def test_2():
    pass

总结

pytest的fixtures机制提供了强大而灵活的测试工具,可以帮助我们:

  1. 通过参数化fixtures减少重复代码
  2. 使用usefixtures简化fixture应用
  3. 利用内置fixtures处理常见测试场景
  4. 控制fixture的作用域优化测试性能
  5. 实现设置和清理逻辑保证测试环境一致性
  6. 自动应用fixtures减少样板代码

掌握这些高级技巧将显著提升你的测试代码质量和开发效率。

learn-python3 Jupyter notebooks for teaching/learning Python 3 learn-python3 项目地址: https://gitcode.com/gh_mirrors/le/learn-python3

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

申梦珏Efrain

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值