mirror of
https://github.com/jorijn/meshcore-stats.git
synced 2026-06-23 03:15:09 +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>
196 lines
6.0 KiB
Python
196 lines
6.0 KiB
Python
"""Tests for database maintenance functions."""
|
|
|
|
import os
|
|
import sqlite3
|
|
|
|
from meshmon.db import (
|
|
get_db_path,
|
|
init_db,
|
|
vacuum_db,
|
|
)
|
|
|
|
|
|
class TestVacuumDb:
|
|
"""Tests for vacuum_db function."""
|
|
|
|
def test_vacuums_existing_db(self, initialized_db):
|
|
"""Vacuum should run without error on initialized database."""
|
|
# Add some data then vacuum
|
|
conn = sqlite3.connect(initialized_db)
|
|
conn.execute(
|
|
"INSERT INTO metrics (ts, role, metric, value) VALUES (1, 'companion', 'test', 1.0)"
|
|
)
|
|
conn.commit()
|
|
conn.close()
|
|
|
|
# Should not raise
|
|
vacuum_db(initialized_db)
|
|
|
|
def test_runs_analyze(self, initialized_db, capfd):
|
|
"""ANALYZE should be run after VACUUM."""
|
|
# Vacuum includes ANALYZE
|
|
vacuum_db(initialized_db)
|
|
|
|
# Check that database stats were updated
|
|
conn = sqlite3.connect(initialized_db)
|
|
conn.execute("SELECT * FROM sqlite_stat1")
|
|
# After ANALYZE, sqlite_stat1 should have entries if tables have data
|
|
conn.close()
|
|
|
|
def test_uses_default_path_when_none(self, configured_env, monkeypatch):
|
|
"""Uses get_db_path() when no path provided."""
|
|
# Initialize db at default location
|
|
init_db()
|
|
|
|
# vacuum_db with None should use default path
|
|
vacuum_db(None)
|
|
|
|
def test_can_vacuum_empty_db(self, initialized_db):
|
|
"""Can vacuum an empty database."""
|
|
vacuum_db(initialized_db)
|
|
|
|
def test_reclaims_space_after_delete(self, initialized_db):
|
|
"""Vacuum should reclaim space after deleting rows."""
|
|
conn = sqlite3.connect(initialized_db)
|
|
|
|
# Insert many rows
|
|
for i in range(1000):
|
|
conn.execute(
|
|
"INSERT INTO metrics (ts, role, metric, value) VALUES (?, 'companion', 'test', 1.0)",
|
|
(i,)
|
|
)
|
|
conn.commit()
|
|
|
|
# Get size before delete
|
|
conn.close()
|
|
size_before = os.path.getsize(initialized_db)
|
|
|
|
# Delete all rows
|
|
conn = sqlite3.connect(initialized_db)
|
|
conn.execute("DELETE FROM metrics")
|
|
conn.commit()
|
|
conn.close()
|
|
|
|
# Vacuum
|
|
vacuum_db(initialized_db)
|
|
|
|
# Size should be smaller (or at least not larger)
|
|
size_after = os.path.getsize(initialized_db)
|
|
# Note: Due to WAL mode, this might not always shrink dramatically
|
|
# but vacuum should at least complete without error
|
|
assert size_after <= size_before + 4096 # Allow for some overhead
|
|
|
|
|
|
class TestGetDbPath:
|
|
"""Tests for get_db_path function."""
|
|
|
|
def test_returns_path_in_state_dir(self, configured_env):
|
|
"""Path should be in the configured state directory."""
|
|
path = get_db_path()
|
|
|
|
assert path.name == "metrics.db"
|
|
assert str(configured_env["state_dir"]) in str(path)
|
|
|
|
def test_returns_path_object(self, configured_env):
|
|
"""Should return a Path object."""
|
|
from pathlib import Path
|
|
|
|
path = get_db_path()
|
|
|
|
assert isinstance(path, Path)
|
|
|
|
|
|
class TestDatabaseIntegrity:
|
|
"""Tests for database integrity after operations."""
|
|
|
|
def test_wal_mode_enabled(self, initialized_db):
|
|
"""Database should be in WAL mode."""
|
|
conn = sqlite3.connect(initialized_db)
|
|
cursor = conn.execute("PRAGMA journal_mode")
|
|
mode = cursor.fetchone()[0]
|
|
conn.close()
|
|
|
|
assert mode.lower() == "wal"
|
|
|
|
def test_foreign_keys_disabled_by_default(self, initialized_db):
|
|
"""Foreign keys should be disabled (SQLite default)."""
|
|
conn = sqlite3.connect(initialized_db)
|
|
cursor = conn.execute("PRAGMA foreign_keys")
|
|
enabled = cursor.fetchone()[0]
|
|
conn.close()
|
|
|
|
# Default is off, and we don't explicitly enable them
|
|
assert enabled == 0
|
|
|
|
def test_metrics_table_exists(self, initialized_db):
|
|
"""Metrics table should exist after init."""
|
|
conn = sqlite3.connect(initialized_db)
|
|
cursor = conn.execute(
|
|
"SELECT name FROM sqlite_master WHERE type='table' AND name='metrics'"
|
|
)
|
|
result = cursor.fetchone()
|
|
conn.close()
|
|
|
|
assert result is not None
|
|
assert result[0] == "metrics"
|
|
|
|
def test_db_meta_table_exists(self, initialized_db):
|
|
"""db_meta table should exist after init."""
|
|
conn = sqlite3.connect(initialized_db)
|
|
cursor = conn.execute(
|
|
"SELECT name FROM sqlite_master WHERE type='table' AND name='db_meta'"
|
|
)
|
|
result = cursor.fetchone()
|
|
conn.close()
|
|
|
|
assert result is not None
|
|
|
|
def test_metrics_index_exists(self, initialized_db):
|
|
"""Index on metrics(role, ts) should exist."""
|
|
conn = sqlite3.connect(initialized_db)
|
|
cursor = conn.execute(
|
|
"SELECT name FROM sqlite_master WHERE type='index' AND name='idx_metrics_role_ts'"
|
|
)
|
|
result = cursor.fetchone()
|
|
conn.close()
|
|
|
|
assert result is not None
|
|
|
|
def test_vacuum_preserves_data(self, initialized_db):
|
|
"""Vacuum should not lose any data."""
|
|
conn = sqlite3.connect(initialized_db)
|
|
for i in range(100):
|
|
conn.execute(
|
|
"INSERT INTO metrics (ts, role, metric, value) VALUES (?, 'companion', 'test', ?)",
|
|
(i, float(i))
|
|
)
|
|
conn.commit()
|
|
conn.close()
|
|
|
|
# Vacuum
|
|
vacuum_db(initialized_db)
|
|
|
|
# Check data is still there
|
|
conn = sqlite3.connect(initialized_db)
|
|
cursor = conn.execute("SELECT COUNT(*) FROM metrics")
|
|
count = cursor.fetchone()[0]
|
|
conn.close()
|
|
|
|
assert count == 100
|
|
|
|
def test_vacuum_preserves_schema_version(self, initialized_db):
|
|
"""Vacuum should not change schema version."""
|
|
from meshmon.db import _get_schema_version
|
|
|
|
conn = sqlite3.connect(initialized_db)
|
|
version_before = _get_schema_version(conn)
|
|
conn.close()
|
|
|
|
vacuum_db(initialized_db)
|
|
|
|
conn = sqlite3.connect(initialized_db)
|
|
version_after = _get_schema_version(conn)
|
|
conn.close()
|
|
|
|
assert version_before == version_after
|