【问题标题】:Pytest: How to test a separate function with input call?Pytest:如何使用输入调用测试单独的函数?
【发布时间】:2019-02-14 08:09:13
【问题描述】:

已在此处提出此问题 Pytest: How to test a function with input call?

但 mareoraft(下)的答案不适用于函数调用,它仅适用于当前测试函数范围内。

原答案:

def test_something_that_involves_user_input(monkeypatch):

    # monkeypatch the "input" function, so that it returns "Mark".
    # This simulates the user entering "Mark" in the terminal:
    monkeypatch.setattr('builtins.input', lambda x: "Mark")

    # go about using input() like you normally would:
    i = input("What is your name?")
    assert i == "Mark"

这是我将输入移动到另一个函数的测试代码(失败)

def separate_input_function():
    a = input()
    return a

def test_separate_function_monkeypatch_input(monkeypatch):
    ans = '3'
    with monkeypatch.context() as m:
        m.setattr('builtins.input', lambda prompt: ans)
        result = separate_input_function()

    assert result == ans

这引发了

TypeError: <lambda>() missing 1 required positional argument: 'prompt'

关于如何让它发挥作用的任何想法?

谢谢

【问题讨论】:

    标签: python pytest monkeypatching


    【解决方案1】:

    修补的替代方法是一种称为“依赖注入”的技术:

    def separate_input_function(_input=input):
        a = _input()
        return a
    
    def test_separate_function_monkeypatch_input(monkeypatch):
        _input = lambda: 42
        result = separate_input_function(_input=_input)
        assert result == 42
    

    也许这会有所帮助。

    【讨论】:

      【解决方案2】:

      您的问题与将input 移动到单独的函数无关,甚至与猴子补丁无关;它与传递错误数量的参数有关——正如错误消息所说。

      在你参考的例子中,monkeypatching函数被定义为带一个参数,input调用传递一个参数。

      如果您自己尝试,monkeypatching 函数被定义为采用一个参数,但 input 调用不传递任何参数。

      您可以将其定义为采用可选参数,就像真正的输入一样:

      m.setattr('builtins.input', lambda prompt="": ans)
      

      【讨论】:

        猜你喜欢
        • 2016-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-15
        • 1970-01-01
        相关资源
        最近更新 更多