package statement import ( "context" "errors" "io" "net/http" "net/http/httptest" "os" "strings" "testing" ) // judge serves the saved responses in testdata: LeetCode's GraphQL answer // for path-with-minimum-effort and USACO's page for cpid=644. func judge(t *testing.T) *Fetcher { t.Helper() lc, _ := os.ReadFile("testdata/leetcode.json") us, _ := os.ReadFile("testdata/usaco.html") srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { case r.URL.Path == "/graphql": b, _ := io.ReadAll(r.Body) if !strings.Contains(string(b), `"s":"path-with-minimum-effort"`) { w.Write([]byte(`{"data":{"question":null}}`)) return } w.Write(lc) case r.URL.Query().Get("cpid") == "644": w.Write(us) default: http.NotFound(w, r) } })) t.Cleanup(srv.Close) return &Fetcher{LeetCodeAPI: srv.URL + "/graphql", USACOBase: srv.URL} } func TestLeetCode(t *testing.T) { md, err := judge(t).Fetch(context.Background(), "https://leetcode.com/problems/path-with-minimum-effort/description/") if err != nil { t.Fatal(err) } for _, want := range []string{"# Path With Minimum Effort", "You are a hiker", "`heights`"} { if !strings.Contains(md, want) { t.Errorf("markdown is missing %q:\n%s", want, md) } } if strings.Contains(md, "

") { t.Errorf("HTML left in the markdown:\n%s", md) } } func TestLeetCodeUnknownSlug(t *testing.T) { if _, err := judge(t).Fetch(context.Background(), "https://leetcode.com/problems/no-such-thing/"); err == nil { t.Fatal("want an error for a problem LeetCode does not have") } } func TestUSACO(t *testing.T) { md, err := judge(t).Fetch(context.Background(), "https://usaco.org/index.php?page=viewproblem2&cpid=644") if err != nil { t.Fatal(err) } for _, want := range []string{"# Problem 3. Closing the Farm", "FJ wants to temporarily close", "SAMPLE INPUT"} { if !strings.Contains(md, want) { t.Errorf("markdown is missing %q:\n%s", want, md) } } if strings.Contains(md, "navbar") || strings.Contains(md, "Contest has ended") { t.Errorf("page chrome leaked into the statement:\n%s", md) } } func TestUnsupported(t *testing.T) { for _, link := range []string{"https://cses.fi/problemset/task/1068", "not a url", ""} { if _, err := judge(t).Fetch(context.Background(), link); !errors.Is(err, ErrUnsupported) { t.Errorf("Fetch(%q) = %v, want ErrUnsupported", link, err) } } }