You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用mocking open为给定pyspark的get_config函数编写pytest测试用例

实现思路
  • 首先明确3个核心测试场景,覆盖所有代码分支:
    • 入参env为local,配置文件读取、yaml解析均正常的正向场景
    • 入参env为local,但yaml内容格式错误触发解析异常的异常场景
    • 入参env不为local的参数校验异常场景
  • 用到的pytest相关能力:
    • 用pytest-mock提供的mocker fixture mock内置open函数、yaml.safe_load方法,不需要依赖真实存在的配置文件
    • 用pytest内置的capsys fixture捕获标准输出,验证错误打印逻辑是否符合预期
测试代码示例

首先安装依赖:
pip install pytest pytest-mock pyyaml pyspark

测试代码(放在test_config.py文件中即可):

import pytest
import yaml
from your_module import get_config # 请将your_module替换为get_config函数实际所在的模块名

def test_get_config_local_success(mocker):
    # 模拟yaml配置内容
    mock_yaml_content = """
env: local
spark:
  executor_memory: 4g
  driver_memory: 2g
"""
    # mock open函数,返回模拟的文件内容
    mock_open = mocker.patch("builtins.open", mocker.mock_open(read_data=mock_yaml_content))
    # 调用被测函数
    result = get_config("local")
    # 验证open调用的文件路径符合预期
    mock_open.assert_called_once_with("src/config/config_local.yml", "r")
    # 验证返回的配置内容正确
    assert result == {
        "env": "local",
        "spark": {
            "executor_memory": "4g",
            "driver_memory": "2g"
        }
    }

def test_get_config_local_yaml_error(mocker, capsys):
    # mock open正常返回,但yaml.safe_load触发解析异常
    mocker.patch("builtins.open", mocker.mock_open(read_data="invalid:: yaml"))
    mocker.patch("yaml.safe_load", side_effect=yaml.YAMLError("parse failed"))
    result = get_config("local")
    # 原函数异常分支无return,返回值为None
    assert result is None
    # 验证错误提示正常打印
    captured = capsys.readouterr()
    assert "Error in reading CONFIG file" in captured.out

def test_get_config_non_local_env(capsys):
    result = get_config("prod")
    assert result is None
    captured = capsys.readouterr()
    assert "Error in reading CONFIG file" in captured.out

直接在终端执行pytest test_config.py -v即可运行所有测试用例。

内容的提问来源于stack exchange,提问作者premjeet kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 15:09:04