基于cmd模块为python3 shell编写unittest

J91321

我正在尝试为我的项目编写一些单元测试,但是在为cmd模块的功能编写单元测试时遇到问题。

我跟随着这个问题的示例:基于Python的cmd模块为交互式shell创建自动化测试

让我们考虑以下内容:

#!/usr/bin/env python3

import cmd
import sys


class Interpreter(cmd.Cmd):
    def __init__(self, stdin=sys.stdin, stdout=sys.stdout):
        cmd.Cmd.__init__(self, stdin=stdin, stdout=stdout)

    def do_show(self, args):
        print("Hello world!")

if __name__ == "__main__":
    interpreter = Interpreter()
    interpreter.onecmd("show")

这是我的单元测试:

import unittest
import unittest.mock
import main
import sys


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

    def create(self):
        return main.Interpreter(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_show_command(self):
        cli = self.create()
        cli.onecmd("show")
        self.assertEqual("Hello world!", self._last_write(1))

如果我理解正确,那么将在sys.stdin和sys.stdout的单元测试模拟中创建该方法,并使用_last_write()方法,我应该能够使用以下方式访问写入模拟的stdout的参数列表 self.mock_stdout.write.call_args_list[-nr:]

测试结果

/home/john/rextenv/bin/python3 /home/john/pycharm/helpers/pycharm/utrunner.py /home/john/PycharmProjects/stackquestion/tests/test_show.py::CmdUiTest::test_show_command true
Testing started at 20:55 ...
Hello world!

Process finished with exit code 0

Failure
Expected :'Hello world!'
Actual   :''
 <Click to see difference>

Traceback (most recent call last):
  File "/home/john/PycharmProjects/stackquestion/tests/test_show.py", line 25, in test_show_command
    self.assertEqual("Hello world!", self._last_write(1))
AssertionError: 'Hello world!' != ''
- Hello world!
+ 

如您所见,您好,世界!fromdo_show()实际上是打印到stdout上。但是由于某种原因self.mock_stdout.write.call_args_list总是返回空列表。

(顺便说一句,我正在从Pycharm运行测试,但我也尝试过从Shell执行测试,没有区别)

我所需要的只是能够以某种方式测试我的cmd解释器的功能。只需比较打印输出即可。

我还尝试模拟内置打印,但是这甚至使我的测试更加无法通过(实际代码和测试更加复杂)。但是我不认为模拟打印和检查named_with()确实不是必需的或正确的解决方案。模拟标准输出应该是可能的。

帮派

orld有所不同不确定这是否是您想要的,last_write肯定无法正常工作!

F
======================================================================
FAIL: test_show_command (__main__.CmdUiTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "./int.py", line 32, in test_show_command
    self.assertEqual('Hello World!', fakeOutput.getvalue().strip())
AssertionError: 'Hello World!' != 'Hello world!'
- Hello World!
?       ^
+ Hello world!
?       ^


----------------------------------------------------------------------
Ran 1 test in 0.003s

FAILED (failures=1)

更改为使用unitte.mock.patch-我的python版本是3.5

from unittest.mock import patch
from io import StringIO


    # not working for reasons unknown
    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:]))

    # modified with unittest.mock.patch
    def test_show_command(self):
        # Interpreter obj
        cli = self.create()
        with patch('sys.stdout', new=StringIO()) as fakeOutput:
            #print ('hello world')
            self.assertFalse(cli.onecmd('show'))
        self.assertEqual('Hello World!', fakeOutput.getvalue().strip())

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何编写GRPC python unittest

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

使用 selenium 和 unittest Python 编写测试

如何使用流作为参数为方法编写unitTest

无法理解如何使用unittest模块在python中为工作日编写测试用例

如何使用Unittest在Python中编写内部类测试方法

如何使用python编写linux shell命令?

Shell无法读取用python编写的文件

Python UnitTest-如何访问subTests消息而不必手动编写它们?

如何在shell中为graphicsmagick编写循环?

如何在Shell脚本中为布尔变量编写if if?

如何编写基于C的模块来处理python词典?

使用换行符在 Python shell 中编写嵌套的 for 循环

用Python编写Shell扩展并进行编译

如何使用python子进程调用用Shell编写的jq?

Python3:编写CSV文件

Python3:编写CSV文件

导入在Python3中运行unittest的错误

python3如何设置在unittest中通过的测试

使用Python 3在unittest中测试未知模块

Python3模块

如何在python3中为多个相同字符编写正则表达式模式?

Shell脚本编写以形成动态数组并基于该数组触发一个过程

用C为Linux编写Shell,执行某个过程的exec无限循环

在 python3 中在 PDF 上编写文本

编写一个Shell脚本,首先进入nix shell,然后进入python虚拟环境

基于已安装模块编写条件语句的Python方式是什么?

编写运行3个ncmpcpp窗格的tmux shell脚本是否不可能?

如何为Android片段类编写unittest?