如何模拟pyun的stdin输入?

时间:2011-06-07 21:40:38

标签: python linux python-unittest

我正在尝试测试一个从stdin获取输入的函数,我目前正在测试这样的函数:

cat /usr/share/dict/words | ./spellchecker.py

在测试自动化的名称中,pyunit是否可以伪造raw_input()的输入?

5 个答案:

答案 0 :(得分:22)

简短回答是monkey patch raw_input()

How to display the redirected stdin in Python?

的答案中有一些很好的例子

这是一个使用lambda的简单琐碎的例子,它会抛弃提示并返回我们想要的内容。

受测试系统

cat ./name_getter.py
#!/usr/bin/env python

class NameGetter(object):

    def get_name(self):
        self.name = raw_input('What is your name? ')

    def greet(self):
        print 'Hello, ', self.name, '!'

    def run(self):
        self.get_name()
        self.greet()

if __name__ == '__main__':
    ng = NameGetter()
    ng.run()

$ echo Derek | ./name_getter.py 
What is your name? Hello,  Derek !

测试用例:

$ cat ./t_name_getter.py
#!/usr/bin/env python

import unittest
import name_getter

class TestNameGetter(unittest.TestCase):

    def test_get_alice(self):
        name_getter.raw_input = lambda _: 'Alice'
        ng = name_getter.NameGetter()
        ng.get_name()
        self.assertEquals(ng.name, 'Alice')

    def test_get_bob(self):
        name_getter.raw_input = lambda _: 'Bob'
        ng = name_getter.NameGetter()
        ng.get_name()
        self.assertEquals(ng.name, 'Bob')

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

$ ./t_name_getter.py -v
test_get_alice (__main__.TestNameGetter) ... ok
test_get_bob (__main__.TestNameGetter) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

答案 1 :(得分:12)

更新 - 使用unittest.mock.patch

从python 3.3开始,有一个名为mock的unittest的新子模块完全可以完成你需要做的事情。对于使用python 2.6或更高版本的用户,有mock找到here的后端。

import unittest
from unittest.mock import patch

import module_under_test


class MyTestCase(unittest.TestCase):

    def setUp(self):
        # raw_input is untouched before test
        assert module_under_test.raw_input is __builtins__.raw_input

    def test_using_with(self):
        input_data = "123"
        expected = int(input_data)

        with patch.object(module_under_test, "raw_input", create=True, 
                return_value=expected):
            # create=True is needed as raw_input is not in the globals of 
            # module_under_test, but actually found in __builtins__ .
            actual = module_under_test.function()

        self.assertEqual(expected, actual)

    @patch.object(module_under_test, "raw_input", create=True)
    def test_using_decorator(self, raw_input):
        raw_input.return_value = input_data = "123"
        expected = int(input_data)

        actual = module_under_test.function()

        self.assertEqual(expected, actual)

    def tearDown(self):
        # raw input is restored after test
        assert module_under_test.raw_input is __builtins__.raw_input

if __name__ == "__main__":
    unittest.main()
# where module_under_test.function is:
def function():
    return int(raw_input("prompt> "))

上一个答案 - 替换sys.stdin

我认为sys模块可能就是你想要的。

您可以执行类似

的操作
import sys

# save actual stdin in case we need it again later
stdin = sys.stdin

sys.stdin = open('simulatedInput.txt','r') 
# or whatever else you want to provide the input eg. StringIO

raw_input现在只要调用,就会从simulatedInput.txt中读取。如果simulatedInput的内容是

hello
bob

然后第一次调用raw_input将返回“hello”,第二次调用“bob”,第三次调用EOFError,因为没有更多文本可供阅读。

答案 2 :(得分:3)

sys.stdin替换为StringIO的实例,并在StringIO实例中加载您希望通过sys.stdin返回的数据。另外,sys.__stdin__包含原始的sys.stdin对象,因此在测试后恢复sys.stdin就像sys.stdin = sys.__stdin__一样简单。

Fudge是一个很棒的python模拟模块,有方便的装饰器,可以为你做这样的修补,并自动清理。你应该看看它。

答案 3 :(得分:2)

您没有描述spellchecker.py中的代码类型,这让我可以自由推测。

假设它是这样的:

import sys

def check_stdin():
  # some code that uses sys.stdin

为了提高check_stdin函数的可测试性,我建议像这样重构它:

def check_stdin():
  return check(sys.stdin)

def check(input_stream):
  # same as original code, but instead of
  # sys.stdin it is written it terms of input_stream.

现在你的大部分逻辑都在check函数中,你可以手工制作你能想象的任何输入,以便正确地测试它,而不需要处理stdin

我的2美分。

答案 4 :(得分:1)

如果您使用mock module(由Michael Foord编写),为了模拟 raw_input 功能,您可以使用以下语法:

@patch('src.main.raw_input', create=True, new=MagicMock(return_value='y'))
def test_1(self):
    method_we_try_to_test();    # method or function that calls **raw_input**