|
| 1 | +package antch |
| 2 | + |
| 3 | +import ( |
| 4 | + "io/ioutil" |
| 5 | + "net/http" |
| 6 | + "strings" |
| 7 | + "testing" |
| 8 | + |
| 9 | + "github.com/antchfx/xquery/html" |
| 10 | +) |
| 11 | + |
| 12 | +func TestMediaTypeParse(t *testing.T) { |
| 13 | + s := "text/html; charset=utf-8" |
| 14 | + m := ParseMediaType(s) |
| 15 | + if v := m.ContentType(); v != s { |
| 16 | + t.Errorf("ContentType() = %s; want %s", v, s) |
| 17 | + } |
| 18 | + |
| 19 | + s = "text/html" |
| 20 | + m = ParseMediaType(s) |
| 21 | + if m.Charset != "" { |
| 22 | + t.Errorf("Charset = %s; want empty", m.Charset) |
| 23 | + } |
| 24 | + if g, e := m.Type, "text/html"; g != e { |
| 25 | + t.Errorf("Type = %s; want e", g, e) |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +var testHTML = `<html><head><meta charset="utf-8"></head><body>abc,这是中文内容</body> </html>` |
| 30 | + |
| 31 | +func TestParseHTML(t *testing.T) { |
| 32 | + res := &http.Response{ |
| 33 | + Header: map[string][]string{ |
| 34 | + "Content-Type": []string{"text/html; charset=utf-8"}, |
| 35 | + }, |
| 36 | + Body: ioutil.NopCloser(strings.NewReader(testHTML)), |
| 37 | + } |
| 38 | + doc, err := ParseHTML(res) |
| 39 | + if err != nil { |
| 40 | + t.Fatalf("ParseHTML failed: %v", err) |
| 41 | + } |
| 42 | + |
| 43 | + body := htmlquery.FindOne(doc, "//body") |
| 44 | + if g, e := strings.TrimSpace(htmlquery.InnerText(body)), "abc,这是中文内容"; g != e { |
| 45 | + t.Errorf("body expected is %s; but got %s", e, g) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +func TestParseHTMLWithoutEncoding(t *testing.T) { |
| 50 | + res := &http.Response{ |
| 51 | + Header: map[string][]string{ |
| 52 | + "Content-Type": []string{"text/html"}, |
| 53 | + }, |
| 54 | + Body: ioutil.NopCloser(strings.NewReader(testHTML)), |
| 55 | + } |
| 56 | + doc, err := ParseHTML(res) |
| 57 | + if err != nil { |
| 58 | + t.Fatalf("ParseHTML failed: %v", err) |
| 59 | + } |
| 60 | + body := htmlquery.FindOne(doc, "//body") |
| 61 | + if g, e := strings.TrimSpace(htmlquery.InnerText(body)), "abc,这是中文内容"; g != e { |
| 62 | + t.Errorf("body expected is %s; but got %s", e, g) |
| 63 | + } |
| 64 | +} |
0 commit comments