PageRenderTime 111ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/goduckgo/duckduck_test.go

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