Commit graph

592 commits

Author SHA1 Message Date
rcourtman
5c584b9eee test: Add comprehensive tests for HandleDockerHostOffline
HandleDockerHostOffline (0%→100%):
- Empty host ID is no-op
- Disabled alerts is no-op
- DisableAllDockerHostsOffline clears tracking and alert
- Override DisableConnectivity clears tracking and alert
- Existing alert updates LastSeen
- Requires 3 confirmations before alert
- Alert has correct metadata (resourceType, hostId, agentId)

Coverage: 55.6% → 56.9%
2025-12-01 16:39:10 +00:00
rcourtman
7bac96d60b test: Add comprehensive tests for HandleHostRemoved, ReevaluateGuestAlert
HandleHostRemoved (0%→100%):
- Empty host ID is no-op
- Clears host offline alert and confirmations
- Clears host metric alerts (CPU, memory)
- Clears host disk alerts
- Clears all alert types together

ReevaluateGuestAlert (0%→100%):
- No active alerts is no-op
- Clears alert when threshold disabled (nil)
- Clears alert when trigger is zero
- Clears alert when value below clear threshold
- Clears alert when value below trigger threshold
- Keeps alert when value above both thresholds
- Processes all metric types (7 types)
- Clears pending alert when threshold disabled
- Uses clear equals trigger when clear is zero
- Ignores alerts for different guests

NormalizeMetricTimeThresholds (0%→100%):
- Updated existing test to call public wrapper instead of internal function

Coverage: 54.6% → 55.6%
2025-12-01 16:36:48 +00:00
rcourtman
65e5eb84ae test: Add comprehensive tests for reevaluateActiveAlertsLocked
Tests major branches for alert re-evaluation on config change:
- Empty alerts map (no-op)
- Alert ID with insufficient parts (skipped)
- DisableAllPMG resolves PMG queue alerts
- DisableAllHosts resolves Host alerts via resourceType metadata
- Docker host offline alerts are skipped (not threshold-based)
- DisableAllDockerHosts resolves dockerhost metric alerts
- DisableAllNodes resolves Node alerts via Instance field
- DisableAllStorage resolves Storage alerts
- DisableAllPBS resolves PBS alerts
- DisableAllGuests resolves Guest alerts
- Disabled override resolves alert
- Alert below clear threshold is resolved
- Alert between clear and trigger is resolved on config change

Coverage improvement:
- reevaluateActiveAlertsLocked: 59.8% → 81.2%
- alerts package: 54.0% → 54.6%
2025-12-01 16:31:05 +00:00
rcourtman
46eccd561a test: Add comprehensive tests for HandleHostOffline function
Tests all branches:
- Empty host ID returns early
- Alerts disabled returns early
- DisableAllHostsOffline clears alert and confirmation tracking
- Override DisableConnectivity clears alert and returns
- Override Disabled clears alert and returns
- Existing alert updates LastSeen only
- Insufficient confirmations waits for more
- Sufficient confirmations (3) creates alert with metadata

Coverage improvement:
- HandleHostOffline: 64.0% → 100%
- alerts package: 53.5% → 54.0%
2025-12-01 16:26:56 +00:00
rcourtman
1647b232db test: Add comprehensive tests for applyGlobalOfflineSettingsLocked
Tests all 7 disable settings branches:
- DisableAllNodesOffline: clears node-offline-* alerts and nodeOfflineCount
- DisableAllPBSOffline: clears pbs-offline-* alerts and offlineConfirmations
- DisableAllGuestsOffline: clears guest-powered-off-* alerts and offlineConfirmations
- DisableAllDockerHostsOffline: clears docker-host-offline-* alerts and dockerOfflineCount
- DisableAllDockerContainers: clears docker-container-* alerts and tracking state
- DisableAllDockerServices: clears docker-service-* alerts
- No settings enabled: verifies no-op behavior

Coverage improvement:
- applyGlobalOfflineSettingsLocked: 57.1% → 100%
- alerts package: 53.0% → 53.5%
2025-12-01 16:23:45 +00:00
rcourtman
a4008f914f test: Add comprehensive tests for alert clearing functions
- TestClearBackupAlertsLocked: tests backup-age alert clearing with nil handling
- TestClearBackupAlerts: tests public wrapper function
- TestClearSnapshotAlertsForInstanceLocked: tests instance-specific snapshot clearing
- TestClearSnapshotAlertsForInstance: tests public wrapper function

Coverage improvement:
- clearBackupAlertsLocked: 75% → 100%
- clearBackupAlerts: 0% → 100%
- clearSnapshotAlertsForInstanceLocked: 50% → 100%
- clearSnapshotAlertsForInstance: 0% → 100%
- alerts package: 52.8% → 53.0%
2025-12-01 16:20:49 +00:00
rcourtman
876d81ea12 test: Add edge case tests for ClearActiveAlerts and sanitizeAlertKey
- TestClearActiveAlertsEmptyMaps: tests early return when both maps empty
- sanitizeAlertKey: test for input with only slashes/backslashes -> root

Coverage improvement:
- sanitizeAlertKey: 96.4% → 100%
- alerts package: 52.8%
2025-12-01 16:15:50 +00:00
rcourtman
6e779742d8 test: Add comprehensive tests for AcknowledgeAlert and UnacknowledgeAlert functions
- TestAcknowledgeAlertNotFound: tests error path when alert doesn't exist
- TestUnacknowledgeAlertNotFound: tests error path when alert doesn't exist
- TestUnacknowledgeAlertSuccess: tests successful unacknowledgement with state verification

Coverage improvement:
- AcknowledgeAlert: 92.3% → 100%
- UnacknowledgeAlert: 41.7% → 100%
- alerts package: 52.6% → 52.8%
2025-12-01 16:12:50 +00:00
rcourtman
edf0cae4f9 test: Add edge case tests for matchesDockerIgnoredPrefix function
- skips empty prefix in list
- all empty prefixes returns false
- empty name/id edge cases
- matchesDockerIgnoredPrefix 92.3%→100%
2025-12-01 16:08:21 +00:00
rcourtman
9052e48245 test: Add comprehensive tests for HandleHostOnline function
- clears offline alert and confirmation tracking
- clears confirmation even without alert
- empty host ID is noop
- HandleHostOnline 90%→100%
2025-12-01 16:06:06 +00:00
rcourtman
9229cf86be test: Add comprehensive tests for safeCallResolvedCallback function
- calls callback synchronously with alert ID
- calls callback asynchronously
- noop when callback is nil
- recovers from panic in sync and async callbacks
- safeCallResolvedCallback 90%→100%
2025-12-01 16:04:25 +00:00
rcourtman
9f1a5c2183 test: Add comprehensive tests for safeCallEscalateCallback function
- calls callback with alert and level
- noop when callback is nil
- recovers from panic in callback
- clones alert to prevent concurrent modification
- safeCallEscalateCallback 0%→100%
2025-12-01 16:02:19 +00:00
rcourtman
d7360c7b22 test: Add comprehensive tests for cleanupDockerContainerAlerts function
- clears alerts and state tracking not in seen set
- skips alerts from other hosts
- handles empty seen set (clears all)
- cleanupDockerContainerAlerts 75%→100%
2025-12-01 15:59:49 +00:00
rcourtman
b5a8817ee4 test: Add comprehensive tests for HandleDockerHostOnline function
- clears offline alert and tracking
- clears tracking even when no alert exists
- empty host ID is noop
- HandleDockerHostOnline 88.9%→100%
2025-12-01 15:57:44 +00:00
rcourtman
e7cf40c2c6 test: Add empty ID test for HandleDockerHostRemoved function
- empty host ID is noop (preserves existing alerts/tracking)
- HandleDockerHostRemoved 75%→100%
2025-12-01 15:56:11 +00:00
rcourtman
7580d0b3d5 test: Add comprehensive tests for cleanupHostDiskAlerts function
- clears alerts not in seen set (stale disk alerts)
- empty host ID is noop
- skips nil alerts without panic
- skips non-matching prefix (non-disk alerts)
- cleanupHostDiskAlerts 76.9%→100%
2025-12-01 15:54:33 +00:00
rcourtman
39a856aaf8 test: Add comprehensive tests for clearHostDiskAlerts function
- clears all disk alerts for specified host
- empty hostID is noop
- skips nil alerts without panic
- noop when no matching alerts
- clearHostDiskAlerts 72.7%→100%
2025-12-01 15:52:39 +00:00
rcourtman
32b346b8ce test: Add comprehensive tests for clearHostMetricAlerts function
- clears specified metrics from host
- defaults to cpu and memory when no metrics specified
- empty hostID is noop
- clearHostMetricAlerts 85.7%→100%
2025-12-01 15:50:59 +00:00
rcourtman
a3aef773ec test: Add comprehensive tests for clearStorageOfflineAlert function
- clears existing offline alert and confirmation
- triggers resolved callback
- noop when no alert exists
- clears offline confirmation even without alert
- clearStorageOfflineAlert 50%→100%
2025-12-01 15:48:32 +00:00
rcourtman
2fbf9cbe7b test: Add comprehensive tests for dockerServiceResourceID function
- with/without host ID (prefix selection)
- derives ID from service name with sanitization
- special chars replaced with dashes
- preserves alphanumeric, underscore, hyphen
- trims leading/trailing dashes/underscores
- truncates long IDs to 32 chars
- fallback to 'service' when empty
- dockerServiceResourceID 23.8%→100%
2025-12-01 15:46:34 +00:00
rcourtman
884d04ae61 test: Add comprehensive tests for dockerServiceDisplayName function
- returns name when present
- returns trimmed name
- returns truncated ID when name empty (first 12 chars)
- returns full short ID when < 12 chars
- returns 'service' when both empty/whitespace
- prefers name over ID
- dockerServiceDisplayName 33.3%→100%
2025-12-01 15:44:40 +00:00
rcourtman
a97a4a022c test: Add comprehensive tests for shouldNotifyAfterCooldown function
- cooldown disabled (0) allows notification
- negative cooldown allows notification
- first notification allowed when never notified
- notification blocked during cooldown period
- notification allowed after cooldown expires
- boundary condition (exact cooldown time)
- shouldNotifyAfterCooldown 42.9%→100%
2025-12-01 15:42:35 +00:00
rcourtman
46f0632c53 test: Add comprehensive tests for applyRelaxedGuestThresholds function
- nil thresholds get defaults (CPU 95, Memory 92, Disk 95)
- low thresholds raised to minimum relaxed values
- high thresholds unchanged
- clear adjusted when too close to trigger
- original config unchanged (no mutation)
- alerts package coverage improvement: applyRelaxedGuestThresholds 75%→93.8%
2025-12-01 15:40:19 +00:00
rcourtman
10498a0d54 test: Add comprehensive tests for checkRateLimit function
Cover all branches: disabled rate limit (zero/negative MaxAlertsHour),
under limit, at limit blocking, separate limits per alertID, old entry
cleanup, and mixed old/recent entries. Coverage improved from 71.4% to 100%.
2025-12-01 15:35:19 +00:00
rcourtman
c488956001 test: Add comprehensive tests for getMetricTimeThreshold function
Cover all branches: empty config, empty/whitespace metricType, direct
match, canonical key matching (vm→guest, container→guest), fallback
chain (default, _default, wildcard), precedence, and no-match scenarios.
Coverage improved from 77.8% to 100%.
2025-12-01 15:32:33 +00:00
rcourtman
a9fe80e1cd test: Add comprehensive tests for EmailTemplate function
Cover both branches: single alert template (isSingle=true with 1 alert)
and grouped alert template (isSingle=false or multiple alerts). Tests
verify subject format, HTML structure, and text body generation.
Coverage improved from 66.7% to 100%.
2025-12-01 15:29:31 +00:00
rcourtman
844b9e5637 test: Add comprehensive tests for getBaseTimeThreshold function
Cover all branches: nil/empty TimeThresholds, direct match, canonical key
matching (vm→guest, container→guest), "all" fallback, specific match
precedence, and global threshold fallback. Coverage improved from 85.7% to 100%.
2025-12-01 15:25:18 +00:00
rcourtman
22abeea3a9 test: Add comprehensive tests for CreateProxmoxConfigFromFields function
Cover all branches: user without realm gets @pam appended, user with
realm unchanged, token auth skips user modification, empty user handling,
and fingerprint/verifySSL preservation. Coverage improved from 66.7% to 100%.
2025-12-01 15:22:50 +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
fecab94dc8 test: Add comprehensive tests for getGlobalMetricTimeThreshold function
Cover all branches: empty config, missing 'all' key, empty perType map,
empty/whitespace metricType, direct match, case insensitivity, default
fallback, _default fallback, wildcard fallback, and no-match scenarios.
Coverage improved from 58.8% to 100%.
2025-12-01 15:17:12 +00:00
rcourtman
7c0ea6a07b test: Add comprehensive tests for isInQuietHours function
Cover all branches: disabled state, invalid timezone fallback, day not
enabled, invalid start/end time parsing, overnight window spanning
midnight, and normal daytime window. Coverage improved from 61.5% to 96.2%.
2025-12-01 15:14:44 +00:00
rcourtman
606764f931 test: Add comprehensive tests for checkFlapping function
Cover all branches of flapping detection: disabled state, below/at/above
threshold, already-flapping state (no suppression update), and window
expiry pruning. Coverage improved from 61.9% to 95.2%.
2025-12-01 15:11:11 +00:00
rcourtman
c7d832c8d9 test: Add comprehensive tests for BuildGuestKey function
- Test different instance and node (full format)
- Test same instance and node (short format)
- Test empty instance defaults to node
- Test whitespace trimming
- Improves BuildGuestKey coverage from 71.4% to 100%
2025-12-01 15:04:37 +00:00
rcourtman
50843d3013 test: Add LoadAPITokens error path tests
- Test nonexistent file returns empty slice (not error)
- Test empty file returns empty slice
- Test invalid JSON returns error
- Improves LoadAPITokens coverage from 80% to 93.3%
2025-12-01 15:00:56 +00:00
rcourtman
9461afc0be test: Add renderWebhookURL URL parsing error test
Add test case for malformed IPv6 URL that triggers url.Parse error.
Improves coverage from 90% to 95%. The remaining 5% is a template
Execute error path that's effectively unreachable with current types.
2025-12-01 14:57:25 +00:00
rcourtman
e774feb8ba test: Add HasScope edge case tests for API tokens
- Test empty scope always returns true
- Test explicit wildcard scope in list grants any scope
- Improves coverage from 85.7% to 100%
2025-12-01 14:51:58 +00:00
rcourtman
4973eb4c8a test: Improve coverage for cluster config handler functions
- deriveSchemeAndPort: 87.5% → 100%
  - Empty/whitespace string handling
  - Invalid URL parsing fallback
  - Host without port
- ensureHostHasPort: 91.7% → 100%
  - Empty port returns host unchanged
  - Protocol-relative URL handling (//host)
2025-12-01 14:46:00 +00:00
rcourtman
c6030d1b13 test: Add tests for ResetRateLimitForIP function
- Test nil globalRateLimitConfig early return (no panic)
- Test actual rate limit reset clears IP from limiter
- Improves coverage from 80% to 100%
2025-12-01 14:38:26 +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
737c02983f test: Improve coverage for security utility functions
- Add fmt.Stringer test cases for isEmptyInterface (80% -> 100%)
- Expand isTrustedNetwork tests with edge cases (80% -> 100%)
  - Empty/invalid IP strings
  - Invalid CIDR handling
  - Whitespace trimming in CIDRs
  - Multiple network matching
2025-12-01 14:33:31 +00:00
rcourtman
17512e076a test: Add tests for updates package utility functions
- TestNormalizeGitDescribeVersion: Git describe format parsing
- TestSanitizeError: Error message length truncation
- TestStatusDelayForStage: Update stage delay logic
Coverage: updates 41.5% → 41.6%
2025-12-01 14:18:54 +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
b863b2473d test: Add tests for config handler utility functions
- TestSanitizeErrorMessage: All operation types and error hiding
- TestFindExistingGuestURL: Node matching and edge cases
- TestMatchInstanceNameByHost: Host normalization and matching
Coverage: api 27.7% → 28.0%
2025-12-01 14:09:35 +00:00
rcourtman
4058e575f7 test: Add tests for metric threshold lookup functions
- normalizeMetricTimeThresholds: key normalization, invalid value filtering
- getThresholdForMetric: all metric types, empty config, case sensitivity
- getThresholdForMetricFromConfig: hysteresis application, all metric types

Coverage: alerts 49.0% → 49.9%
2025-12-01 14:01:25 +00:00
rcourtman
be5a6eb97e test: Add tests for OIDC handler utility functions
- sanitizeOIDCReturnTo: path validation, protocol-relative URL rejection
- addQueryParam: URL building, encoding, fragment preservation
- extractStringClaim: type handling (string, []string, []interface{})
- extractStringSliceClaim: slice extraction with comma/space splitting
- matchesValue: case-insensitive value matching
- matchesDomain: email domain validation with @ handling
- intersects: set intersection with case normalization
- buildRedirectURL: proxy header handling (X-Forwarded-Proto/Host)

Coverage: api 26.7% → 27.7%
2025-12-01 13:56:38 +00:00
rcourtman
23794987f0 test: Add tests for alerts clone functions and parsePulseTags
- cloneThreshold: nil handling, value copying, pointer independence
- cloneStringPtr: nil handling, string copying, pointer independence
- cloneThresholdConfig: full config deep copy verification
- ensureHysteresisThreshold: default clear calculation, edge cases
- parsePulseTags: tag parsing, case insensitivity, whitespace handling

Coverage: alerts 48.9% → 49.0%
2025-12-01 13:52:09 +00:00
rcourtman
03d41fb71b test: Add tests for notification config copy functions
Tests for defensive copy functions that ensure data isolation:
- copyEmailConfig: copies email config with slice independence
- copyWebhookConfigs: deep copies webhooks including maps
- copyAppriseConfig: copies apprise config with slice independence
- buildNotificationTestAlert: validates test alert structure

Tests verify that modifying copies doesn't affect originals,
critical for concurrent access safety.
2025-12-01 13:43:52 +00:00
rcourtman
447478785b test: Add unit tests for filter_evaluation.go functions
Tests for alert filter evaluation logic:
- evaluateVMCondition: metric/text/raw conditions for VMs
- evaluateContainerCondition: same for containers
- evaluateFilterStack: AND/OR logic with multiple conditions
- evaluateFilterCondition: type dispatch

74 test cases covering:
- All metric types (cpu, memory, disk, diskread, diskwrite, network)
- All comparison operators (>, <, >=, <=, =, ==)
- Text search fields (name, node, vmid) with case insensitivity
- Raw text search across multiple fields
- Value type conversions (int to float64)
- Edge cases (zero, empty, invalid types)

Coverage improved from 46.8% to 48.9%.
2025-12-01 13:34:23 +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