简体   繁体   中英

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). For example, your function miniMaxSum performs a) some computations and b) prints the result. Similarly, your main a) transforms a string into a list of ints and b) performs an input operation. 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.

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:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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