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)
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?
If you follow modern practices you should probably write the tests while you are writing your project, and not wait until your project is nearly finished.
There are, in my opinion, three great python testing frameworks that are good to check out. unittest – module comes standard with all python distributions nose – can run unittest tests, and has less boilerplate. pytest – also runs unittest tests, has less boilerplate, better reporting, lots of cool extra features
To get a good comparison of all of these, read through the introductions to each at http://pythontesting.net/start-here.
There’s also extended articles on fixtures, and more there.
The docs for unittest would be a good place to start.
Also, it is a bit late now, but in the future please consider writing unit tests before or during the project itself. That way you can use them to test as you go along, and (in theory) you can use them as regression tests, to verify that your code changes have not broken any existing code. This would give you the full benefit of writing test cases :)
As others already replied, it’s late to write unit tests, but not too late. The question is whether your code is testable or not. Indeed, it’s not easy to put existing code under test, there is even a book about this: Working Effectively with Legacy Code (see key points or precursor PDF).
Now writing the unit tests or not is your call. You just need to be aware that it could be a tedious task. You might tackle this to learn unit-testing or consider writing acceptance (end-to-end) tests first, and start writing unit tests when you’ll change the code or add new feature to the project.
nosetests is brilliant solution for unit-testing in python. It supports both unittest based testcases and doctests, and gets you started with it with just simple config file.