mirror of
https://github.com/rcourtman/Pulse.git
synced 2026-11-30 01:32:00 +01:00
fix: Hosts page not updating in real-time (SolidJS reactivity bug)
Fixed a critical reactivity bug in HostsOverview.tsx where the HostRow
component was destructuring props.host in the function body. In SolidJS,
this breaks reactivity because the destructured value is a static snapshot
captured at component creation time.
Changes:
- Removed 'const { host } = props' destructuring in HostRow
- Changed all 'host.' references to 'props.host.' to maintain reactivity
- Converted cpuPercent and diskStats to reactive getters (functions)
- Added documentation comment explaining why destructuring breaks reactivity
This fixes Issue #949 where CPU, memory, and disk values on the Hosts
page would stay stale until manual page refresh.
Related to #949
This commit is contained in:
@@ -979,16 +979,17 @@ interface HostRowProps {
|
||||
}
|
||||
|
||||
const HostRow: Component<HostRowProps> = (props) => {
|
||||
const { host } = props;
|
||||
// NOTE: Do NOT destructure props.host - it breaks SolidJS reactivity!
|
||||
// Always access props.host directly to ensure updates flow through.
|
||||
|
||||
// Check if this host is in AI context
|
||||
const isInAIContext = createMemo(() => aiChatStore.enabled && aiChatStore.hasContextItem(host.id));
|
||||
const isInAIContext = createMemo(() => aiChatStore.enabled && aiChatStore.hasContextItem(props.host.id));
|
||||
|
||||
// URL editing using shared hook
|
||||
const urlEdit = createUrlEditState();
|
||||
|
||||
const handleStartEditingUrl = (e: MouseEvent) => {
|
||||
urlEdit.startEditing(host.id, props.customUrl || '', e);
|
||||
urlEdit.startEditing(props.host.id, props.customUrl || '', e);
|
||||
};
|
||||
|
||||
const handleSaveUrl = async () => {
|
||||
@@ -996,10 +997,10 @@ const HostRow: Component<HostRowProps> = (props) => {
|
||||
urlEdit.setIsSaving(true);
|
||||
try {
|
||||
if (url) {
|
||||
await props.onUpdateCustomUrl(host.id, url);
|
||||
await props.onUpdateCustomUrl(props.host.id, url);
|
||||
showSuccess('Host URL saved');
|
||||
} else {
|
||||
await props.onDeleteCustomUrl(host.id);
|
||||
await props.onDeleteCustomUrl(props.host.id);
|
||||
showSuccess('Host URL removed');
|
||||
}
|
||||
urlEdit.finishEditing();
|
||||
@@ -1013,7 +1014,7 @@ const HostRow: Component<HostRowProps> = (props) => {
|
||||
const handleDeleteUrl = async () => {
|
||||
urlEdit.setIsSaving(true);
|
||||
try {
|
||||
await props.onDeleteCustomUrl(host.id);
|
||||
await props.onDeleteCustomUrl(props.host.id);
|
||||
showSuccess('Host URL removed');
|
||||
urlEdit.finishEditing();
|
||||
} catch (err) {
|
||||
@@ -1025,16 +1026,16 @@ const HostRow: Component<HostRowProps> = (props) => {
|
||||
|
||||
// Build context for AI - includes routing fields
|
||||
const buildHostContext = (): Record<string, unknown> => ({
|
||||
hostName: host.displayName || host.hostname,
|
||||
hostname: host.hostname,
|
||||
node: host.hostname, // Used by AI for command routing
|
||||
target_host: host.hostname, // Explicit routing hint
|
||||
platform: host.platform,
|
||||
osName: host.osName,
|
||||
osVersion: host.osVersion,
|
||||
cpuUsage: host.cpuUsage ? `${host.cpuUsage.toFixed(1)}%` : undefined,
|
||||
memoryUsage: host.memory?.usage ? `${host.memory.usage.toFixed(1)}%` : undefined,
|
||||
uptime: host.uptimeSeconds ? formatUptime(host.uptimeSeconds) : undefined,
|
||||
hostName: props.host.displayName || props.host.hostname,
|
||||
hostname: props.host.hostname,
|
||||
node: props.host.hostname, // Used by AI for command routing
|
||||
target_host: props.host.hostname, // Explicit routing hint
|
||||
platform: props.host.platform,
|
||||
osName: props.host.osName,
|
||||
osVersion: props.host.osVersion,
|
||||
cpuUsage: props.host.cpuUsage ? `${props.host.cpuUsage.toFixed(1)}%` : undefined,
|
||||
memoryUsage: props.host.memory?.usage ? `${props.host.memory.usage.toFixed(1)}%` : undefined,
|
||||
uptime: props.host.uptimeSeconds ? formatUptime(props.host.uptimeSeconds) : undefined,
|
||||
});
|
||||
|
||||
// Handle row click - toggle AI context selection
|
||||
@@ -1046,10 +1047,10 @@ const HostRow: Component<HostRowProps> = (props) => {
|
||||
|
||||
// If AI is enabled, toggle AI context
|
||||
if (aiChatStore.enabled) {
|
||||
if (aiChatStore.hasContextItem(host.id)) {
|
||||
aiChatStore.removeContextItem(host.id);
|
||||
if (aiChatStore.hasContextItem(props.host.id)) {
|
||||
aiChatStore.removeContextItem(props.host.id);
|
||||
} else {
|
||||
aiChatStore.addContextItem('host', host.id, host.displayName || host.hostname, buildHostContext());
|
||||
aiChatStore.addContextItem('host', props.host.id, props.host.displayName || props.host.hostname, buildHostContext());
|
||||
if (!aiChatStore.isOpen) {
|
||||
aiChatStore.open();
|
||||
}
|
||||
@@ -1057,10 +1058,11 @@ const HostRow: Component<HostRowProps> = (props) => {
|
||||
}
|
||||
};
|
||||
|
||||
const hostStatus = createMemo(() => getHostStatusIndicator(host));
|
||||
const isOnline = () => host.status === 'online';
|
||||
const cpuPercent = host.cpuUsage ?? 0;
|
||||
const diskStats = props.getDiskStats(host);
|
||||
// Reactive getters to ensure values update when WebSocket data changes
|
||||
const hostStatus = createMemo(() => getHostStatusIndicator(props.host));
|
||||
const isOnline = () => props.host.status === 'online';
|
||||
const cpuPercent = () => props.host.cpuUsage ?? 0;
|
||||
const diskStats = () => props.getDiskStats(props.host);
|
||||
|
||||
const rowClass = () => {
|
||||
const base = 'transition-all duration-200';
|
||||
@@ -1086,16 +1088,16 @@ const HostRow: Component<HostRowProps> = (props) => {
|
||||
<div class="min-w-0 flex items-center gap-1.5 group/name">
|
||||
<div>
|
||||
<p class="text-sm font-semibold text-gray-900 dark:text-gray-100 whitespace-nowrap">
|
||||
{host.displayName || host.hostname || host.id}
|
||||
{props.host.displayName || props.host.hostname || props.host.id}
|
||||
</p>
|
||||
<Show when={host.displayName && host.displayName !== host.hostname}>
|
||||
<Show when={props.host.displayName && props.host.displayName !== props.host.hostname}>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-0.5 whitespace-nowrap">
|
||||
{host.hostname}
|
||||
{props.host.hostname}
|
||||
</p>
|
||||
</Show>
|
||||
<Show when={host.lastSeen}>
|
||||
<Show when={props.host.lastSeen}>
|
||||
<p class="text-[10px] text-gray-500 dark:text-gray-400 mt-0.5 whitespace-nowrap">
|
||||
Updated {formatRelativeTime(host.lastSeen!)}
|
||||
Updated {formatRelativeTime(props.host.lastSeen!)}
|
||||
</p>
|
||||
</Show>
|
||||
</div>
|
||||
@@ -1151,10 +1153,10 @@ const HostRow: Component<HostRowProps> = (props) => {
|
||||
<Show when={props.isColVisible('platform')}>
|
||||
<td class="px-2 py-1 align-middle">
|
||||
<div class="text-xs text-gray-700 dark:text-gray-300">
|
||||
<p class="font-medium capitalize whitespace-nowrap">{host.platform || '—'}</p>
|
||||
<Show when={host.osName}>
|
||||
<p class="font-medium capitalize whitespace-nowrap">{props.host.platform || '—'}</p>
|
||||
<Show when={props.host.osName}>
|
||||
<p class="text-[10px] text-gray-500 dark:text-gray-400 mt-0.5 whitespace-nowrap">
|
||||
{host.osName} {host.osVersion}
|
||||
{props.host.osName} {props.host.osVersion}
|
||||
</p>
|
||||
</Show>
|
||||
</div>
|
||||
@@ -1166,9 +1168,9 @@ const HostRow: Component<HostRowProps> = (props) => {
|
||||
<td class="px-2 py-1 align-middle" style={{ "min-width": props.isMobile() ? "60px" : "140px", "width": props.isMobile() ? undefined : "140px", "max-width": props.isMobile() ? undefined : "140px" }}>
|
||||
<Show when={isOnline()} fallback={<div class="flex justify-center"><span class="text-xs text-gray-400">—</span></div>}>
|
||||
<EnhancedCPUBar
|
||||
usage={cpuPercent}
|
||||
loadAverage={host.loadAverage?.[0]}
|
||||
cores={props.isMobile() ? undefined : host.cpuCount}
|
||||
usage={cpuPercent()}
|
||||
loadAverage={props.host.loadAverage?.[0]}
|
||||
cores={props.isMobile() ? undefined : props.host.cpuCount}
|
||||
/>
|
||||
</Show>
|
||||
</td>
|
||||
@@ -1179,11 +1181,11 @@ const HostRow: Component<HostRowProps> = (props) => {
|
||||
<td class="px-2 py-1 align-middle" style={{ "min-width": props.isMobile() ? "60px" : "140px", "width": props.isMobile() ? undefined : "140px", "max-width": props.isMobile() ? undefined : "140px" }}>
|
||||
<Show when={isOnline()} fallback={<div class="flex justify-center"><span class="text-xs text-gray-400">—</span></div>}>
|
||||
<StackedMemoryBar
|
||||
used={host.memory?.used || 0}
|
||||
total={host.memory?.total || 0}
|
||||
balloon={host.memory?.balloon || 0}
|
||||
swapUsed={host.memory?.swapUsed || 0}
|
||||
swapTotal={host.memory?.swapTotal || 0}
|
||||
used={props.host.memory?.used || 0}
|
||||
total={props.host.memory?.total || 0}
|
||||
balloon={props.host.memory?.balloon || 0}
|
||||
swapUsed={props.host.memory?.swapUsed || 0}
|
||||
swapTotal={props.host.memory?.swapTotal || 0}
|
||||
/>
|
||||
</Show>
|
||||
</td>
|
||||
@@ -1194,12 +1196,12 @@ const HostRow: Component<HostRowProps> = (props) => {
|
||||
<td class="px-2 py-1 align-middle" style={{ "min-width": props.isMobile() ? "60px" : "140px", "width": props.isMobile() ? undefined : "140px", "max-width": props.isMobile() ? undefined : "140px" }}>
|
||||
<Show when={isOnline()} fallback={<div class="flex justify-center"><span class="text-xs text-gray-400">—</span></div>}>
|
||||
<StackedDiskBar
|
||||
disks={host.disks}
|
||||
disks={props.host.disks}
|
||||
aggregateDisk={{
|
||||
total: diskStats.total,
|
||||
used: diskStats.used,
|
||||
free: diskStats.total - diskStats.used,
|
||||
usage: diskStats.percent / 100
|
||||
total: diskStats().total,
|
||||
used: diskStats().used,
|
||||
free: diskStats().total - diskStats().used,
|
||||
usage: diskStats().percent / 100
|
||||
}}
|
||||
/>
|
||||
</Show>
|
||||
@@ -1210,7 +1212,7 @@ const HostRow: Component<HostRowProps> = (props) => {
|
||||
<Show when={props.isColVisible('temp')}>
|
||||
<td class="px-2 py-1 align-middle">
|
||||
<div class="flex justify-center">
|
||||
<HostTemperatureCell sensors={host.sensors} />
|
||||
<HostTemperatureCell sensors={props.host.sensors} />
|
||||
</div>
|
||||
</td>
|
||||
</Show>
|
||||
@@ -1219,9 +1221,9 @@ const HostRow: Component<HostRowProps> = (props) => {
|
||||
<Show when={props.isColVisible('uptime')}>
|
||||
<td class="px-2 py-1 align-middle">
|
||||
<div class="flex justify-center">
|
||||
<Show when={isOnline() && host.uptimeSeconds} fallback={<span class="text-xs text-gray-400">—</span>}>
|
||||
<Show when={isOnline() && props.host.uptimeSeconds} fallback={<span class="text-xs text-gray-400">—</span>}>
|
||||
<span class="text-xs text-gray-700 dark:text-gray-300 whitespace-nowrap">
|
||||
{formatUptime(host.uptimeSeconds!)}
|
||||
{formatUptime(props.host.uptimeSeconds!)}
|
||||
</span>
|
||||
</Show>
|
||||
</div>
|
||||
@@ -1232,9 +1234,9 @@ const HostRow: Component<HostRowProps> = (props) => {
|
||||
<Show when={props.isColVisible('agent')}>
|
||||
<td class="px-2 py-1 align-middle">
|
||||
<div class="flex justify-center">
|
||||
<Show when={host.agentVersion} fallback={<span class="text-xs text-gray-400">—</span>}>
|
||||
<Show when={props.host.agentVersion} fallback={<span class="text-xs text-gray-400">—</span>}>
|
||||
<span class="text-xs text-gray-700 dark:text-gray-300 whitespace-nowrap">
|
||||
{host.agentVersion}
|
||||
{props.host.agentVersion}
|
||||
</span>
|
||||
</Show>
|
||||
</div>
|
||||
@@ -1245,7 +1247,7 @@ const HostRow: Component<HostRowProps> = (props) => {
|
||||
<Show when={props.isColVisible('ip')}>
|
||||
<td class="px-2 py-1 align-middle">
|
||||
<div class="flex justify-center">
|
||||
<HostNetworkInfoCell networkInterfaces={host.networkInterfaces || []} />
|
||||
<HostNetworkInfoCell networkInterfaces={props.host.networkInterfaces || []} />
|
||||
</div>
|
||||
</td>
|
||||
</Show>
|
||||
@@ -1254,9 +1256,9 @@ const HostRow: Component<HostRowProps> = (props) => {
|
||||
<Show when={props.isColVisible('arch')}>
|
||||
<td class="px-2 py-1 align-middle">
|
||||
<div class="flex justify-center">
|
||||
<Show when={host.architecture} fallback={<span class="text-xs text-gray-400">—</span>}>
|
||||
<Show when={props.host.architecture} fallback={<span class="text-xs text-gray-400">—</span>}>
|
||||
<span class="text-[10px] text-gray-700 dark:text-gray-300 whitespace-nowrap">
|
||||
{host.architecture}
|
||||
{props.host.architecture}
|
||||
</span>
|
||||
</Show>
|
||||
</div>
|
||||
@@ -1267,12 +1269,12 @@ const HostRow: Component<HostRowProps> = (props) => {
|
||||
<Show when={props.isColVisible('kernel')}>
|
||||
<td class="px-2 py-1 align-middle">
|
||||
<div class="flex justify-center">
|
||||
<Show when={host.kernelVersion} fallback={<span class="text-xs text-gray-400">—</span>}>
|
||||
<Show when={props.host.kernelVersion} fallback={<span class="text-xs text-gray-400">—</span>}>
|
||||
<span
|
||||
class="text-[10px] text-gray-700 dark:text-gray-300 max-w-[100px] truncate"
|
||||
title={host.kernelVersion}
|
||||
title={props.host.kernelVersion}
|
||||
>
|
||||
{host.kernelVersion}
|
||||
{props.host.kernelVersion}
|
||||
</span>
|
||||
</Show>
|
||||
</div>
|
||||
@@ -1283,7 +1285,7 @@ const HostRow: Component<HostRowProps> = (props) => {
|
||||
<Show when={props.isColVisible('raid')}>
|
||||
<td class="px-2 py-1 align-middle">
|
||||
<div class="flex justify-center">
|
||||
<HostRAIDStatusCell raid={host.raid} />
|
||||
<HostRAIDStatusCell raid={props.host.raid} />
|
||||
</div>
|
||||
</td>
|
||||
</Show>
|
||||
@@ -1291,7 +1293,7 @@ const HostRow: Component<HostRowProps> = (props) => {
|
||||
|
||||
{/* URL editing popover - using shared component */}
|
||||
<UrlEditPopover
|
||||
isOpen={urlEdit.isEditing() && urlEdit.editingId() === host.id}
|
||||
isOpen={urlEdit.isEditing() && urlEdit.editingId() === props.host.id}
|
||||
value={urlEdit.editingValue()}
|
||||
position={urlEdit.position()}
|
||||
isSaving={urlEdit.isSaving()}
|
||||
|
||||
416
internal/ai/correlation/detector_coverage_test.go
Normal file
416
internal/ai/correlation/detector_coverage_test.go
Normal file
@@ -0,0 +1,416 @@
|
||||
package correlation
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNewDetector_LoadsFromDisk(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
now := time.Now()
|
||||
data := struct {
|
||||
Events []Event `json:"events"`
|
||||
Correlations map[string]*Correlation `json:"correlations"`
|
||||
}{
|
||||
Events: []Event{
|
||||
{
|
||||
ID: "event-1",
|
||||
ResourceID: "node-1",
|
||||
EventType: EventHighCPU,
|
||||
Timestamp: now,
|
||||
},
|
||||
},
|
||||
Correlations: map[string]*Correlation{
|
||||
"node-1:vm-1:high_cpu -> restart": {
|
||||
SourceID: "node-1",
|
||||
SourceType: "node",
|
||||
TargetID: "vm-1",
|
||||
TargetType: "vm",
|
||||
EventPattern: "high_cpu -> restart",
|
||||
Occurrences: 2,
|
||||
AvgDelay: 2 * time.Minute,
|
||||
Confidence: 0.4,
|
||||
LastSeen: now,
|
||||
},
|
||||
},
|
||||
}
|
||||
jsonData, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal data: %v", err)
|
||||
}
|
||||
path := filepath.Join(tmpDir, "ai_correlations.json")
|
||||
if err := os.WriteFile(path, jsonData, 0600); err != nil {
|
||||
t.Fatalf("write data: %v", err)
|
||||
}
|
||||
|
||||
d := NewDetector(Config{
|
||||
MaxEvents: 100,
|
||||
CorrelationWindow: 10 * time.Minute,
|
||||
MinOccurrences: 1,
|
||||
RetentionWindow: 24 * time.Hour,
|
||||
DataDir: tmpDir,
|
||||
})
|
||||
if len(d.events) == 0 {
|
||||
t.Error("expected events loaded from disk")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDetector_LoadFromDiskError(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
path := filepath.Join(tmpDir, "ai_correlations.json")
|
||||
if err := os.WriteFile(path, []byte("{bad"), 0600); err != nil {
|
||||
t.Fatalf("write invalid data: %v", err)
|
||||
}
|
||||
|
||||
d := NewDetector(Config{DataDir: tmpDir})
|
||||
if len(d.events) != 0 {
|
||||
t.Error("expected empty events on load error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordEvent_AssignsDefaults(t *testing.T) {
|
||||
d := NewDetector(DefaultConfig())
|
||||
d.RecordEvent(Event{ResourceID: "vm-1", EventType: EventHighCPU})
|
||||
|
||||
if len(d.events) != 1 {
|
||||
t.Fatalf("expected 1 event, got %d", len(d.events))
|
||||
}
|
||||
if d.events[0].ID == "" {
|
||||
t.Error("expected event ID to be generated")
|
||||
}
|
||||
if d.events[0].Timestamp.IsZero() {
|
||||
t.Error("expected event timestamp to be set")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordEvent_SaveError(t *testing.T) {
|
||||
tmpFile, err := os.CreateTemp("", "correlation-dir")
|
||||
if err != nil {
|
||||
t.Fatalf("create temp file: %v", err)
|
||||
}
|
||||
path := tmpFile.Name()
|
||||
if err := tmpFile.Close(); err != nil {
|
||||
t.Fatalf("close temp file: %v", err)
|
||||
}
|
||||
defer os.Remove(path)
|
||||
|
||||
d := NewDetector(Config{DataDir: path})
|
||||
d.RecordEvent(Event{ResourceID: "vm-1", EventType: EventHighCPU})
|
||||
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
|
||||
func TestGetCorrelations_SortOrder(t *testing.T) {
|
||||
d := NewDetector(Config{MinOccurrences: 1})
|
||||
d.correlations["a"] = &Correlation{Occurrences: 2, Confidence: 0.4, EventPattern: "high_cpu -> restart"}
|
||||
d.correlations["b"] = &Correlation{Occurrences: 2, Confidence: 0.8, EventPattern: "high_mem -> restart"}
|
||||
|
||||
result := d.GetCorrelations()
|
||||
if len(result) != 2 {
|
||||
t.Fatalf("expected 2 correlations, got %d", len(result))
|
||||
}
|
||||
if result[0].Confidence < result[1].Confidence {
|
||||
t.Error("expected correlations sorted by confidence descending")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPredictCascade_FilterAndSort(t *testing.T) {
|
||||
d := NewDetector(Config{MinOccurrences: 1})
|
||||
d.correlations["a"] = &Correlation{
|
||||
SourceID: "node-1",
|
||||
TargetID: "vm-1",
|
||||
EventPattern: "high_cpu -> restart",
|
||||
Occurrences: 2,
|
||||
AvgDelay: time.Minute,
|
||||
Confidence: 0.6,
|
||||
}
|
||||
d.correlations["b"] = &Correlation{
|
||||
SourceID: "node-1",
|
||||
TargetID: "vm-2",
|
||||
EventPattern: "high_cpu -> restart",
|
||||
Occurrences: 2,
|
||||
AvgDelay: 2 * time.Minute,
|
||||
Confidence: 0.9,
|
||||
}
|
||||
d.correlations["c"] = &Correlation{
|
||||
SourceID: "node-1",
|
||||
TargetID: "vm-3",
|
||||
EventPattern: "high_mem -> restart",
|
||||
Occurrences: 2,
|
||||
AvgDelay: time.Minute,
|
||||
Confidence: 0.95,
|
||||
}
|
||||
|
||||
predictions := d.PredictCascade("node-1", EventHighCPU)
|
||||
if len(predictions) != 2 {
|
||||
t.Fatalf("expected 2 predictions, got %d", len(predictions))
|
||||
}
|
||||
if predictions[0].Confidence < predictions[1].Confidence {
|
||||
t.Error("expected predictions sorted by confidence descending")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatForContext_LimitsAndFallback(t *testing.T) {
|
||||
d := NewDetector(Config{MinOccurrences: 1})
|
||||
for i := 0; i < 12; i++ {
|
||||
desc := ""
|
||||
if i%2 == 0 {
|
||||
desc = "Observed pattern"
|
||||
}
|
||||
key := "k-" + intToStr(i)
|
||||
d.correlations[key] = &Correlation{
|
||||
SourceID: "node-1",
|
||||
TargetID: "vm-" + intToStr(i),
|
||||
EventPattern: "high_cpu -> restart",
|
||||
Occurrences: 2,
|
||||
Confidence: 0.3 + float64(i)*0.01,
|
||||
Description: desc,
|
||||
}
|
||||
}
|
||||
|
||||
result := d.FormatForContext("")
|
||||
if !strings.Contains(result, "... and more") {
|
||||
t.Error("expected context truncation indicator")
|
||||
}
|
||||
if !strings.Contains(result, "confidence") {
|
||||
t.Error("expected confidence fallback text")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveToDisk_EmptyDataDir(t *testing.T) {
|
||||
d := NewDetector(DefaultConfig())
|
||||
if err := d.saveToDisk(); err != nil {
|
||||
t.Fatalf("expected no error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveToDisk_MarshalError(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
d := NewDetector(Config{DataDir: tmpDir})
|
||||
d.events = append(d.events, Event{
|
||||
ID: "event-1",
|
||||
ResourceID: "node-1",
|
||||
EventType: EventHighCPU,
|
||||
Timestamp: time.Now(),
|
||||
Value: math.NaN(),
|
||||
})
|
||||
d.correlations["nil"] = nil
|
||||
|
||||
if err := d.saveToDisk(); err == nil {
|
||||
t.Fatal("expected marshal error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveToDisk_Success(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
d := NewDetector(Config{DataDir: tmpDir})
|
||||
d.events = append(d.events, Event{
|
||||
ID: "event-1",
|
||||
ResourceID: "node-1",
|
||||
EventType: EventHighCPU,
|
||||
Timestamp: time.Now(),
|
||||
Value: 1.0,
|
||||
})
|
||||
d.correlations["ok"] = &Correlation{
|
||||
SourceID: "node-1",
|
||||
TargetID: "vm-1",
|
||||
EventPattern: "high_cpu -> restart",
|
||||
Occurrences: 1,
|
||||
AvgDelay: time.Minute,
|
||||
Confidence: 0.4,
|
||||
LastSeen: time.Now(),
|
||||
}
|
||||
|
||||
if err := d.saveToDisk(); err != nil {
|
||||
t.Fatalf("expected saveToDisk to succeed: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(tmpDir, "ai_correlations.json")); err != nil {
|
||||
t.Fatalf("expected correlations file, got error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveToDisk_WriteError(t *testing.T) {
|
||||
tmpFile, err := os.CreateTemp("", "correlation-data")
|
||||
if err != nil {
|
||||
t.Fatalf("create temp file: %v", err)
|
||||
}
|
||||
path := tmpFile.Name()
|
||||
if err := tmpFile.Close(); err != nil {
|
||||
t.Fatalf("close temp file: %v", err)
|
||||
}
|
||||
defer os.Remove(path)
|
||||
|
||||
d := NewDetector(Config{DataDir: path})
|
||||
if err := d.saveToDisk(); err == nil {
|
||||
t.Fatal("expected write error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveToDisk_RenameError(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
path := filepath.Join(tmpDir, "ai_correlations.json")
|
||||
if err := os.Mkdir(path, 0700); err != nil {
|
||||
t.Fatalf("create dir: %v", err)
|
||||
}
|
||||
|
||||
d := NewDetector(Config{DataDir: tmpDir})
|
||||
if err := d.saveToDisk(); err == nil {
|
||||
t.Fatal("expected rename error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadFromDisk_EmptyDataDir(t *testing.T) {
|
||||
d := &Detector{}
|
||||
if err := d.loadFromDisk(); err != nil {
|
||||
t.Fatalf("expected no error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadFromDisk_TooLarge(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
path := filepath.Join(tmpDir, "ai_correlations.json")
|
||||
blob := make([]byte, (10<<20)+1)
|
||||
if err := os.WriteFile(path, blob, 0600); err != nil {
|
||||
t.Fatalf("write large file: %v", err)
|
||||
}
|
||||
|
||||
d := &Detector{dataDir: tmpDir}
|
||||
if err := d.loadFromDisk(); err == nil {
|
||||
t.Fatal("expected size error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadFromDisk_ReadError(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
path := filepath.Join(tmpDir, "ai_correlations.json")
|
||||
if err := os.Mkdir(path, 0700); err != nil {
|
||||
t.Fatalf("create dir: %v", err)
|
||||
}
|
||||
|
||||
d := &Detector{dataDir: tmpDir}
|
||||
if err := d.loadFromDisk(); err == nil {
|
||||
t.Fatal("expected read error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadFromDisk_InvalidJSON(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
path := filepath.Join(tmpDir, "ai_correlations.json")
|
||||
if err := os.WriteFile(path, []byte("{bad"), 0600); err != nil {
|
||||
t.Fatalf("write invalid json: %v", err)
|
||||
}
|
||||
|
||||
d := &Detector{dataDir: tmpDir}
|
||||
if err := d.loadFromDisk(); err == nil {
|
||||
t.Fatal("expected json parse error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadFromDisk_NullCorrelations(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
path := filepath.Join(tmpDir, "ai_correlations.json")
|
||||
payload := `{"events":[{"id":"event-1","resource_id":"node-1","event_type":"high_cpu","timestamp":"2024-01-01T00:00:00Z"}],"correlations":null}`
|
||||
if err := os.WriteFile(path, []byte(payload), 0600); err != nil {
|
||||
t.Fatalf("write json: %v", err)
|
||||
}
|
||||
|
||||
d := &Detector{
|
||||
dataDir: tmpDir,
|
||||
maxEvents: 100,
|
||||
retentionWindow: 24 * time.Hour,
|
||||
}
|
||||
if err := d.loadFromDisk(); err != nil {
|
||||
t.Fatalf("loadFromDisk failed: %v", err)
|
||||
}
|
||||
if d.correlations == nil {
|
||||
t.Fatal("expected correlations map to be initialized")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadFromDisk_NotExist(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
d := &Detector{dataDir: tmpDir}
|
||||
if err := d.loadFromDisk(); err != nil {
|
||||
t.Fatalf("expected no error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadFromDisk_PruneAndNormalize(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
now := time.Now()
|
||||
data := struct {
|
||||
Events []Event `json:"events"`
|
||||
Correlations map[string]*Correlation `json:"correlations"`
|
||||
}{
|
||||
Events: []Event{
|
||||
{
|
||||
ID: "old",
|
||||
ResourceID: "node-1",
|
||||
EventType: EventHighCPU,
|
||||
Timestamp: now.Add(-2 * time.Hour),
|
||||
},
|
||||
{
|
||||
ID: "new",
|
||||
ResourceID: "node-1",
|
||||
EventType: EventHighCPU,
|
||||
Timestamp: now,
|
||||
},
|
||||
},
|
||||
Correlations: map[string]*Correlation{
|
||||
"old": {
|
||||
SourceID: "node-1",
|
||||
TargetID: "vm-1",
|
||||
EventPattern: "high_cpu -> restart",
|
||||
Occurrences: 1,
|
||||
Confidence: 0.4,
|
||||
LastSeen: now.Add(-2 * time.Hour),
|
||||
},
|
||||
"nil": nil,
|
||||
"new": {
|
||||
SourceID: "node-1",
|
||||
TargetID: "vm-2",
|
||||
EventPattern: "high_cpu -> restart",
|
||||
Occurrences: 1,
|
||||
Confidence: 0.4,
|
||||
LastSeen: now,
|
||||
},
|
||||
},
|
||||
}
|
||||
jsonData, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal data: %v", err)
|
||||
}
|
||||
path := filepath.Join(tmpDir, "ai_correlations.json")
|
||||
if err := os.WriteFile(path, jsonData, 0600); err != nil {
|
||||
t.Fatalf("write data: %v", err)
|
||||
}
|
||||
|
||||
d := &Detector{
|
||||
dataDir: tmpDir,
|
||||
maxEvents: 100,
|
||||
retentionWindow: time.Hour,
|
||||
}
|
||||
if err := d.loadFromDisk(); err != nil {
|
||||
t.Fatalf("loadFromDisk failed: %v", err)
|
||||
}
|
||||
if d.correlations == nil {
|
||||
t.Fatal("expected correlations map to be initialized")
|
||||
}
|
||||
if _, ok := d.correlations["old"]; ok {
|
||||
t.Error("expected old correlation to be pruned")
|
||||
}
|
||||
if _, ok := d.correlations["nil"]; ok {
|
||||
t.Error("expected nil correlation to be pruned")
|
||||
}
|
||||
if _, ok := d.correlations["new"]; !ok {
|
||||
t.Error("expected recent correlation to remain")
|
||||
}
|
||||
if len(d.events) != 1 {
|
||||
t.Errorf("expected 1 recent event, got %d", len(d.events))
|
||||
}
|
||||
}
|
||||
363
internal/ai/cost/coverage_test.go
Normal file
363
internal/ai/cost/coverage_test.go
Normal file
@@ -0,0 +1,363 @@
|
||||
package cost
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type savePersistence struct {
|
||||
saveCh chan []UsageEvent
|
||||
loadErr error
|
||||
saveErr error
|
||||
}
|
||||
|
||||
func (p *savePersistence) LoadUsageHistory() ([]UsageEvent, error) {
|
||||
if p.loadErr != nil {
|
||||
return nil, p.loadErr
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (p *savePersistence) SaveUsageHistory(events []UsageEvent) error {
|
||||
if p.saveCh != nil {
|
||||
p.saveCh <- events
|
||||
}
|
||||
return p.saveErr
|
||||
}
|
||||
|
||||
func TestNormalizeModelForProvider(t *testing.T) {
|
||||
model := normalizeModelForProvider("openai", "openai:gpt-4o", "")
|
||||
if model != "gpt-4o" {
|
||||
t.Fatalf("expected gpt-4o, got %q", model)
|
||||
}
|
||||
|
||||
model = normalizeModelForProvider("openai", "anthropic:claude", "")
|
||||
if model != "anthropic:claude" {
|
||||
t.Fatalf("expected request model passthrough, got %q", model)
|
||||
}
|
||||
|
||||
model = normalizeModelForProvider("openai", "", "openai:gpt-4o")
|
||||
if model != "gpt-4o" {
|
||||
t.Fatalf("expected gpt-4o from response model, got %q", model)
|
||||
}
|
||||
|
||||
model = normalizeModelForProvider("openai", "", "anthropic:claude")
|
||||
if model != "anthropic:claude" {
|
||||
t.Fatalf("expected response model passthrough, got %q", model)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLookupPriceAndPatterns(t *testing.T) {
|
||||
if _, ok := lookupPrice("", "gpt-4o"); ok {
|
||||
t.Fatal("expected empty provider to be unknown")
|
||||
}
|
||||
if _, ok := lookupPrice("openai", ""); ok {
|
||||
t.Fatal("expected empty model to be unknown")
|
||||
}
|
||||
if _, ok := lookupPrice("unknown", "model"); ok {
|
||||
t.Fatal("expected unknown provider to be unknown")
|
||||
}
|
||||
|
||||
price, ok := lookupPrice("openai", "gpt-4o-mini")
|
||||
if !ok || price.InputUSDPerMTok == 0 {
|
||||
t.Fatalf("expected openai pricing match, got ok=%v price=%+v", ok, price)
|
||||
}
|
||||
|
||||
if !matchPattern("gpt-4o-mini", "gpt-4o*") {
|
||||
t.Fatal("expected prefix pattern to match")
|
||||
}
|
||||
if !matchPattern("anything", "*") {
|
||||
t.Fatal("expected wildcard pattern to match")
|
||||
}
|
||||
if matchPattern("gpt-4o-mini", "gpt-4o") {
|
||||
t.Fatal("expected exact match to fail")
|
||||
}
|
||||
if !matchPattern("gpt-4o", "gpt-4o") {
|
||||
t.Fatal("expected exact match to succeed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetPersistence_LoadError(t *testing.T) {
|
||||
store := NewStore(30)
|
||||
mock := &savePersistence{loadErr: errors.New("load failed")}
|
||||
if err := store.SetPersistence(mock); err == nil {
|
||||
t.Fatal("expected load error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecord_SetsTimestampAndTrims(t *testing.T) {
|
||||
store := NewStore(1)
|
||||
store.Record(UsageEvent{
|
||||
Provider: "openai",
|
||||
RequestModel: "openai:gpt-4o",
|
||||
InputTokens: 10,
|
||||
OutputTokens: 5,
|
||||
})
|
||||
if store.events[0].Timestamp.IsZero() {
|
||||
t.Fatal("expected timestamp to be set")
|
||||
}
|
||||
|
||||
old := time.Now().Add(-72 * time.Hour)
|
||||
store.Record(UsageEvent{
|
||||
Timestamp: old,
|
||||
Provider: "openai",
|
||||
RequestModel: "openai:gpt-4o",
|
||||
})
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
for _, e := range store.events {
|
||||
if e.Timestamp.Before(time.Now().Add(-48 * time.Hour)) {
|
||||
t.Fatal("expected old events to be trimmed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrimLocked_NoRetention(t *testing.T) {
|
||||
store := NewStore(1)
|
||||
store.maxDays = 0
|
||||
store.events = []UsageEvent{{Timestamp: time.Now().Add(-365 * 24 * time.Hour)}}
|
||||
store.trimLocked(time.Now())
|
||||
if len(store.events) != 1 {
|
||||
t.Fatalf("expected events preserved, got %d", len(store.events))
|
||||
}
|
||||
}
|
||||
|
||||
func TestListEvents_DefaultAndMaxDays(t *testing.T) {
|
||||
store := NewStore(7)
|
||||
now := time.Now()
|
||||
store.Record(UsageEvent{
|
||||
Timestamp: now.Add(-8 * 24 * time.Hour),
|
||||
Provider: "openai",
|
||||
RequestModel: "openai:gpt-4o",
|
||||
})
|
||||
|
||||
events := store.ListEvents(0)
|
||||
if len(events) != 0 {
|
||||
t.Fatalf("expected no events with maxDays cutoff, got %d", len(events))
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetSummary_UnknownPricing(t *testing.T) {
|
||||
store := NewStore(30)
|
||||
store.Record(UsageEvent{
|
||||
Timestamp: time.Now(),
|
||||
Provider: "unknown",
|
||||
RequestModel: "mystery-model",
|
||||
InputTokens: 100,
|
||||
OutputTokens: 50,
|
||||
})
|
||||
|
||||
summary := store.GetSummary(7)
|
||||
if summary.Totals.PricingKnown {
|
||||
t.Fatal("expected pricing to be unknown")
|
||||
}
|
||||
if summary.Totals.EstimatedUSD != 0 {
|
||||
t.Fatalf("expected zero USD, got %f", summary.Totals.EstimatedUSD)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetSummary_DefaultDays(t *testing.T) {
|
||||
store := NewStore(30)
|
||||
summary := store.GetSummary(0)
|
||||
if summary.Days != 30 {
|
||||
t.Fatalf("expected default days=30, got %d", summary.Days)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScheduleSaveLocked_DebounceAndCancel(t *testing.T) {
|
||||
store := NewStore(30)
|
||||
store.saveDebounce = 20 * time.Millisecond
|
||||
|
||||
saveCh := make(chan []UsageEvent, 1)
|
||||
store.persistence = &savePersistence{saveCh: saveCh}
|
||||
|
||||
store.mu.Lock()
|
||||
store.scheduleSaveLocked()
|
||||
store.mu.Unlock()
|
||||
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
store.mu.Lock()
|
||||
store.savePending = false
|
||||
store.mu.Unlock()
|
||||
|
||||
select {
|
||||
case <-saveCh:
|
||||
t.Fatal("expected no save when pending cleared")
|
||||
case <-time.After(40 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
|
||||
func TestScheduleSaveLocked_StopTimer(t *testing.T) {
|
||||
store := NewStore(30)
|
||||
store.saveDebounce = 20 * time.Millisecond
|
||||
store.persistence = &savePersistence{}
|
||||
|
||||
store.mu.Lock()
|
||||
store.scheduleSaveLocked()
|
||||
store.mu.Unlock()
|
||||
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
|
||||
store.mu.Lock()
|
||||
store.scheduleSaveLocked()
|
||||
store.mu.Unlock()
|
||||
}
|
||||
|
||||
func TestScheduleSaveLocked_LogsError(t *testing.T) {
|
||||
store := NewStore(30)
|
||||
store.saveDebounce = 5 * time.Millisecond
|
||||
store.persistence = &savePersistence{saveErr: errors.New("save failed")}
|
||||
|
||||
store.Record(UsageEvent{
|
||||
Timestamp: time.Now(),
|
||||
Provider: "openai",
|
||||
RequestModel: "openai:gpt-4o",
|
||||
})
|
||||
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
|
||||
func TestScheduleSaveLocked_Saves(t *testing.T) {
|
||||
store := NewStore(30)
|
||||
store.saveDebounce = 5 * time.Millisecond
|
||||
saveCh := make(chan []UsageEvent, 1)
|
||||
store.persistence = &savePersistence{saveCh: saveCh}
|
||||
|
||||
store.Record(UsageEvent{
|
||||
Timestamp: time.Now(),
|
||||
Provider: "openai",
|
||||
RequestModel: "openai:gpt-4o",
|
||||
})
|
||||
|
||||
select {
|
||||
case <-saveCh:
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
t.Fatal("expected save to fire")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlush_ReturnsPersistenceError(t *testing.T) {
|
||||
store := NewStore(30)
|
||||
store.persistence = &savePersistence{saveErr: errors.New("save failed")}
|
||||
store.Record(UsageEvent{
|
||||
Timestamp: time.Now(),
|
||||
Provider: "openai",
|
||||
RequestModel: "openai:gpt-4o",
|
||||
})
|
||||
if err := store.Flush(); err == nil {
|
||||
t.Fatal("expected flush error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSummarizeUseCases_OrderAndUnknown(t *testing.T) {
|
||||
events := []UsageEvent{
|
||||
{UseCase: "", InputTokens: 1},
|
||||
{UseCase: "patrol", InputTokens: 1},
|
||||
{UseCase: "chat", InputTokens: 1},
|
||||
{UseCase: "custom", InputTokens: 1},
|
||||
{UseCase: "alpha", InputTokens: 1},
|
||||
}
|
||||
rollup := summarizeUseCases(events)
|
||||
|
||||
if len(rollup) != 5 {
|
||||
t.Fatalf("expected 5 use cases, got %d", len(rollup))
|
||||
}
|
||||
|
||||
names := make([]string, 0, len(rollup))
|
||||
for _, uc := range rollup {
|
||||
names = append(names, uc.UseCase)
|
||||
}
|
||||
if names[0] != "chat" || names[1] != "patrol" || names[2] != "unknown" {
|
||||
t.Fatalf("unexpected order: %v", names)
|
||||
}
|
||||
if names[3] != "alpha" || names[4] != "custom" {
|
||||
t.Fatalf("expected alpha/custom ordering at end, got %v", names)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSummarizeTargets_SortAndLimit(t *testing.T) {
|
||||
var events []UsageEvent
|
||||
for i := 0; i < 25; i++ {
|
||||
events = append(events, UsageEvent{
|
||||
Provider: "ollama",
|
||||
RequestModel: "llama3",
|
||||
InputTokens: 100 + i,
|
||||
OutputTokens: 10,
|
||||
TargetType: "vm",
|
||||
TargetID: "id-" + string(rune('a'+i)),
|
||||
})
|
||||
}
|
||||
events = append(events, UsageEvent{
|
||||
Provider: "openai",
|
||||
RequestModel: "openai:gpt-4o",
|
||||
InputTokens: 1000,
|
||||
OutputTokens: 100,
|
||||
TargetType: "node",
|
||||
TargetID: "node-1",
|
||||
})
|
||||
events = append(events, UsageEvent{
|
||||
Provider: "openai",
|
||||
RequestModel: "openai:gpt-4o",
|
||||
InputTokens: 1000,
|
||||
OutputTokens: 100,
|
||||
TargetType: "",
|
||||
TargetID: "skip",
|
||||
})
|
||||
events = append(events, UsageEvent{
|
||||
Provider: "openai",
|
||||
RequestModel: "openai:gpt-4o",
|
||||
InputTokens: 1000,
|
||||
OutputTokens: 100,
|
||||
TargetType: "node",
|
||||
TargetID: "",
|
||||
})
|
||||
|
||||
rollup := summarizeTargets(events)
|
||||
if len(rollup) != 20 {
|
||||
t.Fatalf("expected 20 targets after limit, got %d", len(rollup))
|
||||
}
|
||||
if rollup[0].TargetID != "node-1" || rollup[0].TargetType != "node" {
|
||||
t.Fatalf("expected highest cost target first, got %+v", rollup[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSummarizeTargets_SortTiebreakers(t *testing.T) {
|
||||
events := []UsageEvent{
|
||||
{
|
||||
Provider: "ollama",
|
||||
RequestModel: "llama3",
|
||||
InputTokens: 100,
|
||||
OutputTokens: 10,
|
||||
TargetType: "vm",
|
||||
TargetID: "b",
|
||||
},
|
||||
{
|
||||
Provider: "ollama",
|
||||
RequestModel: "llama3",
|
||||
InputTokens: 100,
|
||||
OutputTokens: 10,
|
||||
TargetType: "node",
|
||||
TargetID: "a",
|
||||
},
|
||||
{
|
||||
Provider: "ollama",
|
||||
RequestModel: "llama3",
|
||||
InputTokens: 100,
|
||||
OutputTokens: 10,
|
||||
TargetType: "vm",
|
||||
TargetID: "a",
|
||||
},
|
||||
}
|
||||
|
||||
rollup := summarizeTargets(events)
|
||||
if len(rollup) != 3 {
|
||||
t.Fatalf("expected 3 targets, got %d", len(rollup))
|
||||
}
|
||||
if rollup[0].TargetType != "node" {
|
||||
t.Fatalf("expected node target first, got %+v", rollup[0])
|
||||
}
|
||||
if rollup[1].TargetID != "a" || rollup[2].TargetID != "b" {
|
||||
t.Fatalf("expected target ID ordering, got %+v", rollup)
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,9 @@ type Store struct {
|
||||
crypto *crypto.CryptoManager
|
||||
}
|
||||
|
||||
var newCryptoManagerAt = crypto.NewCryptoManagerAt
|
||||
var beforeKnowledgeWriteLock func()
|
||||
|
||||
// NewStore creates a new knowledge store with encryption
|
||||
func NewStore(dataDir string) (*Store, error) {
|
||||
knowledgeDir := filepath.Join(dataDir, "knowledge")
|
||||
@@ -49,7 +52,7 @@ func NewStore(dataDir string) (*Store, error) {
|
||||
}
|
||||
|
||||
// Initialize crypto manager for encryption (uses same key as other Pulse secrets)
|
||||
cryptoMgr, err := crypto.NewCryptoManagerAt(dataDir)
|
||||
cryptoMgr, err := newCryptoManagerAt(dataDir)
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Msg("Failed to initialize crypto for knowledge store, data will be unencrypted")
|
||||
}
|
||||
@@ -82,6 +85,9 @@ func (s *Store) GetKnowledge(guestID string) (*GuestKnowledge, error) {
|
||||
s.mu.RUnlock()
|
||||
|
||||
// Load from disk
|
||||
if beforeKnowledgeWriteLock != nil {
|
||||
beforeKnowledgeWriteLock()
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
@@ -486,4 +492,3 @@ finalize:
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
|
||||
696
internal/ai/knowledge/store_coverage_test.go
Normal file
696
internal/ai/knowledge/store_coverage_test.go
Normal file
@@ -0,0 +1,696 @@
|
||||
package knowledge
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rcourtman/pulse-go-rewrite/internal/crypto"
|
||||
)
|
||||
|
||||
func TestNewStore_FilePathError(t *testing.T) {
|
||||
tmpFile, err := os.CreateTemp("", "knowledge-file")
|
||||
if err != nil {
|
||||
t.Fatalf("create temp file: %v", err)
|
||||
}
|
||||
path := tmpFile.Name()
|
||||
if err := tmpFile.Close(); err != nil {
|
||||
t.Fatalf("close temp file: %v", err)
|
||||
}
|
||||
defer os.Remove(path)
|
||||
|
||||
store, err := NewStore(path)
|
||||
if err == nil || store != nil {
|
||||
t.Fatal("expected error when dataDir is a file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewStore_CryptoInitFailure(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
orig := newCryptoManagerAt
|
||||
newCryptoManagerAt = func(string) (*crypto.CryptoManager, error) {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
defer func() {
|
||||
newCryptoManagerAt = orig
|
||||
}()
|
||||
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("expected store creation to succeed: %v", err)
|
||||
}
|
||||
if store.crypto != nil {
|
||||
t.Error("expected crypto manager to be nil after init failure")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuestFilePath_Extensions(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
if store.crypto == nil {
|
||||
cryptoMgr, err := crypto.NewCryptoManagerAt(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create crypto manager: %v", err)
|
||||
}
|
||||
store.crypto = cryptoMgr
|
||||
}
|
||||
|
||||
encPath := store.guestFilePath("guest-1")
|
||||
if !strings.HasSuffix(encPath, ".enc") {
|
||||
t.Errorf("expected encrypted path, got %q", encPath)
|
||||
}
|
||||
|
||||
store.crypto = nil
|
||||
jsonPath := store.guestFilePath("guest-1")
|
||||
if !strings.HasSuffix(jsonPath, ".json") {
|
||||
t.Errorf("expected json path, got %q", jsonPath)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetKnowledge_LegacyFallback(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
if store.crypto == nil {
|
||||
cryptoMgr, err := crypto.NewCryptoManagerAt(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create crypto manager: %v", err)
|
||||
}
|
||||
store.crypto = cryptoMgr
|
||||
}
|
||||
|
||||
guestID := "legacy-guest"
|
||||
knowledge := GuestKnowledge{
|
||||
GuestID: guestID,
|
||||
GuestName: "Legacy",
|
||||
Notes: []Note{
|
||||
{ID: "note-1", Category: "service", Title: "svc", Content: "value"},
|
||||
},
|
||||
}
|
||||
data, err := json.Marshal(knowledge)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal knowledge: %v", err)
|
||||
}
|
||||
legacyPath := filepath.Join(store.dataDir, filepath.Base(guestID)+".json")
|
||||
if err := os.WriteFile(legacyPath, data, 0600); err != nil {
|
||||
t.Fatalf("write legacy file: %v", err)
|
||||
}
|
||||
|
||||
loaded, err := store.GetKnowledge(guestID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetKnowledge failed: %v", err)
|
||||
}
|
||||
if loaded.GuestName != "Legacy" {
|
||||
t.Errorf("expected legacy guest name, got %q", loaded.GuestName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetKnowledge_DecryptFallback(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
if store.crypto == nil {
|
||||
cryptoMgr, err := crypto.NewCryptoManagerAt(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create crypto manager: %v", err)
|
||||
}
|
||||
store.crypto = cryptoMgr
|
||||
}
|
||||
|
||||
guestID := "plain-enc"
|
||||
knowledge := GuestKnowledge{
|
||||
GuestID: guestID,
|
||||
Notes: []Note{
|
||||
{ID: "note-1", Category: "service", Title: "svc", Content: "value"},
|
||||
},
|
||||
}
|
||||
data, err := json.Marshal(knowledge)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal knowledge: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(store.guestFilePath(guestID), data, 0600); err != nil {
|
||||
t.Fatalf("write plain enc file: %v", err)
|
||||
}
|
||||
|
||||
loaded, err := store.GetKnowledge(guestID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetKnowledge failed: %v", err)
|
||||
}
|
||||
if len(loaded.Notes) != 1 {
|
||||
t.Errorf("expected 1 note, got %d", len(loaded.Notes))
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetKnowledge_DecryptSuccess(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
if store.crypto == nil {
|
||||
t.Skip("crypto manager unavailable")
|
||||
}
|
||||
|
||||
guestID := "encrypted-guest"
|
||||
knowledge := GuestKnowledge{
|
||||
GuestID: guestID,
|
||||
Notes: []Note{
|
||||
{ID: "note-1", Category: "service", Title: "svc", Content: "value"},
|
||||
},
|
||||
}
|
||||
plain, err := json.Marshal(knowledge)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal knowledge: %v", err)
|
||||
}
|
||||
encrypted, err := store.crypto.Encrypt(plain)
|
||||
if err != nil {
|
||||
t.Fatalf("encrypt knowledge: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(store.guestFilePath(guestID), encrypted, 0600); err != nil {
|
||||
t.Fatalf("write enc file: %v", err)
|
||||
}
|
||||
|
||||
loaded, err := store.GetKnowledge(guestID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetKnowledge failed: %v", err)
|
||||
}
|
||||
if len(loaded.Notes) != 1 {
|
||||
t.Errorf("expected 1 note, got %d", len(loaded.Notes))
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetKnowledge_DecryptParseError(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
if store.crypto == nil {
|
||||
t.Skip("crypto manager unavailable")
|
||||
}
|
||||
|
||||
guestID := "bad-enc-json"
|
||||
encrypted, err := store.crypto.Encrypt([]byte("{bad"))
|
||||
if err != nil {
|
||||
t.Fatalf("encrypt data: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(store.guestFilePath(guestID), encrypted, 0600); err != nil {
|
||||
t.Fatalf("write enc file: %v", err)
|
||||
}
|
||||
|
||||
if _, err := store.GetKnowledge(guestID); err == nil {
|
||||
t.Fatal("expected parse error after decrypt")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetKnowledge_DoubleCheckCache(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
store.crypto = nil
|
||||
|
||||
guestID := "cached-guest"
|
||||
expected := &GuestKnowledge{GuestID: guestID, Notes: []Note{{ID: "note-1"}}}
|
||||
|
||||
orig := beforeKnowledgeWriteLock
|
||||
beforeKnowledgeWriteLock = func() {
|
||||
store.mu.Lock()
|
||||
store.cache[guestID] = expected
|
||||
store.mu.Unlock()
|
||||
}
|
||||
defer func() {
|
||||
beforeKnowledgeWriteLock = orig
|
||||
}()
|
||||
|
||||
loaded, err := store.GetKnowledge(guestID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetKnowledge failed: %v", err)
|
||||
}
|
||||
if loaded != expected {
|
||||
t.Error("expected cached knowledge to be returned from double-check")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetKnowledge_LegacyReadError(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
if store.crypto == nil {
|
||||
t.Skip("crypto manager unavailable")
|
||||
}
|
||||
|
||||
guestID := "legacy-error"
|
||||
legacyPath := filepath.Join(store.dataDir, filepath.Base(guestID)+".json")
|
||||
if err := os.Mkdir(legacyPath, 0700); err != nil {
|
||||
t.Fatalf("create legacy dir: %v", err)
|
||||
}
|
||||
|
||||
if _, err := store.GetKnowledge(guestID); err == nil {
|
||||
t.Fatal("expected legacy read error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetKnowledge_DecryptError(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
if store.crypto == nil {
|
||||
cryptoMgr, err := crypto.NewCryptoManagerAt(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create crypto manager: %v", err)
|
||||
}
|
||||
store.crypto = cryptoMgr
|
||||
}
|
||||
|
||||
guestID := "bad-enc"
|
||||
if err := os.WriteFile(store.guestFilePath(guestID), []byte("not-json"), 0600); err != nil {
|
||||
t.Fatalf("write enc file: %v", err)
|
||||
}
|
||||
|
||||
if _, err := store.GetKnowledge(guestID); err == nil {
|
||||
t.Fatal("expected decrypt error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetKnowledge_ParseError(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
store.crypto = nil
|
||||
|
||||
guestID := "bad-json"
|
||||
if err := os.WriteFile(store.guestFilePath(guestID), []byte("{bad"), 0600); err != nil {
|
||||
t.Fatalf("write json file: %v", err)
|
||||
}
|
||||
|
||||
if _, err := store.GetKnowledge(guestID); err == nil {
|
||||
t.Fatal("expected parse error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetKnowledge_ReadError(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
store.crypto = nil
|
||||
|
||||
guestID := "dir-guest"
|
||||
path := store.guestFilePath(guestID)
|
||||
if err := os.Mkdir(path, 0700); err != nil {
|
||||
t.Fatalf("create dir at file path: %v", err)
|
||||
}
|
||||
|
||||
if _, err := store.GetKnowledge(guestID); err == nil {
|
||||
t.Fatal("expected read error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveNote_LoadExistingInvalid(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
store.crypto = nil
|
||||
|
||||
guestID := "existing-guest"
|
||||
if err := os.WriteFile(store.guestFilePath(guestID), []byte("{bad"), 0600); err != nil {
|
||||
t.Fatalf("write invalid file: %v", err)
|
||||
}
|
||||
|
||||
if err := store.SaveNote(guestID, "Guest", "vm", "service", "Web", "nginx"); err != nil {
|
||||
t.Fatalf("SaveNote failed: %v", err)
|
||||
}
|
||||
knowledge, err := store.GetKnowledge(guestID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetKnowledge failed: %v", err)
|
||||
}
|
||||
if len(knowledge.Notes) != 1 {
|
||||
t.Errorf("expected 1 note, got %d", len(knowledge.Notes))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveNote_LoadEncryptedExisting(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
if store.crypto == nil {
|
||||
t.Skip("crypto manager unavailable")
|
||||
}
|
||||
|
||||
guestID := "encrypted-existing"
|
||||
existing := GuestKnowledge{
|
||||
GuestID: guestID,
|
||||
GuestName: "Guest",
|
||||
GuestType: "vm",
|
||||
Notes: []Note{
|
||||
{ID: "note-1", Category: "service", Title: "Web", Content: "apache"},
|
||||
},
|
||||
}
|
||||
plain, err := json.Marshal(existing)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal knowledge: %v", err)
|
||||
}
|
||||
encrypted, err := store.crypto.Encrypt(plain)
|
||||
if err != nil {
|
||||
t.Fatalf("encrypt knowledge: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(store.guestFilePath(guestID), encrypted, 0600); err != nil {
|
||||
t.Fatalf("write enc file: %v", err)
|
||||
}
|
||||
|
||||
if err := store.SaveNote(guestID, "", "", "service", "Web", "nginx"); err != nil {
|
||||
t.Fatalf("SaveNote failed: %v", err)
|
||||
}
|
||||
knowledge, err := store.GetKnowledge(guestID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetKnowledge failed: %v", err)
|
||||
}
|
||||
if len(knowledge.Notes) != 1 {
|
||||
t.Errorf("expected 1 note, got %d", len(knowledge.Notes))
|
||||
}
|
||||
if knowledge.Notes[0].Content != "nginx" {
|
||||
t.Errorf("expected updated content, got %q", knowledge.Notes[0].Content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteNote_NotFound(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
store.crypto = nil
|
||||
|
||||
if err := store.SaveNote("guest", "Guest", "vm", "service", "Web", "nginx"); err != nil {
|
||||
t.Fatalf("SaveNote failed: %v", err)
|
||||
}
|
||||
if err := store.DeleteNote("guest", "missing"); err == nil {
|
||||
t.Fatal("expected note not found error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetNotesByCategory_All(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
store.crypto = nil
|
||||
|
||||
store.SaveNote("guest", "Guest", "vm", "service", "Web", "nginx")
|
||||
store.SaveNote("guest", "Guest", "vm", "config", "DB", "postgres")
|
||||
|
||||
notes, err := store.GetNotesByCategory("guest", "")
|
||||
if err != nil {
|
||||
t.Fatalf("GetNotesByCategory failed: %v", err)
|
||||
}
|
||||
if len(notes) != 2 {
|
||||
t.Errorf("expected 2 notes, got %d", len(notes))
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetNotesByCategory_Error(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
store.crypto = nil
|
||||
|
||||
guestID := "bad-category"
|
||||
if err := os.WriteFile(store.guestFilePath(guestID), []byte("{bad"), 0600); err != nil {
|
||||
t.Fatalf("write invalid file: %v", err)
|
||||
}
|
||||
|
||||
if _, err := store.GetNotesByCategory(guestID, "service"); err == nil {
|
||||
t.Fatal("expected GetNotesByCategory error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatForContext_Error(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
store.crypto = nil
|
||||
|
||||
guestID := "bad-context"
|
||||
if err := os.WriteFile(store.guestFilePath(guestID), []byte("{bad"), 0600); err != nil {
|
||||
t.Fatalf("write invalid file: %v", err)
|
||||
}
|
||||
|
||||
if result := store.FormatForContext(guestID); result != "" {
|
||||
t.Errorf("expected empty result, got %q", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveToFile_MarshalError(t *testing.T) {
|
||||
store := &Store{
|
||||
dataDir: t.TempDir(),
|
||||
cache: make(map[string]*GuestKnowledge),
|
||||
}
|
||||
|
||||
badTime := time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
knowledge := &GuestKnowledge{
|
||||
GuestID: "guest",
|
||||
UpdatedAt: badTime,
|
||||
Notes: []Note{
|
||||
{
|
||||
ID: "note-1",
|
||||
Category: "service",
|
||||
Title: "Web",
|
||||
Content: "nginx",
|
||||
CreatedAt: badTime,
|
||||
UpdatedAt: badTime,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if err := store.saveToFile("guest", knowledge); err == nil {
|
||||
t.Fatal("expected marshal error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveToFile_WriteError(t *testing.T) {
|
||||
tmpFile, err := os.CreateTemp("", "knowledge-data")
|
||||
if err != nil {
|
||||
t.Fatalf("create temp file: %v", err)
|
||||
}
|
||||
path := tmpFile.Name()
|
||||
if err := tmpFile.Close(); err != nil {
|
||||
t.Fatalf("close temp file: %v", err)
|
||||
}
|
||||
defer os.Remove(path)
|
||||
|
||||
store := &Store{
|
||||
dataDir: path,
|
||||
cache: make(map[string]*GuestKnowledge),
|
||||
}
|
||||
knowledge := &GuestKnowledge{GuestID: "guest"}
|
||||
|
||||
if err := store.saveToFile("guest", knowledge); err == nil {
|
||||
t.Fatal("expected write error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveToFile_RemovesLegacy(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
if store.crypto == nil {
|
||||
t.Skip("crypto manager unavailable")
|
||||
}
|
||||
|
||||
guestID := "legacy-remove"
|
||||
legacyPath := filepath.Join(store.dataDir, filepath.Base(guestID)+".json")
|
||||
if err := os.WriteFile(legacyPath, []byte(`{"guest_id":"legacy-remove","notes":[]}`), 0600); err != nil {
|
||||
t.Fatalf("write legacy file: %v", err)
|
||||
}
|
||||
|
||||
knowledge := &GuestKnowledge{GuestID: guestID}
|
||||
if err := store.saveToFile(guestID, knowledge); err != nil {
|
||||
t.Fatalf("saveToFile failed: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(legacyPath); err == nil {
|
||||
t.Fatal("expected legacy file to be removed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveToFile_EncryptError(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
if store.crypto == nil {
|
||||
t.Skip("crypto manager unavailable")
|
||||
}
|
||||
|
||||
keyPath := filepath.Join(tmpDir, ".encryption.key")
|
||||
if err := os.Remove(keyPath); err != nil {
|
||||
t.Fatalf("remove key: %v", err)
|
||||
}
|
||||
|
||||
knowledge := &GuestKnowledge{GuestID: "guest"}
|
||||
if err := store.saveToFile("guest", knowledge); err == nil {
|
||||
t.Fatal("expected encrypt error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestListGuests_ReadDirError(t *testing.T) {
|
||||
tmpFile, err := os.CreateTemp("", "knowledge-dir")
|
||||
if err != nil {
|
||||
t.Fatalf("create temp file: %v", err)
|
||||
}
|
||||
path := tmpFile.Name()
|
||||
if err := tmpFile.Close(); err != nil {
|
||||
t.Fatalf("close temp file: %v", err)
|
||||
}
|
||||
defer os.Remove(path)
|
||||
|
||||
store := &Store{
|
||||
dataDir: path,
|
||||
cache: make(map[string]*GuestKnowledge),
|
||||
}
|
||||
|
||||
if _, err := store.ListGuests(); err == nil {
|
||||
t.Fatal("expected read dir error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatAllForContext_ListError(t *testing.T) {
|
||||
tmpFile, err := os.CreateTemp("", "knowledge-dir")
|
||||
if err != nil {
|
||||
t.Fatalf("create temp file: %v", err)
|
||||
}
|
||||
path := tmpFile.Name()
|
||||
if err := tmpFile.Close(); err != nil {
|
||||
t.Fatalf("close temp file: %v", err)
|
||||
}
|
||||
defer os.Remove(path)
|
||||
|
||||
store := &Store{
|
||||
dataDir: path,
|
||||
cache: make(map[string]*GuestKnowledge),
|
||||
}
|
||||
|
||||
if result := store.FormatAllForContext(); result != "" {
|
||||
t.Errorf("expected empty result, got %q", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatAllForContext_NoNotes(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
store.crypto = nil
|
||||
|
||||
guestID := "empty-notes"
|
||||
knowledge := &GuestKnowledge{GuestID: guestID, Notes: []Note{}}
|
||||
data, err := json.Marshal(knowledge)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal knowledge: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(store.guestFilePath(guestID), data, 0600); err != nil {
|
||||
t.Fatalf("write file: %v", err)
|
||||
}
|
||||
|
||||
if result := store.FormatAllForContext(); result != "" {
|
||||
t.Errorf("expected empty result, got %q", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatAllForContext_NoTruncate(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
store.crypto = nil
|
||||
|
||||
store.SaveNote("guest-1", "", "vm", "service", "Web", "nginx")
|
||||
store.SaveNote("guest-2", "GuestTwo", "vm", "config", "DB", "postgres")
|
||||
|
||||
result := store.FormatAllForContext()
|
||||
if !strings.Contains(result, "notes across") {
|
||||
t.Errorf("expected non-truncated header, got %q", result)
|
||||
}
|
||||
if !strings.Contains(result, "guest-1") {
|
||||
t.Error("expected guest ID fallback when name is empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatAllForContext_CredentialMasking(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
store.crypto = nil
|
||||
|
||||
store.SaveNote("guest-1", "Guest", "vm", "credential", "Root", "password1234")
|
||||
result := store.FormatAllForContext()
|
||||
if !strings.Contains(result, "pa****34") {
|
||||
t.Errorf("expected masked credential, got %q", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatAllForContext_NoGuests(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
store.crypto = nil
|
||||
|
||||
if result := store.FormatAllForContext(); result != "" {
|
||||
t.Errorf("expected empty result, got %q", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatAllForContext_TooLargeFirstNote(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
store, err := NewStore(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create store: %v", err)
|
||||
}
|
||||
store.crypto = nil
|
||||
|
||||
largeContent := make([]byte, 9000)
|
||||
for i := range largeContent {
|
||||
largeContent[i] = 'x'
|
||||
}
|
||||
store.SaveNote("guest-1", "Guest", "vm", "service", "Big", string(largeContent))
|
||||
|
||||
if result := store.FormatAllForContext(); result != "" {
|
||||
t.Errorf("expected empty result for oversized first note, got %q", result)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user