Tutorial of Testing Python code

Posted in Uncategorized

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Python DocTest

Here we added Python’s DocTest to our greet function …

If you run on the command line …

python -m doctest -v first.py

You will get three tests passing …

The third test is how you would write if you expect your function to raise an exception.

Python UnitTest

Because DocTest writes test in the function document, it may not be sustainable if you have a lot of tests. In that case, you want your tests in a separate file. We can do with the UnitTest module.

Let’s say “greet.py” is the file that we want to test and it contains the greet function shown above.

Then we create our tests.py file which imports the code we want to test…

We also imported the unittest module and derive a class from unittest.TestCase. Our individual test are the methods of this GreetTests class. Here we have one.

Running unittest.main() is what starts the tests. We only want to run this if the file tests.py is the actual file that is invoked by python. That’s why we have the “if __name__ == “__main__” statement.

You run the test file from the command line with…

python tests.py

If you add setUp() and tearDown() methods to the GreetTests class, then it will run the former before each test. And it will run the latter after each test.


Related Posts

Tags

Share This