nosetests: setup and teardown methods

nosetests is a tool used to build unit tests in python.

Here below, I show an example on how to write a class that will perform some tests (test that a directory that has been created exists indeed).

One issue is that if you create a temporary file or directly (as in the example), then you will end up with a bunch of useless files in your directory. So, you need to do some cleaning once the test methods have been called. This is done by writing a method with the special name tearDown. Similarly, you may need some kind of initialisation. This is done with the special method setUp.

import os, shutil
 
class TestClass:
   def setUp(self):
       os.mkdir("testDir")
 
   def tearDown(self):
       shutil.rmtree("testDir")
 
   def test_case_1(self):
       os.path.isdir("testDir") == True

One you have your test, you can check that the tests pass succesfully:

nosetests test_a.py -v
test_a.TestClass.test_case_1 ... ok
 
----------------------------------------------------------------------
Ran 1 test in 0.001s
 
OK
Please follow and like us:
This entry was posted in Python and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.