MCPcopy Create free account
hub / github.com/PuerkitoBio/fetchbot / TestBasicAuth

Function TestBasicAuth

cmd_test.go:30–92  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

28}
29
30func TestBasicAuth(t *testing.T) {
31 creds := base64.StdEncoding.EncodeToString([]byte("me:you"))
32 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
33 auth := req.Header.Get("Authorization")
34 if auth != "Basic "+creds {
35 w.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
36 http.Error(w, "Unauthorized", http.StatusUnauthorized)
37 return
38 }
39 w.Write([]byte("ok"))
40 }))
41 defer srv.Close()
42 cases := []struct {
43 cmd Command
44 status int
45 }{
46 0: {
47 &basicAuthCmd{&Cmd{U: mustParse(t, srv.URL+"/a"), M: "GET"}, "me", "you"},
48 http.StatusOK,
49 },
50 1: {
51 &Cmd{U: mustParse(t, srv.URL+"/b"), M: "GET"},
52 http.StatusUnauthorized,
53 },
54 2: {
55 &basicAuthCmd{&Cmd{U: mustParse(t, srv.URL+"/c"), M: "GET"}, "some", "other"},
56 http.StatusUnauthorized,
57 },
58 3: {
59 &readerCmd{&Cmd{U: mustParse(t, srv.URL+"/d"), M: "POST"},
60 strings.NewReader("a")},
61 http.StatusUnauthorized,
62 },
63 4: {
64 &valuesCmd{&Cmd{U: mustParse(t, srv.URL+"/e"), M: "POST"},
65 url.Values{"k": {"v"}}},
66 http.StatusUnauthorized,
67 },
68 }
69 sh := &spyHandler{}
70 f := New(sh)
71 f.CrawlDelay = 0
72 q := f.Start()
73 for i, c := range cases {
74 if err := q.Send(c.cmd); err != nil {
75 t.Errorf("%d: error sending command: %s", i, err)
76 }
77 }
78 q.Close()
79 var urls []string
80 for i, c := range cases {
81 urls = append(urls, c.cmd.URL().String())
82 if st := sh.StatusFor(c.cmd.URL().String()); st != c.status {
83 t.Errorf("%d: expected status %d, got %d", i, c.status, st)
84 }
85 }
86 if !sh.CalledWithExactly(urls...) {
87 t.Error("expected handler to be called for all cases")

Callers

nothing calls this directly

Calls 10

StatusForMethod · 0.95
CalledWithExactlyMethod · 0.95
ErrorsMethod · 0.95
mustParseFunction · 0.85
NewFunction · 0.85
CloseMethod · 0.80
StartMethod · 0.80
SendMethod · 0.80
HeaderMethod · 0.65
URLMethod · 0.65

Tested by

no test coverage detected