Python Unit Testing

petercour - Jul 5 '19 - - Dev Community

Coders write much code. How do you know that code does what it's supposed to do?

One way is to do "unit tests". A unit test tests a method and tests if the inputs matches the outputs.

Unit Test with Python

Hockey dockey professori. Want to see that in Python?

Start with a simple program:

#!/usr/bin/python3
# program.py
def inc_by_one(x):
    return x + 1

Then test that with the unittest module (test.py).

#!/usr/bin/python3
import unittest
import program

class MyModuleTest(unittest.TestCase):

    def test_inc_by_one(self):
        assert(program.inc_by_one(2) == 3)

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

Pay attention to this line:

        assert(program.inc_by_one(2) == 3)

It tests if the input (2) matches the output (3).

If you run the program the test will be run:

.
  ------------------r----------------------------------------------------
Ran 1 test in 0.000s

OK

Holy ravioli, the test passed!

Learn Python:

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player