https://github.com/niewiaro/mentoring-2024
String Calculator with unittest and doctest
https://github.com/niewiaro/mentoring-2024
doctest python unittest
Last synced: 3 months ago
JSON representation
String Calculator with unittest and doctest
- Host: GitHub
- URL: https://github.com/niewiaro/mentoring-2024
- Owner: Niewiaro
- License: mit
- Created: 2024-11-20T07:31:14.000Z (11 months ago)
- Default Branch: main
- Last Pushed: 2024-12-06T21:41:42.000Z (11 months ago)
- Last Synced: 2025-03-27T09:31:13.295Z (7 months ago)
- Topics: doctest, python, unittest
- Language: Python
- Homepage:
- Size: 12.7 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# String Calculator with `unittest` and `doctest`
Welcome to the **String Calculator** project! This repository showcases my journey in exploring Python's testing frameworks: `unittest` and `doctest`. The implementation follows the [String Calculator Kata](https://codingdojo.org/kata/StringCalculator/) with additional features.
## Features
- **Addition of Numbers**: Supports integers and floats, separated by commas or newlines.
- **Custom Error Handling**: Validates input format and raises descriptive exceptions.
- **Extensive Testing**:
- `doctest`: Inline examples to ensure correctness during development.
- `unittest`: Comprehensive test cases for edge scenarios.---
## File Structure
### `main.py`
This file implements the core functionality:
- `add(number: str, re_separator: str = ",|\n") -> str`
Adds numbers from a delimited string.
Example usage (validated via `doctest`):
```python
>>> add("1,2")
'3'
>>> add("1.5,2.5")
'4.0'
```- Error handling:
- Empty string → Returns `'0'`.
- Trailing separator → Raises `ValueError`.
- Non-string input → Raises `TypeError`.- Benchmarking utility with `timeit`.
### `test_main.py`
Contains test cases written using `unittest`:
- Validates core functionalities.
- Tests edge cases:
- Mixed separators.
- Trailing or missing separators.
- Negative numbers.
- Large numbers.
- Incorrect input types.---
## How to Run
### Running `doctest`
To validate inline examples using `doctest`:
```bash
python main.py
```### Running `unittest`
To execute unit tests:
```bash
python -m unittest test_main.py
```---
## Example Use Case
```python
from main import add# Add numbers from a string
result = add("10,20,30")
print(result) # Output: '60'# Handle floats
result = add("1.1,2.2,3.3")
print(result) # Output: '6.6'
```---
## Project Goals
1. **Learn `doctest`**: Write self-validating examples within the function docstrings.
2. **Explore `unittest`**: Build robust test suites for various scenarios.
3. **Practice Error Handling**: Create descriptive and user-friendly exceptions.---
## Feedback & Contributions
I welcome feedback and suggestions for improving the implementation or test coverage. Feel free to open an issue or a pull request!
---
Thank you for visiting! 🎉