如何模拟 pyunit 的 stdin 输入?

发布于 2024-11-14 11:58:48 字数 228 浏览 2 评论 0原文

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

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

以测试自动化的名义,有什么方法可以使 pyunit code> 可以伪造 raw_input() 的输入吗?

I'm trying to test a function that takes input from stdin, which I'm currently testing with something like this:

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

In the name of test automation, is there any way that pyunit can fake input to raw_input()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

我很OK 2024-11-21 11:58:48

简短的答案是monkey patch raw_input()

如何在中显示重定向的标准输入的答案中有一些很好的例子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

The short answer is to monkey patch raw_input().

There are some good examples in the answer to How to display the redirected stdin in Python?

Here is a simple, trivial example using a lambda that throws away the prompt and returns what we want.

System Under Test

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 !

Test case:

$ 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
那片花海 2024-11-21 11:58:48

更新——使用unittest.mock.patch

从python 3.3开始,有一个名为mock的unittest新子模块,它完全可以完成您需要做的事情。对于使用 python 2.6 或更高版本的用户,可以在 此处mock 的反向移植>。

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,因为没有更多文本可供读取。

Update -- using unittest.mock.patch

Since python 3.3 there is new submodule for unittest called mock that does exactly what you need to do. For those using python 2.6 or above there is a backport of mock found 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> "))

Previous answer -- replacing sys.stdin

I think the sys module might be what you're looking for.

You can do something like

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 will now read from simulatedInput.txt whenever it is called. If the contents of simulatedInput was

hello
bob

then the first call to raw_input would return "hello", the second "bob" and third would throw an EOFError as there was no more text to read.

独行侠 2024-11-21 11:58:48

您没有描述 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分钱。

You didn't describe what sort of code is in spellchecker.py, which gives me freedom to speculate.

Suppose it's something like this:

import sys

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

To improve testability of check_stdin function, I propose to refactor it like so:

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.

Now most of your logic is in check function, and you can hand-craft whatever input you can imagine in order to test it properly, without any need to deal with stdin.

My 2 cents.

浊酒尽余欢 2024-11-21 11:58:48

sys.stdin 替换为 StringIO 实例,并使用您想要通过 sys.stdin< 返回的数据加载 StringIO 实例/代码>。此外,sys.__stdin__包含原始的sys.stdin对象,因此在测试后恢复sys.stdin就像sys一样简单.stdin = sys.__stdin__

Fudge 是一个很棒的 python 模拟模块,具有方便的装饰器,可以为您进行此类修补,并具有自动清理功能。你应该检查一下。

Replace sys.stdin with an instance of StringIO, and load the StringIO instance with the data you want returned via sys.stdin. Also, sys.__stdin__ contains the original sys.stdin object, so restoring sys.stdin after your test is as simple as sys.stdin = sys.__stdin__.

Fudge is a great python mock module, with convenient decorators for doing patching like this for you, with automatic cleanup. You should check it out.

浅听莫相离 2024-11-21 11:58:48

如果您使用 mock 模块(由 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**

If you are using mock module (written by Michael Foord), in order to mock raw_input function you can use syntax like:

@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**
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文