【问题标题】:How to test return value of some function calls in Python如何在 Python 中测试某些函数调用的返回值
【发布时间】:2021-11-02 09:06:36
【问题描述】:

假设我们有以下代码:

def second_func(a, b, c):
    """ some other definition"""
    return something


def first_func(x, y, z):
    """ some definition"""
    d = second_func(a, b, c)
    """ some definition"""
    return something

我们正在尝试为first_func 编写测试。如您所见,first_func 调用 second_func 并带有一些在其定义中生成的参数 a, b, c

有什么方法可以测试second_funcfirst_func 内部调用的返回值是什么? (换句话说,d 是什么?)


这只是一个更大问题的简单形式。我正在使用 Telethon 用户测试我的电报机器人,我需要测试由于使用机器人发送消息而使用的某些函数的一些返回值。

也就是说,我无法更改返回值甚至函数的定义,我希望以某种方式(通过包装或修补这些函数)可以看到它们在我的 e2e 测试中返回的内容。

【问题讨论】:

  • 如果你将d设为全局(不推荐)你可以在函数调用后检查d的值。但是为什么不直接为second_func 编写测试呢?
  • 没有。您想测试first_func 的输入/输出,不是它是如何实现的。您要确保当您将foo 传递给first_func 时,它会返回bar如何它是无关紧要的,实际上可能在未来发生变化。如果您想确保 its 输入/输出,您可以为 second_func 编写单独的测试。
  • 编辑了我的问题,以便我可以更好地解释我的情况。 @deceze
  • "我们正在尝试为 first_func 编写一个测试" 好的,好吧,只要返回值正确,函数就是正确的。规范中没有任何内容要求d 在任何时候都具有正确的值——或存在。 “但我'知道'first_func 依赖于second_func,如果first_func 给出错误答案,我想确保问题不在second_func 中” - 好的,所以写一个second_func 的单独测试,无论如何您都需要这样做
  • "编辑了我的问题,以便我可以更好地解释我的情况" 这种解释无关紧要(也不需要或要求);建议是一样的。

标签: python unit-testing testing


【解决方案1】:

尝试指定你需要在你的函数中使用的默认参数,如果你在没有参数的情况下调用它,你将得到默认结果,并且可以按照你的意愿使用它

def second_func(a=0, b=1, c=2):
    """ some other definition"""
    return a + b * c


def first_func():
    """ some definition"""
    d = second_func()
    print(type(d))
    """ some definition"""
    return 0

first_func()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    • 2019-12-14
    • 2022-07-21
    • 2019-05-30
    • 2018-03-24
    • 2022-10-20
    • 2016-12-26
    相关资源
    最近更新 更多