Commit graph

507 commits

Author SHA1 Message Date
rcourtman
fe8ee86f4e Add unit tests for MetricsHistory (internal/monitoring)
58 test cases covering:
- NewMetricsHistory: constructor and initialization (4 cases)
- appendMetric: time-series append with retention and max limits (5 cases)
- cleanupMetrics: old point removal with cutoff time (5 cases)
- AddGuestMetric: all 7 metric types + unknown type handling (8 cases)
- AddNodeMetric: cpu/memory/disk + unknown type (4 cases)
- AddStorageMetric: usage/used/total/avail + unknown type (5 cases)
- GetGuestMetrics: duration filtering, nonexistent, zero duration (6 cases)
- GetNodeMetrics: duration filtering and edge cases (5 cases)
- GetAllGuestMetrics: multi-metric retrieval (3 cases)
- GetAllStorageMetrics: storage metric retrieval (2 cases)
- Cleanup: retention enforcement across all metric types (1 case)
- Multiple guests isolation: verify metrics don't leak (1 case)
- MaxDataPoints enforcement: oldest points dropped (1 case)
- RetentionTime enforcement: old points removed on append (1 case)

First comprehensive unit test file for metrics_history.go core
functions. Existing concurrency test in separate file.
2025-11-30 21:34:07 +00:00
rcourtman
dadbc180e3 Add unit tests for HTTPClient (internal/tempproxy)
23 test cases covering NewHTTPClient, IsAvailable, GetTemperature,
and HealthCheck including success paths, error handling (401, 403,
429, 5xx), JSON parsing, URL encoding, retry behavior, and connection
errors.

Coverage: 22.4% → 47.6%
2025-11-30 21:18:14 +00:00
rcourtman
94952577e2 Add unit tests for importTransaction (internal/config)
24 test cases covering transaction lifecycle: staging, commit, rollback, and cleanup.
Tests include atomic commit behavior, backup/restore on failure, directory creation,
permission handling, and idempotent cleanup.

First test file for import_transaction.go. Coverage 42.4% → 42.7%.
2025-11-30 21:04:41 +00:00
rcourtman
0eb0824c0a Add unit tests for GuestMetadataStore (internal/config)
22 test cases covering CRUD operations (Get, GetAll, Set, Delete,
ReplaceAll), persistence (Load, save with atomic write, directory
creation), legacy ID migration (GetWithLegacyMigration for clustered
and standalone formats), round-trip verification, and concurrency.

First test file for guest_metadata.go, complementing the similar
docker_metadata_test.go added in previous run.
2025-11-30 20:48:05 +00:00
rcourtman
f8c7a30d28 Fix cluster proxy token collision - store per-node control tokens
When multiple cluster nodes register sensor-proxy, each registration
was overwriting the previous node's control token on the shared
PVEInstance. This caused "Proxy token not recognized" errors on all
but the last-registered node.

Changes:
- Add TemperatureProxyControlToken field to ClusterEndpoint struct
- Store control tokens per-endpoint for cluster registrations
- Check both instance-level and endpoint-level tokens when validating

Related to #738
2025-11-30 20:37:58 +00:00
rcourtman
db56cb7d0d Add unit tests for UpdateHistory (internal/updates)
47 test cases covering:
- NewUpdateHistory: directory creation, loading existing entries
- CreateEntry: event ID generation, timestamp handling, persistence
- UpdateEntry: updates, persistence verification, error handling
- GetEntry: retrieval by ID, non-existent entry errors
- ListEntries: filtering by status/action/deployment type, limits
- GetLatestSuccessful: finding recent successful entries
- Cache management: trimming when exceeding max size
- LoadCache: malformed JSON handling, empty lines
- Type definitions and constant validation
2025-11-30 20:34:40 +00:00
rcourtman
2e884f4a71 Add unit tests for DockerMetadataStore (internal/config)
22 test cases covering:
- Get/GetAll: retrieval of container/service metadata
- GetHostMetadata/GetAllHostMetadata: retrieval of host metadata
- Set: add/update metadata with persistence
- SetHostMetadata: add/update/delete host metadata
- Delete: remove container metadata
- ReplaceAll: bulk replace with nil entry handling
- Load: versioned format, legacy format, nonexistent file, invalid JSON
- Save: directory creation, atomic write
- Round-trip: full persistence cycle verification
- Concurrent access safety

First test file for docker_metadata.go.
2025-11-30 17:20:46 +00:00
rcourtman
6bda5e4d4a Add unit tests for mdadm parseDetail function 2025-11-30 16:42:12 +00:00
rcourtman
ee066d086a Add unit tests for OIDC configuration helpers
Test coverage for internal/config/oidc.go functions:
- normaliseList: 8 cases for deduplication, trimming, empty handling
- parseDelimited: 8 cases for comma/space separation
- DefaultRedirectURL: 7 cases for URL construction
- OIDCConfig.Clone: 2 cases for deep copy behavior
- OIDCConfig.ApplyDefaults: 9 cases for defaults and normalization
- OIDCConfig.Validate: 9 cases for validation rules
- OIDCConfig.MergeFromEnv: 5 cases for environment variable merging
- NewOIDCConfig: constructor verification

Total: 56 new test cases (583 lines).
2025-11-30 16:22:43 +00:00
rcourtman
2620aa5db5 Add unit tests for security.go IP parsing utilities
- extractRemoteIP: 17 test cases for remote address parsing
  (IPv4/IPv6 with/without ports, bracketed notation, edge cases)
- firstValidForwardedIP: 21 test cases for X-Forwarded-For parsing
  (single/multiple IPs, invalid entries, IPv4/IPv6 mixed)
- isPrivateIPExtended: 33 test cases extending existing coverage
  (RFC 1918 boundaries, loopback range, IPv6 private/local, ports)

Total: 71 new test cases for IP address handling utilities.
2025-11-30 15:48:45 +00:00
rcourtman
2c26054d57 Add unit tests for router.go proxy header utility functions (api)
Add 77 test cases for 4 previously untested utility functions:
- firstForwardedValue: 14 cases for X-Forwarded-For header parsing
- sanitizeForwardedHost: 27 cases for host sanitization with scheme/port handling
- isLoopbackHost: 20 cases for loopback detection (localhost, 127.x, ::1)
- shouldAppendForwardedPort: 16 cases for port appending decisions

Key edge cases covered:
- IPv6 address bracket handling in sanitizeForwardedHost
- Case-insensitive localhost detection
- Full 127.0.0.0/8 loopback range validation
- strconv.Atoi accepts negative port strings (documented as current behavior)
2025-11-30 15:34:32 +00:00
rcourtman
930e003519 Add unit tests for normalizeUnifiedAgentArch and getClientIP (api)
Tests for unified_agent.go:
- normalizeUnifiedAgentArch: 51 test cases covering all supported
  architectures (linux/darwin/windows), case insensitivity,
  whitespace handling, and invalid inputs

Tests for updates.go:
- getClientIP: 18 test cases covering X-Forwarded-For priority,
  X-Real-IP fallback, RemoteAddr extraction, IPv4/IPv6 support,
  nil header safety, and case insensitivity
2025-11-30 15:05:37 +00:00
rcourtman
04d4b6606a Add unit tests for CSRF token store (api) 2025-11-30 14:55:47 +00:00
rcourtman
fe3f32ebcc Add unit tests for responseWriter middleware wrapper (api)
Tests for the responseWriter struct in middleware.go:
- APIError.Error() interface implementation (3 cases)
- WriteHeader once-only semantics (4 cases)
- Write with implicit WriteHeader (3 cases)
- StatusCode nil safety (4 cases)
- Hijack support detection (2 cases)
- Flush support detection (3 cases)
- Full flow integration and edge cases (4 cases)

First test file for middleware.go. 22 test cases total covering
HTTP response wrapper behavior used by ErrorHandler middleware.
2025-11-30 14:33:38 +00:00
rcourtman
39d02d62a3 Add unit tests for temperature proxy utility functions (api)
- extractHostPart: 22 test cases covering URL parsing, hostname extraction
- buildAuthorizedNodeList: 8 test cases for PVE instance node list building
- generateSecureToken: 5 test cases for cryptographic token generation
- proxySyncState: 6 test cases for sync status tracking and snapshots

First test file for temperature_proxy.go utility functions.
2025-11-30 14:07:04 +00:00
rcourtman
07587ec818 Add unit tests for GetRateLimiterForEndpoint (api)
37 test cases covering endpoint routing to rate limiters:
- Authentication endpoints (login, logout, change-password, auth/*)
- Recovery endpoints (security/recovery)
- Export/Import endpoints (config/export, config/import)
- Configuration write operations (POST/PUT/DELETE to config/*)
- Configuration read operations (GET to config/*, discover, security/status)
- Update endpoints (updates/*)
- WebSocket endpoints (/ws/*)
- Public endpoints (health, version, metrics, etc.)
- General API fallback
- Case insensitivity (uppercase paths)
- Lazy initialization when globalRateLimitConfig is nil
- Priority ordering tests for overlapping patterns
2025-11-30 13:48:23 +00:00
rcourtman
aee687bb03 Add unit tests for DemoModeMiddleware (api)
26 test cases covering:
- Demo mode disabled (all requests pass through)
- Demo mode enabled with read-only methods (GET/HEAD/OPTIONS allowed)
- WebSocket upgrade handling (case-insensitive)
- Auth endpoint allowlist (login, OIDC, logout)
- Modification request blocking (POST/PUT/DELETE/PATCH)
- Partial path match rejection (security)
- Response format verification (JSON error response)

First test file for demo_middleware.go. Tests verify correct header
setting (X-Demo-Mode) and error response structure.
2025-11-30 13:34:08 +00:00
rcourtman
28a0851868 Add unit tests for container disk usage utility functions (monitoring) 2025-11-30 13:20:39 +00:00
rcourtman
926fe5495f Add unit tests for missing ToFrontend converters (models)
Added 17 new test functions covering:
- DockerHost.ToFrontend() with variants for empty display name, swarm,
  services, tasks, and command status
- Host.ToFrontend() with display name fallback logic
- CephCluster.ToFrontend() including empty pools/services case
- ReplicationJob.ToFrontend() including nil time handling
- DockerServiceUpdate.ToFrontend()
- DockerContainer.ToFrontend() for Podman info

Coverage improved from 33.0% to 44.0% in internal/models package.
2025-11-30 13:03:45 +00:00
rcourtman
fb976acfc3 Add unit tests for ZFS storage utility functions (hostmetrics)
65 test cases covering 8 functions:
- parseZpoolList: zpool command output parsing (15 cases)
- uniqueZFSPools: pool name deduplication (7 cases)
- bestZFSMountpoints: mountpoint selection logic (8 cases)
- zfsMountpointScore: mountpoint scoring algorithm (7 cases)
- zfsPoolFromDevice: pool name extraction (6 cases)
- calculatePercent: percentage calculation (7 cases)
- clampPercent: value clamping (8 cases)
- bestZFSPoolDatasets: dataset selection (7 cases)

First comprehensive unit test coverage for internal/hostmetrics
package ZFS utilities.
2025-11-30 12:50:58 +00:00
rcourtman
ef241d0581 Add unit tests for toDockerHostCommandFrontend converter 2025-11-30 12:38:59 +00:00
rcourtman
d89ba45284 Fix Windows agent self-update restart failure
syscall.Exec is not supported on Windows, causing self-update to fail
with "failed to restart: not supported by windows".

Split restart logic into platform-specific files:
- restart_unix.go: Uses syscall.Exec for in-place process replacement
- restart_windows.go: Uses os.Exit(0) to let Windows SCM restart service

Related to #735
2025-11-30 12:02:43 +00:00
rcourtman
151db60267 Add unit tests for discovery config functions (config)
Add tests for CloneDiscoveryConfig and NormalizeDiscoveryConfig:
- CloneDiscoveryConfig: 7 tests verifying deep copy, slice independence
- NormalizeDiscoveryConfig: 16 tests covering defaults, validation,
  sanitization, edge cases

Total: 23 test cases for discovery config handling.
2025-11-30 10:49:03 +00:00
rcourtman
562fc59c56 Add unit tests for alert utility functions (alerts)
Test coverage for isMonitorOnlyAlert, quietHoursCategoryForAlert, and
ensureValidHysteresis functions that were previously untested. Improves
internal/alerts coverage from 46.4% to 46.8%.
2025-11-30 10:35:22 +00:00
rcourtman
0d22d3d2e4 Add unit tests for host alert utility functions (alerts)
Test hostResourceID, hostDisplayName, hostInstanceName,
sanitizeHostComponent, sanitizeRAIDDevice, and hostDiskResourceID.
2025-11-30 10:20:26 +00:00
rcourtman
702e56c97a Add unit tests for hasLegacyThresholds function (diagnostics)
Covers all legacy threshold field detection paths including
CPU, Memory, Disk, DiskRead, DiskWrite, NetworkIn, NetworkOut,
and mixed modern/legacy configurations.
2025-11-30 10:05:33 +00:00
rcourtman
73e5ff0914 Add unit tests for dockeragent runtime detection functions
Test coverage for:
- detectRuntime: 11 test cases covering podman/docker detection via
  endpoint path, InitBinary, ServerVersion, DriverStatus, SecurityOptions
- buildRuntimeCandidates: 6 test cases verifying candidate ordering,
  deduplication, and preference-based filtering
- randomDuration: 5 test cases for boundary conditions and randomness
- determineSelfUpdateArch: validates architecture detection output

Coverage increased from 17.5% to 21.4%.
2025-11-30 08:47:46 +00:00
rcourtman
f9a64b3251 Add unit tests for notification security utilities (notifications)
Test 7 security-related functions with 118 test cases:
- formatWebhookDuration: webhook payload duration formatting
- isNumeric: Telegram chat_id validation helper
- extractTelegramChatID: Telegram webhook URL parsing
- isPrivateIP: SSRF protection (private IP detection)
- isNumericIP: HTTPS IP address detection
- isEmptyInterface: custom field validation
- ensurePushoverCustomFieldAliases: Pushover legacy field aliasing
2025-11-30 08:05:04 +00:00
rcourtman
132dae92a9 Add unit tests for notification template functions (notifications)
Test GetEmailProviders and GetWebhookTemplates functions covering:
- Provider/template uniqueness, required fields, valid values
- Known provider settings (Gmail, SendGrid, custom)
- Known webhook services (Discord, Slack, Telegram, PagerDuty)
- Payload template validation for required alert fields
2025-11-30 07:48:53 +00:00
rcourtman
19e1d81779 Add unit tests for sanitizeCIDRList (config) 2025-11-30 07:35:52 +00:00
rcourtman
a32aa60600 Add unit tests for config utility functions (config)
Test coverage for IsPasswordHashed, IsValidDiscoveryEnvironment, and
splitAndTrim functions. 63 test cases covering bcrypt hash validation,
discovery environment validation, and comma-separated string parsing.
2025-11-30 07:27:59 +00:00
rcourtman
90e1b8e546 Add unit tests for RateTracker.CalculateRates (monitoring) 2025-11-30 07:07:18 +00:00
rcourtman
d69e1545f2 Add unit tests for alert utility functions (alerts)
Test coverage for pure utility functions:
- sanitizeAlertKey: string normalization for alert IDs
- abs: absolute value for float64
- isQueueOutlier: queue anomaly detection logic
- scaleThreshold: threshold scaling with ceiling
- calculateMedianInt: integer median calculation

78 test cases added, coverage improved from 45.3% to 46.2%.
2025-11-30 06:34:55 +00:00
rcourtman
15d6cae7dd Add unit tests for adaptive scheduler interval selection (scheduler)
46 test cases covering:
- clampFloat helper (9 cases: range checks, boundary conditions)
- Staleness score impact (5 cases: 0/0.25/0.5/0.75/1 scores)
- Error penalty (5 cases: 0 to 10 errors, min clamping)
- Queue depth stretching (5 cases: 1 to 50 depth, max clamping)
- EMA smoothing (convergence behavior with alpha=0.6)
- Jitter (bounds checking, deterministic tests with seeded RNG)
- Boundary conditions (6 cases: zero/negative intervals, max<min)
- Combined factors (3 cases: all factors interacting)
- State persistence (per-instance EMA state isolation)

First unit test file for scheduler.go (previously only had integration tests).
2025-11-30 06:11:22 +00:00
rcourtman
8eea32678e Add unit tests for Docker swarm utility functions (dockeragent)
Test coverage for serviceMode, buildContainerIndex, lookupContainer,
copyStringMap, and isTaskCompletedState. 52 test cases covering service
mode detection, container index building/lookup, and task state classification.
Coverage improved from 14.7% to 17.5%.
2025-11-30 05:32:52 +00:00
rcourtman
36b1c9cf63 Add unit tests for Alert clone and metadata utility functions (alerts)
Tests for:
- normalizePoweredOffSeverity: Verifies severity normalization to warning/critical
- cloneMetadata: Deep copy functionality for metadata maps
- cloneMetadataValue: Type-specific cloning for various slice and map types
- Alert.Clone: Full alert cloning with pointer field independence

46 test cases covering nil handling, deep copy verification, slice/map
independence, and all supported metadata value types.

Coverage improved from 44.8% to 45.3%.
2025-11-30 05:19:38 +00:00
rcourtman
73e5352812 Add unit tests for extractPodmanMetadata and detectHostRemovedError (dockeragent)
- TestExtractPodmanMetadata: 14 test cases covering pod metadata, infra
  containers, compose metadata, auto-update settings, user namespace
  handling, whitespace trimming, and precedence rules
- TestDetectHostRemovedError: 11 test cases covering JSON parsing,
  case-insensitive matching, error code validation, and edge cases

Coverage improved from 11.7% to 14.7% for internal/dockeragent.
2025-11-30 05:03:31 +00:00
rcourtman
722ea83b5d Add unit tests for RateLimiter (internal/api/ratelimit.go)
16 test cases covering:
- Basic rate limiting with Allow() (limit enforcement, different IPs)
- Sliding window behavior (time-based expiry, partial expiry)
- Edge cases (zero limit, large limit, empty IP)
- Cleanup routine (full cleanup, partial cleanup)
- Concurrent access (thread safety with 100 parallel attempts)
- Middleware integration (allowed/denied paths, X-Forwarded-For)

First test file for internal/api package.
2025-11-30 04:33:59 +00:00
rcourtman
c2233fb3f8 Add unit tests for temperature utility functions
Add focused unit tests for four utility functions in temperature.go:
- extractTempInput: 16 test cases for sensor value extraction
- extractCoreNumber: 18 test cases for core number parsing
- extractHostname: 21 test cases for URL hostname extraction
- normalizeSMARTEntries: 15 test cases for SMART data normalization

70 test cases total covering type conversions, edge cases,
boundary conditions, and error handling paths.
2025-11-30 04:20:28 +00:00
rcourtman
ed3c992968 Add unit tests for InstallShAdapter utility functions
- Test parseProgress: 23 test cases for progress parsing from install.sh output
- Test readLastLines: 11 test cases including edge cases
- Test version pattern validation: 45 test cases for command injection prevention
- Test DockerUpdater and AURUpdater basic functionality
- Fix bug in readLastLines: handle n<=0 to prevent slice bounds panic

Coverage increased from 35.9% to 38.2%
2025-11-30 04:04:27 +00:00
rcourtman
351ef94368 Add unit tests for agentupdate utility functions
Tests for:
- verifyBinaryMagic: ELF/Mach-O/PE magic byte validation
- determineArch: platform architecture detection
- unraidPersistentPath: Unraid persistence path generation
- isUnraid: Unraid environment detection
- New(): updater initialization with various configs
- Config defaults and constants

Coverage: 12.9% -> 13.4%
2025-11-30 03:48:50 +00:00
rcourtman
d2a8184833 Add unit tests for notification queue utility functions
Test coverage for calculateBackoff (exponential backoff calculation),
NotificationQueueStatus constants, and QueuedNotification struct fields.
15 test cases covering backoff timing, cap behavior, and struct defaults.
2025-11-30 03:19:23 +00:00
rcourtman
b763ccc412 Add unit tests for HTTP metrics utility functions
83 test cases covering classifyStatus, isNumeric, looksLikeUUID,
normalizeSegment, and normalizeRoute functions used for Prometheus
metrics aggregation. Tests cover status code classification, numeric
string validation, UUID format detection, URL segment normalization,
and route path normalization with query param stripping.
2025-11-30 02:48:05 +00:00
rcourtman
6267554b74 Add unit tests for version utility functions
Test coverage for pure functions in internal/updates/version.go:
- Version.String() - 6 test cases
- Version.Compare() - 14 test cases (major/minor/patch/prerelease)
- Version.IsNewerThan() - 4 test cases
- Version.IsPrerelease() - 4 test cases
- compareInts() - 7 test cases
- extractRCNumber() - 12 test cases
- envBool() - 17 test cases
- sanitizePrereleaseIdentifier() - 14 test cases

Coverage: 35.2% -> 35.9%
2025-11-30 02:03:35 +00:00
rcourtman
9f2798cc96 Add unit tests for config encryption functions
Tests encryptWithPassphrase and decryptWithPassphrase:
- Roundtrip encryption/decryption with various data types
- Unique output verification (random salt/nonce)
- Wrong passphrase rejection
- Tampered ciphertext detection
- Minimum size validation
- Base64 roundtrip (matching export/import flow)
2025-11-30 01:48:20 +00:00
rcourtman
3c24a51298 Add unit tests for hostagent utility functions
Test normalisePlatform (darwin->macos normalization, case handling,
whitespace trimming) and isLoopback (case-insensitive flag matching).
Package had no tests previously.
2025-11-30 01:34:55 +00:00
rcourtman
ed3773b324 Add unit tests for email template utility functions
Test coverage for titleCase, formatDuration, pluralize, formatMetricValue,
and formatMetricThreshold functions. 71 test cases covering edge cases,
boundary conditions, and all metric type variants.
2025-11-30 01:03:05 +00:00
rcourtman
c91375230b Add unit tests for discovery config_override utility functions
Tests for parseCIDRs, parseCIDRMap, environmentFromOverride,
shouldPruneContainerNetworks, isLikelyContainerPhase, filterPhasesForEnvironment,
and ApplyConfigToProfile. Coverage increased from 29.0% to 51.0%.
2025-11-30 00:50:07 +00:00
rcourtman
d11d81688a Add unit tests for websocket utility functions
Test coverage for pure utility functions:
- isValidPrivateOrigin: validates private network origins (security)
- normalizeForwardedProto: normalizes ws/wss to http/https for proxies
- sanitizeValue: handles NaN/Inf values in JSON data
- cloneMetadata/cloneMetadataValue: deep copies metadata maps/slices
- cloneAlert/cloneAlertData: deep copies alert structures

Coverage increased from 20.9% to 37.3% (80 test cases).
2025-11-30 00:34:38 +00:00
rcourtman
04c12414d2 Add unit tests for diagnostics utility functions
Test coverage for 9 pure functions in internal/api/diagnostics.go:
- isFallbackMemorySource: 13 cases covering fallback and non-fallback sources
- copyStringSlice: 4 cases including nil handling and copy verification
- normalizeHostForComparison: 16 cases for URL normalization
- normalizeVersionLabel: 11 cases for version prefix handling
- contains: 8 cases for string slice membership
- containsFold: 11 cases for case-insensitive matching
- interfaceToStringSlice: 9 cases for type conversion
- preferredDockerHostName: 5 cases for name preference hierarchy
- formatTimeMaybe: 3 cases for time formatting
2025-11-30 00:18:41 +00:00