File: util_test.go

package info (click to toggle)
golang-github-go-kit-kit 0.13.0-8
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,784 kB
  • sloc: sh: 22; makefile: 11
file content (75 lines) | stat: -rw-r--r-- 1,787 bytes parent folder | download | duplicates (5)
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
67
68
69
70
71
72
73
74
75
package circuitbreaker_test

import (
	"context"
	"errors"
	"fmt"
	"path/filepath"
	"runtime"
	"testing"
	"time"

	"github.com/go-kit/kit/endpoint"
)

func testFailingEndpoint(
	t *testing.T,
	breaker endpoint.Middleware,
	primeWith int,
	shouldPass func(int) bool,
	requestDelay time.Duration,
	openCircuitError string,
) {
	_, file, line, _ := runtime.Caller(1)
	caller := fmt.Sprintf("%s:%d", filepath.Base(file), line)

	// Create a mock endpoint and wrap it with the breaker.
	m := mock{}
	var e endpoint.Endpoint
	e = m.endpoint
	e = breaker(e)

	// Prime the endpoint with successful requests.
	for i := 0; i < primeWith; i++ {
		if _, err := e(context.Background(), struct{}{}); err != nil {
			t.Fatalf("%s: during priming, got error: %v", caller, err)
		}
		time.Sleep(requestDelay)
	}

	// Switch the endpoint to start throwing errors.
	m.err = errors.New("tragedy+disaster")
	m.through = 0

	// The first several should be allowed through and yield our error.
	for i := 0; shouldPass(i); i++ {
		if _, err := e(context.Background(), struct{}{}); err != m.err {
			t.Fatalf("%s: want %v, have %v", caller, m.err, err)
		}
		time.Sleep(requestDelay)
	}
	through := m.through

	// But the rest should be blocked by an open circuit.
	for i := 0; i < 10; i++ {
		if _, err := e(context.Background(), struct{}{}); err.Error() != openCircuitError {
			t.Fatalf("%s: want %q, have %q", caller, openCircuitError, err.Error())
		}
		time.Sleep(requestDelay)
	}

	// Make sure none of those got through.
	if want, have := through, m.through; want != have {
		t.Errorf("%s: want %d, have %d", caller, want, have)
	}
}

type mock struct {
	through int
	err     error
}

func (m *mock) endpoint(context.Context, interface{}) (interface{}, error) {
	m.through++
	return struct{}{}, m.err
}