PageRenderTime 682ms CodeModel.GetById 52ms app.highlight 63ms RepoModel.GetById 111ms app.codeStats 193ms

/goduckgo/duckduck_test.go

http://github.com/ajanicij/goduckgo
Go | 66 lines | 54 code | 12 blank | 0 comment | 13 complexity | 5ca891ded72e1315fbc3fc4c3ec7baed MD5 | raw file
 1package goduckgo
 2
 3import (
 4	"fmt"
 5	"net/http"
 6	"net/http/httptest"
 7	"reflect"
 8	"strings"
 9	"testing"
10)
11
12func TestQuery(t *testing.T) {
13	query := "New York City"
14	expectedUrl := "https://api.duckduckgo.com/?q=New+York+City&format=json&pretty=1"
15	expectedBody := `{
16        "Heading" : "New York City"
17    }`
18	expectedMessage := &Message{}
19	expectedMessage.Heading = "New York City"
20
21	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
22		w.Header().Set("Content-Type", "application/json")
23		fmt.Fprintln(w, expectedBody)
24	}))
25	defer ts.Close()
26
27	if url := EncodeUrl(query); url != expectedUrl {
28		t.Errorf("Got %s, want %s", url, expectedUrl)
29	}
30
31	body, err := Do(ts.URL)
32	if err != nil {
33		t.Errorf("Got %v, want %v", err, nil)
34	}
35
36	if trimmedBody := strings.TrimSpace(string(body)); trimmedBody != expectedBody {
37		t.Errorf("Got %s, want %s", trimmedBody, expectedBody)
38	}
39
40	message := &Message{}
41	if err = message.Decode(body); err != nil {
42		t.Errorf("Got %v, want %v", err, nil)
43	}
44
45	if !reflect.DeepEqual(message, expectedMessage) {
46		t.Errorf("Got %v, want %v", message, expectedMessage)
47	}
48}
49
50func TestEncodeUrl(t *testing.T) {
51	query := "!gi New York City"
52	expectedUrl := "https://api.duckduckgo.com/?q=%21gi+New+York+City&format=json&pretty=1&no_redirect=1"
53
54	url := EncodeUrl(query)
55	if url != expectedUrl {
56		t.Errorf("Got %s, want %s", url, expectedUrl)
57	}
58
59	query = "New York City"
60	expectedUrl = "https://api.duckduckgo.com/?q=New+York+City&format=json&pretty=1"
61	url = EncodeUrl(query)
62	if url != expectedUrl {
63		t.Errorf("Got %s, want %s", url, expectedUrl)
64	}
65
66}