In Python, doctest
and unittest
are both testing frameworks that allow you to test your code to make sure it’s working correctly.
Doctest
doctest
is a simple testing framework that allows you to embed test cases directly in the documentation for a module or function. It searches for lines in the documentation that look like interactive Python sessions, and then runs the code to see if it produces the expected output. Here’s an example of how you might use doctest
to test a function:
def add(x, y):
"""
>>> add(1, 2)
3
>>> add(5, 10)
15
"""
return x + y
if __name__ == "__main__":
import doctest
doctest.testmod()
Unittest
unittest
is a more comprehensive testing framework that allows you to write test cases in a more organized way. It provides a set of assert methods that you can use to test the behavior of your code. Here’s an example of how you might use unittest
to test the same add
function:
import unittest
class TestAdd(unittest.TestCase):
def test_add(self):
self.assertEqual(add(1, 2), 3)
self.assertEqual(add(5, 10), 15)
if __name__ == "__main__":
unittest.main()
Both doctest
and unittest
are built into Python, so you don’t need to install anything to use them. Which one you choose to use will depend on your needs and personal preference. doctest
is a quick and easy way to test your code, but it can be less flexible and comprehensive than unittest
. unittest
is more powerful and allows you to write more complex and organized test cases, but it may take longer to set up and use.
How to set up doctest and unittest for a project
To set up doctest
for your project, you just need to include test cases in the documentation for your modules and functions. Here’s an example of how you might do this:
def add(x, y):
"""
This function adds two numbers.
>>> add(1, 2)
3
>>> add(5, 10)
15
"""
return x + y
if __name__ == "__main__":
import doctest
doctest.testmod()
To run the tests, you can simply run the script as you would any other Python script. The doctest
module will automatically find and run the test cases.
To set up unittest
for your project, you’ll need to create a separate Python script to hold your test cases. Here’s an example of how you might do this:
import unittest
def add(x, y):
return x + y
class TestAdd(unittest.TestCase):
def test_add(self):
self.assertEqual(add(1, 2), 3)
self.assertEqual(add(5, 10), 15)
if __name__ == "__main__":
unittest.main()
To run the tests, you can use the python -m unittest
command, followed by the name of the script containing your test cases (without the .py
extension). For example:
python -m unittest test_my_module
This will run all of the test cases in the test_my_module
script. You can also use the -v
flag to enable verbose output, which will print the names of each test case as it runs.
I hope this helps! Let me know if you have any questions.