Skip to content

Commit

Permalink
Addressing review comments
Browse files Browse the repository at this point in the history
  • Loading branch information
srahul3 committed Sep 19, 2024
1 parent cc40621 commit 0b89fa4
Show file tree
Hide file tree
Showing 2 changed files with 150 additions and 37 deletions.
89 changes: 88 additions & 1 deletion agent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ func testAgent(t *testing.T, cb func(*Config)) *Agent {
if cb != nil {
cb(conf)
}

agent, err := NewAgent(conf, logger)
if err != nil {
t.Fatal(err)
Expand Down Expand Up @@ -598,6 +597,94 @@ func TestAgent_PartitionOrEmpty(t *testing.T) {
}
}

func TestAgent_PartitionOrEmptyAPI(t *testing.T) {
testPartition := "test-partition"
notUniqueInstanceID := "not-unique-instance-id"
t.Run("with-partition", func(t *testing.T) {
listener, err := net.Listen("tcp", ":0")
require.NoError(t, err)
port := listener.Addr().(*net.TCPAddr).Port
addr := fmt.Sprintf("127.0.0.1:%d", port)
testNs := map[string]bool{}
ts := httptest.NewUnstartedServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
switch r.URL.EscapedPath() {
case "/v1/status/leader":
assert.Equal(t, testPartition, r.URL.Query().Get("partition"))
fmt.Fprint(w, `"`+addr+`"`)
case "/v1/namespaces":
assert.Equal(t, testPartition, r.URL.Query().Get("partition"))
fmt.Fprint(w, testNamespaces())
case "/v1/health/state/any":
assert.Equal(t, testPartition, r.URL.Query().Get("partition"))
namespace := r.URL.Query()["ns"][0]
testNs[namespace] = true
if namespace == "default" {
fmt.Fprint(w, "[]")
}
fmt.Fprint(w, testHealthChecks(r.URL.Query()["ns"][0]))
case "/v1/agent/service/consul-esm:not-unique-instance-id":
assert.Equal(t, testPartition, r.URL.Query().Get("partition"))
// write status 404, to tell the service is not registered and proceed with registration
w.WriteHeader(http.StatusNotFound)
case "/v1/agent/service/register":
assert.Equal(t, testPartition, r.URL.Query().Get("partition"))
var svc api.AgentServiceRegistration
err := json.NewDecoder(r.Body).Decode(&svc)
require.NoError(t, err)
// assert.Equal(t, "consul-esm", svc.Service)
assert.Equal(t, fmt.Sprintf("consul-esm:%s", notUniqueInstanceID), svc.ID)
assert.Equal(t, "test", svc.Tags[0])
assert.Equal(t, "consul-esm", svc.Meta["external-source"])
w.WriteHeader(http.StatusOK)
case "/v1/kv/consul-esm/agents/consul-esm:not-unique-instance-id":
assert.Equal(t, testPartition, r.URL.Query().Get("partition"))
case "/v1/session/create":
assert.Equal(t, testPartition, r.URL.Query().Get("partition"))
case "/v1/agent/check/register":
assert.Equal(t, testPartition, r.URL.Query().Get("partition"))
case "/v1/agent/check/update/consul-esm:not-unique-instance-id:agent-ttl":
assert.Equal(t, testPartition, r.URL.Query().Get("partition"))
case "/v1/catalog/service/consul-esm":
assert.Equal(t, testPartition, r.URL.Query().Get("partition"))
case "/v1/agent/services":
assert.Equal(t, testPartition, r.URL.Query().Get("partition"))

default:
t.Log("unhandled:", r.URL.EscapedPath())
}
}))
ts.Listener = listener
ts.Start()
defer ts.Close()

agent := testAgent(t, func(c *Config) {
c.HTTPAddr = addr
c.Tag = "test"
c.Partition = testPartition
c.InstanceID = notUniqueInstanceID
})
defer agent.Shutdown()

ourNodes := map[string]bool{"foo": true}
ourChecks, _ := agent.getHealthChecks(0, ourNodes)
if len(ourChecks) != 2 {
t.Error("should be 2 checks, got", len(ourChecks))
}
ns1check := ourChecks[0]
ns2check := ourChecks[1]
if ns1check.CheckID != "ns1_svc_ck" {
t.Error("Wrong check id:", ns1check.CheckID)
}
if ns2check.CheckID != "ns2_svc_ck" {
t.Error("Wrong check id:", ns1check.CheckID)
}

// test the state API is called for each namespace in an agent's partition
assert.Len(t, testNs, 3)
})
}

func TestAgent_HasPartition(t *testing.T) {
conf, err := DefaultConfig()
if err != nil {
Expand Down
98 changes: 62 additions & 36 deletions leader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (

"github.com/hashicorp/consul/api"
"github.com/hashicorp/consul/sdk/testutil/retry"
"github.com/stretchr/testify/assert"
)

func (a *Agent) verifyUpdates(t *testing.T, expectedHealthNodes, expectedProbeNodes []string) {
Expand Down Expand Up @@ -490,44 +491,69 @@ func Test_namespacesList(t *testing.T) {
}

func Test_getServiceInstances(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
uri := r.RequestURI
switch { // ignore anything that doesn't require a return body
case strings.Contains(uri, "status/leader"):
fmt.Fprint(w, `"127.0.0.1"`)
case strings.Contains(uri, "namespace"):
fmt.Fprint(w, namespacesJSON)
case strings.Contains(uri, "health/service"):
fmt.Fprint(w, healthserviceJSON)
// parameterized test
cases := []struct {
name, partition string
}{
{"No partition", ""},
{"default partition", "default"},
{"admin partition", "admin"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
uri := r.RequestURI
switch { // ignore anything that doesn't require a return body
case strings.Contains(uri, "status/leader"):
assert.Equal(t, tc.partition, r.URL.Query().Get("partition"))
fmt.Fprint(w, `"127.0.0.1"`)
case strings.Contains(uri, "namespace"):
assert.Equal(t, tc.partition, r.URL.Query().Get("partition"))
fmt.Fprint(w, namespacesJSON)
case strings.Contains(uri, "health/service"):
assert.Equal(t, tc.partition, r.URL.Query().Get("partition"))
fmt.Fprint(w, healthserviceJSON)
}
}))
defer ts.Close()

var agent *Agent
if tc.partition == "" {
agent = testAgent(t, func(c *Config) {
c.HTTPAddr = ts.URL
c.InstanceID = "test-agent"
})
} else {
agent = testAgent(t, func(c *Config) {
c.HTTPAddr = ts.URL
c.InstanceID = "test-agent"
c.Partition = tc.partition
})
}
}))
defer ts.Close()

agent := testAgent(t, func(c *Config) {
c.HTTPAddr = ts.URL
c.InstanceID = "test-agent"
})
defer agent.Shutdown()
defer agent.Shutdown()

opts := &api.QueryOptions{}
serviceInstances, err := agent.getServiceInstances(opts)
if err != nil {
t.Fatal(err)
}
// 4 because test data has 2 namespaces each with 2 services
if len(serviceInstances) != 4 {
t.Fatal("Wrong number of services", len(serviceInstances))
}
for _, si := range serviceInstances {
sv := si.Service
switch {
case sv.ID == "one" && sv.Namespace == "foo":
case sv.ID == "one" && sv.Namespace == "default":
case sv.ID == "two" && sv.Namespace == "foo":
case sv.ID == "two" && sv.Namespace == "default":
default:
t.Fatalf("Unknown service: %#v\n", si.Service)
}
opts := &api.QueryOptions{}
serviceInstances, err := agent.getServiceInstances(opts)
if err != nil {
t.Fatal(err)
}
// 4 because test data has 2 namespaces each with 2 services
if len(serviceInstances) != 4 {
t.Fatal("Wrong number of services", len(serviceInstances))
}
for _, si := range serviceInstances {
sv := si.Service
switch {
case sv.ID == "one" && sv.Namespace == "foo":
case sv.ID == "one" && sv.Namespace == "default":
case sv.ID == "two" && sv.Namespace == "foo":
case sv.ID == "two" && sv.Namespace == "default":
default:
t.Fatalf("Unknown service: %#v\n", si.Service)
}
}
})
}
}

0 comments on commit 0b89fa4

Please sign in to comment.