繁体   English   中英

Pytest:如何使用输入调用测试单独的函数?

[英]Pytest: How to test a separate function with input call?

这个问题在这里被问到 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'

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

谢谢

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

在您引用的示例中,monkeypatching 函数被定义为接受一个参数,并且input调用传递一个参数。

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

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

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

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

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

也许这有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM