Debugging and testing · 11 / 14 Exercise Medium

Run tests with unittest

Objective

Create a Python program that defines a test with unittest, runs it from the program itself and counts the failures.

Instructions

  • Define two functions: square_good(x), which returns x * x, and square_bad(x), which returns x + x (it has a bug).
  • Read a first line, good or bad, to choose the function to test (square_good or square_bad), and a second line with integers separated by spaces.
  • Define class TestSquare(unittest.TestCase) with a method test_values that goes through the numbers and, for each one, inside with self.subTest(n=n):, does self.assertEqual(function(n), n * n).
  • Run it with unittest.TextTestRunner(stream=io.StringIO()).run(...) (the stream prevents the report from being printed), loading the class with unittest.defaultTestLoader.loadTestsFromTestCase(TestSquare).
  • Show Failures: F, with len(result.failures), and on the next line Result: OK if result.wasSuccessful() or Result: FAIL otherwise.
Input
bad
1 2 3 4
Output
Failures: 3
Result: FAIL

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise