Commit graph

1296 commits

Author SHA1 Message Date
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
2078421da4 Fix Docker expanded drawer cards being cut off
The expanded container/service drawer cards were overflowing
horizontally instead of wrapping when the table had overflow-x-auto.
Adding overflow-hidden to the drawer's outer container forces the
flex-wrap to work correctly.

Related to #789
2025-12-01 15:06:49 +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
ba31e4025d test: Add tests for authHTTPError.Error and shouldFallbackToForm
Tests for Proxmox client authentication error handling:
- authHTTPError.Error: message formatting based on status code
  (401/403 include status in message, others don't)
- shouldFallbackToForm: determines when to retry with form encoding
  (triggers on 400/415, not on auth errors or server errors)

16 test cases covering all code paths.
2025-12-01 13:39:50 +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
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
c2de40d696 test: Add error path tests for loadOrCreateBootstrapToken
Cover all error branches in bootstrap token loading:
- Empty/whitespace dataPath validation
- os.MkdirAll failure (directory creation blocked by file)
- os.WriteFile failure (read-only directory)
- os.ReadFile failure (permission denied on existing file)
- Empty file contents after read
- Whitespace-only file contents

Also adds test for generateBootstrapToken helper function.
2025-12-01 13:00:27 +00:00
rcourtman
e6b9bd501d test: Add error path tests for renderWebhookURL and UpdateAllowedPrivateCIDRs
Add comprehensive error handling tests for two pure functions:

renderWebhookURL (8 new test cases):
- Empty/whitespace URL template validation
- Invalid template syntax (unclosed braces, undefined functions)
- Template producing empty URL
- Missing scheme or host in rendered URL

UpdateAllowedPrivateCIDRs (expanded from 8 to 29 cases):
- Invalid IP addresses (garbage, out of range, malformed)
- Invalid CIDR notation (prefix too large, negative, non-numeric)
- Malformed strings (double slash, invalid IP with valid prefix)
- Success cases for valid IPv4/IPv6 CIDRs and bare IPs
2025-12-01 12:58:15 +00:00
rcourtman
e2df1d0ed4 test: Add unit tests for api_tokens.go pure functions
Add comprehensive tests for tokenPrefix, tokenSuffix, normalizeScopes,
and IsKnownScope functions. Coverage increased 42.7% -> 43.3%.
2025-12-01 12:32:37 +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
827a8b4d37 test: Add unit tests for email_enhanced.go error handling
Add comprehensive tests for EnhancedEmailManager covering:
- Rate limiting (exceeds limit, resets after minute, concurrency, negative values)
- Provider username defaults (SendGrid, SparkPost, Resend, Postmark)
- TLS routing (TLS, StartTLS, plain connections)
- Retry logic (retries on failure, rate limit prevents retry)
- Connection error handling for sendTLS, sendStartTLS, sendPlain

This is the first test file for email_enhanced.go which previously had
0% coverage on sendTLS, sendStartTLS, and TestConnection functions.
2025-12-01 11:46:44 +00:00