Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing unit tests in Python: How do I start? [closed]

I completed my first proper project in Python and now my task is to write tests for it.

Since this is the first time I did a project, this is the first time I would be writing tests for it.

The question is, how do I start? I have absolutely no idea. Can anyone point me to some documentation/ tutorial/ link/ book that I can use to start with writing tests (and I guess unit testing in particular)

Any advice will be welcomed on this topic.

like image 878
user225312 Avatar asked Jul 30 '10 12:07

user225312


People also ask

How do you write a unit test in Python?

Unit tests are usually written as a separate code in a different file, and there could be different naming conventions that you could follow. You could either write the name of the unit test file as the name of the code/unit + test separated by an underscore or test + name of the code/unit separated by an underscore.

Where do Python unit tests go?

unittest discovery will find all test in package folder.


1 Answers

If you're brand new to using unittests, the simplest approach to learn is often the best. On that basis along I recommend using py.test rather than the default unittest module.

Consider these two examples, which do the same thing:

Example 1 (unittest):

import unittest  class LearningCase(unittest.TestCase):     def test_starting_out(self):         self.assertEqual(1, 1)  def main():     unittest.main()  if __name__ == "__main__":     main() 

Example 2 (pytest):

def test_starting_out():     assert 1 == 1 

Assuming that both files are named test_unittesting.py, how do we run the tests?

Example 1 (unittest):

cd /path/to/dir/ python test_unittesting.py 

Example 2 (pytest):

cd /path/to/dir/ py.test 
like image 176
Tim McNamara Avatar answered Oct 19 '22 21:10

Tim McNamara