Commit graph

209 commits

Author SHA1 Message Date
rcourtman
1af38e3f99 test: Add tests for parseContainerMountMetadata, convertContainerDiskInfo, StalenessScore
- parseContainerMountMetadata: parts without equals, mountpoint key variant,
  whitespace handling, single source value (96.4% -> 100%)
- convertContainerDiskInfo: nil metadata, device from metadata, negative free
  clamping, whitespace label handling (95.1% -> 97.6%, remaining is dead code)
- StalenessScore: negative maxStale default, metrics lookup failure, score
  clamping edge cases (95.7% - remaining is defensive dead code)
2025-12-01 20:44:00 +00:00
rcourtman
ed0644035f test: Add tests for sanitizeGuestAddressStrings, parseContainerConfigNetworks, mergeNVMeTempsIntoDisks
- sanitizeGuestAddressStrings: IPv6 loopback with CIDR (::1/128) edge case
  (96.2% -> 100%)
- parseContainerConfigNetworks: parts without equals, mac/ips/ip6addr/ip6prefix
  key variants, whitespace-only values, all-empty results (97.2% -> 100%)
- mergeNVMeTempsIntoDisks: NVMe disk with no legacy temps (continue branch),
  more disks than temps (break branch) (97% -> 100%)
2025-12-01 20:34:48 +00:00
rcourtman
4e33b396e0 test: Add tests for normalizeEndpointHost, SelectInterval, generateDockerHostIdentifier
- normalizeEndpointHost: port-only URL host (parsed.Host fallback),
  edge cases for URL parsing (94.4% -> 100%)
- SelectInterval: negative penalty, instance key derivation, clamping
  edge cases (96% - remaining is unreachable dead code guards)
- generateDockerHostIdentifier: empty base fallbacks, suffix candidates,
  hash suffix, numeric suffix increments (91.7% -> 100%)
2025-12-01 20:26:21 +00:00
rcourtman
4c91dce2f8 test: Add tests for allow, ensureContainerRootDiskEntry; remove dead code
- allow (circuitBreaker): all states including unknown/default branch,
  open→half-open transition, half-open window timing (93.8% -> 100%)
- ensureContainerRootDiskEntry: nil container, existing disks, used>total
  clamping, negative free clamping, usage calculation (92.3% -> 100%)
- convertPoolInfoToModel: removed unreachable nil check (dead code since
  ConvertToModelZFSPool only returns nil for nil receiver) (88.9% -> 100%)
2025-12-01 20:15:32 +00:00
rcourtman
0a9177f161 test: Add tests for lookupClusterEndpointLabel, GetNodeMetrics, stateDetails
- lookupClusterEndpointLabel: nil instance, no match, Host vs IP fallback,
  case-insensitive NodeName, whitespace handling (84.6% -> 100%)
- GetNodeMetrics: unknown metric types, empty nodeID, zero duration,
  empty metrics data, disk type (94.1% -> 100%)
- stateDetails: all breaker states including unknown/invalid state,
  retryAt calculations, timestamps (90% -> 100%)
2025-12-01 20:07:22 +00:00
rcourtman
2fdc051c11 fix: Make parseNVMeTemps deterministic by checking Composite before Sensor 1
Go map iteration order is non-deterministic, causing flaky test failures.
This fix ensures "Composite" sensor is always preferred over "Sensor 1"
by checking them in separate loops rather than relying on iteration order.
2025-12-01 20:03:05 +00:00
rcourtman
f79d20296b test: Add tests for GetGuestMetrics, mergeSnapshot, getDockerCommandPayload
- GetGuestMetrics: all metric types, duration filtering, guest not found,
  unknown metric type, empty data (81% -> 100%)
- mergeSnapshot: timestamp merging for LastSuccess/LastError/LastMutated,
  ChangeHash preservation (86.7% -> 100%)
- getDockerCommandPayload: empty hostID, whitespace normalization, host
  not found, expired command cleanup, queued->dispatched marking,
  already-dispatched preservation (91.3% -> 100%)
2025-12-01 19:58:43 +00:00
rcourtman
196389853e test: Add tests for StalenessScore, parseCPUTemps, queueDockerStopCommand
- StalenessScore: 78.3%→95.7% (4 cases for metrics, future timestamp, defaults)
- parseCPUTemps: 98.1%→100% (core temp exceeding package case)
- queueDockerStopCommand: 76.9%→100% (12 cases for validation, status checks)
2025-12-01 19:50:42 +00:00
rcourtman
2594a6c124 test: Add tests for handleProxyHostFailure, recordNodeSnapshot, evaluateHostAgents
- handleProxyHostFailure: 76.5%→100% (9 cases for per-host failure tracking)
- recordNodeSnapshot: 75%→100% (6 cases for diagnostic snapshot storage)
- evaluateHostAgents: 87%→100% (10 cases for host health evaluation)
2025-12-01 19:40:32 +00:00
rcourtman
c6a34c4412 test: Add tests for handleProxyFailure, parseRPiTemperature, RecordResult
- handleProxyFailure: 86.7%→100% (6 cases for proxy disable threshold logic)
- parseRPiTemperature: 77.8%→100% (7 cases for RPi temp parsing edge cases)
- RecordResult: 95.8%→100% (negative staleness clamping case)
2025-12-01 19:33:06 +00:00
rcourtman
1f380eaaf3 test: Add tests for isProxyEnabled, taskHeap.Pop, NewAdaptiveScheduler
- isProxyEnabled: 94.4%→100% (7 cases for proxy cooldown/restore logic)
- taskHeap.Pop: 87.5%→100% (3 cases for empty/single/multi-element heap)
- NewAdaptiveScheduler: 84.6%→100% (14 cases for default value handling)
2025-12-01 19:26:37 +00:00
rcourtman
0ed84f3179 test: Add tests for disableLegacySSHOnAuthFailure, parseNVMeTemps, updateDeadLetterMetrics
- disableLegacySSHOnAuthFailure: 87.5%→100% (13 cases for auth error detection)
- parseNVMeTemps: 88.9%→100% (16 cases for NVMe temp parsing)
- updateDeadLetterMetrics: 75%→100% (6 cases for nil handling, queue states)
2025-12-01 19:20:09 +00:00
rcourtman
7bab2f86af test: Add tests for AllowDockerHostReenroll, SelectInterval, ensureBreaker
- AllowDockerHostReenroll: 95%→100% (7 cases for empty/blocked/cleanup paths)
- ensureBreaker: 94.4%→100% (6 cases for nil map, existing, custom config)
- SelectInterval: 94%→96% (20+ cases for edge cases, remaining guards unreachable)
2025-12-01 19:13:40 +00:00
rcourtman
e7bc06033a test: Add tests for convertDockerSwarmInfo, namespacePathsForDatastore, preserveFailedStorageBackups
- convertDockerSwarmInfo: 66.7%→100% (4 cases for nil, empty, populated structs)
- namespacePathsForDatastore: 92.3%→100% (removed unreachable dead code)
- preserveFailedStorageBackups: 91.3%→100% (6 cases for filtering, deduplication)
2025-12-01 19:04:23 +00:00
rcourtman
0bfc9ed447 test: Add tests for storageNamesForNode, GetDockerHost, and SchedulerHealth edge cases
- storageNamesForNode: 83.3%→100% (8 cases for filtering logic)
- GetDockerHost: 75%→100% (5 cases for lookup and whitespace handling)
- SchedulerHealth: 85.3%→89.1% (13 cases for nil handling, breaker key parsing)
2025-12-01 18:57:09 +00:00
rcourtman
2d775e9409 test: Add tests for polling interval, proxy success handlers, and failed instance removal
- effectivePVEPollingInterval: 80%→100% (6 cases for nil/clamping)
- handleProxySuccess: 80%→100% (3 cases for nil client, reset)
- handleProxyHostSuccess: →100% (6 cases for empty/whitespace/removal)
- removeFailedPBSNode: 75%→100% (5 cases for removal, backups, health)
- removeFailedPMGInstance: 75%→100% (5 cases for removal, backups, health)
2025-12-01 18:49:09 +00:00
rcourtman
acb7f4cf3a test: Add tests for normalizeEndpointHost, taskExecutionTimeout, decrementPending
- normalizeEndpointHost: 89%→94.4% (19 cases covering schemes, ports, paths, edge cases)
- taskExecutionTimeout: 83%→100% (4 cases covering defaults and custom timeouts)
- decrementPending: 88%→100% (5 cases covering decrement logic and no-op scenarios)
2025-12-01 18:42:57 +00:00
rcourtman
6183727368 test: Add tests for getNodeDisplayName, lookupClusterEndpointLabel, extractSnapshotName
- getNodeDisplayName: 71%→100% (12 tests covering cluster/non-cluster fallbacks)
- lookupClusterEndpointLabel: 77%→85% (14 tests covering endpoint matching)
- extractSnapshotName: 78%→100% (8 tests covering volid parsing)

Monitoring package 46.2%→46.4%
2025-12-01 18:37:27 +00:00
rcourtman
330cec7829 test: Add tests for clampUint64ToInt64 and resetAuthFailures
- clampUint64ToInt64: 67%→100% (5 tests covering boundary conditions)
- resetAuthFailures: 67%→100% (6 tests covering map cleanup logic)

Note: cloneStringFloatMap and cloneStringMap tests already existed.
2025-12-01 18:31:34 +00:00
rcourtman
7672cad174 test: Add tests for SetBreakerState, RecordResult, ResetQueueDepth, IncInFlight, DecInFlight
- SetBreakerState: 67%→100% (8 tests covering state conversion, retryAt clamping)
- RecordResult: 75%→96% (11 tests covering success/failure paths, staleness)
- ResetQueueDepth: 75%→100% (4 tests covering negative clamping)
- IncInFlight/DecInFlight: 67%→100% (4 tests)

Monitoring package 45.9%→46.2%
2025-12-01 18:27:05 +00:00
rcourtman
44b6745741 test: Add tests for recordAuthFailure, shouldSkipProxyHost, recoverFromPanic
- recordAuthFailure: 53%→100% (8 tests covering failure counting, node removal)
- shouldSkipProxyHost: 44%→100% (9 tests covering cooldown logic, state cleanup)
- recoverFromPanic: 50%→100% (7 tests covering various panic value types)

Monitoring package 45.3%→45.9%
2025-12-01 18:20:12 +00:00
rcourtman
b4fb5d2a6a test: Add tests for mergeNVMeTempsIntoDisks, UpdateQueueSnapshot, UpdateDeadLetterCounts, templateFuncMap
- mergeNVMeTempsIntoDisks: 57%→97% (14 tests covering WWN/serial/path matching, NVMe fallback)
- UpdateQueueSnapshot: 57%→100% (5 tests covering nil, gauges, stale key cleanup)
- UpdateDeadLetterCounts: 52%→100% (7 tests covering aggregation, normalization)
- templateFuncMap: 20%→100% (8 tests covering all template helper functions)

Monitoring 44.6%→45.3%, notifications 45.7%→45.9%
2025-12-01 18:14:43 +00:00
rcourtman
0803951854 test: Add tests for getInstanceConfig, baseIntervalForInstanceType, LoadOIDCConfig
- getInstanceConfig: 33%→100% (nil handling, case-insensitive matching)
- baseIntervalForInstanceType: 50%→100% (all instance types, clamping)
- LoadOIDCConfig: 35%→94% (file not exist, read errors, decryption)
2025-12-01 18:06:15 +00:00
rcourtman
4defced1a6 test: Add monitoring tests for parseDurationEnv, parseIntEnv, markFailed, logNodeMemorySource
Add comprehensive test coverage for:
- parseDurationEnv: empty/unset env, valid durations, invalid inputs
- parseIntEnv: empty/unset env, valid integers, invalid inputs
- markFailed: status setting, timestamps, failure reason
- logNodeMemorySource: nil handling, source change detection, log levels

All four functions now at 100% coverage (up from 0-78%).
2025-12-01 17:59:20 +00:00
rcourtman
5d592bf4e6 test: Add tests for diagnostic snapshot recording and retrieval
- recordGuestSnapshot: nil handling, field setting, map initialization
- GetDiagnosticSnapshots: nil/empty handling, sorting verification

Both functions now at 100% coverage.
2025-12-01 17:48:36 +00:00
rcourtman
d6359276ed test: Add tests for monitoring and notifications functions
- buildCephClusterModel: 0% → 100% (11 test cases)
- collectContainerRootUsage: 0% → 100% (18 test cases)
- NotificationManager getters/setters: 8 functions now tested

Overall coverage: 45.5% → 45.8%
2025-12-01 17:33:36 +00:00
rcourtman
6ae187c954 test: Add comprehensive tests for hasExpired function
Cover all branches: nil ExpiresAt, future expiry, past expiry, and exact
expiry time edge case. Coverage improved from 66.7% to 100%.
2025-12-01 15:20:11 +00:00
rcourtman
5431ad2595 test: Add taskHeap.Less tiebreaker test case
When tasks have identical NextRun and Priority, the Less function
falls back to comparing InstanceName alphabetically. Add test to
cover this edge case branch, improving Less coverage to 100%.
2025-12-01 14:36:32 +00:00
rcourtman
2947c3dce1 test: Add tests for monitoring helper and normalize functions
- TestCloneStringFloatMap: Deep copy verification for float maps
- TestCloneStringMap: Deep copy verification for string maps
- TestNormalizeAgentVersion: Version prefix normalization
- TestNormalizePBSNamespacePath: PBS namespace path handling
- TestNamespacePathsForDatastore: Datastore namespace extraction
- TestNormalizeDockerHostID: Docker host ID normalization
Coverage: monitoring 42.2% → 42.5%
2025-12-01 14:14:48 +00:00
rcourtman
93ea641791 test: Add unit tests for container_parsing.go pure functions
Tests for LXC container config parsing functions:
- sanitizeRootFSDevice: rootfs device extraction
- collectIPsFromInterface: recursive IP extraction from various types
- parseContainerRawIPs: JSON IP parsing
- parseContainerConfigNetworks: network interface parsing with MAC
  normalization, CIDR stripping, sorting
- parseContainerMountMetadata: mount point metadata parsing
- extractContainerRootDeviceFromConfig: root device extraction
- mergeContainerNetworkInterface: interface merging by name/MAC
- convertContainerDiskInfo: Proxmox disk info conversion
- ensureContainerRootDiskEntry: root disk entry creation

91+ test cases covering edge cases, invalid data, and complex scenarios.
Coverage improved from 40.6% to 42.2%.
2025-12-01 13:28:39 +00:00
rcourtman
611e606513 test: Add unit tests for docker_host_identity.go pure functions
Tests for all 9 functions handling Docker host identification:
- uniqueNonEmptyStrings: dedupe with order preservation
- sanitizeDockerHostSuffix: string cleaning for IDs
- tokenHintFromRecord: redacted token hints
- dockerHostIDExists: ID existence check
- dockerHostSuffixCandidates: candidate suffix generation
- fallbackDockerHostID: hash-based ID generation
- findMatchingDockerHost: host matching by various criteria
- generateDockerHostIdentifier: unique ID generation with suffixes
- resolveDockerHostIdentifier: main resolver orchestration

86 test cases covering edge cases (nil, empty, whitespace), Unicode
handling, and complex matching scenarios.
2025-12-01 13:20:30 +00:00
rcourtman
19bc5f7977 test: Add unit tests for convertDockerServices
Tests cover nil/empty inputs, basic field copying, time fields
(CreatedAt/UpdatedAt with nil and zero value handling), update status
conversion, endpoint ports, and labels cloning.
2025-12-01 13:15:29 +00:00
rcourtman
2990864f66 test: Add unit tests for guest_metadata.go pure functions
Add comprehensive tests for:
- guestMetadataCacheKey: cache key generation with edge cases
- cloneStringSlice: nil/empty handling, deep copy verification
- cloneGuestNetworkInterfaces: nil/empty, deep address copy
- processGuestNetworkInterfaces: IP filtering (loopback, link-local),
  deduplication, sorting, whitespace trimming, traffic-only interfaces

Increases monitoring package coverage from 38.9% to 39.6%.
2025-12-01 12:18:59 +00:00
rcourtman
845b096240 test: Add error path tests for acknowledgeDockerCommand
- Use public API AcknowledgeDockerHostCommand instead of private function
- Use strings.Contains instead of custom helper functions
- Add test case for empty hostID (skips validation, succeeds)
2025-12-01 12:08:16 +00:00
rcourtman
46a72a7600 Fix outdated error message path for removed Docker hosts
The error message referenced "Settings -> Docker -> Removed hosts" but
that UI path no longer exists. The correct path is now
"Settings -> Agents -> Removed Docker Hosts".

Related to #778
2025-12-01 12:03:05 +00:00
rcourtman
56726f15e0 refactor: Extract guest metadata functions to separate file
Move 17 guest-metadata-related functions from monitor.go to new
guest_metadata.go file. This includes:
- Guest agent API call retry logic
- Guest metadata caching (fetch, reserve, schedule, clear)
- Network interface processing and cloning
- OS info extraction
- Type conversion utilities (stringValue, anyToInt64)

Reduces monitor.go by 541 lines (8932 → 8391).
2025-12-01 10:53:41 +00:00
rcourtman
0b2485b26b refactor: Extract container parsing functions to separate file
Move 13 related container parsing functions from monitor.go (9359 lines)
to container_parsing.go (451 lines). Reduces monitor.go by 427 lines.

Functions extracted:
- ensureContainerRootDiskEntry
- convertContainerDiskInfo
- sanitizeRootFSDevice
- parseContainerRawIPs
- collectIPsFromInterface
- sanitizeGuestAddressStrings
- dedupeStringsPreserveOrder
- containerNetworkDetails struct
- containerMountMetadata struct
- parseContainerConfigNetworks
- parseContainerMountMetadata
- mergeContainerNetworkInterface
- extractContainerRootDeviceFromConfig
2025-12-01 10:40:48 +00:00
rcourtman
5a4bc3b053 refactor: Extract Docker host identifier functions to separate file
Move 9 related pure functions from monitor.go (9616 lines) to
docker_host_identity.go (281 lines). Reduces monitor.go by 257 lines.

Functions extracted:
- tokenHintFromRecord
- resolveDockerHostIdentifier
- findMatchingDockerHost
- dockerHostIDExists
- generateDockerHostIdentifier
- dockerHostSuffixCandidates
- sanitizeDockerHostSuffix
- fallbackDockerHostID
- uniqueNonEmptyStrings
2025-12-01 10:03:47 +00:00
rcourtman
0c50d9e6b7 Add unit tests for error classification functions in monitoring
Add 56 test cases covering:
- isTransientError: 13 cases for context errors, retryable MonitorErrors,
  and standard error types (nil, Canceled, DeadlineExceeded, Timeout, etc.)
- shouldTryPortlessFallback: 14 cases for connection error patterns that
  trigger port fallback (refused, reset, no such host, timeout variants)
- shouldAttemptFallback: 13 cases for timeout/deadline/canceled patterns
  used in storage polling fallback
- classifyDLQReason: 8 cases for dead letter queue reason classification
  (max_retry_attempts vs permanent_failure)
- Edge cases: 3 cases for overlapping error patterns and partial matches

First test file for these error classification utilities used in retry
and fallback decision logic.
2025-12-01 01:37:28 +00:00
rcourtman
fb240c2d40 Add unit tests for monitor.go type conversion utilities
Add 97 test cases for four utility functions in monitor.go:
- stringValue (30 cases): Type-to-string conversion for various Go types
  including string, int types, float types, json.Number, fmt.Stringer
- anyToInt64 (34 cases): Interface-to-int64 conversion with overflow
  handling, string parsing, and json.Number support
- parseInterfaceStat (15 cases): Interface stat map parsing for network
  interface statistics
- extractGuestOSInfo (18 cases): QEMU guest agent OS info extraction
  with fallback logic for various Linux distros, Windows, FreeBSD

Coverage for these functions: 0% → 100%
Package coverage: 37.5% → 38.5%
2025-12-01 00:51:20 +00:00
rcourtman
0198eaf6c8 Add unit tests for monitoring utility functions
Added comprehensive tests for 6 previously untested pure utility functions:
- sortContent: sorts comma-separated storage content values
- formatSeconds: converts total seconds to HH:MM:SS format
- dedupeStringsPreserveOrder: deduplicates strings while preserving order
- sanitizeGuestAddressStrings: validates and filters IP addresses
- copyFloatPointer: creates independent copy of float64 pointer
- clampInterval: clamps time.Duration to specified bounds

Tests cover edge cases including empty inputs, boundary conditions,
special values (DHCP, loopback addresses), and various separators.
Coverage increased from 36.8% to 37.5%.
2025-12-01 00:37:24 +00:00
rcourtman
0538e8f013 Add unit tests for diagnostic snapshot key generation functions
32 test cases covering makeNodeSnapshotKey and makeGuestSnapshotKey
utility functions used for diagnostic memory snapshot storage. Tests
cover simple inputs, edge cases (empty strings, negative VMIDs),
special characters, and key uniqueness verification. Also includes
struct field tests for NodeMemoryRaw and VMMemoryRaw.

First test file for diagnostic_snapshots.go. Coverage 36.7% → 36.8%.
2025-11-30 22:34:09 +00:00
rcourtman
54fab46bd6 Fix backup status indicator not showing for guests
The backup status indicator feature was incomplete - it added the UI
component but never populated VM/Container LastBackup from actual
backup data. Now SyncGuestBackupTimes() is called after storage
backups and PBS backups are polled, matching each guest's VMID to
its most recent backup timestamp.

Fixes #786
2025-11-30 22:13:46 +00:00
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
28a0851868 Add unit tests for container disk usage utility functions (monitoring) 2025-11-30 13:20:39 +00:00
rcourtman
90e1b8e546 Add unit tests for RateTracker.CalculateRates (monitoring) 2025-11-30 07:07:18 +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
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
0dd65c5db2 Add unit tests for TaskQueue Upsert and Remove methods 2025-11-29 21:38:33 +00:00
rcourtman
9393574f05 ADA: Add unit tests for Ceph helper functions
Test coverage for isCephStorageType, countServiceDaemons,
extractCephCheckSummary, and summarizeCephHealth functions.
These parse Ceph storage types and health status JSON.
2025-11-29 19:49:43 +00:00