python unit testing ( AI generated)
To test Python code unit by unit, you use unit testing frameworks like unittest (built-in), pytest, or nose2. Here's a step-by-step guide:
---
1. Write Testable Code
Ensure your code is modular, with each function or method performing a specific task.
Example Python Code (math_operations.py):
def add(a, b):
return a + b
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
---
2. Use a Unit Testing Framework
Using unittest (Built-in Framework)
1. Create a test file (e.g., test_math_operations.py).
2. Import the unittest module and the functions to be tested.
3. Define test cases by subclassing unittest.TestCase.
Example:
import unittest
from math_operations import add, divide
class TestMathOperations(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
self.assertEqual(add(-1, 1), 0)
def test_divide(self):
self.assertEqual(divide(10, 2), 5)
with self.assertRaises(ValueError):
divide(10, 0)
if __name__ == '__main__':
unittest.main()
Run the tests:
python test_math_operations.py
---
Using pytest (Popular Third-Party Framework)
1. Install pytest:
pip install pytest
2. Write test cases in a simple, plain function format.
Example:
from math_operations import add, divide
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
def test_divide():
assert divide(10, 2) == 5
try:
divide(10, 0)
except ValueError:
pass
Run the tests:
pytest test_math_operations.py
Pytest automatically discovers test files prefixed with test_ and runs them.
---
3. Write Assertions
Assertions are the core of unit tests. They check the expected outcome against the actual outcome.
Examples of assertions:
self.assertEqual(actual, expected) # Check equality
self.assertTrue(condition) # Check if condition is True
self.assertRaises(Exception, func) # Check if exception is raised
Pytest equivalents:
assert actual == expected
with pytest.raises(Exception):
func()
---
4. Mocking External Dependencies
If your function interacts with external systems (e.g., APIs, databases), use the unittest.mock library to simulate their behavior.
Example with Mocking:
from unittest.mock import patch
import requests
def fetch_data(url):
response = requests.get(url)
return response.json()
@patch('requests.get')
def test_fetch_data(mock_get):
mock_get.return_value.json.return_value = {"key": "value"}
result = fetch_data("http://example.com")
assert result == {"key": "value"}
---
5. Test Coverage
To measure how much of your code is tested, use the coverage tool:
1. Install coverage:
pip install coverage
2. Run your tests with coverage:
coverage run -m pytest
3. Generate a coverage report:
coverage report -m
---
6. Run Tests Automatically
Integrate unit tests into CI/CD pipelines using Jenkins, GitHub Actions, or GitLab CI/CD.
Example Jenkins Pipeline Stage:
stage('Run Unit Tests') {
steps {
sh 'pytest --junitxml=results.xml'
}
}
---
Would you like an example for testing a specific type of function, like API calls or database operations?
( Article enerated using chatgpt)
Comments
Post a Comment