python-unittest.md

#Python Unittest

A guide to unit testing in Python using the built-in unittest module.


#Basic Test Structure

To create a test, you must import the unittest module and create a class that inherits from unittest.TestCase. Every test method must start with the test_ prefix.

#Example

pythonimport unittest

# Function we want to test
def add(a, b):
    return a + b

# Class containing the tests
class TestMath(unittest.TestCase):
    
    def test_addition(self):
        result = add(3, 5)
        self.assertEqual(result, 8)

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

#Most Important Assertions

pythonself.assertEqual(function_result, expected_value)

self.assertTrue(is_pesel_valid("99010112345"))
self.assertFalse(is_even(7))

self.assertIn("Python", ["Java", "Python", "C++"])

#Testing Exceptions

pythondef divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero!")
    return a / b

class TestDivision(unittest.TestCase):
    
    def test_division_by_zero(self):
        with self.assertRaises(ValueError):
            divide(10, 0)

#SetUp

#Environment Setup (setUp)

The setUp() method runs automatically before each test method in the class. It is ideal for initializing class instances (objects) that will be used across multiple tests.

pythonclass TestEmployee(unittest.TestCase):

    def setUp(self):
        # Runs automatically before every test_ method
        self.employee = Employee("John", "Doe", 5000)

    def test_salary(self):
        self.assertEqual(self.employee.salary, 5000)

    def test_salary_increase(self):
        self.employee.increase_salary(1000)
        self.assertEqual(self.employee.salary, 6000)