package backlinks import ( "context" "encoding/json" "net/http" "net/http/httptest" "path/filepath" "testing" "time" "supermarket/internal/api/bing" "supermarket/internal/db" ) func openDB(t *testing.T) *db.DB { t.Helper() d, err := db.Open(filepath.Join(t.TempDir(), "app.db")) if err != nil { t.Fatal(err) } t.Cleanup(func() { d.Close() }) return d } func TestSyncBing(t *testing.T) { d := openDB(t) extra := false srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() if q.Get("apikey") != "k" || q.Get("siteUrl") != "https://example.com/" { w.WriteHeader(http.StatusUnauthorized) return } var d any switch r.URL.Path { case "/GetLinkCounts": d = map[string]any{"TotalPages": 1, "Links": []map[string]any{ {"Url": "https://example.com/", "Count": 3}, {"Url": "https://example.com/freescout", "Count": 5}}} case "/GetUrlLinks": switch q.Get("link") { case "https://example.com/freescout": links := []map[string]any{{"Url": "https://selfhosted.blog/hosts/#top", "AnchorText": "Federated"}, {"Url": "https://selfhosted.blog/freescout/", "AnchorText": "FreeScout hosting"}} if extra { links = append(links, map[string]any{"Url": "https://newsite.example/list", "AnchorText": "a host"}) } d = map[string]any{"TotalPages": 1, "Details": links} default: d = map[string]any{"TotalPages": 1, "Details": []map[string]any{{"Url": "https://wdtprs.com/2026/11/post/", "AnchorText": ""}}} } } json.NewEncoder(w).Encode(map[string]any{"d": d}) })) defer srv.Close() c := bing.New("k").WithBase(srv.URL) now := time.Date(2026, 11, 24, 9, 0, 0, 0, time.UTC) st, err := SyncBing(context.Background(), d, c, "https://example.com/", "https://example.com/", now) if err != nil { t.Fatal(err) } if st.Total != 8 || len(st.Pages) != 2 || st.Pages[0].Path != "/freescout/" || st.Linked != 3 { t.Errorf("state: %+v", st) } links, _ := Links(d, "https://example.com/") sites := Sites(links, st.First) if len(sites) != 2 || sites[0].Host != "selfhosted.blog" || sites[0].Links != 2 || sites[0].New || sites[0].Targets[0] != "/freescout/" { t.Errorf("sites: %+v", sites) } if DueBing(d, "https://example.com/", now.Add(time.Hour)) || !DueBing(d, "https://example.com/", now.Add(8*24*time.Hour)) { t.Error("DueBing") } // A week later Bing knows one more site: it's new; nothing doubles. extra = true st, _ = SyncBing(context.Background(), d, c, "https://example.com/", "https://example.com/", now.AddDate(0, 0, 7)) links, _ = Links(d, "https://example.com/") sites = Sites(links, st.First) if len(links) != 4 || sites[0].Host != "newsite.example" || !sites[0].New { t.Errorf("a week later: %d %+v", len(links), sites) } // A refused key keeps what was read before, with the error. bad := bing.New("x").WithBase(srv.URL) if st, err := SyncBing(context.Background(), d, bad, "https://example.com/", "https://example.com/", now.AddDate(0, 0, 14)); err == nil || st.Total != 8 || st.Error == "" { t.Errorf("refused: %+v %v", st, err) } }