package services import ( "context" "net/http" "net/http/httptest" "strings" "testing" "adam-french.co.uk/job-tracker/internal/models" ) // The source fetchers, each against a stub server replying with a cut-down // copy of a real response (the board kinds) or of the documented shape (the // search kinds, which need API keys). What is under test is the request each // one makes and how its JSON becomes a fetchedJob. // sourceStub points every source's base URL at one stub server for the test. func sourceStub(t *testing.T, config JobLeadConfig, handler http.HandlerFunc) *JobLeadService { t.Helper() srv := httptest.NewServer(handler) t.Cleanup(srv.Close) for _, base := range []*string{&greenhouseBase, &leverBase, &ashbyBase, &adzunaBase, &reedBase} { old := *base *base = srv.URL t.Cleanup(func() { *base = old }) } return &JobLeadService{Config: &config, HTTPClient: srv.Client()} } func TestFetchGreenhouse(t *testing.T) { var path string s := sourceStub(t, JobLeadConfig{}, func(w http.ResponseWriter, r *http.Request) { path = r.URL.RequestURI() w.Write([]byte(`{"jobs": [{ "absolute_url": "https://job-boards.greenhouse.io/monzo/jobs/8143930", "location": {"name": "Cardiff, London or Remote (UK)"}, "id": 8143930, "updated_at": "2026-09-25T05:17:09-04:00", "title": "Backend Engineer", "first_published": "2026-08-24T09:04:42-04:00", "content": "<div class="intro"><p><strong>About us</strong></p><ul><li>Go & Kotlin</li><li>On-call</li></ul></div>" }], "meta": {"total": 1}}`)) }) jobs, err := s.fetchGreenhouse(context.Background(), models.JobSource{Kind: SourceGreenhouse, Label: "Monzo", Token: "Monzo"}) if err != nil { t.Fatalf("fetchGreenhouse: %v", err) } if path != "/v1/boards/Monzo/jobs?content=true" { t.Errorf("request = %q", path) } if len(jobs) != 1 { t.Fatalf("got %d jobs", len(jobs)) } j := jobs[0] // The id is namespaced by the board, lowercased so "Monzo" and "monzo" // are one board. if j.ExternalID != "monzo/8143930" || j.Title != "Backend Engineer" || j.Company != "Monzo" || j.Location != "Cardiff, London or Remote (UK)" || j.URL != "https://job-boards.greenhouse.io/monzo/jobs/8143930" { t.Errorf("job = %+v", j) } // Doubly escaped HTML comes out as plain lines. if j.Description != "About us\n\nGo & Kotlin\n\nOn-call" { t.Errorf("description = %q", j.Description) } if j.PostedAt == nil || j.PostedAt.UTC().Format("2006-01-02") != "2026-08-24" { t.Errorf("postedAt = %v", j.PostedAt) } } func TestFetchLever(t *testing.T) { s := sourceStub(t, JobLeadConfig{}, func(w http.ResponseWriter, r *http.Request) { if r.URL.RequestURI() != "/v0/postings/acme?mode=json" { t.Errorf("request = %q", r.URL.RequestURI()) } w.Write([]byte(`[{ "additionalPlain": "We are an equal opportunity employer.", "categories": {"commitment": "Full-time", "location": "London, UK", "team": "Platform"}, "createdAt": 1786469891368, "descriptionPlain": "A World-Changing Company\n", "id": "6ed76ce8-4156", "lists": [{"text": "What you'll do", "content": "
The full advert.
Second paragraph.
"}`)) default: t.Errorf("unexpected path %q", r.URL.Path) } }) jobs, err := s.fetchReed(context.Background(), models.JobSource{Kind: SourceReed, Query: "golang", Location: "London"}) if err != nil || len(jobs) != 1 { t.Fatalf("fetchReed: %v, %d jobs", err, len(jobs)) } j := jobs[0] if j.ExternalID != "51234567" || j.Company != "Acme" || j.Description != "Snippet…" || j.detailID != "51234567" { t.Errorf("job = %+v", j) } if j.PostedAt == nil || j.PostedAt.Format("2006-01-02") != "2026-10-03" { t.Errorf("postedAt = %v", j.PostedAt) } full, err := s.fetchReedDescription(context.Background(), j.detailID) if err != nil || full != "The full advert.\n\nSecond paragraph." { t.Errorf("fetchReedDescription = %q, %v", full, err) } } func TestSearchSourcesNeedTheirKeys(t *testing.T) { s := sourceStub(t, JobLeadConfig{}, func(w http.ResponseWriter, r *http.Request) { t.Errorf("no request should be made without a key, got %s", r.URL.Path) }) if _, err := s.fetchSource(context.Background(), models.JobSource{Kind: SourceAdzuna, Query: "go"}); err == nil || !strings.Contains(err.Error(), "ADZUNA_APP_ID") { t.Errorf("adzuna err = %v", err) } if _, err := s.fetchSource(context.Background(), models.JobSource{Kind: SourceReed, Query: "go"}); err == nil || !strings.Contains(err.Error(), "REED_API_KEY") { t.Errorf("reed err = %v", err) } if _, err := s.fetchSource(context.Background(), models.JobSource{Kind: "monster"}); err == nil { t.Error("an unknown kind should be an error") } } // The error ends up in JobSource.LastError, on the page. It must say what to // fix and must never quote the request URL, which for Adzuna holds the key. func TestSourceErrorsAreSafeToShow(t *testing.T) { cases := []struct { status int want string }{ {http.StatusNotFound, "check the board token"}, {http.StatusUnauthorized, "check the API key"}, {http.StatusInternalServerError, "source returned 500"}, } for _, c := range cases { s := sourceStub(t, JobLeadConfig{AdzunaAppID: "id1", AdzunaAppKey: "sekrit"}, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(c.status) }) _, err := s.fetchSource(context.Background(), models.JobSource{Kind: SourceAdzuna, Query: "go"}) if err == nil || !strings.Contains(err.Error(), c.want) || strings.Contains(err.Error(), "sekrit") { t.Errorf("status %d: err = %v", c.status, err) } } // A connection failure is the case where net/http would quote the URL. s := sourceStub(t, JobLeadConfig{AdzunaAppID: "id1", AdzunaAppKey: "sekrit"}, func(http.ResponseWriter, *http.Request) {}) adzunaBase = "http://127.0.0.1:1" _, err := s.fetchSource(context.Background(), models.JobSource{Kind: SourceAdzuna, Query: "go"}) if err == nil || strings.Contains(err.Error(), "sekrit") { t.Errorf("connection failure: err = %v", err) } s = sourceStub(t, JobLeadConfig{}, func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("")) }) if _, err := s.fetchSource(context.Background(), models.JobSource{Kind: SourceLever, Token: "acme"}); err == nil || !strings.Contains(err.Error(), "unexpected response") { t.Errorf("non-JSON reply: err = %v", err) } } func TestHTMLToText(t *testing.T) { cases := []struct{ in, want string }{ {"One
Two
", "One\n\nTwo"}, {"