如何使用mocking open为给定pyspark的get_config函数编写pytest测试用例
实现思路
- 首先明确3个核心测试场景,覆盖所有代码分支:
- 入参
env为local,配置文件读取、yaml解析均正常的正向场景 - 入参
env为local,但yaml内容格式错误触发解析异常的异常场景 - 入参
env不为local的参数校验异常场景
- 入参
- 用到的pytest相关能力:
- 用
pytest-mock提供的mockerfixture mock内置open函数、yaml.safe_load方法,不需要依赖真实存在的配置文件 - 用pytest内置的
capsysfixture捕获标准输出,验证错误打印逻辑是否符合预期
- 用
测试代码示例
首先安装依赖: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
相关产品推荐
相关产品推荐

