使用用户输入验证对方法进行单元测试

我有一种方法可以接受用户输入并验证它们,直到他们输入正确的值。我不确定如何为此方法编写单元测试,因为它已经验证了用户输入。


def refreshtime_validation():

    while True:

        try:

            runtime_input = float(raw_input("Enter Refresh Time (in seconds): "))

        except ValueError:

            print "\n**Please enter a valid number (Must be an integer).**\n"

            continue

        if runtime_input <= 0:

            print "\n**Please enter a valid number (Must be greater than 0).**\n"

            continue

        else:

            return runtime_input

我该如何为这种方法编写单元测试?到目前为止我唯一的一个是


self.assertEquals('1','1')    

self.assertEquals('100','100')

self.assertEquals('100000','100000')


隔江千里
浏览 178回答 1
1回答

婷婷同学_

您可以使用mock来模拟 Python 中的 raw_input,并且可以通过重定向sys.stdout到StringIO. 这样你就可以模拟你的函数输入并测试无效和有效的情况:import sysimport mockimport unittestimport StringIOimport __builtin__# [..] your codeclass Test(unittest.TestCase):&nbsp; &nbsp; @mock.patch.object(__builtin__, 'raw_input')&nbsp; &nbsp; def test_refreshtime_validation(self, mocked_raw_input):&nbsp; &nbsp; &nbsp; &nbsp; my_stdout = StringIO.StringIO()&nbsp; &nbsp; &nbsp; &nbsp; sys.stdout = my_stdout&nbsp; &nbsp; &nbsp; &nbsp; mocked_raw_input.side_effect = ['error', '0', '1']&nbsp; &nbsp; &nbsp; &nbsp; outputs = '\n**Please enter a valid number (Must be an integer).**\n'+\&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '\n\n**Please enter a valid number (Must be greater than 0).**\n\n'&nbsp; &nbsp; &nbsp; &nbsp; valid_value = refreshtime_validation()&nbsp; &nbsp; &nbsp; &nbsp; sys.stdout = sys.__stdout__&nbsp; &nbsp; &nbsp; &nbsp; self.assertEquals(my_stdout.getvalue(), outputs)&nbsp; &nbsp; &nbsp; &nbsp; self.assertEquals(valid_value, 1)unittest.main()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python