【问题标题】:Can someone suggest or help on creating pytest using mocking open有人可以建议或帮助使用模拟打开创建 pytest
【发布时间】:2021-09-30 12:04:20
【问题描述】:

#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")

【问题讨论】:

  • 你想在这里做什么?我无法按照目前的方式关注问题
  • 我已经编写了 pyspark 函数,我需要为单元测试创​​建 pytest 函数
  • 也许io.TextIOWrapper 可以帮助你。您可以找到一些使用示例here

标签: python pyspark pytest-mock


【解决方案1】:

我认为您正在寻找这样的东西:

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中)。

【讨论】:

  • 好 :) 随意接受 :)
  • ??这是什么意思?
  • 无论如何,如果这解决了问题,请随时接受
  • 现在让我在问题陈述中添加错误部分,您能否帮助提供完整的 pytest,包括其他部分。会很开心
  • @premjeetkumar 我注意到为您编写测试套件;这不是这个网站的工作方式。如果您遇到特定问题并尝试解决它,我很乐意提供帮助,但我不会为您编写代码
猜你喜欢
  • 1970-01-01
  • 2012-05-18
  • 2020-07-25
  • 2018-01-24
  • 1970-01-01
  • 2011-06-06
  • 1970-01-01
  • 1970-01-01
  • 2022-10-12
相关资源
最近更新 更多