mirror of
https://github.com/jorijn/meshcore-stats.git
synced 2026-06-26 12:51:22 +02:00
a9f6926104
* test: add comprehensive pytest test suite with 95% coverage Add full unit and integration test coverage for the meshcore-stats project: - 1020 tests covering all modules (db, charts, html, reports, client, etc.) - 95.95% code coverage with pytest-cov (95% threshold enforced) - GitHub Actions CI workflow for automated testing on push/PR - Proper mocking of external dependencies (meshcore, serial, filesystem) - SVG snapshot infrastructure for chart regression testing - Integration tests for collection and rendering pipelines Test organization: - tests/charts/: Chart rendering and statistics - tests/client/: MeshCore client and connection handling - tests/config/: Environment and configuration parsing - tests/database/: SQLite operations and migrations - tests/html/: HTML generation and Jinja templates - tests/reports/: Report generation and formatting - tests/retry/: Circuit breaker and retry logic - tests/unit/: Pure unit tests for utilities - tests/integration/: End-to-end pipeline tests 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * chore: add test-engineer agent configuration Add project-local test-engineer agent for pytest test development, coverage analysis, and test review tasks. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * docs: comprehensive test suite review with 956 tests analyzed Conducted thorough review of all 956 test cases across 47 test files: - Unit Tests: 338 tests (battery, metrics, log, telemetry, env, charts, html, reports, formatters) - Config Tests: 53 tests (env loading, config file parsing) - Database Tests: 115 tests (init, insert, queries, migrations, maintenance, validation) - Retry Tests: 59 tests (circuit breaker, async retries, factory) - Charts Tests: 76 tests (transforms, statistics, timeseries, rendering, I/O) - HTML Tests: 81 tests (site generation, Jinja2, metrics builders, reports index) - Reports Tests: 149 tests (location, JSON/TXT formatting, aggregation, counter totals) - Client Tests: 63 tests (contacts, connection, meshcore availability, commands) - Integration Tests: 22 tests (reports, collection, rendering pipelines) Results: - Overall Pass Rate: 99.7% (953/956) - 3 tests marked for improvement (empty test bodies in client tests) - 0 tests requiring fixes Key findings documented in test_review/tests.md including quality observations, F.I.R.S.T. principle adherence, and recommendations. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * test: implement snapshot testing for charts and reports Add comprehensive snapshot testing infrastructure: SVG Chart Snapshots: - Deterministic fixtures with fixed timestamps (2024-01-15 12:00:00) - Tests for gauge/counter metrics in light/dark themes - Empty chart and single-point edge cases - Extended normalize_svg_for_snapshot_full() for reproducible comparisons TXT Report Snapshots: - Monthly/yearly report snapshots for repeater and companion - Empty report handling tests - Tests in tests/reports/test_snapshots.py Infrastructure: - tests/snapshots/conftest.py with shared fixtures - UPDATE_SNAPSHOTS=1 environment variable for regeneration - scripts/generate_snapshots.py for batch snapshot generation Run `UPDATE_SNAPSHOTS=1 pytest tests/charts/test_chart_render.py::TestSvgSnapshots` to generate initial snapshots. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * test: fix SVG normalization and generate initial snapshots Fix normalize_svg_for_snapshot() to handle: - clipPath IDs like id="p47c77a2a6e" - url(#p...) references - xlink:href="#p..." references - <dc:date> timestamps Generated initial snapshot files: - 7 SVG chart snapshots (gauge, counter, empty, single-point in light/dark) - 6 TXT report snapshots (monthly/yearly for repeater/companion + empty) All 13 snapshot tests now pass. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * test: fix SVG normalization to preserve axis rendering The SVG normalization was replacing all matplotlib-generated IDs with the same value, causing duplicate IDs that broke SVG rendering: - Font glyphs, clipPaths, and tick marks all got id="normalized" - References couldn't resolve to the correct elements - X and Y axes failed to render in normalized snapshots Fix uses type-specific prefixes with sequential numbering: - glyph_N for font glyphs (DejaVuSans-XX patterns) - clip_N for clipPath definitions (p[0-9a-f]{8,} patterns) - tick_N for tick marks (m[0-9a-f]{8,} patterns) This ensures all IDs remain unique while still being deterministic for snapshot comparison. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * chore: add coverage and pytest artifacts to gitignore Add .coverage, .coverage.*, htmlcov/, and .pytest_cache/ to prevent test artifacts from being committed. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * style: fix all ruff lint errors across codebase - Sort and organize imports (I001) - Use modern type annotations (X | Y instead of Union, collections.abc) - Remove unused imports (F401) - Combine nested if statements (SIM102) - Use ternary operators where appropriate (SIM108) - Combine nested with statements (SIM117) - Use contextlib.suppress instead of try-except-pass (SIM105) - Add noqa comments for intentional SIM115 violations (file locks) - Add TYPE_CHECKING import for forward references - Fix exception chaining (B904) All 1033 tests pass. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * docs: add TDD workflow and pre-commit requirements to CLAUDE.md - Add mandatory test-driven development workflow (write tests first) - Add pre-commit requirements (must run lint and tests before committing) - Document test organization and running commands - Document 95% coverage requirement 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: resolve mypy type checking errors with proper structural fixes - charts.py: Create PeriodConfig dataclass for type-safe period configuration, use mdates.date2num() for matplotlib datetime handling, fix x-axis limits for single-point charts - db.py: Add explicit int() conversion with None handling for SQLite returns - env.py: Add class-level type annotations to Config class - html.py: Add MetricDisplay TypedDict, fix import order, add proper type annotations for table data functions - meshcore_client.py: Add return type annotation Update tests to use new dataclass attribute access and regenerate SVG snapshots. Add mypy step to CLAUDE.md pre-commit requirements. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: cast Jinja2 template.render() to str for mypy Jinja2's type stubs declare render() as returning Any, but it actually returns str. Wrap with str() to satisfy mypy's no-any-return check. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * ci: improve workflow security and reliability - test.yml: Pin all actions by SHA, add concurrency control to cancel in-progress runs on rapid pushes - release-please.yml: Pin action by SHA, add 10-minute timeout - conftest.py: Fix snapshot_base_time to use explicit UTC timezone for consistent behavior across CI and local environments Regenerate SVG snapshots with UTC-aware timestamps. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: add mypy command to permissions in settings.local.json * test: add comprehensive script tests with coroutine warning fixes - Add tests/scripts/ with tests for collect_companion, collect_repeater, and render scripts (1135 tests total, 96% coverage) - Fix unawaited coroutine warnings by using AsyncMock properly for async functions and async_context_manager_factory fixture for context managers - Add --cov=scripts to CI workflow and pyproject.toml coverage config - Omit scripts/generate_snapshots.py from coverage (dev utility) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * docs: migrate claude setup to codex skills * feat: migrate dependencies to uv (#31) * fix: run tests through uv * test: fix ruff lint issues in tests Consolidate patch context managers and clean unused imports/variables Use datetime.UTC in snapshot fixtures * test: avoid unawaited async mocks in entrypoint tests * ci: replace codecov with github coverage artifacts Add junit XML output and coverage summary in job output Upload HTML and XML coverage artifacts (3.12 only) on every run --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
318 lines
10 KiB
Python
318 lines
10 KiB
Python
"""Tests for shared formatting functions."""
|
|
|
|
from meshmon.formatters import (
|
|
format_compact_number,
|
|
format_duration,
|
|
format_duration_compact,
|
|
format_number,
|
|
format_time,
|
|
format_uptime,
|
|
format_value,
|
|
format_voltage_with_pct,
|
|
)
|
|
|
|
|
|
class TestFormatTime:
|
|
"""Test format_time function."""
|
|
|
|
def test_none_returns_na(self):
|
|
"""None timestamp returns N/A."""
|
|
assert format_time(None) == "N/A"
|
|
|
|
def test_valid_timestamp(self):
|
|
"""Valid timestamp formats correctly."""
|
|
import time
|
|
# Use a recent timestamp and verify it produces a datetime string
|
|
ts = int(time.time()) - 3600 # 1 hour ago
|
|
result = format_time(ts)
|
|
# Should produce a datetime string with format YYYY-MM-DD HH:MM:SS
|
|
assert len(result) == 19 # "2024-06-15 14:30:45" format
|
|
assert "-" in result
|
|
assert ":" in result
|
|
|
|
def test_zero_timestamp(self):
|
|
"""Zero timestamp (epoch) formats correctly."""
|
|
result = format_time(0)
|
|
assert "1970" in result
|
|
|
|
def test_invalid_timestamp_returns_na(self):
|
|
"""Invalid timestamps return N/A."""
|
|
# Extremely large value that causes OSError
|
|
assert format_time(99999999999999) == "N/A"
|
|
|
|
def test_negative_timestamp(self):
|
|
"""Negative timestamp (before epoch) should work or return N/A."""
|
|
result = format_time(-86400)
|
|
# Either formats pre-epoch time or returns N/A (platform-dependent)
|
|
assert result == "N/A" or "1969" in result
|
|
|
|
|
|
class TestFormatValue:
|
|
"""Test format_value function."""
|
|
|
|
def test_none_returns_na(self):
|
|
"""None value returns N/A."""
|
|
assert format_value(None) == "N/A"
|
|
|
|
def test_float_two_decimals(self):
|
|
"""Float values are formatted to 2 decimal places."""
|
|
assert format_value(3.14159) == "3.14"
|
|
assert format_value(0.0) == "0.00"
|
|
assert format_value(100.999) == "101.00"
|
|
|
|
def test_integer_unchanged(self):
|
|
"""Integer values are converted to string."""
|
|
assert format_value(42) == "42"
|
|
assert format_value(0) == "0"
|
|
|
|
def test_string_unchanged(self):
|
|
"""String values pass through."""
|
|
assert format_value("hello") == "hello"
|
|
|
|
def test_negative_float(self):
|
|
"""Negative floats format correctly."""
|
|
assert format_value(-12.345) == "-12.35"
|
|
|
|
|
|
class TestFormatNumber:
|
|
"""Test format_number function."""
|
|
|
|
def test_none_returns_na(self):
|
|
"""None value returns N/A."""
|
|
assert format_number(None) == "N/A"
|
|
|
|
def test_small_numbers(self):
|
|
"""Small numbers without separators."""
|
|
assert format_number(0) == "0"
|
|
assert format_number(999) == "999"
|
|
|
|
def test_thousands_separator(self):
|
|
"""Numbers >= 1000 get comma separators."""
|
|
assert format_number(1000) == "1,000"
|
|
assert format_number(1234567) == "1,234,567"
|
|
|
|
def test_negative_numbers(self):
|
|
"""Negative numbers format correctly."""
|
|
assert format_number(-1234) == "-1,234"
|
|
|
|
|
|
class TestFormatDuration:
|
|
"""Test format_duration function."""
|
|
|
|
def test_none_returns_na(self):
|
|
"""None value returns N/A."""
|
|
assert format_duration(None) == "N/A"
|
|
|
|
def test_zero_seconds(self):
|
|
"""Zero seconds shows just 0s."""
|
|
assert format_duration(0) == "0s"
|
|
|
|
def test_seconds_only(self):
|
|
"""Less than a minute shows seconds only (with 0h 0m prefix)."""
|
|
result = format_duration(45)
|
|
assert "45s" in result
|
|
|
|
def test_minutes_and_seconds(self):
|
|
"""Minutes and seconds format."""
|
|
result = format_duration(125) # 2m 5s
|
|
assert "2m" in result
|
|
assert "5s" in result
|
|
|
|
def test_hours_minutes_seconds(self):
|
|
"""Hours, minutes, and seconds format."""
|
|
result = format_duration(3725) # 1h 2m 5s
|
|
assert "1h" in result
|
|
assert "2m" in result
|
|
assert "5s" in result
|
|
|
|
def test_days_hours_minutes_seconds(self):
|
|
"""Full duration with days."""
|
|
result = format_duration(90125) # 1d 1h 2m 5s
|
|
assert "1d" in result
|
|
assert "1h" in result
|
|
assert "2m" in result
|
|
assert "5s" in result
|
|
|
|
def test_exact_day(self):
|
|
"""Exactly one day."""
|
|
result = format_duration(86400)
|
|
assert "1d" in result
|
|
assert "0h" in result
|
|
|
|
def test_multiple_days(self):
|
|
"""Multiple days."""
|
|
result = format_duration(172800) # 2 days
|
|
assert "2d" in result
|
|
|
|
|
|
class TestFormatUptime:
|
|
"""Test format_uptime function."""
|
|
|
|
def test_none_returns_na(self):
|
|
"""None value returns N/A."""
|
|
assert format_uptime(None) == "N/A"
|
|
|
|
def test_zero_seconds(self):
|
|
"""Zero seconds shows just 0m."""
|
|
assert format_uptime(0) == "0m"
|
|
|
|
def test_under_minute(self):
|
|
"""Less than a minute shows 0m."""
|
|
assert format_uptime(45) == "0m"
|
|
|
|
def test_minutes_only(self):
|
|
"""Minutes only (no hours/days)."""
|
|
assert format_uptime(120) == "2m"
|
|
|
|
def test_hours_and_minutes(self):
|
|
"""Hours and minutes format."""
|
|
result = format_uptime(3720) # 1h 2m
|
|
assert "1h" in result
|
|
assert "2m" in result
|
|
|
|
def test_days_hours_minutes(self):
|
|
"""Days, hours, and minutes format (no seconds in uptime)."""
|
|
result = format_uptime(90120) # 1d 1h 2m
|
|
assert "1d" in result
|
|
assert "1h" in result
|
|
assert "2m" in result
|
|
# Seconds not included in uptime format
|
|
assert "s" not in result
|
|
|
|
def test_exact_hour(self):
|
|
"""Exactly one hour shows 0m."""
|
|
result = format_uptime(3600)
|
|
assert "1h" in result
|
|
assert "0m" in result
|
|
|
|
|
|
class TestFormatVoltageWithPct:
|
|
"""Test format_voltage_with_pct function."""
|
|
|
|
def test_none_returns_na(self):
|
|
"""None value returns N/A."""
|
|
assert format_voltage_with_pct(None) == "N/A"
|
|
|
|
def test_full_battery(self):
|
|
"""Full battery (4200mV = 4.20V = 100%)."""
|
|
result = format_voltage_with_pct(4200)
|
|
assert "4.20 V" in result
|
|
assert "100%" in result
|
|
|
|
def test_empty_battery(self):
|
|
"""Empty battery (3000mV = 3.00V = 0%)."""
|
|
result = format_voltage_with_pct(3000)
|
|
assert "3.00 V" in result
|
|
assert "0%" in result
|
|
|
|
def test_mid_range_battery(self):
|
|
"""Mid-range battery shows voltage and percentage."""
|
|
result = format_voltage_with_pct(3820) # 50%
|
|
assert "3.82 V" in result
|
|
assert "50%" in result
|
|
|
|
def test_format_structure(self):
|
|
"""Output matches expected format: X.XX V (XX%)."""
|
|
result = format_voltage_with_pct(3850)
|
|
assert " V (" in result
|
|
assert result.endswith("%)")
|
|
|
|
|
|
class TestFormatCompactNumber:
|
|
"""Test format_compact_number function."""
|
|
|
|
def test_none_returns_na(self):
|
|
"""None value returns N/A."""
|
|
assert format_compact_number(None) == "N/A"
|
|
|
|
def test_small_numbers_raw(self):
|
|
"""Numbers < 1000 shown as raw integers."""
|
|
assert format_compact_number(0) == "0"
|
|
assert format_compact_number(847) == "847"
|
|
assert format_compact_number(999) == "999"
|
|
|
|
def test_thousands_with_comma(self):
|
|
"""1000-9999 shown with comma separator."""
|
|
assert format_compact_number(1000) == "1,000"
|
|
assert format_compact_number(4989) == "4,989"
|
|
assert format_compact_number(9999) == "9,999"
|
|
|
|
def test_tens_of_thousands_with_k(self):
|
|
"""10000-999999 shown with k suffix."""
|
|
assert format_compact_number(10000) == "10.0k"
|
|
assert format_compact_number(242100) == "242.1k"
|
|
assert format_compact_number(999999) == "1000.0k"
|
|
|
|
def test_millions_with_m(self):
|
|
""">= 1000000 shown with M suffix."""
|
|
assert format_compact_number(1000000) == "1.0M"
|
|
assert format_compact_number(1500000) == "1.5M"
|
|
assert format_compact_number(25000000) == "25.0M"
|
|
|
|
def test_custom_precision(self):
|
|
"""Custom precision affects decimal places."""
|
|
assert format_compact_number(242156, precision=2) == "242.16k"
|
|
assert format_compact_number(1234567, precision=2) == "1.23M"
|
|
assert format_compact_number(10500, precision=0) == "10k"
|
|
|
|
def test_negative_numbers(self):
|
|
"""Negative numbers get minus prefix."""
|
|
assert format_compact_number(-500) == "-500"
|
|
assert format_compact_number(-5000) == "-5,000"
|
|
assert format_compact_number(-50000) == "-50.0k"
|
|
assert format_compact_number(-5000000) == "-5.0M"
|
|
|
|
def test_float_input(self):
|
|
"""Float inputs work correctly."""
|
|
assert format_compact_number(1234.5) == "1,234"
|
|
assert format_compact_number(12345.6) == "12.3k"
|
|
|
|
|
|
class TestFormatDurationCompact:
|
|
"""Test format_duration_compact function."""
|
|
|
|
def test_none_returns_na(self):
|
|
"""None value returns N/A."""
|
|
assert format_duration_compact(None) == "N/A"
|
|
|
|
def test_zero_returns_0s(self):
|
|
"""Zero seconds returns 0s."""
|
|
assert format_duration_compact(0) == "0s"
|
|
|
|
def test_seconds_only(self):
|
|
"""Less than 60 seconds shows seconds only."""
|
|
assert format_duration_compact(1) == "1s"
|
|
assert format_duration_compact(45) == "45s"
|
|
assert format_duration_compact(59) == "59s"
|
|
|
|
def test_minutes_and_seconds(self):
|
|
"""1 minute to < 1 hour shows minutes and seconds."""
|
|
assert format_duration_compact(60) == "1m 0s"
|
|
assert format_duration_compact(125) == "2m 5s"
|
|
assert format_duration_compact(3599) == "59m 59s"
|
|
|
|
def test_hours_and_minutes(self):
|
|
"""1 hour to < 1 day shows hours and minutes."""
|
|
assert format_duration_compact(3600) == "1h 0m"
|
|
assert format_duration_compact(7260) == "2h 1m"
|
|
assert format_duration_compact(86399) == "23h 59m"
|
|
|
|
def test_days_and_hours(self):
|
|
"""1 day or more shows days and hours."""
|
|
assert format_duration_compact(86400) == "1d 0h"
|
|
assert format_duration_compact(90000) == "1d 1h"
|
|
assert format_duration_compact(172800) == "2d 0h"
|
|
assert format_duration_compact(259200) == "3d 0h"
|
|
|
|
def test_truncation_not_rounding(self):
|
|
"""Verifies truncation behavior (floor)."""
|
|
# 1d 23h 59m 59s should show as 1d 23h (not 2d 0h)
|
|
result = format_duration_compact(86400 + 23 * 3600 + 59 * 60 + 59)
|
|
assert result == "1d 23h"
|
|
|
|
def test_large_durations(self):
|
|
"""Very large durations work correctly."""
|
|
# 365 days
|
|
result = format_duration_compact(365 * 86400)
|
|
assert result == "365d 0h"
|