aboutsummaryrefslogtreecommitdiff
path: root/logs_test.go
blob: abef7ebce9926f7a27cd9db7ba4b8b7961caf5d4 (plain) (blame)
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
55
56
57
58
59
60
61
62
63
64
65
66
package main

import (
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"sync"
	"testing"
)

// A gap in the log reads as nothing having happened, so a line that never
// reaches the worker has to be counted and reported by one that does. The two
// ways it fails are a send that errors and a send that is answered with an
// error, and only the first of them looks like a failure to the client.
func TestShipperReportsWhatDidNotLand(t *testing.T) {
	var mu sync.Mutex
	mode := "refuse"
	var landed []string
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		mu.Lock()
		defer mu.Unlock()
		switch mode {
		case "refuse":
			http.Error(w, "no", http.StatusInternalServerError)
		case "drop":
			// A send that errors rather than answering.
			if conn, _, err := w.(http.Hijacker).Hijack(); err == nil {
				conn.Close()
			}
		default:
			body, _ := io.ReadAll(r.Body)
			landed = append(landed, string(body))
			w.WriteHeader(http.StatusNoContent)
		}
	}))
	defer srv.Close()

	s := newShipper(srv.URL)
	// close sends what is queued and waits, so each of these is one send.
	for _, step := range []struct{ mode, line string }{
		{"refuse", "answered with a 500"},
		{"drop", "the connection went away"},
		{"take", "this one lands"},
	} {
		mu.Lock()
		mode = step.mode
		mu.Unlock()
		if _, err := s.Write([]byte(step.line + "\n")); err != nil {
			t.Fatal(err)
		}
		s.close()
	}

	mu.Lock()
	defer mu.Unlock()
	if len(landed) != 1 {
		t.Fatalf("the worker was handed %d bodies, want the one it accepted: %q", len(landed), landed)
	}
	if !strings.Contains(landed[0], "this one lands") {
		t.Errorf("the line that should have landed is missing from %q", landed[0])
	}
	if !strings.Contains(landed[0], "2 log lines did not reach the worker") {
		t.Errorf("the two lines that did not land are not reported in %q", landed[0])
	}
}