Python Unit Test Notes

Here are some notes I make about Python Unit Test

The includes will cover the following topics

  • The basic template for a test file
  • How to execute one time set up
  • How to use CLION to run Python unit test
  • How to check if a bash command succeeded in PyUnit test

The basic template I have

class TestSuite(unittest.TestCase):
    first_time_setup = True

    @classmethod
    def setUpClass(cls):
        #one time set up 

    def setUp(self):
        #execute before every test case

    def tearDown(self):
        #execute after every test case

    def utility(self, arg):
        #utility method that can be used in test cases

    def test_case_one(self):
        #test case one, can call utility here
        #self.assertEqual('foo'.upper(), 'FOO')

if __name__ == '__main__':
 suite = unittest.TestLoader().loadTestsFromTestCase(TestSuite)
 unittest.TextTestRunner(verbosity=2).run(suite)

The official PyUnit documentation

https://docs.python.org/2/library/unittest.html

How to execute one time set up

Note that you must have “@classmethod”

    @classmethod
    def setUpClass(cls):
        #one time set up

How to use CLION to run Python unit test

First, install the PyCharm community edition plugin for Python. Then go to Preference, Build Execution tab and set up your Python Interpreter.

The other thing is that you can go to run configuration and create a new type for “Python Test” (NOT Python), this gives a prettier interface for unit test.

Remember to set the working directory to where your python test file is. 

Details can be found in this video (Python Plugin for CLion)

How to check if a bash command succeeded in PyUnit test

Use the “subprocess.call” library. It would return a “return code”. If it is “0”, it should have succeeded. I use assertNotEquals(subprocess.call(cmd), 0) to check if something failed.

The return code comes from Popen.wait() I think. The return code would be the exit code of the process. As a result, it would be depending on the program.  There is a strong convention that 0 means successful.

You can check the process code by executing it in bash

command

echo $?

Advertisements
This entry was posted in Tools, Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s