package resolver import ( "context" "net/http" "net/http/httptest" "net/url" "testing" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox" ) // NetBox ignores unknown filters, so the strategy must use the real filter // names; otherwise it silently returns the host's first address. func TestInterfaceNameStrategyFilters(t *testing.T) { for kind, want := range map[string]string{ "device": "device_id=7&interface=mgmt0", "vm": "virtual_machine_id=7&vminterface=mgmt0", } { var got string srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() q.Del("limit") q.Del("offset") got = q.Encode() w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{"count":1,"results":[{"address":"10.0.0.7/24"}]}`)) })) ip, err := (&InterfaceNameStrategy{name: "mgmt0"}).Resolve(context.Background(), &netbox.HostEntry{ID: 7, Kind: kind}, netbox.NewClient(srv.URL, "t", 1)) srv.Close() if err != nil || ip != "10.0.0.7" { t.Fatalf("%s: %q %v", kind, ip, err) } if parsed, _ := urlQuery(want); got != parsed { t.Errorf("%s: query %q, want %q", kind, got, parsed) } } } func TestInterfaceNameStrategyMissingInterfaceFallsThrough(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, `{"vminterface":["Select a valid choice."]}`, http.StatusBadRequest) })) defer srv.Close() client := netbox.NewClient(srv.URL, "t", 1) chain := &Chain{strategies: []Strategy{&InterfaceNameStrategy{name: "mgmt0"}, &PrimaryIPStrategy{}}} ip, err := chain.Resolve(context.Background(), &netbox.HostEntry{ID: 7, Kind: "vm", PrimaryIP4: "10.0.0.9"}, client) if err != nil || ip != "10.0.0.9" { t.Fatalf("got %q %v", ip, err) } } func urlQuery(s string) (string, error) { q, err := url.ParseQuery(s) return q.Encode(), err }