【问题标题】:How can I generate keyboard inputs for Python's 'input' function?如何为 Python 的“输入”功能生成键盘输入?
【发布时间】:2016-11-27 21:43:42
【问题描述】:

我有一个用 Python 编写的控制台程序。我想在自动测试例程中测试几个输入组合。输入通过 Pythons input(...) 函数读取。

  • 如何模拟键盘或任何其他输入流将单个字符或字符串发送到input
  • 或者我是否需要将输入替换为连接到我的测试用例的另一个函数?

【问题讨论】:

  • 为什么不重构让你可以直接调用实际的功能呢?
  • @jonrsharpe 因为这是一个集成测试,没有单元测试:)。
  • 我建议您在问题中提及集成测试 - 在这种情况下,您可能不想想模拟任何东西。
  • 我同意@jonrsharpe。除非input 可以(并且将)在整个系统中只被调用一次,否则模拟不是正确的方法。

标签: python python-3.x testing input stdin


【解决方案1】:

您可以使用unittest.mock 修补函数的输出(包括流)。

#!/usr/bin/env python3

import unittest
from unittest.mock import patch

# Unit under test.
def get_input():
    my_input = input("Enter some string: ")
    if my_input == "bad":
        raise Exception("You were a bad boy...")
    return my_input

class MyTestCase(unittest.TestCase):
    # Force input to return "hello" whenever it's called in the following test
    @patch("builtins.input", return_value="hello")
    def test_input_good(self, mock_input):
        self.assertEqual(get_input(), "hello")

    # Force input to return "bad" whenever it's called in the following test
    @patch("builtins.input", return_value="bad")
    def test_input_throws_exception(self, mock_input):
        with self.assertRaises(Exception) as e:
            get_input()
            self.assertEqual(e.message, "You were a bad boy...")

if __name__ == "__main__":
    unittest.main()

【讨论】:

    【解决方案2】:

    如果这只是一个测试用例而不是“大系统的真正组成部分” - 意味着您只需将某个输入传递给您的命令行可执行文件(例如运行测试)并且您正在使用 Unix,一个方便这样做的方法是使用pipes:

    // read.py 
    val = raw_input()
    print 'nice', val
    

    然后通过控制台:

    $ echo "hat" | python read.py 
    nice hat
    

    在 Windows 上的语法是 little different - 应该类似于

    dir> python.exe read.py < file.txt
    

    实现相同目的的另一种 hacky-simple 方法是将 sys.stdin 替换为自定义流对象:

    sys.stdin = StringIO.StringIO("line 1\nline 2\nline 3")
    

    不过,如果@erip 的答案比自动化例程或测试学生的家庭作业与固定的测试集更大,则应该考虑使用它。

    【讨论】:

    • 这不是一种非常自动化的软件测试方式。
    • @erip,如果你需要,比如说,根据一组固定的预定义测试来测试学生的家庭作业,那为什么不呢? :) OP 的初衷不是很清楚。我完全同意您的解决方案应该用于实际生产中
    猜你喜欢
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    • 2020-12-28
    • 2014-05-30
    • 2011-01-15
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多