【发布时间】:2019-10-13 20:47:27
【问题描述】:
我无法在 Python 中测试我的代码输入。我尝试了几个解决方案,但我缺少一些东西,所以如果你能给我一些提示,我将不胜感激。
首先是我要测试的主代码文件中的 sn-p:
if __name__ == '__main__':
n = int(input())
m = int(input())
grid = []
for _ in range(n):
grid.append(list(map(str, input().rstrip().split())))
calculate(grid)
当我运行我的代码时,我输入“n”,然后输入“m”,然后根据用户输入创建一个网格(每一行在一个新行上......),并执行一个函数来计算一些关于网格和函数返回结果。这一切都很好,但现在我需要为它创建几个测试用例(根据预期输出测试不同的输入)。
首先,我尝试了这个:(在单独的 .py 文件上)
from unittest import mock
from unittest import TestCase
import main_file
class DictCreateTests(TestCase):
@mock.patch('main_file.input', create=True)
def testdictCreateSimple(self, mocked_input):
mocked_input.side_effect = ['2', '2', 'R G B\nR G B'] #this is the input I need for my color grid
self.assertEqual(calculate(grid), 2)
if __name__ == '__main__':
unittest.main()
然后我研究了更多选项并尝试了这个选项,这让我最接近:
import unittest
import os
class Test1(unittest.TestCase):
def test_case1(self):
input = "2\n2\nR G B\nR G B"
expected_output = '2'
with os.popen("echo " + input + "' | python main_file.py") as o:
output = o.read()
output = output.strip() # Remove leading spaces and LFs
self.assertEqual(output, expected_output)
if __name__ == '__main__':
unittest.main()
不幸的是,即使它通过了测试,我发现当它与预期输出进行比较时,它总是接受输入的第一个字母/数字作为结果。所以,我认为这与我需要输入的多个值有关。我尝试在不同的输入(输入 1 + 输入 2+ 输入 3)上将它们分开,但它仍然不起作用。
如果有人能给我一些如何操作的提示,我将不胜感激!提前谢谢!
【问题讨论】: