简体   繁体   English

python测试用户输入和输出

[英]python testing user input and output

How is it possible to test this function that takes in a list of integers and returns the minimum obtained by adding up exactly four of them and the maximum obtained again by adding up exactly four of the integers(the function works perfectly well). 如何测试该函数,该函数接受一个整数列表,并返回通过恰好相加四个整数而获得的最小值,并返回通过恰好相加四个整数而再次获得的最大值(该函数运行良好)。 I'll be grateful for any support offered. 感谢您提供的任何支持。

def miniMaxSum(arr):
  x = sum(arr)
  print( (x-(max(arr))), (x-(min(arr))) )

if __name__ == '__main__':
  arr = list(map(int, input().rstrip().split()))

  miniMaxSum(arr)

Your code is difficult to test because you are mixing computations and interactions (I/O operations in this case). 您的代码难以测试,因为您混合了计算和交互(在这种情况下为I / O操作)。 For example, your function miniMaxSum performs a) some computations and b) prints the result. 例如,函数miniMaxSum执行a)一些计算并b)打印结果。 Similarly, your main a) transforms a string into a list of ints and b) performs an input operation. 同样,您的main a)将字符串转换为整数列表,b)执行输入操作。 That makes both parts difficult to tests with an automated test suite: You could create unit-tests, but this would require you to create some test doubles for the I/O part. 这使得使用自动化测试套件很难对这两个部分进行测试:您可以创建单元测试,但这需要您为I / O部分创建一些测试双打。

If you clearly separate computations and interactions, the code could look as follows: 如果您清楚地将计算和交互分开,代码可能如下所示:

def miniMaxSum(arr):
  x = sum(arr)
  return ( (x-(max(arr))), (x-(min(arr))) )

def inputStringToNumbers(inputString):
  token = inputString.rstrip().split()
  numbers = list(map(int, token))
  return numbers

if __name__ == '__main__':
  inputString = input()
  numbers = inputStringToNumbers(inputString)
  mini, maxi = miniMaxSum(numbers)
  print(mini, maxi)

Then, very easily, you could create tests for both functions miniMaxSum and inputStringToNumbers , for example: 然后,非常容易地,您可以为函数miniMaxSuminputStringToNumbers创建测试,例如:

import miniMaxSum
import unittest

class TestMiniMaxSum(unittest.TestCase):

    def test_miniMaxSum_withOneElementList_shallGiveZeroes(self):
        actualResult = miniMaxSum.miniMaxSum([42])
        self.assertTupleEqual((0,0), actualResult)

    def test_miniMaxSum_withAandB_shallGiveAandB(self):
        actualResult = miniMaxSum.miniMaxSum([42,56])
        self.assertTupleEqual((42,56), actualResult)

    def test_inputStringToNumbers_withEmptyString_shallGiveEmptyList(self):
        actualResult = miniMaxSum.inputStringToNumbers("")
        self.assertListEqual([], actualResult)

    def test_inputStringToNumbers_withOneNumberStringt_shallGiveOneIntList(self):
        actualResult = miniMaxSum.inputStringToNumbers("42")
        self.assertListEqual([42], actualResult)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM