- Python has a built-in module called
unittestthat you can use to write unit tests for your programs. - You can use this module to write tests for your own functions and make sure your code is working as expected.
- Unit tests are some pieces of code to exercise the input, the output and the behaviour of your code.
- To test a class, we need to create a class that inherits from
unittest.TestCase. - We use the
setUp()method to create instances of the class we want to test. - We use the
assertEqual()method to verify that the result obtained is the same as the expected result.
import unittest
def add(x, y):
return x + y
class TestAdd(unittest.TestCase):
def test_add(self):
self.assertEqual(add(10, 20), 30)
self.assertEqual(add(-10, 20), 10)
self.assertEqual(add(-10, -20), -30)
self.assertEqual(add(0, 0), 0)
if __name__ == '__main__':
unittest.main()-
assert-
is a method provided by the
unittestmodule. -
It tests whether the result obtained is the same as the expected result.
import unittest def main(): test_add() def add(x, y): return x + y def test_add(): assert add(10, 20) == 30 assert add(-10, 20) == 10 assert add(-10, -20) == -30 assert add(0, 0) == 0 if __name__ == '__main__': main()
-
-
assertRaises-
is a method provided by the
unittestmodule. -
It tests whether the function raises an exception when it is called with the given arguments.
import unittest def main(): test_divide() test_divide_raises() def divide(x, y): if y == 0: raise ValueError("Can not divide by zero!") return x / y def test_divide(): assert divide(10, 2) == 5 assert divide(10, 5) == 2 assert divide(10, 0) == 0 def test_divide_raises(): with assertRaises(ValueError): divide(10, 0) if __name__ == '__main__': main()
-
-
AssertionError- is raised when an
assertstatement fails. - it gives us ability to provide a custom message to be displayed when the assertion fails.
- is raised when an
import unittest
def main():
test_divide()
def divide(x, y):
if y == 0:
raise ValueError("Can not divide by zero!")
return x / y
def test_divide():
try:
divide(10, 0)
except AssertionError:
print("AssertionError: Can not divide by zero!")
if __name__ == '__main__':
main()// TODO: read this tutorial and add notes
It's a framework that makes building simple and scalable tests easy.
-
it will run all files of the form
test_*.pyor*_test.pyin the current directory and its subdirectories. -
it will run all functions and classes which have names that start with
test_prefixed. -
Example:
-
Test file:
test_add.pyimport pytest def add(x, y): return x + y def test_add(): # testing logic
-
To run the tests, enter the following command in the terminal:
pytest
-
