mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-11-24 06:06:02 +09:00
background tasks
This commit is contained in:
1 parent
e1afe444d4
commit
9811b78b5b
215 files changed
+39531
-2917
No files matched your search
@@ -0,0 +1,151 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
.python-version
|
||||
|
||||
# pipenv
|
||||
Pipfile.lock
|
||||
|
||||
# poetry
|
||||
poetry.lock
|
||||
|
||||
# pdm
|
||||
.pdm.toml
|
||||
|
||||
# PEP 582
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Logs
|
||||
logs/
|
||||
*.log
|
||||
@@ -0,0 +1,181 @@
|
||||
# Complex Hello World Application
|
||||
|
||||
A sophisticated multi-module Python application demonstrating advanced software engineering patterns and best practices.
|
||||
|
||||
## Features
|
||||
|
||||
- **Multi-language Support**: Greet in English, Spanish, French, German, and Japanese
|
||||
- **Multiple Output Formats**: Plain text, bold, colored, and ASCII art
|
||||
- **Modular Architecture**: Clean separation of concerns with factory patterns
|
||||
- **Performance Monitoring**: Built-in performance measurement decorators
|
||||
- **Comprehensive Logging**: Configurable logging with file and console output
|
||||
- **Input Validation**: Robust input sanitization and validation
|
||||
- **Extensive Testing**: Unit tests with high code coverage
|
||||
- **Command-line Interface**: Rich CLI with argparse
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
python-hello-complex/
|
||||
├── main.py # Application entry point
|
||||
├── config/ # Configuration module
|
||||
│ ├── __init__.py
|
||||
│ └── settings.py # Application settings
|
||||
├── src/ # Source code modules
|
||||
│ ├── __init__.py
|
||||
│ ├── greetings/ # Greeting strategies
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── base.py # Abstract base class
|
||||
│ │ ├── strategies.py # Concrete implementations
|
||||
│ │ └── greeting_factory.py
|
||||
│ ├── formatters/ # Text formatting
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── base.py # Abstract base class
|
||||
│ │ ├── styles.py # Formatting styles
|
||||
│ │ └── formatter_factory.py
|
||||
│ └── utils/ # Utility modules
|
||||
│ ├── __init__.py
|
||||
│ ├── logger.py # Logging utilities
|
||||
│ ├── performance.py # Performance monitoring
|
||||
│ └── validators.py # Input validation
|
||||
├── tests/ # Unit tests
|
||||
│ ├── __init__.py
|
||||
│ ├── test_greetings.py
|
||||
│ ├── test_formatters.py
|
||||
│ └── test_utils.py
|
||||
├── requirements.txt # Project dependencies
|
||||
├── setup.py # Package configuration
|
||||
└── README.md # This file
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
### From source:
|
||||
```bash
|
||||
# Clone the repository
|
||||
git clone <repository-url>
|
||||
cd python-hello-complex
|
||||
|
||||
# Install in development mode
|
||||
pip install -e .
|
||||
|
||||
# Or install with all extras
|
||||
pip install -e ".[dev,color,env]"
|
||||
```
|
||||
|
||||
### Using pip:
|
||||
```bash
|
||||
pip install complex-hello-world
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### Basic usage:
|
||||
```bash
|
||||
python main.py
|
||||
# Output: Hello, World!
|
||||
```
|
||||
|
||||
### With custom name:
|
||||
```bash
|
||||
python main.py Alice
|
||||
# Output: Hello, Alice!
|
||||
```
|
||||
|
||||
### Different language:
|
||||
```bash
|
||||
python main.py --language spanish Maria
|
||||
# Output: ¡Hola, Maria!
|
||||
```
|
||||
|
||||
### With formatting:
|
||||
```bash
|
||||
python main.py --format bold John
|
||||
# Output: **Hello, John!** (in bold)
|
||||
|
||||
python main.py --format color --language french Pierre
|
||||
# Output: Bonjour, Pierre! (in color)
|
||||
|
||||
python main.py --format ascii_art World
|
||||
# Output:
|
||||
# ******************
|
||||
# * Hello, World! *
|
||||
# ******************
|
||||
```
|
||||
|
||||
### With timestamp:
|
||||
```bash
|
||||
python main.py --timestamp Alice
|
||||
# Output: [2024-01-15 10:30:45] Hello, Alice!
|
||||
```
|
||||
|
||||
### Full example:
|
||||
```bash
|
||||
python main.py --language japanese --format color --timestamp --log-level DEBUG Yuki
|
||||
```
|
||||
|
||||
## Command-line Arguments
|
||||
|
||||
- `name` (positional): Name to greet (default: "World")
|
||||
- `-l, --language`: Language for greeting (choices: english, spanish, french, german, japanese)
|
||||
- `-f, --format`: Output format (choices: plain, bold, color, ascii_art)
|
||||
- `-t, --timestamp`: Include timestamp in output
|
||||
- `--log-level`: Logging level (choices: DEBUG, INFO, WARNING, ERROR)
|
||||
|
||||
## Development
|
||||
|
||||
### Running tests:
|
||||
```bash
|
||||
# Run all tests
|
||||
python -m pytest
|
||||
|
||||
# Run with coverage
|
||||
python -m pytest --cov=src --cov-report=html
|
||||
|
||||
# Run specific test file
|
||||
python -m pytest tests/test_greetings.py
|
||||
```
|
||||
|
||||
### Code quality:
|
||||
```bash
|
||||
# Format code
|
||||
black .
|
||||
|
||||
# Sort imports
|
||||
isort .
|
||||
|
||||
# Lint code
|
||||
flake8 .
|
||||
|
||||
# Type checking
|
||||
mypy .
|
||||
```
|
||||
|
||||
## Design Patterns
|
||||
|
||||
This application demonstrates several design patterns:
|
||||
|
||||
1. **Strategy Pattern**: Different greeting implementations for each language
|
||||
2. **Factory Pattern**: Creation of greeting and formatter objects
|
||||
3. **Decorator Pattern**: Performance measurement decorator
|
||||
4. **Template Method**: Abstract base classes for greetings and formatters
|
||||
5. **Singleton Pattern**: Logger instance management
|
||||
6. **Dependency Injection**: Settings injection into application
|
||||
|
||||
## Extending the Application
|
||||
|
||||
### Adding a new language:
|
||||
1. Create a new class in `src/greetings/strategies.py` inheriting from `GreetingStrategy`
|
||||
2. Implement the `greet()` method and `language` property
|
||||
3. Register it in `GreetingFactory` in `src/greetings/greeting_factory.py`
|
||||
4. Add it to the CLI choices in `main.py`
|
||||
|
||||
### Adding a new format:
|
||||
1. Create a new class in `src/formatters/styles.py` inheriting from `TextFormatter`
|
||||
2. Implement the `format()` method and `style_name` property
|
||||
3. Register it in `FormatterFactory` in `src/formatters/formatter_factory.py`
|
||||
4. Add it to the CLI choices in `main.py`
|
||||
|
||||
## License
|
||||
|
||||
MIT License - see LICENSE file for details.
|
||||
Whitespace-only changes.
@@ -0,0 +1,53 @@
|
||||
"""Application settings and configuration."""
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
|
||||
@dataclass
|
||||
class Settings:
|
||||
"""Application settings container."""
|
||||
|
||||
# Logging configuration
|
||||
log_level: str = "INFO"
|
||||
log_format: str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
|
||||
# Application metadata
|
||||
app_name: str = "Complex Hello World"
|
||||
app_version: str = "1.0.0"
|
||||
|
||||
# Performance settings
|
||||
enable_performance_logging: bool = True
|
||||
|
||||
# Output settings
|
||||
default_language: str = "english"
|
||||
default_format: str = "plain"
|
||||
|
||||
# File paths
|
||||
log_file: Optional[str] = None
|
||||
|
||||
def __post_init__(self):
|
||||
"""Validate and process settings after initialization."""
|
||||
# Ensure log level is uppercase
|
||||
self.log_level = self.log_level.upper()
|
||||
|
||||
# Set log file path if not provided
|
||||
if self.log_file is None:
|
||||
self.log_file = os.path.join(
|
||||
os.path.dirname(os.path.dirname(__file__)),
|
||||
"logs",
|
||||
"app.log"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_env(cls):
|
||||
"""Create settings from environment variables."""
|
||||
return cls(
|
||||
log_level=os.getenv("HELLO_LOG_LEVEL", "INFO"),
|
||||
default_language=os.getenv("HELLO_DEFAULT_LANGUAGE", "english"),
|
||||
default_format=os.getenv("HELLO_DEFAULT_FORMAT", "plain"),
|
||||
enable_performance_logging=os.getenv(
|
||||
"HELLO_ENABLE_PERFORMANCE", "true"
|
||||
).lower() == "true"
|
||||
)
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Complex Hello World Application
|
||||
A sophisticated multi-module Python application demonstrating advanced patterns.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import argparse
|
||||
from datetime import datetime
|
||||
from src.greetings.greeting_factory import GreetingFactory
|
||||
from src.formatters.formatter_factory import FormatterFactory
|
||||
from src.utils.logger import Logger
|
||||
from src.utils.performance import measure_performance
|
||||
from config.settings import Settings
|
||||
|
||||
|
||||
class HelloWorldApplication:
|
||||
"""Main application class for the complex Hello World system."""
|
||||
|
||||
def __init__(self, settings: Settings):
|
||||
self.settings = settings
|
||||
self.logger = Logger(settings.log_level)
|
||||
self.greeting_factory = GreetingFactory()
|
||||
self.formatter_factory = FormatterFactory()
|
||||
|
||||
@measure_performance
|
||||
def run(self, args):
|
||||
"""Execute the main application logic."""
|
||||
try:
|
||||
self.logger.info("Starting Hello World Application")
|
||||
|
||||
# Get appropriate greeting
|
||||
greeting_strategy = self.greeting_factory.get_greeting(args.language)
|
||||
message = greeting_strategy.greet(args.name)
|
||||
|
||||
# Apply formatting
|
||||
formatter = self.formatter_factory.get_formatter(args.format)
|
||||
formatted_message = formatter.format(message)
|
||||
|
||||
# Add timestamp if requested
|
||||
if args.timestamp:
|
||||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
formatted_message = f"[{timestamp}] {formatted_message}"
|
||||
|
||||
# Output the result
|
||||
print(formatted_message)
|
||||
|
||||
# Log success
|
||||
self.logger.info(f"Successfully greeted {args.name} in {args.language}")
|
||||
|
||||
return 0
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"Application error: {str(e)}")
|
||||
return 1
|
||||
|
||||
|
||||
def parse_arguments():
|
||||
"""Parse command line arguments."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description="A complex Hello World application with multiple features"
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"name",
|
||||
nargs="?",
|
||||
default="World",
|
||||
help="Name to greet (default: World)"
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"-l", "--language",
|
||||
choices=["english", "spanish", "french", "german", "japanese"],
|
||||
default="english",
|
||||
help="Language for greeting (default: english)"
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"-f", "--format",
|
||||
choices=["plain", "bold", "color", "ascii_art"],
|
||||
default="plain",
|
||||
help="Output format (default: plain)"
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"-t", "--timestamp",
|
||||
action="store_true",
|
||||
help="Include timestamp in output"
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--log-level",
|
||||
choices=["DEBUG", "INFO", "WARNING", "ERROR"],
|
||||
default="INFO",
|
||||
help="Logging level (default: INFO)"
|
||||
)
|
||||
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point for the application."""
|
||||
args = parse_arguments()
|
||||
|
||||
# Initialize settings
|
||||
settings = Settings(log_level=args.log_level)
|
||||
|
||||
# Create and run application
|
||||
app = HelloWorldApplication(settings)
|
||||
return app.run(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,14 @@
|
||||
# Core dependencies
|
||||
# No external dependencies required for this example
|
||||
|
||||
# Development dependencies
|
||||
pytest>=7.0.0
|
||||
pytest-cov>=4.0.0
|
||||
black>=22.0.0
|
||||
flake8>=5.0.0
|
||||
mypy>=0.990
|
||||
isort>=5.10.0
|
||||
|
||||
# Optional dependencies for enhanced features
|
||||
colorama>=0.4.6 # For cross-platform colored output
|
||||
python-dotenv>=0.19.0 # For environment variable management
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Setup configuration for Complex Hello World application."""
|
||||
|
||||
from setuptools import setup, find_packages
|
||||
|
||||
with open("README.md", "r", encoding="utf-8") as fh:
|
||||
long_description = fh.read()
|
||||
|
||||
setup(
|
||||
name="complex-hello-world",
|
||||
version="1.0.0",
|
||||
author="Hello World Team",
|
||||
author_email="hello@example.com",
|
||||
description="A sophisticated multi-module Python Hello World application",
|
||||
long_description=long_description,
|
||||
long_description_content_type="text/markdown",
|
||||
url="https://github.com/example/complex-hello-world",
|
||||
packages=find_packages(),
|
||||
classifiers=[
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
"Intended Audience :: Developers",
|
||||
"Topic :: Software Development :: Libraries :: Python Modules",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
],
|
||||
python_requires=">=3.8",
|
||||
install_requires=[
|
||||
# Core dependencies (none required for basic functionality)
|
||||
],
|
||||
extras_require={
|
||||
"dev": [
|
||||
"pytest>=7.0.0",
|
||||
"pytest-cov>=4.0.0",
|
||||
"black>=22.0.0",
|
||||
"flake8>=5.0.0",
|
||||
"mypy>=0.990",
|
||||
"isort>=5.10.0",
|
||||
],
|
||||
"color": [
|
||||
"colorama>=0.4.6",
|
||||
],
|
||||
"env": [
|
||||
"python-dotenv>=0.19.0",
|
||||
],
|
||||
},
|
||||
entry_points={
|
||||
"console_scripts": [
|
||||
"hello-complex=main:main",
|
||||
],
|
||||
},
|
||||
include_package_data=True,
|
||||
zip_safe=False,
|
||||
)
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,25 @@
|
||||
"""Base classes for text formatters."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
|
||||
class TextFormatter(ABC):
|
||||
"""Abstract base class for text formatters."""
|
||||
|
||||
@abstractmethod
|
||||
def format(self, text: str) -> str:
|
||||
"""Format the given text.
|
||||
|
||||
Args:
|
||||
text: The text to format.
|
||||
|
||||
Returns:
|
||||
The formatted text.
|
||||
"""
|
||||
pass
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def style_name(self) -> str:
|
||||
"""Get the name of this formatting style."""
|
||||
pass
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Factory for creating text formatters."""
|
||||
|
||||
from typing import Dict, Type
|
||||
from .base import TextFormatter
|
||||
from .styles import (
|
||||
PlainFormatter,
|
||||
BoldFormatter,
|
||||
ColorFormatter,
|
||||
AsciiArtFormatter
|
||||
)
|
||||
|
||||
|
||||
class FormatterFactory:
|
||||
"""Factory class for creating text formatters."""
|
||||
|
||||
def __init__(self):
|
||||
self._formatters: Dict[str, Type[TextFormatter]] = {
|
||||
"plain": PlainFormatter,
|
||||
"bold": BoldFormatter,
|
||||
"color": ColorFormatter,
|
||||
"ascii_art": AsciiArtFormatter
|
||||
}
|
||||
|
||||
def get_formatter(self, style: str) -> TextFormatter:
|
||||
"""Get a text formatter for the specified style.
|
||||
|
||||
Args:
|
||||
style: The formatting style identifier.
|
||||
|
||||
Returns:
|
||||
An instance of the appropriate text formatter.
|
||||
|
||||
Raises:
|
||||
ValueError: If the style is not supported.
|
||||
"""
|
||||
style = style.lower()
|
||||
if style not in self._formatters:
|
||||
raise ValueError(f"Unsupported formatting style: {style}")
|
||||
|
||||
return self._formatters[style]()
|
||||
|
||||
def list_styles(self) -> list:
|
||||
"""Get a list of supported formatting styles."""
|
||||
return list(self._formatters.keys())
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Concrete text formatter implementations."""
|
||||
|
||||
import random
|
||||
from .base import TextFormatter
|
||||
|
||||
|
||||
class PlainFormatter(TextFormatter):
|
||||
"""Plain text formatter (no formatting)."""
|
||||
|
||||
def format(self, text: str) -> str:
|
||||
return text
|
||||
|
||||
@property
|
||||
def style_name(self) -> str:
|
||||
return "Plain"
|
||||
|
||||
|
||||
class BoldFormatter(TextFormatter):
|
||||
"""Bold text formatter using ANSI escape codes."""
|
||||
|
||||
def format(self, text: str) -> str:
|
||||
return f"\033[1m{text}\033[0m"
|
||||
|
||||
@property
|
||||
def style_name(self) -> str:
|
||||
return "Bold"
|
||||
|
||||
|
||||
class ColorFormatter(TextFormatter):
|
||||
"""Colorful text formatter using ANSI escape codes."""
|
||||
|
||||
def __init__(self):
|
||||
self.colors = [
|
||||
'\033[91m', # Red
|
||||
'\033[92m', # Green
|
||||
'\033[93m', # Yellow
|
||||
'\033[94m', # Blue
|
||||
'\033[95m', # Magenta
|
||||
'\033[96m', # Cyan
|
||||
]
|
||||
|
||||
def format(self, text: str) -> str:
|
||||
color = random.choice(self.colors)
|
||||
return f"{color}{text}\033[0m"
|
||||
|
||||
@property
|
||||
def style_name(self) -> str:
|
||||
return "Color"
|
||||
|
||||
|
||||
class AsciiArtFormatter(TextFormatter):
|
||||
"""ASCII art text formatter."""
|
||||
|
||||
def format(self, text: str) -> str:
|
||||
# Simple ASCII art border
|
||||
border = "*" * (len(text) + 4)
|
||||
return f"""
|
||||
{border}
|
||||
* {text} *
|
||||
{border}
|
||||
""".strip()
|
||||
|
||||
@property
|
||||
def style_name(self) -> str:
|
||||
return "ASCII Art"
|
||||
Whitespace-only changes.
@@ -0,0 +1,25 @@
|
||||
"""Base classes for greeting strategies."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
|
||||
class GreetingStrategy(ABC):
|
||||
"""Abstract base class for greeting strategies."""
|
||||
|
||||
@abstractmethod
|
||||
def greet(self, name: str) -> str:
|
||||
"""Generate a greeting message.
|
||||
|
||||
Args:
|
||||
name: The name to include in the greeting.
|
||||
|
||||
Returns:
|
||||
The greeting message.
|
||||
"""
|
||||
pass
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def language(self) -> str:
|
||||
"""Get the language name for this greeting."""
|
||||
pass
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Factory for creating greeting strategies."""
|
||||
|
||||
from typing import Dict, Type
|
||||
from .base import GreetingStrategy
|
||||
from .strategies import (
|
||||
EnglishGreeting,
|
||||
SpanishGreeting,
|
||||
FrenchGreeting,
|
||||
GermanGreeting,
|
||||
JapaneseGreeting
|
||||
)
|
||||
|
||||
|
||||
class GreetingFactory:
|
||||
"""Factory class for creating greeting strategies."""
|
||||
|
||||
def __init__(self):
|
||||
self._strategies: Dict[str, Type[GreetingStrategy]] = {
|
||||
"english": EnglishGreeting,
|
||||
"spanish": SpanishGreeting,
|
||||
"french": FrenchGreeting,
|
||||
"german": GermanGreeting,
|
||||
"japanese": JapaneseGreeting
|
||||
}
|
||||
|
||||
def get_greeting(self, language: str) -> GreetingStrategy:
|
||||
"""Get a greeting strategy for the specified language.
|
||||
|
||||
Args:
|
||||
language: The language identifier.
|
||||
|
||||
Returns:
|
||||
An instance of the appropriate greeting strategy.
|
||||
|
||||
Raises:
|
||||
ValueError: If the language is not supported.
|
||||
"""
|
||||
language = language.lower()
|
||||
if language not in self._strategies:
|
||||
raise ValueError(f"Unsupported language: {language}")
|
||||
|
||||
return self._strategies[language]()
|
||||
|
||||
def list_languages(self) -> list:
|
||||
"""Get a list of supported languages."""
|
||||
return list(self._strategies.keys())
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Concrete greeting strategy implementations."""
|
||||
|
||||
from .base import GreetingStrategy
|
||||
|
||||
|
||||
class EnglishGreeting(GreetingStrategy):
|
||||
"""English greeting implementation."""
|
||||
|
||||
def greet(self, name: str) -> str:
|
||||
return f"Hello, {name}!"
|
||||
|
||||
@property
|
||||
def language(self) -> str:
|
||||
return "English"
|
||||
|
||||
|
||||
class SpanishGreeting(GreetingStrategy):
|
||||
"""Spanish greeting implementation."""
|
||||
|
||||
def greet(self, name: str) -> str:
|
||||
return f"¡Hola, {name}!"
|
||||
|
||||
@property
|
||||
def language(self) -> str:
|
||||
return "Spanish"
|
||||
|
||||
|
||||
class FrenchGreeting(GreetingStrategy):
|
||||
"""French greeting implementation."""
|
||||
|
||||
def greet(self, name: str) -> str:
|
||||
return f"Bonjour, {name}!"
|
||||
|
||||
@property
|
||||
def language(self) -> str:
|
||||
return "French"
|
||||
|
||||
|
||||
class GermanGreeting(GreetingStrategy):
|
||||
"""German greeting implementation."""
|
||||
|
||||
def greet(self, name: str) -> str:
|
||||
return f"Hallo, {name}!"
|
||||
|
||||
@property
|
||||
def language(self) -> str:
|
||||
return "German"
|
||||
|
||||
|
||||
class JapaneseGreeting(GreetingStrategy):
|
||||
"""Japanese greeting implementation."""
|
||||
|
||||
def greet(self, name: str) -> str:
|
||||
return f"こんにちは、{name}さん!"
|
||||
|
||||
@property
|
||||
def language(self) -> str:
|
||||
return "Japanese"
|
||||
Whitespace-only changes.
@@ -0,0 +1,65 @@
|
||||
"""Logging utilities for the application."""
|
||||
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class Logger:
|
||||
"""Custom logger wrapper with enhanced functionality."""
|
||||
|
||||
def __init__(self, level: str = "INFO", log_file: Optional[str] = None):
|
||||
"""Initialize the logger.
|
||||
|
||||
Args:
|
||||
level: The logging level.
|
||||
log_file: Optional path to a log file.
|
||||
"""
|
||||
self.logger = logging.getLogger("HelloWorld")
|
||||
self.logger.setLevel(getattr(logging, level.upper()))
|
||||
|
||||
# Remove existing handlers
|
||||
self.logger.handlers.clear()
|
||||
|
||||
# Console handler
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setLevel(logging.DEBUG)
|
||||
|
||||
# Formatter
|
||||
formatter = logging.Formatter(
|
||||
'%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S'
|
||||
)
|
||||
console_handler.setFormatter(formatter)
|
||||
self.logger.addHandler(console_handler)
|
||||
|
||||
# File handler if specified
|
||||
if log_file:
|
||||
log_path = Path(log_file)
|
||||
log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
file_handler = logging.FileHandler(log_file)
|
||||
file_handler.setLevel(logging.DEBUG)
|
||||
file_handler.setFormatter(formatter)
|
||||
self.logger.addHandler(file_handler)
|
||||
|
||||
def debug(self, message: str):
|
||||
"""Log a debug message."""
|
||||
self.logger.debug(message)
|
||||
|
||||
def info(self, message: str):
|
||||
"""Log an info message."""
|
||||
self.logger.info(message)
|
||||
|
||||
def warning(self, message: str):
|
||||
"""Log a warning message."""
|
||||
self.logger.warning(message)
|
||||
|
||||
def error(self, message: str):
|
||||
"""Log an error message."""
|
||||
self.logger.error(message)
|
||||
|
||||
def critical(self, message: str):
|
||||
"""Log a critical message."""
|
||||
self.logger.critical(message)
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Performance monitoring utilities."""
|
||||
|
||||
import time
|
||||
import functools
|
||||
from typing import Callable, Any
|
||||
|
||||
|
||||
def measure_performance(func: Callable) -> Callable:
|
||||
"""Decorator to measure function execution time.
|
||||
|
||||
Args:
|
||||
func: The function to measure.
|
||||
|
||||
Returns:
|
||||
The wrapped function.
|
||||
"""
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs) -> Any:
|
||||
start_time = time.perf_counter()
|
||||
|
||||
try:
|
||||
result = func(*args, **kwargs)
|
||||
return result
|
||||
finally:
|
||||
end_time = time.perf_counter()
|
||||
execution_time = end_time - start_time
|
||||
|
||||
# Try to log if logger is available
|
||||
if hasattr(args[0], 'logger'):
|
||||
args[0].logger.debug(
|
||||
f"{func.__name__} executed in {execution_time:.4f} seconds"
|
||||
)
|
||||
else:
|
||||
print(f"Performance: {func.__name__} took {execution_time:.4f}s")
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
class PerformanceTimer:
|
||||
"""Context manager for timing code blocks."""
|
||||
|
||||
def __init__(self, name: str = "Operation"):
|
||||
self.name = name
|
||||
self.start_time = None
|
||||
self.end_time = None
|
||||
|
||||
def __enter__(self):
|
||||
self.start_time = time.perf_counter()
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
self.end_time = time.perf_counter()
|
||||
self.elapsed = self.end_time - self.start_time
|
||||
print(f"{self.name} completed in {self.elapsed:.4f} seconds")
|
||||
|
||||
@property
|
||||
def elapsed_time(self) -> float:
|
||||
"""Get the elapsed time."""
|
||||
if self.end_time is None:
|
||||
return time.perf_counter() - self.start_time
|
||||
return self.elapsed
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Input validation utilities."""
|
||||
|
||||
import re
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class InputValidator:
|
||||
"""Validator for user inputs."""
|
||||
|
||||
@staticmethod
|
||||
def validate_name(name: str) -> bool:
|
||||
"""Validate that a name contains only valid characters.
|
||||
|
||||
Args:
|
||||
name: The name to validate.
|
||||
|
||||
Returns:
|
||||
True if valid, False otherwise.
|
||||
"""
|
||||
if not name or not name.strip():
|
||||
return False
|
||||
|
||||
# Allow letters, spaces, hyphens, and apostrophes
|
||||
pattern = r"^[a-zA-Z\s\-']+$"
|
||||
return bool(re.match(pattern, name))
|
||||
|
||||
@staticmethod
|
||||
def sanitize_name(name: str) -> str:
|
||||
"""Sanitize a name by removing invalid characters.
|
||||
|
||||
Args:
|
||||
name: The name to sanitize.
|
||||
|
||||
Returns:
|
||||
The sanitized name.
|
||||
"""
|
||||
# Remove any characters that aren't letters, spaces, hyphens, or apostrophes
|
||||
sanitized = re.sub(r"[^a-zA-Z\s\-']", "", name)
|
||||
|
||||
# Collapse multiple spaces
|
||||
sanitized = re.sub(r'\s+', ' ', sanitized)
|
||||
|
||||
return sanitized.strip()
|
||||
|
||||
@staticmethod
|
||||
def validate_language_code(code: str, supported_languages: list) -> bool:
|
||||
"""Validate that a language code is supported.
|
||||
|
||||
Args:
|
||||
code: The language code to validate.
|
||||
supported_languages: List of supported language codes.
|
||||
|
||||
Returns:
|
||||
True if valid, False otherwise.
|
||||
"""
|
||||
return code.lower() in [lang.lower() for lang in supported_languages]
|
||||
Whitespace-only changes.
@@ -0,0 +1,93 @@
|
||||
"""Unit tests for text formatters."""
|
||||
|
||||
import unittest
|
||||
from src.formatters.styles import (
|
||||
PlainFormatter,
|
||||
BoldFormatter,
|
||||
ColorFormatter,
|
||||
AsciiArtFormatter
|
||||
)
|
||||
from src.formatters.formatter_factory import FormatterFactory
|
||||
|
||||
|
||||
class TestTextFormatters(unittest.TestCase):
|
||||
"""Test cases for text formatters."""
|
||||
|
||||
def test_plain_formatter(self):
|
||||
"""Test plain text formatter."""
|
||||
formatter = PlainFormatter()
|
||||
text = "Hello, World!"
|
||||
self.assertEqual(formatter.format(text), text)
|
||||
self.assertEqual(formatter.style_name, "Plain")
|
||||
|
||||
def test_bold_formatter(self):
|
||||
"""Test bold text formatter."""
|
||||
formatter = BoldFormatter()
|
||||
text = "Hello, World!"
|
||||
formatted = formatter.format(text)
|
||||
self.assertTrue(formatted.startswith("\033[1m"))
|
||||
self.assertTrue(formatted.endswith("\033[0m"))
|
||||
self.assertIn(text, formatted)
|
||||
self.assertEqual(formatter.style_name, "Bold")
|
||||
|
||||
def test_color_formatter(self):
|
||||
"""Test color text formatter."""
|
||||
formatter = ColorFormatter()
|
||||
text = "Hello, World!"
|
||||
formatted = formatter.format(text)
|
||||
self.assertTrue(formatted.startswith("\033[9"))
|
||||
self.assertTrue(formatted.endswith("\033[0m"))
|
||||
self.assertIn(text, formatted)
|
||||
self.assertEqual(formatter.style_name, "Color")
|
||||
|
||||
def test_ascii_art_formatter(self):
|
||||
"""Test ASCII art formatter."""
|
||||
formatter = AsciiArtFormatter()
|
||||
text = "Hello!"
|
||||
formatted = formatter.format(text)
|
||||
self.assertIn(text, formatted)
|
||||
self.assertIn("*", formatted)
|
||||
self.assertEqual(formatter.style_name, "ASCII Art")
|
||||
|
||||
|
||||
class TestFormatterFactory(unittest.TestCase):
|
||||
"""Test cases for formatter factory."""
|
||||
|
||||
def setUp(self):
|
||||
"""Set up test fixtures."""
|
||||
self.factory = FormatterFactory()
|
||||
|
||||
def test_get_formatter_valid_styles(self):
|
||||
"""Test getting formatters for valid styles."""
|
||||
styles = ["plain", "bold", "color", "ascii_art"]
|
||||
|
||||
for style in styles:
|
||||
formatter = self.factory.get_formatter(style)
|
||||
self.assertIsNotNone(formatter)
|
||||
self.assertTrue(hasattr(formatter, 'format'))
|
||||
|
||||
def test_get_formatter_case_insensitive(self):
|
||||
"""Test that style selection is case-insensitive."""
|
||||
formatter1 = self.factory.get_formatter("PLAIN")
|
||||
formatter2 = self.factory.get_formatter("plain")
|
||||
formatter3 = self.factory.get_formatter("Plain")
|
||||
|
||||
self.assertEqual(type(formatter1), type(formatter2))
|
||||
self.assertEqual(type(formatter2), type(formatter3))
|
||||
|
||||
def test_get_formatter_invalid_style(self):
|
||||
"""Test getting formatter for invalid style."""
|
||||
with self.assertRaises(ValueError):
|
||||
self.factory.get_formatter("rainbow")
|
||||
|
||||
def test_list_styles(self):
|
||||
"""Test listing supported styles."""
|
||||
styles = self.factory.list_styles()
|
||||
self.assertIsInstance(styles, list)
|
||||
self.assertIn("plain", styles)
|
||||
self.assertIn("bold", styles)
|
||||
self.assertEqual(len(styles), 4)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Unit tests for greeting strategies."""
|
||||
|
||||
import unittest
|
||||
from src.greetings.strategies import (
|
||||
EnglishGreeting,
|
||||
SpanishGreeting,
|
||||
FrenchGreeting,
|
||||
GermanGreeting,
|
||||
JapaneseGreeting
|
||||
)
|
||||
from src.greetings.greeting_factory import GreetingFactory
|
||||
|
||||
|
||||
class TestGreetingStrategies(unittest.TestCase):
|
||||
"""Test cases for greeting strategies."""
|
||||
|
||||
def test_english_greeting(self):
|
||||
"""Test English greeting."""
|
||||
greeting = EnglishGreeting()
|
||||
self.assertEqual(greeting.greet("Alice"), "Hello, Alice!")
|
||||
self.assertEqual(greeting.language, "English")
|
||||
|
||||
def test_spanish_greeting(self):
|
||||
"""Test Spanish greeting."""
|
||||
greeting = SpanishGreeting()
|
||||
self.assertEqual(greeting.greet("Carlos"), "¡Hola, Carlos!")
|
||||
self.assertEqual(greeting.language, "Spanish")
|
||||
|
||||
def test_french_greeting(self):
|
||||
"""Test French greeting."""
|
||||
greeting = FrenchGreeting()
|
||||
self.assertEqual(greeting.greet("Marie"), "Bonjour, Marie!")
|
||||
self.assertEqual(greeting.language, "French")
|
||||
|
||||
def test_german_greeting(self):
|
||||
"""Test German greeting."""
|
||||
greeting = GermanGreeting()
|
||||
self.assertEqual(greeting.greet("Hans"), "Hallo, Hans!")
|
||||
self.assertEqual(greeting.language, "German")
|
||||
|
||||
def test_japanese_greeting(self):
|
||||
"""Test Japanese greeting."""
|
||||
greeting = JapaneseGreeting()
|
||||
self.assertEqual(greeting.greet("Yuki"), "こんにちは、Yukiさん!")
|
||||
self.assertEqual(greeting.language, "Japanese")
|
||||
|
||||
|
||||
class TestGreetingFactory(unittest.TestCase):
|
||||
"""Test cases for greeting factory."""
|
||||
|
||||
def setUp(self):
|
||||
"""Set up test fixtures."""
|
||||
self.factory = GreetingFactory()
|
||||
|
||||
def test_get_greeting_valid_languages(self):
|
||||
"""Test getting greetings for valid languages."""
|
||||
languages = ["english", "spanish", "french", "german", "japanese"]
|
||||
|
||||
for lang in languages:
|
||||
greeting = self.factory.get_greeting(lang)
|
||||
self.assertIsNotNone(greeting)
|
||||
self.assertTrue(hasattr(greeting, 'greet'))
|
||||
|
||||
def test_get_greeting_case_insensitive(self):
|
||||
"""Test that language selection is case-insensitive."""
|
||||
greeting1 = self.factory.get_greeting("ENGLISH")
|
||||
greeting2 = self.factory.get_greeting("english")
|
||||
greeting3 = self.factory.get_greeting("English")
|
||||
|
||||
self.assertEqual(type(greeting1), type(greeting2))
|
||||
self.assertEqual(type(greeting2), type(greeting3))
|
||||
|
||||
def test_get_greeting_invalid_language(self):
|
||||
"""Test getting greeting for invalid language."""
|
||||
with self.assertRaises(ValueError):
|
||||
self.factory.get_greeting("klingon")
|
||||
|
||||
def test_list_languages(self):
|
||||
"""Test listing supported languages."""
|
||||
languages = self.factory.list_languages()
|
||||
self.assertIsInstance(languages, list)
|
||||
self.assertIn("english", languages)
|
||||
self.assertIn("spanish", languages)
|
||||
self.assertEqual(len(languages), 5)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Unit tests for utility modules."""
|
||||
|
||||
import unittest
|
||||
import time
|
||||
from src.utils.validators import InputValidator
|
||||
from src.utils.performance import measure_performance, PerformanceTimer
|
||||
|
||||
|
||||
class TestInputValidator(unittest.TestCase):
|
||||
"""Test cases for input validator."""
|
||||
|
||||
def test_validate_name_valid(self):
|
||||
"""Test validation of valid names."""
|
||||
valid_names = [
|
||||
"John",
|
||||
"Mary Jane",
|
||||
"Jean-Pierre",
|
||||
"O'Connor",
|
||||
"Anne-Marie"
|
||||
]
|
||||
|
||||
for name in valid_names:
|
||||
self.assertTrue(
|
||||
InputValidator.validate_name(name),
|
||||
f"'{name}' should be valid"
|
||||
)
|
||||
|
||||
def test_validate_name_invalid(self):
|
||||
"""Test validation of invalid names."""
|
||||
invalid_names = [
|
||||
"",
|
||||
" ",
|
||||
"John123",
|
||||
"User@Name",
|
||||
"Name!",
|
||||
"Test#Name"
|
||||
]
|
||||
|
||||
for name in invalid_names:
|
||||
self.assertFalse(
|
||||
InputValidator.validate_name(name),
|
||||
f"'{name}' should be invalid"
|
||||
)
|
||||
|
||||
def test_sanitize_name(self):
|
||||
"""Test name sanitization."""
|
||||
test_cases = [
|
||||
("John123", "John"),
|
||||
("Mary@Jane", "MaryJane"),
|
||||
("Test!Name#", "TestName"),
|
||||
("Jean Pierre", "Jean Pierre"),
|
||||
(" Space Test ", "Space Test")
|
||||
]
|
||||
|
||||
for input_name, expected in test_cases:
|
||||
result = InputValidator.sanitize_name(input_name)
|
||||
self.assertEqual(result, expected)
|
||||
|
||||
def test_validate_language_code(self):
|
||||
"""Test language code validation."""
|
||||
supported = ["en", "es", "fr", "de", "ja"]
|
||||
|
||||
# Valid codes
|
||||
self.assertTrue(InputValidator.validate_language_code("en", supported))
|
||||
self.assertTrue(InputValidator.validate_language_code("ES", supported))
|
||||
|
||||
# Invalid codes
|
||||
self.assertFalse(InputValidator.validate_language_code("ru", supported))
|
||||
self.assertFalse(InputValidator.validate_language_code("xyz", supported))
|
||||
|
||||
|
||||
class TestPerformanceUtilities(unittest.TestCase):
|
||||
"""Test cases for performance utilities."""
|
||||
|
||||
def test_performance_timer(self):
|
||||
"""Test performance timer context manager."""
|
||||
with PerformanceTimer("Test Operation") as timer:
|
||||
time.sleep(0.1)
|
||||
|
||||
self.assertIsNotNone(timer.elapsed)
|
||||
self.assertGreater(timer.elapsed, 0.09)
|
||||
self.assertLess(timer.elapsed, 0.2)
|
||||
|
||||
def test_measure_performance_decorator(self):
|
||||
"""Test performance measurement decorator."""
|
||||
|
||||
class MockObject:
|
||||
def __init__(self):
|
||||
self.call_count = 0
|
||||
|
||||
@measure_performance
|
||||
def slow_method(self, duration):
|
||||
self.call_count += 1
|
||||
time.sleep(duration)
|
||||
return self.call_count
|
||||
|
||||
obj = MockObject()
|
||||
result = obj.slow_method(0.05)
|
||||
|
||||
self.assertEqual(result, 1)
|
||||
self.assertEqual(obj.call_count, 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user