package infraview import ( "encoding/json" "testing" "time" ) // An inventory written before a field existed must still parse, and a kind // no reader knows must survive as itself rather than being dropped — the // repo's additive wire-shape rule applied to a bucket object. func TestInventoryParsesAdditively(t *testing.T) { old := []byte(`{ "provider":"aws","account":"1234","taken_at":"2026-08-19T10:00:00Z", "resources":[ {"provider":"aws","kind":"machine","native_type":"ec2:instance", "id":"i-123","name":"carlos-eu-west-1","region":"eu-west-1", "attrs":{"type":"t4g.medium","public_ip":"52.0.0.1"}}, {"provider":"aws","kind":"quantum_widget","native_type":"qc:widget","id":"q-1"} ], "future_field":"ignored" }`) var inv Inventory if err := json.Unmarshal(old, &inv); err != nil { t.Fatalf("parse: %v", err) } if inv.Provider != "aws" || inv.Account != "1234" { t.Fatalf("header: %+v", inv) } if !inv.TakenAt.Equal(time.Date(2026, 8, 19, 10, 0, 0, 0, time.UTC)) { t.Fatalf("taken_at: %v", inv.TakenAt) } if len(inv.Resources) != 2 { t.Fatalf("resources: %d, want 2 (an unknown kind must not be dropped)", len(inv.Resources)) } if got := inv.Resources[1].Kind; got != "quantum_widget" { t.Fatalf("unknown kind = %q, want it carried verbatim", got) } } func TestByKindAndFind(t *testing.T) { inv := Inventory{Resources: []Resource{ {Kind: KindMachine, ID: "i-1", Attrs: map[string]string{"public_ip": "52.0.0.1"}}, {Kind: KindMachine, ID: "i-2", Attrs: map[string]string{"public_ip": "52.0.0.2"}}, {Kind: KindBucket, ID: "carlos-data-ie"}, }} if got := len(inv.ByKind(KindMachine)); got != 2 { t.Fatalf("ByKind(machine) = %d, want 2", got) } if got := inv.Find(KindMachine, "public_ip", "52.0.0.2"); got == nil || got.ID != "i-2" { t.Fatalf("Find = %+v, want i-2", got) } if got := inv.Find(KindMachine, "public_ip", "10.0.0.9"); got != nil { t.Fatalf("Find(miss) = %+v, want nil", got) } } // A resource with no Attrs map must not panic any accessor — an inventory // read from an older writer is full of them. func TestFindNilAttrs(t *testing.T) { inv := Inventory{Resources: []Resource{{Kind: KindMachine, ID: "i-1"}}} if got := inv.Find(KindMachine, "public_ip", "52.0.0.1"); got != nil { t.Fatalf("Find over nil Attrs = %+v, want nil", got) } }