package leetcode import ( "context" "net/http" "net/http/httptest" "os" "os/exec" "path/filepath" "strings" "testing" ) func TestDaily(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`{"data":{"activeDailyCodingChallengeQuestion":{"question":{"titleSlug":"two-sum"}}}}`)) })) defer srv.Close() slug, err := (&Importer{API: srv.URL}).Daily(context.Background()) if err != nil || slug != "two-sum" { t.Fatalf("Daily = %q, %v; want two-sum", slug, err) } } func TestDailyMissing(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`{"data":{"activeDailyCodingChallengeQuestion":null}}`)) })) defer srv.Close() if _, err := (&Importer{API: srv.URL}).Daily(context.Background()); err == nil { t.Fatal("Daily with no question succeeded") } } // The script's own "Error: ..." line is the message, not the exit status. func TestImportError(t *testing.T) { if _, err := exec.LookPath("python3"); err != nil { t.Skip("no python3") } root := t.TempDir() os.MkdirAll(filepath.Join(root, "lib"), 0o755) script := "import sys\nprint('Error: LeetCode has no problem ' + repr(sys.argv[2]), file=sys.stderr)\nsys.exit(1)\n" os.WriteFile(filepath.Join(root, "lib", "leetcode.py"), []byte(script), 0o644) err := (&Importer{}).Import(context.Background(), root, "nope") if err == nil || !strings.Contains(err.Error(), "LeetCode has no problem 'nope'") { t.Fatalf("Import = %v, want the script's message", err) } }