有人可以建议或帮助使用 mocking open 创建 pytest
Can someone suggest or help on creating pytest using mocking open
#pyspark 函数#
def get_config(环境)
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()
我将编写一个完整的测试套件留给你(这会很乏味,因为这个函数不会抛出错误但会打印到标准输出,如果失败则 returns None
。
关键的想法是你用“builtins.thing”模拟内置函数(在 python 3 中)。
#pyspark 函数#
def get_config(环境)
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()
我将编写一个完整的测试套件留给你(这会很乏味,因为这个函数不会抛出错误但会打印到标准输出,如果失败则 returns None
。
关键的想法是你用“builtins.thing”模拟内置函数(在 python 3 中)。