-
Notifications
You must be signed in to change notification settings - Fork 357
Expand file tree
/
Copy pathcore_test.go
More file actions
97 lines (87 loc) · 2.41 KB
/
Copy pathcore_test.go
File metadata and controls
97 lines (87 loc) · 2.41 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package core
import (
"context"
"crypto/x509"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"chain/core/config"
"chain/core/leader"
"chain/net"
"chain/net/http/httpjson"
"chain/testutil"
)
func TestForwardToLeader(t *testing.T) {
// Create a test http server with TLS to be a fake leader process.
ts := httptest.NewTLSServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if req.URL.Path != "/info" {
t.Fatalf("unexpected call to %s", req.URL.Path)
}
username, password, ok := req.BasicAuth()
if ok && username != "" && password != "" {
t.Error("request credentials shouldn't be forwarded")
}
rw.Header().Set("Content-Type", "application/json")
fmt.Fprintln(rw, `{
"state": "leading",
"is_configured": true
}`)
}))
defer ts.Close()
// TODO(jackson): In Go 1.9+ use ts.Client():
// https://go-review.googlesource.com/c/34639/
cert, err := x509.ParseCertificate(ts.TLS.Certificates[0].Certificate[0])
if err != nil {
t.Fatal(err)
}
certpool := x509.NewCertPool()
certpool.AddCert(cert)
// Setup a core.API so that it's a follower and leader.Address will
// return the fake HTTPS server created above. Also, include its
// certs in an internal httpClient so that it trusts the test server's
// certs.
u, err := url.Parse(ts.URL)
if err != nil {
t.Fatal(err)
}
tlsConfig := net.DefaultTLSConfig()
tlsConfig.RootCAs = certpool
api := &API{
config: &config.Config{},
leader: alwaysFollower{leaderAddress: u.Host},
httpClient: &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
},
},
}
// Create a fake incoming request so that forwardToLeader can propagate
// the basic auth credentials.
fakeRequest, err := http.NewRequest("POST", "http://localhost:1999/info", nil)
if err != nil {
t.Fatal(err)
}
fakeRequest.SetBasicAuth("example", "password")
ctx := context.Background()
ctx = httpjson.WithRequest(ctx, fakeRequest)
got, err := api.info(ctx)
if err != nil {
t.Fatal(err)
}
want := map[string]interface{}{
"state": "leading",
"is_configured": true,
}
if !testutil.DeepEqual(got, want) {
t.Errorf("Got response %#v, want %#v", got, want)
}
}
type alwaysFollower struct {
leaderAddress string
}
func (af alwaysFollower) State() leader.ProcessState { return leader.Following }
func (af alwaysFollower) Address(context.Context) (string, error) {
return af.leaderAddress, nil
}