diff --git a/command/agent/acl_endpoint_test.go b/command/agent/acl_endpoint_test.go index f980b84199..6a77e655a9 100644 --- a/command/agent/acl_endpoint_test.go +++ b/command/agent/acl_endpoint_test.go @@ -32,129 +32,136 @@ func makeTestACL(t *testing.T, srv *HTTPServer) string { func TestACLUpdate(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - id := makeTestACL(t, srv) + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() - body := bytes.NewBuffer(nil) - enc := json.NewEncoder(body) - raw := map[string]interface{}{ - "ID": id, - "Name": "User Token 2", - "Type": "client", - "Rules": "", - } - enc.Encode(raw) + id := makeTestACL(t, a.srv) - req, _ := http.NewRequest("PUT", "/v1/acl/update?token=root", body) - resp := httptest.NewRecorder() - obj, err := srv.ACLUpdate(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - aclResp := obj.(aclCreateResponse) - if aclResp.ID != id { - t.Fatalf("bad: %v", aclResp) - } - }) + body := bytes.NewBuffer(nil) + enc := json.NewEncoder(body) + raw := map[string]interface{}{ + "ID": id, + "Name": "User Token 2", + "Type": "client", + "Rules": "", + } + enc.Encode(raw) + + req, _ := http.NewRequest("PUT", "/v1/acl/update?token=root", body) + resp := httptest.NewRecorder() + obj, err := a.srv.ACLUpdate(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + aclResp := obj.(aclCreateResponse) + if aclResp.ID != id { + t.Fatalf("bad: %v", aclResp) + } } func TestACLUpdate_Upsert(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - body := bytes.NewBuffer(nil) - enc := json.NewEncoder(body) - raw := map[string]interface{}{ - "ID": "my-old-id", - "Name": "User Token 2", - "Type": "client", - "Rules": "", - } - enc.Encode(raw) + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() - req, _ := http.NewRequest("PUT", "/v1/acl/update?token=root", body) - resp := httptest.NewRecorder() - obj, err := srv.ACLUpdate(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - aclResp := obj.(aclCreateResponse) - if aclResp.ID != "my-old-id" { - t.Fatalf("bad: %v", aclResp) - } - }) + body := bytes.NewBuffer(nil) + enc := json.NewEncoder(body) + raw := map[string]interface{}{ + "ID": "my-old-id", + "Name": "User Token 2", + "Type": "client", + "Rules": "", + } + enc.Encode(raw) + + req, _ := http.NewRequest("PUT", "/v1/acl/update?token=root", body) + resp := httptest.NewRecorder() + obj, err := a.srv.ACLUpdate(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + aclResp := obj.(aclCreateResponse) + if aclResp.ID != "my-old-id" { + t.Fatalf("bad: %v", aclResp) + } } func TestACLDestroy(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - id := makeTestACL(t, srv) - req, _ := http.NewRequest("PUT", "/v1/acl/destroy/"+id+"?token=root", nil) - resp := httptest.NewRecorder() - obj, err := srv.ACLDestroy(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - if resp, ok := obj.(bool); !ok || !resp { - t.Fatalf("should work") - } + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() - req, _ = http.NewRequest("GET", "/v1/acl/info/"+id, nil) - resp = httptest.NewRecorder() - obj, err = srv.ACLGet(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - respObj, ok := obj.(structs.ACLs) - if !ok { - t.Fatalf("should work") - } - if len(respObj) != 0 { - t.Fatalf("bad: %v", respObj) - } - }) + id := makeTestACL(t, a.srv) + req, _ := http.NewRequest("PUT", "/v1/acl/destroy/"+id+"?token=root", nil) + resp := httptest.NewRecorder() + obj, err := a.srv.ACLDestroy(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + if resp, ok := obj.(bool); !ok || !resp { + t.Fatalf("should work") + } + + req, _ = http.NewRequest("GET", "/v1/acl/info/"+id, nil) + resp = httptest.NewRecorder() + obj, err = a.srv.ACLGet(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + respObj, ok := obj.(structs.ACLs) + if !ok { + t.Fatalf("should work") + } + if len(respObj) != 0 { + t.Fatalf("bad: %v", respObj) + } } func TestACLClone(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - id := makeTestACL(t, srv) + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() - req, _ := http.NewRequest("PUT", "/v1/acl/clone/"+id+"?token=root", nil) - resp := httptest.NewRecorder() - obj, err := srv.ACLClone(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - aclResp, ok := obj.(aclCreateResponse) - if !ok { - t.Fatalf("should work: %#v %#v", obj, resp) - } - if aclResp.ID == id { - t.Fatalf("bad id") - } + id := makeTestACL(t, a.srv) - req, _ = http.NewRequest("GET", "/v1/acl/info/"+aclResp.ID, nil) - resp = httptest.NewRecorder() - obj, err = srv.ACLGet(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - respObj, ok := obj.(structs.ACLs) - if !ok { - t.Fatalf("should work") - } - if len(respObj) != 1 { - t.Fatalf("bad: %v", respObj) - } - }) + req, _ := http.NewRequest("PUT", "/v1/acl/clone/"+id+"?token=root", nil) + resp := httptest.NewRecorder() + obj, err := a.srv.ACLClone(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + aclResp, ok := obj.(aclCreateResponse) + if !ok { + t.Fatalf("should work: %#v %#v", obj, resp) + } + if aclResp.ID == id { + t.Fatalf("bad id") + } + + req, _ = http.NewRequest("GET", "/v1/acl/info/"+aclResp.ID, nil) + resp = httptest.NewRecorder() + obj, err = a.srv.ACLGet(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + respObj, ok := obj.(structs.ACLs) + if !ok { + t.Fatalf("should work") + } + if len(respObj) != 1 { + t.Fatalf("bad: %v", respObj) + } } func TestACLGet(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + req, _ := http.NewRequest("GET", "/v1/acl/info/nope", nil) resp := httptest.NewRecorder() - obj, err := srv.ACLGet(resp, req) + obj, err := a.srv.ACLGet(resp, req) if err != nil { t.Fatalf("err: %v", err) } @@ -167,12 +174,15 @@ func TestACLGet(t *testing.T) { } }) - httpTest(t, func(srv *HTTPServer) { - id := makeTestACL(t, srv) + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + + id := makeTestACL(t, a.srv) req, _ := http.NewRequest("GET", "/v1/acl/info/"+id, nil) resp := httptest.NewRecorder() - obj, err := srv.ACLGet(resp, req) + obj, err := a.srv.ACLGet(resp, req) if err != nil { t.Fatalf("err: %v", err) } @@ -188,42 +198,44 @@ func TestACLGet(t *testing.T) { func TestACLList(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - var ids []string - for i := 0; i < 10; i++ { - ids = append(ids, makeTestACL(t, srv)) - } + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() - req, _ := http.NewRequest("GET", "/v1/acl/list?token=root", nil) - resp := httptest.NewRecorder() - obj, err := srv.ACLList(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - respObj, ok := obj.(structs.ACLs) - if !ok { - t.Fatalf("should work") - } + var ids []string + for i := 0; i < 10; i++ { + ids = append(ids, makeTestACL(t, a.srv)) + } - // 10 + anonymous + master - if len(respObj) != 12 { - t.Fatalf("bad: %v", respObj) - } - }) + req, _ := http.NewRequest("GET", "/v1/acl/list?token=root", nil) + resp := httptest.NewRecorder() + obj, err := a.srv.ACLList(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + respObj, ok := obj.(structs.ACLs) + if !ok { + t.Fatalf("should work") + } + + // 10 + anonymous + master + if len(respObj) != 12 { + t.Fatalf("bad: %v", respObj) + } } func TestACLReplicationStatus(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - req, _ := http.NewRequest("GET", "/v1/acl/replication", nil) - resp := httptest.NewRecorder() - obj, err := srv.ACLReplicationStatus(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - _, ok := obj.(structs.ACLReplicationStatus) - if !ok { - t.Fatalf("should work") - } - }) + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + + req, _ := http.NewRequest("GET", "/v1/acl/replication", nil) + resp := httptest.NewRecorder() + obj, err := a.srv.ACLReplicationStatus(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + _, ok := obj.(structs.ACLReplicationStatus) + if !ok { + t.Fatalf("should work") + } } diff --git a/command/agent/event_endpoint_test.go b/command/agent/event_endpoint_test.go index 44488eef1b..9864ece026 100644 --- a/command/agent/event_endpoint_test.go +++ b/command/agent/event_endpoint_test.go @@ -15,166 +15,170 @@ import ( func TestEventFire(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - body := bytes.NewBuffer([]byte("test")) - url := "/v1/event/fire/test?node=Node&service=foo&tag=bar" - req, _ := http.NewRequest("PUT", url, body) - resp := httptest.NewRecorder() - obj, err := srv.EventFire(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() - event, ok := obj.(*UserEvent) - if !ok { - t.Fatalf("bad: %#v", obj) - } + body := bytes.NewBuffer([]byte("test")) + url := "/v1/event/fire/test?node=Node&service=foo&tag=bar" + req, _ := http.NewRequest("PUT", url, body) + resp := httptest.NewRecorder() + obj, err := a.srv.EventFire(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } - if event.ID == "" { - t.Fatalf("bad: %#v", event) - } - if event.Name != "test" { - t.Fatalf("bad: %#v", event) - } - if string(event.Payload) != "test" { - t.Fatalf("bad: %#v", event) - } - if event.NodeFilter != "Node" { - t.Fatalf("bad: %#v", event) - } - if event.ServiceFilter != "foo" { - t.Fatalf("bad: %#v", event) - } - if event.TagFilter != "bar" { - t.Fatalf("bad: %#v", event) - } - }) + event, ok := obj.(*UserEvent) + if !ok { + t.Fatalf("bad: %#v", obj) + } + + if event.ID == "" { + t.Fatalf("bad: %#v", event) + } + if event.Name != "test" { + t.Fatalf("bad: %#v", event) + } + if string(event.Payload) != "test" { + t.Fatalf("bad: %#v", event) + } + if event.NodeFilter != "Node" { + t.Fatalf("bad: %#v", event) + } + if event.ServiceFilter != "foo" { + t.Fatalf("bad: %#v", event) + } + if event.TagFilter != "bar" { + t.Fatalf("bad: %#v", event) + } } func TestEventFire_token(t *testing.T) { t.Parallel() - httpTestWithConfig(t, func(srv *HTTPServer) { - // Create an ACL token - args := structs.ACLRequest{ - Datacenter: "dc1", - Op: structs.ACLSet, - ACL: structs.ACL{ - Name: "User token", - Type: structs.ACLTypeClient, - Rules: testEventPolicy, - }, - WriteRequest: structs.WriteRequest{Token: "root"}, - } - var token string - if err := srv.agent.RPC("ACL.Apply", &args, &token); err != nil { - t.Fatalf("err: %v", err) + conf := TestConfig() + conf.ACLDefaultPolicy = "deny" + a := NewTestAgent(t.Name(), conf) + defer a.Shutdown() + + // Create an ACL token + args := structs.ACLRequest{ + Datacenter: "dc1", + Op: structs.ACLSet, + ACL: structs.ACL{ + Name: "User token", + Type: structs.ACLTypeClient, + Rules: testEventPolicy, + }, + WriteRequest: structs.WriteRequest{Token: "root"}, + } + var token string + if err := a.RPC("ACL.Apply", &args, &token); err != nil { + t.Fatalf("err: %v", err) + } + + type tcase struct { + event string + allowed bool + } + tcases := []tcase{ + {"foo", false}, + {"bar", false}, + {"baz", true}, + } + for _, c := range tcases { + // Try to fire the event over the HTTP interface + url := fmt.Sprintf("/v1/event/fire/%s?token=%s", c.event, token) + req, _ := http.NewRequest("PUT", url, nil) + resp := httptest.NewRecorder() + if _, err := a.srv.EventFire(resp, req); err != nil { + t.Fatalf("err: %s", err) } - type tcase struct { - event string - allowed bool - } - tcases := []tcase{ - {"foo", false}, - {"bar", false}, - {"baz", true}, - } - for _, c := range tcases { - // Try to fire the event over the HTTP interface - url := fmt.Sprintf("/v1/event/fire/%s?token=%s", c.event, token) - req, _ := http.NewRequest("PUT", url, nil) - resp := httptest.NewRecorder() - if _, err := srv.EventFire(resp, req); err != nil { - t.Fatalf("err: %s", err) + // Check the result + body := resp.Body.String() + if c.allowed { + if strings.Contains(body, permissionDenied) { + t.Fatalf("bad: %s", body) } - - // Check the result - body := resp.Body.String() - if c.allowed { - if strings.Contains(body, permissionDenied) { - t.Fatalf("bad: %s", body) - } - if resp.Code != 200 { - t.Fatalf("bad: %d", resp.Code) - } - } else { - if !strings.Contains(body, permissionDenied) { - t.Fatalf("bad: %s", body) - } - if resp.Code != 403 { - t.Fatalf("bad: %d", resp.Code) - } + if resp.Code != 200 { + t.Fatalf("bad: %d", resp.Code) + } + } else { + if !strings.Contains(body, permissionDenied) { + t.Fatalf("bad: %s", body) + } + if resp.Code != 403 { + t.Fatalf("bad: %d", resp.Code) } } - }, func(c *Config) { - c.ACLDefaultPolicy = "deny" - }) + } } func TestEventList(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - p := &UserEvent{Name: "test"} - if err := srv.agent.UserEvent("dc1", "root", p); err != nil { - t.Fatalf("err: %v", err) + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + + p := &UserEvent{Name: "test"} + if err := a.UserEvent("dc1", "root", p); err != nil { + t.Fatalf("err: %v", err) + } + + retry.Run(t, func(r *retry.R) { + req, _ := http.NewRequest("GET", "/v1/event/list", nil) + resp := httptest.NewRecorder() + obj, err := a.srv.EventList(resp, req) + if err != nil { + r.Fatal(err) } - retry.Run(t, func(r *retry.R) { - req, _ := http.NewRequest("GET", "/v1/event/list", nil) - resp := httptest.NewRecorder() - obj, err := srv.EventList(resp, req) - if err != nil { - r.Fatal(err) - } - - list, ok := obj.([]*UserEvent) - if !ok { - r.Fatalf("bad: %#v", obj) - } - if len(list) != 1 || list[0].Name != "test" { - r.Fatalf("bad: %#v", list) - } - header := resp.Header().Get("X-Consul-Index") - if header == "" || header == "0" { - r.Fatalf("bad: %#v", header) - } - }) + list, ok := obj.([]*UserEvent) + if !ok { + r.Fatalf("bad: %#v", obj) + } + if len(list) != 1 || list[0].Name != "test" { + r.Fatalf("bad: %#v", list) + } + header := resp.Header().Get("X-Consul-Index") + if header == "" || header == "0" { + r.Fatalf("bad: %#v", header) + } }) } func TestEventList_Filter(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - p := &UserEvent{Name: "test"} - if err := srv.agent.UserEvent("dc1", "root", p); err != nil { - t.Fatalf("err: %v", err) + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + + p := &UserEvent{Name: "test"} + if err := a.UserEvent("dc1", "root", p); err != nil { + t.Fatalf("err: %v", err) + } + + p = &UserEvent{Name: "foo"} + if err := a.UserEvent("dc1", "root", p); err != nil { + t.Fatalf("err: %v", err) + } + + retry.Run(t, func(r *retry.R) { + req, _ := http.NewRequest("GET", "/v1/event/list?name=foo", nil) + resp := httptest.NewRecorder() + obj, err := a.srv.EventList(resp, req) + if err != nil { + r.Fatal(err) } - p = &UserEvent{Name: "foo"} - if err := srv.agent.UserEvent("dc1", "root", p); err != nil { - t.Fatalf("err: %v", err) + list, ok := obj.([]*UserEvent) + if !ok { + r.Fatalf("bad: %#v", obj) + } + if len(list) != 1 || list[0].Name != "foo" { + r.Fatalf("bad: %#v", list) + } + header := resp.Header().Get("X-Consul-Index") + if header == "" || header == "0" { + r.Fatalf("bad: %#v", header) } - - retry.Run(t, func(r *retry.R) { - req, _ := http.NewRequest("GET", "/v1/event/list?name=foo", nil) - resp := httptest.NewRecorder() - obj, err := srv.EventList(resp, req) - if err != nil { - r.Fatal(err) - } - - list, ok := obj.([]*UserEvent) - if !ok { - r.Fatalf("bad: %#v", obj) - } - if len(list) != 1 || list[0].Name != "foo" { - r.Fatalf("bad: %#v", list) - } - header := resp.Header().Get("X-Consul-Index") - if header == "" || header == "0" { - r.Fatalf("bad: %#v", header) - } - }) }) } @@ -230,89 +234,91 @@ func TestEventList_ACLFilter(t *testing.T) { func TestEventList_Blocking(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - p := &UserEvent{Name: "test"} - if err := srv.agent.UserEvent("dc1", "root", p); err != nil { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + + p := &UserEvent{Name: "test"} + if err := a.UserEvent("dc1", "root", p); err != nil { + t.Fatalf("err: %v", err) + } + + var index string + retry.Run(t, func(r *retry.R) { + req, _ := http.NewRequest("GET", "/v1/event/list", nil) + resp := httptest.NewRecorder() + if _, err := a.srv.EventList(resp, req); err != nil { + r.Fatal(err) + } + header := resp.Header().Get("X-Consul-Index") + if header == "" || header == "0" { + r.Fatalf("bad: %#v", header) + } + index = header + }) + + go func() { + time.Sleep(50 * time.Millisecond) + p := &UserEvent{Name: "second"} + if err := a.UserEvent("dc1", "root", p); err != nil { t.Fatalf("err: %v", err) } + }() - var index string - retry.Run(t, func(r *retry.R) { - req, _ := http.NewRequest("GET", "/v1/event/list", nil) - resp := httptest.NewRecorder() - if _, err := srv.EventList(resp, req); err != nil { - r.Fatal(err) - } - header := resp.Header().Get("X-Consul-Index") - if header == "" || header == "0" { - r.Fatalf("bad: %#v", header) - } - index = header - }) + retry.Run(t, func(r *retry.R) { + url := "/v1/event/list?index=" + index + req, _ := http.NewRequest("GET", url, nil) + resp := httptest.NewRecorder() + obj, err := a.srv.EventList(resp, req) + if err != nil { + r.Fatal(err) + } - go func() { - time.Sleep(50 * time.Millisecond) - p := &UserEvent{Name: "second"} - if err := srv.agent.UserEvent("dc1", "root", p); err != nil { - t.Fatalf("err: %v", err) - } - }() - - retry.Run(t, func(r *retry.R) { - url := "/v1/event/list?index=" + index - req, _ := http.NewRequest("GET", url, nil) - resp := httptest.NewRecorder() - obj, err := srv.EventList(resp, req) - if err != nil { - r.Fatal(err) - } - - list, ok := obj.([]*UserEvent) - if !ok { - r.Fatalf("bad: %#v", obj) - } - if len(list) != 2 || list[1].Name != "second" { - r.Fatalf("bad: %#v", list) - } - }) + list, ok := obj.([]*UserEvent) + if !ok { + r.Fatalf("bad: %#v", obj) + } + if len(list) != 2 || list[1].Name != "second" { + r.Fatalf("bad: %#v", list) + } }) } func TestEventList_EventBufOrder(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - // Fire some events in a non-sequential order - expected := &UserEvent{Name: "foo"} + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() - for _, e := range []*UserEvent{ - &UserEvent{Name: "foo"}, - &UserEvent{Name: "bar"}, - &UserEvent{Name: "foo"}, - expected, - &UserEvent{Name: "bar"}, - } { - if err := srv.agent.UserEvent("dc1", "root", e); err != nil { - t.Fatalf("err: %v", err) - } + // Fire some events in a non-sequential order + expected := &UserEvent{Name: "foo"} + + for _, e := range []*UserEvent{ + &UserEvent{Name: "foo"}, + &UserEvent{Name: "bar"}, + &UserEvent{Name: "foo"}, + expected, + &UserEvent{Name: "bar"}, + } { + if err := a.UserEvent("dc1", "root", e); err != nil { + t.Fatalf("err: %v", err) + } + } + // Test that the event order is preserved when name + // filtering on a list of > 1 matching event. + retry.Run(t, func(r *retry.R) { + url := "/v1/event/list?name=foo" + req, _ := http.NewRequest("GET", url, nil) + resp := httptest.NewRecorder() + obj, err := a.srv.EventList(resp, req) + if err != nil { + r.Fatal(err) + } + list, ok := obj.([]*UserEvent) + if !ok { + r.Fatalf("bad: %#v", obj) + } + if len(list) != 3 || list[2].ID != expected.ID { + r.Fatalf("bad: %#v", list) } - // Test that the event order is preserved when name - // filtering on a list of > 1 matching event. - retry.Run(t, func(r *retry.R) { - url := "/v1/event/list?name=foo" - req, _ := http.NewRequest("GET", url, nil) - resp := httptest.NewRecorder() - obj, err := srv.EventList(resp, req) - if err != nil { - r.Fatal(err) - } - list, ok := obj.([]*UserEvent) - if !ok { - r.Fatalf("bad: %#v", obj) - } - if len(list) != 3 || list[2].ID != expected.ID { - r.Fatalf("bad: %#v", list) - } - }) }) } diff --git a/command/agent/health_endpoint_test.go b/command/agent/health_endpoint_test.go index f9ff42cd86..68264b6dd1 100644 --- a/command/agent/health_endpoint_test.go +++ b/command/agent/health_endpoint_test.go @@ -15,11 +15,14 @@ import ( func TestHealthChecksInState(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + req, _ := http.NewRequest("GET", "/v1/health/state/warning?dc=dc1", nil) retry.Run(t, func(r *retry.R) { resp := httptest.NewRecorder() - obj, err := srv.HealthChecksInState(resp, req) + obj, err := a.srv.HealthChecksInState(resp, req) if err != nil { r.Fatal(err) } @@ -35,11 +38,14 @@ func TestHealthChecksInState(t *testing.T) { }) }) - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + req, _ := http.NewRequest("GET", "/v1/health/state/passing?dc=dc1", nil) retry.Run(t, func(r *retry.R) { resp := httptest.NewRecorder() - obj, err := srv.HealthChecksInState(resp, req) + obj, err := a.srv.HealthChecksInState(resp, req) if err != nil { r.Fatal(err) } @@ -58,40 +64,41 @@ func TestHealthChecksInState(t *testing.T) { func TestHealthChecksInState_NodeMetaFilter(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - args := &structs.RegisterRequest{ - Datacenter: "dc1", - Node: "bar", - Address: "127.0.0.1", - NodeMeta: map[string]string{"somekey": "somevalue"}, - Check: &structs.HealthCheck{ - Node: "bar", - Name: "node check", - Status: api.HealthCritical, - }, + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + + args := &structs.RegisterRequest{ + Datacenter: "dc1", + Node: "bar", + Address: "127.0.0.1", + NodeMeta: map[string]string{"somekey": "somevalue"}, + Check: &structs.HealthCheck{ + Node: "bar", + Name: "node check", + Status: api.HealthCritical, + }, + } + var out struct{} + if err := a.RPC("Catalog.Register", args, &out); err != nil { + t.Fatalf("err: %v", err) + } + + req, _ := http.NewRequest("GET", "/v1/health/state/critical?node-meta=somekey:somevalue", nil) + retry.Run(t, func(r *retry.R) { + resp := httptest.NewRecorder() + obj, err := a.srv.HealthChecksInState(resp, req) + if err != nil { + r.Fatal(err) } - var out struct{} - if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil { - t.Fatalf("err: %v", err) + if err := checkIndex(resp); err != nil { + r.Fatal(err) } - req, _ := http.NewRequest("GET", "/v1/health/state/critical?node-meta=somekey:somevalue", nil) - retry.Run(t, func(r *retry.R) { - resp := httptest.NewRecorder() - obj, err := srv.HealthChecksInState(resp, req) - if err != nil { - r.Fatal(err) - } - if err := checkIndex(resp); err != nil { - r.Fatal(err) - } - - // Should be 1 health check for the server - nodes := obj.(structs.HealthChecks) - if len(nodes) != 1 { - r.Fatalf("bad: %v", obj) - } - }) + // Should be 1 health check for the server + nodes := obj.(structs.HealthChecks) + if len(nodes) != 1 { + r.Fatalf("bad: %v", obj) + } }) } diff --git a/command/agent/http_test.go b/command/agent/http_test.go index 2d354de24e..24e8405148 100644 --- a/command/agent/http_test.go +++ b/command/agent/http_test.go @@ -481,53 +481,55 @@ func TestACLResolution(t *testing.T) { reqBothTokens, _ := http.NewRequest("GET", "/v1/catalog/nodes?token=baz", nil) reqBothTokens.Header.Add("X-Consul-Token", "zap") - httpTest(t, func(srv *HTTPServer) { - // Check when no token is set - srv.agent.config.ACLToken = "" - srv.parseToken(req, &token) - if token != "" { - t.Fatalf("bad: %s", token) - } + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() - // Check when ACLToken set - srv.agent.config.ACLToken = "agent" - srv.parseToken(req, &token) - if token != "agent" { - t.Fatalf("bad: %s", token) - } + // Check when no token is set + a.config.ACLToken = "" + a.srv.parseToken(req, &token) + if token != "" { + t.Fatalf("bad: %s", token) + } - // Explicit token has highest precedence - srv.parseToken(reqToken, &token) - if token != "foo" { - t.Fatalf("bad: %s", token) - } + // Check when ACLToken set + a.config.ACLToken = "agent" + a.srv.parseToken(req, &token) + if token != "agent" { + t.Fatalf("bad: %s", token) + } - // Header token has precedence over agent token - srv.parseToken(reqHeaderToken, &token) - if token != "bar" { - t.Fatalf("bad: %s", token) - } + // Explicit token has highest precedence + a.srv.parseToken(reqToken, &token) + if token != "foo" { + t.Fatalf("bad: %s", token) + } - // Querystring token has precedence over header and agent tokens - srv.parseToken(reqBothTokens, &token) - if token != "baz" { - t.Fatalf("bad: %s", token) - } - }) + // Header token has precedence over agent token + a.srv.parseToken(reqHeaderToken, &token) + if token != "bar" { + t.Fatalf("bad: %s", token) + } + + // Querystring token has precedence over header and agent tokens + a.srv.parseToken(reqBothTokens, &token) + if token != "baz" { + t.Fatalf("bad: %s", token) + } } func TestEnableWebUI(t *testing.T) { t.Parallel() - httpTestWithConfig(t, func(s *HTTPServer) { - req, _ := http.NewRequest("GET", "/ui/", nil) - resp := httptest.NewRecorder() - s.Handler.ServeHTTP(resp, req) - if resp.Code != 200 { - t.Fatalf("should handle ui") - } - }, func(c *Config) { - c.EnableUI = true - }) + conf := TestConfig() + conf.EnableUI = true + a := NewTestAgent(t.Name(), conf) + defer a.Shutdown() + + req, _ := http.NewRequest("GET", "/ui/", nil) + resp := httptest.NewRecorder() + a.srv.Handler.ServeHTTP(resp, req) + if resp.Code != 200 { + t.Fatalf("should handle ui") + } } // assertIndex tests that X-Consul-Index is set and non-zero @@ -560,20 +562,6 @@ func getIndex(t *testing.T, resp *httptest.ResponseRecorder) uint64 { return uint64(val) } -func httpTest(t *testing.T, f func(srv *HTTPServer)) { - httpTestWithConfig(t, f, nil) -} - -func httpTestWithConfig(t *testing.T, f func(srv *HTTPServer), cb func(c *Config)) { - c := TestConfig() - if cb != nil { - cb(c) - } - a := NewTestAgent(t.Name(), c) - defer a.Shutdown() - f(a.srv) -} - func isPermissionDenied(err error) bool { return err != nil && strings.Contains(err.Error(), errPermissionDenied.Error()) } diff --git a/command/agent/kvs_endpoint_test.go b/command/agent/kvs_endpoint_test.go index 039d6229e1..da6b7444b4 100644 --- a/command/agent/kvs_endpoint_test.go +++ b/command/agent/kvs_endpoint_test.go @@ -339,121 +339,125 @@ func TestKVSEndpoint_ListKeys(t *testing.T) { func TestKVSEndpoint_AcquireRelease(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - // Acquire the lock - id := makeTestSession(t, srv) - req, _ := http.NewRequest("PUT", "/v1/kv/test?acquire="+id, bytes.NewReader(nil)) - resp := httptest.NewRecorder() - obj, err := srv.KVSEndpoint(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - if res := obj.(bool); !res { - t.Fatalf("should work") - } + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() - // Verify we have the lock - req, _ = http.NewRequest("GET", "/v1/kv/test", nil) - resp = httptest.NewRecorder() - obj, err = srv.KVSEndpoint(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - d := obj.(structs.DirEntries)[0] + // Acquire the lock + id := makeTestSession(t, a.srv) + req, _ := http.NewRequest("PUT", "/v1/kv/test?acquire="+id, bytes.NewReader(nil)) + resp := httptest.NewRecorder() + obj, err := a.srv.KVSEndpoint(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + if res := obj.(bool); !res { + t.Fatalf("should work") + } - // Check the flags - if d.Session != id { - t.Fatalf("bad: %v", d) - } + // Verify we have the lock + req, _ = http.NewRequest("GET", "/v1/kv/test", nil) + resp = httptest.NewRecorder() + obj, err = a.srv.KVSEndpoint(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + d := obj.(structs.DirEntries)[0] - // Release the lock - req, _ = http.NewRequest("PUT", "/v1/kv/test?release="+id, bytes.NewReader(nil)) - resp = httptest.NewRecorder() - obj, err = srv.KVSEndpoint(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - if res := obj.(bool); !res { - t.Fatalf("should work") - } + // Check the flags + if d.Session != id { + t.Fatalf("bad: %v", d) + } - // Verify we do not have the lock - req, _ = http.NewRequest("GET", "/v1/kv/test", nil) - resp = httptest.NewRecorder() - obj, err = srv.KVSEndpoint(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - d = obj.(structs.DirEntries)[0] + // Release the lock + req, _ = http.NewRequest("PUT", "/v1/kv/test?release="+id, bytes.NewReader(nil)) + resp = httptest.NewRecorder() + obj, err = a.srv.KVSEndpoint(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + if res := obj.(bool); !res { + t.Fatalf("should work") + } - // Check the flags - if d.Session != "" { - t.Fatalf("bad: %v", d) - } - }) + // Verify we do not have the lock + req, _ = http.NewRequest("GET", "/v1/kv/test", nil) + resp = httptest.NewRecorder() + obj, err = a.srv.KVSEndpoint(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + d = obj.(structs.DirEntries)[0] + + // Check the flags + if d.Session != "" { + t.Fatalf("bad: %v", d) + } } func TestKVSEndpoint_GET_Raw(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - buf := bytes.NewBuffer([]byte("test")) - req, _ := http.NewRequest("PUT", "/v1/kv/test", buf) - resp := httptest.NewRecorder() - obj, err := srv.KVSEndpoint(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - if res := obj.(bool); !res { - t.Fatalf("should work") - } + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() - req, _ = http.NewRequest("GET", "/v1/kv/test?raw", nil) - resp = httptest.NewRecorder() - obj, err = srv.KVSEndpoint(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - assertIndex(t, resp) + buf := bytes.NewBuffer([]byte("test")) + req, _ := http.NewRequest("PUT", "/v1/kv/test", buf) + resp := httptest.NewRecorder() + obj, err := a.srv.KVSEndpoint(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + if res := obj.(bool); !res { + t.Fatalf("should work") + } - // Check the body - if !bytes.Equal(resp.Body.Bytes(), []byte("test")) { - t.Fatalf("bad: %s", resp.Body.Bytes()) - } - }) + req, _ = http.NewRequest("GET", "/v1/kv/test?raw", nil) + resp = httptest.NewRecorder() + obj, err = a.srv.KVSEndpoint(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + assertIndex(t, resp) + + // Check the body + if !bytes.Equal(resp.Body.Bytes(), []byte("test")) { + t.Fatalf("bad: %s", resp.Body.Bytes()) + } } func TestKVSEndpoint_PUT_ConflictingFlags(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - req, _ := http.NewRequest("PUT", "/v1/kv/test?cas=0&acquire=xxx", nil) - resp := httptest.NewRecorder() - if _, err := srv.KVSEndpoint(resp, req); err != nil { - t.Fatalf("err: %v", err) - } + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() - if resp.Code != 400 { - t.Fatalf("expected 400, got %d", resp.Code) - } - if !bytes.Contains(resp.Body.Bytes(), []byte("Conflicting")) { - t.Fatalf("expected conflicting args error") - } - }) + req, _ := http.NewRequest("PUT", "/v1/kv/test?cas=0&acquire=xxx", nil) + resp := httptest.NewRecorder() + if _, err := a.srv.KVSEndpoint(resp, req); err != nil { + t.Fatalf("err: %v", err) + } + + if resp.Code != 400 { + t.Fatalf("expected 400, got %d", resp.Code) + } + if !bytes.Contains(resp.Body.Bytes(), []byte("Conflicting")) { + t.Fatalf("expected conflicting args error") + } } func TestKVSEndpoint_DELETE_ConflictingFlags(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - req, _ := http.NewRequest("DELETE", "/v1/kv/test?recurse&cas=0", nil) - resp := httptest.NewRecorder() - if _, err := srv.KVSEndpoint(resp, req); err != nil { - t.Fatalf("err: %v", err) - } + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() - if resp.Code != 400 { - t.Fatalf("expected 400, got %d", resp.Code) - } - if !bytes.Contains(resp.Body.Bytes(), []byte("Conflicting")) { - t.Fatalf("expected conflicting args error") - } - }) + req, _ := http.NewRequest("DELETE", "/v1/kv/test?recurse&cas=0", nil) + resp := httptest.NewRecorder() + if _, err := a.srv.KVSEndpoint(resp, req); err != nil { + t.Fatalf("err: %v", err) + } + + if resp.Code != 400 { + t.Fatalf("expected 400, got %d", resp.Code) + } + if !bytes.Contains(resp.Body.Bytes(), []byte("Conflicting")) { + t.Fatalf("expected conflicting args error") + } } diff --git a/command/agent/operator_endpoint_test.go b/command/agent/operator_endpoint_test.go index 9a6666dd9b..f5ad07e1b3 100644 --- a/command/agent/operator_endpoint_test.go +++ b/command/agent/operator_endpoint_test.go @@ -16,51 +16,58 @@ import ( func TestOperator_RaftConfiguration(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - body := bytes.NewBuffer(nil) - req, _ := http.NewRequest("GET", "/v1/operator/raft/configuration", body) - resp := httptest.NewRecorder() - obj, err := srv.OperatorRaftConfiguration(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - if resp.Code != 200 { - t.Fatalf("bad code: %d", resp.Code) - } - out, ok := obj.(structs.RaftConfigurationResponse) - if !ok { - t.Fatalf("unexpected: %T", obj) - } - if len(out.Servers) != 1 || - !out.Servers[0].Leader || - !out.Servers[0].Voter { - t.Fatalf("bad: %v", out) - } - }) + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + + body := bytes.NewBuffer(nil) + req, _ := http.NewRequest("GET", "/v1/operator/raft/configuration", body) + resp := httptest.NewRecorder() + obj, err := a.srv.OperatorRaftConfiguration(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + if resp.Code != 200 { + t.Fatalf("bad code: %d", resp.Code) + } + out, ok := obj.(structs.RaftConfigurationResponse) + if !ok { + t.Fatalf("unexpected: %T", obj) + } + if len(out.Servers) != 1 || + !out.Servers[0].Leader || + !out.Servers[0].Voter { + t.Fatalf("bad: %v", out) + } } func TestOperator_RaftPeer(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + body := bytes.NewBuffer(nil) req, _ := http.NewRequest("DELETE", "/v1/operator/raft/peer?address=nope", body) // If we get this error, it proves we sent the address all the // way through. resp := httptest.NewRecorder() - _, err := srv.OperatorRaftPeer(resp, req) + _, err := a.srv.OperatorRaftPeer(resp, req) if err == nil || !strings.Contains(err.Error(), "address \"nope\" was not found in the Raft configuration") { t.Fatalf("err: %v", err) } }) - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + body := bytes.NewBuffer(nil) req, _ := http.NewRequest("DELETE", "/v1/operator/raft/peer?id=nope", body) // If we get this error, it proves we sent the ID all the // way through. resp := httptest.NewRecorder() - _, err := srv.OperatorRaftPeer(resp, req) + _, err := a.srv.OperatorRaftPeer(resp, req) if err == nil || !strings.Contains(err.Error(), "id \"nope\" was not found in the Raft configuration") { t.Fatalf("err: %v", err) @@ -72,391 +79,393 @@ func TestOperator_KeyringInstall(t *testing.T) { t.Parallel() oldKey := "H3/9gBxcKKRf45CaI2DlRg==" newKey := "z90lFx3sZZLtTOkutXcwYg==" - configFunc := func(c *Config) { - c.EncryptKey = oldKey + config := TestConfig() + config.EncryptKey = oldKey + a := NewTestAgent(t.Name(), config) + defer a.Shutdown() + + body := bytes.NewBufferString(fmt.Sprintf("{\"Key\":\"%s\"}", newKey)) + req, _ := http.NewRequest("POST", "/v1/operator/keyring", body) + resp := httptest.NewRecorder() + _, err := a.srv.OperatorKeyringEndpoint(resp, req) + if err != nil { + t.Fatalf("err: %s", err) } - httpTestWithConfig(t, func(srv *HTTPServer) { - body := bytes.NewBufferString(fmt.Sprintf("{\"Key\":\"%s\"}", newKey)) - req, _ := http.NewRequest("POST", "/v1/operator/keyring", body) - resp := httptest.NewRecorder() - _, err := srv.OperatorKeyringEndpoint(resp, req) - if err != nil { - t.Fatalf("err: %s", err) - } - listResponse, err := srv.agent.ListKeys("", 0) - if err != nil { - t.Fatalf("err: %s", err) - } - if len(listResponse.Responses) != 2 { - t.Fatalf("bad: %d", len(listResponse.Responses)) - } + listResponse, err := a.ListKeys("", 0) + if err != nil { + t.Fatalf("err: %s", err) + } + if len(listResponse.Responses) != 2 { + t.Fatalf("bad: %d", len(listResponse.Responses)) + } - for _, response := range listResponse.Responses { - count, ok := response.Keys[newKey] - if !ok { - t.Fatalf("bad: %v", response.Keys) - } - if count != response.NumNodes { - t.Fatalf("bad: %d, %d", count, response.NumNodes) - } + for _, response := range listResponse.Responses { + count, ok := response.Keys[newKey] + if !ok { + t.Fatalf("bad: %v", response.Keys) } - }, configFunc) + if count != response.NumNodes { + t.Fatalf("bad: %d, %d", count, response.NumNodes) + } + } } func TestOperator_KeyringList(t *testing.T) { t.Parallel() key := "H3/9gBxcKKRf45CaI2DlRg==" - configFunc := func(c *Config) { - c.EncryptKey = key + config := TestConfig() + config.EncryptKey = key + a := NewTestAgent(t.Name(), config) + defer a.Shutdown() + + req, _ := http.NewRequest("GET", "/v1/operator/keyring", nil) + resp := httptest.NewRecorder() + r, err := a.srv.OperatorKeyringEndpoint(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + responses, ok := r.([]*structs.KeyringResponse) + if !ok { + t.Fatalf("err: %v", !ok) } - httpTestWithConfig(t, func(srv *HTTPServer) { - req, _ := http.NewRequest("GET", "/v1/operator/keyring", nil) - resp := httptest.NewRecorder() - r, err := srv.OperatorKeyringEndpoint(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - responses, ok := r.([]*structs.KeyringResponse) - if !ok { - t.Fatalf("err: %v", !ok) - } - // Check that we get both a LAN and WAN response, and that they both only - // contain the original key - if len(responses) != 2 { - t.Fatalf("bad: %d", len(responses)) - } + // Check that we get both a LAN and WAN response, and that they both only + // contain the original key + if len(responses) != 2 { + t.Fatalf("bad: %d", len(responses)) + } - // WAN - if len(responses[0].Keys) != 1 { - t.Fatalf("bad: %d", len(responses[0].Keys)) - } - if !responses[0].WAN { - t.Fatalf("bad: %v", responses[0].WAN) - } - if _, ok := responses[0].Keys[key]; !ok { - t.Fatalf("bad: %v", ok) - } + // WAN + if len(responses[0].Keys) != 1 { + t.Fatalf("bad: %d", len(responses[0].Keys)) + } + if !responses[0].WAN { + t.Fatalf("bad: %v", responses[0].WAN) + } + if _, ok := responses[0].Keys[key]; !ok { + t.Fatalf("bad: %v", ok) + } - // LAN - if len(responses[1].Keys) != 1 { - t.Fatalf("bad: %d", len(responses[1].Keys)) - } - if responses[1].WAN { - t.Fatalf("bad: %v", responses[1].WAN) - } - if _, ok := responses[1].Keys[key]; !ok { - t.Fatalf("bad: %v", ok) - } - }, configFunc) + // LAN + if len(responses[1].Keys) != 1 { + t.Fatalf("bad: %d", len(responses[1].Keys)) + } + if responses[1].WAN { + t.Fatalf("bad: %v", responses[1].WAN) + } + if _, ok := responses[1].Keys[key]; !ok { + t.Fatalf("bad: %v", ok) + } } func TestOperator_KeyringRemove(t *testing.T) { t.Parallel() key := "H3/9gBxcKKRf45CaI2DlRg==" tempKey := "z90lFx3sZZLtTOkutXcwYg==" - configFunc := func(c *Config) { - c.EncryptKey = key + config := TestConfig() + config.EncryptKey = key + a := NewTestAgent(t.Name(), config) + defer a.Shutdown() + + _, err := a.InstallKey(tempKey, "", 0) + if err != nil { + t.Fatalf("err: %v", err) } - httpTestWithConfig(t, func(srv *HTTPServer) { - _, err := srv.agent.InstallKey(tempKey, "", 0) - if err != nil { - t.Fatalf("err: %v", err) - } - // Make sure the temp key is installed - list, err := srv.agent.ListKeys("", 0) - if err != nil { - t.Fatalf("err: %v", err) + // Make sure the temp key is installed + list, err := a.ListKeys("", 0) + if err != nil { + t.Fatalf("err: %v", err) + } + responses := list.Responses + if len(responses) != 2 { + t.Fatalf("bad: %d", len(responses)) + } + for _, response := range responses { + if len(response.Keys) != 2 { + t.Fatalf("bad: %d", len(response.Keys)) } - responses := list.Responses - if len(responses) != 2 { - t.Fatalf("bad: %d", len(responses)) - } - for _, response := range responses { - if len(response.Keys) != 2 { - t.Fatalf("bad: %d", len(response.Keys)) - } - if _, ok := response.Keys[tempKey]; !ok { - t.Fatalf("bad: %v", ok) - } + if _, ok := response.Keys[tempKey]; !ok { + t.Fatalf("bad: %v", ok) } + } - body := bytes.NewBufferString(fmt.Sprintf("{\"Key\":\"%s\"}", tempKey)) - req, _ := http.NewRequest("DELETE", "/v1/operator/keyring", body) - resp := httptest.NewRecorder() - if _, err := srv.OperatorKeyringEndpoint(resp, req); err != nil { - t.Fatalf("err: %s", err) - } + body := bytes.NewBufferString(fmt.Sprintf("{\"Key\":\"%s\"}", tempKey)) + req, _ := http.NewRequest("DELETE", "/v1/operator/keyring", body) + resp := httptest.NewRecorder() + if _, err := a.srv.OperatorKeyringEndpoint(resp, req); err != nil { + t.Fatalf("err: %s", err) + } - // Make sure the temp key has been removed - list, err = srv.agent.ListKeys("", 0) - if err != nil { - t.Fatalf("err: %v", err) + // Make sure the temp key has been removed + list, err = a.ListKeys("", 0) + if err != nil { + t.Fatalf("err: %v", err) + } + responses = list.Responses + if len(responses) != 2 { + t.Fatalf("bad: %d", len(responses)) + } + for _, response := range responses { + if len(response.Keys) != 1 { + t.Fatalf("bad: %d", len(response.Keys)) } - responses = list.Responses - if len(responses) != 2 { - t.Fatalf("bad: %d", len(responses)) + if _, ok := response.Keys[tempKey]; ok { + t.Fatalf("bad: %v", ok) } - for _, response := range responses { - if len(response.Keys) != 1 { - t.Fatalf("bad: %d", len(response.Keys)) - } - if _, ok := response.Keys[tempKey]; ok { - t.Fatalf("bad: %v", ok) - } - } - }, configFunc) + } } func TestOperator_KeyringUse(t *testing.T) { t.Parallel() oldKey := "H3/9gBxcKKRf45CaI2DlRg==" newKey := "z90lFx3sZZLtTOkutXcwYg==" - configFunc := func(c *Config) { - c.EncryptKey = oldKey + config := TestConfig() + config.EncryptKey = oldKey + a := NewTestAgent(t.Name(), config) + defer a.Shutdown() + + if _, err := a.InstallKey(newKey, "", 0); err != nil { + t.Fatalf("err: %v", err) } - httpTestWithConfig(t, func(srv *HTTPServer) { - if _, err := srv.agent.InstallKey(newKey, "", 0); err != nil { - t.Fatalf("err: %v", err) - } - body := bytes.NewBufferString(fmt.Sprintf("{\"Key\":\"%s\"}", newKey)) - req, _ := http.NewRequest("PUT", "/v1/operator/keyring", body) - resp := httptest.NewRecorder() - _, err := srv.OperatorKeyringEndpoint(resp, req) - if err != nil { - t.Fatalf("err: %s", err) - } + body := bytes.NewBufferString(fmt.Sprintf("{\"Key\":\"%s\"}", newKey)) + req, _ := http.NewRequest("PUT", "/v1/operator/keyring", body) + resp := httptest.NewRecorder() + _, err := a.srv.OperatorKeyringEndpoint(resp, req) + if err != nil { + t.Fatalf("err: %s", err) + } - if _, err := srv.agent.RemoveKey(oldKey, "", 0); err != nil { - t.Fatalf("err: %v", err) - } + if _, err := a.RemoveKey(oldKey, "", 0); err != nil { + t.Fatalf("err: %v", err) + } - // Make sure only the new key remains - list, err := srv.agent.ListKeys("", 0) - if err != nil { - t.Fatalf("err: %v", err) + // Make sure only the new key remains + list, err := a.ListKeys("", 0) + if err != nil { + t.Fatalf("err: %v", err) + } + responses := list.Responses + if len(responses) != 2 { + t.Fatalf("bad: %d", len(responses)) + } + for _, response := range responses { + if len(response.Keys) != 1 { + t.Fatalf("bad: %d", len(response.Keys)) } - responses := list.Responses - if len(responses) != 2 { - t.Fatalf("bad: %d", len(responses)) + if _, ok := response.Keys[newKey]; !ok { + t.Fatalf("bad: %v", ok) } - for _, response := range responses { - if len(response.Keys) != 1 { - t.Fatalf("bad: %d", len(response.Keys)) - } - if _, ok := response.Keys[newKey]; !ok { - t.Fatalf("bad: %v", ok) - } - } - }, configFunc) + } } func TestOperator_Keyring_InvalidRelayFactor(t *testing.T) { t.Parallel() key := "H3/9gBxcKKRf45CaI2DlRg==" - configFunc := func(c *Config) { - c.EncryptKey = key + config := TestConfig() + config.EncryptKey = key + a := NewTestAgent(t.Name(), config) + defer a.Shutdown() + + cases := map[string]string{ + "999": "Relay factor must be in range", + "asdf": "Error parsing relay factor", } - httpTestWithConfig(t, func(srv *HTTPServer) { - cases := map[string]string{ - "999": "Relay factor must be in range", - "asdf": "Error parsing relay factor", + for relayFactor, errString := range cases { + req, _ := http.NewRequest("GET", "/v1/operator/keyring?relay-factor="+relayFactor, nil) + resp := httptest.NewRecorder() + _, err := a.srv.OperatorKeyringEndpoint(resp, req) + if err != nil { + t.Fatalf("err: %v", err) } - for relayFactor, errString := range cases { - req, _ := http.NewRequest("GET", "/v1/operator/keyring?relay-factor="+relayFactor, nil) - resp := httptest.NewRecorder() - _, err := srv.OperatorKeyringEndpoint(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - body := resp.Body.String() - if !strings.Contains(body, errString) { - t.Fatalf("bad: %v", body) - } + body := resp.Body.String() + if !strings.Contains(body, errString) { + t.Fatalf("bad: %v", body) } - }, configFunc) + } } func TestOperator_AutopilotGetConfiguration(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - body := bytes.NewBuffer(nil) - req, _ := http.NewRequest("GET", "/v1/operator/autopilot/configuration", body) - resp := httptest.NewRecorder() - obj, err := srv.OperatorAutopilotConfiguration(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - if resp.Code != 200 { - t.Fatalf("bad code: %d", resp.Code) - } - out, ok := obj.(api.AutopilotConfiguration) - if !ok { - t.Fatalf("unexpected: %T", obj) - } - if !out.CleanupDeadServers { - t.Fatalf("bad: %#v", out) - } - }) + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + + body := bytes.NewBuffer(nil) + req, _ := http.NewRequest("GET", "/v1/operator/autopilot/configuration", body) + resp := httptest.NewRecorder() + obj, err := a.srv.OperatorAutopilotConfiguration(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + if resp.Code != 200 { + t.Fatalf("bad code: %d", resp.Code) + } + out, ok := obj.(api.AutopilotConfiguration) + if !ok { + t.Fatalf("unexpected: %T", obj) + } + if !out.CleanupDeadServers { + t.Fatalf("bad: %#v", out) + } } func TestOperator_AutopilotSetConfiguration(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - body := bytes.NewBuffer([]byte(`{"CleanupDeadServers": false}`)) - req, _ := http.NewRequest("PUT", "/v1/operator/autopilot/configuration", body) - resp := httptest.NewRecorder() - if _, err := srv.OperatorAutopilotConfiguration(resp, req); err != nil { - t.Fatalf("err: %v", err) - } - if resp.Code != 200 { - t.Fatalf("bad code: %d", resp.Code) - } + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() - args := structs.DCSpecificRequest{ - Datacenter: "dc1", - } + body := bytes.NewBuffer([]byte(`{"CleanupDeadServers": false}`)) + req, _ := http.NewRequest("PUT", "/v1/operator/autopilot/configuration", body) + resp := httptest.NewRecorder() + if _, err := a.srv.OperatorAutopilotConfiguration(resp, req); err != nil { + t.Fatalf("err: %v", err) + } + if resp.Code != 200 { + t.Fatalf("bad code: %d", resp.Code) + } - var reply structs.AutopilotConfig - if err := srv.agent.RPC("Operator.AutopilotGetConfiguration", &args, &reply); err != nil { - t.Fatalf("err: %v", err) - } - if reply.CleanupDeadServers { - t.Fatalf("bad: %#v", reply) - } - }) + args := structs.DCSpecificRequest{ + Datacenter: "dc1", + } + + var reply structs.AutopilotConfig + if err := a.RPC("Operator.AutopilotGetConfiguration", &args, &reply); err != nil { + t.Fatalf("err: %v", err) + } + if reply.CleanupDeadServers { + t.Fatalf("bad: %#v", reply) + } } func TestOperator_AutopilotCASConfiguration(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - body := bytes.NewBuffer([]byte(`{"CleanupDeadServers": false}`)) - req, _ := http.NewRequest("PUT", "/v1/operator/autopilot/configuration", body) + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + + body := bytes.NewBuffer([]byte(`{"CleanupDeadServers": false}`)) + req, _ := http.NewRequest("PUT", "/v1/operator/autopilot/configuration", body) + resp := httptest.NewRecorder() + if _, err := a.srv.OperatorAutopilotConfiguration(resp, req); err != nil { + t.Fatalf("err: %v", err) + } + if resp.Code != 200 { + t.Fatalf("bad code: %d", resp.Code) + } + + args := structs.DCSpecificRequest{ + Datacenter: "dc1", + } + + var reply structs.AutopilotConfig + if err := a.RPC("Operator.AutopilotGetConfiguration", &args, &reply); err != nil { + t.Fatalf("err: %v", err) + } + + if reply.CleanupDeadServers { + t.Fatalf("bad: %#v", reply) + } + + // Create a CAS request, bad index + { + buf := bytes.NewBuffer([]byte(`{"CleanupDeadServers": true}`)) + req, _ := http.NewRequest("PUT", fmt.Sprintf("/v1/operator/autopilot/configuration?cas=%d", reply.ModifyIndex-1), buf) resp := httptest.NewRecorder() - if _, err := srv.OperatorAutopilotConfiguration(resp, req); err != nil { - t.Fatalf("err: %v", err) - } - if resp.Code != 200 { - t.Fatalf("bad code: %d", resp.Code) - } - - args := structs.DCSpecificRequest{ - Datacenter: "dc1", - } - - var reply structs.AutopilotConfig - if err := srv.agent.RPC("Operator.AutopilotGetConfiguration", &args, &reply); err != nil { + obj, err := a.srv.OperatorAutopilotConfiguration(resp, req) + if err != nil { t.Fatalf("err: %v", err) } - if reply.CleanupDeadServers { - t.Fatalf("bad: %#v", reply) + if res := obj.(bool); res { + t.Fatalf("should NOT work") } + } - // Create a CAS request, bad index - { - buf := bytes.NewBuffer([]byte(`{"CleanupDeadServers": true}`)) - req, _ := http.NewRequest("PUT", fmt.Sprintf("/v1/operator/autopilot/configuration?cas=%d", reply.ModifyIndex-1), buf) - resp := httptest.NewRecorder() - obj, err := srv.OperatorAutopilotConfiguration(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - - if res := obj.(bool); res { - t.Fatalf("should NOT work") - } - } - - // Create a CAS request, good index - { - buf := bytes.NewBuffer([]byte(`{"CleanupDeadServers": true}`)) - req, _ := http.NewRequest("PUT", fmt.Sprintf("/v1/operator/autopilot/configuration?cas=%d", reply.ModifyIndex), buf) - resp := httptest.NewRecorder() - obj, err := srv.OperatorAutopilotConfiguration(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - - if res := obj.(bool); !res { - t.Fatalf("should work") - } - } - - // Verify the update - if err := srv.agent.RPC("Operator.AutopilotGetConfiguration", &args, &reply); err != nil { + // Create a CAS request, good index + { + buf := bytes.NewBuffer([]byte(`{"CleanupDeadServers": true}`)) + req, _ := http.NewRequest("PUT", fmt.Sprintf("/v1/operator/autopilot/configuration?cas=%d", reply.ModifyIndex), buf) + resp := httptest.NewRecorder() + obj, err := a.srv.OperatorAutopilotConfiguration(resp, req) + if err != nil { t.Fatalf("err: %v", err) } - if !reply.CleanupDeadServers { - t.Fatalf("bad: %#v", reply) + + if res := obj.(bool); !res { + t.Fatalf("should work") } - }) + } + + // Verify the update + if err := a.RPC("Operator.AutopilotGetConfiguration", &args, &reply); err != nil { + t.Fatalf("err: %v", err) + } + if !reply.CleanupDeadServers { + t.Fatalf("bad: %#v", reply) + } } func TestOperator_ServerHealth(t *testing.T) { t.Parallel() - cb := func(c *Config) { - c.RaftProtocol = 3 - } - httpTestWithConfig(t, func(srv *HTTPServer) { - body := bytes.NewBuffer(nil) - req, _ := http.NewRequest("GET", "/v1/operator/autopilot/health", body) - retry.Run(t, func(r *retry.R) { - resp := httptest.NewRecorder() - obj, err := srv.OperatorServerHealth(resp, req) - if err != nil { - r.Fatalf("err: %v", err) - } - if resp.Code != 200 { - r.Fatalf("bad code: %d", resp.Code) - } - out, ok := obj.(*api.OperatorHealthReply) - if !ok { - r.Fatalf("unexpected: %T", obj) - } - if len(out.Servers) != 1 || - !out.Servers[0].Healthy || - out.Servers[0].Name != srv.agent.config.NodeName || - out.Servers[0].SerfStatus != "alive" || - out.FailureTolerance != 0 { - r.Fatalf("bad: %v", out) - } - }) - }, cb) + config := TestConfig() + config.RaftProtocol = 3 + a := NewTestAgent(t.Name(), config) + defer a.Shutdown() + + body := bytes.NewBuffer(nil) + req, _ := http.NewRequest("GET", "/v1/operator/autopilot/health", body) + retry.Run(t, func(r *retry.R) { + resp := httptest.NewRecorder() + obj, err := a.srv.OperatorServerHealth(resp, req) + if err != nil { + r.Fatalf("err: %v", err) + } + if resp.Code != 200 { + r.Fatalf("bad code: %d", resp.Code) + } + out, ok := obj.(*api.OperatorHealthReply) + if !ok { + r.Fatalf("unexpected: %T", obj) + } + if len(out.Servers) != 1 || + !out.Servers[0].Healthy || + out.Servers[0].Name != a.config.NodeName || + out.Servers[0].SerfStatus != "alive" || + out.FailureTolerance != 0 { + r.Fatalf("bad: %v", out) + } + }) } func TestOperator_ServerHealth_Unhealthy(t *testing.T) { t.Parallel() - cb := func(c *Config) { - c.RaftProtocol = 3 + config := TestConfig() + config.RaftProtocol = 3 + threshold := time.Duration(-1) + config.Autopilot.LastContactThreshold = &threshold + a := NewTestAgent(t.Name(), config) + defer a.Shutdown() - threshold := time.Duration(-1) - c.Autopilot.LastContactThreshold = &threshold - } - httpTestWithConfig(t, func(srv *HTTPServer) { - body := bytes.NewBuffer(nil) - req, _ := http.NewRequest("GET", "/v1/operator/autopilot/health", body) - retry.Run(t, func(r *retry.R) { - resp := httptest.NewRecorder() - obj, err := srv.OperatorServerHealth(resp, req) - if err != nil { - r.Fatalf("err: %v", err) - } - if resp.Code != 429 { - r.Fatalf("bad code: %d", resp.Code) - } - out, ok := obj.(*api.OperatorHealthReply) - if !ok { - r.Fatalf("unexpected: %T", obj) - } - if len(out.Servers) != 1 || - out.Healthy || - out.Servers[0].Name != srv.agent.config.NodeName { - r.Fatalf("bad: %#v", out.Servers) - } - }) - }, cb) + body := bytes.NewBuffer(nil) + req, _ := http.NewRequest("GET", "/v1/operator/autopilot/health", body) + retry.Run(t, func(r *retry.R) { + resp := httptest.NewRecorder() + obj, err := a.srv.OperatorServerHealth(resp, req) + if err != nil { + r.Fatalf("err: %v", err) + } + if resp.Code != 429 { + r.Fatalf("bad code: %d", resp.Code) + } + out, ok := obj.(*api.OperatorHealthReply) + if !ok { + r.Fatalf("unexpected: %T", obj) + } + if len(out.Servers) != 1 || + out.Healthy || + out.Servers[0].Name != a.config.NodeName { + r.Fatalf("bad: %#v", out.Servers) + } + }) } diff --git a/command/agent/prepared_query_endpoint_test.go b/command/agent/prepared_query_endpoint_test.go index f613d53152..484573dd5e 100644 --- a/command/agent/prepared_query_endpoint_test.go +++ b/command/agent/prepared_query_endpoint_test.go @@ -70,92 +70,96 @@ func (m *MockPreparedQuery) Explain(args *structs.PreparedQueryExecuteRequest, func TestPreparedQuery_Create(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - m := MockPreparedQuery{} - if err := srv.agent.InjectEndpoint("PreparedQuery", &m); err != nil { - t.Fatalf("err: %v", err) - } + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() - m.applyFn = func(args *structs.PreparedQueryRequest, reply *string) error { - expected := &structs.PreparedQueryRequest{ - Datacenter: "dc1", - Op: structs.PreparedQueryCreate, - Query: &structs.PreparedQuery{ - Name: "my-query", - Session: "my-session", - Service: structs.ServiceQuery{ - Service: "my-service", - Failover: structs.QueryDatacenterOptions{ - NearestN: 4, - Datacenters: []string{"dc1", "dc2"}, - }, - OnlyPassing: true, - Tags: []string{"foo", "bar"}, - NodeMeta: map[string]string{"somekey": "somevalue"}, - }, - DNS: structs.QueryDNSOptions{ - TTL: "10s", + m := MockPreparedQuery{} + if err := a.InjectEndpoint("PreparedQuery", &m); err != nil { + t.Fatalf("err: %v", err) + } + + m.applyFn = func(args *structs.PreparedQueryRequest, reply *string) error { + expected := &structs.PreparedQueryRequest{ + Datacenter: "dc1", + Op: structs.PreparedQueryCreate, + Query: &structs.PreparedQuery{ + Name: "my-query", + Session: "my-session", + Service: structs.ServiceQuery{ + Service: "my-service", + Failover: structs.QueryDatacenterOptions{ + NearestN: 4, + Datacenters: []string{"dc1", "dc2"}, }, + OnlyPassing: true, + Tags: []string{"foo", "bar"}, + NodeMeta: map[string]string{"somekey": "somevalue"}, }, - WriteRequest: structs.WriteRequest{ - Token: "my-token", + DNS: structs.QueryDNSOptions{ + TTL: "10s", }, - } - if !reflect.DeepEqual(args, expected) { - t.Fatalf("bad: %v", args) - } - - *reply = "my-id" - return nil - } - - body := bytes.NewBuffer(nil) - enc := json.NewEncoder(body) - raw := map[string]interface{}{ - "Name": "my-query", - "Session": "my-session", - "Service": map[string]interface{}{ - "Service": "my-service", - "Failover": map[string]interface{}{ - "NearestN": 4, - "Datacenters": []string{"dc1", "dc2"}, - }, - "OnlyPassing": true, - "Tags": []string{"foo", "bar"}, - "NodeMeta": map[string]string{"somekey": "somevalue"}, }, - "DNS": map[string]interface{}{ - "TTL": "10s", + WriteRequest: structs.WriteRequest{ + Token: "my-token", }, } - if err := enc.Encode(raw); err != nil { - t.Fatalf("err: %v", err) + if !reflect.DeepEqual(args, expected) { + t.Fatalf("bad: %v", args) } - req, _ := http.NewRequest("POST", "/v1/query?token=my-token", body) - resp := httptest.NewRecorder() - obj, err := srv.PreparedQueryGeneral(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - if resp.Code != 200 { - t.Fatalf("bad code: %d", resp.Code) - } - r, ok := obj.(preparedQueryCreateResponse) - if !ok { - t.Fatalf("unexpected: %T", obj) - } - if r.ID != "my-id" { - t.Fatalf("bad ID: %s", r.ID) - } - }) + *reply = "my-id" + return nil + } + + body := bytes.NewBuffer(nil) + enc := json.NewEncoder(body) + raw := map[string]interface{}{ + "Name": "my-query", + "Session": "my-session", + "Service": map[string]interface{}{ + "Service": "my-service", + "Failover": map[string]interface{}{ + "NearestN": 4, + "Datacenters": []string{"dc1", "dc2"}, + }, + "OnlyPassing": true, + "Tags": []string{"foo", "bar"}, + "NodeMeta": map[string]string{"somekey": "somevalue"}, + }, + "DNS": map[string]interface{}{ + "TTL": "10s", + }, + } + if err := enc.Encode(raw); err != nil { + t.Fatalf("err: %v", err) + } + + req, _ := http.NewRequest("POST", "/v1/query?token=my-token", body) + resp := httptest.NewRecorder() + obj, err := a.srv.PreparedQueryGeneral(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + if resp.Code != 200 { + t.Fatalf("bad code: %d", resp.Code) + } + r, ok := obj.(preparedQueryCreateResponse) + if !ok { + t.Fatalf("unexpected: %T", obj) + } + if r.ID != "my-id" { + t.Fatalf("bad ID: %s", r.ID) + } } func TestPreparedQuery_List(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + m := MockPreparedQuery{} - if err := srv.agent.InjectEndpoint("PreparedQuery", &m); err != nil { + if err := a.InjectEndpoint("PreparedQuery", &m); err != nil { t.Fatalf("err: %v", err) } @@ -167,7 +171,7 @@ func TestPreparedQuery_List(t *testing.T) { body := bytes.NewBuffer(nil) req, _ := http.NewRequest("GET", "/v1/query", body) resp := httptest.NewRecorder() - obj, err := srv.PreparedQueryGeneral(resp, req) + obj, err := a.srv.PreparedQueryGeneral(resp, req) if err != nil { t.Fatalf("err: %v", err) } @@ -183,9 +187,12 @@ func TestPreparedQuery_List(t *testing.T) { } }) - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + m := MockPreparedQuery{} - if err := srv.agent.InjectEndpoint("PreparedQuery", &m); err != nil { + if err := a.InjectEndpoint("PreparedQuery", &m); err != nil { t.Fatalf("err: %v", err) } @@ -211,7 +218,7 @@ func TestPreparedQuery_List(t *testing.T) { body := bytes.NewBuffer(nil) req, _ := http.NewRequest("GET", "/v1/query?token=my-token&consistent=true", body) resp := httptest.NewRecorder() - obj, err := srv.PreparedQueryGeneral(resp, req) + obj, err := a.srv.PreparedQueryGeneral(resp, req) if err != nil { t.Fatalf("err: %v", err) } @@ -230,9 +237,12 @@ func TestPreparedQuery_List(t *testing.T) { func TestPreparedQuery_Execute(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + m := MockPreparedQuery{} - if err := srv.agent.InjectEndpoint("PreparedQuery", &m); err != nil { + if err := a.InjectEndpoint("PreparedQuery", &m); err != nil { t.Fatalf("err: %v", err) } @@ -244,7 +254,7 @@ func TestPreparedQuery_Execute(t *testing.T) { body := bytes.NewBuffer(nil) req, _ := http.NewRequest("GET", "/v1/query/my-id/execute", body) resp := httptest.NewRecorder() - obj, err := srv.PreparedQuerySpecific(resp, req) + obj, err := a.srv.PreparedQuerySpecific(resp, req) if err != nil { t.Fatalf("err: %v", err) } @@ -260,9 +270,12 @@ func TestPreparedQuery_Execute(t *testing.T) { } }) - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + m := MockPreparedQuery{} - if err := srv.agent.InjectEndpoint("PreparedQuery", &m); err != nil { + if err := a.InjectEndpoint("PreparedQuery", &m); err != nil { t.Fatalf("err: %v", err) } @@ -276,8 +289,8 @@ func TestPreparedQuery_Execute(t *testing.T) { Node: "my-node", }, Agent: structs.QuerySource{ - Datacenter: srv.agent.config.Datacenter, - Node: srv.agent.config.NodeName, + Datacenter: a.config.Datacenter, + Node: a.config.NodeName, }, QueryOptions: structs.QueryOptions{ Token: "my-token", @@ -296,7 +309,7 @@ func TestPreparedQuery_Execute(t *testing.T) { body := bytes.NewBuffer(nil) req, _ := http.NewRequest("GET", "/v1/query/my-id/execute?token=my-token&consistent=true&near=my-node&limit=5", body) resp := httptest.NewRecorder() - obj, err := srv.PreparedQuerySpecific(resp, req) + obj, err := a.srv.PreparedQuerySpecific(resp, req) if err != nil { t.Fatalf("err: %v", err) } @@ -313,9 +326,12 @@ func TestPreparedQuery_Execute(t *testing.T) { }) // Ensure the proper params are set when no special args are passed - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + m := MockPreparedQuery{} - if err := srv.agent.InjectEndpoint("PreparedQuery", &m); err != nil { + if err := a.InjectEndpoint("PreparedQuery", &m); err != nil { t.Fatalf("err: %v", err) } @@ -324,8 +340,8 @@ func TestPreparedQuery_Execute(t *testing.T) { t.Fatalf("expect node to be empty, got %q", args.Source.Node) } expect := structs.QuerySource{ - Datacenter: srv.agent.config.Datacenter, - Node: srv.agent.config.NodeName, + Datacenter: a.config.Datacenter, + Node: a.config.NodeName, } if !reflect.DeepEqual(args.Agent, expect) { t.Fatalf("expect: %#v\nactual: %#v", expect, args.Agent) @@ -335,15 +351,21 @@ func TestPreparedQuery_Execute(t *testing.T) { req, _ := http.NewRequest("GET", "/v1/query/my-id/execute", nil) resp := httptest.NewRecorder() - if _, err := srv.PreparedQuerySpecific(resp, req); err != nil { + if _, err := a.srv.PreparedQuerySpecific(resp, req); err != nil { t.Fatalf("err: %v", err) } }) // Ensure WAN translation occurs for a response outside of the local DC. - httpTestWithConfig(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + config := TestConfig() + config.Datacenter = "dc1" + config.TranslateWanAddrs = true + a := NewTestAgent(t.Name(), config) + defer a.Shutdown() + m := MockPreparedQuery{} - if err := srv.agent.InjectEndpoint("PreparedQuery", &m); err != nil { + if err := a.InjectEndpoint("PreparedQuery", &m); err != nil { t.Fatalf("err: %v", err) } @@ -363,7 +385,7 @@ func TestPreparedQuery_Execute(t *testing.T) { body := bytes.NewBuffer(nil) req, _ := http.NewRequest("GET", "/v1/query/my-id/execute?dc=dc2", body) resp := httptest.NewRecorder() - obj, err := srv.PreparedQuerySpecific(resp, req) + obj, err := a.srv.PreparedQuerySpecific(resp, req) if err != nil { t.Fatalf("err: %v", err) } @@ -382,15 +404,18 @@ func TestPreparedQuery_Execute(t *testing.T) { if node.Node.Address != "127.0.0.2" { t.Fatalf("bad: %v", node.Node) } - }, func(c *Config) { - c.Datacenter = "dc1" - c.TranslateWanAddrs = true }) // Ensure WAN translation doesn't occur for the local DC. - httpTestWithConfig(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + config := TestConfig() + config.Datacenter = "dc1" + config.TranslateWanAddrs = true + a := NewTestAgent(t.Name(), config) + defer a.Shutdown() + m := MockPreparedQuery{} - if err := srv.agent.InjectEndpoint("PreparedQuery", &m); err != nil { + if err := a.InjectEndpoint("PreparedQuery", &m); err != nil { t.Fatalf("err: %v", err) } @@ -410,7 +435,7 @@ func TestPreparedQuery_Execute(t *testing.T) { body := bytes.NewBuffer(nil) req, _ := http.NewRequest("GET", "/v1/query/my-id/execute?dc=dc2", body) resp := httptest.NewRecorder() - obj, err := srv.PreparedQuerySpecific(resp, req) + obj, err := a.srv.PreparedQuerySpecific(resp, req) if err != nil { t.Fatalf("err: %v", err) } @@ -429,16 +454,16 @@ func TestPreparedQuery_Execute(t *testing.T) { if node.Node.Address != "127.0.0.1" { t.Fatalf("bad: %v", node.Node) } - }, func(c *Config) { - c.Datacenter = "dc1" - c.TranslateWanAddrs = true }) - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + body := bytes.NewBuffer(nil) req, _ := http.NewRequest("GET", "/v1/query/not-there/execute", body) resp := httptest.NewRecorder() - if _, err := srv.PreparedQuerySpecific(resp, req); err != nil { + if _, err := a.srv.PreparedQuerySpecific(resp, req); err != nil { t.Fatalf("err: %v", err) } if resp.Code != 404 { @@ -449,9 +474,12 @@ func TestPreparedQuery_Execute(t *testing.T) { func TestPreparedQuery_Explain(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + m := MockPreparedQuery{} - if err := srv.agent.InjectEndpoint("PreparedQuery", &m); err != nil { + if err := a.InjectEndpoint("PreparedQuery", &m); err != nil { t.Fatalf("err: %v", err) } @@ -465,8 +493,8 @@ func TestPreparedQuery_Explain(t *testing.T) { Node: "my-node", }, Agent: structs.QuerySource{ - Datacenter: srv.agent.config.Datacenter, - Node: srv.agent.config.NodeName, + Datacenter: a.config.Datacenter, + Node: a.config.NodeName, }, QueryOptions: structs.QueryOptions{ Token: "my-token", @@ -485,7 +513,7 @@ func TestPreparedQuery_Explain(t *testing.T) { body := bytes.NewBuffer(nil) req, _ := http.NewRequest("GET", "/v1/query/my-id/explain?token=my-token&consistent=true&near=my-node&limit=5", body) resp := httptest.NewRecorder() - obj, err := srv.PreparedQuerySpecific(resp, req) + obj, err := a.srv.PreparedQuerySpecific(resp, req) if err != nil { t.Fatalf("err: %v", err) } @@ -501,11 +529,14 @@ func TestPreparedQuery_Explain(t *testing.T) { } }) - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + body := bytes.NewBuffer(nil) req, _ := http.NewRequest("GET", "/v1/query/not-there/explain", body) resp := httptest.NewRecorder() - if _, err := srv.PreparedQuerySpecific(resp, req); err != nil { + if _, err := a.srv.PreparedQuerySpecific(resp, req); err != nil { t.Fatalf("err: %v", err) } if resp.Code != 404 { @@ -516,9 +547,12 @@ func TestPreparedQuery_Explain(t *testing.T) { func TestPreparedQuery_Get(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + m := MockPreparedQuery{} - if err := srv.agent.InjectEndpoint("PreparedQuery", &m); err != nil { + if err := a.InjectEndpoint("PreparedQuery", &m); err != nil { t.Fatalf("err: %v", err) } @@ -545,7 +579,7 @@ func TestPreparedQuery_Get(t *testing.T) { body := bytes.NewBuffer(nil) req, _ := http.NewRequest("GET", "/v1/query/my-id?token=my-token&consistent=true", body) resp := httptest.NewRecorder() - obj, err := srv.PreparedQuerySpecific(resp, req) + obj, err := a.srv.PreparedQuerySpecific(resp, req) if err != nil { t.Fatalf("err: %v", err) } @@ -561,11 +595,14 @@ func TestPreparedQuery_Get(t *testing.T) { } }) - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + body := bytes.NewBuffer(nil) req, _ := http.NewRequest("GET", "/v1/query/f004177f-2c28-83b7-4229-eacc25fe55d1", body) resp := httptest.NewRecorder() - if _, err := srv.PreparedQuerySpecific(resp, req); err != nil { + if _, err := a.srv.PreparedQuerySpecific(resp, req); err != nil { t.Fatalf("err: %v", err) } if resp.Code != 404 { @@ -576,135 +613,140 @@ func TestPreparedQuery_Get(t *testing.T) { func TestPreparedQuery_Update(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - m := MockPreparedQuery{} - if err := srv.agent.InjectEndpoint("PreparedQuery", &m); err != nil { - t.Fatalf("err: %v", err) - } + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() - m.applyFn = func(args *structs.PreparedQueryRequest, reply *string) error { - expected := &structs.PreparedQueryRequest{ - Datacenter: "dc1", - Op: structs.PreparedQueryUpdate, - Query: &structs.PreparedQuery{ - ID: "my-id", - Name: "my-query", - Session: "my-session", - Service: structs.ServiceQuery{ - Service: "my-service", - Failover: structs.QueryDatacenterOptions{ - NearestN: 4, - Datacenters: []string{"dc1", "dc2"}, - }, - OnlyPassing: true, - Tags: []string{"foo", "bar"}, - NodeMeta: map[string]string{"somekey": "somevalue"}, - }, - DNS: structs.QueryDNSOptions{ - TTL: "10s", + m := MockPreparedQuery{} + if err := a.InjectEndpoint("PreparedQuery", &m); err != nil { + t.Fatalf("err: %v", err) + } + + m.applyFn = func(args *structs.PreparedQueryRequest, reply *string) error { + expected := &structs.PreparedQueryRequest{ + Datacenter: "dc1", + Op: structs.PreparedQueryUpdate, + Query: &structs.PreparedQuery{ + ID: "my-id", + Name: "my-query", + Session: "my-session", + Service: structs.ServiceQuery{ + Service: "my-service", + Failover: structs.QueryDatacenterOptions{ + NearestN: 4, + Datacenters: []string{"dc1", "dc2"}, }, + OnlyPassing: true, + Tags: []string{"foo", "bar"}, + NodeMeta: map[string]string{"somekey": "somevalue"}, }, - WriteRequest: structs.WriteRequest{ - Token: "my-token", + DNS: structs.QueryDNSOptions{ + TTL: "10s", }, - } - if !reflect.DeepEqual(args, expected) { - t.Fatalf("bad: %v", args) - } - - *reply = "don't care" - return nil - } - - body := bytes.NewBuffer(nil) - enc := json.NewEncoder(body) - raw := map[string]interface{}{ - "ID": "this should get ignored", - "Name": "my-query", - "Session": "my-session", - "Service": map[string]interface{}{ - "Service": "my-service", - "Failover": map[string]interface{}{ - "NearestN": 4, - "Datacenters": []string{"dc1", "dc2"}, - }, - "OnlyPassing": true, - "Tags": []string{"foo", "bar"}, - "NodeMeta": map[string]string{"somekey": "somevalue"}, }, - "DNS": map[string]interface{}{ - "TTL": "10s", + WriteRequest: structs.WriteRequest{ + Token: "my-token", }, } - if err := enc.Encode(raw); err != nil { - t.Fatalf("err: %v", err) + if !reflect.DeepEqual(args, expected) { + t.Fatalf("bad: %v", args) } - req, _ := http.NewRequest("PUT", "/v1/query/my-id?token=my-token", body) - resp := httptest.NewRecorder() - if _, err := srv.PreparedQuerySpecific(resp, req); err != nil { - t.Fatalf("err: %v", err) - } - if resp.Code != 200 { - t.Fatalf("bad code: %d", resp.Code) - } - }) + *reply = "don't care" + return nil + } + + body := bytes.NewBuffer(nil) + enc := json.NewEncoder(body) + raw := map[string]interface{}{ + "ID": "this should get ignored", + "Name": "my-query", + "Session": "my-session", + "Service": map[string]interface{}{ + "Service": "my-service", + "Failover": map[string]interface{}{ + "NearestN": 4, + "Datacenters": []string{"dc1", "dc2"}, + }, + "OnlyPassing": true, + "Tags": []string{"foo", "bar"}, + "NodeMeta": map[string]string{"somekey": "somevalue"}, + }, + "DNS": map[string]interface{}{ + "TTL": "10s", + }, + } + if err := enc.Encode(raw); err != nil { + t.Fatalf("err: %v", err) + } + + req, _ := http.NewRequest("PUT", "/v1/query/my-id?token=my-token", body) + resp := httptest.NewRecorder() + if _, err := a.srv.PreparedQuerySpecific(resp, req); err != nil { + t.Fatalf("err: %v", err) + } + if resp.Code != 200 { + t.Fatalf("bad code: %d", resp.Code) + } } func TestPreparedQuery_Delete(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - m := MockPreparedQuery{} - if err := srv.agent.InjectEndpoint("PreparedQuery", &m); err != nil { - t.Fatalf("err: %v", err) + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + + m := MockPreparedQuery{} + if err := a.InjectEndpoint("PreparedQuery", &m); err != nil { + t.Fatalf("err: %v", err) + } + + m.applyFn = func(args *structs.PreparedQueryRequest, reply *string) error { + expected := &structs.PreparedQueryRequest{ + Datacenter: "dc1", + Op: structs.PreparedQueryDelete, + Query: &structs.PreparedQuery{ + ID: "my-id", + }, + WriteRequest: structs.WriteRequest{ + Token: "my-token", + }, + } + if !reflect.DeepEqual(args, expected) { + t.Fatalf("bad: %v", args) } - m.applyFn = func(args *structs.PreparedQueryRequest, reply *string) error { - expected := &structs.PreparedQueryRequest{ - Datacenter: "dc1", - Op: structs.PreparedQueryDelete, - Query: &structs.PreparedQuery{ - ID: "my-id", - }, - WriteRequest: structs.WriteRequest{ - Token: "my-token", - }, - } - if !reflect.DeepEqual(args, expected) { - t.Fatalf("bad: %v", args) - } + *reply = "don't care" + return nil + } - *reply = "don't care" - return nil - } + body := bytes.NewBuffer(nil) + enc := json.NewEncoder(body) + raw := map[string]interface{}{ + "ID": "this should get ignored", + } + if err := enc.Encode(raw); err != nil { + t.Fatalf("err: %v", err) + } - body := bytes.NewBuffer(nil) - enc := json.NewEncoder(body) - raw := map[string]interface{}{ - "ID": "this should get ignored", - } - if err := enc.Encode(raw); err != nil { - t.Fatalf("err: %v", err) - } - - req, _ := http.NewRequest("DELETE", "/v1/query/my-id?token=my-token", body) - resp := httptest.NewRecorder() - if _, err := srv.PreparedQuerySpecific(resp, req); err != nil { - t.Fatalf("err: %v", err) - } - if resp.Code != 200 { - t.Fatalf("bad code: %d", resp.Code) - } - }) + req, _ := http.NewRequest("DELETE", "/v1/query/my-id?token=my-token", body) + resp := httptest.NewRecorder() + if _, err := a.srv.PreparedQuerySpecific(resp, req); err != nil { + t.Fatalf("err: %v", err) + } + if resp.Code != 200 { + t.Fatalf("bad code: %d", resp.Code) + } } func TestPreparedQuery_BadMethods(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + body := bytes.NewBuffer(nil) req, _ := http.NewRequest("DELETE", "/v1/query", body) resp := httptest.NewRecorder() - if _, err := srv.PreparedQueryGeneral(resp, req); err != nil { + if _, err := a.srv.PreparedQueryGeneral(resp, req); err != nil { t.Fatalf("err: %v", err) } if resp.Code != 405 { @@ -712,11 +754,14 @@ func TestPreparedQuery_BadMethods(t *testing.T) { } }) - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + body := bytes.NewBuffer(nil) req, _ := http.NewRequest("POST", "/v1/query/my-id", body) resp := httptest.NewRecorder() - if _, err := srv.PreparedQuerySpecific(resp, req); err != nil { + if _, err := a.srv.PreparedQuerySpecific(resp, req); err != nil { t.Fatalf("err: %v", err) } if resp.Code != 405 { @@ -756,153 +801,154 @@ func TestPreparedQuery_parseLimit(t *testing.T) { // correctly when calling through to the real endpoints. func TestPreparedQuery_Integration(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - // Register a node and a service. - { - args := &structs.RegisterRequest{ - Datacenter: "dc1", - Node: srv.agent.config.NodeName, - Address: "127.0.0.1", - Service: &structs.NodeService{ - Service: "my-service", - }, - } - var out struct{} - if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil { - t.Fatalf("err: %v", err) - } + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + + // Register a node and a service. + { + args := &structs.RegisterRequest{ + Datacenter: "dc1", + Node: a.config.NodeName, + Address: "127.0.0.1", + Service: &structs.NodeService{ + Service: "my-service", + }, + } + var out struct{} + if err := a.RPC("Catalog.Register", args, &out); err != nil { + t.Fatalf("err: %v", err) + } + } + + // Create a query. + var id string + { + body := bytes.NewBuffer(nil) + enc := json.NewEncoder(body) + raw := map[string]interface{}{ + "Name": "my-query", + "Service": map[string]interface{}{ + "Service": "my-service", + }, + } + if err := enc.Encode(raw); err != nil { + t.Fatalf("err: %v", err) } - // Create a query. - var id string - { - body := bytes.NewBuffer(nil) - enc := json.NewEncoder(body) - raw := map[string]interface{}{ - "Name": "my-query", - "Service": map[string]interface{}{ - "Service": "my-service", - }, - } - if err := enc.Encode(raw); err != nil { - t.Fatalf("err: %v", err) - } + req, _ := http.NewRequest("POST", "/v1/query", body) + resp := httptest.NewRecorder() + obj, err := a.srv.PreparedQueryGeneral(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + if resp.Code != 200 { + t.Fatalf("bad code: %d", resp.Code) + } + r, ok := obj.(preparedQueryCreateResponse) + if !ok { + t.Fatalf("unexpected: %T", obj) + } + id = r.ID + } - req, _ := http.NewRequest("POST", "/v1/query", body) - resp := httptest.NewRecorder() - obj, err := srv.PreparedQueryGeneral(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - if resp.Code != 200 { - t.Fatalf("bad code: %d", resp.Code) - } - r, ok := obj.(preparedQueryCreateResponse) - if !ok { - t.Fatalf("unexpected: %T", obj) - } - id = r.ID + // List them all. + { + body := bytes.NewBuffer(nil) + req, _ := http.NewRequest("GET", "/v1/query?token=root", body) + resp := httptest.NewRecorder() + obj, err := a.srv.PreparedQueryGeneral(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + if resp.Code != 200 { + t.Fatalf("bad code: %d", resp.Code) + } + r, ok := obj.(structs.PreparedQueries) + if !ok { + t.Fatalf("unexpected: %T", obj) + } + if len(r) != 1 { + t.Fatalf("bad: %v", r) + } + } + + // Execute it. + { + body := bytes.NewBuffer(nil) + req, _ := http.NewRequest("GET", "/v1/query/"+id+"/execute", body) + resp := httptest.NewRecorder() + obj, err := a.srv.PreparedQuerySpecific(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + if resp.Code != 200 { + t.Fatalf("bad code: %d", resp.Code) + } + r, ok := obj.(structs.PreparedQueryExecuteResponse) + if !ok { + t.Fatalf("unexpected: %T", obj) + } + if len(r.Nodes) != 1 { + t.Fatalf("bad: %v", r) + } + } + + // Read it back. + { + body := bytes.NewBuffer(nil) + req, _ := http.NewRequest("GET", "/v1/query/"+id, body) + resp := httptest.NewRecorder() + obj, err := a.srv.PreparedQuerySpecific(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + if resp.Code != 200 { + t.Fatalf("bad code: %d", resp.Code) + } + r, ok := obj.(structs.PreparedQueries) + if !ok { + t.Fatalf("unexpected: %T", obj) + } + if len(r) != 1 { + t.Fatalf("bad: %v", r) + } + } + + // Make an update to it. + { + body := bytes.NewBuffer(nil) + enc := json.NewEncoder(body) + raw := map[string]interface{}{ + "Name": "my-query", + "Service": map[string]interface{}{ + "Service": "my-service", + "OnlyPassing": true, + }, + } + if err := enc.Encode(raw); err != nil { + t.Fatalf("err: %v", err) } - // List them all. - { - body := bytes.NewBuffer(nil) - req, _ := http.NewRequest("GET", "/v1/query?token=root", body) - resp := httptest.NewRecorder() - obj, err := srv.PreparedQueryGeneral(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - if resp.Code != 200 { - t.Fatalf("bad code: %d", resp.Code) - } - r, ok := obj.(structs.PreparedQueries) - if !ok { - t.Fatalf("unexpected: %T", obj) - } - if len(r) != 1 { - t.Fatalf("bad: %v", r) - } + req, _ := http.NewRequest("PUT", "/v1/query/"+id, body) + resp := httptest.NewRecorder() + if _, err := a.srv.PreparedQuerySpecific(resp, req); err != nil { + t.Fatalf("err: %v", err) } - - // Execute it. - { - body := bytes.NewBuffer(nil) - req, _ := http.NewRequest("GET", "/v1/query/"+id+"/execute", body) - resp := httptest.NewRecorder() - obj, err := srv.PreparedQuerySpecific(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - if resp.Code != 200 { - t.Fatalf("bad code: %d", resp.Code) - } - r, ok := obj.(structs.PreparedQueryExecuteResponse) - if !ok { - t.Fatalf("unexpected: %T", obj) - } - if len(r.Nodes) != 1 { - t.Fatalf("bad: %v", r) - } + if resp.Code != 200 { + t.Fatalf("bad code: %d", resp.Code) } + } - // Read it back. - { - body := bytes.NewBuffer(nil) - req, _ := http.NewRequest("GET", "/v1/query/"+id, body) - resp := httptest.NewRecorder() - obj, err := srv.PreparedQuerySpecific(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - if resp.Code != 200 { - t.Fatalf("bad code: %d", resp.Code) - } - r, ok := obj.(structs.PreparedQueries) - if !ok { - t.Fatalf("unexpected: %T", obj) - } - if len(r) != 1 { - t.Fatalf("bad: %v", r) - } + // Delete it. + { + body := bytes.NewBuffer(nil) + req, _ := http.NewRequest("DELETE", "/v1/query/"+id, body) + resp := httptest.NewRecorder() + if _, err := a.srv.PreparedQuerySpecific(resp, req); err != nil { + t.Fatalf("err: %v", err) } - - // Make an update to it. - { - body := bytes.NewBuffer(nil) - enc := json.NewEncoder(body) - raw := map[string]interface{}{ - "Name": "my-query", - "Service": map[string]interface{}{ - "Service": "my-service", - "OnlyPassing": true, - }, - } - if err := enc.Encode(raw); err != nil { - t.Fatalf("err: %v", err) - } - - req, _ := http.NewRequest("PUT", "/v1/query/"+id, body) - resp := httptest.NewRecorder() - if _, err := srv.PreparedQuerySpecific(resp, req); err != nil { - t.Fatalf("err: %v", err) - } - if resp.Code != 200 { - t.Fatalf("bad code: %d", resp.Code) - } + if resp.Code != 200 { + t.Fatalf("bad code: %d", resp.Code) } - - // Delete it. - { - body := bytes.NewBuffer(nil) - req, _ := http.NewRequest("DELETE", "/v1/query/"+id, body) - resp := httptest.NewRecorder() - if _, err := srv.PreparedQuerySpecific(resp, req); err != nil { - t.Fatalf("err: %v", err) - } - if resp.Code != 200 { - t.Fatalf("bad code: %d", resp.Code) - } - } - }) + } } diff --git a/command/agent/session_endpoint_test.go b/command/agent/session_endpoint_test.go index aa6a92cacd..a2eafaa980 100644 --- a/command/agent/session_endpoint_test.go +++ b/command/agent/session_endpoint_test.go @@ -16,93 +16,95 @@ import ( func TestSessionCreate(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - // Create a health check - args := &structs.RegisterRequest{ - Datacenter: "dc1", - Node: srv.agent.config.NodeName, - Address: "127.0.0.1", - Check: &structs.HealthCheck{ - CheckID: "consul", - Node: srv.agent.config.NodeName, - Name: "consul", - ServiceID: "consul", - Status: api.HealthPassing, - }, - } - var out struct{} - if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil { - t.Fatalf("err: %v", err) - } + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() - // Associate session with node and 2 health checks - body := bytes.NewBuffer(nil) - enc := json.NewEncoder(body) - raw := map[string]interface{}{ - "Name": "my-cool-session", - "Node": srv.agent.config.NodeName, - "Checks": []types.CheckID{consul.SerfCheckID, "consul"}, - "LockDelay": "20s", - } - enc.Encode(raw) + // Create a health check + args := &structs.RegisterRequest{ + Datacenter: "dc1", + Node: a.config.NodeName, + Address: "127.0.0.1", + Check: &structs.HealthCheck{ + CheckID: "consul", + Node: a.config.NodeName, + Name: "consul", + ServiceID: "consul", + Status: api.HealthPassing, + }, + } + var out struct{} + if err := a.RPC("Catalog.Register", args, &out); err != nil { + t.Fatalf("err: %v", err) + } - req, _ := http.NewRequest("PUT", "/v1/session/create", body) - resp := httptest.NewRecorder() - obj, err := srv.SessionCreate(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } + // Associate session with node and 2 health checks + body := bytes.NewBuffer(nil) + enc := json.NewEncoder(body) + raw := map[string]interface{}{ + "Name": "my-cool-session", + "Node": a.config.NodeName, + "Checks": []types.CheckID{consul.SerfCheckID, "consul"}, + "LockDelay": "20s", + } + enc.Encode(raw) - if _, ok := obj.(sessionCreateResponse); !ok { - t.Fatalf("should work") - } - }) + req, _ := http.NewRequest("PUT", "/v1/session/create", body) + resp := httptest.NewRecorder() + obj, err := a.srv.SessionCreate(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + + if _, ok := obj.(sessionCreateResponse); !ok { + t.Fatalf("should work") + } } func TestSessionCreateDelete(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - // Create a health check - args := &structs.RegisterRequest{ - Datacenter: "dc1", - Node: srv.agent.config.NodeName, - Address: "127.0.0.1", - Check: &structs.HealthCheck{ - CheckID: "consul", - Node: srv.agent.config.NodeName, - Name: "consul", - ServiceID: "consul", - Status: api.HealthPassing, - }, - } - var out struct{} - if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil { - t.Fatalf("err: %v", err) - } + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() - // Associate session with node and 2 health checks, and make it delete on session destroy - body := bytes.NewBuffer(nil) - enc := json.NewEncoder(body) - raw := map[string]interface{}{ - "Name": "my-cool-session", - "Node": srv.agent.config.NodeName, - "Checks": []types.CheckID{consul.SerfCheckID, "consul"}, - "LockDelay": "20s", - "Behavior": structs.SessionKeysDelete, - } - enc.Encode(raw) + // Create a health check + args := &structs.RegisterRequest{ + Datacenter: "dc1", + Node: a.config.NodeName, + Address: "127.0.0.1", + Check: &structs.HealthCheck{ + CheckID: "consul", + Node: a.config.NodeName, + Name: "consul", + ServiceID: "consul", + Status: api.HealthPassing, + }, + } + var out struct{} + if err := a.RPC("Catalog.Register", args, &out); err != nil { + t.Fatalf("err: %v", err) + } - req, _ := http.NewRequest("PUT", "/v1/session/create", body) - resp := httptest.NewRecorder() - obj, err := srv.SessionCreate(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } + // Associate session with node and 2 health checks, and make it delete on session destroy + body := bytes.NewBuffer(nil) + enc := json.NewEncoder(body) + raw := map[string]interface{}{ + "Name": "my-cool-session", + "Node": a.config.NodeName, + "Checks": []types.CheckID{consul.SerfCheckID, "consul"}, + "LockDelay": "20s", + "Behavior": structs.SessionKeysDelete, + } + enc.Encode(raw) - if _, ok := obj.(sessionCreateResponse); !ok { - t.Fatalf("should work") - } - }) + req, _ := http.NewRequest("PUT", "/v1/session/create", body) + resp := httptest.NewRecorder() + obj, err := a.srv.SessionCreate(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + + if _, ok := obj.(sessionCreateResponse); !ok { + t.Fatalf("should work") + } } func TestFixupLockDelay(t *testing.T) { @@ -189,155 +191,153 @@ func makeTestSessionTTL(t *testing.T, srv *HTTPServer, ttl string) string { func TestSessionDestroy(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - id := makeTestSession(t, srv) + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() - req, _ := http.NewRequest("PUT", "/v1/session/destroy/"+id, nil) - resp := httptest.NewRecorder() - obj, err := srv.SessionDestroy(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - if resp := obj.(bool); !resp { - t.Fatalf("should work") - } - }) + id := makeTestSession(t, a.srv) + + req, _ := http.NewRequest("PUT", "/v1/session/destroy/"+id, nil) + resp := httptest.NewRecorder() + obj, err := a.srv.SessionDestroy(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + if resp := obj.(bool); !resp { + t.Fatalf("should work") + } } func TestSessionCustomTTL(t *testing.T) { t.Parallel() ttl := 250 * time.Millisecond - testSessionTTL(t, ttl, customTTL(ttl)) -} + config := TestConfig() + config.SessionTTLMin = ttl + config.SessionTTLMinRaw = ttl.String() + a := NewTestAgent(t.Name(), config) + defer a.Shutdown() -func customTTL(d time.Duration) func(c *Config) { - return func(c *Config) { - c.SessionTTLMinRaw = d.String() - c.SessionTTLMin = d + id := makeTestSessionTTL(t, a.srv, ttl.String()) + + req, _ := http.NewRequest("GET", "/v1/session/info/"+id, nil) + resp := httptest.NewRecorder() + obj, err := a.srv.SessionGet(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + respObj, ok := obj.(structs.Sessions) + if !ok { + t.Fatalf("should work") + } + if len(respObj) != 1 { + t.Fatalf("bad: %v", respObj) + } + if respObj[0].TTL != ttl.String() { + t.Fatalf("Incorrect TTL: %s", respObj[0].TTL) } -} -func testSessionTTL(t *testing.T, ttl time.Duration, cb func(c *Config)) { - httpTestWithConfig(t, func(srv *HTTPServer) { - TTL := ttl.String() + time.Sleep(ttl*structs.SessionTTLMultiplier + ttl) - id := makeTestSessionTTL(t, srv, TTL) - - req, _ := http.NewRequest("GET", "/v1/session/info/"+id, nil) - resp := httptest.NewRecorder() - obj, err := srv.SessionGet(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - respObj, ok := obj.(structs.Sessions) - if !ok { - t.Fatalf("should work") - } - if len(respObj) != 1 { - t.Fatalf("bad: %v", respObj) - } - if respObj[0].TTL != TTL { - t.Fatalf("Incorrect TTL: %s", respObj[0].TTL) - } - - time.Sleep(ttl*structs.SessionTTLMultiplier + ttl) - - req, _ = http.NewRequest("GET", "/v1/session/info/"+id, nil) - resp = httptest.NewRecorder() - obj, err = srv.SessionGet(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - respObj, ok = obj.(structs.Sessions) - if len(respObj) != 0 { - t.Fatalf("session '%s' should have been destroyed", id) - } - }, cb) + req, _ = http.NewRequest("GET", "/v1/session/info/"+id, nil) + resp = httptest.NewRecorder() + obj, err = a.srv.SessionGet(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + respObj, ok = obj.(structs.Sessions) + if len(respObj) != 0 { + t.Fatalf("session '%s' should have been destroyed", id) + } } func TestSessionTTLRenew(t *testing.T) { t.Parallel() ttl := 250 * time.Millisecond - TTL := ttl.String() - httpTestWithConfig(t, func(srv *HTTPServer) { - id := makeTestSessionTTL(t, srv, TTL) + config := TestConfig() + config.SessionTTLMin = ttl + config.SessionTTLMinRaw = ttl.String() + a := NewTestAgent(t.Name(), config) + defer a.Shutdown() - req, _ := http.NewRequest("GET", "/v1/session/info/"+id, nil) - resp := httptest.NewRecorder() - obj, err := srv.SessionGet(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - respObj, ok := obj.(structs.Sessions) - if !ok { - t.Fatalf("should work") - } - if len(respObj) != 1 { - t.Fatalf("bad: %v", respObj) - } - if respObj[0].TTL != TTL { - t.Fatalf("Incorrect TTL: %s", respObj[0].TTL) - } + id := makeTestSessionTTL(t, a.srv, ttl.String()) - // Sleep to consume some time before renew - time.Sleep(ttl * (structs.SessionTTLMultiplier / 2)) + req, _ := http.NewRequest("GET", "/v1/session/info/"+id, nil) + resp := httptest.NewRecorder() + obj, err := a.srv.SessionGet(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + respObj, ok := obj.(structs.Sessions) + if !ok { + t.Fatalf("should work") + } + if len(respObj) != 1 { + t.Fatalf("bad: %v", respObj) + } + if respObj[0].TTL != ttl.String() { + t.Fatalf("Incorrect TTL: %s", respObj[0].TTL) + } - req, _ = http.NewRequest("PUT", "/v1/session/renew/"+id, nil) - resp = httptest.NewRecorder() - obj, err = srv.SessionRenew(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - respObj, ok = obj.(structs.Sessions) - if !ok { - t.Fatalf("should work") - } - if len(respObj) != 1 { - t.Fatalf("bad: %v", respObj) - } + // Sleep to consume some time before renew + time.Sleep(ttl * (structs.SessionTTLMultiplier / 2)) - // Sleep for ttl * TTL Multiplier - time.Sleep(ttl * structs.SessionTTLMultiplier) + req, _ = http.NewRequest("PUT", "/v1/session/renew/"+id, nil) + resp = httptest.NewRecorder() + obj, err = a.srv.SessionRenew(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + respObj, ok = obj.(structs.Sessions) + if !ok { + t.Fatalf("should work") + } + if len(respObj) != 1 { + t.Fatalf("bad: %v", respObj) + } - req, _ = http.NewRequest("GET", "/v1/session/info/"+id, nil) - resp = httptest.NewRecorder() - obj, err = srv.SessionGet(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - respObj, ok = obj.(structs.Sessions) - if !ok { - t.Fatalf("session '%s' should have renewed", id) - } - if len(respObj) != 1 { - t.Fatalf("session '%s' should have renewed", id) - } + // Sleep for ttl * TTL Multiplier + time.Sleep(ttl * structs.SessionTTLMultiplier) - // now wait for timeout and expect session to get destroyed - time.Sleep(ttl * structs.SessionTTLMultiplier) + req, _ = http.NewRequest("GET", "/v1/session/info/"+id, nil) + resp = httptest.NewRecorder() + obj, err = a.srv.SessionGet(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + respObj, ok = obj.(structs.Sessions) + if !ok { + t.Fatalf("session '%s' should have renewed", id) + } + if len(respObj) != 1 { + t.Fatalf("session '%s' should have renewed", id) + } - req, _ = http.NewRequest("GET", "/v1/session/info/"+id, nil) - resp = httptest.NewRecorder() - obj, err = srv.SessionGet(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - respObj, ok = obj.(structs.Sessions) - if !ok { - t.Fatalf("session '%s' should have destroyed", id) - } - if len(respObj) != 0 { - t.Fatalf("session '%s' should have destroyed", id) - } - }, customTTL(ttl)) + // now wait for timeout and expect session to get destroyed + time.Sleep(ttl * structs.SessionTTLMultiplier) + + req, _ = http.NewRequest("GET", "/v1/session/info/"+id, nil) + resp = httptest.NewRecorder() + obj, err = a.srv.SessionGet(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + respObj, ok = obj.(structs.Sessions) + if !ok { + t.Fatalf("session '%s' should have destroyed", id) + } + if len(respObj) != 0 { + t.Fatalf("session '%s' should have destroyed", id) + } } func TestSessionGet(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + req, _ := http.NewRequest("GET", "/v1/session/info/adf4238a-882b-9ddc-4a9d-5b6758e4159e", nil) resp := httptest.NewRecorder() - obj, err := srv.SessionGet(resp, req) + obj, err := a.srv.SessionGet(resp, req) if err != nil { t.Fatalf("err: %v", err) } @@ -350,12 +350,15 @@ func TestSessionGet(t *testing.T) { } }) - httpTest(t, func(srv *HTTPServer) { - id := makeTestSession(t, srv) + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + + id := makeTestSession(t, a.srv) req, _ := http.NewRequest("GET", "/v1/session/info/"+id, nil) resp := httptest.NewRecorder() - obj, err := srv.SessionGet(resp, req) + obj, err := a.srv.SessionGet(resp, req) if err != nil { t.Fatalf("err: %v", err) } @@ -371,10 +374,13 @@ func TestSessionGet(t *testing.T) { func TestSessionList(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + req, _ := http.NewRequest("GET", "/v1/session/list", nil) resp := httptest.NewRecorder() - obj, err := srv.SessionList(resp, req) + obj, err := a.srv.SessionList(resp, req) if err != nil { t.Fatalf("err: %v", err) } @@ -387,15 +393,18 @@ func TestSessionList(t *testing.T) { } }) - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + var ids []string for i := 0; i < 10; i++ { - ids = append(ids, makeTestSession(t, srv)) + ids = append(ids, makeTestSession(t, a.srv)) } req, _ := http.NewRequest("GET", "/v1/session/list", nil) resp := httptest.NewRecorder() - obj, err := srv.SessionList(resp, req) + obj, err := a.srv.SessionList(resp, req) if err != nil { t.Fatalf("err: %v", err) } @@ -411,10 +420,13 @@ func TestSessionList(t *testing.T) { func TestSessionsForNode(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - req, _ := http.NewRequest("GET", "/v1/session/node/"+srv.agent.config.NodeName, nil) + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + + req, _ := http.NewRequest("GET", "/v1/session/node/"+a.Config.NodeName, nil) resp := httptest.NewRecorder() - obj, err := srv.SessionsForNode(resp, req) + obj, err := a.srv.SessionsForNode(resp, req) if err != nil { t.Fatalf("err: %v", err) } @@ -427,15 +439,18 @@ func TestSessionsForNode(t *testing.T) { } }) - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + var ids []string for i := 0; i < 10; i++ { - ids = append(ids, makeTestSession(t, srv)) + ids = append(ids, makeTestSession(t, a.srv)) } - req, _ := http.NewRequest("GET", "/v1/session/node/"+srv.agent.config.NodeName, nil) + req, _ := http.NewRequest("GET", "/v1/session/node/"+a.Config.NodeName, nil) resp := httptest.NewRecorder() - obj, err := srv.SessionsForNode(resp, req) + obj, err := a.srv.SessionsForNode(resp, req) if err != nil { t.Fatalf("err: %v", err) } @@ -451,40 +466,41 @@ func TestSessionsForNode(t *testing.T) { func TestSessionDeleteDestroy(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - id := makeTestSessionDelete(t, srv) + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() - // now create a new key for the session and acquire it - buf := bytes.NewBuffer([]byte("test")) - req, _ := http.NewRequest("PUT", "/v1/kv/ephemeral?acquire="+id, buf) - resp := httptest.NewRecorder() - obj, err := srv.KVSEndpoint(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } + id := makeTestSessionDelete(t, a.srv) - if res := obj.(bool); !res { - t.Fatalf("should work") - } + // now create a new key for the session and acquire it + buf := bytes.NewBuffer([]byte("test")) + req, _ := http.NewRequest("PUT", "/v1/kv/ephemeral?acquire="+id, buf) + resp := httptest.NewRecorder() + obj, err := a.srv.KVSEndpoint(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } - // now destroy the session, this should delete the key created above - req, _ = http.NewRequest("PUT", "/v1/session/destroy/"+id, nil) - resp = httptest.NewRecorder() - obj, err = srv.SessionDestroy(resp, req) - if err != nil { - t.Fatalf("err: %v", err) - } - if resp := obj.(bool); !resp { - t.Fatalf("should work") - } + if res := obj.(bool); !res { + t.Fatalf("should work") + } - // Verify that the key is gone - req, _ = http.NewRequest("GET", "/v1/kv/ephemeral", nil) - resp = httptest.NewRecorder() - obj, _ = srv.KVSEndpoint(resp, req) - res, found := obj.(structs.DirEntries) - if found || len(res) != 0 { - t.Fatalf("bad: %v found, should be nothing", res) - } - }) + // now destroy the session, this should delete the key created above + req, _ = http.NewRequest("PUT", "/v1/session/destroy/"+id, nil) + resp = httptest.NewRecorder() + obj, err = a.srv.SessionDestroy(resp, req) + if err != nil { + t.Fatalf("err: %v", err) + } + if resp := obj.(bool); !resp { + t.Fatalf("should work") + } + + // Verify that the key is gone + req, _ = http.NewRequest("GET", "/v1/kv/ephemeral", nil) + resp = httptest.NewRecorder() + obj, _ = a.srv.KVSEndpoint(resp, req) + res, found := obj.(structs.DirEntries) + if found || len(res) != 0 { + t.Fatalf("bad: %v found, should be nothing", res) + } } diff --git a/command/agent/snapshot_endpoint_test.go b/command/agent/snapshot_endpoint_test.go index 94845df857..c7f152a3cb 100644 --- a/command/agent/snapshot_endpoint_test.go +++ b/command/agent/snapshot_endpoint_test.go @@ -12,11 +12,14 @@ import ( func TestSnapshot(t *testing.T) { t.Parallel() var snap io.Reader - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + body := bytes.NewBuffer(nil) req, _ := http.NewRequest("GET", "/v1/snapshot?token=root", body) resp := httptest.NewRecorder() - if _, err := srv.Snapshot(resp, req); err != nil { + if _, err := a.srv.Snapshot(resp, req); err != nil { t.Fatalf("err: %v", err) } snap = resp.Body @@ -35,10 +38,13 @@ func TestSnapshot(t *testing.T) { } }) - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + req, _ := http.NewRequest("PUT", "/v1/snapshot?token=root", snap) resp := httptest.NewRecorder() - if _, err := srv.Snapshot(resp, req); err != nil { + if _, err := a.srv.Snapshot(resp, req); err != nil { t.Fatalf("err: %v", err) } }) @@ -47,31 +53,40 @@ func TestSnapshot(t *testing.T) { func TestSnapshot_Options(t *testing.T) { t.Parallel() for _, method := range []string{"GET", "PUT"} { - httpTest(t, func(srv *HTTPServer) { + t.Run(method, func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + body := bytes.NewBuffer(nil) req, _ := http.NewRequest(method, "/v1/snapshot?token=anonymous", body) resp := httptest.NewRecorder() - _, err := srv.Snapshot(resp, req) + _, err := a.srv.Snapshot(resp, req) if err == nil || !strings.Contains(err.Error(), "Permission denied") { t.Fatalf("err: %v", err) } }) - httpTest(t, func(srv *HTTPServer) { + t.Run(method, func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + body := bytes.NewBuffer(nil) req, _ := http.NewRequest(method, "/v1/snapshot?dc=nope", body) resp := httptest.NewRecorder() - _, err := srv.Snapshot(resp, req) + _, err := a.srv.Snapshot(resp, req) if err == nil || !strings.Contains(err.Error(), "No path to datacenter") { t.Fatalf("err: %v", err) } }) - httpTest(t, func(srv *HTTPServer) { + t.Run(method, func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + body := bytes.NewBuffer(nil) req, _ := http.NewRequest(method, "/v1/snapshot?token=root&stale", body) resp := httptest.NewRecorder() - _, err := srv.Snapshot(resp, req) + _, err := a.srv.Snapshot(resp, req) if method == "GET" { if err != nil { t.Fatalf("err: %v", err) @@ -87,11 +102,14 @@ func TestSnapshot_Options(t *testing.T) { func TestSnapshot_BadMethods(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + body := bytes.NewBuffer(nil) req, _ := http.NewRequest("POST", "/v1/snapshot", body) resp := httptest.NewRecorder() - _, err := srv.Snapshot(resp, req) + _, err := a.srv.Snapshot(resp, req) if err != nil { t.Fatalf("err: %v", err) } @@ -100,11 +118,14 @@ func TestSnapshot_BadMethods(t *testing.T) { } }) - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + body := bytes.NewBuffer(nil) req, _ := http.NewRequest("DELETE", "/v1/snapshot", body) resp := httptest.NewRecorder() - _, err := srv.Snapshot(resp, req) + _, err := a.srv.Snapshot(resp, req) if err != nil { t.Fatalf("err: %v", err) } diff --git a/command/agent/txn_endpoint_test.go b/command/agent/txn_endpoint_test.go index 6148f85aa5..e9de14e595 100644 --- a/command/agent/txn_endpoint_test.go +++ b/command/agent/txn_endpoint_test.go @@ -14,41 +14,45 @@ import ( func TestTxnEndpoint_Bad_JSON(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - buf := bytes.NewBuffer([]byte("{")) - req, _ := http.NewRequest("PUT", "/v1/txn", buf) - resp := httptest.NewRecorder() - if _, err := srv.Txn(resp, req); err != nil { - t.Fatalf("err: %v", err) - } - if resp.Code != 400 { - t.Fatalf("expected 400, got %d", resp.Code) - } - if !bytes.Contains(resp.Body.Bytes(), []byte("Failed to parse")) { - t.Fatalf("expected conflicting args error") - } - }) + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + + buf := bytes.NewBuffer([]byte("{")) + req, _ := http.NewRequest("PUT", "/v1/txn", buf) + resp := httptest.NewRecorder() + if _, err := a.srv.Txn(resp, req); err != nil { + t.Fatalf("err: %v", err) + } + if resp.Code != 400 { + t.Fatalf("expected 400, got %d", resp.Code) + } + if !bytes.Contains(resp.Body.Bytes(), []byte("Failed to parse")) { + t.Fatalf("expected conflicting args error") + } } func TestTxnEndpoint_Bad_Method(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - buf := bytes.NewBuffer([]byte("{}")) - req, _ := http.NewRequest("GET", "/v1/txn", buf) - resp := httptest.NewRecorder() - if _, err := srv.Txn(resp, req); err != nil { - t.Fatalf("err: %v", err) - } - if resp.Code != 405 { - t.Fatalf("expected 405, got %d", resp.Code) - } - }) + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + + buf := bytes.NewBuffer([]byte("{}")) + req, _ := http.NewRequest("GET", "/v1/txn", buf) + resp := httptest.NewRecorder() + if _, err := a.srv.Txn(resp, req); err != nil { + t.Fatalf("err: %v", err) + } + if resp.Code != 405 { + t.Fatalf("expected 405, got %d", resp.Code) + } } func TestTxnEndpoint_Bad_Size_Item(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - buf := bytes.NewBuffer([]byte(fmt.Sprintf(` + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + + buf := bytes.NewBuffer([]byte(fmt.Sprintf(` [ { "KV": { @@ -59,22 +63,23 @@ func TestTxnEndpoint_Bad_Size_Item(t *testing.T) { } ] `, strings.Repeat("bad", 2*maxKVSize)))) - req, _ := http.NewRequest("PUT", "/v1/txn", buf) - resp := httptest.NewRecorder() - if _, err := srv.Txn(resp, req); err != nil { - t.Fatalf("err: %v", err) - } - if resp.Code != 413 { - t.Fatalf("expected 413, got %d", resp.Code) - } - }) + req, _ := http.NewRequest("PUT", "/v1/txn", buf) + resp := httptest.NewRecorder() + if _, err := a.srv.Txn(resp, req); err != nil { + t.Fatalf("err: %v", err) + } + if resp.Code != 413 { + t.Fatalf("expected 413, got %d", resp.Code) + } } func TestTxnEndpoint_Bad_Size_Net(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - value := strings.Repeat("X", maxKVSize/2) - buf := bytes.NewBuffer([]byte(fmt.Sprintf(` + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + + value := strings.Repeat("X", maxKVSize/2) + buf := bytes.NewBuffer([]byte(fmt.Sprintf(` [ { "KV": { @@ -99,21 +104,22 @@ func TestTxnEndpoint_Bad_Size_Net(t *testing.T) { } ] `, value, value, value))) - req, _ := http.NewRequest("PUT", "/v1/txn", buf) - resp := httptest.NewRecorder() - if _, err := srv.Txn(resp, req); err != nil { - t.Fatalf("err: %v", err) - } - if resp.Code != 413 { - t.Fatalf("expected 413, got %d", resp.Code) - } - }) + req, _ := http.NewRequest("PUT", "/v1/txn", buf) + resp := httptest.NewRecorder() + if _, err := a.srv.Txn(resp, req); err != nil { + t.Fatalf("err: %v", err) + } + if resp.Code != 413 { + t.Fatalf("expected 413, got %d", resp.Code) + } } func TestTxnEndpoint_Bad_Size_Ops(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { - buf := bytes.NewBuffer([]byte(fmt.Sprintf(` + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + + buf := bytes.NewBuffer([]byte(fmt.Sprintf(` [ %s { @@ -125,24 +131,26 @@ func TestTxnEndpoint_Bad_Size_Ops(t *testing.T) { } ] `, strings.Repeat(`{ "KV": { "Verb": "get", "Key": "key" } },`, 2*maxTxnOps)))) - req, _ := http.NewRequest("PUT", "/v1/txn", buf) - resp := httptest.NewRecorder() - if _, err := srv.Txn(resp, req); err != nil { - t.Fatalf("err: %v", err) - } - if resp.Code != 413 { - t.Fatalf("expected 413, got %d", resp.Code) - } - }) + req, _ := http.NewRequest("PUT", "/v1/txn", buf) + resp := httptest.NewRecorder() + if _, err := a.srv.Txn(resp, req); err != nil { + t.Fatalf("err: %v", err) + } + if resp.Code != 413 { + t.Fatalf("expected 413, got %d", resp.Code) + } } func TestTxnEndpoint_KV_Actions(t *testing.T) { t.Parallel() - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + // Make sure all incoming fields get converted properly to the internal // RPC format. var index uint64 - id := makeTestSession(t, srv) + id := makeTestSession(t, a.srv) { buf := bytes.NewBuffer([]byte(fmt.Sprintf(` [ @@ -165,7 +173,7 @@ func TestTxnEndpoint_KV_Actions(t *testing.T) { `, id))) req, _ := http.NewRequest("PUT", "/v1/txn", buf) resp := httptest.NewRecorder() - obj, err := srv.Txn(resp, req) + obj, err := a.srv.Txn(resp, req) if err != nil { t.Fatalf("err: %v", err) } @@ -237,7 +245,7 @@ func TestTxnEndpoint_KV_Actions(t *testing.T) { `)) req, _ := http.NewRequest("PUT", "/v1/txn", buf) resp := httptest.NewRecorder() - obj, err := srv.Txn(resp, req) + obj, err := a.srv.Txn(resp, req) if err != nil { t.Fatalf("err: %v", err) } @@ -321,7 +329,7 @@ func TestTxnEndpoint_KV_Actions(t *testing.T) { `, index))) req, _ := http.NewRequest("PUT", "/v1/txn", buf) resp := httptest.NewRecorder() - obj, err := srv.Txn(resp, req) + obj, err := a.srv.Txn(resp, req) if err != nil { t.Fatalf("err: %v", err) } @@ -370,7 +378,10 @@ func TestTxnEndpoint_KV_Actions(t *testing.T) { }) // Verify an error inside a transaction. - httpTest(t, func(srv *HTTPServer) { + t.Run("", func(t *testing.T) { + a := NewTestAgent(t.Name(), nil) + defer a.Shutdown() + buf := bytes.NewBuffer([]byte(` [ { @@ -391,7 +402,7 @@ func TestTxnEndpoint_KV_Actions(t *testing.T) { `)) req, _ := http.NewRequest("PUT", "/v1/txn", buf) resp := httptest.NewRecorder() - if _, err := srv.Txn(resp, req); err != nil { + if _, err := a.srv.Txn(resp, req); err != nil { t.Fatalf("err: %v", err) } if resp.Code != 409 {