如何模拟pyunit的stdin输入?

2024-06-16 10:19:14 发布

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

我正在尝试测试一个从stdin获取输入的函数,我目前正在使用类似这样的函数进行测试:

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

以测试自动化的名义,有没有办法pyunit可以伪造输入到raw_input()


Tags: 函数pyshareinputrawusrstdindict
3条回答

简而言之,答案是monkey patchraw_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

StringIO的实例替换sys.stdin,并用通过sys.stdin返回的数据加载StringIO实例。而且,sys.__stdin__包含原始的sys.stdin对象,因此在测试后恢复sys.stdin就如同sys.stdin = sys.__stdin__一样简单。

Fudge是一个很棒的python模拟模块,有方便的装饰器来为您进行这样的修补,并具有自动清理功能。你应该去看看。

更新——使用unittest.mock.patch

自从python3.3以来,unittest有了一个新的子模块mock,它可以完成您需要做的事情。对于那些使用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

我想系统模块可能就是你要找的。

你可以这样做

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

无论何时调用,原始输入都将从simulatedInput.txt中读取。如果模拟输入的内容是

hello
bob

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

相关问题 更多 >