# Unit Testing

A unit test tests a small "unit" of code - usually a function or method - independently from the rest of the program.

Some key advantages of unit testing include:

* **Isolates code** - This allows testing individual units in isolation from other parts of the codebase, making bugs easier to identify.
* **Early detection** - Tests can catch issues early in development before code is deployed, saving time and money.
* **Regression prevention** - Existing unit tests can be run whenever code is changed to prevent new bugs or regressions.
* **Facilitates changes** - Unit tests give developers the confidence to refactor or update code without breaking functionality.
* **Quality assurance** - High unit test coverage helps enforce quality standards and identify edge cases.

Every language has its unit testing framework. In Python, some popular ones are

* unittest
* pytest
* doctest
* testify

**Example:**

**calc.py**

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

def subtract(a,b):
    return a-b

def multiply(a,b):
    return a * b

def divide(a, b):
    return a / b
```

**main.py**

```python
from calc import add, subtract, multiply, divide

print(add(1,2))
print(subtract(1,2))
print(multiply(1,2))
print(divide(1,2))
```

**test\_calc.py**

```python
from calc import *
import unittest 

class TestMathOperations(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(10, 5), 15)
        self.assertEqual(add(-1, 1), 0)
        self.assertEqual(add(-1, -1), -2)

    def test_subtract(self):
        self.assertEqual(subtract(10, 5), 5)
        self.assertEqual(subtract(-1, 1), -2)
        self.assertEqual(subtract(-1, -1), 0)

    def test_multiply(self):
        self.assertEqual(multiply(10, 5), 50)
        self.assertEqual(multiply(-1, 1), -1)
        self.assertEqual(multiply(-1, -1), 1)

    def test_divide(self):
        self.assertEqual(divide(10, 5), 2)
        self.assertEqual(divide(-1, 1), -1)
        self.assertEqual(divide(-1, -1), 1)
        self.assertRaises(ZeroDivisionError, divide, 10, 0)  # Test for division by zero

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gchandra.gitbook.io/big-data-and-tools-with-nosql/data-format/python/unit-testing.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
