Python Day 27: Testing




This problem is all about unit testing.

Your company needs a function that meets the following requirements:

For a given array of n integers, the function returns the index of the element with the minimum value in the array. If there is more than one element with the minimum value, the returned index should be the smallest one.
If an empty array is passed to the function, it should raise an Exception.
Note: The arrays are indexed from 0.



  1. def minimum_index(seq):
  2. if len(seq) == 0:
  3. raise ValueError("Cannot get the minimum value index from an empty sequence")
  4. min_idx = 0
  5. for i in range(1, len(seq)):
  6. if seq[i] < seq[min_idx]:
  7. min_idx = i
  8. return min_idx
  9. class TestDataEmptyArray():
  10. @staticmethod
  11. def get_array():
  12. return list()
  13. class TestDataUniqueValues():
  14. @staticmethod
  15. def get_array():
  16. return [5, 2, 8, 3, 1, -6, 9]
  17. @staticmethod
  18. def get_expected_result():
  19. return 5
  20. class TestDataExactlyTwoDifferentMinimums():
  21. @staticmethod
  22. def get_array():
  23. return [5, 2, 8, 3, 1, -6, 9, -6, 10]
  24. @staticmethod
  25. def get_expected_result():
  26. return 5
  27. def TestWithEmptyArray():
  28. try:
  29. seq = TestDataEmptyArray.get_array()
  30. result = minimum_index(seq)
  31. except ValueError as e:
  32. pass
  33. else:
  34. assert False
  35. def TestWithUniqueValues():
  36. seq = TestDataUniqueValues.get_array()
  37. assert len(seq) >= 2
  38. assert len(list(set(seq))) == len(seq)
  39. expected_result = TestDataUniqueValues.get_expected_result()
  40. result = minimum_index(seq)
  41. assert result == expected_result
  42. def TestiWithExactyTwoDifferentMinimums():
  43. seq = TestDataExactlyTwoDifferentMinimums.get_array()
  44. assert len(seq) >= 2
  45. tmp = sorted(seq)
  46. assert tmp[0] == tmp[1] and (len(tmp) == 2 or tmp[1] < tmp[2])
  47. expected_result = TestDataExactlyTwoDifferentMinimums.get_expected_result()
  48. result = minimum_index(seq)
  49. assert result == expected_result
  50. TestWithEmptyArray()
  51. TestWithUniqueValues()
  52. TestiWithExactyTwoDifferentMinimums()
  53. print("OK")
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]


donate a cup of tea :)


Join Our Facebook Group

Share this solution






codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube