模拟标准输入-Python 3中的多行 [英] Mock standard input - multi line in python 3

查看:54
本文介绍了模拟标准输入-Python 3中的多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,并且一直在使用python 3进行学习.我正在使用python的单元测试框架来测试我的代码.

I am new to python and have been using python 3 for my learning. I am using python's unit test framework to test my code.

问题:-

我需要进行单元测试的功能以以下方式接受输入:-

The function that I need to unit test takes inputs in the following manner:-

def compare():
   a, b, c = input().strip().split(' ')
   d, e, f = input().strip().split(' ')
   # other code here

我正在使用以下测试用例来模拟输入:-

I am using the following test case to mock the input :-

class TestCompare(unittest.TestCase):

   @patch("builtins.input", lambda: "1 2 3")
   @patch("builtins.input", lambda: "4 5 6")
   def test_compare(self):
      self.assertEqual(compare(), "1 1")

我面临的问题是,在运行测试用例时,变量三元组a,b,c和d,e,f具有相同的值-1,2,3

The problem I am facing is that when the test case is run the variable triplets a,b,c and d,e,f have the same values - 1,2,3

我一直试图找到一种方法来注入第二组输入来运行我的测试,但徒劳无功.

I have been trying to find a way to inject the second set of inputs to run my test but in vain.

非常感谢您提供有关上述内容的任何帮助.

Any help regarding the above is greatly appreciated.

解决方案环境:-Python 3

Solution environment :- Python 3

推荐答案

修补程序装饰器将确保修补的函数始终返回该值,并且如果后续调用必须不同,则模拟对象必须具有模拟该值的方法.最终变得更加复杂.

The patch decorator will ensure the patched function always return that value, and if subsequent calls must be different, your mock object must have a way to simulate that. This ends up being much more complicated.

但是,您可以做的是再降低一步,修补基础层,即标准输入/输出层.其他测试框架执行的一种常见策略是直接处理 sys.stdin sys.stdout 对象.考虑一下:

What you can do however is go one step lower and patch the underlying layer, which is the standard input/output layer. One common strategy that other test frameworks have done is to deal with the sys.stdin and sys.stdout objects directly. Consider this:

import unittest
from unittest.mock import patch

from io import StringIO

def compare():
    a, b, c = input().strip().split(' ')
    d, e, f = input().strip().split(' ')

    return '%s %s' % (a, d)

class TestCompareSysStdin(unittest.TestCase):

    @patch("sys.stdin", StringIO("1 2 3\n4 5 6"))
    def test_compare(self):
        self.assertEqual(compare(), "1 4")

执行

$ python -m unittest foo
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

自然地,这在较低的级别上起作用,因此具有在后续调用中返回不同值的迭代器的选项可能更合适.

Naturally, this works at a lower level, and so the option to have an iterator that returns different values on subsequent calls may be more suitable.

这篇关于模拟标准输入-Python 3中的多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆