package app import ( "encoding/json" "fmt" "math" "testing" ) // The profile and chat headers label distance, so the single-profile endpoint // has to answer with the same reading the nearby list gives. func TestProfileDistanceMySQL(t *testing.T) { db := isolatedIMDatabase(t) a := &App{db: db, hub: NewHub(), config: Config{Environment: "development", JWTSecret: "isolated-im-regression-secret-only"}} // Shenzhen city centre and a point a few kilometres north of it. for _, seed := range []struct { user int64 lat, lng float64 }{{1, 22.5431, 114.0579}, {2, 22.5731, 114.0579}} { if _, err := db.Exec(`INSERT INTO user_location_states(user_id,city_code,latitude,longitude) VALUES(?,'440300',?,?)`, seed.user, seed.lat, seed.lng); err != nil { t.Fatal(err) } } profile := func(viewer, target int64) profileView { t.Helper() var item profileView path := fmt.Sprintf("/api/v1/users/%d/profile", target) if err := json.Unmarshal(imTestCall(t, a.userProfile, viewer, "GET", path, "", 200), &item); err != nil { t.Fatal(err) } return item } t.Run("another profile carries the distance between the two locations", func(t *testing.T) { item := profile(1, 2) if math.Abs(item.Distance-3.34) > 0.1 { t.Fatalf("distance = %v km, want about 3.34", item.Distance) } if item.DistanceText != distanceText(item.Distance) { t.Fatalf("distanceText = %q, want %q", item.DistanceText, distanceText(item.Distance)) } }) t.Run("my own profile has no distance to label", func(t *testing.T) { if item := profile(1, 1); item.DistanceText != "" { t.Fatalf("distanceText = %q, want empty", item.DistanceText) } }) t.Run("a viewer without a location sees no distance", func(t *testing.T) { if item := profile(3, 2); item.DistanceText != "" { t.Fatalf("distanceText = %q, want empty", item.DistanceText) } }) t.Run("hiding distance hides it here too", func(t *testing.T) { if _, err := db.Exec(`UPDATE user_privacy_settings SET distance_visible=0 WHERE user_id=2`); err != nil { t.Fatal(err) } if item := profile(1, 2); item.DistanceText != "" || item.Distance != 0 { t.Fatalf("hidden distance leaked: %v %q", item.Distance, item.DistanceText) } }) }