基于Python的cmd modu为交互式shell创建自动测试

2024-04-24 23:58:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python3和cmd模块构建一个交互式shell。我已经用py.测试测试单个函数,如do帴*函数。我想创建更全面的测试,通过模拟用户的输入与shell本身进行实际交互。例如,如何测试以下模拟会话:

bash$ console-app.py
md:> show options
  Available Options:
  ------------------
  HOST      The IP address or hostname of the machine to interact with
  PORT      The TCP port number of the server on the HOST
md:> set HOST localhost
  HOST => 'localhost'
md:> set PORT 2222
  PORT => '2222'
md:>

Tags: 模块ofthe函数pycmdlocalhosthost
2条回答

使用pythonmock库模拟用户输入。在这里,您将发现与示例12类似的问题。在

您可以mockinput或传递给cmd的输入流来注入用户输入,但是我发现通过onecmd()CmdAPI方法和信任Cmd读取输入的方式来测试它。这样,您就不必关心Cmd如何直接通过users命令执行脏工作和测试:我通过控制台和socket使用cmd,而这我不关心流来自何处。在

此外,我使用onecmd()来测试偶数do_*(偶尔{})方法,使我的测试与代码的耦合程度降低。在

下面是我如何使用它的一个简单示例。create()_last_write()是分别构建MyCLI实例和获取最后输出行的帮助方法。在

from mymodule import MyCLI
from unittest.mock import create_autospec

class TestMyCLI(unittest.TestCase):
    def setUp(self):
        self.mock_stdin = create_autospec(sys.stdin)
        self.mock_stdout = create_autospec(sys.stdout)

    def create(self, server=None):
        return MyCLI(stdin=self.mock_stdin, stdout=self.mock_stdout)

    def _last_write(self, nr=None):
        """:return: last `n` output lines"""
        if nr is None:
            return self.mock_stdout.write.call_args[0][0]
        return "".join(map(lambda c: c[0][0], self.mock_stdout.write.call_args_list[-nr:]))

    def test_active(self):
        """Tesing `active` command"""
        cli = self.create()
        self.assertFalse(cli.onecmd("active"))
        self.assertTrue(self.mock_stdout.flush.called)
        self.assertEqual("Autogain active=False\n", self._last_write())
        self.mock_stdout.reset_mock()
        self.assertFalse(cli.onecmd("active TRue"))
        self.assertTrue(self.mock_stdout.flush.called)
        self.assertEqual("Autogain active=True\n", self._last_write())
        self.assertFalse(cli.onecmd("active 0"))
        self.assertTrue(self.mock_stdout.flush.called)
        self.assertEqual("Autogain active=False\n", self._last_write())

    def test_exit(self):
        """exit command"""
        cli = self.create()
        self.assertTrue(cli.onecmd("exit"))
        self.assertEqual("Goodbay\n", self._last_write())

注意,onecmd()如果cli应该终止,False则返回{},否则返回{}。在

相关问题 更多 >