Sobes.tech
Junior — Middle

How do you define and write tests for Python code?

sobes.tech AI

Answer from AI

Tests in Python are usually written using the built-in unittest module or popular libraries such as pytest.

To define tests for code, you should:

  1. Identify functions or methods that perform individual logical operations.
  2. Determine the expected result for different input data.
  3. Write test functions that call these methods and verify that the result matches the expected.

An example using unittest:

import unittest

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

class TestAddFunction(unittest.TestCase):
    def test_add_positive(self):
        self.assertEqual(add(2, 3), 5)

    def test_add_negative(self):
        self.assertEqual(add(-1, -1), -2)

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

This approach helps automate code correctness checks and quickly identify errors when making changes.