的 我想你正在寻找测试。 Python测试 强>
有很多方法可以为您的代码获得自动标准输入,但是具有更好结果的方法(虽然初学者之间的不常见做法)是单元测试。它的工作原理如下:
顺便说一句,python本身有一个unittest库,可以很容易地运行这种测试。但是你正在寻找的功能(把事情搞定 input() )需要更高级的实现 mock lib的帮助来自 patch 功能。
input()
mock
patch
让我们进入代码:
的 App.py 强>
def printName(): return input("What's your name man?")
的 Test.py 强>
from unittest.mock import patch import app @patch('builtins.input', lambda *args: 'Nolan') def test_print_name(): # The why we call args there is explained in the link bellow answer = app.printName() # Will call buitins.input inside it, but it's patched so don't worry about it assert answer == 'Nolan' # True, so no errors here if __name__ == "__main__": test_query_y()
此代码基于 这个答案
通过不使用类,你从unittest lib中遗漏了很多功能。我的意思是,你可以按原样使用它(尽管这可能不是一个好习惯)。因此,我建议您了解有关lib的更多信息:3