mirror of
https://github.com/jorijn/meshcore-stats.git
synced 2026-03-28 17:42:55 +01:00
* 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>
156 lines
6.4 KiB
Python
156 lines
6.4 KiB
Python
"""Tests for battery voltage to percentage conversion."""
|
|
|
|
import pytest
|
|
|
|
from meshmon.battery import VOLTAGE_TABLE, voltage_to_percentage
|
|
|
|
|
|
class TestVoltageToPercentage:
|
|
"""Test battery voltage to percentage conversion."""
|
|
|
|
# ==========================================================================
|
|
# Boundary conditions
|
|
# ==========================================================================
|
|
|
|
@pytest.mark.parametrize(
|
|
"voltage,expected",
|
|
[
|
|
(4.20, 100.0), # Exact maximum
|
|
(4.21, 100.0), # Above maximum (clamped)
|
|
(4.50, 100.0), # Well above maximum
|
|
(5.00, 100.0), # Way above maximum
|
|
(3.00, 0.0), # Exact minimum
|
|
(2.99, 0.0), # Below minimum (clamped)
|
|
(2.50, 0.0), # Well below minimum
|
|
(0.00, 0.0), # Zero voltage
|
|
(-1.0, 0.0), # Negative (impossible but should handle)
|
|
],
|
|
)
|
|
def test_boundary_values(self, voltage: float, expected: float):
|
|
"""Test values at and beyond the voltage table boundaries."""
|
|
assert voltage_to_percentage(voltage) == expected
|
|
|
|
# ==========================================================================
|
|
# Table lookup exact values
|
|
# ==========================================================================
|
|
|
|
@pytest.mark.parametrize("voltage,expected", VOLTAGE_TABLE)
|
|
def test_exact_table_values(self, voltage: float, expected: float):
|
|
"""Test that exact table values return correct percentages."""
|
|
result = voltage_to_percentage(voltage)
|
|
assert result == expected, f"Expected {expected}% at {voltage}V, got {result}%"
|
|
|
|
# ==========================================================================
|
|
# Interpolation tests
|
|
# ==========================================================================
|
|
|
|
@pytest.mark.parametrize(
|
|
"voltage,expected_range",
|
|
[
|
|
(4.13, (90.0, 100.0)), # Between 4.20 and 4.06
|
|
(4.02, (80.0, 90.0)), # Between 4.06 and 3.98
|
|
(3.95, (70.0, 80.0)), # Between 3.98 and 3.92
|
|
(3.50, (0.0, 10.0)), # Between 3.45 and 3.68
|
|
(3.72, (10.0, 20.0)), # Between 3.68 and 3.74
|
|
],
|
|
)
|
|
def test_interpolation_ranges(
|
|
self, voltage: float, expected_range: tuple[float, float]
|
|
):
|
|
"""Test that interpolated values fall within expected ranges."""
|
|
result = voltage_to_percentage(voltage)
|
|
assert expected_range[0] <= result <= expected_range[1], (
|
|
f"At {voltage}V, expected {expected_range[0]}-{expected_range[1]}%, "
|
|
f"got {result}%"
|
|
)
|
|
|
|
def test_midpoint_interpolation(self):
|
|
"""Midpoint between two table entries should give midpoint percentage."""
|
|
# Use the first two table entries (4.20V=100%, 4.06V=90%)
|
|
v_high, p_high = 4.20, 100
|
|
v_low, p_low = 4.06, 90
|
|
midpoint_v = (v_high + v_low) / 2 # 4.13V
|
|
midpoint_p = (p_high + p_low) / 2 # 95%
|
|
|
|
result = voltage_to_percentage(midpoint_v)
|
|
# Allow small floating point tolerance
|
|
assert abs(result - midpoint_p) < 0.01, (
|
|
f"Midpoint voltage {midpoint_v}V should give ~{midpoint_p}%, "
|
|
f"got {result}%"
|
|
)
|
|
|
|
def test_interpolation_is_linear(self):
|
|
"""Verify linear interpolation between adjacent table points."""
|
|
# Test linearity between 3.82V (50%) and 3.87V (60%)
|
|
v1, p1 = 3.82, 50
|
|
v2, p2 = 3.87, 60
|
|
|
|
# Test at 25%, 50%, and 75% between the points
|
|
for fraction in [0.25, 0.50, 0.75]:
|
|
test_voltage = v1 + fraction * (v2 - v1)
|
|
expected_pct = p1 + fraction * (p2 - p1)
|
|
result = voltage_to_percentage(test_voltage)
|
|
|
|
assert abs(result - expected_pct) < 0.01, (
|
|
f"At {test_voltage}V ({fraction*100}% between {v1}V and {v2}V), "
|
|
f"expected {expected_pct}%, got {result}%"
|
|
)
|
|
|
|
# ==========================================================================
|
|
# Monotonicity test
|
|
# ==========================================================================
|
|
|
|
def test_percentage_is_monotonic(self):
|
|
"""Battery percentage should decrease monotonically as voltage drops."""
|
|
voltages = [v / 100 for v in range(420, 299, -1)] # 4.20 down to 3.00
|
|
percentages = [voltage_to_percentage(v) for v in voltages]
|
|
|
|
for i in range(1, len(percentages)):
|
|
assert percentages[i] <= percentages[i - 1], (
|
|
f"Monotonicity violation: at {voltages[i]}V got {percentages[i]}%, "
|
|
f"but at {voltages[i-1]}V got {percentages[i-1]}%"
|
|
)
|
|
|
|
# ==========================================================================
|
|
# Type handling
|
|
# ==========================================================================
|
|
|
|
def test_integer_voltage_input(self):
|
|
"""Function should handle integer input."""
|
|
# Integer 4 should be treated as 4.0V
|
|
result = voltage_to_percentage(4)
|
|
assert isinstance(result, float)
|
|
assert 80.0 <= result <= 100.0 # 4.0V is between 3.98V (80%) and 4.06V (90%)
|
|
|
|
|
|
class TestVoltageTable:
|
|
"""Test the VOLTAGE_TABLE constant."""
|
|
|
|
def test_table_is_sorted_descending(self):
|
|
"""Voltage table should be sorted in descending order by voltage."""
|
|
voltages = [v for v, _ in VOLTAGE_TABLE]
|
|
assert voltages == sorted(voltages, reverse=True), (
|
|
"VOLTAGE_TABLE should be sorted by voltage in descending order"
|
|
)
|
|
|
|
def test_table_has_expected_endpoints(self):
|
|
"""Table should cover the full 18650 range."""
|
|
voltages = [v for v, _ in VOLTAGE_TABLE]
|
|
percentages = [p for _, p in VOLTAGE_TABLE]
|
|
|
|
assert voltages[0] == 4.20, "Table should start at 4.20V (100%)"
|
|
assert voltages[-1] == 3.00, "Table should end at 3.00V (0%)"
|
|
assert percentages[0] == 100, "First entry should be 100%"
|
|
assert percentages[-1] == 0, "Last entry should be 0%"
|
|
|
|
def test_table_has_reasonable_entries(self):
|
|
"""Table should have enough entries for smooth interpolation."""
|
|
assert len(VOLTAGE_TABLE) >= 10, "Table should have at least 10 entries"
|
|
|
|
def test_percentages_are_descending(self):
|
|
"""Percentages should decrease as voltage decreases."""
|
|
percentages = [p for _, p in VOLTAGE_TABLE]
|
|
assert percentages == sorted(percentages, reverse=True), (
|
|
"Percentages should be in descending order"
|
|
)
|