w1coding.comAll tutorials

Python Unity

Python lessons
  1. Environment Setup
  2. Introduction
  3. Control
  4. Control
  5. Loops
  6. Functions
  7. Lists
  8. Dictionary
  9. Classes
  10. Exception
  11. File
  12. Libray
  13. Date
  14. Regula
  15. JSON
  16. Web
  17. Zweb
  18. Apis
  19. Unity
  20. Llampda
  21. Iterators
  22. Generators
  23. Files
  24. Context
  25. Ilogging
  26. Multithreading
  27. Networking
  28. SQLite

Python Unit Testing

Unit testing is essential for verifying that your code works correctly. In Python, you can use the built-in unittest module to write tests for your functions.

Writing Unit Tests

Here is an example of how to write and run a simple test using unittest:

      
        import unittest

        def add(a, b):
            return a + b

        class TestMathOperations(unittest.TestCase):
            def test_add(self):
                self.assertEqual(add(3, 4), 7)
                self.assertEqual(add(-1, 1), 0)

        if __name__ == "__main__":
            unittest.main()
      
    

The test class TestMathOperations contains a test method test_add(), which checks if the add() function works correctly. You can run the tests with the command python -m unittest test_file.py.

Activity

Try It Yourself!

Write a unit test for a function that subtracts two numbers. Ensure that it passes all cases, including negative numbers and zero.

Quick Quiz

Quick Quiz

  1. What module do you use for unit testing in Python?
  2. How do you run unit tests in Python?

Answers: The unittest module is used for unit testing. You can run tests using python -m unittest.