Python单元测试用例

时间:2018-10-26 18:26:04

标签: python unit-testing

我是python的新手,我已经写了一些代码,但是在编写相同问题的测试用例时遇到了困难。问题陈述来自here。这是我的解决方案代码:

def get_input_stacks():
  c=list(map(int,input().split()))
  sc=list(map(int,input().split()))
  return c,sc

def Main():
  p,s=map(int,input().split())
  print(" I am calling through main")
  i=0
  differ=list()
  c=list()
  sc=list()
  for i in range(s):
    differ.append([])
  for i in range(p):
    n=0

    c,sc=get_input_stacks()
    dictionary=dict(zip(c,sc))
    c.sort()

    for j in range(s-1):
      if dictionary[c[j]]>dictionary[c[j+1]]:
        n+=1
    differ[n].append(i+1)
  for i in range(s):
    for j in range(len(differ[i])):
      print(differ[i][j])

if __name__ == '__main__':
  Main()

出于测试目的,我编写了以下代码:

from unittest.mock import patch
import unittest

import confusion

class ContainersTestCase(unittest.TestCase):
  def test_get_input_stacks_processed_input_correctly(self):
    user_input = [ '3 3' '16 24 60' '498 861 589'
                   '14 24 62' '72 557 819' '16 15 69' '435 779 232' ]
    expected_stacks = [ '2' '1' '3' ]

    with patch('builtins.input', side_effect=user_input):
        stacks =confusion.get_input_stacks()
    self.assertEqual(stacks, expected_stacks)

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

但是我遇到以下错误:

ERROR: test_get_input_stacks_processed_input_correctly (__main__.ContainersTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "testing.py", line 26, in test_get_input_stacks_processed_input_correctly
    stacks =confusion.get_input_stacks()
  File "G:\python learn\confusion.py", line 5, in get_input_stacks
    sc=list(map(int,input().split()))
  File "C:\Users\Vanshu Hassija\AppData\Local\Programs\Python\Python37-32\lib\unittest\mock.py", line 951, in __call__
    return _mock_self._mock_call(*args, **kwargs)
  File "C:\Users\Vanshu Hassija\AppData\Local\Programs\Python\Python37-32\lib\unittest\mock.py", line 1010, in _mock_call
    result = next(effect)
StopIteration

1 个答案:

答案 0 :(得分:0)

我不确定这些错误是在您的帖子中还是在您的代码中,而是尝试检查以下部分:

  1. 测试代码中的列表没有分隔符“,”。
  2. 您的源代码和测试代码在各个位置都有很差的缩进。