Published on

5. Test Python code

Authors

5. How would you test Python code?

Testing Python code can be done in several ways depending on the scope and complexity. Here's a quick overview of common methods:


1. Manual Testing

  • Run your script or function manually.
  • Print outputs and check if they behave as expected.
  • Good for quick checks but not scalable.

2. Using assert Statements

  • Insert assert statements in your code to verify assumptions.

  • Example:

    def add(a, b):
        return a + b
    
    assert add(2, 3) == 5
    assert add(-1, 1) == 0
    
  • If an assertion fails, Python raises an AssertionError.


3. Unit Testing with unittest Module

  • Python’s built-in testing framework.

  • Write test cases in classes derived from unittest.TestCase.

  • Example:

    import unittest
    
    def add(a, b):
        return a + b
    
    class TestAdd(unittest.TestCase):
        def test_add_positive(self):
            self.assertEqual(add(2, 3), 5)
    
        def test_add_negative(self):
            self.assertEqual(add(-1, 1), 0)
    
    if __name__ == "__main__":
        unittest.main()
    
  • Run tests via command line or an IDE.


  • More concise and feature-rich than unittest.

  • Example:

    def add(a, b):
        return a + b
    
    def test_add():
        assert add(2, 3) == 5
        assert add(-1, 1) == 0
    
  • Run with pytest command in terminal.

  • Supports fixtures, parameterization, and plugins.


5. Integration and Functional Testing

  • Test how different parts of your program work together.
  • Use tools like unittest, pytest, or specialized frameworks like behave (for BDD).

6. Test Automation

  • Use CI/CD pipelines (GitHub Actions, Jenkins) to run tests automatically on code changes.

Summary:

  • Start with manual and assert for small scripts.
  • Use unittest or pytest for scalable, maintainable testing.
  • Automate tests to ensure code quality continuously.