python - 有人可以建议或帮助使用模拟打开创建 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")
解决方案
我想你正在寻找这样的东西:
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中)。
推荐阅读
- php - 带有 33 个参数的 PDO 插入不插入数据
- python - 如何在 Python 中提取对象的值?
- azure-ad-b2c - Azure B2C - Facebook 注册要求提供个人资料图片而不是电子邮件
- python - Python二项式系数混淆
- sharepoint - 级联下拉菜单和默认值
- next.js - 使用 Next.js 和 WPGraphQL 进行客户端渲染后的未定义数据
- android - Cordova Android - 相机没有所有选项
- node.js - Next.js + API 在同一台服务器上
- angular - 部署在 firebase 中的应用程序可以通过 http 使用来自 api 的数据?(不是https)
- python - 用于返回列(表达式)的 PySpark 类型提示?