aboutsummaryrefslogtreecommitdiff
path: root/internal/pushgateway/client_test.go
blob: bd0dca4701190a5a7109b8f2c9dbd4ca1542e420 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package pushgateway

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"reflect"
	"testing"
)

func TestNotify(t *testing.T) {
	wantResponse := NotifyResponse{
		Rejected: []string{"testing"},
	}

	var i = 0

	svr := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// /notify only accepts POST requests
		if r.Method != http.MethodPost {
			w.WriteHeader(http.StatusNotImplemented)
			return
		}

		if i != 0 { // error path
			w.WriteHeader(http.StatusBadRequest)
			return
		}

		// happy path
		json.NewEncoder(w).Encode(wantResponse)
	}))
	defer svr.Close()

	cl := NewHTTPClient(true)
	gotResponse := NotifyResponse{}

	// Test happy path
	err := cl.Notify(context.Background(), svr.URL, &NotifyRequest{}, &gotResponse)
	if err != nil {
		t.Errorf("failed to notify client")
	}
	if !reflect.DeepEqual(gotResponse, wantResponse) {
		t.Errorf("expected response %+v, got %+v", wantResponse, gotResponse)
	}

	// Test error path
	i++
	err = cl.Notify(context.Background(), svr.URL, &NotifyRequest{}, &gotResponse)
	if err == nil {
		t.Errorf("expected notifying the pushgateway to fail, but it succeeded")
	}
}