首页 > 解决方案 > 有人可以建议或帮助使用模拟打开创建 pytest

问题描述

#pyspark函数#

def get_config(env)

 if env == 'local':
    with open(f"src/config/config_{env}.yml", "r") as stream:
        try:
            data = yaml.safe_load(stream)
            return data
        except yaml.YAMLError as exc:
            print("Error in reading CONFIG file")
else:
       print("Error in reading CONFIG file")

标签: pythonpysparkpytest-mock

解决方案


我想你正在寻找这样的东西:

import pytest
from io import StringIO
import yaml


def get_config(env):
    if env == "local":
        with open(f"src/config/config_{env}.yml", "r") as stream:
            try:
                data = yaml.safe_load(stream)
                return data
            except yaml.YAMLError as exc:
                print("Error in reading CONFIG file")
    else:
        print("Env is not local")


def test_valid_config(mocker):
    content = "{this: 7}"
    mocked_open = mocker.patch("builtins.open")
    mocked_open.return_value = StringIO(content)
    assert get_config("local") == {"this": 7}
    assert mocked_open.called_once()

我把编写一个完整的测试套件留给你(这会很乏味,因为这个函数不会抛出错误,而是打印到标准输出并None在失败时返回。

关键的想法是你用“builtins.thing”模拟内置函数(在python 3中)。


推荐阅读