diff --git a/docs/api-reference.md b/docs/api-reference.md new file mode 100644 index 0000000..7bb4e7c --- /dev/null +++ b/docs/api-reference.md @@ -0,0 +1,603 @@ +# API Reference + +Use **speedtest-cli** as a Python library to integrate network speed testing into your own applications. + +## Installation for Library Use + +Install speedtest-cli in your Python project: + +```bash +# Using pip +pip install speedtest-cloudflare-cli + +# Using poetry +poetry add speedtest-cloudflare-cli + +# Using uv +uv add speedtest-cloudflare-cli +``` + +## Quick Start + +### Basic Usage + +```python +from speedtest_cloudflare_cli.core.speedtest import SpeedTest + +# Create SpeedTest instance +test = SpeedTest() + +# Run complete speed test +results = test.run() + +# Access results +print(f"Download: {results.download} Mbps") +print(f"Upload: {results.upload} Mbps") +print(f"Ping: {results.ping} ms") +print(f"Jitter: {results.jitter} ms") +``` + +### Download Only + +```python +from speedtest_cloudflare_cli.core.speedtest import SpeedTest + +test = SpeedTest(run_download=True, run_upload=False) +results = test.run() + +print(f"Download: {results.download} Mbps") +``` + +### Upload Only + +```python +from speedtest_cloudflare_cli.core.speedtest import SpeedTest + +test = SpeedTest(run_download=False, run_upload=True) +results = test.run() + +print(f"Upload: {results.upload} Mbps") +``` + +### Custom Test Sizes + +```python +from speedtest_cloudflare_cli.core.speedtest import SpeedTest + +test = SpeedTest( + download_size=50, # MB + upload_size=25, # MB +) +results = test.run() +``` + +### Silent Mode + +```python +from speedtest_cloudflare_cli.core.speedtest import SpeedTest + +test = SpeedTest(silent=True) +results = test.run() +# No progress bars or output, just results +``` + +## Core Classes + +### SpeedTest + +::: speedtest_cloudflare_cli.core.speedtest.SpeedTest + options: + show_root_heading: true + show_source: false + heading_level: 4 + +## Data Models + +### Result + +::: speedtest_cloudflare_cli.models.result.Result + options: + show_root_heading: true + show_source: false + heading_level: 4 + +### Metadata + +::: speedtest_cloudflare_cli.models.metadata.Metadata + options: + show_root_heading: true + show_source: false + heading_level: 4 + +## Advanced Examples + +### Error Handling + +```python +from speedtest_cloudflare_cli.core.speedtest import SpeedTest +import httpx + +try: + test = SpeedTest() + results = test.run() + print(f"Download: {results.download} Mbps") +except httpx.HTTPError as e: + print(f"Network error: {e}") +except Exception as e: + print(f"Error running speed test: {e}") +``` + +### Multiple Attempts + +```python +from speedtest_cloudflare_cli.core.speedtest import SpeedTest + +def run_multiple_tests(attempts=3): + """Run multiple speed tests and return average results.""" + download_speeds = [] + upload_speeds = [] + + for i in range(attempts): + print(f"Attempt {i+1}/{attempts}") + test = SpeedTest() + results = test.run() + + download_speeds.append(results.download) + upload_speeds.append(results.upload) + + avg_download = sum(download_speeds) / len(download_speeds) + avg_upload = sum(upload_speeds) / len(upload_speeds) + + return { + 'download': avg_download, + 'upload': avg_upload, + 'download_speeds': download_speeds, + 'upload_speeds': upload_speeds, + } + +# Usage +averages = run_multiple_tests(attempts=5) +print(f"Average Download: {averages['download']:.2f} Mbps") +print(f"Average Upload: {averages['upload']:.2f} Mbps") +``` + +### Accessing Metadata + +```python +from speedtest_cloudflare_cli.core.speedtest import SpeedTest + +test = SpeedTest() +results = test.run() + +# Access metadata +metadata = results.metadata +if metadata: + print(f"IP: {metadata.ip}") + print(f"ISP: {metadata.isp}") + print(f"Location: {metadata.city}, {metadata.region}, {metadata.country}") + print(f"Coordinates: {metadata.loc}") + print(f"Cloudflare Datacenter: {metadata.colo}") +``` + +### Export to JSON + +```python +from speedtest_cloudflare_cli.core.speedtest import SpeedTest +import json + +test = SpeedTest() +results = test.run() + +# Convert to dict for JSON serialization +results_dict = { + 'download': results.download, + 'upload': results.upload, + 'ping': results.ping, + 'jitter': results.jitter, + 'http_latency': results.http_latency, + 'metadata': { + 'ip': results.metadata.ip if results.metadata else None, + 'isp': results.metadata.isp if results.metadata else None, + 'city': results.metadata.city if results.metadata else None, + 'region': results.metadata.region if results.metadata else None, + 'country': results.metadata.country if results.metadata else None, + 'loc': results.metadata.loc if results.metadata else None, + 'colo': results.metadata.colo if results.metadata else None, + } if results.metadata else None +} + +# Save to file +with open('speedtest_results.json', 'w') as f: + json.dump(results_dict, f, indent=2) + +print("Results saved to speedtest_results.json") +``` + +### Custom Progress Callback + +```python +from speedtest_cloudflare_cli.core.speedtest import SpeedTest + +def progress_callback(progress: float, task: str): + """Custom progress callback.""" + print(f"{task}: {progress:.1f}%") + +# Note: This is conceptual - check actual API for progress hooks +test = SpeedTest() +results = test.run() +``` + +### Conditional Testing + +```python +from speedtest_cloudflare_cli.core.speedtest import SpeedTest + +def smart_speed_test(min_download=50, min_upload=10): + """ + Run speed test and alert if below thresholds. + + Args: + min_download: Minimum acceptable download speed (Mbps) + min_upload: Minimum acceptable upload speed (Mbps) + + Returns: + dict: Results and status + """ + test = SpeedTest() + results = test.run() + + download_ok = results.download >= min_download + upload_ok = results.upload >= min_upload + + status = { + 'download': results.download, + 'upload': results.upload, + 'download_ok': download_ok, + 'upload_ok': upload_ok, + 'overall_ok': download_ok and upload_ok, + } + + if not status['overall_ok']: + print("⚠️ Warning: Speed below threshold!") + if not download_ok: + print(f" Download: {results.download:.1f} Mbps (min: {min_download})") + if not upload_ok: + print(f" Upload: {results.upload:.1f} Mbps (min: {min_upload})") + else: + print("✓ Speed test passed!") + + return status + +# Usage +status = smart_speed_test(min_download=100, min_upload=20) +``` + +### Integration with Web Framework + +#### Flask Example + +```python +from flask import Flask, jsonify +from speedtest_cloudflare_cli.core.speedtest import SpeedTest + +app = Flask(__name__) + +@app.route('/api/speedtest', methods=['POST']) +def run_speedtest(): + """API endpoint to run speed test.""" + try: + test = SpeedTest(silent=True) + results = test.run() + + return jsonify({ + 'success': True, + 'data': { + 'download': results.download, + 'upload': results.upload, + 'ping': results.ping, + 'jitter': results.jitter, + 'http_latency': results.http_latency, + } + }) + except Exception as e: + return jsonify({ + 'success': False, + 'error': str(e) + }), 500 + +if __name__ == '__main__': + app.run() +``` + +#### FastAPI Example + +```python +from fastapi import FastAPI, HTTPException +from pydantic import BaseModel +from speedtest_cloudflare_cli.core.speedtest import SpeedTest + +app = FastAPI() + +class SpeedTestResult(BaseModel): + download: float + upload: float + ping: float + jitter: float + http_latency: float + +@app.post('/api/speedtest', response_model=SpeedTestResult) +async def run_speedtest(): + """API endpoint to run speed test.""" + try: + test = SpeedTest(silent=True) + results = test.run() + + return SpeedTestResult( + download=results.download, + upload=results.upload, + ping=results.ping, + jitter=results.jitter, + http_latency=results.http_latency, + ) + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) +``` + +### Background Task + +```python +import threading +from speedtest_cloudflare_cli.core.speedtest import SpeedTest + +def background_speedtest(callback): + """Run speed test in background thread.""" + def run(): + test = SpeedTest(silent=True) + results = test.run() + callback(results) + + thread = threading.Thread(target=run) + thread.start() + return thread + +# Usage +def on_complete(results): + print(f"Test complete! Download: {results.download} Mbps") + +thread = background_speedtest(on_complete) +print("Speed test running in background...") +thread.join() # Wait for completion +``` + +### Scheduled Testing + +```python +import schedule +import time +from speedtest_cloudflare_cli.core.speedtest import SpeedTest +import json +from datetime import datetime + +def scheduled_speed_test(): + """Run speed test and log results.""" + test = SpeedTest(silent=True) + results = test.run() + + log_entry = { + 'timestamp': datetime.now().isoformat(), + 'download': results.download, + 'upload': results.upload, + 'ping': results.ping, + } + + # Append to log file + with open('speedtest_log.jsonl', 'a') as f: + f.write(json.dumps(log_entry) + '\n') + + print(f"Logged: {log_entry}") + +# Schedule tests +schedule.every().hour.do(scheduled_speed_test) +schedule.every().day.at("02:00").do(scheduled_speed_test) + +print("Scheduler started. Press Ctrl+C to stop.") +while True: + schedule.run_pending() + time.sleep(60) +``` + +### Data Analysis + +```python +import json +import pandas as pd +from speedtest_cloudflare_cli.core.speedtest import SpeedTest + +def analyze_speed_history(log_file='speedtest_log.jsonl'): + """Analyze historical speed test data.""" + # Read log file + data = [] + with open(log_file) as f: + for line in f: + data.append(json.loads(line)) + + # Create DataFrame + df = pd.DataFrame(data) + df['timestamp'] = pd.to_datetime(df['timestamp']) + + # Calculate statistics + stats = { + 'download': { + 'mean': df['download'].mean(), + 'min': df['download'].min(), + 'max': df['download'].max(), + 'std': df['download'].std(), + }, + 'upload': { + 'mean': df['upload'].mean(), + 'min': df['upload'].min(), + 'max': df['upload'].max(), + 'std': df['upload'].std(), + }, + 'ping': { + 'mean': df['ping'].mean(), + 'min': df['ping'].min(), + 'max': df['ping'].max(), + 'std': df['ping'].std(), + } + } + + return stats, df + +# Usage +stats, df = analyze_speed_history() +print(f"Average Download: {stats['download']['mean']:.2f} Mbps") +print(f"Average Upload: {stats['upload']['mean']:.2f} Mbps") +print(f"Average Ping: {stats['ping']['mean']:.2f} ms") +``` + +## Type Hints + +The library uses comprehensive type hints for better IDE support: + +```python +from typing import Optional +from speedtest_cloudflare_cli.core.speedtest import SpeedTest +from speedtest_cloudflare_cli.models.result import Result + +def run_test(silent: bool = False) -> Optional[Result]: + """Run speed test with type hints.""" + test: SpeedTest = SpeedTest(silent=silent) + results: Result = test.run() + return results +``` + +## Best Practices + +### 1. Use Silent Mode in Production + +```python +# ✅ Good - no console output +test = SpeedTest(silent=True) + +# ❌ Bad - progress bars in production logs +test = SpeedTest(silent=False) +``` + +### 2. Handle Exceptions + +```python +# ✅ Good - proper error handling +try: + test = SpeedTest() + results = test.run() +except Exception as e: + logger.error(f"Speed test failed: {e}") + return None + +# ❌ Bad - no error handling +test = SpeedTest() +results = test.run() # May crash +``` + +### 3. Use Context Managers (if available) + +```python +# Check if context manager is supported +# (Conceptual - verify in actual implementation) +with SpeedTest(silent=True) as test: + results = test.run() +``` + +### 4. Don't Run Too Frequently + +```python +# ✅ Good - reasonable intervals +schedule.every().hour.do(run_speedtest) + +# ❌ Bad - too frequent, wastes bandwidth +schedule.every().minute.do(run_speedtest) +``` + +### 5. Cache Metadata + +```python +# ✅ Good - reuse metadata when possible +metadata = get_metadata_once() +# Use cached metadata for multiple operations + +# ❌ Bad - fetch metadata repeatedly +# (This depends on API design) +``` + +## Performance Considerations + +### Memory Usage + +- Silent mode uses less memory (no progress tracking) +- Smaller test sizes reduce memory footprint +- Single instance recommended per process + +### Network Impact + +- Each test consumes bandwidth +- Download test: ~10-200 MB +- Upload test: ~5-100 MB +- Consider test frequency in production + +### Execution Time + +Typical execution times: +- Complete test: 15-60 seconds +- Download only: 10-30 seconds +- Upload only: 10-30 seconds + +Factors affecting speed: +- Test sizes +- Connection speed +- Network latency +- System load + +## Troubleshooting + +### Import Errors + +```python +# If you get import errors, ensure package is installed +try: + from speedtest_cloudflare_cli.core.speedtest import SpeedTest +except ImportError: + print("Install: pip install speedtest-cloudflare-cli") +``` + +### Network Errors + +```python +import httpx + +try: + test = SpeedTest() + results = test.run() +except httpx.ConnectError: + print("Cannot connect to Cloudflare servers") +except httpx.TimeoutError: + print("Request timed out") +except httpx.HTTPError as e: + print(f"HTTP error: {e}") +``` + +### Permission Errors + +```python +# For ICMP ping, may need elevated privileges +# Library falls back to HTTP latency automatically +test = SpeedTest() +results = test.run() # Works even without ICMP access +``` + +## Next Steps + +- **[Usage Guide](usage.md)** - CLI usage patterns +- **[Features](features.md)** - Complete feature list +- **[Contributing](contributing.md)** - Contribute to development +- **[FAQ](faq.md)** - Common questions diff --git a/docs/contributing.md b/docs/contributing.md new file mode 100644 index 0000000..66c2ea6 --- /dev/null +++ b/docs/contributing.md @@ -0,0 +1,578 @@ +# Contributing + +We welcome contributions to **speedtest-cli**! This guide will help you get started with development, testing, and submitting your changes. + +## Ways to Contribute + +### Report Bugs + +Found a bug? Please report it at [GitHub Issues](https://github.com/takitsu21/speedtest/issues). + +When reporting a bug, include: + +- Operating system name and version +- Python version +- speedtest-cli version (`speedtest-cli --version`) +- Steps to reproduce the bug +- Expected vs. actual behavior +- Error messages or logs +- Network configuration (if relevant) + +### Suggest Features + +Have an idea for a new feature? Open an issue with the `enhancement` label. + +Include: + +- Clear description of the feature +- Use cases and benefits +- Proposed implementation (if you have ideas) +- Any alternatives you've considered + +### Fix Bugs + +Look for issues tagged with `bug` and `help wanted`. These are great starting points! + +### Implement Features + +Check issues tagged with `enhancement` and `help wanted` for feature requests. + +### Improve Documentation + +Documentation improvements are always welcome: + +- Fix typos or unclear explanations +- Add examples +- Improve API documentation +- Write tutorials or guides +- Translate documentation + +### Submit Feedback + +Share your experience using speedtest-cli, suggest improvements, or ask questions in [GitHub Discussions](https://github.com/takitsu21/speedtest/discussions). + +## Development Setup + +### Prerequisites + +- **Git**: Version control +- **Python**: 3.9 or higher (3.12+ recommended) +- **uv**: Modern Python package manager ([install uv](https://github.com/astral-sh/uv)) + +### 1. Fork and Clone + +Fork the repository on GitHub, then clone your fork: + +```bash +git clone git@github.com:YOUR_USERNAME/speedtest.git +cd speedtest +``` + +### 2. Install Dependencies + +Use `uv` to create a virtual environment and install all dependencies: + +```bash +uv sync +``` + +This installs: +- Main dependencies (httpx, rich, etc.) +- Development dependencies (pytest, mypy, ruff, etc.) +- The package in editable mode + +### 3. Install Pre-commit Hooks + +Pre-commit hooks run linters and formatters automatically before each commit: + +```bash +uv run pre-commit install +``` + +This ensures code quality standards are met before committing. + +### 4. Verify Installation + +Test that everything is set up correctly: + +```bash +# Run speedtest-cli from source +uv run speedtest-cli --help + +# Run tests +uv run pytest + +# Run linters +uv run ruff check . +``` + +## Development Workflow + +### 1. Create a Branch + +Create a new branch for your changes: + +```bash +git checkout -b feature/your-feature-name +# or +git checkout -b fix/your-bug-fix +``` + +**Branch Naming Conventions:** +- `feature/`: New features +- `fix/`: Bug fixes +- `docs/`: Documentation changes +- `refactor/`: Code refactoring +- `test/`: Test improvements + +### 2. Make Changes + +Edit the code as needed. Key directories: + +``` +speedtest/ +├── speedtest_cloudflare_cli/ +│ ├── core/ # Core functionality +│ │ ├── speedtest.py # Main SpeedTest class +│ │ └── dashboard.py # Dashboard generation +│ ├── models/ # Data models +│ │ ├── result.py # Result dataclass +│ │ └── metadata.py # Metadata model +│ └── main.py # CLI entry point +├── tests/ # Test files +├── docs/ # Documentation +└── templates/ # Jinja2 templates +``` + +### 3. Add Tests + +Write tests for your changes in the `tests/` directory: + +```python +# tests/test_your_feature.py +import pytest +from speedtest_cloudflare_cli.core.speedtest import SpeedTest + +def test_your_feature(): + """Test your new feature.""" + test = SpeedTest() + # Your test code here + assert result == expected +``` + +**Testing Guidelines:** +- Write tests for new features +- Ensure existing tests still pass +- Aim for good code coverage +- Use pytest fixtures for common setup +- Mock external API calls + +### 4. Run Tests + +```bash +# Run all tests +uv run pytest + +# Run with coverage +uv run pytest --cov=speedtest_cloudflare_cli + +# Run specific test file +uv run pytest tests/test_your_feature.py + +# Run specific test +uv run pytest tests/test_your_feature.py::test_specific_function +``` + +### 5. Code Quality Checks + +Run code quality tools before committing: + +```bash +# Run all checks (recommended) +make check + +# Individual tools: +uv run ruff check . # Linting +uv run ruff format . # Formatting +uv run mypy . # Type checking +uv run deptry . # Dependency checking +``` + +**Fix Issues Automatically:** + +```bash +# Auto-fix linting issues +uv run ruff check --fix . + +# Auto-format code +uv run ruff format . +``` + +### 6. Build and Test Locally + +```bash +# Build the package +make build + +# Install locally +uv pip install -e . + +# Test the CLI +speedtest-cli --help +``` + +### 7. Update Documentation + +If your changes affect user-facing functionality: + +- Update relevant documentation in `docs/` +- Add docstrings to new functions/classes +- Update README.md if needed +- Add examples for new features + +### 8. Commit Changes + +```bash +git add . +git commit -m "feat: add awesome new feature" +``` + +**Commit Message Format:** + +Follow [Conventional Commits](https://www.conventionalcommits.org/): + +- `feat:` New feature +- `fix:` Bug fix +- `docs:` Documentation changes +- `style:` Code style changes (formatting) +- `refactor:` Code refactoring +- `test:` Test changes +- `chore:` Build/tooling changes + +**Examples:** +``` +feat: add support for custom server selection +fix: correct latency calculation for IPv6 +docs: update installation guide for Windows +refactor: simplify progress bar logic +test: add tests for upload functionality +``` + +### 9. Push and Create Pull Request + +```bash +git push origin feature/your-feature-name +``` + +Then open a pull request on GitHub. + +## Code Style + +### Python Code Style + +We use **Ruff** for linting and formatting (configured in `pyproject.toml`): + +**Key Guidelines:** + +- Line length: 120 characters +- Use type hints for function signatures +- Write descriptive docstrings (Google style) +- Follow PEP 8 conventions +- Prefer f-strings for formatting +- Use meaningful variable names + +**Example:** + +```python +def calculate_speed( + bytes_transferred: int, + duration: float, +) -> float: + """ + Calculate speed in Mbps from bytes and duration. + + Args: + bytes_transferred: Number of bytes transferred + duration: Time duration in seconds + + Returns: + Speed in megabits per second (Mbps) + """ + bits = bytes_transferred * 8 + megabits = bits / 1_000_000 + return megabits / duration if duration > 0 else 0.0 +``` + +### Type Hints + +All functions should have type hints: + +```python +from typing import Optional +from speedtest_cloudflare_cli.models.result import Result + +def run_test(silent: bool = False) -> Optional[Result]: + """Run speed test.""" + ... +``` + +### Docstrings + +Use Google-style docstrings: + +```python +def example_function(param1: str, param2: int) -> bool: + """ + Short description of function. + + Longer description if needed, explaining what the function + does in more detail. + + Args: + param1: Description of param1 + param2: Description of param2 + + Returns: + Description of return value + + Raises: + ValueError: When param2 is negative + """ + ... +``` + +## Testing + +### Running Tests + +```bash +# All tests +uv run pytest + +# With coverage report +uv run pytest --cov=speedtest_cloudflare_cli --cov-report=html + +# Specific test file +uv run pytest tests/core/test_speedtest.py + +# Verbose output +uv run pytest -v + +# Stop on first failure +uv run pytest -x +``` + +### Writing Tests + +Use pytest fixtures and mocking: + +```python +import pytest +from unittest.mock import Mock, patch + +@pytest.fixture +def mock_speedtest(): + """Mock SpeedTest instance.""" + with patch('speedtest_cloudflare_cli.core.speedtest.SpeedTest') as mock: + yield mock + +def test_with_mock(mock_speedtest): + """Test using mock.""" + mock_speedtest.return_value.run.return_value = Mock(download=100.0) + # Your test code +``` + +### Test Coverage + +Aim for good test coverage: + +```bash +# Generate coverage report +uv run pytest --cov=speedtest_cloudflare_cli --cov-report=term-missing + +# HTML report for detailed view +uv run pytest --cov=speedtest_cloudflare_cli --cov-report=html +open htmlcov/index.html +``` + +## Building Documentation + +### Local Documentation Server + +```bash +# Serve documentation locally +make docs + +# Or manually +uv run mkdocs serve +``` + +Open http://127.0.0.1:8000 in your browser. + +### Build Documentation + +```bash +# Build static documentation +uv run mkdocs build + +# Output in site/ directory +``` + +### Documentation Style + +- Use clear, concise language +- Include code examples +- Add links to related pages +- Use admonitions for important notes +- Test all code examples + +## Pull Request Process + +### Before Submitting + +**Checklist:** + +- [ ] Tests pass locally (`uv run pytest`) +- [ ] Code passes linting (`uv run ruff check .`) +- [ ] Code is formatted (`uv run ruff format .`) +- [ ] Type checking passes (`uv run mypy .`) +- [ ] Documentation updated (if needed) +- [ ] Commit messages follow conventions +- [ ] Branch is up to date with main + +### PR Description + +Include in your PR: + +1. **Summary**: What does this PR do? +2. **Motivation**: Why is this change needed? +3. **Changes**: List of key changes +4. **Testing**: How was this tested? +5. **Screenshots**: If UI changes +6. **Related Issues**: Link to issues + +**Template:** + +```markdown +## Summary +Brief description of changes + +## Motivation +Why is this change needed? + +## Changes +- Change 1 +- Change 2 + +## Testing +- [ ] Unit tests added/updated +- [ ] Manual testing performed +- [ ] All tests pass + +## Related Issues +Closes #123 +``` + +### Review Process + +1. **Automated Checks**: CI/CD runs tests and linters +2. **Code Review**: Maintainers review your code +3. **Feedback**: Address any requested changes +4. **Approval**: PR approved by maintainer +5. **Merge**: PR merged to main branch + +### After Merge + +- Delete your feature branch +- Update your fork +- Celebrate! 🎉 + +## Development Tools + +### Makefile Commands + +Convenient commands available via `make`: + +```bash +make help # Show all available commands +make install # Install dependencies +make check # Run all quality checks +make test # Run tests +make build # Build package +make docs # Serve documentation +make clean # Clean build artifacts +``` + +### Pre-commit Hooks + +Configured in `.pre-commit-config.yaml`: + +- **ruff**: Linting and formatting +- **mypy**: Type checking +- **trailing-whitespace**: Remove trailing spaces +- **end-of-file-fixer**: Ensure newline at EOF +- **check-yaml**: Validate YAML files + +### Tox + +Test across multiple Python versions: + +```bash +# Test all Python versions (3.9-3.13) +tox + +# Test specific version +tox -e py312 + +# List all environments +tox -l +``` + +## Release Process + +Releases are automated via GitHub Actions: + +1. Update version in code +2. Create git tag: `git tag v1.2.3` +3. Push tag: `git push origin v1.2.3` +4. GitHub Actions builds and publishes to PyPI +5. Docker images built and pushed to ghcr.io + +## Getting Help + +### Resources + +- **Documentation**: https://takitsu21.github.io/speedtest/ +- **Issues**: https://github.com/takitsu21/speedtest/issues +- **Discussions**: https://github.com/takitsu21/speedtest/discussions +- **Source Code**: https://github.com/takitsu21/speedtest + +### Contact + +- Open an issue for bugs or features +- Use discussions for questions +- Mention maintainers in PRs for review + +## Code of Conduct + +Please be respectful and constructive: + +- Be welcoming to newcomers +- Respect different viewpoints +- Accept constructive criticism +- Focus on what's best for the project +- Show empathy towards others + +## License + +By contributing, you agree that your contributions will be licensed under the MIT License. + +## Recognition + +Contributors are recognized in: + +- GitHub contributors page +- Release notes +- Project documentation + +Thank you for contributing to speedtest-cli! 🚀 diff --git a/docs/docker.md b/docs/docker.md new file mode 100644 index 0000000..fbf70d4 --- /dev/null +++ b/docs/docker.md @@ -0,0 +1,617 @@ +# Docker & Container Deployment + +Run **speedtest-cli** in a container using Docker or Podman for isolated, reproducible speed tests. + +## Quick Start + +### Using Docker + +```bash +docker run --rm -it ghcr.io/takitsu21/speedtest:latest +``` + +### Using Podman + +```bash +podman run --rm -it ghcr.io/takitsu21/speedtest:latest +``` + +Both commands will: +1. Pull the latest speedtest-cli image (if not already cached) +2. Run a complete speed test +3. Display results in your terminal +4. Remove the container after completion + +## Container Image Details + +### Image Information + +- **Registry**: GitHub Container Registry (ghcr.io) +- **Repository**: `ghcr.io/takitsu21/speedtest` +- **Tags**: `latest`, version-specific tags (e.g., `1.2.3`) +- **Base Image**: Python 3.13-slim +- **Size**: ~200 MB (optimized) + +### Supported Platforms + +- **linux/amd64** (x86_64) +- **linux/arm64** (ARM64/Apple Silicon) +- **linux/arm/v7** (ARM 32-bit) + +Multi-architecture support ensures the image works on: +- Intel/AMD servers and desktops +- Apple Silicon Macs (M1/M2/M3) +- Raspberry Pi and ARM devices +- Cloud platforms (AWS, GCP, Azure) + +## Basic Usage + +### Run Default Speed Test + +```bash +docker run --rm -it ghcr.io/takitsu21/speedtest:latest +``` + +**Flags Explained:** +- `--rm`: Remove container after it exits +- `-it`: Interactive terminal (for colored output) +- `ghcr.io/takitsu21/speedtest:latest`: Image name + +### Run with CLI Options + +Pass any speedtest-cli option to the container: + +```bash +# Download only +docker run --rm -it ghcr.io/takitsu21/speedtest:latest --download + +# Custom size +docker run --rm -it ghcr.io/takitsu21/speedtest:latest -ds 50 -us 25 + +# Multiple attempts +docker run --rm -it ghcr.io/takitsu21/speedtest:latest --attempts 3 + +# JSON output +docker run --rm -it ghcr.io/takitsu21/speedtest:latest --json +``` + +## Advanced Usage + +### Save JSON Results to Host + +Mount a volume to save results to your host machine: + +```bash +# Create output directory +mkdir -p ~/speedtest-results + +# Run and save JSON output +docker run --rm -it \ + -v ~/speedtest-results:/output \ + ghcr.io/takitsu21/speedtest:latest \ + --json-output /output/results.json +``` + +**Result:** JSON file saved to `~/speedtest-results/results.json` on your host. + +### Silent Mode for Automation + +Run without interactive terminal: + +```bash +docker run --rm ghcr.io/takitsu21/speedtest:latest --silent --json +``` + +### Specific Version + +Use a specific version instead of `latest`: + +```bash +docker run --rm -it ghcr.io/takitsu21/speedtest:1.2.3 +``` + +**Benefits:** +- Reproducible builds +- Version pinning for CI/CD +- Rollback capability + +### Custom Network Configuration + +Run with host networking for accurate results: + +```bash +# Docker +docker run --rm -it --network host ghcr.io/takitsu21/speedtest:latest + +# Podman +podman run --rm -it --network host ghcr.io/takitsu21/speedtest:latest +``` + +**When to Use:** +- Container networking adds latency +- Host network gives most accurate results +- Required for some network configurations + +!!! warning "Security Note" + `--network host` gives container access to host network stack. Only use if you trust the image. + +## Building Custom Image + +### Clone Repository + +```bash +git clone https://github.com/takitsu21/speedtest.git +cd speedtest +``` + +### Build Image + +```bash +# Using Docker +docker build -t speedtest-custom . + +# Using Podman +podman build -t speedtest-custom . +``` + +### Build with BuildKit (Faster) + +```bash +# Docker with BuildKit +DOCKER_BUILDKIT=1 docker build -t speedtest-custom . + +# Podman (BuildKit enabled by default) +podman build -t speedtest-custom . +``` + +### Multi-Platform Build + +Build for multiple architectures: + +```bash +docker buildx create --use +docker buildx build \ + --platform linux/amd64,linux/arm64,linux/arm/v7 \ + -t speedtest-custom \ + --push . +``` + +### Run Custom Image + +```bash +docker run --rm -it speedtest-custom +``` + +## Docker Compose + +Create `docker-compose.yml` for easier management: + +```yaml +version: '3.8' + +services: + speedtest: + image: ghcr.io/takitsu21/speedtest:latest + stdin_open: true + tty: true + volumes: + - ./results:/output + command: --json-output /output/speedtest.json +``` + +**Run:** + +```bash +docker-compose run --rm speedtest +``` + +**Custom Options:** + +```bash +docker-compose run --rm speedtest --download --attempts 3 +``` + +## Scheduled Testing with Cron + +### Using Docker + +Create a script `~/speedtest.sh`: + +```bash +#!/bin/bash +TIMESTAMP=$(date +%Y%m%d_%H%M%S) +docker run --rm \ + -v ~/speedtest-logs:/output \ + ghcr.io/takitsu21/speedtest:latest \ + --silent --json-output /output/speedtest_$TIMESTAMP.json +``` + +Make it executable: + +```bash +chmod +x ~/speedtest.sh +``` + +Add to crontab: + +```bash +# Run every day at 2 AM +0 2 * * * /home/username/speedtest.sh +``` + +### Using systemd Timer (Linux) + +Create `~/.config/systemd/user/speedtest.service`: + +```ini +[Unit] +Description=Speed Test + +[Service] +Type=oneshot +ExecStart=/usr/bin/docker run --rm \ + -v %h/speedtest-logs:/output \ + ghcr.io/takitsu21/speedtest:latest \ + --silent --json-output /output/speedtest_$(date +\%Y\%m\%d_\%H\%M\%S).json +``` + +Create `~/.config/systemd/user/speedtest.timer`: + +```ini +[Unit] +Description=Run Speed Test Daily + +[Timer] +OnCalendar=daily +Persistent=true + +[Install] +WantedBy=timers.target +``` + +Enable and start: + +```bash +systemctl --user enable --now speedtest.timer +systemctl --user status speedtest.timer +``` + +## Kubernetes Deployment + +### CronJob for Scheduled Testing + +Create `speedtest-cronjob.yaml`: + +```yaml +apiVersion: batch/v1 +kind: CronJob +metadata: + name: speedtest +spec: + schedule: "0 2 * * *" # Daily at 2 AM + jobTemplate: + spec: + template: + spec: + containers: + - name: speedtest + image: ghcr.io/takitsu21/speedtest:latest + args: ["--silent", "--json-output", "/output/results.json"] + volumeMounts: + - name: results + mountPath: /output + volumes: + - name: results + persistentVolumeClaim: + claimName: speedtest-results + restartPolicy: OnFailure +``` + +Apply: + +```bash +kubectl apply -f speedtest-cronjob.yaml +``` + +### One-Time Job + +Create `speedtest-job.yaml`: + +```yaml +apiVersion: batch/v1 +kind: Job +metadata: + name: speedtest-once +spec: + template: + spec: + containers: + - name: speedtest + image: ghcr.io/takitsu21/speedtest:latest + args: ["--json"] + restartPolicy: Never + backoffLimit: 3 +``` + +Run: + +```bash +kubectl apply -f speedtest-job.yaml +kubectl logs job/speedtest-once +``` + +## CI/CD Integration + +### GitHub Actions + +Add to `.github/workflows/speedtest.yml`: + +```yaml +name: Network Speed Test + +on: + schedule: + - cron: '0 */6 * * *' # Every 6 hours + workflow_dispatch: + +jobs: + speedtest: + runs-on: ubuntu-latest + steps: + - name: Run Speed Test + run: | + docker run --rm ghcr.io/takitsu21/speedtest:latest --json > results.json + + - name: Upload Results + uses: actions/upload-artifact@v3 + with: + name: speedtest-results + path: results.json +``` + +### GitLab CI + +Add to `.gitlab-ci.yml`: + +```yaml +speedtest: + image: docker:latest + services: + - docker:dind + script: + - docker run --rm ghcr.io/takitsu21/speedtest:latest --json > results.json + artifacts: + paths: + - results.json + expire_in: 1 week + only: + - schedules +``` + +### Jenkins + +```groovy +pipeline { + agent any + triggers { + cron('0 */6 * * *') + } + stages { + stage('Speed Test') { + steps { + sh ''' + docker run --rm ghcr.io/takitsu21/speedtest:latest \ + --json-output results.json + ''' + archiveArtifacts artifacts: 'results.json' + } + } + } +} +``` + +## Monitoring Integration + +### Prometheus Exporter + +Create a simple exporter script: + +```bash +#!/bin/bash + +# Run speedtest and convert to Prometheus metrics +RESULTS=$(docker run --rm ghcr.io/takitsu21/speedtest:latest --json) + +echo "# HELP speedtest_download_mbps Download speed in Mbps" +echo "# TYPE speedtest_download_mbps gauge" +echo "speedtest_download_mbps $(echo $RESULTS | jq -r '.download')" + +echo "# HELP speedtest_upload_mbps Upload speed in Mbps" +echo "# TYPE speedtest_upload_mbps gauge" +echo "speedtest_upload_mbps $(echo $RESULTS | jq -r '.upload')" + +echo "# HELP speedtest_ping_ms Ping latency in milliseconds" +echo "# TYPE speedtest_ping_ms gauge" +echo "speedtest_ping_ms $(echo $RESULTS | jq -r '.ping')" +``` + +### InfluxDB Integration + +```python +import subprocess +import json +from influxdb import InfluxDBClient + +# Run speedtest +result = subprocess.run( + ['docker', 'run', '--rm', 'ghcr.io/takitsu21/speedtest:latest', '--json'], + capture_output=True, + text=True +) + +data = json.loads(result.stdout) + +# Write to InfluxDB +client = InfluxDBClient(host='localhost', port=8086, database='speedtest') +point = { + "measurement": "speed", + "fields": { + "download": data['download'], + "upload": data['upload'], + "ping": data['ping'], + "jitter": data['jitter'] + } +} +client.write_points([point]) +``` + +## Troubleshooting + +### Image Pull Issues + +**Problem:** Cannot pull image + +**Solutions:** + +```bash +# Try with explicit registry +docker pull ghcr.io/takitsu21/speedtest:latest + +# Check network connectivity +ping ghcr.io + +# Login if private (not needed for this public image) +echo $GITHUB_TOKEN | docker login ghcr.io -u USERNAME --password-stdin +``` + +### Permission Denied + +**Problem:** Docker permission errors on Linux + +**Solution:** + +```bash +# Add user to docker group +sudo usermod -aG docker $USER + +# Logout and login again, or: +newgrp docker + +# Or use Podman (rootless by default) +podman run --rm -it ghcr.io/takitsu21/speedtest:latest +``` + +### Slow Test Execution + +**Problem:** Tests take too long in container + +**Possible Causes:** +- Container networking overhead +- Resource limits +- Network configuration + +**Solutions:** + +```bash +# Use host networking +docker run --rm -it --network host ghcr.io/takitsu21/speedtest:latest + +# Increase container resources +docker run --rm -it --memory 512m --cpus 2 ghcr.io/takitsu21/speedtest:latest + +# Use smaller test sizes +docker run --rm -it ghcr.io/takitsu21/speedtest:latest -ds 25 -us 10 +``` + +### No Output + +**Problem:** Container runs but shows no output + +**Solutions:** + +```bash +# Ensure -it flags are used +docker run --rm -it ghcr.io/takitsu21/speedtest:latest + +# Check container logs +docker ps -a +docker logs + +# Run with explicit shell +docker run --rm -it ghcr.io/takitsu21/speedtest:latest sh -c "speedtest-cli" +``` + +## Best Practices + +### 1. Use Specific Tags + +```bash +# ✅ Good - version pinning +docker run --rm -it ghcr.io/takitsu21/speedtest:1.2.3 + +# ⚠️ Acceptable - latest +docker run --rm -it ghcr.io/takitsu21/speedtest:latest +``` + +### 2. Resource Limits + +```bash +docker run --rm -it \ + --memory 256m \ + --cpus 0.5 \ + ghcr.io/takitsu21/speedtest:latest +``` + +### 3. Cleanup Old Images + +```bash +# Remove unused images +docker image prune -a + +# Remove specific version +docker rmi ghcr.io/takitsu21/speedtest:old-version +``` + +### 4. Security + +```bash +# Run as non-root (image already does this) +# Use read-only filesystem when possible +docker run --rm -it --read-only ghcr.io/takitsu21/speedtest:latest + +# Drop capabilities +docker run --rm -it --cap-drop=ALL ghcr.io/takitsu21/speedtest:latest +``` + +## Comparison: Container vs. Native + +| Aspect | Container | Native Installation | +|--------|-----------|---------------------| +| **Setup** | Pull image only | Install Python + packages | +| **Isolation** | Fully isolated | System packages | +| **Updates** | Pull new image | Package upgrade | +| **Portability** | Highly portable | Python dependency | +| **Performance** | Slight overhead | Native speed | +| **Networking** | May affect latency | Direct access | +| **Disk Space** | ~200 MB | ~50 MB | + +**Use Containers When:** +- CI/CD pipelines +- Consistent environments needed +- Multiple versions required +- Easy cleanup desired +- Kubernetes/cloud deployments + +**Use Native When:** +- Development +- Frequent testing +- Minimal overhead required +- Direct system access needed + +## Next Steps + +- **[Usage Guide](usage.md)** - Learn all CLI options +- **[Features](features.md)** - Explore capabilities +- **[API Reference](api-reference.md)** - Programmatic usage +- **[Contributing](contributing.md)** - Build from source +- **[FAQ](faq.md)** - Common questions diff --git a/docs/faq.md b/docs/faq.md new file mode 100644 index 0000000..0aad24e --- /dev/null +++ b/docs/faq.md @@ -0,0 +1,770 @@ +# FAQ & Troubleshooting + +Common questions and solutions for **speedtest-cli**. + +## General Questions + +### What is speedtest-cli? + +speedtest-cli is a command-line tool for testing your internet connection speed. It uses Cloudflare's global network infrastructure to measure download/upload speeds, latency, jitter, and other network metrics. + +### How accurate is speedtest-cli? + +speedtest-cli provides accurate measurements when: + +- You're connected via Ethernet (Wi-Fi adds variability) +- No other applications are using bandwidth +- Tests are run to nearby Cloudflare servers +- Adequate test file sizes are used + +Results may vary slightly from other speed test tools due to different testing methodologies and server locations. + +### Which servers does speedtest-cli use? + +speedtest-cli uses Cloudflare's global network (speed.cloudflare.com). It automatically connects to the nearest Cloudflare edge server for optimal performance. + +### Can I choose a specific server? + +Currently, speedtest-cli automatically selects the nearest Cloudflare server. Manual server selection is not supported, but it's on the roadmap for future releases. + +### Is my data private? + +Yes. speedtest-cli: + +- ✅ Uses HTTPS for all connections +- ✅ Doesn't collect personal information +- ✅ Doesn't store browsing history +- ✅ Is open source (auditable) +- ✅ Doesn't send telemetry to developers + +The only data transmitted is: +- Test data to/from Cloudflare +- Your IP address (necessary for routing) + +### Is speedtest-cli free? + +Yes, speedtest-cli is completely free and open source under the MIT License. + +### Does it work offline? + +No, speedtest-cli requires an active internet connection to test your speed. + +--- + +## Installation Issues + +### Command Not Found After Installation + +**Problem:** `speedtest-cli: command not found` + +**Solutions:** + +1. **Ensure installation path is in PATH:** + + ```bash + # For pipx + pipx ensurepath + + # Restart terminal or reload shell + source ~/.bashrc # or ~/.zshrc + ``` + +2. **Verify installation:** + + ```bash + pipx list # or uv tool list + ``` + +3. **Reinstall:** + + ```bash + pipx uninstall speedtest-cloudflare-cli + pipx install speedtest-cloudflare-cli + ``` + +4. **Use full path:** + + ```bash + ~/.local/bin/speedtest-cli + ``` + +### Permission Denied During Installation + +**Problem:** Permission errors with pip + +**Solutions:** + +1. **Use pipx or uv instead (recommended):** + + ```bash + pipx install speedtest-cloudflare-cli + ``` + +2. **Install for current user only:** + + ```bash + pip install --user speedtest-cloudflare-cli + ``` + +3. **Don't use sudo with pip** (can break system packages) + +### Python Version Incompatibility + +**Problem:** `Requires Python 3.9+` + +**Solutions:** + +1. **Check Python version:** + + ```bash + python --version + ``` + +2. **Install compatible Python:** + + ```bash + # Ubuntu/Debian + sudo apt install python3.12 + + # macOS + brew install python@3.12 + ``` + +3. **Use pyenv for multiple Python versions:** + + ```bash + pyenv install 3.12 + pyenv global 3.12 + ``` + +### Package Not Found on PyPI + +**Problem:** `Could not find a version that satisfies the requirement` + +**Solution:** + +Ensure correct package name: + +```bash +# ✅ Correct +pip install speedtest-cloudflare-cli + +# ❌ Wrong +pip install speedtest-cli # Different package! +``` + +--- + +## Usage Issues + +### Tests Are Very Slow + +**Problem:** Speed tests take too long to complete + +**Possible Causes & Solutions:** + +1. **Large test files on slow connection:** + + ```bash + # Use smaller file sizes + speedtest-cli -ds 10 -us 5 + ``` + +2. **Network congestion:** + - Test during off-peak hours + - Close bandwidth-heavy applications + +3. **Wi-Fi interference:** + - Switch to Ethernet + - Move closer to router + - Test on 5GHz band if available + +4. **System resources:** + - Close unnecessary applications + - Check CPU/memory usage + +### Ping/Latency Test Fails + +**Problem:** `Ping test failed` or very high latency + +**Solutions:** + +1. **ICMP may be blocked:** + + speedtest-cli automatically falls back to HTTP latency measurement. This is normal and expected in many environments. + +2. **Grant ICMP permissions (Linux):** + + ```bash + # Not recommended for security reasons + sudo setcap cap_net_raw+ep $(which python3) + ``` + +3. **Use HTTP latency instead:** + + HTTP latency is displayed automatically and is sufficient for most use cases. + +4. **Check firewall:** + - Ensure outbound HTTPS is allowed + - Check for corporate firewall rules + +### Connection Timeout Errors + +**Problem:** `Connection timeout` or `Network unreachable` + +**Solutions:** + +1. **Check internet connection:** + + ```bash + ping 1.1.1.1 + curl https://speed.cloudflare.com + ``` + +2. **Check proxy settings:** + + speedtest-cli respects system proxy settings. Ensure they're correct. + +3. **Disable VPN temporarily:** + + Some VPNs may interfere with speed tests. + +4. **Check firewall:** + + Allow outbound HTTPS connections to *.cloudflare.com + +5. **Try different network:** + + Test on different Wi-Fi or Ethernet connection. + +### Results Differ from Other Speed Tests + +**Problem:** Different results compared to Ookla, Fast.com, etc. + +**Explanation:** + +This is **normal** and expected because: + +- **Different servers**: speedtest-cli uses Cloudflare, others use different networks +- **Different methodologies**: Varying test algorithms +- **Different times**: Network conditions change +- **Different locations**: Server distances vary + +**Tips for Consistency:** + +1. Run multiple tests: + + ```bash + speedtest-cli --attempts 5 + ``` + +2. Test at same time of day +3. Use same connection type (Wi-Fi vs Ethernet) +4. Close background applications + +### Web Dashboard Won't Open + +**Problem:** `--web_view` doesn't open browser + +**Solutions:** + +1. **Manually open HTML file:** + + ```bash + # Linux/macOS + find /tmp -name "speedtest_dashboard*.html" -exec firefox {} \; + + # macOS + open "$(find /tmp -name 'speedtest_dashboard*.html' | head -1)" + ``` + +2. **Check default browser:** + + Ensure you have a default browser configured. + +3. **Permissions:** + + Check that /tmp is writable: + + ```bash + ls -ld /tmp + ``` + +4. **Try different browser:** + + ```bash + # Specify browser + BROWSER=chromium speedtest-cli --web_view + ``` + +### JSON Output Not Working + +**Problem:** `--json` produces no output or errors + +**Solutions:** + +1. **Check for syntax errors:** + + ```bash + speedtest-cli --json | jq . + ``` + +2. **Redirect errors:** + + ```bash + speedtest-cli --json 2>&1 | tee output.log + ``` + +3. **Check file permissions:** + + ```bash + speedtest-cli --json-output results.json + ls -l results.json + ``` + +--- + +## Performance Issues + +### Slower Speeds Than Expected + +**Problem:** Test results slower than ISP advertised speeds + +**Troubleshooting Steps:** + +1. **Use Ethernet connection:** + + Wi-Fi typically slower than wired. + +2. **Test at different times:** + + Network congestion varies throughout day. + +3. **Close bandwidth-heavy apps:** + - Stop downloads/uploads + - Pause cloud sync (Dropbox, Google Drive) + - Close streaming services + - Disable auto-updates + +4. **Restart router/modem:** + + Power cycle your network equipment. + +5. **Check for ISP issues:** + + Contact ISP if consistently slow. + +6. **Test on different devices:** + + Isolate whether issue is device-specific. + +7. **Check system resources:** + + ```bash + top # or htop + ``` + +8. **Disable QoS:** + + Quality of Service settings may limit speed. + +### High Jitter Values + +**Problem:** Jitter is high (> 30ms) + +**Causes & Solutions:** + +1. **Wi-Fi interference:** + - Switch to Ethernet + - Change Wi-Fi channel + - Move closer to router + +2. **Network congestion:** + - Test during off-peak hours + - Close bandwidth-heavy applications + +3. **ISP issues:** + - Contact ISP if persistent + - Check for service outages + +4. **Router issues:** + - Restart router + - Update router firmware + - Replace old router + +### High Ping Latency + +**Problem:** Ping is high (> 100ms) + +**Possible Causes:** + +1. **Geographic distance to server:** + - Normal if far from Cloudflare edge + - Check with `metadata.colo` + +2. **Network routing:** + - ISP routing inefficiency + - Use traceroute to diagnose + +3. **VPN/Proxy:** + - Adds latency + - Test without VPN + +4. **Wi-Fi:** + - Switch to Ethernet + - Reduce interference + +--- + +## Docker/Container Issues + +### Cannot Pull Docker Image + +**Problem:** `Error response from daemon: pull access denied` + +**Solutions:** + +1. **Use correct image name:** + + ```bash + docker pull ghcr.io/takitsu21/speedtest:latest + ``` + +2. **Check network connectivity:** + + ```bash + ping ghcr.io + ``` + +3. **Retry pull:** + + ```bash + docker pull --quiet ghcr.io/takitsu21/speedtest:latest + ``` + +### Container Doesn't Show Output + +**Problem:** Docker container runs but no output + +**Solutions:** + +1. **Use -it flags:** + + ```bash + docker run --rm -it ghcr.io/takitsu21/speedtest:latest + ``` + +2. **Check logs:** + + ```bash + docker logs + ``` + +3. **Run with shell:** + + ```bash + docker run --rm -it ghcr.io/takitsu21/speedtest:latest sh + speedtest-cli + ``` + +### Docker Permission Denied (Linux) + +**Problem:** `permission denied while trying to connect to Docker daemon` + +**Solutions:** + +1. **Add user to docker group:** + + ```bash + sudo usermod -aG docker $USER + newgrp docker + ``` + +2. **Use Podman (rootless):** + + ```bash + podman run --rm -it ghcr.io/takitsu21/speedtest:latest + ``` + +3. **Use sudo (not recommended):** + + ```bash + sudo docker run --rm -it ghcr.io/takitsu21/speedtest:latest + ``` + +--- + +## API/Library Usage Issues + +### Import Errors + +**Problem:** `ModuleNotFoundError: No module named 'speedtest_cloudflare_cli'` + +**Solutions:** + +1. **Verify installation:** + + ```bash + pip list | grep speedtest + ``` + +2. **Install package:** + + ```bash + pip install speedtest-cloudflare-cli + ``` + +3. **Check Python path:** + + ```python + import sys + print(sys.path) + ``` + +4. **Use virtual environment:** + + ```bash + python -m venv venv + source venv/bin/activate + pip install speedtest-cloudflare-cli + ``` + +### Type Checking Errors + +**Problem:** mypy shows type errors + +**Solution:** + +Install type stubs if needed: + +```bash +pip install types-httpx +``` + +The library includes type hints, so most IDEs will have proper autocomplete. + +--- + +## Platform-Specific Issues + +### Windows Issues + +**Problem:** Various Windows-specific issues + +**Solutions:** + +1. **Use Windows Terminal:** + + Download from Microsoft Store for best experience. + +2. **PowerShell encoding:** + + ```powershell + [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 + ``` + +3. **Path issues:** + + Add Python Scripts directory to PATH: + ``` + C:\Users\YourName\AppData\Local\Programs\Python\Python312\Scripts + ``` + +4. **ICMP permissions:** + + Usually available by default on Windows. + +### macOS Issues + +**Problem:** macOS-specific issues + +**Solutions:** + +1. **System Integrity Protection:** + + No special configuration needed. + +2. **Homebrew Python:** + + Use pipx or uv to avoid conflicts. + +3. **Terminal permissions:** + + Grant Terminal full disk access in System Preferences if needed. + +### Linux Issues + +**Problem:** Linux-specific issues + +**Solutions:** + +1. **ICMP permissions:** + + ```bash + # Grant capabilities (optional) + sudo setcap cap_net_raw+ep $(which python3) + ``` + +2. **Snap/Flatpak isolation:** + + Use native installation instead. + +3. **SELinux:** + + May need to adjust policies in rare cases. + +--- + +## Comparing with Other Tools + +### vs. Ookla Speedtest + +**Differences:** + +- **Backend**: Cloudflare vs Ookla servers +- **Open Source**: Yes vs No +- **CLI-first**: Yes vs GUI-first +- **Privacy**: High vs Medium + +**When to use speedtest-cli:** +- Command-line workflows +- Automation/scripting +- Privacy concerns +- Cloudflare infrastructure testing + +**When to use Ookla:** +- Need server selection +- Prefer GUI +- ISP uses Ookla for official tests + +### vs. Fast.com + +**Differences:** + +- **Backend**: Cloudflare vs Netflix CDN +- **CLI**: Native vs Web-only +- **Metrics**: Comprehensive vs Basic +- **Automation**: Easy vs Difficult + +**When to use speedtest-cli:** +- More detailed metrics needed +- CLI automation required +- JSON output needed + +**When to use Fast.com:** +- Quick browser test +- Netflix streaming quality + +--- + +## Getting More Help + +### Check Documentation + +- **[Installation Guide](installation.md)** - Setup help +- **[Usage Guide](usage.md)** - CLI options +- **[Features](features.md)** - Capabilities +- **[API Reference](api-reference.md)** - Library usage + +### Report Issues + +If you've found a bug: + +1. Check [existing issues](https://github.com/takitsu21/speedtest/issues) +2. Create a new issue with: + - OS and Python version + - speedtest-cli version + - Steps to reproduce + - Error messages + - Expected vs actual behavior + +### Ask Questions + +- **[GitHub Discussions](https://github.com/takitsu21/speedtest/discussions)** - Ask questions +- **[GitHub Issues](https://github.com/takitsu21/speedtest/issues)** - Report bugs + +### Enable Debug Output + +For troubleshooting, run with verbose Python logging: + +```bash +python -m speedtest_cloudflare_cli.main --help +``` + +--- + +## Common Error Messages + +### "Network error: Could not connect to speed.cloudflare.com" + +**Cause:** Cannot reach Cloudflare servers + +**Solution:** +1. Check internet connection +2. Check firewall settings +3. Try with VPN disabled +4. Verify DNS resolution: `nslookup speed.cloudflare.com` + +### "Permission denied: Cannot create file" + +**Cause:** No write permissions for output file + +**Solution:** +```bash +# Check permissions +ls -la /path/to/output/ + +# Use writable location +speedtest-cli --json-output ~/results.json +``` + +### "ModuleNotFoundError" + +**Cause:** Package not installed or wrong environment + +**Solution:** +```bash +# Verify installation +pip show speedtest-cloudflare-cli + +# Reinstall +pip install --force-reinstall speedtest-cloudflare-cli +``` + +### "Command 'speedtest-cli' not found" + +**Cause:** Installation path not in PATH + +**Solution:** +See [Command Not Found](#command-not-found-after-installation) above. + +--- + +## Tips for Best Results + +### Optimize Test Accuracy + +1. **Use Ethernet** instead of Wi-Fi +2. **Close all applications** using bandwidth +3. **Run multiple tests** with `--attempts 3` +4. **Test at different times** to see variance +5. **Restart router** before important tests + +### Automation Best Practices + +1. **Use silent mode** in scripts +2. **Export to JSON** for parsing +3. **Don't test too frequently** (respect bandwidth) +4. **Handle errors gracefully** in scripts +5. **Log results** for historical tracking + +### Performance Tuning + +1. **Adjust test sizes** based on connection speed +2. **Use download-only** for quick tests +3. **Enable silent mode** to reduce overhead +4. **Run from containers** for isolation + +--- + +Still have questions? [Open a discussion](https://github.com/takitsu21/speedtest/discussions) on GitHub! diff --git a/docs/features.md b/docs/features.md new file mode 100644 index 0000000..bea5cd0 --- /dev/null +++ b/docs/features.md @@ -0,0 +1,658 @@ +# Features + +**speedtest-cli** offers a comprehensive suite of features for testing and analyzing your network connection. This page provides an in-depth look at all capabilities. + +## Speed Testing + +### Download Speed Test + +Measures how fast data can be downloaded from the internet to your device. + +**How It Works:** + +1. Connects to Cloudflare's speed testing infrastructure +2. Downloads data in chunks over HTTP +3. Measures throughput in real-time +4. Calculates average speed in Mbps (megabits per second) + +**Features:** + +- Real-time progress bars +- Configurable download size (`--download_size`) +- Multiple attempt support for averaging +- HTTP streaming for accurate measurements + +**Use Cases:** + +- Verifying ISP advertised speeds +- Troubleshooting slow downloads +- Comparing speeds at different times +- Monitoring connection quality + +**Example:** + +```bash +# Download test only with 50 MB size +speedtest-cli --download --download_size 50 +``` + +### Upload Speed Test + +Measures how fast data can be uploaded from your device to the internet. + +**How It Works:** + +1. Generates test data locally +2. Uploads to Cloudflare servers via HTTP POST +3. Tracks upload progress +4. Calculates throughput in Mbps + +**Features:** + +- Configurable upload size (`--upload_size`) +- Efficient data generation +- Progress tracking +- Multiple attempts support + +**Use Cases:** + +- Testing video conferencing capabilities +- Verifying file upload performance +- Streaming quality assessment +- Cloud backup speed testing + +**Example:** + +```bash +# Upload test only with 25 MB size +speedtest-cli --upload --upload_size 25 +``` + +--- + +## Network Metrics + +### Ping Latency + +Measures round-trip time (RTT) for packets to reach Cloudflare servers and return. + +**How It Works:** + +- Uses ICMP ping protocol (when available) +- Falls back to HTTP-based latency measurement +- Runs in background thread for better UX +- Measures in milliseconds (ms) + +**What It Indicates:** + +- **< 20ms**: Excellent (great for gaming, real-time apps) +- **20-50ms**: Good (suitable for most activities) +- **50-100ms**: Fair (may notice lag in real-time apps) +- **> 100ms**: Poor (noticeable delays) + +**Use Cases:** + +- Gaming performance assessment +- VoIP quality prediction +- Video conferencing suitability +- Real-time application testing + +**Fallback Mechanism:** + +If ICMP ping is blocked or requires privileges: +- Automatically uses HTTP latency measurement +- Ensures you always get latency data +- Slightly higher values due to HTTP overhead + +### Jitter + +Measures variation in ping latency over time. + +**How It Works:** + +- Calculates standard deviation of ping times +- Multiple ping samples analyzed +- Reported in milliseconds (ms) + +**What It Indicates:** + +- **< 5ms**: Excellent (stable connection) +- **5-15ms**: Good (minor variations) +- **15-30ms**: Fair (noticeable in real-time apps) +- **> 30ms**: Poor (unstable connection) + +**Use Cases:** + +- VoIP quality assessment +- Online gaming performance +- Video conferencing stability +- Network stability monitoring + +**Impact:** + +High jitter can cause: +- Choppy voice in calls +- Lag spikes in games +- Buffering in live streams +- Packet loss + +### HTTP Latency + +Measures time to establish HTTP connection to Cloudflare servers. + +**How It Works:** + +- Times the HTTP connection handshake +- Includes DNS lookup and TCP connection +- Separate from ICMP ping +- Measured in milliseconds (ms) + +**What It Indicates:** + +- Overall web browsing responsiveness +- API call performance +- Web application speed + +**Difference from Ping:** + +- **Ping**: Pure network latency (ICMP) +- **HTTP Latency**: Application-level latency (includes protocol overhead) + +--- + +## Network Information + +### IP Address Detection + +Automatically detects and displays your public IP address. + +**Features:** + +- IPv4 detection +- IPv6 detection and support +- Displays both when available + +**Example Output:** + +``` +IP: 203.0.113.45 (IPv4) +IPv6: 2001:0db8:85a3::8a2e:0370:7334 +``` + +### ISP Information + +Identifies your Internet Service Provider. + +**Information Provided:** + +- ISP name +- Autonomous System Number (ASN) +- Organization details + +**Example:** + +``` +ISP: Example Broadband +ASN: AS12345 +``` + +### Geolocation + +Determines your geographic location based on IP address. + +**Details Provided:** + +- City +- Region/State +- Country +- Coordinates (latitude, longitude) + +**Example:** + +``` +Location: San Francisco, California, US +Coordinates: 37.7749, -122.4194 +``` + +**Privacy Note:** + +All geolocation is done via Cloudflare's API. No data is stored or transmitted elsewhere. + +### Cloudflare Data Center + +Shows which Cloudflare edge server (colo) handled your test. + +**Example:** + +``` +Cloudflare Datacenter: SFO +``` + +**Why It Matters:** + +- Indicates routing efficiency +- Shows network path optimization +- Helps diagnose routing issues + +--- + +## Output Formats + +### Rich Console Output + +Beautiful terminal interface with colors and formatting. + +**Features:** + +- Color-coded output +- Progress bars with animations +- Formatted tables +- Unicode box drawing +- Emoji indicators (connection quality) + +**Powered By:** + +[Rich](https://github.com/Textualize/rich) - Python library for rich terminal output + +**Example:** + +```bash +speedtest-cli +``` + +### JSON Output + +Machine-readable structured data format. + +**To Console:** + +```bash +speedtest-cli --json +``` + +**To File:** + +```bash +speedtest-cli --json-output results.json +``` + +**Schema:** + +```json +{ + "download": 150.5, // Mbps + "upload": 45.3, // Mbps + "ping": 12, // ms + "jitter": 2, // ms + "http_latency": 15, // ms + "metadata": { + "ip": "203.0.113.45", + "isp": "Example ISP", + "city": "San Francisco", + "region": "California", + "country": "US", + "loc": "37.7749,-122.4194", + "colo": "SFO", + "asn": "AS12345" + } +} +``` + +**Use Cases:** + +- Automation scripts +- Data analysis +- Monitoring systems +- API integrations +- Long-term logging + +### HTML Dashboard + +Interactive web-based visualization of results. + +**Access:** + +```bash +speedtest-cli --web_view +``` + +**Features:** + +- Interactive map with location marker +- Dark/light theme toggle +- Connection quality indicators +- Responsive design +- All metrics displayed +- Beautiful visual design +- Shareable HTML file + +See [Web Dashboard](web-dashboard.md) for detailed guide. + +--- + +## Cloudflare Infrastructure + +### Why Cloudflare? + +**speedtest-cli** uses Cloudflare's global network for testing: + +**Advantages:** + +1. **Global Coverage**: 300+ cities worldwide +2. **Low Latency**: Edge servers close to users +3. **High Capacity**: No bandwidth bottlenecks +4. **Reliability**: 99.99%+ uptime +5. **Privacy**: No account required, minimal data collection +6. **Speed**: Optimized infrastructure + +### How It Works + +``` +Your Device → Your ISP → Internet → Cloudflare Edge → Speed Test +``` + +**Test Process:** + +1. Your device connects to nearest Cloudflare edge server +2. Metadata retrieved (IP, location, ISP) +3. Speed tests executed using HTTP streaming +4. Results calculated locally +5. Optional dashboard generation + +### Accuracy + +**Factors Ensuring Accuracy:** + +- Large test files to smooth out variance +- HTTP streaming for realistic measurements +- Multiple attempts support +- Cloudflare's uncongested network +- Direct measurement without middle servers + +**Potential Variations:** + +- Network congestion +- Wi-Fi interference +- Background applications +- Time of day +- Server load (rare with Cloudflare) + +--- + +## Advanced Features + +### Multiple Attempts + +Run tests multiple times and get averaged results. + +```bash +speedtest-cli --attempts 5 +``` + +**Benefits:** + +- Reduces impact of random variance +- More reliable measurements +- Identifies connection instability +- Better statistical confidence + +**Use Case:** + +When you need accurate measurements for reporting or diagnostics. + +### Silent Mode + +Run tests without visual output. + +```bash +speedtest-cli --silent +``` + +**Features:** + +- No progress bars +- No console output (except errors) +- Exit codes indicate success/failure +- Works with `--json-output` + +**Use Cases:** + +- Cron jobs +- Background monitoring +- Automated scripts +- Minimal logging + +### Selective Testing + +Test only specific aspects: + +```bash +# Download only +speedtest-cli --download + +# Upload only +speedtest-cli --upload + +# Both (explicit) +speedtest-cli --download --upload +``` + +**Benefits:** + +- Faster testing +- Focus on specific metrics +- Save bandwidth +- Targeted troubleshooting + +### Configurable Test Sizes + +Adjust data volume for your connection speed: + +```bash +# Small files for slow connections +speedtest-cli -ds 10 -us 5 + +# Large files for fast connections +speedtest-cli -ds 100 -us 50 +``` + +**Guidelines:** + +| Connection Speed | Recommended Download Size | Recommended Upload Size | +|-----------------|--------------------------|------------------------| +| < 10 Mbps | 10-25 MB | 5-10 MB | +| 10-50 Mbps | 25-50 MB | 10-25 MB | +| 50-100 Mbps | 50-100 MB | 25-50 MB | +| 100-500 Mbps | 100-200 MB | 50-100 MB | +| > 500 Mbps | 200+ MB | 100+ MB | + +--- + +## IPv6 Support + +Full support for IPv6 connections. + +**Features:** + +- Automatic IPv6 detection +- IPv4 and IPv6 dual-stack support +- Displays both addresses when available +- Tests over IPv6 when preferred + +**Example:** + +``` +IPv4: 203.0.113.45 +IPv6: 2001:0db8:85a3::8a2e:0370:7334 +``` + +**Benefits:** + +- Future-proof testing +- Proper IPv6 performance measurement +- Dual-stack validation + +--- + +## Privacy and Security + +### Data Collection + +**What speedtest-cli Collects:** + +- Your public IP address (temporary, for testing) +- ISP information (from Cloudflare) +- Geolocation (from Cloudflare) + +**What It Doesn't Collect:** + +- Personal information +- Browsing history +- Device details +- Persistent identifiers + +### Local Processing + +- All calculations done locally +- Results stored only if you use `--json-output` +- No telemetry sent to developers +- No analytics or tracking + +### Open Source + +- Full source code available on GitHub +- Auditable security +- Community reviewed +- Transparent operation + +--- + +## Performance Optimization + +### Tips for Accurate Results + +1. **Use Wired Connection**: Ethernet is more stable than Wi-Fi +2. **Close Background Apps**: Stop downloads, updates, streaming +3. **Test Multiple Times**: Use `--attempts 3` or more +4. **Avoid Peak Hours**: Test during off-peak times +5. **Direct Connection**: Connect directly to modem when possible + +### System Requirements + +**Minimum:** + +- Python 3.9+ +- 50 MB free RAM +- Internet connection + +**Recommended:** + +- Python 3.12+ +- 100 MB free RAM +- Wired Ethernet connection +- ICMP ping permissions + +--- + +## Integration Capabilities + +### Command-Line Scripts + +Easily integrate into shell scripts: + +```bash +#!/bin/bash +SPEED=$(speedtest-cli --json | jq -r '.download') +echo "Current speed: $SPEED Mbps" +``` + +### Python Programs + +Use as a library (see [API Reference](api-reference.md)): + +```python +from speedtest_cloudflare_cli.core.speedtest import SpeedTest + +test = SpeedTest() +results = test.run() +print(f"Download: {results.download} Mbps") +``` + +### Monitoring Systems + +- Prometheus exporters +- Grafana dashboards +- Custom alerting +- Historical tracking + +### CI/CD Pipelines + +Monitor deployment environment network: + +```yaml +- name: Test Network Speed + run: speedtest-cli --json-output network-test.json +``` + +--- + +## Comparison with Other Tools + +### vs. Ookla Speedtest + +| Feature | speedtest-cli | Ookla Speedtest | +|---------|---------------|-----------------| +| Backend | Cloudflare | Ookla servers | +| Open Source | Yes | No | +| CLI Only | Yes | No (GUI available) | +| JSON Output | Yes | Limited | +| Privacy | High | Medium | +| Accounts | Not required | Optional | + +### vs. Fast.com + +| Feature | speedtest-cli | Fast.com | +|---------|---------------|----------| +| Backend | Cloudflare | Netflix CDN | +| CLI | Yes | Web only | +| Upload Test | Yes | Yes | +| Detailed Metrics | Yes | Basic | +| Automation | Easy | Difficult | + +### vs. LibreSpeed + +| Feature | speedtest-cli | LibreSpeed | +|---------|---------------|------------| +| Backend | Cloudflare | Self-hosted | +| Installation | Simple | Complex | +| Global Servers | Yes | Depends | +| Maintenance | None | Self-managed | + +--- + +## Limitations + +### Known Limitations + +1. **Network Access Required**: Cannot test without internet +2. **ICMP Permissions**: May need elevated privileges for ping on some systems +3. **Cloudflare Only**: Tests only to Cloudflare servers, not other endpoints +4. **No Server Selection**: Automatically uses nearest Cloudflare edge +5. **Single Connection**: Doesn't test multi-connection scenarios + +### Not Suitable For + +- Testing local network speeds (use iperf instead) +- Measuring Wi-Fi range +- Testing specific server endpoints +- Multi-threaded download scenarios + +--- + +## Next Steps + +- **[Usage Guide](usage.md)** - Learn all CLI options +- **[Web Dashboard](web-dashboard.md)** - Explore the interactive dashboard +- **[Docker](docker.md)** - Run in containers +- **[API Reference](api-reference.md)** - Use as a Python library +- **[FAQ](faq.md)** - Common questions and troubleshooting diff --git a/docs/index.md b/docs/index.md index 25473f8..822219b 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,72 +1,134 @@

- Speed Test Icon + Speed Test Icon

-# speedtest-cli +

speedtest-cli

-![PyPI - Python Version](https://img.shields.io/pypi/pyversions/speedtest-cloudflare-cli) -![PyPI - Version](https://img.shields.io/pypi/v/speedtest-cloudflare-cli) -[![Release](https://img.shields.io/github/v/release/takitsu21/speedtest)](https://img.shields.io/github/v/release/takitsu21/speedtest) -[![test](https://github.com/takitsu21/speedtest/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/takitsu21/speedtest/actions/workflows/test.yml) -[![build](https://github.com/takitsu21/speedtest/actions/workflows/deploy.yml/badge.svg)](https://github.com/takitsu21/speedtest/actions/workflows/deploy.yml) -[![Commit activity](https://img.shields.io/github/commit-activity/m/takitsu21/speedtest)](https://img.shields.io/github/commit-activity/m/takitsu21/speedtest) -[![License](https://img.shields.io/github/license/takitsu21/speedtest)](https://img.shields.io/github/license/takitsu21/speedtest) +

+ A fast, beautiful command-line tool for testing your network speed +

+ +

+ Python Version + PyPI Version + Release + Tests + License +

+--- + +## Overview + +**speedtest-cli** is a modern, feature-rich command-line tool that measures your internet connection speed with style. Built on Cloudflare's global infrastructure, it provides accurate speed measurements along with detailed network metrics, all displayed in a beautiful terminal interface. ![SpeedTest Video demo](assets/demo.gif) + +## Key Features + +- **Accurate Speed Testing** - Powered by Cloudflare's global network for reliable measurements +- **Comprehensive Metrics** - Download/upload speeds, latency, jitter, and HTTP latency +- **Beautiful Interface** - Rich terminal output with progress bars and formatted tables +- **Web Dashboard** - Interactive HTML dashboard with maps and visualizations +- **Flexible Output** - Console display, JSON export, or silent mode for automation +- **Network Details** - ISP information, location data, IPv4/IPv6 support +- **Cross-Platform** - Works on Linux, macOS, and Windows +- **Container Ready** - Available as Docker/Podman image + ![SpeedTest dashboard](assets/web_view.png) -## Installation +## Quick Start + +### Installation -I strongly recommend to use [pipx](https://github.com/pypa/pipx/tree/main) or [uv](https://github.com/astral-sh/uv) to install this tool. -These tools will install the package in an isolated environment and will not interfere with your system packages. +Install using [pipx](installation.md#using-pipx) (recommended) or [uv](installation.md#using-uv): -### Using pipx ```bash +# Using pipx pipx install speedtest-cloudflare-cli -``` -### Using uv -```bash +# Using uv uv tool install speedtest-cloudflare-cli ``` -### Using pip -> [!WARNING] -> -> It is not recommended to install this package using pip. It will install the package in your system packages and may interfere with other packages. +See the [Installation Guide](installation.md) for more options. + +### Basic Usage + +Run a complete speed test: ```bash -pip install speedtest-cloudflare-cli +speedtest-cli ``` -## Usage +![Speedtest output](assets/speedtest_output.png) -Run the following command to test your internet speed. +Open results in an interactive web dashboard: ```bash -speedtest-cli +speedtest-cli --web_view ``` -![Speedtest output](assets/speedtest_output.png) +Export results to JSON: -For more information, run the --help command. ```bash -speedtest-cli --help +speedtest-cli --json-output results.json ``` -![Help output](assets/help.png) +See the [Usage Guide](usage.md) for all available options and examples. + +## Why speedtest-cli? + +- **Cloudflare Infrastructure** - Leverage one of the world's largest and fastest networks +- **Privacy Focused** - No account required, no tracking, open source +- **Modern Python** - Built with type hints, async support, and modern best practices +- **Beautiful UX** - Powered by [Rich](https://github.com/Textualize/rich) for stunning terminal output +- **Automation Friendly** - JSON output and silent mode for scripts and monitoring -## Running in a container +## Quick Links -### Using Podman +- **[Installation](installation.md)** - Detailed installation instructions for all platforms +- **[Usage Guide](usage.md)** - Complete guide to all CLI options and features +- **[Features](features.md)** - In-depth look at capabilities and metrics +- **[Web Dashboard](web-dashboard.md)** - Interactive dashboard features +- **[Docker](docker.md)** - Running in containers +- **[API Reference](api-reference.md)** - Using as a Python library +- **[Contributing](contributing.md)** - Development setup and guidelines +- **[FAQ](faq.md)** - Common questions and troubleshooting + +## Running in a Container + +Pre-built container images are available: ```bash +# Using Podman podman run --rm -it ghcr.io/takitsu21/speedtest:latest + +# Using Docker +docker run --rm -it ghcr.io/takitsu21/speedtest:latest ``` -### Using Docker +See the [Docker Guide](docker.md) for more details. -```bash -docker run --rm -it ghcr.io/takitsu21/speedtest:latest -``` \ No newline at end of file +## Example Output + +When you run `speedtest-cli`, you'll see: + +1. **Connection Information** - Your IP, ISP, and location +2. **Progress Tracking** - Real-time progress bars for downloads/uploads +3. **Results Table** - Formatted table with all metrics: + - Download speed (Mbps) + - Upload speed (Mbps) + - Ping latency (ms) + - Jitter (ms) + - HTTP latency (ms) + +## Support + +- **Documentation** - You're reading it! +- **Issues** - [GitHub Issues](https://github.com/takitsu21/speedtest/issues) +- **Discussions** - [GitHub Discussions](https://github.com/takitsu21/speedtest/discussions) + +## License + +This project is licensed under the MIT License - see the [LICENSE](https://github.com/takitsu21/speedtest/blob/main/LICENSE) file for details. diff --git a/docs/installation.md b/docs/installation.md new file mode 100644 index 0000000..6f601f8 --- /dev/null +++ b/docs/installation.md @@ -0,0 +1,318 @@ +# Installation + +This guide covers all the ways to install **speedtest-cli** on your system. + +## System Requirements + +- **Python**: 3.9, 3.10, 3.11, 3.12, or 3.13 +- **Operating Systems**: Linux, macOS, Windows +- **Network**: Internet connection with ICMP (ping) access (optional but recommended) + +## Recommended Installation Methods + +We strongly recommend using **pipx** or **uv** to install speedtest-cli. These tools create isolated environments for each application, preventing dependency conflicts with your system packages. + +### Using pipx + +[pipx](https://github.com/pypa/pipx) is a tool to help you install and run end-user applications written in Python. It's similar to macOS's brew, JavaScript's npx, and Linux's apt/yum. + +#### Install pipx + +If you don't have pipx installed: + +=== "Linux" + ```bash + # Ubuntu/Debian + sudo apt update + sudo apt install pipx + pipx ensurepath + + # Fedora + sudo dnf install pipx + pipx ensurepath + + # Arch Linux + sudo pacman -S python-pipx + pipx ensurepath + ``` + +=== "macOS" + ```bash + brew install pipx + pipx ensurepath + ``` + +=== "Windows" + ```powershell + # Using scoop + scoop install pipx + pipx ensurepath + + # Or using pip + python -m pip install --user pipx + python -m pipx ensurepath + ``` + +#### Install speedtest-cli + +```bash +pipx install speedtest-cloudflare-cli +``` + +#### Verify Installation + +```bash +speedtest-cli --version +``` + +### Using uv + +[uv](https://github.com/astral-sh/uv) is an extremely fast Python package installer and resolver written in Rust. It's the fastest way to install Python packages. + +#### Install uv + +```bash +# Linux and macOS +curl -LsSf https://astral.sh/uv/install.sh | sh + +# Windows +powershell -c "irm https://astral.sh/uv/install.ps1 | iex" +``` + +#### Install speedtest-cli + +```bash +uv tool install speedtest-cloudflare-cli +``` + +#### Verify Installation + +```bash +speedtest-cli --version +``` + +## Alternative Installation Methods + +### Using pip + +!!! warning "Not Recommended" + Installing with pip directly can interfere with your system's Python packages. Use pipx or uv instead. + +If you still want to use pip: + +```bash +# Install for current user only (recommended if using pip) +pip install --user speedtest-cloudflare-cli + +# Or install system-wide (requires admin/sudo) +sudo pip install speedtest-cloudflare-cli +``` + +### From Source + +For developers who want to contribute or test the latest changes: + +#### Clone the Repository + +```bash +git clone https://github.com/takitsu21/speedtest.git +cd speedtest +``` + +#### Install with uv (Recommended for Development) + +```bash +# Install uv if you haven't already +curl -LsSf https://astral.sh/uv/install.sh | sh + +# Sync all dependencies including dev dependencies +uv sync + +# Run from source +uv run speedtest-cli +``` + +#### Install with pip + +```bash +# Create a virtual environment +python -m venv venv +source venv/bin/activate # On Windows: venv\Scripts\activate + +# Install in editable mode with dev dependencies +pip install -e ".[dev]" + +# Run +speedtest-cli +``` + +### Using Container Images + +See the [Docker Guide](docker.md) for running speedtest-cli in containers. + +## Post-Installation + +### Verify Installation + +After installation, verify that speedtest-cli is correctly installed: + +```bash +speedtest-cli --version +``` + +You should see output like: +``` +speedtest-cli, version 1.x.x +``` + +### Run Your First Speed Test + +```bash +speedtest-cli +``` + +This will run a complete speed test and display results in your terminal. + +### Check Available Options + +```bash +speedtest-cli --help +``` + +## Upgrading + +### With pipx + +```bash +pipx upgrade speedtest-cloudflare-cli +``` + +### With uv + +```bash +uv tool upgrade speedtest-cloudflare-cli +``` + +### With pip + +```bash +pip install --upgrade speedtest-cloudflare-cli +``` + +## Uninstalling + +### With pipx + +```bash +pipx uninstall speedtest-cloudflare-cli +``` + +### With uv + +```bash +uv tool uninstall speedtest-cloudflare-cli +``` + +### With pip + +```bash +pip uninstall speedtest-cloudflare-cli +``` + +## Troubleshooting + +### Command Not Found + +If you get a "command not found" error after installation: + +1. **Ensure the installation directory is in your PATH**: + + ```bash + # For pipx + pipx ensurepath + + # For uv + # The installer usually adds this automatically + ``` + +2. **Restart your terminal** or reload your shell configuration: + + ```bash + # Bash + source ~/.bashrc + + # Zsh + source ~/.zshrc + ``` + +3. **Check the installation location**: + + ```bash + # For pipx + pipx list + + # For uv + uv tool list + ``` + +### Permission Denied + +If you get permission errors: + +- **Don't use sudo with pipx or uv** - they install to your user directory +- **Use `--user` flag with pip**: `pip install --user speedtest-cloudflare-cli` +- **Use a virtual environment** instead of system-wide installation + +### Python Version Issues + +If you have multiple Python versions installed: + +```bash +# Specify Python version explicitly +pipx install --python python3.12 speedtest-cloudflare-cli + +# Or with uv +uv tool install --python 3.12 speedtest-cloudflare-cli +``` + +### Network Issues During Installation + +If installation fails due to network issues: + +```bash +# Retry with increased timeout +pip install --timeout 300 speedtest-cloudflare-cli + +# Or use a different index +pip install --index-url https://pypi.org/simple speedtest-cloudflare-cli +``` + +## Platform-Specific Notes + +### Linux + +- **ICMP Permissions**: For accurate ping measurements, you may need to set capabilities: + + ```bash + sudo setcap cap_net_raw+ep $(which python3) + ``` + + Or run with sudo (not recommended for regular use). + +### macOS + +- **Homebrew Users**: If you have issues with Python from Homebrew, try using pipx or uv +- **System Integrity Protection**: No special configuration needed + +### Windows + +- **Windows Terminal**: For best visual experience, use [Windows Terminal](https://aka.ms/terminal) +- **PowerShell**: Works in PowerShell, CMD, and Git Bash +- **ICMP Permissions**: Usually available by default on Windows + +## Next Steps + +- **[Usage Guide](usage.md)** - Learn all the command-line options +- **[Features](features.md)** - Explore what speedtest-cli can do +- **[Web Dashboard](web-dashboard.md)** - Use the interactive dashboard +- **[FAQ](faq.md)** - Common questions and solutions diff --git a/docs/usage.md b/docs/usage.md new file mode 100644 index 0000000..2dee573 --- /dev/null +++ b/docs/usage.md @@ -0,0 +1,511 @@ +# Usage Guide + +This guide covers all the command-line options and common usage patterns for **speedtest-cli**. + +## Basic Usage + +Run a complete speed test with default settings: + +```bash +speedtest-cli +``` + +This will: + +1. Detect your network information (IP, ISP, location) +2. Measure ping latency and jitter +3. Test download speed +4. Test upload speed +5. Display results in a formatted table + +## Command-Line Options + +### General Options + +#### `--version` + +Display the version of speedtest-cli and exit. + +```bash +speedtest-cli --version +``` + +**Output:** +``` +speedtest-cli, version 1.x.x +``` + +#### `--help` + +Show help message with all available options. + +```bash +speedtest-cli --help +``` + +--- + +### Test Selection Options + +#### `--download` / `-d` + +Run **only** the download speed test. + +```bash +speedtest-cli --download +# or +speedtest-cli -d +``` + +**Use Case:** Quick check of your download speed without waiting for upload test. + +**Example Output:** +``` +Download: 150.5 Mbps +Ping: 12 ms +Jitter: 2 ms +``` + +#### `--upload` / `-u` + +Run **only** the upload speed test. + +```bash +speedtest-cli --upload +# or +speedtest-cli -u +``` + +**Use Case:** Test upload speed for video conferencing or file uploads. + +**Example Output:** +``` +Upload: 45.3 Mbps +Ping: 12 ms +Jitter: 2 ms +``` + +!!! tip "Combine Both" + You can combine both flags to run both tests (same as default): + ```bash + speedtest-cli -d -u + ``` + +--- + +### Test Configuration Options + +#### `--download_size` / `-ds` + +Specify the download size in megabytes (MB). + +```bash +speedtest-cli --download_size 50 +# or +speedtest-cli -ds 50 +``` + +**Default:** Varies based on implementation +**Use Case:** +- Smaller size for quick tests on slow connections +- Larger size for more accurate measurements on fast connections + +**Example:** +```bash +# Quick test with 10 MB download +speedtest-cli -d -ds 10 + +# Thorough test with 100 MB download +speedtest-cli -d -ds 100 +``` + +#### `--upload_size` / `-us` + +Specify the upload size in megabytes (MB). + +```bash +speedtest-cli --upload_size 25 +# or +speedtest-cli -us 25 +``` + +**Default:** Varies based on implementation +**Use Case:** Similar to download_size, adjust based on your connection speed. + +**Example:** +```bash +# Test upload with 5 MB +speedtest-cli -u -us 5 +``` + +#### `--attempts` / `-a` + +Specify the number of test attempts. + +```bash +speedtest-cli --attempts 3 +# or +speedtest-cli -a 3 +``` + +**Default:** 1 +**Use Case:** Run multiple attempts to get average results and reduce variance. + +**Example:** +```bash +# Run 5 attempts for more reliable results +speedtest-cli -a 5 +``` + +--- + +### Output Options + +#### `--json` + +Output results in JSON format to stdout. + +```bash +speedtest-cli --json +``` + +**Example Output:** +```json +{ + "download": 150.5, + "upload": 45.3, + "ping": 12, + "jitter": 2, + "http_latency": 15, + "metadata": { + "ip": "203.0.113.45", + "isp": "Example ISP", + "city": "San Francisco", + "region": "California", + "country": "US", + "loc": "37.7749,-122.4194", + "colo": "SFO" + } +} +``` + +**Use Case:** +- Automation and scripting +- Integration with monitoring systems +- Processing results programmatically + +**Example:** +```bash +# Parse JSON with jq +speedtest-cli --json | jq '.download' + +# Save to variable in bash +DOWNLOAD_SPEED=$(speedtest-cli --json | jq -r '.download') +echo "Download speed: $DOWNLOAD_SPEED Mbps" +``` + +#### `--json-output` + +Save JSON results to a file. + +```bash +speedtest-cli --json-output results.json +``` + +**Use Case:** +- Logging test results over time +- Storing results for later analysis +- Integration with data analysis tools + +**Example:** +```bash +# Save with timestamp +speedtest-cli --json-output "speedtest_$(date +%Y%m%d_%H%M%S).json" + +# Append to log file (requires manual JSON array handling) +speedtest-cli --json-output daily_results.json +``` + +#### `--silent` + +Run in silent mode with minimal output. + +```bash +speedtest-cli --silent +``` + +**Use Case:** +- Running in background scripts +- Cron jobs +- When you only care about exit codes or JSON output + +**Example:** +```bash +# Combine with JSON output for automation +speedtest-cli --silent --json-output /var/log/speedtest.json + +# Use in scripts +if speedtest-cli --silent; then + echo "Speed test completed successfully" +fi +``` + +#### `--web_view` + +Open results in a web browser with an interactive dashboard. + +```bash +speedtest-cli --web_view +``` + +**Use Case:** +- Visual representation of results +- Sharing results with others +- Seeing location on a map + +See the [Web Dashboard Guide](web-dashboard.md) for more details. + +--- + +## Common Usage Patterns + +### Quick Download Test + +Test only download speed with a smaller file: + +```bash +speedtest-cli -d -ds 25 +``` + +### Complete Test with JSON Export + +Run a full test and save results: + +```bash +speedtest-cli --json-output ~/speedtest_results.json +``` + +### Multiple Attempts for Accuracy + +Run 5 attempts to get average results: + +```bash +speedtest-cli -a 5 +``` + +### Automated Monitoring + +Silent mode with JSON output for scripts: + +```bash +speedtest-cli --silent --json-output /tmp/speedtest.json +``` + +### Visual Dashboard + +Run test and open in browser: + +```bash +speedtest-cli --web_view +``` + +### Custom Download and Upload Sizes + +Optimize test duration for your connection: + +```bash +# For slow connections (< 10 Mbps) +speedtest-cli -ds 10 -us 5 + +# For fast connections (> 100 Mbps) +speedtest-cli -ds 100 -us 50 +``` + +### Upload Only Test + +Test upload without download: + +```bash +speedtest-cli -u -us 25 +``` + +--- + +## Understanding the Output + +### Console Output + +When you run speedtest-cli without `--json` or `--silent`, you'll see: + +#### 1. Connection Information +``` +IP: 203.0.113.45 +ISP: Example ISP +Location: San Francisco, California, US +Cloudflare Datacenter: SFO +``` + +#### 2. Progress Bars + +Real-time progress during tests: +``` +Downloading... ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% +Uploading... ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% +``` + +#### 3. Results Table + +``` +╭─────────────────┬──────────╮ +│ Metric │ Value │ +├─────────────────┼──────────┤ +│ Download │ 150.5 Mbps│ +│ Upload │ 45.3 Mbps │ +│ Ping │ 12 ms │ +│ Jitter │ 2 ms │ +│ HTTP Latency │ 15 ms │ +╰─────────────────┴──────────╯ +``` + +### Metrics Explained + +- **Download**: Download speed in megabits per second (Mbps) +- **Upload**: Upload speed in megabits per second (Mbps) +- **Ping**: Round-trip time to Cloudflare servers in milliseconds (ms) +- **Jitter**: Variation in ping latency in milliseconds (ms) +- **HTTP Latency**: Time to establish HTTP connection in milliseconds (ms) + +### Exit Codes + +- `0`: Test completed successfully +- `1`: Test failed (network error, timeout, etc.) + +--- + +## Advanced Examples + +### Cron Job for Daily Monitoring + +Add to crontab (`crontab -e`): + +```bash +# Run speed test daily at 2 AM +0 2 * * * /usr/local/bin/speedtest-cli --silent --json-output /var/log/speedtest/$(date +\%Y\%m\%d).json +``` + +### Bash Script for Logging + +```bash +#!/bin/bash + +LOG_DIR="$HOME/speedtest_logs" +mkdir -p "$LOG_DIR" + +TIMESTAMP=$(date +%Y%m%d_%H%M%S) +OUTPUT_FILE="$LOG_DIR/speedtest_$TIMESTAMP.json" + +echo "Running speed test..." +if speedtest-cli --json-output "$OUTPUT_FILE"; then + echo "Results saved to $OUTPUT_FILE" + + # Parse and display key metrics + DOWNLOAD=$(jq -r '.download' "$OUTPUT_FILE") + UPLOAD=$(jq -r '.upload' "$OUTPUT_FILE") + + echo "Download: $DOWNLOAD Mbps" + echo "Upload: $UPLOAD Mbps" +else + echo "Speed test failed!" + exit 1 +fi +``` + +### Python Integration + +```python +import subprocess +import json + +# Run speedtest and capture JSON output +result = subprocess.run( + ['speedtest-cli', '--json'], + capture_output=True, + text=True +) + +if result.returncode == 0: + data = json.loads(result.stdout) + print(f"Download: {data['download']} Mbps") + print(f"Upload: {data['upload']} Mbps") + print(f"Ping: {data['ping']} ms") +else: + print("Speed test failed!") +``` + +### Performance Alert Script + +```bash +#!/bin/bash + +# Run test and get download speed +DOWNLOAD=$(speedtest-cli --json --silent | jq -r '.download') + +# Alert if speed is below threshold +THRESHOLD=50 +if (( $(echo "$DOWNLOAD < $THRESHOLD" | bc -l) )); then + echo "WARNING: Download speed is ${DOWNLOAD} Mbps (below ${THRESHOLD} Mbps)" + # Send notification (example using notify-send) + notify-send "Slow Internet" "Speed is only ${DOWNLOAD} Mbps" +fi +``` + +--- + +## Tips and Best Practices + +### 1. Minimize Network Activity + +Close bandwidth-heavy applications during testing: +- Stop downloads/uploads +- Pause streaming services +- Close cloud sync applications (Dropbox, Google Drive, etc.) + +### 2. Use Wired Connection + +For most accurate results: +- Use Ethernet instead of Wi-Fi when possible +- Test directly from the device connected to your modem/router + +### 3. Multiple Tests + +Run several tests at different times: +```bash +# Morning, afternoon, evening tests +for i in {1..3}; do + speedtest-cli --json-output "test_$i.json" + sleep 3600 # Wait 1 hour between tests +done +``` + +### 4. Interpret Results + +- **Download/Upload**: Should match your ISP's advertised speeds +- **Ping**: Lower is better (< 20ms is excellent, < 50ms is good) +- **Jitter**: Lower is better (< 5ms is good for gaming/VoIP) + +### 5. Troubleshooting Slow Speeds + +If results are slower than expected: +1. Test at different times of day +2. Test with wired connection +3. Restart your modem/router +4. Contact your ISP if consistently slow + +--- + +## Next Steps + +- **[Features](features.md)** - Learn about all capabilities +- **[Web Dashboard](web-dashboard.md)** - Explore the interactive dashboard +- **[API Reference](api-reference.md)** - Use speedtest-cli as a Python library +- **[FAQ](faq.md)** - Common questions and solutions diff --git a/docs/web-dashboard.md b/docs/web-dashboard.md new file mode 100644 index 0000000..6311452 --- /dev/null +++ b/docs/web-dashboard.md @@ -0,0 +1,474 @@ +# Web Dashboard + +The **speedtest-cli** web dashboard provides an interactive, visual representation of your speed test results in a beautiful HTML interface that opens in your browser. + +![Web Dashboard](assets/web_view.png) + +## Launching the Dashboard + +To run a speed test and open the results in your web browser: + +```bash +speedtest-cli --web_view +``` + +This will: + +1. Run a complete speed test +2. Generate an HTML dashboard +3. Automatically open it in your default browser + +## Dashboard Features + +### Overview + +The dashboard provides a comprehensive view of your network performance with: + +- **Visual Speed Metrics** - Large, easy-to-read speed indicators +- **Connection Quality** - At-a-glance connection status +- **Interactive Map** - Your location on an interactive map +- **Network Details** - Complete metadata about your connection +- **Theme Toggle** - Switch between light and dark modes +- **Responsive Design** - Works on desktop, tablet, and mobile + +### Main Sections + +#### 1. Speed Metrics Display + +The top section shows your primary speed test results: + +**Download Speed** +- Displayed in Mbps (megabits per second) +- Large, prominent number +- Color-coded based on speed: + - 🟢 Green: Fast (> 100 Mbps) + - 🟡 Yellow: Medium (25-100 Mbps) + - 🔴 Red: Slow (< 25 Mbps) + +**Upload Speed** +- Displayed in Mbps +- Similar color coding +- Typically lower than download + +**Latency Metrics** +- **Ping**: Round-trip time in milliseconds + - 🟢 Excellent: < 20ms + - 🟡 Good: 20-50ms + - 🔴 Poor: > 50ms +- **Jitter**: Latency variation in milliseconds +- **HTTP Latency**: Application-level latency + +#### 2. Connection Quality Indicator + +A visual badge showing overall connection quality: + +- **Excellent**: Low latency, high speeds +- **Good**: Decent performance for most tasks +- **Fair**: Adequate for basic browsing +- **Poor**: May experience slowdowns + +**Calculation:** +Based on a combination of: +- Download speed +- Upload speed +- Ping latency +- Jitter + +#### 3. Interactive Map + +Powered by [Leaflet.js](https://leafletjs.com/), the map shows: + +**Your Location** +- Pin marker at your coordinates +- Based on IP geolocation +- City/region displayed + +**Map Features** +- Zoom in/out controls +- Pan around the map +- OpenStreetMap tiles +- Responsive to screen size + +**Privacy Note:** +The map is rendered entirely in your browser using your approximate location from Cloudflare's API. No tracking or external requests beyond map tiles. + +#### 4. Network Metadata + +Detailed information about your connection: + +**IP Information** +``` +IP Address: 203.0.113.45 +IPv6: 2001:0db8:85a3::8a2e:0370:7334 (if available) +``` + +**ISP Details** +``` +Provider: Example Broadband +ASN: AS12345 +``` + +**Location Details** +``` +City: San Francisco +Region: California +Country: United States +Coordinates: 37.7749, -122.4194 +``` + +**Cloudflare Information** +``` +Data Center: SFO +Colo: San Francisco +``` + +### Theme Toggle + +Switch between light and dark modes for comfortable viewing in any environment. + +**Light Mode** +- Bright background +- Dark text +- Better for daytime viewing +- Reduced eye strain in bright environments + +**Dark Mode** +- Dark background +- Light text +- Better for nighttime viewing +- Reduced blue light exposure +- Easier on the eyes in dark rooms + +**How to Switch:** +- Click the theme toggle button (usually top-right) +- Theme preference saved in browser +- Automatically persists across refreshes + +## Saving the Dashboard + +The dashboard is a standalone HTML file that includes all results and resources. + +### Automatic Save Location + +When you run `speedtest-cli --web_view`, the dashboard is saved to a temporary file and opened. The file location is typically: + +- **Linux**: `/tmp/speedtest_dashboard_XXXXXX.html` +- **macOS**: `/tmp/speedtest_dashboard_XXXXXX.html` +- **Windows**: `%TEMP%\speedtest_dashboard_XXXXXX.html` + +### Manual Save + +To keep the dashboard permanently, save the HTML file from your browser: + +**Method 1: Save From Browser** +1. Run `speedtest-cli --web_view` +2. In your browser: `File` → `Save Page As...` +3. Choose location and filename +4. Save as "Webpage, Complete" or "HTML Only" + +**Method 2: Redirect Output** +Currently, the dashboard file path isn't configurable, but you can find it in the temporary directory. + +### Sharing Results + +The dashboard HTML file is **self-contained** and can be shared: + +**What's Included:** +- All test results +- Embedded CSS and JavaScript +- Map functionality (requires internet for tiles) +- Complete metadata + +**How to Share:** +1. Save the HTML file +2. Send via email, cloud storage, or file sharing +3. Recipients can open it in any modern browser +4. No installation or special software needed + +**Privacy Considerations:** +The HTML file contains: +- Your public IP address +- Your approximate location (city/region) +- Your ISP information + +Remove or redact this information if sharing publicly. + +## Dashboard Technology + +### Built With + +- **HTML5**: Modern, semantic markup +- **CSS3**: Beautiful styling with dark/light themes +- **Vanilla JavaScript**: No framework dependencies +- **Leaflet.js**: Interactive maps +- **Jinja2 Templates**: Server-side rendering + +### Browser Compatibility + +Works in all modern browsers: + +- ✅ Chrome/Chromium 90+ +- ✅ Firefox 88+ +- ✅ Safari 14+ +- ✅ Edge 90+ +- ✅ Opera 76+ + +**Minimum Requirements:** +- JavaScript enabled +- ES6 support +- LocalStorage (for theme preference) + +### Mobile Support + +Fully responsive design optimized for: + +- 📱 Smartphones (portrait and landscape) +- 📱 Tablets (all orientations) +- 💻 Laptops and desktops +- 🖥️ Large displays + +**Mobile Features:** +- Touch-friendly controls +- Optimized layout for small screens +- Fast loading +- No horizontal scrolling + +## Use Cases + +### 1. ISP Verification + +Run tests and save dashboards to document your actual speeds vs. advertised speeds: + +```bash +# Run test and save dashboard +speedtest-cli --web_view +# Save the HTML file for your records +``` + +**Great For:** +- Comparing to ISP promises +- Documenting performance issues +- Submitting to customer support + +### 2. Network Troubleshooting + +Visual representation helps identify issues: + +- **High Ping/Jitter**: Network instability +- **Low Download**: ISP or Wi-Fi issues +- **Low Upload**: Router or ISP configuration +- **Location Mismatch**: VPN or routing issues + +### 3. Sharing Results + +Send dashboard to: +- IT support for troubleshooting +- Friends for comparison +- Social media for discussion +- ISP customer service for evidence + +### 4. Before/After Comparisons + +Document network changes: + +```bash +# Before upgrade +speedtest-cli --web_view +# Save as "before_upgrade.html" + +# After upgrade +speedtest-cli --web_view +# Save as "after_upgrade.html" +``` + +Compare the two dashboards side-by-side. + +### 5. Multiple Location Testing + +Test from different locations and save results: + +- Home office +- Living room (Wi-Fi) +- Different floors +- During different times of day + +### 6. Visual Presentations + +Use in reports or presentations: + +- Screenshot the dashboard +- Embed in PowerPoint/Google Slides +- Include in network documentation +- Share in team meetings + +## Customization + +### Current Customization Options + +The dashboard currently includes: + +- **Theme Toggle**: Switch between light/dark +- **Automatic Browser Detection**: Opens in default browser +- **Responsive Layout**: Adapts to screen size + +### Future Customization + +Planned features (check GitHub for updates): + +- Custom color schemes +- Export to PDF +- Chart/graph views +- Historical comparison +- Multiple test results in one dashboard + +## Troubleshooting + +### Dashboard Won't Open + +**Problem:** Browser doesn't open automatically + +**Solutions:** + +1. **Check Default Browser**: + - Ensure you have a default browser set + - Try setting a different default + +2. **Manual Open**: + - Find the temporary HTML file in `/tmp` or `%TEMP%` + - Open it manually in your browser + +3. **Check Browser Installation**: + ```bash + # Linux: Try explicitly + firefox "$(find /tmp -name 'speedtest_dashboard*.html' | head -1)" + + # macOS + open "$(find /tmp -name 'speedtest_dashboard*.html' | head -1)" + + # Windows + start chrome "C:\Users\YourName\AppData\Local\Temp\speedtest_dashboard*.html" + ``` + +### Map Not Displaying + +**Problem:** Interactive map shows empty or broken + +**Solutions:** + +1. **Check Internet Connection**: Map tiles require internet +2. **Check Firewall**: Allow access to OpenStreetMap servers +3. **Try Different Browser**: Some browsers block external resources +4. **Disable Extensions**: Ad blockers might block map resources + +### Theme Not Switching + +**Problem:** Theme toggle button doesn't work + +**Solutions:** + +1. **Enable JavaScript**: Dashboard requires JavaScript +2. **Clear Browser Cache**: Old files might be cached +3. **Check Browser Console**: Look for JavaScript errors (F12 → Console) +4. **Try Incognito/Private Mode**: Test without extensions + +### Incorrect Location + +**Problem:** Map shows wrong location + +**Explanation:** +- Location is based on IP geolocation from Cloudflare +- May not be exact street address +- Usually accurate to city/region level +- VPNs will show VPN server location + +**This is Normal:** +IP-based geolocation is approximate and can be: +- Several miles off +- In a nearby city +- At ISP's location rather than yours + +### Dashboard Looks Broken + +**Problem:** Styling issues or layout problems + +**Solutions:** + +1. **Update Browser**: Use latest version +2. **Enable CSS**: Ensure stylesheets are loaded +3. **Check Browser Compatibility**: Use supported browser +4. **Disable Reader Mode**: May interfere with layout +5. **Reset Zoom**: Set browser zoom to 100% + +## Privacy and Security + +### Data in Dashboard + +The HTML file contains: + +**Personal Information:** +- Public IP address +- Approximate location (city/region) +- ISP name + +**Does NOT Contain:** +- Exact home address +- Personal identification +- Browsing history +- Device information beyond test results + +### Safe Sharing Practices + +**Public Sharing:** +If posting online, consider: +- Blurring or editing IP address +- Removing precise coordinates +- Using screenshot instead of full HTML + +**Private Sharing:** +For IT support or troubleshooting: +- Full HTML is helpful +- Contains necessary diagnostic info +- Can be shared safely with trusted parties + +### Local Storage + +**What's Stored:** +- Theme preference (light/dark) +- Saved in browser's localStorage + +**What's NOT Stored:** +- Test results +- Personal data +- Analytics or tracking + +## Comparison: Dashboard vs. Console + +| Feature | Web Dashboard | Console Output | +|---------|---------------|----------------| +| **Visual Appeal** | High | Medium | +| **Interactivity** | Yes (map, theme) | No | +| **Shareability** | Easy (HTML file) | Screenshot needed | +| **Automation** | Manual | Easy (scripting) | +| **Details** | All metadata | All metrics | +| **Map** | Yes | No | +| **Theme** | Light/Dark | Terminal theme | +| **Browser Required** | Yes | No | + +**Use Dashboard When:** +- Sharing results with others +- Presenting to non-technical users +- Documenting for records +- Visual comparison needed + +**Use Console When:** +- Automation/scripting +- Quick tests +- Headless environments +- CI/CD pipelines + +## Next Steps + +- **[Usage Guide](usage.md)** - Learn all CLI options +- **[Features](features.md)** - Explore all capabilities +- **[API Reference](api-reference.md)** - Programmatic access +- **[FAQ](faq.md)** - Common questions and troubleshooting diff --git a/mkdocs.yml b/mkdocs.yml index b7a9604..4f84f61 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -8,7 +8,18 @@ repo_name: takitsu21/speedtest copyright: Maintained by takitsu21. nav: - - Getting started: index.md + - Home: index.md + - User Guide: + - Installation: installation.md + - Usage: usage.md + - Features: features.md + - Web Dashboard: web-dashboard.md + - Deployment: + - Docker: docker.md + - For Developers: + - API Reference: api-reference.md + - Contributing: contributing.md + - FAQ: faq.md plugins: - search - mkdocstrings: diff --git a/speedtest_cloudflare_cli/core/speedtest.py b/speedtest_cloudflare_cli/core/speedtest.py index 7f9f791..8a3aacc 100644 --- a/speedtest_cloudflare_cli/core/speedtest.py +++ b/speedtest_cloudflare_cli/core/speedtest.py @@ -30,10 +30,7 @@ @functools.cache def client() -> httpx.Client: - headers = { - "Connection": "Keep-Alive", - "Referer": CLOUDFLARE_HOST - } + headers = {"Connection": "Keep-Alive", "Referer": f"https://{CLOUDFLARE_HOST}/"} return httpx.Client(headers=headers, timeout=None) # noqa: S113 diff --git a/speedtest_cloudflare_cli/main.py b/speedtest_cloudflare_cli/main.py index ac4bd7e..7129830 100644 --- a/speedtest_cloudflare_cli/main.py +++ b/speedtest_cloudflare_cli/main.py @@ -16,7 +16,7 @@ DOWNLOAD_SIZE = 30 # 30MB UPLOAD_SIZE = 30 # 30MB -SPEEDTEST_URL = "https://speed.cloudflare.com/" +SPEEDTEST_URL = "https://speed.cloudflare.com" def display_results( diff --git a/speedtest_cloudflare_cli/models/metadata.py b/speedtest_cloudflare_cli/models/metadata.py index 503cf4b..a625447 100644 --- a/speedtest_cloudflare_cli/models/metadata.py +++ b/speedtest_cloudflare_cli/models/metadata.py @@ -1,6 +1,6 @@ import datetime -from pydantic import BaseModel, Field, computed_field +from pydantic import BaseModel, Field, computed_field, field_validator class Metadata(BaseModel): @@ -17,6 +17,14 @@ class Metadata(BaseModel): latitude: str longitude: str + @field_validator("colo", mode="before") + @classmethod + def extract_colo_iata(cls, v): + """Extract IATA code from colo object if present.""" + if isinstance(v, dict): + return v.get("iata", "N/A") + return v # Return as-is if already a string + @computed_field @property def is_ipv6(self) -> bool: