package identity import ( "context" "net/http" "net/http/httptest" "testing" ) func TestParseASNOrg(t *testing.T) { cases := []struct { in string asn int org string }{ {"AS577 Bell Canada", 577, "Bell Canada"}, {"AS16276 OVH SAS", 16276, "OVH SAS"}, {"Bell Canada", 0, "Bell Canada"}, {"", 0, ""}, {"ASN Something", 0, "ASN Something"}, } for _, c := range cases { asn, org := ParseASNOrg(c.in) if asn != c.asn || org != c.org { t.Errorf("%q → %d %q, want %d %q", c.in, asn, org, c.asn, c.org) } } } func TestFallbackAndRounding(t *testing.T) { ipinfo := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "rate limited", 429) })) defer ipinfo.Close() ipapi := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`{"status":"success","country":"Canada","countryCode":"CA","city":"Québec","lat":46.812345,"lon":-71.214567,"as":"AS577 Bell Canada","org":"Bell Canada","query":"76.70.60.50"}`)) })) defer ipapi.Close() IPInfoURL, IPAPIURL = ipinfo.URL, ipapi.URL s := New("InternetPressureProbe/test") id, err := s.Refresh(context.Background()) if err != nil { t.Fatal(err) } if id.Source != "ip-api.com" || id.PublicIP != "76.70.60.50" || id.ASN != 577 || id.Country != "CA" || id.City != "Québec" { t.Fatalf("%+v", id) } if *id.Lat != 46.81 || *id.Lon != -71.21 { t.Fatalf("coordinates must be rounded to city level: %v %v", *id.Lat, *id.Lon) } if s.Current() != id { t.Fatal("current not stored") } } func TestIPInfo(t *testing.T) { ipinfo := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`{"ip":"51.161.112.61","city":"Beauharnois","region":"Quebec","country":"CA","loc":"45.3151,-73.8779","org":"AS16276 OVH SAS"}`)) })) defer ipinfo.Close() IPInfoURL = ipinfo.URL id, err := New("ua").Refresh(context.Background()) if err != nil { t.Fatal(err) } if id.Source != "ipinfo.io" || id.ASN != 16276 || id.Org != "OVH SAS" || *id.Lat != 45.32 || *id.Lon != -73.88 { t.Fatalf("%+v", id) } }