| 76 | } |
| 77 | |
| 78 | func TestStore(t *testing.T) { |
| 79 | t.Parallel() |
| 80 | |
| 81 | mocktrans := MockTransport{ |
| 82 | Response: &http.Response{ |
| 83 | StatusCode: http.StatusOK, |
| 84 | Body: ioutil.NopCloser(strings.NewReader(`{}`)), |
| 85 | Header: http.Header{"X-Elastic-Product": []string{"Elasticsearch"}}, |
| 86 | }, |
| 87 | } |
| 88 | mocktrans.RoundTripFn = func(req *http.Request) (*http.Response, error) { return mocktrans.Response, nil } |
| 89 | |
| 90 | client, err := elasticsearch.New( |
| 91 | elasticsearch.WithTransportOptions(elastictransport.WithTransport(&mocktrans)), |
| 92 | ) |
| 93 | if err != nil { |
| 94 | t.Fatalf("Error creating Elasticsearch client: %s", err) |
| 95 | } |
| 96 | |
| 97 | config := xkcdsearch.StoreConfig{Client: client} |
| 98 | store, err := xkcdsearch.NewStore(config) |
| 99 | if err != nil { |
| 100 | t.Fatalf("Error creating the store: %s", err) |
| 101 | } |
| 102 | |
| 103 | t.Run("Empty response", func(t *testing.T) { |
| 104 | results, err := store.Search("foobar") |
| 105 | if err != nil { |
| 106 | t.Errorf("Unexpected error: %s", err) |
| 107 | } |
| 108 | if results.Total != 0 { |
| 109 | t.Errorf("Unexpected total results, want=0, got=%d", results.Total) |
| 110 | } |
| 111 | }) |
| 112 | |
| 113 | t.Run("Match all", func(t *testing.T) { |
| 114 | mocktrans.Response = &http.Response{ |
| 115 | StatusCode: http.StatusOK, |
| 116 | Body: fixture("match_all.json"), |
| 117 | } |
| 118 | |
| 119 | results, err := store.Search("") |
| 120 | if err != nil { |
| 121 | t.Fatalf("Unexpected error: %s", err) |
| 122 | } |
| 123 | if results.Total != 42 { |
| 124 | t.Errorf("Unexpected total results, want=42, got=%d", results.Total) |
| 125 | } |
| 126 | if results.Hits[0].Title != "Title One" { |
| 127 | t.Errorf("Unexpected title, want=\"Title One\", got=%q", results.Hits[0].Title) |
| 128 | } |
| 129 | }) |
| 130 | |
| 131 | t.Run("Match all with search_after", func(t *testing.T) { |
| 132 | mocktrans.RoundTripFn = func(req *http.Request) (*http.Response, error) { |
| 133 | var b map[string]interface{} |
| 134 | if err := json.NewDecoder(req.Body).Decode(&b); err != nil { |
| 135 | t.Fatalf("Error parsing search definition: %s", err) |