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 returnsx * x, andsquare_bad(x), which returnsx + x(it has a bug). - Read a first line,
goodorbad, to choose the function to test (square_goodorsquare_bad), and a second line with integers separated by spaces. - Define
class TestSquare(unittest.TestCase)with a methodtest_valuesthat goes through the numbers and, for each one, insidewith self.subTest(n=n):, doesself.assertEqual(function(n), n * n). - Run it with
unittest.TextTestRunner(stream=io.StringIO()).run(...)(thestreamprevents the report from being printed), loading the class withunittest.defaultTestLoader.loadTestsFromTestCase(TestSquare). - Show
Failures: F, withlen(result.failures), and on the next lineResult: OKifresult.wasSuccessful()orResult: FAILotherwise.
bad
1 2 3 4
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