Skip to main content
 首页 » 编程设计

python之如何测试内部有两个或多个 input() 的函数

2025年05月04日14sxdcgaq8080

我需要测试一些 python 3 代码,但我在测试函数时遇到了一些 input() 问题。

例子:

def two_answers(): 
    if input("Input 'go' to proceed") != "go": 
        return two_answers() 
    else: 
        while input("Input 'bananas' to proceed") != "bananas": 
            print("What?!") 
    print("You've just gone bananas!") 

对于只有一个输入的函数,我使用:

def test_some_function(self): 
    codefile.input = lambda x: 'u' 
    codefile.some_function() . . . . 

然后:

def teardown_method(self, method): 
    codefile.input = input 

还原输入。

但是这里不行。帮助!

请您参考如下方法:

这是我的解决方案:

class SimulatedInput: 
 
    def __init__(self,*args): 
        self.args = iter(args)  
 
    def __call__(self,x): 
        try: 
            return next(self.args) 
        except StopIteration: 
            raise Exception("No more input") 

然后你就可以像以前一样使用它了:

def test_some_function(self): 
    codefile.input = SimulatedInput("u","v") 
    codefile.some_function() . . . .