42 lines
1.1 KiB
Go
42 lines
1.1 KiB
Go
package main
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestFetch(t *testing.T) {
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
switch r.URL.Path {
|
|
case "/ok":
|
|
w.Header().Set("Content-Type", "text/html")
|
|
w.Write([]byte("<html><body><h1>Hello</h1></body></html>"))
|
|
case "/bad":
|
|
http.Error(w, "no", http.StatusNotFound)
|
|
case "/text":
|
|
w.Header().Set("Content-Type", "text/plain")
|
|
w.Write([]byte("hello"))
|
|
}
|
|
}))
|
|
defer srv.Close()
|
|
body, err := fetch(srv.URL + "/ok")
|
|
if err != nil || !strings.Contains(body, "Hello") {
|
|
t.Fatalf("body=%q err=%v", body, err)
|
|
}
|
|
if _, err = fetch(srv.URL + "/bad"); err == nil || !strings.Contains(err.Error(), "HTTP") {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err = fetch(srv.URL + "/text"); err == nil || !strings.Contains(err.Error(), "not HTML") {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
func TestFetchURLValidation(t *testing.T) {
|
|
for _, u := range []string{"", "ftp://example.com", "/relative"} {
|
|
if _, err := fetch(u); err == nil || !strings.Contains(err.Error(), "absolute http or https") {
|
|
t.Errorf("fetch(%q) err=%v", u, err)
|
|
}
|
|
}
|
|
}
|