code
stringlengths
0
56.1M
repo_name
stringclasses
515 values
path
stringlengths
2
147
language
stringclasses
447 values
license
stringclasses
7 values
size
int64
0
56.8M
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package grpc import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/subscriptions/programmatic/grpc/routes" )
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/grpc/grpc.go
GO
mit
681
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package grpc import ( "context" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/types/known/emptypb" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/grpc/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(missing)) } type missing struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (m *missing) Setup(t *testing.T) []framework.Option { m.sub = subscriber.New(t, subscriber.WithListTopicSubscriptions(func(context.Context, *emptypb.Empty) (*rtv1.ListTopicSubscriptionsResponse, error) { return &rtv1.ListTopicSubscriptionsResponse{ Subscriptions: []*rtv1.TopicSubscription{ { PubsubName: "anotherpub", Topic: "a", Routes: &rtv1.TopicRoutes{ Default: "/a", }, }, { PubsubName: "mypub", Topic: "c", Routes: &rtv1.TopicRoutes{ Default: "/c", }, }, }, }, nil }), ) m.daprd = daprd.New(t, daprd.WithAppPort(m.sub.Port(t)), daprd.WithAppProtocol("grpc"), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(m.sub, m.daprd), } } func (m *missing) Run(t *testing.T, ctx context.Context) { m.daprd.WaitUntilRunning(t, ctx) client := m.daprd.GRPCClient(t, ctx) meta, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest)) require.NoError(t, err) assert.Len(t, meta.GetRegisteredComponents(), 1) assert.Len(t, meta.GetSubscriptions(), 2) m.sub.ExpectPublishError(t, ctx, m.daprd, &rtv1.PublishEventRequest{ PubsubName: "anotherpub", Topic: "a", Data: []byte(`{"status": "completed"}`), }) m.sub.ExpectPublishNoReceive(t, ctx, m.daprd, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "b", Data: []byte(`{"status": "completed"}`), }) m.sub.ExpectPublishReceive(t, ctx, m.daprd, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "c", Data: []byte(`{"status": "completed"}`), }) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/grpc/missing.go
GO
mit
2,847
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package grpc import ( "bytes" "context" "encoding/json" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/types/known/emptypb" "github.com/dapr/components-contrib/pubsub" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/grpc/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(rawpayload)) } type rawpayload struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (r *rawpayload) Setup(t *testing.T) []framework.Option { r.sub = subscriber.New(t, subscriber.WithListTopicSubscriptions(func(context.Context, *emptypb.Empty) (*rtv1.ListTopicSubscriptionsResponse, error) { return &rtv1.ListTopicSubscriptionsResponse{ Subscriptions: []*rtv1.TopicSubscription{ { PubsubName: "mypub", Topic: "a", Routes: &rtv1.TopicRoutes{ Default: "/a", }, Metadata: map[string]string{ "rawPayload": "true", }, }, }, }, nil }), ) r.daprd = daprd.New(t, daprd.WithAppPort(r.sub.Port(t)), daprd.WithAppProtocol("grpc"), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(r.sub, r.daprd), } } func (r *rawpayload) Run(t *testing.T, ctx context.Context) { r.daprd.WaitUntilRunning(t, ctx) client := r.daprd.GRPCClient(t, ctx) _, err := client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "a", Data: []byte(`{"status": "completed"}`), Metadata: map[string]string{"foo": "bar"}, DataContentType: "application/json", }) require.NoError(t, err) resp := r.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.GetPath()) assert.Equal(t, "1.0", resp.GetSpecVersion()) assert.Equal(t, "mypub", resp.GetPubsubName()) assert.Equal(t, "com.dapr.event.sent", resp.GetType()) assert.Equal(t, "application/octet-stream", resp.GetDataContentType()) var ce map[string]any require.NoError(t, json.NewDecoder(bytes.NewReader(resp.GetData())).Decode(&ce)) exp := pubsub.NewCloudEventsEnvelope("", "", "com.dapr.event.sent", "", "a", "mypub", "application/json", []byte(`{"status": "completed"}`), "", "") exp["id"] = ce["id"] exp["source"] = ce["source"] exp["time"] = ce["time"] exp["traceid"] = ce["traceid"] exp["traceparent"] = ce["traceparent"] assert.Equal(t, exp, ce) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "a", Data: []byte(`{"status": "completed"}`), DataContentType: "foo/bar", }) require.NoError(t, err) resp = r.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.GetPath()) assert.Equal(t, "1.0", resp.GetSpecVersion()) assert.Equal(t, "mypub", resp.GetPubsubName()) assert.Equal(t, "com.dapr.event.sent", resp.GetType()) assert.Equal(t, "application/octet-stream", resp.GetDataContentType()) require.NoError(t, json.NewDecoder(bytes.NewReader(resp.GetData())).Decode(&ce)) exp = pubsub.NewCloudEventsEnvelope("", "", "com.dapr.event.sent", "", "a", "mypub", "application/json", nil, "", "") exp["id"] = ce["id"] exp["data"] = `{"status": "completed"}` exp["datacontenttype"] = "foo/bar" exp["source"] = ce["source"] exp["time"] = ce["time"] exp["traceid"] = ce["traceid"] exp["traceparent"] = ce["traceparent"] assert.Equal(t, exp, ce) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "a", Data: []byte("foo"), }) require.NoError(t, err) resp = r.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.GetPath()) assert.Equal(t, "application/octet-stream", resp.GetDataContentType()) assert.Equal(t, "1.0", resp.GetSpecVersion()) assert.Equal(t, "mypub", resp.GetPubsubName()) assert.Equal(t, "com.dapr.event.sent", resp.GetType()) require.NoError(t, json.NewDecoder(bytes.NewReader(resp.GetData())).Decode(&ce)) exp = pubsub.NewCloudEventsEnvelope("", "", "com.dapr.event.sent", "", "a", "mypub", "application/json", []byte("foo"), "", "") exp["id"] = ce["id"] exp["source"] = ce["source"] exp["time"] = ce["time"] exp["traceid"] = ce["traceid"] exp["traceparent"] = ce["traceparent"] exp["datacontenttype"] = "text/plain" assert.Equal(t, exp, ce) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/grpc/rawpayload.go
GO
mit
5,005
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package routes import ( "context" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/types/known/emptypb" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/grpc/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(defaultroute)) } type defaultroute struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (d *defaultroute) Setup(t *testing.T) []framework.Option { d.sub = subscriber.New(t, subscriber.WithListTopicSubscriptions(func(context.Context, *emptypb.Empty) (*rtv1.ListTopicSubscriptionsResponse, error) { return &rtv1.ListTopicSubscriptionsResponse{ Subscriptions: []*rtv1.TopicSubscription{ { PubsubName: "mypub", Topic: "a", Routes: &rtv1.TopicRoutes{ Default: "/a/b/c/d", }, }, { PubsubName: "mypub", Topic: "a", Routes: &rtv1.TopicRoutes{ Default: "/a", }, }, { PubsubName: "mypub", Topic: "b", Routes: &rtv1.TopicRoutes{ Default: "/b", }, }, { PubsubName: "mypub", Topic: "b", Routes: &rtv1.TopicRoutes{ Default: "/d/c/b/a", }, }, }, }, nil }), ) d.daprd = daprd.New(t, daprd.WithAppPort(d.sub.Port(t)), daprd.WithAppProtocol("grpc"), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(d.sub, d.daprd), } } func (d *defaultroute) Run(t *testing.T, ctx context.Context) { d.daprd.WaitUntilRunning(t, ctx) client := d.daprd.GRPCClient(t, ctx) _, err := client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "a", }) require.NoError(t, err) resp := d.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.GetPath()) assert.Empty(t, resp.GetData()) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "b", }) require.NoError(t, err) resp = d.sub.Receive(t, ctx) assert.Equal(t, "/d/c/b/a", resp.GetPath()) assert.Empty(t, resp.GetData()) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/grpc/routes/defaultroute.go
GO
mit
2,965
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package routes import ( "context" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/types/known/emptypb" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/grpc/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(emptymatch)) } type emptymatch struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (e *emptymatch) Setup(t *testing.T) []framework.Option { e.sub = subscriber.New(t, subscriber.WithListTopicSubscriptions(func(context.Context, *emptypb.Empty) (*rtv1.ListTopicSubscriptionsResponse, error) { return &rtv1.ListTopicSubscriptionsResponse{ Subscriptions: []*rtv1.TopicSubscription{ { PubsubName: "mypub", Topic: "justpath", Routes: &rtv1.TopicRoutes{ Rules: []*rtv1.TopicRule{ {Path: "/justpath", Match: ""}, }, }, }, { PubsubName: "mypub", Topic: "defaultandpath", Routes: &rtv1.TopicRoutes{ Default: "/abc", Rules: []*rtv1.TopicRule{ {Path: "/123", Match: ""}, }, }, }, { PubsubName: "mypub", Topic: "multipaths", Routes: &rtv1.TopicRoutes{ Rules: []*rtv1.TopicRule{ {Path: "/xyz", Match: ""}, {Path: "/456", Match: ""}, {Path: "/789", Match: ""}, }, }, }, { PubsubName: "mypub", Topic: "defaultandpaths", Routes: &rtv1.TopicRoutes{ Default: "/def", Rules: []*rtv1.TopicRule{ {Path: "/zyz", Match: ""}, {Path: "/aaa", Match: ""}, {Path: "/bbb", Match: ""}, }, }, }, }, }, nil }), ) e.daprd = daprd.New(t, daprd.WithAppPort(e.sub.Port(t)), daprd.WithAppProtocol("grpc"), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(e.sub, e.daprd), } } func (e *emptymatch) Run(t *testing.T, ctx context.Context) { e.daprd.WaitUntilRunning(t, ctx) client := e.daprd.GRPCClient(t, ctx) _, err := client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "justpath", }) require.NoError(t, err) resp := e.sub.Receive(t, ctx) assert.Equal(t, "/justpath", resp.GetPath()) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "defaultandpath", }) require.NoError(t, err) resp = e.sub.Receive(t, ctx) assert.Equal(t, "/123", resp.GetPath()) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "multipaths", }) require.NoError(t, err) resp = e.sub.Receive(t, ctx) assert.Equal(t, "/xyz", resp.GetPath()) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "defaultandpaths", }) require.NoError(t, err) resp = e.sub.Receive(t, ctx) assert.Equal(t, "/zyz", resp.GetPath()) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/grpc/routes/emptymatch.go
GO
mit
3,795
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package routes import ( "context" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/types/known/emptypb" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/grpc/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(match)) } type match struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (m *match) Setup(t *testing.T) []framework.Option { m.sub = subscriber.New(t, subscriber.WithListTopicSubscriptions(func(context.Context, *emptypb.Empty) (*rtv1.ListTopicSubscriptionsResponse, error) { return &rtv1.ListTopicSubscriptionsResponse{ Subscriptions: []*rtv1.TopicSubscription{ { PubsubName: "mypub", Topic: "type", Routes: &rtv1.TopicRoutes{ Default: "/aaa", Rules: []*rtv1.TopicRule{ {Path: "/type", Match: `event.type == "com.dapr.event.sent"`}, {Path: "/foo", Match: ""}, {Path: "/bar", Match: `event.type == "com.dapr.event.recv"`}, }, }, }, { PubsubName: "mypub", Topic: "order1", Routes: &rtv1.TopicRoutes{ Default: "/aaa", Rules: []*rtv1.TopicRule{ {Path: "/type", Match: `event.type == "com.dapr.event.sent"`}, {Path: "/topic", Match: `event.topic == "order1"`}, }, }, }, { PubsubName: "mypub", Topic: "order2", Routes: &rtv1.TopicRoutes{ Default: "/aaa", Rules: []*rtv1.TopicRule{ {Path: "/topic", Match: `event.topic == "order2"`}, {Path: "/type", Match: `event.type == "com.dapr.event.sent"`}, }, }, }, { PubsubName: "mypub", Topic: "order3", Routes: &rtv1.TopicRoutes{ Default: "/aaa", Rules: []*rtv1.TopicRule{ {Path: "/123", Match: `event.topic == "order3"`}, {Path: "/456", Match: `event.topic == "order3"`}, }, }, }, { PubsubName: "mypub", Topic: "order4", Routes: &rtv1.TopicRoutes{ Rules: []*rtv1.TopicRule{ {Path: "/123", Match: `event.topic == "order5"`}, {Path: "/456", Match: `event.topic == "order6"`}, }, }, }, { PubsubName: "mypub", Topic: "order7", Routes: &rtv1.TopicRoutes{ Default: "/order7def", Rules: []*rtv1.TopicRule{ {Path: "/order7rule", Match: ""}, }, }, }, }, }, nil }), ) m.daprd = daprd.New(t, daprd.WithAppPort(m.sub.Port(t)), daprd.WithAppProtocol("grpc"), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(m.sub, m.daprd), } } func (m *match) Run(t *testing.T, ctx context.Context) { m.daprd.WaitUntilRunning(t, ctx) client := m.daprd.GRPCClient(t, ctx) _, err := client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "type", }) require.NoError(t, err) resp := m.sub.Receive(t, ctx) assert.Equal(t, "/type", resp.GetPath()) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "order1", }) require.NoError(t, err) resp = m.sub.Receive(t, ctx) assert.Equal(t, "/type", resp.GetPath()) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "order2", }) require.NoError(t, err) resp = m.sub.Receive(t, ctx) assert.Equal(t, "/topic", resp.GetPath()) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "order3", }) require.NoError(t, err) resp = m.sub.Receive(t, ctx) assert.Equal(t, "/123", resp.GetPath()) m.sub.ExpectPublishNoReceive(t, ctx, m.daprd, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "order4", }) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "order7", }) require.NoError(t, err) resp = m.sub.Receive(t, ctx) assert.Equal(t, "/order7rule", resp.GetPath()) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/grpc/routes/match.go
GO
mit
4,882
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package http import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/subscriptions/programmatic/http/mixed" _ "github.com/dapr/dapr/tests/integration/suite/daprd/subscriptions/programmatic/http/v1alpha1" _ "github.com/dapr/dapr/tests/integration/suite/daprd/subscriptions/programmatic/http/v2alpha1" )
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/http/http.go
GO
mit
874
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package mixed import ( "context" "testing" "github.com/stretchr/testify/assert" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/http/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(defaultroute)) } type defaultroute struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (d *defaultroute) Setup(t *testing.T) []framework.Option { d.sub = subscriber.New(t, subscriber.WithRoutes( "/a/b/c/d", "/d/c/b/a", "/123", "/456", "/zyx", "/xyz", ), subscriber.WithProgrammaticSubscriptions( subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "a", Route: "/a/b/c/d", Routes: subscriber.RoutesJSON{ Default: "/d/c/b/a", }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "b", Route: "/123", }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "b", Routes: subscriber.RoutesJSON{ Default: "/456", }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "c", Routes: subscriber.RoutesJSON{ Default: "/xyz", }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "c", Route: "/zyx", }, ), ) d.daprd = daprd.New(t, daprd.WithAppPort(d.sub.Port()), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(d.sub, d.daprd), } } func (d *defaultroute) Run(t *testing.T, ctx context.Context) { d.daprd.WaitUntilRunning(t, ctx) d.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: d.daprd, PubSubName: "mypub", Topic: "a", }) assert.Equal(t, "/d/c/b/a", d.sub.Receive(t, ctx).Route) d.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: d.daprd, PubSubName: "mypub", Topic: "b", }) assert.Equal(t, "/456", d.sub.Receive(t, ctx).Route) d.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: d.daprd, PubSubName: "mypub", Topic: "c", }) assert.Equal(t, "/zyx", d.sub.Receive(t, ctx).Route) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/http/mixed/defaultroute.go
GO
mit
2,863
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package mixed import ( "context" "testing" "github.com/stretchr/testify/assert" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/http/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(emptyroute)) } type emptyroute struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (e *emptyroute) Setup(t *testing.T) []framework.Option { e.sub = subscriber.New(t, subscriber.WithRoutes( "/a/b/c/d", "/123", ), subscriber.WithProgrammaticSubscriptions( subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "a", Route: "/a/b/c/d", Routes: subscriber.RoutesJSON{ Rules: []*subscriber.RuleJSON{ { Path: "/123", Match: "", }, }, }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "b", Route: "/a/b/c/d", }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "b", Routes: subscriber.RoutesJSON{ Rules: []*subscriber.RuleJSON{ { Path: "/123", Match: "", }, }, }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "c", Routes: subscriber.RoutesJSON{ Rules: []*subscriber.RuleJSON{ { Path: "/123", Match: "", }, }, }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "c", Route: "/a/b/c/d", }, ), ) e.daprd = daprd.New(t, daprd.WithAppPort(e.sub.Port()), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(e.sub, e.daprd), } } func (e *emptyroute) Run(t *testing.T, ctx context.Context) { e.daprd.WaitUntilRunning(t, ctx) e.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: e.daprd, PubSubName: "mypub", Topic: "a", }) assert.Equal(t, "/123", e.sub.Receive(t, ctx).Route) e.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: e.daprd, PubSubName: "mypub", Topic: "b", }) assert.Equal(t, "/123", e.sub.Receive(t, ctx).Route) e.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: e.daprd, PubSubName: "mypub", Topic: "c", }) assert.Equal(t, "/a/b/c/d", e.sub.Receive(t, ctx).Route) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/http/mixed/emptyroute.go
GO
mit
3,054
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package mixed import ( "context" "testing" "github.com/stretchr/testify/assert" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/http/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(match)) } type match struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (m *match) Setup(t *testing.T) []framework.Option { m.sub = subscriber.New(t, subscriber.WithRoutes( "/a/b/c/d", "/123", ), subscriber.WithProgrammaticSubscriptions( subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "a", Route: "/a/b/c/d", Routes: subscriber.RoutesJSON{ Rules: []*subscriber.RuleJSON{ { Path: "/123", Match: `event.topic == "a"`, }, }, }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "b", Route: "/a/b/c/d", }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "b", Routes: subscriber.RoutesJSON{ Rules: []*subscriber.RuleJSON{ { Path: "/123", Match: `event.topic == "b"`, }, }, }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "c", Routes: subscriber.RoutesJSON{ Rules: []*subscriber.RuleJSON{ { Path: "/123", Match: `event.topic == "c"`, }, }, }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "c", Route: "/a/b/c/d", }, ), ) m.daprd = daprd.New(t, daprd.WithAppPort(m.sub.Port()), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(m.sub, m.daprd), } } func (m *match) Run(t *testing.T, ctx context.Context) { m.daprd.WaitUntilRunning(t, ctx) m.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: m.daprd, PubSubName: "mypub", Topic: "a", }) assert.Equal(t, "/123", m.sub.Receive(t, ctx).Route) m.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: m.daprd, PubSubName: "mypub", Topic: "b", }) assert.Equal(t, "/123", m.sub.Receive(t, ctx).Route) m.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: m.daprd, PubSubName: "mypub", Topic: "c", }) assert.Equal(t, "/a/b/c/d", m.sub.Receive(t, ctx).Route) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/http/mixed/match.go
GO
mit
3,088
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1alpha1 import ( "context" "testing" "github.com/stretchr/testify/assert" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/http/subscriber" "github.com/dapr/dapr/tests/integration/suite" "github.com/dapr/kit/ptr" ) func init() { suite.Register(new(basic)) } type basic struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (b *basic) Setup(t *testing.T) []framework.Option { b.sub = subscriber.New(t, subscriber.WithRoutes("/a"), subscriber.WithProgrammaticSubscriptions(subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "a", Route: "/a", }), ) b.daprd = daprd.New(t, daprd.WithAppPort(b.sub.Port()), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(b.sub, b.daprd), } } func (b *basic) Run(t *testing.T, ctx context.Context) { b.daprd.WaitUntilRunning(t, ctx) b.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: b.daprd, PubSubName: "mypub", Topic: "a", Data: `{"status": "completed"}`, }) resp := b.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.Route) assert.JSONEq(t, `{"status": "completed"}`, string(resp.Data())) assert.Equal(t, "1.0", resp.SpecVersion()) assert.Equal(t, "mypub", resp.Extensions()["pubsubname"]) assert.Equal(t, "a", resp.Extensions()["topic"]) assert.Equal(t, "com.dapr.event.sent", resp.Type()) assert.Equal(t, "text/plain", resp.DataContentType()) b.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: b.daprd, PubSubName: "mypub", Topic: "a", Data: `{"status": "completed"}`, DataContentType: ptr.Of("application/json"), }) resp = b.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.Route) assert.JSONEq(t, `{"status": "completed"}`, string(resp.Data())) assert.Equal(t, "1.0", resp.SpecVersion()) assert.Equal(t, "mypub", resp.Extensions()["pubsubname"]) assert.Equal(t, "a", resp.Extensions()["topic"]) assert.Equal(t, "com.dapr.event.sent", resp.Type()) assert.Equal(t, "application/json", resp.DataContentType()) b.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: b.daprd, PubSubName: "mypub", Topic: "a", Data: `{"status": "completed"}`, DataContentType: ptr.Of("foo/bar"), }) resp = b.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.Route) assert.JSONEq(t, `{"status": "completed"}`, string(resp.Data())) assert.Equal(t, "1.0", resp.SpecVersion()) assert.Equal(t, "mypub", resp.Extensions()["pubsubname"]) assert.Equal(t, "a", resp.Extensions()["topic"]) assert.Equal(t, "com.dapr.event.sent", resp.Type()) assert.Equal(t, "foo/bar", resp.DataContentType()) b.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: b.daprd, PubSubName: "mypub", Topic: "a", Data: "foo", }) resp = b.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.Route) assert.Equal(t, "foo", string(resp.Data())) assert.Equal(t, "1.0", resp.SpecVersion()) assert.Equal(t, "mypub", resp.Extensions()["pubsubname"]) assert.Equal(t, "a", resp.Extensions()["topic"]) assert.Equal(t, "com.dapr.event.sent", resp.Type()) assert.Equal(t, "text/plain", resp.DataContentType()) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/http/v1alpha1/basic.go
GO
mit
3,977
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1alpha1 import ( "context" "testing" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/http/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(bulk)) } type bulk struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (b *bulk) Setup(t *testing.T) []framework.Option { b.sub = subscriber.New(t, subscriber.WithBulkRoutes("/a", "/b"), subscriber.WithProgrammaticSubscriptions( subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "a", Route: "/a", BulkSubscribe: subscriber.BulkSubscribeJSON{ Enabled: true, MaxMessagesCount: 100, MaxAwaitDurationMs: 40, }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "b", Route: "/b", }, ), ) b.daprd = daprd.New(t, daprd.WithAppPort(b.sub.Port()), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(b.sub, b.daprd), } } func (b *bulk) Run(t *testing.T, ctx context.Context) { b.daprd.WaitUntilRunning(t, ctx) // TODO: @joshvanl: add support for bulk publish to in-memory pubsub. b.sub.PublishBulk(t, ctx, subscriber.PublishBulkRequest{ Daprd: b.daprd, PubSubName: "mypub", Topic: "a", Entries: []subscriber.PublishBulkRequestEntry{ {EntryID: "1", Event: `{"id": 1}`, ContentType: "application/json"}, {EntryID: "2", Event: `{"id": 2}`, ContentType: "application/json"}, {EntryID: "3", Event: `{"id": 3}`, ContentType: "application/json"}, {EntryID: "4", Event: `{"id": 4}`, ContentType: "application/json"}, }, }) b.sub.ReceiveBulk(t, ctx) b.sub.ReceiveBulk(t, ctx) b.sub.ReceiveBulk(t, ctx) b.sub.ReceiveBulk(t, ctx) b.sub.PublishBulk(t, ctx, subscriber.PublishBulkRequest{ Daprd: b.daprd, PubSubName: "mypub", Topic: "b", Entries: []subscriber.PublishBulkRequestEntry{ {EntryID: "1", Event: `{"id": 1}`, ContentType: "application/json"}, {EntryID: "2", Event: `{"id": 2}`, ContentType: "application/json"}, {EntryID: "3", Event: `{"id": 3}`, ContentType: "application/json"}, {EntryID: "4", Event: `{"id": 4}`, ContentType: "application/json"}, }, }) b.sub.ReceiveBulk(t, ctx) b.sub.ReceiveBulk(t, ctx) b.sub.ReceiveBulk(t, ctx) b.sub.ReceiveBulk(t, ctx) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/http/v1alpha1/bulk.go
GO
mit
3,110
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1alpha1 import ( "context" nethttp "net/http" "testing" "github.com/stretchr/testify/assert" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/http/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(deadletter)) } type deadletter struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (d *deadletter) Setup(t *testing.T) []framework.Option { d.sub = subscriber.New(t, subscriber.WithHandlerFunc("/a", func(w nethttp.ResponseWriter, r *nethttp.Request) { w.WriteHeader(nethttp.StatusServiceUnavailable) }), subscriber.WithRoutes("/b"), subscriber.WithProgrammaticSubscriptions( subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "a", Route: "/a", DeadLetterTopic: "mydead", }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "mydead", Route: "/b", }, ), ) d.daprd = daprd.New(t, daprd.WithAppPort(d.sub.Port()), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(d.sub, d.daprd), } } func (d *deadletter) Run(t *testing.T, ctx context.Context) { d.daprd.WaitUntilRunning(t, ctx) d.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: d.daprd, PubSubName: "mypub", Topic: "a", Data: `{"status": "completed"}`, }) resp := d.sub.Receive(t, ctx) assert.Equal(t, "/b", resp.Route) assert.Equal(t, "a", resp.Extensions()["topic"]) assert.Equal(t, `{"status": "completed"}`, string(resp.Data())) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/http/v1alpha1/deadletter.go
GO
mit
2,347
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1alpha1 import ( "context" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/http/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(missing)) } type missing struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (m *missing) Setup(t *testing.T) []framework.Option { m.sub = subscriber.New(t, subscriber.WithRoutes("/a", "/b", "/c"), subscriber.WithProgrammaticSubscriptions( subscriber.SubscriptionJSON{ PubsubName: "anotherpub", Topic: "a", Route: "/a", }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "c", Route: "/c", }, ), ) m.daprd = daprd.New(t, daprd.WithAppPort(m.sub.Port()), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(m.sub, m.daprd), } } func (m *missing) Run(t *testing.T, ctx context.Context) { m.daprd.WaitUntilRunning(t, ctx) meta, err := m.daprd.GRPCClient(t, ctx).GetMetadata(ctx, new(rtv1.GetMetadataRequest)) require.NoError(t, err) assert.Len(t, meta.GetRegisteredComponents(), 1) assert.Len(t, meta.GetSubscriptions(), 2) m.sub.ExpectPublishError(t, ctx, subscriber.PublishRequest{ Daprd: m.daprd, PubSubName: "anotherpub", Topic: "a", Data: `{"status": "completed"}`, }) m.sub.ExpectPublishNoReceive(t, ctx, subscriber.PublishRequest{ Daprd: m.daprd, PubSubName: "mypub", Topic: "b", Data: `{"status": "completed"}`, }) m.sub.ExpectPublishReceive(t, ctx, subscriber.PublishRequest{ Daprd: m.daprd, PubSubName: "mypub", Topic: "c", Data: `{"status": "completed"}`, }) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/http/v1alpha1/missing.go
GO
mit
2,616
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1alpha1 import ( "bytes" "context" "encoding/json" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/dapr/components-contrib/pubsub" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/http/subscriber" "github.com/dapr/dapr/tests/integration/suite" "github.com/dapr/kit/ptr" ) func init() { suite.Register(new(rawpayload)) } type rawpayload struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (r *rawpayload) Setup(t *testing.T) []framework.Option { r.sub = subscriber.New(t, subscriber.WithRoutes("/a"), subscriber.WithProgrammaticSubscriptions( subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "a", Route: "/a", Metadata: map[string]string{ "rawPayload": "true", }, }, ), ) r.daprd = daprd.New(t, daprd.WithAppPort(r.sub.Port()), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(r.sub, r.daprd), } } func (r *rawpayload) Run(t *testing.T, ctx context.Context) { r.daprd.WaitUntilRunning(t, ctx) r.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: r.daprd, PubSubName: "mypub", Topic: "a", Data: `{"status": "completed"}`, }) resp := r.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.Route) assert.Equal(t, "1.0", resp.SpecVersion()) assert.Equal(t, "mypub", resp.Extensions()["pubsubname"]) assert.Equal(t, "a", resp.Extensions()["topic"]) assert.Equal(t, "com.dapr.event.sent", resp.Type()) assert.Equal(t, "application/octet-stream", resp.DataContentType()) var ce map[string]any require.NoError(t, json.NewDecoder(bytes.NewReader(resp.Data())).Decode(&ce)) exp := pubsub.NewCloudEventsEnvelope("", "", "com.dapr.event.sent", "", "a", "mypub", "text/plain", []byte(`{"status": "completed"}`), "", "") exp["id"] = ce["id"] exp["source"] = ce["source"] exp["time"] = ce["time"] exp["traceid"] = ce["traceid"] exp["traceparent"] = ce["traceparent"] assert.Equal(t, exp, ce) r.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: r.daprd, PubSubName: "mypub", Topic: "a", Data: `{"status": "completed"}`, DataContentType: ptr.Of("application/json"), }) resp = r.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.Route) assert.Equal(t, "1.0", resp.SpecVersion()) assert.Equal(t, "mypub", resp.Extensions()["pubsubname"]) assert.Equal(t, "a", resp.Extensions()["topic"]) assert.Equal(t, "com.dapr.event.sent", resp.Type()) assert.Equal(t, "application/octet-stream", resp.DataContentType()) require.NoError(t, json.NewDecoder(bytes.NewReader(resp.Data())).Decode(&ce)) exp = pubsub.NewCloudEventsEnvelope("", "", "com.dapr.event.sent", "", "a", "mypub", "application/json", []byte(`{"status": "completed"}`), "", "") exp["id"] = ce["id"] exp["source"] = ce["source"] exp["time"] = ce["time"] exp["traceid"] = ce["traceid"] exp["traceparent"] = ce["traceparent"] assert.Equal(t, exp, ce) r.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: r.daprd, PubSubName: "mypub", Topic: "a", Data: `{"status": "completed"}`, DataContentType: ptr.Of("foo/bar"), }) resp = r.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.Route) assert.Equal(t, "1.0", resp.SpecVersion()) assert.Equal(t, "mypub", resp.Extensions()["pubsubname"]) assert.Equal(t, "a", resp.Extensions()["topic"]) assert.Equal(t, "com.dapr.event.sent", resp.Type()) assert.Equal(t, "application/octet-stream", resp.DataContentType()) require.NoError(t, json.NewDecoder(bytes.NewReader(resp.Data())).Decode(&ce)) exp = pubsub.NewCloudEventsEnvelope("", "", "com.dapr.event.sent", "", "a", "mypub", "application/json", nil, "", "") exp["id"] = ce["id"] exp["data"] = `{"status": "completed"}` exp["source"] = ce["source"] exp["time"] = ce["time"] exp["traceid"] = ce["traceid"] exp["traceparent"] = ce["traceparent"] exp["datacontenttype"] = "foo/bar" assert.Equal(t, exp, ce) r.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: r.daprd, PubSubName: "mypub", Topic: "a", Data: "foo", }) resp = r.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.Route) assert.Equal(t, "1.0", resp.SpecVersion()) assert.Equal(t, "mypub", resp.Extensions()["pubsubname"]) assert.Equal(t, "a", resp.Extensions()["topic"]) assert.Equal(t, "com.dapr.event.sent", resp.Type()) assert.Equal(t, "application/octet-stream", resp.DataContentType()) require.NoError(t, json.NewDecoder(bytes.NewReader(resp.Data())).Decode(&ce)) exp = pubsub.NewCloudEventsEnvelope("", "", "com.dapr.event.sent", "", "a", "mypub", "application/json", []byte("foo"), "", "") exp["id"] = ce["id"] exp["source"] = ce["source"] exp["time"] = ce["time"] exp["traceid"] = ce["traceid"] exp["traceparent"] = ce["traceparent"] exp["datacontenttype"] = "text/plain" assert.Equal(t, exp, ce) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/http/v1alpha1/rawpayload.go
GO
mit
5,696
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1alpha1 import ( "context" "testing" "github.com/stretchr/testify/assert" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/http/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(route)) } type route struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (r *route) Setup(t *testing.T) []framework.Option { r.sub = subscriber.New(t, subscriber.WithRoutes("/a", "/a/b/c/d", "/d/c/b/a"), subscriber.WithProgrammaticSubscriptions( subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "a", Route: "/a/b/c/d", }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "a", Route: "/a", }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "b", Route: "/a", }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "b", Route: "/d/c/b/a", }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "b", Route: "/a/b/c/d", }, ), ) r.daprd = daprd.New(t, daprd.WithAppPort(r.sub.Port()), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(r.sub, r.daprd), } } func (r *route) Run(t *testing.T, ctx context.Context) { r.daprd.WaitUntilRunning(t, ctx) r.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: r.daprd, PubSubName: "mypub", Topic: "a", }) resp := r.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.Route) assert.Empty(t, resp.Data()) // Uses the first defined route for a topic when two declared routes match // the topic. r.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: r.daprd, PubSubName: "mypub", Topic: "b", }) resp = r.sub.Receive(t, ctx) assert.Equal(t, "/a/b/c/d", resp.Route) assert.Empty(t, resp.Data()) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/http/v1alpha1/route.go
GO
mit
2,656
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v2alpha1 import ( "context" "testing" "github.com/stretchr/testify/assert" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/http/subscriber" "github.com/dapr/dapr/tests/integration/suite" "github.com/dapr/kit/ptr" ) func init() { suite.Register(new(basic)) } type basic struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (b *basic) Setup(t *testing.T) []framework.Option { b.sub = subscriber.New(t, subscriber.WithRoutes("/a"), subscriber.WithProgrammaticSubscriptions(subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "a", Routes: subscriber.RoutesJSON{ Default: "/a", }, }), ) b.daprd = daprd.New(t, daprd.WithAppPort(b.sub.Port()), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(b.sub, b.daprd), } } func (b *basic) Run(t *testing.T, ctx context.Context) { b.daprd.WaitUntilRunning(t, ctx) b.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: b.daprd, PubSubName: "mypub", Topic: "a", Data: `{"status": "completed"}`, }) resp := b.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.Route) assert.JSONEq(t, `{"status": "completed"}`, string(resp.Data())) assert.Equal(t, "1.0", resp.SpecVersion()) assert.Equal(t, "mypub", resp.Extensions()["pubsubname"]) assert.Equal(t, "a", resp.Extensions()["topic"]) assert.Equal(t, "com.dapr.event.sent", resp.Type()) assert.Equal(t, "text/plain", resp.DataContentType()) b.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: b.daprd, PubSubName: "mypub", Topic: "a", Data: `{"status": "completed"}`, DataContentType: ptr.Of("application/json"), }) resp = b.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.Route) assert.JSONEq(t, `{"status": "completed"}`, string(resp.Data())) assert.Equal(t, "1.0", resp.SpecVersion()) assert.Equal(t, "mypub", resp.Extensions()["pubsubname"]) assert.Equal(t, "a", resp.Extensions()["topic"]) assert.Equal(t, "com.dapr.event.sent", resp.Type()) assert.Equal(t, "application/json", resp.DataContentType()) b.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: b.daprd, PubSubName: "mypub", Topic: "a", Data: `{"status": "completed"}`, DataContentType: ptr.Of("foo/bar"), }) resp = b.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.Route) assert.JSONEq(t, `{"status": "completed"}`, string(resp.Data())) assert.Equal(t, "1.0", resp.SpecVersion()) assert.Equal(t, "mypub", resp.Extensions()["pubsubname"]) assert.Equal(t, "a", resp.Extensions()["topic"]) assert.Equal(t, "com.dapr.event.sent", resp.Type()) assert.Equal(t, "foo/bar", resp.DataContentType()) b.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: b.daprd, PubSubName: "mypub", Topic: "a", Data: "foo", }) resp = b.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.Route) assert.Equal(t, "foo", string(resp.Data())) assert.Equal(t, "1.0", resp.SpecVersion()) assert.Equal(t, "mypub", resp.Extensions()["pubsubname"]) assert.Equal(t, "a", resp.Extensions()["topic"]) assert.Equal(t, "com.dapr.event.sent", resp.Type()) assert.Equal(t, "text/plain", resp.DataContentType()) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/http/v2alpha1/basic.go
GO
mit
4,015
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v2alpha1 import ( "context" "testing" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/http/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(bulk)) } type bulk struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (b *bulk) Setup(t *testing.T) []framework.Option { b.sub = subscriber.New(t, subscriber.WithBulkRoutes("/a", "/b"), subscriber.WithProgrammaticSubscriptions(subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "a", Routes: subscriber.RoutesJSON{ Default: "/a", }, BulkSubscribe: subscriber.BulkSubscribeJSON{ Enabled: true, MaxMessagesCount: 100, MaxAwaitDurationMs: 40, }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "b", Routes: subscriber.RoutesJSON{ Default: "/b", }, }, ), ) b.daprd = daprd.New(t, daprd.WithAppPort(b.sub.Port()), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(b.sub, b.daprd), } } func (b *bulk) Run(t *testing.T, ctx context.Context) { b.daprd.WaitUntilRunning(t, ctx) // TODO: @joshvanl: add support for bulk publish to in-memory pubsub. b.sub.PublishBulk(t, ctx, subscriber.PublishBulkRequest{ Daprd: b.daprd, PubSubName: "mypub", Topic: "a", Entries: []subscriber.PublishBulkRequestEntry{ {EntryID: "1", Event: `{"id": 1}`, ContentType: "application/json"}, {EntryID: "2", Event: `{"id": 2}`, ContentType: "application/json"}, {EntryID: "3", Event: `{"id": 3}`, ContentType: "application/json"}, {EntryID: "4", Event: `{"id": 4}`, ContentType: "application/json"}, }, }) b.sub.ReceiveBulk(t, ctx) b.sub.ReceiveBulk(t, ctx) b.sub.ReceiveBulk(t, ctx) b.sub.ReceiveBulk(t, ctx) b.sub.PublishBulk(t, ctx, subscriber.PublishBulkRequest{ Daprd: b.daprd, PubSubName: "mypub", Topic: "b", Entries: []subscriber.PublishBulkRequestEntry{ {EntryID: "1", Event: `{"id": 1}`, ContentType: "application/json"}, {EntryID: "2", Event: `{"id": 2}`, ContentType: "application/json"}, {EntryID: "3", Event: `{"id": 3}`, ContentType: "application/json"}, {EntryID: "4", Event: `{"id": 4}`, ContentType: "application/json"}, }, }) b.sub.ReceiveBulk(t, ctx) b.sub.ReceiveBulk(t, ctx) b.sub.ReceiveBulk(t, ctx) b.sub.ReceiveBulk(t, ctx) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/http/v2alpha1/bulk.go
GO
mit
3,175
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v2alpha1 import ( "context" nethttp "net/http" "testing" "github.com/stretchr/testify/assert" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/http/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(deadletter)) } type deadletter struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (d *deadletter) Setup(t *testing.T) []framework.Option { d.sub = subscriber.New(t, subscriber.WithRoutes("/b"), subscriber.WithHandlerFunc("/a", func(w nethttp.ResponseWriter, r *nethttp.Request) { w.WriteHeader(nethttp.StatusServiceUnavailable) }), subscriber.WithProgrammaticSubscriptions(subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "a", Routes: subscriber.RoutesJSON{ Default: "/a", }, DeadLetterTopic: "mydead", }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "mydead", Routes: subscriber.RoutesJSON{ Default: "/b", }, }, ), ) d.daprd = daprd.New(t, daprd.WithAppPort(d.sub.Port()), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(d.sub, d.daprd), } } func (d *deadletter) Run(t *testing.T, ctx context.Context) { d.daprd.WaitUntilRunning(t, ctx) d.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: d.daprd, PubSubName: "mypub", Topic: "a", Data: `{"status": "completed"}`, }) resp := d.sub.Receive(t, ctx) assert.Equal(t, "/b", resp.Route) assert.Equal(t, "a", resp.Extensions()["topic"]) assert.Equal(t, `{"status": "completed"}`, string(resp.Data())) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/http/v2alpha1/deadletter.go
GO
mit
2,401
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v2alpha1 import ( "context" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/http/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(missing)) } type missing struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (m *missing) Setup(t *testing.T) []framework.Option { m.sub = subscriber.New(t, subscriber.WithRoutes("/a", "/b", "/c"), subscriber.WithProgrammaticSubscriptions(subscriber.SubscriptionJSON{ PubsubName: "anotherpub", Topic: "a", Routes: subscriber.RoutesJSON{ Default: "/a", }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "c", Routes: subscriber.RoutesJSON{ Default: "/c", }, }, ), ) m.daprd = daprd.New(t, daprd.WithAppPort(m.sub.Port()), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(m.sub, m.daprd), } } func (m *missing) Run(t *testing.T, ctx context.Context) { m.daprd.WaitUntilRunning(t, ctx) meta, err := m.daprd.GRPCClient(t, ctx).GetMetadata(ctx, new(rtv1.GetMetadataRequest)) require.NoError(t, err) assert.Len(t, meta.GetRegisteredComponents(), 1) assert.Len(t, meta.GetSubscriptions(), 2) m.sub.ExpectPublishError(t, ctx, subscriber.PublishRequest{ Daprd: m.daprd, PubSubName: "anotherpub", Topic: "a", Data: `{"status": "completed"}`, }) m.sub.ExpectPublishNoReceive(t, ctx, subscriber.PublishRequest{ Daprd: m.daprd, PubSubName: "mypub", Topic: "b", Data: `{"status": "completed"}`, }) m.sub.ExpectPublishReceive(t, ctx, subscriber.PublishRequest{ Daprd: m.daprd, PubSubName: "mypub", Topic: "c", Data: `{"status": "completed"}`, }) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/http/v2alpha1/missing.go
GO
mit
2,686
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v2alpha1 import ( "bytes" "context" "encoding/json" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/dapr/components-contrib/pubsub" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/http/subscriber" "github.com/dapr/dapr/tests/integration/suite" "github.com/dapr/kit/ptr" ) func init() { suite.Register(new(rawpayload)) } type rawpayload struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (r *rawpayload) Setup(t *testing.T) []framework.Option { r.sub = subscriber.New(t, subscriber.WithRoutes("/a"), subscriber.WithProgrammaticSubscriptions(subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "a", Routes: subscriber.RoutesJSON{ Default: "/a", }, Metadata: map[string]string{ "rawPayload": "true", }, }), ) r.daprd = daprd.New(t, daprd.WithAppPort(r.sub.Port()), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(r.sub, r.daprd), } } func (r *rawpayload) Run(t *testing.T, ctx context.Context) { r.daprd.WaitUntilRunning(t, ctx) r.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: r.daprd, PubSubName: "mypub", Topic: "a", Data: `{"status": "completed"}`, }) resp := r.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.Route) assert.Equal(t, "1.0", resp.SpecVersion()) assert.Equal(t, "mypub", resp.Extensions()["pubsubname"]) assert.Equal(t, "a", resp.Extensions()["topic"]) assert.Equal(t, "com.dapr.event.sent", resp.Type()) assert.Equal(t, "application/octet-stream", resp.DataContentType()) var ce map[string]any require.NoError(t, json.NewDecoder(bytes.NewReader(resp.Data())).Decode(&ce)) exp := pubsub.NewCloudEventsEnvelope("", "", "com.dapr.event.sent", "", "a", "mypub", "text/plain", []byte(`{"status": "completed"}`), "", "") exp["id"] = ce["id"] exp["source"] = ce["source"] exp["time"] = ce["time"] exp["traceid"] = ce["traceid"] exp["traceparent"] = ce["traceparent"] assert.Equal(t, exp, ce) r.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: r.daprd, PubSubName: "mypub", Topic: "a", Data: `{"status": "completed"}`, DataContentType: ptr.Of("application/json"), }) resp = r.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.Route) assert.Equal(t, "1.0", resp.SpecVersion()) assert.Equal(t, "mypub", resp.Extensions()["pubsubname"]) assert.Equal(t, "a", resp.Extensions()["topic"]) assert.Equal(t, "com.dapr.event.sent", resp.Type()) assert.Equal(t, "application/octet-stream", resp.DataContentType()) require.NoError(t, json.NewDecoder(bytes.NewReader(resp.Data())).Decode(&ce)) exp = pubsub.NewCloudEventsEnvelope("", "", "com.dapr.event.sent", "", "a", "mypub", "application/json", []byte(`{"status": "completed"}`), "", "") exp["id"] = ce["id"] exp["source"] = ce["source"] exp["time"] = ce["time"] exp["traceid"] = ce["traceid"] exp["traceparent"] = ce["traceparent"] assert.Equal(t, exp, ce) r.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: r.daprd, PubSubName: "mypub", Topic: "a", Data: `{"status": "completed"}`, DataContentType: ptr.Of("foo/bar"), }) resp = r.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.Route) assert.Equal(t, "1.0", resp.SpecVersion()) assert.Equal(t, "mypub", resp.Extensions()["pubsubname"]) assert.Equal(t, "a", resp.Extensions()["topic"]) assert.Equal(t, "com.dapr.event.sent", resp.Type()) assert.Equal(t, "application/octet-stream", resp.DataContentType()) require.NoError(t, json.NewDecoder(bytes.NewReader(resp.Data())).Decode(&ce)) exp = pubsub.NewCloudEventsEnvelope("", "", "com.dapr.event.sent", "", "a", "mypub", "application/json", nil, "", "") exp["id"] = ce["id"] exp["data"] = `{"status": "completed"}` exp["source"] = ce["source"] exp["time"] = ce["time"] exp["traceid"] = ce["traceid"] exp["traceparent"] = ce["traceparent"] exp["datacontenttype"] = "foo/bar" assert.Equal(t, exp, ce) r.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: r.daprd, PubSubName: "mypub", Topic: "a", Data: "foo", }) resp = r.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.Route) assert.Equal(t, "1.0", resp.SpecVersion()) assert.Equal(t, "mypub", resp.Extensions()["pubsubname"]) assert.Equal(t, "a", resp.Extensions()["topic"]) assert.Equal(t, "com.dapr.event.sent", resp.Type()) assert.Equal(t, "application/octet-stream", resp.DataContentType()) require.NoError(t, json.NewDecoder(bytes.NewReader(resp.Data())).Decode(&ce)) exp = pubsub.NewCloudEventsEnvelope("", "", "com.dapr.event.sent", "", "a", "mypub", "application/json", []byte("foo"), "", "") exp["id"] = ce["id"] exp["source"] = ce["source"] exp["time"] = ce["time"] exp["traceid"] = ce["traceid"] exp["traceparent"] = ce["traceparent"] exp["datacontenttype"] = "text/plain" assert.Equal(t, exp, ce) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/http/v2alpha1/rawpayload.go
GO
mit
5,719
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package routes import ( "context" "testing" "github.com/stretchr/testify/assert" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/http/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(defaultroute)) } type defaultroute struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (d *defaultroute) Setup(t *testing.T) []framework.Option { d.sub = subscriber.New(t, subscriber.WithRoutes("/a/b/c/d", "/a", "/b", "/d/c/b/a"), subscriber.WithProgrammaticSubscriptions( subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "a", Routes: subscriber.RoutesJSON{ Default: "/a/b/c/d", }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "a", Routes: subscriber.RoutesJSON{ Default: "/a", }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "b", Routes: subscriber.RoutesJSON{ Default: "/b", }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "b", Routes: subscriber.RoutesJSON{ Default: "/d/c/b/a", }, }, ), ) d.daprd = daprd.New(t, daprd.WithAppPort(d.sub.Port()), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(d.sub, d.daprd), } } func (d *defaultroute) Run(t *testing.T, ctx context.Context) { d.daprd.WaitUntilRunning(t, ctx) d.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: d.daprd, PubSubName: "mypub", Topic: "a", }) resp := d.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.Route) assert.Empty(t, resp.Data()) d.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: d.daprd, PubSubName: "mypub", Topic: "b", }) resp = d.sub.Receive(t, ctx) assert.Equal(t, "/d/c/b/a", resp.Route) assert.Empty(t, resp.Data()) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/http/v2alpha1/routes/defaultroute.go
GO
mit
2,645
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package routes import ( "context" "testing" "github.com/stretchr/testify/assert" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/http/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(emptymatch)) } type emptymatch struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (e *emptymatch) Setup(t *testing.T) []framework.Option { e.sub = subscriber.New(t, subscriber.WithRoutes( "/justpath", "/abc", "/123", "/def", "/zyz", "/aaa", "/bbb", "/xyz", "/456", "/789", ), subscriber.WithProgrammaticSubscriptions( subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "justpath", Routes: subscriber.RoutesJSON{ Rules: []*subscriber.RuleJSON{ {Path: "/justpath", Match: ""}, }, }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "defaultandpath", Routes: subscriber.RoutesJSON{ Default: "/abc", Rules: []*subscriber.RuleJSON{ {Path: "/123", Match: ""}, }, }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "multipaths", Routes: subscriber.RoutesJSON{ Rules: []*subscriber.RuleJSON{ {Path: "/xyz", Match: ""}, {Path: "/456", Match: ""}, {Path: "/789", Match: ""}, }, }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "defaultandpaths", Routes: subscriber.RoutesJSON{ Default: "/def", Rules: []*subscriber.RuleJSON{ {Path: "/zyz", Match: ""}, {Path: "/aaa", Match: ""}, {Path: "/bbb", Match: ""}, }, }, }, ), ) e.daprd = daprd.New(t, daprd.WithAppPort(e.sub.Port()), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(e.sub, e.daprd), } } func (e *emptymatch) Run(t *testing.T, ctx context.Context) { e.daprd.WaitUntilRunning(t, ctx) e.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: e.daprd, PubSubName: "mypub", Topic: "justpath", }) resp := e.sub.Receive(t, ctx) assert.Equal(t, "/justpath", resp.Route) e.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: e.daprd, PubSubName: "mypub", Topic: "defaultandpath", }) resp = e.sub.Receive(t, ctx) assert.Equal(t, "/123", resp.Route) e.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: e.daprd, PubSubName: "mypub", Topic: "multipaths", }) resp = e.sub.Receive(t, ctx) assert.Equal(t, "/xyz", resp.Route) e.sub.Publish(t, ctx, subscriber.PublishRequest{ Daprd: e.daprd, PubSubName: "mypub", Topic: "defaultandpaths", }) resp = e.sub.Receive(t, ctx) assert.Equal(t, "/zyz", resp.Route) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/http/v2alpha1/routes/emptymatch.go
GO
mit
3,497
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package routes import ( "context" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/http/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(match)) } type match struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (m *match) Setup(t *testing.T) []framework.Option { m.sub = subscriber.New(t, subscriber.WithRoutes( "/aaa", "/type", "/foo", "/bar", "/topic", "/123", "/456", "/order7def", "/order7rule", ), subscriber.WithProgrammaticSubscriptions( subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "type", Routes: subscriber.RoutesJSON{ Rules: []*subscriber.RuleJSON{ { Path: "/type", Match: `event.type == "com.dapr.event.sent"`, }, {Path: "/foo", Match: ""}, { Path: "/bar", Match: `event.type == "com.dapr.event.recv"`, }, }, }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "order1", Routes: subscriber.RoutesJSON{ Default: "/aaa", Rules: []*subscriber.RuleJSON{ { Path: "/type", Match: `event.type == "com.dapr.event.sent"`, }, { Path: "/topic", Match: `event.topic == "order1"`, }, }, }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "order2", Routes: subscriber.RoutesJSON{ Default: "/aaa", Rules: []*subscriber.RuleJSON{ { Path: "/topic", Match: `event.topic == "order2"`, }, { Path: "/type", Match: `event.type == "com.dapr.event.sent"`, }, }, }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "order3", Routes: subscriber.RoutesJSON{ Default: "/aaa", Rules: []*subscriber.RuleJSON{ { Path: "/123", Match: `event.topic == "order3"`, }, { Path: "/456", Match: `event.topic == "order3"`, }, }, }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "order4", Routes: subscriber.RoutesJSON{ Rules: []*subscriber.RuleJSON{ { Path: "/123", Match: `event.topic == "order5"`, }, { Path: "/456", Match: `event.topic == "order6"`, }, }, }, }, subscriber.SubscriptionJSON{ PubsubName: "mypub", Topic: "order7", Routes: subscriber.RoutesJSON{ Default: "/order7def", Rules: []*subscriber.RuleJSON{ { Path: "/order7rule", Match: "", }, }, }, }, ), ) m.daprd = daprd.New(t, daprd.WithAppPort(m.sub.Port()), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(m.sub, m.daprd), } } func (m *match) Run(t *testing.T, ctx context.Context) { m.daprd.WaitUntilRunning(t, ctx) client := m.daprd.GRPCClient(t, ctx) _, err := client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "type", }) require.NoError(t, err) resp := m.sub.Receive(t, ctx) assert.Equal(t, "/type", resp.Route) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "order1", }) require.NoError(t, err) resp = m.sub.Receive(t, ctx) assert.Equal(t, "/type", resp.Route) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "order2", }) require.NoError(t, err) resp = m.sub.Receive(t, ctx) assert.Equal(t, "/topic", resp.Route) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "order3", }) require.NoError(t, err) resp = m.sub.Receive(t, ctx) assert.Equal(t, "/123", resp.Route) m.sub.ExpectPublishNoReceive(t, ctx, subscriber.PublishRequest{ Daprd: m.daprd, PubSubName: "mypub", Topic: "order4", }) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "order7", }) require.NoError(t, err) resp = m.sub.Receive(t, ctx) assert.Equal(t, "/order7rule", resp.Route) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/http/v2alpha1/routes/match.go
GO
mit
5,049
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v2alpha1 import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/subscriptions/programmatic/http/v2alpha1/routes" )
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/http/v2alpha1/v2alpha1.go
GO
mit
694
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package programmatic import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/subscriptions/programmatic/grpc" _ "github.com/dapr/dapr/tests/integration/suite/daprd/subscriptions/programmatic/http" )
mikeee/dapr
tests/integration/suite/daprd/subscriptions/programmatic/programmatic.go
GO
mit
770
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package stream import ( "context" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/grpc/app" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(basic)) } type basic struct { daprd *daprd.Daprd } func (b *basic) Setup(t *testing.T) []framework.Option { app := app.New(t) b.daprd = daprd.New(t, daprd.WithAppProtocol("grpc"), daprd.WithAppPort(app.Port(t)), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(app, b.daprd), } } func (b *basic) Run(t *testing.T, ctx context.Context) { b.daprd.WaitUntilRunning(t, ctx) client := b.daprd.GRPCClient(t, ctx) stream, err := client.SubscribeTopicEventsAlpha1(ctx) require.NoError(t, err) require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_InitialRequest{ InitialRequest: &rtv1.SubscribeTopicEventsInitialRequestAlpha1{ PubsubName: "mypub", Topic: "a", }, }, })) assert.EventuallyWithT(t, func(c *assert.CollectT) { assert.Len(c, b.daprd.GetMetaSubscriptions(c, ctx), 1) }, time.Second*10, time.Millisecond*10) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "a", Data: []byte(`{"status": "completed"}`), DataContentType: "application/json", }) require.NoError(t, err) event, err := stream.Recv() require.NoError(t, err) assert.Equal(t, "a", event.GetTopic()) assert.Equal(t, "mypub", event.GetPubsubName()) assert.JSONEq(t, `{"status": "completed"}`, string(event.GetData())) assert.Equal(t, "/", event.GetPath()) require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_EventResponse{ EventResponse: &rtv1.SubscribeTopicEventsResponseAlpha1{ Id: event.GetId(), Status: &rtv1.TopicEventResponse{Status: rtv1.TopicEventResponse_SUCCESS}, }, }, })) require.NoError(t, stream.CloseSend()) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/stream/basic.go
GO
mit
2,969
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package stream import ( "context" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/grpc/app" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(bulk)) } type bulk struct { daprd *daprd.Daprd } func (b *bulk) Setup(t *testing.T) []framework.Option { app := app.New(t) b.daprd = daprd.New(t, daprd.WithAppProtocol("grpc"), daprd.WithAppPort(app.Port(t)), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(app, b.daprd), } } func (b *bulk) Run(t *testing.T, ctx context.Context) { b.daprd.WaitUntilRunning(t, ctx) client := b.daprd.GRPCClient(t, ctx) stream, err := client.SubscribeTopicEventsAlpha1(ctx) require.NoError(t, err) require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_InitialRequest{ InitialRequest: &rtv1.SubscribeTopicEventsInitialRequestAlpha1{ PubsubName: "mypub", Topic: "a", }, }, })) t.Cleanup(func() { require.NoError(t, stream.CloseSend()) }) assert.EventuallyWithT(t, func(c *assert.CollectT) { assert.Len(c, b.daprd.GetMetaSubscriptions(c, ctx), 1) }, time.Second*10, time.Millisecond*10) errCh := make(chan error, 8) go func() { for i := 0; i < 4; i++ { event, serr := stream.Recv() errCh <- serr errCh <- stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_EventResponse{ EventResponse: &rtv1.SubscribeTopicEventsResponseAlpha1{ Id: event.GetId(), Status: &rtv1.TopicEventResponse{Status: rtv1.TopicEventResponse_SUCCESS}, }, }, }) } }() resp, err := client.BulkPublishEventAlpha1(ctx, &rtv1.BulkPublishRequest{ PubsubName: "mypub", Topic: "a", Entries: []*rtv1.BulkPublishRequestEntry{ {EntryId: "1", Event: []byte(`{"id": 1}`), ContentType: "application/json"}, {EntryId: "2", Event: []byte(`{"id": 2}`), ContentType: "application/json"}, {EntryId: "3", Event: []byte(`{"id": 3}`), ContentType: "application/json"}, {EntryId: "4", Event: []byte(`{"id": 4}`), ContentType: "application/json"}, }, }) require.NoError(t, err) assert.Empty(t, len(resp.GetFailedEntries())) for i := 0; i < 8; i++ { require.NoError(t, <-errCh) } }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/stream/bulk.go
GO
mit
3,272
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package stream import ( "context" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(disconnect)) } type disconnect struct { daprd *daprd.Daprd } func (d *disconnect) Setup(t *testing.T) []framework.Option { d.daprd = daprd.New(t, daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return nil } func (d *disconnect) Run(t *testing.T, ctx context.Context) { d.daprd.Run(t, ctx) d.daprd.WaitUntilRunning(t, ctx) client := d.daprd.GRPCClient(t, ctx) stream1, err := client.SubscribeTopicEventsAlpha1(ctx) require.NoError(t, err) require.NoError(t, stream1.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_InitialRequest{ InitialRequest: &rtv1.SubscribeTopicEventsInitialRequestAlpha1{ PubsubName: "mypub", Topic: "a", }, }, })) stream2, err := client.SubscribeTopicEventsAlpha1(ctx) require.NoError(t, err) assert.EventuallyWithT(t, func(c *assert.CollectT) { assert.Len(c, d.daprd.GetMetaSubscriptions(c, ctx), 1) }, time.Second*10, time.Millisecond*10) d.daprd.Cleanup(t) require.NoError(t, stream1.CloseSend()) require.NoError(t, stream2.CloseSend()) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/stream/disconnect.go
GO
mit
2,123
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package stream import ( "context" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc/status" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/grpc/app" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(errors)) } type errors struct { daprd *daprd.Daprd } func (e *errors) Setup(t *testing.T) []framework.Option { app := app.New(t) e.daprd = daprd.New(t, daprd.WithAppProtocol("grpc"), daprd.WithAppPort(app.Port(t)), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(app, e.daprd), } } func (e *errors) Run(t *testing.T, ctx context.Context) { e.daprd.WaitUntilRunning(t, ctx) client := e.daprd.GRPCClient(t, ctx) stream, err := client.SubscribeTopicEventsAlpha1(ctx) require.NoError(t, err) require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_InitialRequest{ InitialRequest: &rtv1.SubscribeTopicEventsInitialRequestAlpha1{ PubsubName: "", Topic: "a", }, }, })) _, err = stream.Recv() s, ok := status.FromError(err) require.True(t, ok) assert.Contains(t, s.Message(), "pubsubName is required") require.NoError(t, stream.CloseSend()) stream, err = client.SubscribeTopicEventsAlpha1(ctx) require.NoError(t, err) require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_InitialRequest{ InitialRequest: &rtv1.SubscribeTopicEventsInitialRequestAlpha1{ PubsubName: "mypub", Topic: "", }, }, })) _, err = stream.Recv() s, ok = status.FromError(err) require.True(t, ok) assert.Contains(t, s.Message(), "topic is required") require.NoError(t, stream.CloseSend()) stream, err = client.SubscribeTopicEventsAlpha1(ctx) require.NoError(t, err) require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_InitialRequest{ InitialRequest: &rtv1.SubscribeTopicEventsInitialRequestAlpha1{ PubsubName: "mypub", Topic: "a", }, }, })) t.Cleanup(func() { require.NoError(t, stream.CloseSend()) }) assert.EventuallyWithT(t, func(c *assert.CollectT) { assert.Len(c, e.daprd.GetMetaSubscriptions(c, ctx), 1) }, time.Second*10, time.Millisecond*10) streamDupe, err := client.SubscribeTopicEventsAlpha1(ctx) require.NoError(t, err) require.NoError(t, streamDupe.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_InitialRequest{ InitialRequest: &rtv1.SubscribeTopicEventsInitialRequestAlpha1{ PubsubName: "mypub", Topic: "a", }, }, })) t.Cleanup(func() { require.NoError(t, streamDupe.CloseSend()) }) _, err = streamDupe.Recv() s, ok = status.FromError(err) require.True(t, ok) assert.Contains(t, s.Message(), `streamer already subscribed to pubsub "mypub" topic "a"`) streamDoubleInit, err := client.SubscribeTopicEventsAlpha1(ctx) require.NoError(t, err) t.Cleanup(func() { require.NoError(t, streamDoubleInit.CloseSend()) }) require.NoError(t, streamDoubleInit.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_InitialRequest{ InitialRequest: &rtv1.SubscribeTopicEventsInitialRequestAlpha1{ PubsubName: "mypub", Topic: "b", }, }, })) require.NoError(t, streamDoubleInit.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_InitialRequest{ InitialRequest: &rtv1.SubscribeTopicEventsInitialRequestAlpha1{ PubsubName: "mypub", Topic: "b", }, }, })) _, err = streamDoubleInit.Recv() s, ok = status.FromError(err) require.True(t, ok) assert.Contains(t, s.Message(), "duplicate initial request received") }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/stream/errors.go
GO
mit
4,794
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package stream import ( "context" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/http/app" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(healthz)) } type healthz struct { app *app.App daprd *daprd.Daprd } func (h *healthz) Setup(t *testing.T) []framework.Option { h.app = app.New(t, app.WithInitialHealth(false), ) h.daprd = daprd.New(t, daprd.WithAppHealthCheck(true), daprd.WithAppHealthProbeInterval(1), daprd.WithAppHealthProbeThreshold(1), daprd.WithAppPort(h.app.Port()), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(h.app, h.daprd), } } func (h *healthz) Run(t *testing.T, ctx context.Context) { h.daprd.WaitUntilRunning(t, ctx) client := h.daprd.GRPCClient(t, ctx) stream, err := client.SubscribeTopicEventsAlpha1(ctx) require.NoError(t, err) require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_InitialRequest{ InitialRequest: &rtv1.SubscribeTopicEventsInitialRequestAlpha1{ PubsubName: "mypub", Topic: "a", }, }, })) assert.EventuallyWithT(t, func(c *assert.CollectT) { assert.Len(c, h.daprd.GetMetaSubscriptions(c, ctx), 1) }, time.Second*10, time.Millisecond*10) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "a", Data: []byte(`{"status": "completed"}`), DataContentType: "application/json", }) require.NoError(t, err) event, err := stream.Recv() require.NoError(t, err) assert.JSONEq(t, `{"status": "completed"}`, string(event.GetData())) require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_EventResponse{ EventResponse: &rtv1.SubscribeTopicEventsResponseAlpha1{ Id: event.GetId(), Status: &rtv1.TopicEventResponse{Status: rtv1.TopicEventResponse_SUCCESS}, }, }, })) require.NoError(t, stream.CloseSend()) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/stream/healthz.go
GO
mit
2,984
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package stream import ( "context" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/types/known/emptypb" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/grpc/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(mixed)) } type mixed struct { daprd *daprd.Daprd sub *subscriber.Subscriber } func (m *mixed) Setup(t *testing.T) []framework.Option { m.sub = subscriber.New(t, subscriber.WithListTopicSubscriptions(func(context.Context, *emptypb.Empty) (*rtv1.ListTopicSubscriptionsResponse, error) { return &rtv1.ListTopicSubscriptionsResponse{ Subscriptions: []*rtv1.TopicSubscription{{ PubsubName: "mypub", Topic: "a", Routes: &rtv1.TopicRoutes{Default: "/123"}, }}, }, nil }), ) m.daprd = daprd.New(t, daprd.WithAppProtocol("grpc"), daprd.WithAppPort(m.sub.Port(t)), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 Kind: Subscription metadata: name: sub spec: pubsubname: mypub topic: b route: /zyx `)) return []framework.Option{ framework.WithProcesses(m.sub, m.daprd), } } func (m *mixed) Run(t *testing.T, ctx context.Context) { m.daprd.WaitUntilRunning(t, ctx) client := m.daprd.GRPCClient(t, ctx) stream, err := client.SubscribeTopicEventsAlpha1(ctx) require.NoError(t, err) require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_InitialRequest{ InitialRequest: &rtv1.SubscribeTopicEventsInitialRequestAlpha1{ PubsubName: "mypub", Topic: "c", }, }, })) assert.EventuallyWithT(t, func(c *assert.CollectT) { assert.Len(c, m.daprd.GetMetaSubscriptions(c, ctx), 3) }, time.Second*10, time.Millisecond*10) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "a", Data: []byte(`{"status": "completed"}`), }) require.NoError(t, err) assert.Equal(t, "/123", m.sub.Receive(t, ctx).GetPath()) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "b", Data: []byte(`{"status": "completed"}`), }) require.NoError(t, err) assert.Equal(t, "/zyx", m.sub.Receive(t, ctx).GetPath()) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "c", Data: []byte(`{"status": "completed"}`), }) require.NoError(t, err) event, err := stream.Recv() require.NoError(t, err) assert.Equal(t, "c", event.GetTopic()) require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_EventResponse{ EventResponse: &rtv1.SubscribeTopicEventsResponseAlpha1{ Id: event.GetId(), Status: &rtv1.TopicEventResponse{Status: rtv1.TopicEventResponse_SUCCESS}, }, }, })) stream, err = client.SubscribeTopicEventsAlpha1(ctx) require.NoError(t, err) require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_InitialRequest{ InitialRequest: &rtv1.SubscribeTopicEventsInitialRequestAlpha1{ PubsubName: "mypub", Topic: "a", }, }, })) // TODO: @joshvanl: expose bi-direction subscriptions to measure so we don't // need to sleep. time.Sleep(time.Second) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "a", Data: []byte(`{"status": "completed"}`), }) require.NoError(t, err) event, err = stream.Recv() require.NoError(t, err) require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_EventResponse{ EventResponse: &rtv1.SubscribeTopicEventsResponseAlpha1{ Id: event.GetId(), Status: &rtv1.TopicEventResponse{Status: rtv1.TopicEventResponse_SUCCESS}, }, }, })) require.NoError(t, stream.CloseSend()) // TODO: @joshvanl: expose bi-direction subscriptions to measure so we don't // need to sleep. time.Sleep(time.Second) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "a", Data: []byte(`{"status": "completed"}`), }) require.NoError(t, err) assert.Equal(t, "a", m.sub.Receive(t, ctx).GetTopic()) stream, err = client.SubscribeTopicEventsAlpha1(ctx) require.NoError(t, err) require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_InitialRequest{ InitialRequest: &rtv1.SubscribeTopicEventsInitialRequestAlpha1{ PubsubName: "mypub", Topic: "a", }, }, })) // TODO: @joshvanl: expose bi-direction subscriptions to measure so we don't // need to sleep. time.Sleep(time.Second) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "a", Data: []byte(`{"status": "completed"}`), }) require.NoError(t, err) event, err = stream.Recv() require.NoError(t, err) require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_EventResponse{ EventResponse: &rtv1.SubscribeTopicEventsResponseAlpha1{ Id: event.GetId(), Status: &rtv1.TopicEventResponse{Status: rtv1.TopicEventResponse_SUCCESS}, }, }, })) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/stream/mixed.go
GO
mit
6,226
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package stream import ( "context" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/grpc/app" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(multi)) } type multi struct { daprd *daprd.Daprd } func (m *multi) Setup(t *testing.T) []framework.Option { app := app.New(t) m.daprd = daprd.New(t, daprd.WithAppProtocol("grpc"), daprd.WithAppPort(app.Port(t)), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(app, m.daprd), } } func (m *multi) Run(t *testing.T, ctx context.Context) { m.daprd.WaitUntilRunning(t, ctx) client := m.daprd.GRPCClient(t, ctx) stream1, err := client.SubscribeTopicEventsAlpha1(ctx) require.NoError(t, err) require.NoError(t, stream1.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_InitialRequest{ InitialRequest: &rtv1.SubscribeTopicEventsInitialRequestAlpha1{ PubsubName: "mypub", Topic: "a", }, }, })) stream2, err := client.SubscribeTopicEventsAlpha1(ctx) require.NoError(t, err) require.NoError(t, stream2.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_InitialRequest{ InitialRequest: &rtv1.SubscribeTopicEventsInitialRequestAlpha1{ PubsubName: "mypub", Topic: "b", }, }, })) stream3, err := client.SubscribeTopicEventsAlpha1(ctx) require.NoError(t, err) require.NoError(t, stream3.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_InitialRequest{ InitialRequest: &rtv1.SubscribeTopicEventsInitialRequestAlpha1{ PubsubName: "mypub", Topic: "c", }, }, })) t.Cleanup(func() { require.NoError(t, stream1.CloseSend()) require.NoError(t, stream2.CloseSend()) require.NoError(t, stream3.CloseSend()) }) assert.EventuallyWithT(t, func(c *assert.CollectT) { assert.Len(c, m.daprd.GetMetaSubscriptions(c, ctx), 3) }, time.Second*10, time.Millisecond*10) for _, topic := range []string{"a", "b", "c"} { _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: topic, Data: []byte(`{"status": "completed"}`), DataContentType: "application/json", }) require.NoError(t, err) } for stream, topic := range map[rtv1.Dapr_SubscribeTopicEventsAlpha1Client]string{ stream1: "a", stream2: "b", stream3: "c", } { event, err := stream.Recv() require.NoError(t, err) assert.Equal(t, topic, event.GetTopic()) } }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/stream/multi.go
GO
mit
3,512
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package stream import ( "context" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(noapp)) } type noapp struct { daprd *daprd.Daprd } func (n *noapp) Setup(t *testing.T) []framework.Option { n.daprd = daprd.New(t, daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(n.daprd), } } func (n *noapp) Run(t *testing.T, ctx context.Context) { n.daprd.WaitUntilRunning(t, ctx) client := n.daprd.GRPCClient(t, ctx) stream, err := client.SubscribeTopicEventsAlpha1(ctx) require.NoError(t, err) require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_InitialRequest{ InitialRequest: &rtv1.SubscribeTopicEventsInitialRequestAlpha1{ PubsubName: "mypub", Topic: "a", }, }, })) assert.EventuallyWithT(t, func(c *assert.CollectT) { assert.Len(c, n.daprd.GetMetaSubscriptions(c, ctx), 1) }, time.Second*10, time.Millisecond*10) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "a", Data: []byte(`{"status": "completed"}`), DataContentType: "application/json", }) require.NoError(t, err) event, err := stream.Recv() require.NoError(t, err) assert.Equal(t, "a", event.GetTopic()) assert.Equal(t, "mypub", event.GetPubsubName()) assert.JSONEq(t, `{"status": "completed"}`, string(event.GetData())) require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_EventResponse{ EventResponse: &rtv1.SubscribeTopicEventsResponseAlpha1{ Id: event.GetId(), Status: &rtv1.TopicEventResponse{Status: rtv1.TopicEventResponse_SUCCESS}, }, }, })) require.NoError(t, stream.CloseSend()) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/stream/noapp.go
GO
mit
2,770
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package stream import ( "context" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(retry)) } type retry struct { daprd *daprd.Daprd } func (r *retry) Setup(t *testing.T) []framework.Option { r.daprd = daprd.New(t, daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(r.daprd), } } func (r *retry) Run(t *testing.T, ctx context.Context) { r.daprd.WaitUntilRunning(t, ctx) client := r.daprd.GRPCClient(t, ctx) stream, err := client.SubscribeTopicEventsAlpha1(ctx) require.NoError(t, err) require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_InitialRequest{ InitialRequest: &rtv1.SubscribeTopicEventsInitialRequestAlpha1{ PubsubName: "mypub", Topic: "a", }, }, })) assert.EventuallyWithT(t, func(c *assert.CollectT) { assert.Len(c, r.daprd.GetMetaSubscriptions(c, ctx), 1) }, time.Second*10, time.Millisecond*10) pubReq := &rtv1.PublishEventRequest{ PubsubName: "mypub", Topic: "a", Data: []byte(`{"status": "completed"}`), DataContentType: "application/json", } _, err = client.PublishEvent(ctx, pubReq) require.NoError(t, err) event, err := stream.Recv() require.NoError(t, err) assert.Equal(t, "a", event.GetTopic()) id := event.GetId() require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_EventResponse{ EventResponse: &rtv1.SubscribeTopicEventsResponseAlpha1{ Id: event.GetId(), Status: &rtv1.TopicEventResponse{Status: rtv1.TopicEventResponse_RETRY}, }, }, })) event, err = stream.Recv() require.NoError(t, err) assert.Equal(t, "a", event.GetTopic()) assert.Equal(t, id, event.GetId()) require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_EventResponse{ EventResponse: &rtv1.SubscribeTopicEventsResponseAlpha1{ Id: event.GetId(), Status: &rtv1.TopicEventResponse{Status: rtv1.TopicEventResponse_RETRY}, }, }, })) event, err = stream.Recv() require.NoError(t, err) assert.Equal(t, "a", event.GetTopic()) assert.Equal(t, id, event.GetId()) require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_EventResponse{ EventResponse: &rtv1.SubscribeTopicEventsResponseAlpha1{ Id: event.GetId(), Status: &rtv1.TopicEventResponse{Status: rtv1.TopicEventResponse_DROP}, }, }, })) _, err = client.PublishEvent(ctx, pubReq) require.NoError(t, err) event, err = stream.Recv() require.NoError(t, err) assert.Equal(t, "a", event.GetTopic()) assert.NotEqual(t, id, event.GetId()) require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_EventResponse{ EventResponse: &rtv1.SubscribeTopicEventsResponseAlpha1{ Id: event.GetId(), Status: &rtv1.TopicEventResponse{Status: rtv1.TopicEventResponse_SUCCESS}, }, }, })) _, err = client.PublishEvent(ctx, pubReq) require.NoError(t, err) event1, err := stream.Recv() require.NoError(t, err) require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_EventResponse{ EventResponse: &rtv1.SubscribeTopicEventsResponseAlpha1{ Id: event1.GetId(), Status: &rtv1.TopicEventResponse{Status: rtv1.TopicEventResponse_DROP}, }, }, })) _, err = client.PublishEvent(ctx, pubReq) require.NoError(t, err) event2, err := stream.Recv() require.NoError(t, err) require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{ SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_EventResponse{ EventResponse: &rtv1.SubscribeTopicEventsResponseAlpha1{ Id: event2.GetId(), Status: &rtv1.TopicEventResponse{Status: rtv1.TopicEventResponse_RETRY}, }, }, })) event3, err := stream.Recv() require.NoError(t, err) assert.Equal(t, event2.GetId(), event3.GetId()) require.NoError(t, stream.CloseSend()) }
mikeee/dapr
tests/integration/suite/daprd/subscriptions/stream/retry.go
GO
mit
5,220
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package subscriptions import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/subscriptions/declarative" _ "github.com/dapr/dapr/tests/integration/suite/daprd/subscriptions/mixed" _ "github.com/dapr/dapr/tests/integration/suite/daprd/subscriptions/programmatic" _ "github.com/dapr/dapr/tests/integration/suite/daprd/subscriptions/stream" )
mikeee/dapr
tests/integration/suite/daprd/subscriptions/subscriptions.go
GO
mit
913
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://wwb.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package backend import ( "context" "fmt" "testing" "github.com/microsoft/durabletask-go/api" "github.com/microsoft/durabletask-go/backend" "github.com/microsoft/durabletask-go/client" "github.com/microsoft/durabletask-go/task" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/placement" "github.com/dapr/dapr/tests/integration/framework/util" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(actors)) } type actors struct { daprd *daprd.Daprd place *placement.Placement } func (a *actors) Setup(t *testing.T) []framework.Option { a.place = placement.New(t) a.daprd = daprd.New(t, daprd.WithPlacementAddresses(a.place.Address()), daprd.WithInMemoryActorStateStore("mystore"), daprd.WithResourceFiles(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: wfbackend spec: type: workflowbackend.actors version: v1 `), ) return []framework.Option{ framework.WithProcesses(a.place, a.daprd), } } func (a *actors) Run(t *testing.T, ctx context.Context) { a.daprd.WaitUntilRunning(t, ctx) comps := util.GetMetaComponents(t, ctx, util.HTTPClient(t), a.daprd.HTTPPort()) require.ElementsMatch(t, []*rtv1.RegisteredComponents{ {Name: "wfbackend", Type: "workflowbackend.actors", Version: "v1"}, { Name: "mystore", Type: "state.in-memory", Version: "v1", Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"}, }, }, comps) r := task.NewTaskRegistry() r.AddOrchestratorN("SingleActivity", func(ctx *task.OrchestrationContext) (any, error) { var input string if err := ctx.GetInput(&input); err != nil { return nil, err } var output string err := ctx.CallActivity("SayHello", task.WithActivityInput(input)).Await(&output) return output, err }) r.AddActivityN("SayHello", func(ctx task.ActivityContext) (any, error) { var name string if err := ctx.GetInput(&name); err != nil { return nil, err } return fmt.Sprintf("Hello, %s!", name), nil }) backendClient := client.NewTaskHubGrpcClient(a.daprd.GRPCConn(t, ctx), backend.DefaultLogger()) require.NoError(t, backendClient.StartWorkItemListener(ctx, r)) resp, err := a.daprd.GRPCClient(t, ctx).StartWorkflowBeta1(ctx, &rtv1.StartWorkflowRequest{ WorkflowComponent: "dapr", WorkflowName: "SingleActivity", Input: []byte(`"Dapr"`), InstanceId: "myinstance", }) require.NoError(t, err) id := api.InstanceID(resp.GetInstanceId()) metadata, err := backendClient.WaitForOrchestrationCompletion(ctx, id, api.WithFetchPayloads(true)) require.NoError(t, err) assert.True(t, metadata.IsComplete()) assert.Equal(t, `"Hello, Dapr!"`, metadata.SerializedOutput) }
mikeee/dapr
tests/integration/suite/daprd/workflow/backend/actors.go
GO
mit
3,504
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package backend import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/workflow/backend/singular" )
mikeee/dapr
tests/integration/suite/daprd/workflow/backend/backend.go
GO
mit
671
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://wwb.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package singular import ( "context" "testing" "github.com/stretchr/testify/require" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/exec" "github.com/dapr/dapr/tests/integration/framework/process/logline" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(actors)) } // actors ensures that 2 actor workflow backends cannot be loaded at the same time. type actors struct { logline *logline.LogLine daprd *daprd.Daprd } func (a *actors) Setup(t *testing.T) []framework.Option { a.logline = logline.New(t, logline.WithStdoutLineContains( "Fatal error from runtime: process component wfbackend2 error: [INIT_COMPONENT_FAILURE]: initialization error occurred for wfbackend2 (workflowbackend.actors/v1): cannot create more than one workflow backend component", ), ) a.daprd = daprd.New(t, daprd.WithResourceFiles(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: wfbackend1 spec: type: workflowbackend.actors version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: wfbackend2 spec: type: workflowbackend.actors version: v1 `), daprd.WithExecOptions( exec.WithExitCode(1), exec.WithRunError(func(t *testing.T, err error) { require.ErrorContains(t, err, "exit status 1") }), exec.WithStdout(a.logline.Stdout()), ), ) return []framework.Option{ framework.WithProcesses(a.logline, a.daprd), } } func (a *actors) Run(t *testing.T, ctx context.Context) { a.logline.EventuallyFoundAll(t) }
mikeee/dapr
tests/integration/suite/daprd/workflow/backend/singular/actors.go
GO
mit
2,195
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://wwb.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package singular import ( "context" "testing" "github.com/stretchr/testify/require" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/exec" "github.com/dapr/dapr/tests/integration/framework/process/logline" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(sqlite)) } // sqlite ensures that 2 sqlite workflow backends cannot be loaded at the same time. type sqlite struct { logline *logline.LogLine daprd *daprd.Daprd } func (s *sqlite) Setup(t *testing.T) []framework.Option { s.logline = logline.New(t, logline.WithStdoutLineContains( "Fatal error from runtime: process component wfbackend2 error: [INIT_COMPONENT_FAILURE]: initialization error occurred for wfbackend2 (workflowbackend.sqlite/v1): cannot create more than one workflow backend component", ), ) s.daprd = daprd.New(t, daprd.WithResourceFiles(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: wfbackend1 spec: type: workflowbackend.sqlite version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: wfbackend2 spec: type: workflowbackend.sqlite version: v1 `), daprd.WithExecOptions( exec.WithExitCode(1), exec.WithRunError(func(t *testing.T, err error) { require.ErrorContains(t, err, "exit status 1") }), exec.WithStdout(s.logline.Stdout()), ), ) return []framework.Option{ framework.WithProcesses(s.logline, s.daprd), } } func (s *sqlite) Run(t *testing.T, ctx context.Context) { s.logline.EventuallyFoundAll(t) }
mikeee/dapr
tests/integration/suite/daprd/workflow/backend/singular/sqlite.go
GO
mit
2,196
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://wwb.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package singular import ( "context" "testing" "github.com/stretchr/testify/require" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/exec" "github.com/dapr/dapr/tests/integration/framework/process/logline" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(sqliteactors)) } // sqliteactors ensures that 2 workflow backends of different type cannot be // loaded at the same time. type sqliteactors struct { logline *logline.LogLine daprd *daprd.Daprd } func (s *sqliteactors) Setup(t *testing.T) []framework.Option { s.logline = logline.New(t, logline.WithStdoutLineContains( "Fatal error from runtime: process component wfbackend2 error: [INIT_COMPONENT_FAILURE]: initialization error occurred for wfbackend2 (workflowbackend.actors/v1): cannot create more than one workflow backend component", ), ) s.daprd = daprd.New(t, daprd.WithResourceFiles(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: wfbackend1 spec: type: workflowbackend.sqlite version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: wfbackend2 spec: type: workflowbackend.actors version: v1 `), daprd.WithExecOptions( exec.WithExitCode(1), exec.WithRunError(func(t *testing.T, err error) { require.ErrorContains(t, err, "exit status 1") }), exec.WithStdout(s.logline.Stdout()), ), ) return []framework.Option{ framework.WithProcesses(s.logline, s.daprd), } } func (s *sqliteactors) Run(t *testing.T, ctx context.Context) { s.logline.EventuallyFoundAll(t) }
mikeee/dapr
tests/integration/suite/daprd/workflow/backend/singular/sqliteactors.go
GO
mit
2,240
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://wwb.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package backend import ( "context" "fmt" "path/filepath" "testing" "github.com/microsoft/durabletask-go/api" "github.com/microsoft/durabletask-go/backend" "github.com/microsoft/durabletask-go/client" "github.com/microsoft/durabletask-go/task" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/util" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(sqlite)) } type sqlite struct { daprd *daprd.Daprd dir string } func (s *sqlite) Setup(t *testing.T) []framework.Option { s.dir = filepath.Join(t.TempDir(), "wf.db") s.daprd = daprd.New(t, daprd.WithResourceFiles(fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: wfbackend spec: type: workflowbackend.sqlite version: v1 metadata: - name: connectionString value: %s `, s.dir)), ) return []framework.Option{ framework.WithProcesses(s.daprd), } } func (s *sqlite) Run(t *testing.T, ctx context.Context) { s.daprd.WaitUntilRunning(t, ctx) comps := util.GetMetaComponents(t, ctx, util.HTTPClient(t), s.daprd.HTTPPort()) require.ElementsMatch(t, []*rtv1.RegisteredComponents{ {Name: "wfbackend", Type: "workflowbackend.sqlite", Version: "v1"}, }, comps) r := task.NewTaskRegistry() r.AddOrchestratorN("SingleActivity", func(ctx *task.OrchestrationContext) (any, error) { var input string if err := ctx.GetInput(&input); err != nil { return nil, err } var output string err := ctx.CallActivity("SayHello", task.WithActivityInput(input)).Await(&output) return output, err }) r.AddActivityN("SayHello", func(ctx task.ActivityContext) (any, error) { var name string if err := ctx.GetInput(&name); err != nil { return nil, err } return fmt.Sprintf("Hello, %s!", name), nil }) backendClient := client.NewTaskHubGrpcClient(s.daprd.GRPCConn(t, ctx), backend.DefaultLogger()) require.NoError(t, backendClient.StartWorkItemListener(ctx, r)) resp, err := s.daprd.GRPCClient(t, ctx). StartWorkflowBeta1(ctx, &rtv1.StartWorkflowRequest{ WorkflowComponent: "dapr", WorkflowName: "SingleActivity", Input: []byte(`"Dapr"`), InstanceId: "myinstance", }) require.NoError(t, err) id := api.InstanceID(resp.GetInstanceId()) metadata, err := backendClient.WaitForOrchestrationCompletion(ctx, id, api.WithFetchPayloads(true)) require.NoError(t, err) assert.True(t, metadata.IsComplete()) assert.Equal(t, `"Hello, Dapr!"`, metadata.SerializedOutput) }
mikeee/dapr
tests/integration/suite/daprd/workflow/backend/sqlite.go
GO
mit
3,265
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://wwb.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package workflow import ( "context" "encoding/json" "errors" "fmt" "net/http" "strconv" "strings" "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/status" "github.com/microsoft/durabletask-go/api" "github.com/microsoft/durabletask-go/backend" "github.com/microsoft/durabletask-go/client" "github.com/microsoft/durabletask-go/task" runtimev1pb "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" prochttp "github.com/dapr/dapr/tests/integration/framework/process/http" "github.com/dapr/dapr/tests/integration/framework/process/placement" "github.com/dapr/dapr/tests/integration/framework/util" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(basic)) } // metrics tests daprd metrics type basic struct { daprd *daprd.Daprd place *placement.Placement httpClient *http.Client grpcClient runtimev1pb.DaprClient } func (b *basic) Setup(t *testing.T) []framework.Option { handler := http.NewServeMux() handler.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("")) }) srv := prochttp.New(t, prochttp.WithHandler(handler)) b.place = placement.New(t) b.daprd = daprd.New(t, daprd.WithAppID("myapp"), daprd.WithAppPort(srv.Port()), daprd.WithAppProtocol("http"), daprd.WithPlacementAddresses(b.place.Address()), daprd.WithInMemoryActorStateStore("mystore"), ) return []framework.Option{ framework.WithProcesses(b.place, srv, b.daprd), } } func (b *basic) Run(t *testing.T, ctx context.Context) { b.place.WaitUntilRunning(t, ctx) b.daprd.WaitUntilRunning(t, ctx) b.httpClient = util.HTTPClient(t) conn, err := grpc.DialContext(ctx, b.daprd.GRPCAddress(), grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock(), ) require.NoError(t, err) t.Cleanup(func() { require.NoError(t, conn.Close()) }) b.grpcClient = runtimev1pb.NewDaprClient(conn) backendClient := client.NewTaskHubGrpcClient(conn, backend.DefaultLogger()) t.Run("basic", func(t *testing.T) { r := task.NewTaskRegistry() r.AddOrchestratorN("SingleActivity", func(ctx *task.OrchestrationContext) (any, error) { var input string if err := ctx.GetInput(&input); err != nil { return nil, err } var output string err := ctx.CallActivity("SayHello", task.WithActivityInput(input)).Await(&output) return output, err }) r.AddActivityN("SayHello", func(ctx task.ActivityContext) (any, error) { var name string if err := ctx.GetInput(&name); err != nil { return nil, err } return fmt.Sprintf("Hello, %s!", name), nil }) taskhubCtx, cancelTaskhub := context.WithCancel(ctx) backendClient.StartWorkItemListener(taskhubCtx, r) defer cancelTaskhub() id := api.InstanceID(b.startWorkflow(ctx, t, "SingleActivity", "Dapr")) metadata, err := backendClient.WaitForOrchestrationCompletion(ctx, id, api.WithFetchPayloads(true)) require.NoError(t, err) assert.True(t, metadata.IsComplete()) assert.Equal(t, `"Hello, Dapr!"`, metadata.SerializedOutput) }) t.Run("terminate", func(t *testing.T) { delayTime := 4 * time.Second var executedActivity atomic.Bool r := task.NewTaskRegistry() r.AddOrchestratorN("Root", func(ctx *task.OrchestrationContext) (any, error) { tasks := []task.Task{} for i := 0; i < 5; i++ { task := ctx.CallSubOrchestrator("L1", task.WithSubOrchestrationInstanceID(string(ctx.ID)+"_L1_"+strconv.Itoa(i))) tasks = append(tasks, task) } for _, task := range tasks { task.Await(nil) } return nil, nil }) r.AddOrchestratorN("L1", func(ctx *task.OrchestrationContext) (any, error) { ctx.CallSubOrchestrator("L2", task.WithSubOrchestrationInstanceID(string(ctx.ID)+"_L2")).Await(nil) return nil, nil }) r.AddOrchestratorN("L2", func(ctx *task.OrchestrationContext) (any, error) { ctx.CreateTimer(delayTime).Await(nil) ctx.CallActivity("Fail").Await(nil) return nil, nil }) r.AddActivityN("Fail", func(ctx task.ActivityContext) (any, error) { executedActivity.Store(true) return nil, errors.New("failed: Should not have executed the activity") }) taskhubCtx, cancelTaskhub := context.WithCancel(ctx) backendClient.StartWorkItemListener(taskhubCtx, r) defer cancelTaskhub() id := api.InstanceID(b.startWorkflow(ctx, t, "Root", "")) // Wait long enough to ensure all orchestrations have started (but not longer than the timer delay) assert.Eventually(t, func() bool { // List of all orchestrations created orchestrationIDs := []string{string(id)} for i := 0; i < 5; i++ { orchestrationIDs = append(orchestrationIDs, string(id)+"_L1_"+strconv.Itoa(i), string(id)+"_L1_"+strconv.Itoa(i)+"_L2") } for _, orchID := range orchestrationIDs { meta, err := backendClient.FetchOrchestrationMetadata(ctx, api.InstanceID(orchID)) require.NoError(t, err) // All orchestrations should be running if meta.RuntimeStatus != api.RUNTIME_STATUS_RUNNING { return false } } return true }, 2*time.Second, 10*time.Millisecond) // Terminate the root orchestration b.terminateWorkflow(t, ctx, string(id)) // Wait for the root orchestration to complete and verify its terminated status metadata, err := backendClient.WaitForOrchestrationCompletion(ctx, id) require.NoError(t, err) require.Equal(t, api.RUNTIME_STATUS_TERMINATED, metadata.RuntimeStatus) // Wait for all L2 suborchestrations to complete orchIDs := []string{} for i := 0; i < 5; i++ { orchIDs = append(orchIDs, string(id)+"_L1_"+strconv.Itoa(i)+"_L2") } for _, orchID := range orchIDs { _, err := backendClient.WaitForOrchestrationCompletion(ctx, api.InstanceID(orchID)) require.NoError(t, err) } // Verify that none of the L2 suborchestrations executed the activity assert.False(t, executedActivity.Load()) }) t.Run("purge", func(t *testing.T) { delayTime := 4 * time.Second r := task.NewTaskRegistry() r.AddOrchestratorN("Root", func(ctx *task.OrchestrationContext) (any, error) { ctx.CallSubOrchestrator("L1", task.WithSubOrchestrationInstanceID(string(ctx.ID)+"_L1")).Await(nil) return nil, nil }) r.AddOrchestratorN("L1", func(ctx *task.OrchestrationContext) (any, error) { ctx.CallSubOrchestrator("L2", task.WithSubOrchestrationInstanceID(string(ctx.ID)+"_L2")).Await(nil) return nil, nil }) r.AddOrchestratorN("L2", func(ctx *task.OrchestrationContext) (any, error) { ctx.CreateTimer(delayTime).Await(nil) return nil, nil }) taskhubCtx, cancelTaskhub := context.WithCancel(ctx) backendClient.StartWorkItemListener(taskhubCtx, r) defer cancelTaskhub() // Run the orchestration, which will block waiting for external events id := api.InstanceID(b.startWorkflow(ctx, t, "Root", "")) metadata, err := backendClient.WaitForOrchestrationCompletion(ctx, id) require.NoError(t, err) require.Equal(t, api.RUNTIME_STATUS_COMPLETED, metadata.RuntimeStatus) // Purge the root orchestration b.purgeWorkflow(t, ctx, string(id)) // Verify that root Orchestration has been purged _, err = backendClient.FetchOrchestrationMetadata(ctx, id) assert.Contains(t, status.Convert(err).Message(), api.ErrInstanceNotFound.Error()) // Verify that L1 and L2 orchestrations have been purged _, err = backendClient.FetchOrchestrationMetadata(ctx, id+"_L1") require.Contains(t, status.Convert(err).Message(), api.ErrInstanceNotFound.Error()) _, err = backendClient.FetchOrchestrationMetadata(ctx, id+"_L1_L2") require.Contains(t, status.Convert(err).Message(), api.ErrInstanceNotFound.Error()) }) t.Run("child workflow", func(t *testing.T) { r := task.NewTaskRegistry() r.AddOrchestratorN("root", func(ctx *task.OrchestrationContext) (any, error) { var input string if err := ctx.GetInput(&input); err != nil { return nil, err } var output string err := ctx.CallSubOrchestrator("child", task.WithSubOrchestratorInput(input)).Await(&output) return output, err }) r.AddOrchestratorN("child", func(ctx *task.OrchestrationContext) (any, error) { var input string if err := ctx.GetInput(&input); err != nil { return nil, err } return fmt.Sprintf("Hello, %s!", input), nil }) taskhubCtx, cancelTaskhub := context.WithCancel(ctx) backendClient.StartWorkItemListener(taskhubCtx, r) defer cancelTaskhub() id := api.InstanceID(b.startWorkflow(ctx, t, "root", "Dapr")) metadata, err := backendClient.WaitForOrchestrationCompletion(ctx, id, api.WithFetchPayloads(true)) require.NoError(t, err) assert.True(t, metadata.IsComplete()) assert.Equal(t, `"Hello, Dapr!"`, metadata.SerializedOutput) }) } func (b *basic) startWorkflow(ctx context.Context, t *testing.T, name string, input string) string { // use http client to start the workflow reqURL := fmt.Sprintf("http://localhost:%d/v1.0-beta1/workflows/dapr/%s/start", b.daprd.HTTPPort(), name) data, err := json.Marshal(input) require.NoError(t, err) reqCtx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, reqURL, strings.NewReader(string(data))) req.Header.Set("Content-Type", "application/json") require.NoError(t, err) resp, err := b.httpClient.Do(req) require.NoError(t, err) defer resp.Body.Close() require.Equal(t, http.StatusAccepted, resp.StatusCode) var response struct { InstanceID string `json:"instanceID"` } err = json.NewDecoder(resp.Body).Decode(&response) require.NoError(t, err) return response.InstanceID } // terminate workflow func (b *basic) terminateWorkflow(t *testing.T, ctx context.Context, instanceID string) { // use http client to terminate the workflow reqURL := fmt.Sprintf("http://localhost:%d/v1.0-beta1/workflows/dapr/%s/terminate", b.daprd.HTTPPort(), instanceID) reqCtx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, reqURL, nil) require.NoError(t, err) resp, err := b.httpClient.Do(req) require.NoError(t, err) defer resp.Body.Close() require.Equal(t, http.StatusAccepted, resp.StatusCode) } // purge workflow func (b *basic) purgeWorkflow(t *testing.T, ctx context.Context, instanceID string) { // use http client to purge the workflow reqURL := fmt.Sprintf("http://localhost:%d/v1.0-beta1/workflows/dapr/%s/purge", b.daprd.HTTPPort(), instanceID) reqCtx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, reqURL, nil) require.NoError(t, err) resp, err := b.httpClient.Do(req) require.NoError(t, err) defer resp.Body.Close() require.Equal(t, http.StatusAccepted, resp.StatusCode) }
mikeee/dapr
tests/integration/suite/daprd/workflow/basic.go
GO
mit
11,504
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package workflow import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/workflow/backend" )
mikeee/dapr
tests/integration/suite/daprd/workflow/workflow.go
GO
mit
663
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package healthz import ( "context" "fmt" "io" "net/http" "strings" "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/dapr/dapr/tests/integration/framework" procdaprd "github.com/dapr/dapr/tests/integration/framework/process/daprd" prochttp "github.com/dapr/dapr/tests/integration/framework/process/http" "github.com/dapr/dapr/tests/integration/framework/util" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(app)) } // app tests that Dapr responds to healthz requests for the app. type app struct { daprd *procdaprd.Daprd healthy atomic.Bool srv *prochttp.HTTP } func (a *app) Setup(t *testing.T) []framework.Option { a.healthy.Store(true) mux := http.NewServeMux() mux.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) { if a.healthy.Load() { w.WriteHeader(http.StatusOK) } else { w.WriteHeader(http.StatusServiceUnavailable) } fmt.Fprintf(w, "%s %s", r.Method, r.URL.Path) }) mux.HandleFunc("/myfunc", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) fmt.Fprintf(w, "%s %s", r.Method, r.URL.Path) }) a.srv = prochttp.New(t, prochttp.WithHandler(mux)) a.daprd = procdaprd.New(t, procdaprd.WithAppHealthCheck(true), procdaprd.WithAppHealthCheckPath("/foo"), procdaprd.WithAppPort(a.srv.Port()), procdaprd.WithAppHealthProbeInterval(1), procdaprd.WithAppHealthProbeThreshold(1), ) return []framework.Option{ framework.WithProcesses(a.daprd, a.srv), } } func (a *app) Run(t *testing.T, ctx context.Context) { a.daprd.WaitUntilRunning(t, ctx) a.healthy.Store(true) reqURL := fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/myfunc", a.daprd.HTTPPort(), a.daprd.AppID()) a.healthy.Store(true) httpClient := util.HTTPClient(t) assert.Eventually(t, func() bool { req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil) require.NoError(t, err) resp, err := httpClient.Do(req) require.NoError(t, err) body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) return resp.StatusCode == http.StatusOK && string(body) == "GET /myfunc" }, time.Second*5, 10*time.Millisecond, "expected dapr to report app healthy when /foo returns 200") a.healthy.Store(false) assert.Eventually(t, func() bool { req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil) require.NoError(t, err) resp, err := httpClient.Do(req) require.NoError(t, err) body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) return resp.StatusCode == http.StatusInternalServerError && strings.Contains(string(body), "app is not in a healthy state") }, time.Second*20, 10*time.Millisecond, "expected dapr to report app unhealthy now /foo returns 503") }
mikeee/dapr
tests/integration/suite/healthz/app.go
GO
mit
3,459
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package healthz import ( "context" "fmt" "net/http" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/dapr/dapr/tests/integration/framework" procdaprd "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/util" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(daprd)) } // daprd tests that Dapr responds to healthz requests. type daprd struct { proc *procdaprd.Daprd } func (d *daprd) Setup(t *testing.T) []framework.Option { d.proc = procdaprd.New(t) return []framework.Option{ framework.WithProcesses(d.proc), } } func (d *daprd) Run(t *testing.T, ctx context.Context) { d.proc.WaitUntilRunning(t, ctx) reqURL := fmt.Sprintf("http://localhost:%d/v1.0/healthz", d.proc.PublicPort()) httpClient := util.HTTPClient(t) assert.Eventually(t, func() bool { req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil) require.NoError(t, err) resp, err := httpClient.Do(req) require.NoError(t, err) require.NoError(t, resp.Body.Close()) return resp.StatusCode == http.StatusNoContent }, time.Second*10, 10*time.Millisecond) }
mikeee/dapr
tests/integration/suite/healthz/daprd.go
GO
mit
1,786
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package healthz import ( "context" "fmt" "net/http" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/dapr/dapr/tests/integration/framework" procinjector "github.com/dapr/dapr/tests/integration/framework/process/injector" procsentry "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/framework/util" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(injector)) } type injector struct { injector *procinjector.Injector } func (i *injector) Setup(t *testing.T) []framework.Option { sentry := procsentry.New(t, procsentry.WithTrustDomain("integration.test.dapr.io"), procsentry.WithNamespace("dapr-system"), ) i.injector = procinjector.New(t, procinjector.WithNamespace("dapr-system"), procinjector.WithSentry(sentry), ) return []framework.Option{ framework.WithProcesses(sentry, i.injector), } } func (i *injector) Run(t *testing.T, ctx context.Context) { i.injector.WaitUntilRunning(t, ctx) httpClient := util.HTTPClient(t) reqURL := fmt.Sprintf("http://localhost:%d/healthz", i.injector.HealthzPort()) assert.Eventually(t, func() bool { req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil) require.NoError(t, err) resp, err := httpClient.Do(req) require.NoError(t, err) require.NoError(t, resp.Body.Close()) return resp.StatusCode == http.StatusOK }, time.Second*10, 10*time.Millisecond) }
mikeee/dapr
tests/integration/suite/healthz/injector.go
GO
mit
2,070
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package healthz import ( "context" "fmt" "net/http" "testing" "time" "github.com/spiffe/go-spiffe/v2/spiffeid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/exec" "github.com/dapr/dapr/tests/integration/framework/process/kubernetes" procoperator "github.com/dapr/dapr/tests/integration/framework/process/operator" procsentry "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/framework/util" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(operator)) } // operator tests Operator. type operator struct { sentry *procsentry.Sentry proc *procoperator.Operator } func (o *operator) Setup(t *testing.T) []framework.Option { o.sentry = procsentry.New(t, procsentry.WithTrustDomain("integration.test.dapr.io"), procsentry.WithExecOptions(exec.WithEnvVars(t, "NAMESPACE", "dapr-system")), ) kubeAPI := kubernetes.New(t, kubernetes.WithBaseOperatorAPI(t, spiffeid.RequireTrustDomainFromString("integration.test.dapr.io"), "dapr-system", o.sentry.Port(), )) o.proc = procoperator.New(t, procoperator.WithNamespace("dapr-system"), procoperator.WithKubeconfigPath(kubeAPI.KubeconfigPath(t)), procoperator.WithTrustAnchorsFile(o.sentry.TrustAnchorsFile(t)), ) return []framework.Option{ framework.WithProcesses(kubeAPI, o.sentry, o.proc), } } func (o *operator) Run(t *testing.T, ctx context.Context) { o.sentry.WaitUntilRunning(t, ctx) o.proc.WaitUntilRunning(t, ctx) httpClient := util.HTTPClient(t) reqURL := fmt.Sprintf("http://localhost:%d/healthz", o.proc.HealthzPort()) assert.Eventually(t, func() bool { req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil) require.NoError(t, err) resp, err := httpClient.Do(req) require.NoError(t, err) require.NoError(t, resp.Body.Close()) return resp.StatusCode == http.StatusOK }, time.Second*10, 10*time.Millisecond) }
mikeee/dapr
tests/integration/suite/healthz/operator.go
GO
mit
2,637
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package healthz import ( "context" "fmt" "net/http" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/dapr/dapr/tests/integration/framework" procplace "github.com/dapr/dapr/tests/integration/framework/process/placement" "github.com/dapr/dapr/tests/integration/framework/util" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(placement)) } // placement tests that Placement responds to healthz requests. type placement struct { proc *procplace.Placement } func (p *placement) Setup(t *testing.T) []framework.Option { p.proc = procplace.New(t) return []framework.Option{ framework.WithProcesses(p.proc), } } func (p *placement) Run(t *testing.T, ctx context.Context) { p.proc.WaitUntilRunning(t, ctx) reqURL := fmt.Sprintf("http://127.0.0.1:%d/healthz", p.proc.HealthzPort()) httpClient := util.HTTPClient(t) assert.Eventually(t, func() bool { req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil) require.NoError(t, err) resp, err := httpClient.Do(req) require.NoError(t, err) require.NoError(t, resp.Body.Close()) return http.StatusOK == resp.StatusCode }, time.Second*10, 10*time.Millisecond) }
mikeee/dapr
tests/integration/suite/healthz/placement.go
GO
mit
1,808
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package healthz import ( "context" "fmt" "net/http" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/dapr/dapr/tests/integration/framework" procsentry "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/framework/util" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(sentry)) } // sentry tests that Sentry responds to healthz requests. type sentry struct { proc *procsentry.Sentry } func (s *sentry) Setup(t *testing.T) []framework.Option { s.proc = procsentry.New(t) return []framework.Option{ framework.WithProcesses(s.proc), } } func (s *sentry) Run(t *testing.T, ctx context.Context) { s.proc.WaitUntilRunning(t, ctx) reqURL := fmt.Sprintf("http://127.0.0.1:%d/healthz", s.proc.HealthzPort()) httpClient := util.HTTPClient(t) assert.Eventually(t, func() bool { req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil) require.NoError(t, err) resp, err := httpClient.Do(req) require.NoError(t, err) require.NoError(t, resp.Body.Close()) return http.StatusOK == resp.StatusCode }, time.Second*10, 10*time.Millisecond) }
mikeee/dapr
tests/integration/suite/healthz/sentry.go
GO
mit
1,785
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh. See the License for the specific language governing permissions and limitations under the License. */ package api import ( _ "github.com/dapr/dapr/tests/integration/suite/operator/api/componentupdate" _ "github.com/dapr/dapr/tests/integration/suite/operator/api/listcomponents" )
mikeee/dapr
tests/integration/suite/operator/api/api.go
GO
mit
742
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package api import ( "context" "strconv" "testing" "github.com/spiffe/go-spiffe/v2/spiffeid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/emptypb" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1" configapi "github.com/dapr/dapr/pkg/apis/configuration/v1alpha1" httpendapi "github.com/dapr/dapr/pkg/apis/httpEndpoint/v1alpha1" resapi "github.com/dapr/dapr/pkg/apis/resiliency/v1alpha1" subapi "github.com/dapr/dapr/pkg/apis/subscriptions/v1alpha1" operatorv1pb "github.com/dapr/dapr/pkg/proto/operator/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/kubernetes" operator "github.com/dapr/dapr/tests/integration/framework/process/operator" procsentry "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(authz)) } // authz tests the authz of the operator API which is based on client request // namespace. type authz struct { sentry *procsentry.Sentry kubeapi *kubernetes.Kubernetes op *operator.Operator } func (a *authz) Setup(t *testing.T) []framework.Option { a.sentry = procsentry.New(t, procsentry.WithTrustDomain("integration.test.dapr.io")) a.kubeapi = kubernetes.New(t, kubernetes.WithBaseOperatorAPI(t, spiffeid.RequireTrustDomainFromString("integration.test.dapr.io"), "default", a.sentry.Port(), ), kubernetes.WithClusterDaprConfigurationList(t, &configapi.ConfigurationList{Items: []configapi.Configuration{ { TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Configuration"}, ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "default"}, }, }}), kubernetes.WithClusterDaprResiliencyList(t, &resapi.ResiliencyList{Items: []resapi.Resiliency{ { TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Resiliency"}, ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "default"}, }, }}), kubernetes.WithClusterDaprSubscriptionList(t, &subapi.SubscriptionList{Items: []subapi.Subscription{ { TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Subscription"}, ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "default"}, }, }}), ) a.op = operator.New(t, operator.WithNamespace("default"), operator.WithKubeconfigPath(a.kubeapi.KubeconfigPath(t)), operator.WithTrustAnchorsFile(a.sentry.TrustAnchorsFile(t)), ) return []framework.Option{ framework.WithProcesses(a.kubeapi, a.sentry, a.op), } } func (a *authz) Run(t *testing.T, ctx context.Context) { a.sentry.WaitUntilRunning(t, ctx) a.op.WaitUntilRunning(t, ctx) t.Run("no client auth should error", func(t *testing.T) { conn, err := grpc.DialContext(ctx, "localhost:"+strconv.Itoa(a.op.Port()), grpc.WithTransportCredentials(insecure.NewCredentials()), ) require.NoError(t, err) t.Cleanup(func() { require.NoError(t, conn.Close()) }) client := operatorv1pb.NewOperatorClient(conn) resp, err := client.ListComponents(ctx, &operatorv1pb.ListComponentsRequest{ Namespace: "default", }) require.Error(t, err) assert.Nil(t, resp) }) client := a.op.Dial(t, ctx, a.sentry, "myapp") type tcase struct { funcGoodNamespace func() (any, error) funcBadNamespace func() (any, error) } for name, test := range map[string]tcase{ "ComponentUpdate": { funcGoodNamespace: func() (any, error) { stream, err := client.ComponentUpdate(ctx, &operatorv1pb.ComponentUpdateRequest{Namespace: "default"}) require.NoError(t, err) a.kubeapi.Informer().Add(t, &compapi.Component{ TypeMeta: metav1.TypeMeta{Kind: "Component", APIVersion: "dapr.io/v1alpha1"}, ObjectMeta: metav1.ObjectMeta{Name: "mycomponent", Namespace: "default"}, }) return stream.Recv() }, funcBadNamespace: func() (any, error) { stream, err := client.ComponentUpdate(ctx, &operatorv1pb.ComponentUpdateRequest{Namespace: "random-namespace"}) require.NoError(t, err) return stream.Recv() }, }, "GetConfiguration": { funcGoodNamespace: func() (any, error) { resp, err := client.GetConfiguration(ctx, &operatorv1pb.GetConfigurationRequest{Namespace: "default", Name: "foo"}) return resp, err }, funcBadNamespace: func() (any, error) { resp, err := client.GetConfiguration(ctx, &operatorv1pb.GetConfigurationRequest{Namespace: "random-namespace", Name: "foo"}) return resp, err }, }, "GetResiliency": { funcGoodNamespace: func() (any, error) { return client.GetResiliency(ctx, &operatorv1pb.GetResiliencyRequest{Namespace: "default", Name: "foo"}) }, funcBadNamespace: func() (any, error) { return client.GetResiliency(ctx, &operatorv1pb.GetResiliencyRequest{Namespace: "random-namespace", Name: "foo"}) }, }, "HTTPEndpointUpdate": { funcGoodNamespace: func() (any, error) { stream, err := client.HTTPEndpointUpdate(ctx, &operatorv1pb.HTTPEndpointUpdateRequest{Namespace: "default"}) require.NoError(t, err) a.kubeapi.Informer().Add(t, &httpendapi.HTTPEndpoint{ TypeMeta: metav1.TypeMeta{Kind: "HTTPEndpoint", APIVersion: "dapr.io/v1alpha1"}, ObjectMeta: metav1.ObjectMeta{Name: "myendpoint", Namespace: "default"}, }) return stream.Recv() }, funcBadNamespace: func() (any, error) { stream, err := client.HTTPEndpointUpdate(ctx, &operatorv1pb.HTTPEndpointUpdateRequest{Namespace: "random-namespace"}) require.NoError(t, err) return stream.Recv() }, }, "ListComponents": { funcGoodNamespace: func() (any, error) { return client.ListComponents(ctx, &operatorv1pb.ListComponentsRequest{Namespace: "default"}) }, funcBadNamespace: func() (any, error) { return client.ListComponents(ctx, &operatorv1pb.ListComponentsRequest{Namespace: "random-namespace"}) }, }, "ListHTTPEndpoints": { funcGoodNamespace: func() (any, error) { return client.ListHTTPEndpoints(ctx, &operatorv1pb.ListHTTPEndpointsRequest{Namespace: "default"}) }, funcBadNamespace: func() (any, error) { return client.ListHTTPEndpoints(ctx, &operatorv1pb.ListHTTPEndpointsRequest{Namespace: "random-namespace"}) }, }, "ListResiliency": { funcGoodNamespace: func() (any, error) { return client.ListResiliency(ctx, &operatorv1pb.ListResiliencyRequest{Namespace: "default"}) }, funcBadNamespace: func() (any, error) { return client.ListResiliency(ctx, &operatorv1pb.ListResiliencyRequest{Namespace: "random-namespace"}) }, }, "ListSubscriptions": { funcGoodNamespace: func() (any, error) { // ListSubscriptions is not implemented in the operator. return 1, nil }, funcBadNamespace: func() (any, error) { return client.ListSubscriptions(ctx, new(emptypb.Empty)) }, }, "ListSubscriptionsV2": { funcGoodNamespace: func() (any, error) { return client.ListSubscriptionsV2(ctx, &operatorv1pb.ListSubscriptionsRequest{Namespace: "default"}) }, funcBadNamespace: func() (any, error) { return client.ListSubscriptionsV2(ctx, &operatorv1pb.ListSubscriptionsRequest{Namespace: "random-namespace"}) }, }, } { t.Run(name, func(t *testing.T) { // Bad namespace should error permission denied resp, err := test.funcBadNamespace() s, ok := status.FromError(err) require.True(t, ok) assert.Equal(t, codes.PermissionDenied.String(), s.Code().String()) assert.Contains(t, s.Message(), "identity does not match requested namespace") assert.Nil(t, resp) // Good namespace should not error resp, err = test.funcGoodNamespace() require.NoError(t, err) assert.NotNil(t, resp) }) } }
mikeee/dapr
tests/integration/suite/operator/api/authz.go
GO
mit
8,461
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package componentupdate import ( "context" "encoding/json" "testing" "time" "github.com/spiffe/go-spiffe/v2/spiffeid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/dapr/dapr/pkg/apis/common" compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1" operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/kubernetes" "github.com/dapr/dapr/tests/integration/framework/process/kubernetes/store" "github.com/dapr/dapr/tests/integration/framework/process/operator" "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(basic)) } // basic tests the operator's ComponentUpdate API. type basic struct { sentry *sentry.Sentry store *store.Store kubeapi *kubernetes.Kubernetes operator *operator.Operator } func (b *basic) Setup(t *testing.T) []framework.Option { b.sentry = sentry.New(t, sentry.WithTrustDomain("integration.test.dapr.io")) b.store = store.New(metav1.GroupVersionKind{ Group: "dapr.io", Version: "v1alpha1", Kind: "Component", }) b.kubeapi = kubernetes.New(t, kubernetes.WithBaseOperatorAPI(t, spiffeid.RequireTrustDomainFromString("integration.test.dapr.io"), "default", b.sentry.Port(), ), kubernetes.WithClusterDaprComponentListFromStore(t, b.store), ) b.operator = operator.New(t, operator.WithNamespace("default"), operator.WithKubeconfigPath(b.kubeapi.KubeconfigPath(t)), operator.WithTrustAnchorsFile(b.sentry.TrustAnchorsFile(t)), ) return []framework.Option{ framework.WithProcesses(b.kubeapi, b.sentry, b.operator), } } func (b *basic) Run(t *testing.T, ctx context.Context) { b.sentry.WaitUntilRunning(t, ctx) b.operator.WaitUntilRunning(t, ctx) client := b.operator.Dial(t, ctx, b.sentry, "myapp") stream, err := client.ComponentUpdate(ctx, &operatorv1.ComponentUpdateRequest{Namespace: "default"}) require.NoError(t, err) comp := &compapi.Component{ ObjectMeta: metav1.ObjectMeta{Name: "mycomponent", Namespace: "default", CreationTimestamp: metav1.Time{}}, Spec: compapi.ComponentSpec{ Type: "state.redis", Version: "v1", IgnoreErrors: false, Metadata: []common.NameValuePair{ { Name: "connectionString", Value: common.DynamicValue{ JSON: apiextv1.JSON{Raw: []byte(`"foobar"`)}, }, }, }, }, } t.Run("CREATE", func(t *testing.T) { b.store.Add(comp) b.kubeapi.Informer().Add(t, comp) event, err := stream.Recv() require.NoError(t, err) var gotComp compapi.Component require.NoError(t, json.Unmarshal(event.GetComponent(), &gotComp)) assert.Equal(t, comp, &gotComp) assert.Equal(t, operatorv1.ResourceEventType_CREATED, event.GetType()) assert.Equal(t, "CREATED", event.GetType().String()) }) t.Run("UPDATE", func(t *testing.T) { comp.Spec.Type = "state.inmemory" comp.Spec.Metadata = nil b.store.Set(comp) b.kubeapi.Informer().Modify(t, comp) b, err := json.Marshal(comp) require.NoError(t, err) assert.EventuallyWithT(t, func(c *assert.CollectT) { event, err := stream.Recv() //nolint:testifylint if !assert.NoError(c, err) { return } var gotComp compapi.Component require.NoError(t, json.Unmarshal(event.GetComponent(), &gotComp)) assert.Equal(c, comp, &gotComp) assert.JSONEq(c, string(b), string(event.GetComponent())) assert.Equal(c, operatorv1.ResourceEventType_UPDATED, event.GetType()) assert.Equal(c, "UPDATED", event.GetType().String()) }, time.Second*10, time.Millisecond*10) }) t.Run("DELETE", func(t *testing.T) { b.store.Set() b.kubeapi.Informer().Delete(t, comp) b, err := json.Marshal(comp) require.NoError(t, err) assert.EventuallyWithT(t, func(c *assert.CollectT) { event, err := stream.Recv() //nolint:testifylint if !assert.NoError(c, err) { return } var gotComp compapi.Component require.NoError(t, json.Unmarshal(event.GetComponent(), &gotComp)) assert.Equal(t, comp, &gotComp) assert.JSONEq(c, string(b), string(event.GetComponent())) assert.Equal(c, operatorv1.ResourceEventType_DELETED, event.GetType()) assert.Equal(c, "DELETED", event.GetType().String()) }, time.Second*10, time.Millisecond*10) }) }
mikeee/dapr
tests/integration/suite/operator/api/componentupdate/basic.go
GO
mit
5,047
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh. See the License for the specific language governing permissions and limitations under the License. */ package componentupdate import ( _ "github.com/dapr/dapr/tests/integration/suite/operator/api/componentupdate/scopes" )
mikeee/dapr
tests/integration/suite/operator/api/componentupdate/componentupdate.go
GO
mit
683
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package scopes import ( "context" "encoding/json" "testing" "github.com/spiffe/go-spiffe/v2/spiffeid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/dapr/dapr/pkg/apis/common" compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1" operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/kubernetes" "github.com/dapr/dapr/tests/integration/framework/process/kubernetes/store" "github.com/dapr/dapr/tests/integration/framework/process/operator" "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(addapp)) } type addapp struct { sentry *sentry.Sentry store *store.Store kubeapi *kubernetes.Kubernetes operator *operator.Operator } func (a *addapp) Setup(t *testing.T) []framework.Option { a.sentry = sentry.New(t, sentry.WithTrustDomain("integration.test.dapr.io")) a.store = store.New(metav1.GroupVersionKind{ Group: "dapr.io", Version: "v1alpha1", Kind: "Component", }) a.kubeapi = kubernetes.New(t, kubernetes.WithBaseOperatorAPI(t, spiffeid.RequireTrustDomainFromString("integration.test.dapr.io"), "default", a.sentry.Port(), ), kubernetes.WithClusterDaprComponentListFromStore(t, a.store), ) a.operator = operator.New(t, operator.WithNamespace("default"), operator.WithKubeconfigPath(a.kubeapi.KubeconfigPath(t)), operator.WithTrustAnchorsFile(a.sentry.TrustAnchorsFile(t)), ) return []framework.Option{ framework.WithProcesses(a.sentry, a.kubeapi, a.operator), } } func (a *addapp) Run(t *testing.T, ctx context.Context) { a.sentry.WaitUntilRunning(t, ctx) a.operator.WaitUntilRunning(t, ctx) client := a.operator.Dial(t, ctx, a.sentry, "myapp") comp := &compapi.Component{ ObjectMeta: metav1.ObjectMeta{Name: "mycomponent", Namespace: "default", CreationTimestamp: metav1.Time{}}, Spec: compapi.ComponentSpec{ Type: "state.redis", Version: "v1", IgnoreErrors: false, Metadata: []common.NameValuePair{ {Name: "connectionString", Value: common.DynamicValue{JSON: apiextv1.JSON{Raw: []byte(`"foobar"`)}}}, }, }, } a.store.Add(comp) stream, err := client.ComponentUpdate(ctx, &operatorv1.ComponentUpdateRequest{Namespace: "default"}) require.NoError(t, err) t.Cleanup(func() { require.NoError(t, stream.CloseSend()) }) event, err := stream.Recv() require.NoError(t, err) var gotComp compapi.Component require.NoError(t, json.Unmarshal(event.GetComponent(), &gotComp)) assert.Equal(t, comp, &gotComp) assert.Equal(t, operatorv1.ResourceEventType_CREATED, event.GetType()) assert.Equal(t, "CREATED", event.GetType().String()) t.Run("Adding scope for another app ID should send update", func(t *testing.T) { newcomp := comp.DeepCopy() newcomp.Scopes = []string{"myapp", "app1"} a.store.Set(newcomp) a.kubeapi.Informer().Modify(t, newcomp) event, err := stream.Recv() require.NoError(t, err) var gotComp compapi.Component require.NoError(t, json.Unmarshal(event.GetComponent(), &gotComp)) assert.Equal(t, newcomp, &gotComp) assert.Equal(t, operatorv1.ResourceEventType_UPDATED, event.GetType()) assert.Equal(t, "UPDATED", event.GetType().String()) }) }
mikeee/dapr
tests/integration/suite/operator/api/componentupdate/scopes/addapp.go
GO
mit
4,043
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package scopes import ( "context" "encoding/json" "testing" "github.com/spiffe/go-spiffe/v2/spiffeid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/dapr/dapr/pkg/apis/common" compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1" operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/kubernetes" "github.com/dapr/dapr/tests/integration/framework/process/kubernetes/store" "github.com/dapr/dapr/tests/integration/framework/process/operator" "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(deleteapp)) } type deleteapp struct { sentry *sentry.Sentry store *store.Store kubeapi *kubernetes.Kubernetes operator *operator.Operator } func (d *deleteapp) Setup(t *testing.T) []framework.Option { d.sentry = sentry.New(t, sentry.WithTrustDomain("integration.test.dapr.io")) d.store = store.New(metav1.GroupVersionKind{ Group: "dapr.io", Version: "v1alpha1", Kind: "Component", }) d.kubeapi = kubernetes.New(t, kubernetes.WithBaseOperatorAPI(t, spiffeid.RequireTrustDomainFromString("integration.test.dapr.io"), "default", d.sentry.Port(), ), kubernetes.WithClusterDaprComponentListFromStore(t, d.store), ) d.operator = operator.New(t, operator.WithNamespace("default"), operator.WithKubeconfigPath(d.kubeapi.KubeconfigPath(t)), operator.WithTrustAnchorsFile(d.sentry.TrustAnchorsFile(t)), ) return []framework.Option{ framework.WithProcesses(d.sentry, d.kubeapi, d.operator), } } func (d *deleteapp) Run(t *testing.T, ctx context.Context) { d.sentry.WaitUntilRunning(t, ctx) d.operator.WaitUntilRunning(t, ctx) client := d.operator.Dial(t, ctx, d.sentry, "myapp") comp := &compapi.Component{ ObjectMeta: metav1.ObjectMeta{Name: "mycomponent", Namespace: "default", CreationTimestamp: metav1.Time{}}, Spec: compapi.ComponentSpec{ Type: "state.redis", Version: "v1", IgnoreErrors: false, Metadata: []common.NameValuePair{ {Name: "connectionString", Value: common.DynamicValue{JSON: apiextv1.JSON{Raw: []byte(`"foobar"`)}}}, }, }, } d.store.Add(comp) stream, err := client.ComponentUpdate(ctx, &operatorv1.ComponentUpdateRequest{Namespace: "default"}) require.NoError(t, err) t.Cleanup(func() { require.NoError(t, stream.CloseSend()) }) event, err := stream.Recv() require.NoError(t, err) var gotComp compapi.Component require.NoError(t, json.Unmarshal(event.GetComponent(), &gotComp)) assert.Equal(t, comp, &gotComp) assert.Equal(t, operatorv1.ResourceEventType_CREATED, event.GetType()) assert.Equal(t, "CREATED", event.GetType().String()) t.Run("Adding scope for another app ID should send delete", func(t *testing.T) { newcomp := comp.DeepCopy() newcomp.Scopes = []string{"app1"} d.store.Set(newcomp) d.kubeapi.Informer().Modify(t, newcomp) event, err := stream.Recv() require.NoError(t, err) var gotComp compapi.Component require.NoError(t, json.Unmarshal(event.GetComponent(), &gotComp)) assert.Equal(t, comp, &gotComp) assert.Equal(t, operatorv1.ResourceEventType_DELETED, event.GetType()) assert.Equal(t, "DELETED", event.GetType().String()) }) }
mikeee/dapr
tests/integration/suite/operator/api/componentupdate/scopes/deleteapp.go
GO
mit
4,043
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package listcomponents import ( "context" "encoding/json" "strings" "testing" "time" "github.com/spiffe/go-spiffe/v2/spiffeid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/dapr/dapr/pkg/apis/common" compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1" operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/kubernetes" operator "github.com/dapr/dapr/tests/integration/framework/process/operator" procsentry "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(basic)) } // basic tests the operator's ListCompontns API. type basic struct { sentry *procsentry.Sentry kubeapi *kubernetes.Kubernetes operator *operator.Operator comp1 *compapi.Component comp2 *compapi.Component } func (b *basic) Setup(t *testing.T) []framework.Option { b.sentry = procsentry.New(t, procsentry.WithTrustDomain("integration.test.dapr.io")) b.comp1 = &compapi.Component{ TypeMeta: metav1.TypeMeta{Kind: "Component", APIVersion: "dapr.io/v1alpha1"}, ObjectMeta: metav1.ObjectMeta{Name: "mycomponent", Namespace: "default"}, Spec: compapi.ComponentSpec{ Type: "state.redis", Version: "v1", IgnoreErrors: false, Metadata: []common.NameValuePair{ { Name: "connectionString", Value: common.DynamicValue{ JSON: apiextv1.JSON{Raw: []byte(`"foobar"`)}, }, }, }, }, } b.comp2 = &compapi.Component{ TypeMeta: metav1.TypeMeta{Kind: "Component", APIVersion: "dapr.io/v1alpha1"}, ObjectMeta: metav1.ObjectMeta{Name: "myothercomponent", Namespace: "default"}, Spec: compapi.ComponentSpec{ Type: "state.inmemory", Version: "v1", }, } // This component should not be listed as it is in a different namespace. comp3 := &compapi.Component{ TypeMeta: metav1.TypeMeta{Kind: "Component", APIVersion: "dapr.io/v1alpha1"}, ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "bar"}, Spec: compapi.ComponentSpec{ Type: "state.inmemory", Version: "v1", }, } b.kubeapi = kubernetes.New(t, kubernetes.WithBaseOperatorAPI(t, spiffeid.RequireTrustDomainFromString("integration.test.dapr.io"), "default", b.sentry.Port(), ), kubernetes.WithClusterDaprComponentList(t, &compapi.ComponentList{ TypeMeta: metav1.TypeMeta{Kind: "ComponentList", APIVersion: "dapr.io/v1alpha1"}, Items: []compapi.Component{*b.comp1, *b.comp2, *comp3}, }), ) b.operator = operator.New(t, operator.WithNamespace("default"), operator.WithKubeconfigPath(b.kubeapi.KubeconfigPath(t)), operator.WithTrustAnchorsFile(b.sentry.TrustAnchorsFile(t)), ) return []framework.Option{ framework.WithProcesses(b.kubeapi, b.sentry, b.operator), } } func (b *basic) Run(t *testing.T, ctx context.Context) { b.sentry.WaitUntilRunning(t, ctx) b.operator.WaitUntilRunning(t, ctx) client := b.operator.Dial(t, ctx, b.sentry, "myapp") t.Run("LIST", func(t *testing.T) { var resp *operatorv1.ListComponentResponse require.EventuallyWithT(t, func(c *assert.CollectT) { var err error resp, err = client.ListComponents(ctx, &operatorv1.ListComponentsRequest{Namespace: "default"}) require.NoError(t, err) assert.Len(c, resp.GetComponents(), 2) }, time.Second*20, time.Millisecond*10) b1, err := json.Marshal(b.comp1) require.NoError(t, err) b2, err := json.Marshal(b.comp2) require.NoError(t, err) if strings.Contains(string(resp.GetComponents()[0]), "mycomponent") { assert.JSONEq(t, string(b1), string(resp.GetComponents()[0])) assert.JSONEq(t, string(b2), string(resp.GetComponents()[1])) } else { assert.JSONEq(t, string(b1), string(resp.GetComponents()[1])) assert.JSONEq(t, string(b2), string(resp.GetComponents()[0])) } }) }
mikeee/dapr
tests/integration/suite/operator/api/listcomponents/basic.go
GO
mit
4,602
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh. See the License for the specific language governing permissions and limitations under the License. */ package listcomponents import ( _ "github.com/dapr/dapr/tests/integration/suite/operator/api/listcomponents/scopes" )
mikeee/dapr
tests/integration/suite/operator/api/listcomponents/listcomponents.go
GO
mit
681
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package scopes import ( "context" "encoding/json" "testing" "time" "github.com/spiffe/go-spiffe/v2/spiffeid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/dapr/dapr/pkg/apis/common" compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1" operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/kubernetes" "github.com/dapr/dapr/tests/integration/framework/process/kubernetes/store" "github.com/dapr/dapr/tests/integration/framework/process/operator" "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(addapp)) } type addapp struct { sentry *sentry.Sentry store *store.Store kubeapi *kubernetes.Kubernetes operator *operator.Operator } func (a *addapp) Setup(t *testing.T) []framework.Option { a.sentry = sentry.New(t, sentry.WithTrustDomain("integration.test.dapr.io")) a.store = store.New(metav1.GroupVersionKind{ Group: "dapr.io", Version: "v1alpha1", Kind: "Component", }) a.kubeapi = kubernetes.New(t, kubernetes.WithBaseOperatorAPI(t, spiffeid.RequireTrustDomainFromString("integration.test.dapr.io"), "default", a.sentry.Port(), ), kubernetes.WithClusterDaprComponentListFromStore(t, a.store), ) a.operator = operator.New(t, operator.WithNamespace("default"), operator.WithKubeconfigPath(a.kubeapi.KubeconfigPath(t)), operator.WithTrustAnchorsFile(a.sentry.TrustAnchorsFile(t)), ) return []framework.Option{ framework.WithProcesses(a.sentry, a.kubeapi, a.operator), } } func (a *addapp) Run(t *testing.T, ctx context.Context) { a.sentry.WaitUntilRunning(t, ctx) a.operator.WaitUntilRunning(t, ctx) client := a.operator.Dial(t, ctx, a.sentry, "myapp") comp := &compapi.Component{ ObjectMeta: metav1.ObjectMeta{Name: "mycomponent", Namespace: "default", CreationTimestamp: metav1.Time{}}, TypeMeta: metav1.TypeMeta{Kind: "Component", APIVersion: "dapr.io/v1alpha1"}, Spec: compapi.ComponentSpec{ Type: "state.redis", Version: "v1", IgnoreErrors: false, Metadata: []common.NameValuePair{ {Name: "connectionString", Value: common.DynamicValue{JSON: apiextv1.JSON{Raw: []byte(`"foobar"`)}}}, }, }, } a.store.Add(comp) var list *operatorv1.ListComponentResponse assert.EventuallyWithT(t, func(c *assert.CollectT) { var err error list, err = client.ListComponents(ctx, &operatorv1.ListComponentsRequest{Namespace: "default"}) //nolint:testifylint if assert.NoError(c, err) { assert.Len(c, list.GetComponents(), 1) } }, time.Second*10, time.Millisecond*10) var gotComp compapi.Component require.NoError(t, json.Unmarshal(list.GetComponents()[0], &gotComp)) assert.Equal(t, comp, &gotComp) t.Run("Adding scope for another app ID should still be sent", func(t *testing.T) { newcomp := comp.DeepCopy() newcomp.Scopes = []string{"myapp", "app1"} a.store.Set(newcomp) assert.EventuallyWithT(t, func(c *assert.CollectT) { list, err := client.ListComponents(ctx, &operatorv1.ListComponentsRequest{Namespace: "default"}) //nolint:testifylint if !assert.NoError(c, err) { return } if !assert.Len(c, list.GetComponents(), 1) { return } var gotComp compapi.Component require.NoError(t, json.Unmarshal(list.GetComponents()[0], &gotComp)) assert.Equal(c, newcomp, &gotComp) }, time.Second*10, time.Millisecond*10) }) }
mikeee/dapr
tests/integration/suite/operator/api/listcomponents/scopes/addapp.go
GO
mit
4,232
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package scopes import ( "context" "encoding/json" "testing" "time" "github.com/spiffe/go-spiffe/v2/spiffeid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/dapr/dapr/pkg/apis/common" compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1" operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/kubernetes" "github.com/dapr/dapr/tests/integration/framework/process/kubernetes/store" "github.com/dapr/dapr/tests/integration/framework/process/operator" "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(deleteapp)) } type deleteapp struct { sentry *sentry.Sentry store *store.Store kubeapi *kubernetes.Kubernetes operator *operator.Operator } func (d *deleteapp) Setup(t *testing.T) []framework.Option { d.sentry = sentry.New(t, sentry.WithTrustDomain("integration.test.dapr.io")) d.store = store.New(metav1.GroupVersionKind{ Group: "dapr.io", Version: "v1alpha1", Kind: "Component", }) d.kubeapi = kubernetes.New(t, kubernetes.WithBaseOperatorAPI(t, spiffeid.RequireTrustDomainFromString("integration.test.dapr.io"), "default", d.sentry.Port(), ), kubernetes.WithClusterDaprComponentListFromStore(t, d.store), ) d.operator = operator.New(t, operator.WithNamespace("default"), operator.WithKubeconfigPath(d.kubeapi.KubeconfigPath(t)), operator.WithTrustAnchorsFile(d.sentry.TrustAnchorsFile(t)), ) return []framework.Option{ framework.WithProcesses(d.sentry, d.kubeapi, d.operator), } } func (d *deleteapp) Run(t *testing.T, ctx context.Context) { d.sentry.WaitUntilRunning(t, ctx) d.operator.WaitUntilRunning(t, ctx) client := d.operator.Dial(t, ctx, d.sentry, "myapp") comp := &compapi.Component{ ObjectMeta: metav1.ObjectMeta{Name: "mycomponent", Namespace: "default", CreationTimestamp: metav1.Time{}}, TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Component"}, Spec: compapi.ComponentSpec{ Type: "state.redis", Version: "v1", IgnoreErrors: false, Metadata: []common.NameValuePair{ {Name: "connectionString", Value: common.DynamicValue{JSON: apiextv1.JSON{Raw: []byte(`"foobar"`)}}}, }, }, } d.store.Set(comp) var list *operatorv1.ListComponentResponse assert.EventuallyWithT(t, func(c *assert.CollectT) { var err error list, err = client.ListComponents(ctx, &operatorv1.ListComponentsRequest{Namespace: "default"}) //nolint:testifylint if assert.NoError(c, err) { assert.Len(c, list.GetComponents(), 1) } }, time.Second*10, time.Millisecond*10) var gotComp compapi.Component require.NoError(t, json.Unmarshal(list.GetComponents()[0], &gotComp)) assert.Equal(t, comp, &gotComp) t.Run("Adding scope for another app ID should no longer be sent", func(t *testing.T) { newcomp := comp.DeepCopy() newcomp.Scopes = []string{"app1"} d.store.Set(newcomp) assert.EventuallyWithT(t, func(c *assert.CollectT) { list, err := client.ListComponents(ctx, &operatorv1.ListComponentsRequest{Namespace: "default"}) //nolint:testifylint if assert.NoError(c, err) { assert.Empty(c, list.GetComponents()) } }, time.Second*10, time.Millisecond*10) }) }
mikeee/dapr
tests/integration/suite/operator/api/listcomponents/scopes/deleteapp.go
GO
mit
4,061
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh. See the License for the specific language governing permissions and limitations under the License. */ package operator import ( _ "github.com/dapr/dapr/tests/integration/suite/operator/api" )
mikeee/dapr
tests/integration/suite/operator/operator.go
GO
mit
653
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package apilevel import ( "context" "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" placementv1pb "github.com/dapr/dapr/pkg/proto/placement/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/placement" "github.com/dapr/dapr/tests/integration/framework/util" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(noMax)) } // noMax tests placement reports API level with no maximum API level. type noMax struct { place *placement.Placement } func (n *noMax) Setup(t *testing.T) []framework.Option { n.place = placement.New(t, placement.WithMetadataEnabled(true), placement.WithMaxAPILevel(-1), ) return []framework.Option{ framework.WithProcesses(n.place), } } func (n *noMax) Run(t *testing.T, ctx context.Context) { const level1 = 20 const level2 = 30 httpClient := util.HTTPClient(t) n.place.WaitUntilRunning(t, ctx) currentVersion := atomic.Uint32{} lastVersionUpdate := atomic.Int64{} // Register the first host with the lower API level msg1 := &placementv1pb.Host{ Name: "myapp1", Port: 1111, Entities: []string{"someactor1"}, Id: "myapp1", ApiLevel: uint32(level1), } ctx1, cancel1 := context.WithCancel(ctx) placementMessageCh1 := n.place.RegisterHost(t, ctx1, msg1) // Collect messages go func() { for { select { case <-ctx.Done(): return case <-ctx1.Done(): return case pt1 := <-placementMessageCh1: if ctx.Err() != nil { return } newAPILevel := pt1.GetApiLevel() oldAPILevel := currentVersion.Swap(newAPILevel) if oldAPILevel != newAPILevel { lastVersionUpdate.Store(time.Now().Unix()) } } } }() require.EventuallyWithT(t, func(t *assert.CollectT) { assert.Equal(t, uint32(level1), currentVersion.Load()) }, 10*time.Second, 50*time.Millisecond) lastUpdate := lastVersionUpdate.Load() var versionInPlacementTable int require.EventuallyWithT(t, func(t *assert.CollectT) { versionInPlacementTable = n.place.CheckAPILevelInState(t, httpClient, level1) }, 5*time.Second, 10*time.Millisecond) // Register the second host with the higher API level msg2 := &placementv1pb.Host{ Name: "myapp2", Port: 2222, Entities: []string{"someactor2"}, Id: "myapp2", ApiLevel: uint32(level2), } ctx2, cancel2 := context.WithCancel(ctx) placementMessageCh2 := n.place.RegisterHost(t, ctx2, msg2) go func() { for { select { case <-ctx.Done(): return case <-ctx2.Done(): return case pt2 := <-placementMessageCh2: if ctx.Err() != nil { return } newAPILevel := pt2.GetApiLevel() oldAPILevel := currentVersion.Swap(newAPILevel) if oldAPILevel != newAPILevel { lastVersionUpdate.Store(time.Now().Unix()) } } } }() // After 3s, we should not receive an update // This can take a while as dissemination happens on intervals time.Sleep(3 * time.Second) require.Equal(t, lastUpdate, lastVersionUpdate.Load()) // API level should still be lower (20), but table version should have increased require.EventuallyWithT(t, func(t *assert.CollectT) { newTableVersion := n.place.CheckAPILevelInState(t, httpClient, level1) assert.Greater(t, newTableVersion, versionInPlacementTable) }, 10*time.Second, 10*time.Millisecond) // Stop the first host, and the in API level should increase cancel1() assert.EventuallyWithT(t, func(t *assert.CollectT) { assert.Equal(t, uint32(level2), currentVersion.Load()) }, 10*time.Second, 50*time.Millisecond) require.EventuallyWithT(t, func(t *assert.CollectT) { versionInPlacementTable = n.place.CheckAPILevelInState(t, httpClient, level2) }, 5*time.Second, 10*time.Millisecond) // Trying to register a host with version 5 should fail n.place.AssertRegisterHostFails(t, ctx, 5) // Stop the second host too cancel2() // Ensure that the table version increases, but the API level remains the same require.EventuallyWithT(t, func(t *assert.CollectT) { newTableVersion := n.place.CheckAPILevelInState(t, httpClient, level2) assert.Greater(t, newTableVersion, versionInPlacementTable) }, 5*time.Second, 10*time.Millisecond) // Trying to register a host with version 10 should fail n.place.AssertRegisterHostFails(t, ctx, level1) }
mikeee/dapr
tests/integration/suite/placement/apilevel/no_max.go
GO
mit
4,925
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package apilevel import ( "context" "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" placementv1pb "github.com/dapr/dapr/pkg/proto/placement/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/placement" "github.com/dapr/dapr/tests/integration/framework/util" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(withMax)) } // withMax tests placement reports API level with maximum API level. type withMax struct { place *placement.Placement } func (n *withMax) Setup(t *testing.T) []framework.Option { n.place = placement.New(t, placement.WithMaxAPILevel(25), placement.WithMetadataEnabled(true), ) return []framework.Option{ framework.WithProcesses(n.place), } } func (n *withMax) Run(t *testing.T, ctx context.Context) { const level1 = 20 const level2 = 30 httpClient := util.HTTPClient(t) n.place.WaitUntilRunning(t, ctx) // Collect messages currentVersion := atomic.Uint32{} lastVersionUpdate := atomic.Int64{} // Register the first host with the lower API level msg1 := &placementv1pb.Host{ Name: "myapp1", Port: 1111, Entities: []string{"someactor1"}, Id: "myapp1", ApiLevel: uint32(level1), } ctx1, cancel1 := context.WithCancel(ctx) placementMessageCh1 := n.place.RegisterHost(t, ctx1, msg1) // Collect messages go func() { for { select { case <-ctx.Done(): return case <-ctx1.Done(): return case pt1 := <-placementMessageCh1: if ctx.Err() != nil { return } newAPILevel := pt1.GetApiLevel() oldAPILevel := currentVersion.Swap(newAPILevel) if oldAPILevel != newAPILevel { lastVersionUpdate.Store(time.Now().Unix()) } } } }() require.EventuallyWithT(t, func(t *assert.CollectT) { assert.Equal(t, uint32(level1), currentVersion.Load()) }, 10*time.Second, 50*time.Millisecond) lastUpdate := lastVersionUpdate.Load() require.EventuallyWithT(t, func(t *assert.CollectT) { n.place.CheckAPILevelInState(t, httpClient, level1) }, 5*time.Second, 10*time.Millisecond) // Register the second host with the higher API level msg2 := &placementv1pb.Host{ Name: "myapp2", Port: 2222, Entities: []string{"someactor2"}, Id: "myapp2", ApiLevel: uint32(level2), } placementMessageCh2 := n.place.RegisterHost(t, ctx, msg2) go func() { for { select { case <-ctx.Done(): return case pt2 := <-placementMessageCh2: if ctx.Err() != nil { return } newAPILevel := pt2.GetApiLevel() oldAPILevel := currentVersion.Swap(newAPILevel) if oldAPILevel != newAPILevel { lastVersionUpdate.Store(time.Now().Unix()) } } } }() // After 3s, we should not receive an update // This can take a while as dissemination happens on intervals time.Sleep(3 * time.Second) require.Equal(t, lastUpdate, lastVersionUpdate.Load()) // API level should not increase require.EventuallyWithT(t, func(t *assert.CollectT) { n.place.CheckAPILevelInState(t, httpClient, level1) }, 5*time.Second, 10*time.Millisecond) // Stop the first host, and the in API level should increase to the max (25) cancel1() require.EventuallyWithT(t, func(t *assert.CollectT) { assert.Equal(t, uint32(25), currentVersion.Load()) }, 15*time.Second, 50*time.Millisecond) require.EventuallyWithT(t, func(t *assert.CollectT) { n.place.CheckAPILevelInState(t, httpClient, 25) }, 5*time.Second, 10*time.Millisecond) }
mikeee/dapr
tests/integration/suite/placement/apilevel/with_max.go
GO
mit
4,107
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package apilevel import ( "context" "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" placementv1pb "github.com/dapr/dapr/pkg/proto/placement/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/placement" "github.com/dapr/dapr/tests/integration/framework/util" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(withMin)) } // withMin tests placement reports API level with minimum API level. type withMin struct { place *placement.Placement } func (n *withMin) Setup(t *testing.T) []framework.Option { n.place = placement.New(t, placement.WithMaxAPILevel(-1), placement.WithMinAPILevel(20), placement.WithMetadataEnabled(true), ) return []framework.Option{ framework.WithProcesses(n.place), } } func (n *withMin) Run(t *testing.T, ctx context.Context) { const ( level1 = 20 level2 = 30 ) httpClient := util.HTTPClient(t) n.place.WaitUntilRunning(t, ctx) currentVersion := atomic.Uint32{} lastVersionUpdate := atomic.Int64{} // API level should be lower require.EventuallyWithT(t, func(t *assert.CollectT) { n.place.CheckAPILevelInState(t, httpClient, level1) }, 5*time.Second, 10*time.Millisecond) // Trying to register a host with version 5 should fail n.place.AssertRegisterHostFails(t, ctx, 5) // Register the first host with the lower API level msg1 := &placementv1pb.Host{ Name: "myapp1", Port: 1111, Entities: []string{"someactor1"}, Id: "myapp1", ApiLevel: uint32(level1), } ctx1, cancel1 := context.WithCancel(ctx) placementMessageCh1 := n.place.RegisterHost(t, ctx1, msg1) // Collect messages go func() { for { select { case <-ctx.Done(): return case <-ctx1.Done(): return case msg := <-placementMessageCh1: if ctx.Err() != nil { return } newAPILevel := msg.GetApiLevel() oldAPILevel := currentVersion.Swap(newAPILevel) if oldAPILevel != newAPILevel { lastVersionUpdate.Store(time.Now().Unix()) } } } }() require.EventuallyWithT(t, func(t *assert.CollectT) { n.place.CheckAPILevelInState(t, httpClient, level1) }, 5*time.Second, 10*time.Millisecond) // Register the second host with the higher API level msg2 := &placementv1pb.Host{ Name: "myapp2", Port: 2222, Entities: []string{"someactor2"}, Id: "myapp2", ApiLevel: uint32(level2), } placementMessageCh2 := n.place.RegisterHost(t, ctx, msg2) go func() { for { select { case <-ctx.Done(): return case pt2 := <-placementMessageCh2: if ctx.Err() != nil { return } newAPILevel := pt2.GetApiLevel() oldAPILevel := currentVersion.Swap(newAPILevel) if oldAPILevel != newAPILevel { lastVersionUpdate.Store(time.Now().Unix()) } } } }() // API level should not increase require.EventuallyWithT(t, func(t *assert.CollectT) { n.place.CheckAPILevelInState(t, httpClient, level1) }, 5*time.Second, 10*time.Millisecond) // Stop the first host, and the in API level should increase to the higher one (30) cancel1() require.EventuallyWithT(t, func(t *assert.CollectT) { assert.Equal(t, uint32(level2), currentVersion.Load()) }, 15*time.Second, 50*time.Millisecond) require.EventuallyWithT(t, func(t *assert.CollectT) { n.place.CheckAPILevelInState(t, httpClient, level2) }, 5*time.Second, 10*time.Millisecond) }
mikeee/dapr
tests/integration/suite/placement/apilevel/with_min.go
GO
mit
4,030
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package authz import ( "context" "os" "path/filepath" "testing" "time" "github.com/spiffe/go-spiffe/v2/spiffeid" "github.com/stretchr/testify/require" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" v1pb "github.com/dapr/dapr/pkg/proto/placement/v1" "github.com/dapr/dapr/pkg/security" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/placement" "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(mtls)) } // mtls tests placement can find quorum with tls disabled. type mtls struct { sentry *sentry.Sentry place *placement.Placement } func (m *mtls) Setup(t *testing.T) []framework.Option { m.sentry = sentry.New(t) taFile := filepath.Join(t.TempDir(), "ca.pem") require.NoError(t, os.WriteFile(taFile, m.sentry.CABundle().TrustAnchors, 0o600)) m.place = placement.New(t, placement.WithEnableTLS(true), placement.WithSentryAddress(m.sentry.Address()), placement.WithTrustAnchorsFile(taFile), ) return []framework.Option{ framework.WithProcesses(m.sentry, m.place), } } func (m *mtls) Run(t *testing.T, ctx context.Context) { m.sentry.WaitUntilRunning(t, ctx) m.place.WaitUntilRunning(t, ctx) secProv, err := security.New(ctx, security.Options{ SentryAddress: m.sentry.Address(), ControlPlaneTrustDomain: "localhost", ControlPlaneNamespace: "default", TrustAnchors: m.sentry.CABundle().TrustAnchors, AppID: "app-1", MTLSEnabled: true, }) require.NoError(t, err) ctx, cancel := context.WithCancel(ctx) errCh := make(chan error, 1) go func() { errCh <- secProv.Run(ctx) }() t.Cleanup(func() { cancel(); require.NoError(t, <-errCh) }) sec, err := secProv.Handler(ctx) require.NoError(t, err) placeID, err := spiffeid.FromSegments(sec.ControlPlaneTrustDomain(), "ns", "default", "dapr-placement") require.NoError(t, err) host := m.place.Address() conn, err := grpc.DialContext(ctx, host, grpc.WithBlock(), sec.GRPCDialOptionMTLS(placeID)) require.NoError(t, err) t.Cleanup(func() { require.NoError(t, conn.Close()) }) client := v1pb.NewPlacementClient(conn) // Can only create hosts where the app ID match. // When no namespace is sent in the message, and tls is enabled // the placement service will infer the namespace from the SPIFFE ID. _, err = establishStream(t, ctx, client, &v1pb.Host{ Id: "app-1", }) require.NoError(t, err) _, err = establishStream(t, ctx, client, &v1pb.Host{ Id: "app-2", }) require.Error(t, err) require.Equal(t, codes.PermissionDenied, status.Code(err)) // Older sidecars (pre 1.4) will not send the namespace in the message. // In this case the namespace is inferred from the SPIFFE ID. _, err = establishStream(t, ctx, client, &v1pb.Host{ Id: "app-1", Namespace: "", }) require.NoError(t, err) // The namespace id in the message and SPIFFE ID should match _, err = establishStream(t, ctx, client, &v1pb.Host{ Id: "app-1", Namespace: "default", }) require.NoError(t, err) _, err = establishStream(t, ctx, client, &v1pb.Host{ Id: "app-1", Namespace: "foo", }) require.Error(t, err) require.Equal(t, codes.PermissionDenied, status.Code(err)) } func establishStream(t *testing.T, ctx context.Context, client v1pb.PlacementClient, firstMessage *v1pb.Host) (v1pb.Placement_ReportDaprStatusClient, error) { t.Helper() var stream v1pb.Placement_ReportDaprStatusClient var err error require.Eventually(t, func() bool { stream, err = client.ReportDaprStatus(ctx) if err != nil { return false } err = stream.Send(firstMessage) return err == nil }, 10*time.Second, 10*time.Millisecond) _, err = stream.Recv() return stream, err }
mikeee/dapr
tests/integration/suite/placement/authz/mtls.go
GO
mit
4,430
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package authz import ( "context" "testing" "github.com/stretchr/testify/require" "google.golang.org/grpc" grpcinsecure "google.golang.org/grpc/credentials/insecure" v1pb "github.com/dapr/dapr/pkg/proto/placement/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/placement" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(nomtls)) } // nomtls tests placement can find quorum with tls disabled. type nomtls struct { place *placement.Placement } func (n *nomtls) Setup(t *testing.T) []framework.Option { n.place = placement.New(t) return []framework.Option{ framework.WithProcesses(n.place), } } func (n *nomtls) Run(t *testing.T, ctx context.Context) { n.place.WaitUntilRunning(t, ctx) host := n.place.Address() conn, err := grpc.DialContext(ctx, host, grpc.WithBlock(), grpc.WithReturnConnectionError(), grpc.WithTransportCredentials(grpcinsecure.NewCredentials()), ) require.NoError(t, err) t.Cleanup(func() { require.NoError(t, conn.Close()) }) client := v1pb.NewPlacementClient(conn) // Can create hosts with any appIDs or namespaces. _, err = establishStream(t, ctx, client, new(v1pb.Host)) require.NoError(t, err) _, err = establishStream(t, ctx, client, &v1pb.Host{ Name: "bar", }) require.NoError(t, err) _, err = establishStream(t, ctx, client, &v1pb.Host{ Name: "bar", Namespace: "ns1", }) require.NoError(t, err) }
mikeee/dapr
tests/integration/suite/placement/authz/nomtls.go
GO
mit
2,040
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package dissemination import ( "context" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" v1pb "github.com/dapr/dapr/pkg/proto/placement/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/placement" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(notls)) } type notls struct { place *placement.Placement } func (n *notls) Setup(t *testing.T) []framework.Option { n.place = placement.New(t) return []framework.Option{ framework.WithProcesses(n.place), } } func (n *notls) Run(t *testing.T, ctx context.Context) { n.place.WaitUntilRunning(t, ctx) t.Run("actors in different namespaces are disseminated properly", func(t *testing.T) { host1 := &v1pb.Host{ Name: "myapp1", Namespace: "ns1", Port: 1231, Entities: []string{"actor1", "actor10"}, Id: "myapp1", ApiLevel: uint32(20), } host2 := &v1pb.Host{ Name: "myapp2", Namespace: "ns2", Port: 1232, Entities: []string{"actor2", "actor3"}, Id: "myapp2", ApiLevel: uint32(20), } host3 := &v1pb.Host{ Name: "myapp3", Namespace: "ns2", Port: 1233, Entities: []string{"actor4", "actor5", "actor6", "actor10"}, Id: "myapp3", ApiLevel: uint32(20), } ctx3, cancel3 := context.WithCancel(ctx) placementMessageCh1 := n.place.RegisterHost(t, ctx, host1) placementMessageCh2 := n.place.RegisterHost(t, ctx, host2) placementMessageCh3 := n.place.RegisterHost(t, ctx3, host3) select { case <-ctx.Done(): cancel3() return case placementTables := <-placementMessageCh1: require.Len(t, placementTables.GetEntries(), 2) require.Contains(t, placementTables.GetEntries(), "actor1") require.Contains(t, placementTables.GetEntries(), "actor10") entry, ok := placementTables.GetEntries()["actor10"] require.True(t, ok) loadMap := entry.GetLoadMap() require.Len(t, loadMap, 1) require.Contains(t, loadMap, host1.GetName()) } // Dissemination is done properly on host 2 msgCnt := 0 require.EventuallyWithT(t, func(c *assert.CollectT) { select { case <-ctx.Done(): return case placementTables := <-placementMessageCh2: if ctx.Err() != nil { return } msgCnt++ assert.Len(c, placementTables.GetEntries(), 6) assert.Contains(c, placementTables.GetEntries(), "actor2") assert.Contains(c, placementTables.GetEntries(), "actor3") assert.Contains(c, placementTables.GetEntries(), "actor4") assert.Contains(c, placementTables.GetEntries(), "actor5") assert.Contains(c, placementTables.GetEntries(), "actor6") assert.Contains(c, placementTables.GetEntries(), "actor10") entry, ok := placementTables.GetEntries()["actor10"] if assert.True(c, ok) { loadMap := entry.GetLoadMap() assert.Len(c, loadMap, 1) assert.Contains(c, loadMap, host3.GetName()) } } assert.GreaterOrEqual(c, msgCnt, 1) }, 10*time.Second, 10*time.Millisecond) // Dissemination is done properly on host 3 msgCnt = 0 require.EventuallyWithT(t, func(c *assert.CollectT) { select { case <-ctx.Done(): return case placementTables := <-placementMessageCh3: if ctx.Err() != nil { return } msgCnt++ assert.Len(c, placementTables.GetEntries(), 6) assert.Contains(c, placementTables.GetEntries(), "actor2") assert.Contains(c, placementTables.GetEntries(), "actor3") assert.Contains(c, placementTables.GetEntries(), "actor4") assert.Contains(c, placementTables.GetEntries(), "actor5") assert.Contains(c, placementTables.GetEntries(), "actor6") assert.Contains(c, placementTables.GetEntries(), "actor10") entry, ok := placementTables.GetEntries()["actor10"] if assert.True(c, ok) { loadMap := entry.GetLoadMap() assert.Len(c, loadMap, 1) assert.Contains(c, loadMap, host3.GetName()) } } assert.GreaterOrEqual(c, msgCnt, 1) }, 10*time.Second, 10*time.Millisecond) cancel3() // Disconnect host 3 // Host 2 require.EventuallyWithT(t, func(t *assert.CollectT) { select { case <-ctx.Done(): return case placementTables := <-placementMessageCh2: if ctx.Err() != nil { return } assert.Len(t, placementTables.GetEntries(), 2) assert.Contains(t, placementTables.GetEntries(), "actor2") assert.Contains(t, placementTables.GetEntries(), "actor3") } }, 10*time.Second, 10*time.Millisecond) }) // old sidecars = pre 1.14 t.Run("namespaces are disseminated properly when there are old sidecars in the cluster", func(t *testing.T) { host1 := &v1pb.Host{ Name: "myapp1", Namespace: "ns1", Port: 1231, Entities: []string{"actor1"}, Id: "myapp1", ApiLevel: uint32(20), } host2 := &v1pb.Host{ Name: "myapp2", Port: 1232, Entities: []string{"actor2", "actor3"}, Id: "myapp2", ApiLevel: uint32(20), } host3 := &v1pb.Host{ Name: "myapp3", Port: 1233, Entities: []string{"actor4", "actor5", "actor6"}, Id: "myapp3", ApiLevel: uint32(20), } ctx3, cancel3 := context.WithCancel(ctx) placementMessageCh1 := n.place.RegisterHost(t, ctx, host1) placementMessageCh2 := n.place.RegisterHost(t, ctx, host2) placementMessageCh3 := n.place.RegisterHost(t, ctx3, host3) // Dissemination is done properly on host 1 msgCnt := 0 require.EventuallyWithT(t, func(c *assert.CollectT) { select { case <-ctx.Done(): return case placementTables := <-placementMessageCh1: if ctx.Err() != nil { return } msgCnt++ assert.Len(t, placementTables.GetEntries(), 1) assert.Contains(t, placementTables.GetEntries(), "actor1") } // There's only one host in ns1, so we'll receive only one message assert.Equal(c, 1, msgCnt) }, 10*time.Second, 10*time.Millisecond) // Dissemination is done properly on host 2 msgCnt = 0 require.EventuallyWithT(t, func(c *assert.CollectT) { select { case <-ctx.Done(): return case placementTables := <-placementMessageCh2: if ctx.Err() != nil { return } msgCnt++ assert.Len(c, placementTables.GetEntries(), 5) assert.Contains(c, placementTables.GetEntries(), "actor2") assert.Contains(c, placementTables.GetEntries(), "actor3") assert.Contains(c, placementTables.GetEntries(), "actor4") assert.Contains(c, placementTables.GetEntries(), "actor5") assert.Contains(c, placementTables.GetEntries(), "actor6") } assert.GreaterOrEqual(c, msgCnt, 1) }, 10*time.Second, 10*time.Millisecond) // Dissemination is done properly on host 3 msgCnt = 0 require.EventuallyWithT(t, func(c *assert.CollectT) { select { case <-ctx.Done(): return case placementTables := <-placementMessageCh3: if ctx.Err() != nil { return } msgCnt++ assert.Len(c, placementTables.GetEntries(), 5) assert.Contains(c, placementTables.GetEntries(), "actor2") assert.Contains(c, placementTables.GetEntries(), "actor3") assert.Contains(c, placementTables.GetEntries(), "actor4") assert.Contains(c, placementTables.GetEntries(), "actor5") assert.Contains(c, placementTables.GetEntries(), "actor6") } assert.GreaterOrEqual(c, msgCnt, 1) }, 10*time.Second, 10*time.Millisecond) cancel3() // Disconnect host 3 // Host 2 require.EventuallyWithT(t, func(c *assert.CollectT) { select { case <-ctx.Done(): return case placementTables := <-placementMessageCh2: if ctx.Err() != nil { return } assert.Len(c, placementTables.GetEntries(), 2) assert.Contains(c, placementTables.GetEntries(), "actor2") assert.Contains(c, placementTables.GetEntries(), "actor3") } }, 10*time.Second, 10*time.Millisecond) }) }
mikeee/dapr
tests/integration/suite/placement/dissemination/notls.go
GO
mit
8,425
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package dissemination import ( "context" "fmt" "net/http" "os" "path/filepath" "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/exec" prochttp "github.com/dapr/dapr/tests/integration/framework/process/http" "github.com/dapr/dapr/tests/integration/framework/process/placement" "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(tls)) } type tls struct { sentry *sentry.Sentry place *placement.Placement daprd1, daprd2, daprd3 *daprd.Daprd srv1, srv2, srv3 *prochttp.HTTP } func (n *tls) Setup(t *testing.T) []framework.Option { n.sentry = sentry.New(t) taFile := filepath.Join(t.TempDir(), "ca.pem") require.NoError(t, os.WriteFile(taFile, n.sentry.CABundle().TrustAnchors, 0o600)) n.place = placement.New(t, placement.WithEnableTLS(true), placement.WithSentryAddress(n.sentry.Address()), placement.WithTrustAnchorsFile(taFile), placement.WithMetadataEnabled(true), ) handler1 := http.NewServeMux() handler1.HandleFunc("/dapr/config", func(w http.ResponseWriter, r *http.Request) { types := []string{"actor1"} fmt.Fprintf(w, `{"entities": ["%s"]}`, strings.Join(types, `","`)) }) handler1.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }) handler1.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`OK1`)) }) handler2 := http.NewServeMux() handler2.HandleFunc("/dapr/config", func(w http.ResponseWriter, r *http.Request) { types := []string{"actor2"} fmt.Fprintf(w, `{"entities": ["%s"]}`, strings.Join(types, `","`)) }) handler2.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }) handler2.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`OK2`)) }) handler3 := http.NewServeMux() handler3.HandleFunc("/dapr/config", func(w http.ResponseWriter, r *http.Request) { types := []string{"actor1", "actor3"} // "actor1" exists in both app 1 and app3, but the apps are in a different namespace fmt.Fprintf(w, `{"entities": ["%s"]}`, strings.Join(types, `","`)) }) handler3.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }) handler3.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`OK3`)) }) n.srv1 = prochttp.New(t, prochttp.WithHandler(handler1)) n.srv2 = prochttp.New(t, prochttp.WithHandler(handler2)) n.srv3 = prochttp.New(t, prochttp.WithHandler(handler3)) n.daprd1 = daprd.New(t, daprd.WithInMemoryActorStateStore("mystore1"), daprd.WithAppID("my-app1"), daprd.WithNamespace("ns1"), daprd.WithMode("standalone"), daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(n.sentry.CABundle().TrustAnchors))), daprd.WithSentryAddress(n.sentry.Address()), daprd.WithPlacementAddresses(n.place.Address()), daprd.WithEnableMTLS(true), daprd.WithAppPort(n.srv1.Port()), ) n.daprd2 = daprd.New(t, daprd.WithInMemoryActorStateStore("mystore2"), daprd.WithAppID("my-app2"), daprd.WithNamespace("ns2"), daprd.WithMode("standalone"), daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(n.sentry.CABundle().TrustAnchors))), daprd.WithSentryAddress(n.sentry.Address()), daprd.WithPlacementAddresses(n.place.Address()), daprd.WithEnableMTLS(true), daprd.WithAppPort(n.srv2.Port()), ) n.daprd3 = daprd.New(t, daprd.WithInMemoryActorStateStore("mystore3"), daprd.WithAppID("my-app3"), daprd.WithNamespace("ns2"), daprd.WithMode("standalone"), daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(n.sentry.CABundle().TrustAnchors))), daprd.WithSentryAddress(n.sentry.Address()), daprd.WithPlacementAddresses(n.place.Address()), daprd.WithEnableMTLS(true), daprd.WithAppPort(n.srv3.Port()), ) return []framework.Option{ framework.WithProcesses(n.sentry, n.place, n.srv1, n.srv2, n.srv3, n.daprd1, n.daprd2, n.daprd3), } } func (n *tls) Run(t *testing.T, ctx context.Context) { n.sentry.WaitUntilRunning(t, ctx) n.place.WaitUntilRunning(t, ctx) n.daprd1.WaitUntilRunning(t, ctx) n.daprd2.WaitUntilRunning(t, ctx) n.daprd3.WaitUntilRunning(t, ctx) t.Run("host1 can see actor 1 in ns1, but not actors 2 and 3 in ns2", func(t *testing.T) { client := n.daprd1.GRPCClient(t, ctx) require.EventuallyWithT(t, func(c *assert.CollectT) { val1, err := client.InvokeActor(ctx, &rtv1.InvokeActorRequest{ ActorType: "actor1", ActorId: "myactorid", Method: "foo", }) //nolint:testifylint assert.NoError(c, err) assert.Equal(t, "OK1", string(val1.GetData())) _, err = client.InvokeActor(ctx, &rtv1.InvokeActorRequest{ ActorType: "actor2", ActorId: "myactorid", Method: "foo", }) //nolint:testifylint assert.Error(c, err) _, err = client.InvokeActor(ctx, &rtv1.InvokeActorRequest{ ActorType: "actor3", ActorId: "myactorid", Method: "foo", }) //nolint:testifylint assert.Error(c, err) _, err = client.InvokeActor(ctx, &rtv1.InvokeActorRequest{ ActorType: "inexistant-actor", ActorId: "myactorid", Method: "foo", }) //nolint:testifylint assert.Error(c, err, err) }, time.Second*20, time.Millisecond*10, "actor not ready") }) t.Run("host2 can see actors 1,2,3 in ns2, but not actor 1 in ns1", func(t *testing.T) { client := n.daprd2.GRPCClient(t, ctx) require.EventuallyWithT(t, func(c *assert.CollectT) { val2, err := client.InvokeActor(ctx, &rtv1.InvokeActorRequest{ ActorType: "actor1", ActorId: "myactorid", Method: "foo", }) //nolint:testifylint assert.NoError(c, err) assert.Equal(t, "OK3", string(val2.GetData())) _, err = client.InvokeActor(ctx, &rtv1.InvokeActorRequest{ ActorType: "actor2", ActorId: "myactorid", Method: "foo", }) //nolint:testifylint assert.NoError(c, err) _, err = client.InvokeActor(ctx, &rtv1.InvokeActorRequest{ ActorType: "actor3", ActorId: "myactorid", Method: "foo", }) //nolint:testifylint assert.NoError(c, err) _, err = client.InvokeActor(ctx, &rtv1.InvokeActorRequest{ ActorType: "inexistant-actor", ActorId: "myactorid", Method: "foo", }) //nolint:testifylint assert.Error(c, err, err) }, time.Second*20, time.Millisecond*10, "actors not ready") }) t.Run("host3 can see actors 1,2,3 in ns2, but not actor 1 in ns1", func(t *testing.T) { client := n.daprd3.GRPCClient(t, ctx) require.EventuallyWithT(t, func(c *assert.CollectT) { val3, err := client.InvokeActor(ctx, &rtv1.InvokeActorRequest{ ActorType: "actor1", ActorId: "myactorid", Method: "foo", }) //nolint:testifylint assert.NoError(c, err) assert.Equal(t, "OK3", string(val3.GetData())) _, err = client.InvokeActor(ctx, &rtv1.InvokeActorRequest{ ActorType: "actor2", ActorId: "myactorid", Method: "foo", }) //nolint:testifylint assert.NoError(c, err) _, err = client.InvokeActor(ctx, &rtv1.InvokeActorRequest{ ActorType: "actor3", ActorId: "myactorid", Method: "foo", }) //nolint:testifylint assert.NoError(c, err) _, err = client.InvokeActor(ctx, &rtv1.InvokeActorRequest{ ActorType: "inexistant-actor", ActorId: "myactorid", Method: "foo", }) //nolint:testifylint assert.Error(c, err, err) }, time.Second*20, time.Millisecond*10, "actors not ready") }) }
mikeee/dapr
tests/integration/suite/placement/dissemination/tls.go
GO
mit
8,447
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ha import ( "context" "fmt" "net/http" "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" v1pb "github.com/dapr/dapr/pkg/proto/placement/v1" "github.com/dapr/dapr/tests/integration/framework" prochttp "github.com/dapr/dapr/tests/integration/framework/process/http" "github.com/dapr/dapr/tests/integration/framework/process/placement" "github.com/dapr/dapr/tests/integration/framework/process/ports" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(failover)) } type failover struct { fp *ports.Ports placements []*placement.Placement srv *prochttp.HTTP } func (n *failover) Setup(t *testing.T) []framework.Option { n.fp = ports.Reserve(t, 3) port1, port2, port3 := n.fp.Port(t), n.fp.Port(t), n.fp.Port(t) opts := []placement.Option{ placement.WithInitialCluster(fmt.Sprintf("p1=localhost:%d,p2=localhost:%d,p3=localhost:%d", port1, port2, port3)), placement.WithInitialClusterPorts(port1, port2, port3), } n.placements = []*placement.Placement{ placement.New(t, append(opts, placement.WithID("p1"))...), placement.New(t, append(opts, placement.WithID("p2"))...), placement.New(t, append(opts, placement.WithID("p3"))...), } // Dummy http server that returns the list of actors handler := http.NewServeMux() handler.HandleFunc("/dapr/config", func(w http.ResponseWriter, r *http.Request) { types := []string{"actor1"} fmt.Fprintf(w, `{"entities": ["%s"]}`, strings.Join(types, `","`)) }) handler.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }) handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`OK1`)) }) n.srv = prochttp.New(t, prochttp.WithHandler(handler)) return []framework.Option{ framework.WithProcesses(n.fp, n.srv), } } func (n *failover) Run(t *testing.T, ctx context.Context) { host1 := &v1pb.Host{ Name: "myapp1", Namespace: "ns1", Port: 1231, Entities: []string{"actor1", "actor10"}, Id: "myapp1", ApiLevel: uint32(20), } host2 := &v1pb.Host{ Name: "myapp2", Namespace: "ns2", Port: 1232, Entities: []string{"actor2", "actor3"}, Id: "myapp2", ApiLevel: uint32(20), } host3 := &v1pb.Host{ Name: "myapp3", Namespace: "ns2", Port: 1233, Entities: []string{"actor4", "actor5", "actor6", "actor10"}, Id: "myapp3", ApiLevel: uint32(20), } n.placements[0].Run(t, ctx) n.placements[1].Run(t, ctx) n.placements[2].Run(t, ctx) n.placements[0].WaitUntilRunning(t, ctx) n.placements[1].WaitUntilRunning(t, ctx) n.placements[2].WaitUntilRunning(t, ctx) leaderIndex := n.getLeader(t, ctx, -1) require.NotEqualf(t, -1, leaderIndex, "no leader elected") placementMessageCh1 := n.placements[leaderIndex].RegisterHost(t, ctx, host1) placementMessageCh2 := n.placements[leaderIndex].RegisterHost(t, ctx, host2) placementMessageCh3 := n.placements[leaderIndex].RegisterHost(t, ctx, host3) // Dissemination is done properly on host 1 select { case <-ctx.Done(): return case placementTables := <-placementMessageCh1: if ctx.Err() != nil { return } require.Len(t, placementTables.GetEntries(), 2) require.Contains(t, placementTables.GetEntries(), "actor1") require.Contains(t, placementTables.GetEntries(), "actor10") entry, ok := placementTables.GetEntries()["actor10"] require.True(t, ok) loadMap := entry.GetLoadMap() assert.Len(t, loadMap, 1) assert.Contains(t, loadMap, host1.GetName()) } // Dissemination is done properly on host 2 msgCnt := 0 require.EventuallyWithT(t, func(c *assert.CollectT) { select { case <-ctx.Done(): return case placementTables := <-placementMessageCh2: if ctx.Err() != nil { return } msgCnt++ assert.Len(c, placementTables.GetEntries(), 6) assert.Contains(c, placementTables.GetEntries(), "actor2") assert.Contains(c, placementTables.GetEntries(), "actor3") assert.Contains(c, placementTables.GetEntries(), "actor4") assert.Contains(c, placementTables.GetEntries(), "actor5") assert.Contains(c, placementTables.GetEntries(), "actor6") assert.Contains(c, placementTables.GetEntries(), "actor10") entry, ok := placementTables.GetEntries()["actor10"] if assert.True(c, ok) { loadMap := entry.GetLoadMap() assert.Len(c, loadMap, 1) assert.Contains(c, loadMap, host3.GetName()) } } assert.GreaterOrEqual(c, msgCnt, 1) }, 10*time.Second, 10*time.Millisecond) // Dissemination is done properly on host 3 msgCnt = 0 require.EventuallyWithT(t, func(c *assert.CollectT) { select { case <-ctx.Done(): return case placementTables := <-placementMessageCh3: if ctx.Err() != nil { return } msgCnt++ assert.Len(c, placementTables.GetEntries(), 6) assert.Contains(c, placementTables.GetEntries(), "actor2") assert.Contains(c, placementTables.GetEntries(), "actor3") assert.Contains(c, placementTables.GetEntries(), "actor4") assert.Contains(c, placementTables.GetEntries(), "actor5") assert.Contains(c, placementTables.GetEntries(), "actor6") assert.Contains(c, placementTables.GetEntries(), "actor10") entry, ok := placementTables.GetEntries()["actor10"] if assert.True(c, ok) { loadMap := entry.GetLoadMap() assert.Len(c, loadMap, 1) assert.Contains(c, loadMap, host3.GetName()) } } assert.GreaterOrEqual(c, msgCnt, 1) }, 10*time.Second, 10*time.Millisecond) // Stop the placement leader and don't reconnect one fo the hosts in ns2. Check that: // - a new leader has been elected // - dissemination message hasn't been sent to host1, because there haven't been changes in ns1 // - dissemination message has been sent to host2, because host 3 hasn't reconnected, thus // there have been changes in the dissemination table n.placements[leaderIndex].Cleanup(t) leaderIndex = n.getLeader(t, ctx, leaderIndex) require.NotEqualf(t, -1, leaderIndex, "no leader elected") placementMessageCh2 = n.placements[leaderIndex].RegisterHost(t, ctx, host2) n.placements[leaderIndex].RegisterHost(t, ctx, host1) require.EventuallyWithT(t, func(c *assert.CollectT) { select { case <-ctx.Done(): return case placementTables := <-placementMessageCh2: if ctx.Err() != nil { return } msgCnt++ assert.Len(t, placementTables.GetEntries(), 2) assert.Contains(t, placementTables.GetEntries(), "actor2") assert.Contains(t, placementTables.GetEntries(), "actor3") } assert.GreaterOrEqual(c, msgCnt, 1) }, 10*time.Second, 500*time.Millisecond) } func (n *failover) getLeader(t *testing.T, ctx context.Context, skip int) int { // Connect to each placement until one succeeds, indicating that a leader has been elected. // If the condition is met, j is the index of the placement leader var stream v1pb.Placement_ReportDaprStatusClient i := -1 j := 0 require.Eventually(t, func() bool { i++ j = i % len(n.placements) if j == skip { return false } host := n.placements[j].Address() conn, err := grpc.DialContext(ctx, host, grpc.WithBlock(), grpc.WithReturnConnectionError(), grpc.WithTransportCredentials(insecure.NewCredentials()), ) if err != nil { return false } t.Cleanup(func() { require.NoError(t, conn.Close()) }) client := v1pb.NewPlacementClient(conn) stream, err = client.ReportDaprStatus(ctx) defer stream.CloseSend() if err != nil { return false } // The dummy host doesn't host any actors, so it won't affect the placement table err = stream.Send(&v1pb.Host{ ApiLevel: uint32(20), }) if err != nil { return false } _, err = stream.Recv() if err != nil { return false } return true }, time.Second*10, time.Millisecond*50) return j }
mikeee/dapr
tests/integration/suite/placement/ha/failover.go
GO
mit
8,450
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh. See the License for the specific language governing permissions and limitations under the License. */ package placement import ( _ "github.com/dapr/dapr/tests/integration/suite/placement/apilevel" _ "github.com/dapr/dapr/tests/integration/suite/placement/authz" _ "github.com/dapr/dapr/tests/integration/suite/placement/dissemination" _ "github.com/dapr/dapr/tests/integration/suite/placement/ha" _ "github.com/dapr/dapr/tests/integration/suite/placement/quorum" _ "github.com/dapr/dapr/tests/integration/suite/placement/vnodes" )
mikeee/dapr
tests/integration/suite/placement/placement.go
GO
mit
997
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package quorum import ( "context" "fmt" "os" "path/filepath" "testing" "time" "github.com/spiffe/go-spiffe/v2/spiffeid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc" v1pb "github.com/dapr/dapr/pkg/proto/placement/v1" "github.com/dapr/dapr/pkg/security" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/placement" "github.com/dapr/dapr/tests/integration/framework/process/ports" "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(insecure)) } // insecure tests placement can find quorum with tls (insecure) enabled. type insecure struct { places []*placement.Placement sentry *sentry.Sentry } func (i *insecure) Setup(t *testing.T) []framework.Option { i.sentry = sentry.New(t) bundle := i.sentry.CABundle() taFile := filepath.Join(t.TempDir(), "ca.pem") require.NoError(t, os.WriteFile(taFile, bundle.TrustAnchors, 0o600)) fp := ports.Reserve(t, 3) port1, port2, port3 := fp.Port(t), fp.Port(t), fp.Port(t) opts := []placement.Option{ placement.WithInitialCluster(fmt.Sprintf("p1=localhost:%d,p2=localhost:%d,p3=localhost:%d", port1, port2, port3)), placement.WithInitialClusterPorts(port1, port2, port3), placement.WithEnableTLS(true), placement.WithTrustAnchorsFile(taFile), placement.WithSentryAddress(i.sentry.Address()), } i.places = []*placement.Placement{ placement.New(t, append(opts, placement.WithID("p1"))...), placement.New(t, append(opts, placement.WithID("p2"))...), placement.New(t, append(opts, placement.WithID("p3"))...), } return []framework.Option{ framework.WithProcesses(i.sentry, fp, i.places[0], i.places[1], i.places[2]), } } func (i *insecure) Run(t *testing.T, ctx context.Context) { i.sentry.WaitUntilRunning(t, ctx) i.places[0].WaitUntilRunning(t, ctx) i.places[1].WaitUntilRunning(t, ctx) i.places[2].WaitUntilRunning(t, ctx) secProv, err := security.New(ctx, security.Options{ SentryAddress: i.sentry.Address(), ControlPlaneTrustDomain: "localhost", ControlPlaneNamespace: "default", TrustAnchors: i.sentry.CABundle().TrustAnchors, AppID: "app-1", MTLSEnabled: true, }) require.NoError(t, err) ctx, cancel := context.WithCancel(ctx) errCh := make(chan error, 1) go func() { errCh <- secProv.Run(ctx) }() t.Cleanup(func() { cancel(); require.NoError(t, <-errCh) }) sec, err := secProv.Handler(ctx) require.NoError(t, err) placeID, err := spiffeid.FromSegments(sec.ControlPlaneTrustDomain(), "ns", "default", "dapr-placement") require.NoError(t, err) var stream v1pb.Placement_ReportDaprStatusClient // Try connecting to each placement until one succeeds, // indicating that a leader has been elected j := -1 require.Eventually(t, func() bool { j++ if j >= 3 { j = 0 } host := i.places[j].Address() conn, cerr := grpc.DialContext(ctx, host, grpc.WithBlock(), grpc.WithReturnConnectionError(), sec.GRPCDialOptionMTLS(placeID), ) if cerr != nil { return false } t.Cleanup(func() { require.NoError(t, conn.Close()) }) client := v1pb.NewPlacementClient(conn) stream, err = client.ReportDaprStatus(ctx) if err != nil { return false } err = stream.Send(&v1pb.Host{Id: "app-1", Namespace: "default"}) if err != nil { return false } _, err = stream.Recv() if err != nil { return false } return true }, time.Second*10, time.Millisecond*10) err = stream.Send(&v1pb.Host{ Name: "app-1", Namespace: "default", Port: 1234, Load: 1, Entities: []string{"entity-1", "entity-2"}, Id: "app-1", Pod: "pod-1", }) require.NoError(t, err) assert.EventuallyWithT(t, func(c *assert.CollectT) { o, err := stream.Recv() require.NoError(t, err) assert.Equal(c, "update", o.GetOperation()) if assert.NotNil(c, o.GetTables()) { assert.Len(c, o.GetTables().GetEntries(), 2) assert.Contains(c, o.GetTables().GetEntries(), "entity-1") assert.Contains(c, o.GetTables().GetEntries(), "entity-2") } }, time.Second*20, time.Millisecond*10) }
mikeee/dapr
tests/integration/suite/placement/quorum/insecure.go
GO
mit
4,791
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package quorum import ( "context" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "encoding/json" "fmt" "os" "path/filepath" "strconv" "testing" "time" "github.com/lestrrat-go/jwx/v2/jwa" "github.com/lestrrat-go/jwx/v2/jwk" "github.com/lestrrat-go/jwx/v2/jwt" "github.com/spiffe/go-spiffe/v2/spiffeid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc" v1pb "github.com/dapr/dapr/pkg/proto/placement/v1" "github.com/dapr/dapr/pkg/security" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/exec" "github.com/dapr/dapr/tests/integration/framework/process/placement" "github.com/dapr/dapr/tests/integration/framework/process/ports" "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" "github.com/dapr/kit/ptr" ) func init() { suite.Register(new(jwks)) } // jwks tests placement can find quorum with tls (jwks) enabled. type jwks struct { places []*placement.Placement sentry *sentry.Sentry appTokenFile string } func (j *jwks) Setup(t *testing.T) []framework.Option { jwtPriv, jwtPub := j.genPrivateJWK(t) tokenFiles := make([]string, 3) for i := 0; i < 3; i++ { token := j.signJWT(t, jwtPriv, "spiffe://localhost/ns/default/dapr-placement") tokenFiles[i] = filepath.Join(t.TempDir(), "token-"+strconv.Itoa(i)) require.NoError(t, os.WriteFile(tokenFiles[i], token, 0o600)) } j.appTokenFile = filepath.Join(t.TempDir(), "app-token") require.NoError(t, os.WriteFile(j.appTokenFile, j.signJWT(t, jwtPriv, "spiffe://public/ns/default/app-1"), 0o600), ) jwksConfig := ` kind: Configuration apiVersion: dapr.io/v1alpha1 metadata: name: sentryconfig spec: mtls: enabled: true tokenValidators: - name: jwks options: minRefreshInterval: 2m requestTimeout: 1m source: | {"keys":[` + string(jwtPub) + `]} ` j.sentry = sentry.New(t, sentry.WithConfiguration(jwksConfig)) bundle := j.sentry.CABundle() taFile := filepath.Join(t.TempDir(), "ca.pem") require.NoError(t, os.WriteFile(taFile, bundle.TrustAnchors, 0o600)) fp := ports.Reserve(t, 3) port1, port2, port3 := fp.Port(t), fp.Port(t), fp.Port(t) opts := []placement.Option{ placement.WithInitialCluster(fmt.Sprintf("p1=localhost:%d,p2=localhost:%d,p3=localhost:%d", port1, port2, port3)), placement.WithInitialClusterPorts(port1, port2, port3), placement.WithEnableTLS(true), placement.WithTrustAnchorsFile(taFile), placement.WithSentryAddress(j.sentry.Address()), } j.places = []*placement.Placement{ placement.New(t, append(opts, placement.WithID("p1"), placement.WithExecOptions(exec.WithEnvVars(t, "DAPR_SENTRY_TOKEN_FILE", tokenFiles[0])))...), placement.New(t, append(opts, placement.WithID("p2"), placement.WithExecOptions(exec.WithEnvVars(t, "DAPR_SENTRY_TOKEN_FILE", tokenFiles[1])))...), placement.New(t, append(opts, placement.WithID("p3"), placement.WithExecOptions(exec.WithEnvVars(t, "DAPR_SENTRY_TOKEN_FILE", tokenFiles[2])))...), } return []framework.Option{ framework.WithProcesses(j.sentry, fp, j.places[0], j.places[1], j.places[2]), } } func (j *jwks) Run(t *testing.T, ctx context.Context) { j.sentry.WaitUntilRunning(t, ctx) j.places[0].WaitUntilRunning(t, ctx) j.places[1].WaitUntilRunning(t, ctx) j.places[2].WaitUntilRunning(t, ctx) secProv, err := security.New(ctx, security.Options{ SentryAddress: j.sentry.Address(), ControlPlaneTrustDomain: "localhost", ControlPlaneNamespace: "default", TrustAnchors: j.sentry.CABundle().TrustAnchors, AppID: "app-1", MTLSEnabled: true, SentryTokenFile: ptr.Of(j.appTokenFile), }) require.NoError(t, err) ctx, cancel := context.WithCancel(ctx) errCh := make(chan error, 1) go func() { errCh <- secProv.Run(ctx) }() t.Cleanup(func() { cancel(); require.NoError(t, <-errCh) }) sec, err := secProv.Handler(ctx) require.NoError(t, err) placeID, err := spiffeid.FromSegments(sec.ControlPlaneTrustDomain(), "ns", "default", "dapr-placement") require.NoError(t, err) var stream v1pb.Placement_ReportDaprStatusClient // Try connecting to each placement until one succeeds, // indicating that a leader has been elected i := -1 require.Eventually(t, func() bool { i++ if i >= 3 { i = 0 } host := j.places[i].Address() conn, cerr := grpc.DialContext(ctx, host, grpc.WithBlock(), grpc.WithReturnConnectionError(), sec.GRPCDialOptionMTLS(placeID), ) if cerr != nil { return false } t.Cleanup(func() { require.NoError(t, conn.Close()) }) client := v1pb.NewPlacementClient(conn) stream, err = client.ReportDaprStatus(ctx) if err != nil { return false } err = stream.Send(&v1pb.Host{Id: "app-1"}) if err != nil { return false } _, err = stream.Recv() if err != nil { return false } return true }, time.Second*10, time.Millisecond*10) err = stream.Send(&v1pb.Host{ Name: "app-1", Namespace: "default", Port: 1234, Load: 1, Entities: []string{"entity-1", "entity-2"}, Id: "app-1", Pod: "pod-1", }) require.NoError(t, err) assert.EventuallyWithT(t, func(c *assert.CollectT) { o, err := stream.Recv() require.NoError(t, err) assert.Equal(c, "update", o.GetOperation()) if assert.NotNil(c, o.GetTables()) { assert.Len(c, o.GetTables().GetEntries(), 2) assert.Contains(c, o.GetTables().GetEntries(), "entity-1") assert.Contains(c, o.GetTables().GetEntries(), "entity-2") } }, time.Second*20, time.Millisecond*10) } func (j *jwks) signJWT(t *testing.T, jwkPriv jwk.Key, id string) []byte { t.Helper() now := time.Now() token, err := jwt.NewBuilder(). Audience([]string{"spiffe://localhost/ns/default/dapr-sentry"}). Expiration(now.Add(time.Hour)). IssuedAt(now). Subject(id). Build() require.NoError(t, err) signed, err := jwt.Sign(token, jwt.WithKey(jwa.ES256, jwkPriv)) require.NoError(t, err) return signed } func (j *jwks) genPrivateJWK(t *testing.T) (jwk.Key, []byte) { t.Helper() // Generate a signing key privK, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) require.NoError(t, err) jwtSigningKeyPriv, err := jwk.FromRaw(privK) require.NoError(t, err) jwtSigningKeyPriv.Set("kid", "mykey") jwtSigningKeyPriv.Set("alg", "ES256") jwtSigningKeyPub, err := jwtSigningKeyPriv.PublicKey() require.NoError(t, err) jwtSigningKeyPubJSON, err := json.Marshal(jwtSigningKeyPub) require.NoError(t, err) return jwtSigningKeyPriv, jwtSigningKeyPubJSON }
mikeee/dapr
tests/integration/suite/placement/quorum/jwks.go
GO
mit
7,221
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package quorum import ( "context" "fmt" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc" grpcinsecure "google.golang.org/grpc/credentials/insecure" v1pb "github.com/dapr/dapr/pkg/proto/placement/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/placement" "github.com/dapr/dapr/tests/integration/framework/process/ports" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(notls)) } // notls tests placement can find quorum with tls disabled. type notls struct { places []*placement.Placement } func (n *notls) Setup(t *testing.T) []framework.Option { fp := ports.Reserve(t, 3) port1, port2, port3 := fp.Port(t), fp.Port(t), fp.Port(t) opts := []placement.Option{ placement.WithInitialCluster(fmt.Sprintf("p1=localhost:%d,p2=localhost:%d,p3=localhost:%d", port1, port2, port3)), placement.WithInitialClusterPorts(port1, port2, port3), } n.places = []*placement.Placement{ placement.New(t, append(opts, placement.WithID("p1"))...), placement.New(t, append(opts, placement.WithID("p2"))...), placement.New(t, append(opts, placement.WithID("p3"))...), } return []framework.Option{ framework.WithProcesses(fp, n.places[0], n.places[1], n.places[2]), } } func (n *notls) Run(t *testing.T, ctx context.Context) { n.places[0].WaitUntilRunning(t, ctx) n.places[1].WaitUntilRunning(t, ctx) n.places[2].WaitUntilRunning(t, ctx) var stream v1pb.Placement_ReportDaprStatusClient // Try connecting to each placement until one succeeds, // indicating that a leader has been elected j := -1 require.Eventually(t, func() bool { j++ if j >= 3 { j = 0 } host := n.places[j].Address() conn, err := grpc.DialContext(ctx, host, grpc.WithBlock(), grpc.WithReturnConnectionError(), grpc.WithTransportCredentials(grpcinsecure.NewCredentials()), ) if err != nil { return false } t.Cleanup(func() { require.NoError(t, conn.Close()) }) client := v1pb.NewPlacementClient(conn) stream, err = client.ReportDaprStatus(ctx) if err != nil { return false } err = stream.Send(new(v1pb.Host)) if err != nil { return false } _, err = stream.Recv() if err != nil { return false } return true }, time.Second*10, time.Millisecond*10) err := stream.Send(&v1pb.Host{ Name: "app-1", Port: 1234, Load: 1, Entities: []string{"entity-1", "entity-2"}, Id: "app-1", Pod: "pod-1", }) require.NoError(t, err) assert.EventuallyWithT(t, func(c *assert.CollectT) { o, err := stream.Recv() require.NoError(t, err) assert.Equal(c, "update", o.GetOperation()) if assert.NotNil(c, o.GetTables()) { assert.Len(c, o.GetTables().GetEntries(), 2) assert.Contains(c, o.GetTables().GetEntries(), "entity-1") assert.Contains(c, o.GetTables().GetEntries(), "entity-2") } }, time.Second*20, time.Millisecond*10) }
mikeee/dapr
tests/integration/suite/placement/quorum/notls.go
GO
mit
3,544
/* Copyright 2024 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package vnodes import ( "context" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" placementv1pb "github.com/dapr/dapr/pkg/proto/placement/v1" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/placement" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(vnodes)) } type vnodes struct { place *placement.Placement } func (v *vnodes) Setup(t *testing.T) []framework.Option { v.place = placement.New(t, placement.WithMetadataEnabled(true), ) return []framework.Option{ framework.WithProcesses(v.place), } } func (v *vnodes) Run(t *testing.T, ctx context.Context) { v.place.WaitUntilRunning(t, ctx) t.Run("register host without vnodes metadata (simulating daprd <1.13)", func(t *testing.T) { // Register the host, with API level 10 (pre v1.13) msg := &placementv1pb.Host{ Name: "myapp", Port: 1234, Entities: []string{"someactor"}, Id: "myapp1", ApiLevel: uint32(10), } // The host won't send the "dapr-accept-vnodes" metadata, simulating an older daprd version placementMessageCh := v.place.RegisterHostWithMetadata(t, ctx, msg, nil) require.EventuallyWithT(t, func(t *assert.CollectT) { select { case <-ctx.Done(): return case placementTables := <-placementMessageCh: if ctx.Err() != nil { return } assert.Len(t, placementTables.GetEntries(), 1) // Check that the placement service sends the vnodes assert.Len(t, placementTables.GetEntries()["someactor"].GetHosts(), int(placementTables.GetReplicationFactor())) assert.Len(t, placementTables.GetEntries()["someactor"].GetSortedSet(), int(placementTables.GetReplicationFactor())) } }, 10*time.Second, 10*time.Millisecond) }) t.Run("register host with vnodes metadata (simulating daprd 1.13+)", func(t *testing.T) { // Register the host, with API level 10 (pre v1.13) msg := &placementv1pb.Host{ Name: "myapp", Port: 1234, Entities: []string{"someactor"}, Id: "myapp1", ApiLevel: uint32(10), } // The host will send the "dapr-accept-vnodes" metadata, simulating an older daprd version placementMessageCh := v.place.RegisterHost(t, ctx, msg) require.EventuallyWithT(t, func(t *assert.CollectT) { select { case <-ctx.Done(): return case placementTables := <-placementMessageCh: assert.Len(t, placementTables.GetEntries(), 1) // Check that the placement service doesn't send the vnodes assert.Empty(t, placementTables.GetEntries()["someactor"].GetHosts()) assert.Empty(t, placementTables.GetEntries()["someactor"].GetSortedSet()) } }, 10*time.Second, 10*time.Millisecond) }) t.Run("register heterogeneous hosts (simulating daprd pre and post 1.13)", func(t *testing.T) { const ( level1 = 10 level2 = 20 ) msg1 := &placementv1pb.Host{ Name: "myapp1", Port: 1111, Entities: []string{"someactor1"}, Id: "myapp1", ApiLevel: uint32(level1), } msg2 := &placementv1pb.Host{ Name: "myapp2", Port: 2222, Entities: []string{"someactor2"}, Id: "myapp2", ApiLevel: uint32(level2), } // First host won't send the "dapr-accept-vnodes" metadata, simulating daprd pre 1.13 placementMessageCh1 := v.place.RegisterHostWithMetadata(t, ctx, msg1, nil) // Second host will send the "dapr-accept-vnodes" metadata, simulating daprd 1.13+ placementMessageCh2 := v.place.RegisterHost(t, ctx, msg2) require.EventuallyWithT(t, func(t *assert.CollectT) { select { case <-ctx.Done(): return case placementTables := <-placementMessageCh1: assert.Len(t, placementTables.GetEntries(), 2) // Check that the placement service sends the vnodes assert.Len(t, placementTables.GetEntries()["someactor1"].GetHosts(), int(placementTables.GetReplicationFactor())) assert.Len(t, placementTables.GetEntries()["someactor1"].GetSortedSet(), int(placementTables.GetReplicationFactor())) assert.Len(t, placementTables.GetEntries()["someactor2"].GetHosts(), int(placementTables.GetReplicationFactor())) assert.Len(t, placementTables.GetEntries()["someactor2"].GetSortedSet(), int(placementTables.GetReplicationFactor())) } }, 10*time.Second, 500*time.Millisecond) require.EventuallyWithT(t, func(t *assert.CollectT) { select { case <-ctx.Done(): return case placementTables := <-placementMessageCh2: if ctx.Err() != nil { return } assert.Len(t, placementTables.GetEntries(), 2) // Check that the placement service doesn't send the vnodes to this (1.13+) host, // even though there are hosts with lower dapr versions in the cluster assert.Empty(t, placementTables.GetEntries()["someactor1"].GetHosts()) assert.Empty(t, placementTables.GetEntries()["someactor1"].GetSortedSet()) assert.Empty(t, placementTables.GetEntries()["someactor2"].GetHosts()) assert.Empty(t, placementTables.GetEntries()["someactor2"].GetSortedSet()) } }, 10*time.Second, 2000*time.Millisecond) }) }
mikeee/dapr
tests/integration/suite/placement/vnodes/vnodes.go
GO
mit
5,662
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ports import ( "context" "fmt" "net" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/dapr/dapr/tests/integration/framework" procdaprd "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(daprd)) } // daprd tests that the ports are available when daprd is running. type daprd struct { proc *procdaprd.Daprd } func (d *daprd) Setup(t *testing.T) []framework.Option { d.proc = procdaprd.New(t) return []framework.Option{ framework.WithProcesses(d.proc), } } func (d *daprd) Run(t *testing.T, ctx context.Context) { dialer := net.Dialer{Timeout: time.Second * 5} for name, port := range map[string]int{ "app": d.proc.AppPort(), "grpc": d.proc.GRPCPort(), "http": d.proc.HTTPPort(), "metrics": d.proc.MetricsPort(), "internal-grpc": d.proc.InternalGRPCPort(), "public": d.proc.PublicPort(), } { assert.Eventuallyf(t, func() bool { conn, err := dialer.DialContext(ctx, "tcp", fmt.Sprintf("localhost:%d", port)) if err != nil { return false } require.NoError(t, conn.Close()) return true }, time.Second*5, 10*time.Millisecond, "port %s (:%d) was not available in time", name, port) } }
mikeee/dapr
tests/integration/suite/ports/daprd.go
GO
mit
1,902
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ports import ( "context" "fmt" "net" "testing" "time" "github.com/stretchr/testify/assert" "github.com/dapr/dapr/tests/integration/framework" procinjector "github.com/dapr/dapr/tests/integration/framework/process/injector" procsentry "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(injector)) } type injector struct { injector *procinjector.Injector } func (i *injector) Setup(t *testing.T) []framework.Option { sentry := procsentry.New(t, procsentry.WithNamespace("dapr-system"), procsentry.WithTrustDomain("integration.test.dapr.io"), ) i.injector = procinjector.New(t, procinjector.WithNamespace("dapr-system"), procinjector.WithSentry(sentry), ) return []framework.Option{ framework.WithProcesses(sentry, i.injector), } } func (i *injector) Run(t *testing.T, ctx context.Context) { dialer := net.Dialer{Timeout: time.Second} for name, port := range map[string]int{ "port": i.injector.Port(), "metrics": i.injector.MetricsPort(), "healthz": i.injector.HealthzPort(), } { assert.EventuallyWithT(t, func(c *assert.CollectT) { conn, err := dialer.DialContext(ctx, "tcp", fmt.Sprintf("localhost:%d", port)) //nolint:testifylint _ = assert.NoError(c, err) && assert.NoError(c, conn.Close()) }, time.Second*10, 100*time.Millisecond, "port %s (:%d) was not available in time", name, port) } }
mikeee/dapr
tests/integration/suite/ports/injector.go
GO
mit
2,021
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ports import ( "context" "fmt" "net" "testing" "time" "github.com/spiffe/go-spiffe/v2/spiffeid" "github.com/stretchr/testify/assert" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/exec" "github.com/dapr/dapr/tests/integration/framework/process/kubernetes" procoperator "github.com/dapr/dapr/tests/integration/framework/process/operator" procsentry "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(operator)) } // operator tests that the ports are available when operator is running. type operator struct { proc *procoperator.Operator } func (o *operator) Setup(t *testing.T) []framework.Option { sentry := procsentry.New(t, procsentry.WithTrustDomain("integration.test.dapr.io"), procsentry.WithExecOptions(exec.WithEnvVars(t, "NAMESPACE", "dapr-system")), ) kubeAPI := kubernetes.New(t, kubernetes.WithBaseOperatorAPI(t, spiffeid.RequireTrustDomainFromString("integration.test.dapr.io"), "dapr-system", sentry.Port(), )) o.proc = procoperator.New(t, procoperator.WithNamespace("dapr-system"), procoperator.WithKubeconfigPath(kubeAPI.KubeconfigPath(t)), procoperator.WithTrustAnchorsFile(sentry.TrustAnchorsFile(t)), ) return []framework.Option{ framework.WithProcesses(kubeAPI, sentry, o.proc), } } func (o *operator) Run(t *testing.T, ctx context.Context) { dialer := net.Dialer{Timeout: time.Second} for name, port := range map[string]int{ "port": o.proc.Port(), "metrics": o.proc.MetricsPort(), "healthz": o.proc.HealthzPort(), } { assert.EventuallyWithT(t, func(c *assert.CollectT) { conn, err := dialer.DialContext(ctx, "tcp", fmt.Sprintf("localhost:%d", port)) //nolint:testifylint _ = assert.NoError(c, err) && assert.NoError(c, conn.Close()) }, time.Second*10, 10*time.Millisecond, "port %s (:%d) was not available in time", name, port) } // Shutting the operator down too fast will cause the operator to exit error // as the cache has not had time to sync. Wait until healthz before exiting. o.proc.WaitUntilRunning(t, ctx) }
mikeee/dapr
tests/integration/suite/ports/operator.go
GO
mit
2,747
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ports import ( "context" "fmt" "net" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/dapr/dapr/tests/integration/framework" procplace "github.com/dapr/dapr/tests/integration/framework/process/placement" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(placement)) } // placement tests that the ports are available when daprd is running. type placement struct { proc *procplace.Placement } func (p *placement) Setup(t *testing.T) []framework.Option { p.proc = procplace.New(t) return []framework.Option{ framework.WithProcesses(p.proc), } } func (p *placement) Run(t *testing.T, ctx context.Context) { dialer := net.Dialer{Timeout: time.Second * 5} for name, port := range map[string]int{ "port": p.proc.Port(), "metrics": p.proc.MetricsPort(), "healthz": p.proc.HealthzPort(), "initialCluster": p.proc.InitialClusterPorts()[0], } { assert.Eventuallyf(t, func() bool { conn, err := dialer.DialContext(ctx, "tcp", fmt.Sprintf("127.0.0.1:%d", port)) if err != nil { return false } require.NoError(t, conn.Close()) return true }, time.Second*5, 10*time.Millisecond, "port %s (:%d) was not available in time", name, port) } }
mikeee/dapr
tests/integration/suite/ports/placement.go
GO
mit
1,862
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ports import ( "context" "fmt" "net" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/dapr/dapr/tests/integration/framework" procsentry "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(sentry)) } // sentry tests that the ports are available when sentry is running. type sentry struct { proc *procsentry.Sentry } func (s *sentry) Setup(t *testing.T) []framework.Option { s.proc = procsentry.New(t) return []framework.Option{ framework.WithProcesses(s.proc), } } func (s *sentry) Run(t *testing.T, ctx context.Context) { dialer := net.Dialer{Timeout: time.Second * 5} for name, port := range map[string]int{ "port": s.proc.Port(), "healthz": s.proc.HealthzPort(), "metrics": s.proc.MetricsPort(), } { assert.Eventuallyf(t, func() bool { conn, err := dialer.DialContext(ctx, "tcp", fmt.Sprintf("localhost:%d", port)) if err != nil { return false } require.NoError(t, conn.Close()) return true }, time.Second*5, 10*time.Millisecond, "port %s (:%d) was not available in time", name, port) } }
mikeee/dapr
tests/integration/suite/ports/sentry.go
GO
mit
1,771
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package metrics import ( "bytes" "context" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "fmt" "io" "net/http" "strconv" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/dapr/dapr/pkg/sentry/server/ca" "github.com/dapr/dapr/tests/integration/framework" procsentry "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/framework/util" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(expiry)) } // expiry tests the certificate expiry metric. type expiry struct { notGiven *procsentry.Sentry given *procsentry.Sentry } func (e *expiry) Setup(t *testing.T) []framework.Option { rootKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) require.NoError(t, err) onemonth := time.Hour * 24 * 30 bundle, err := ca.GenerateBundle(rootKey, "integration.test.dapr.io", time.Second*5, &onemonth) require.NoError(t, err) e.notGiven = procsentry.New(t, procsentry.WithWriteTrustBundle(false)) e.given = procsentry.New(t, procsentry.WithCABundle(bundle)) return []framework.Option{ framework.WithProcesses(e.notGiven, e.given), } } func (e *expiry) Run(t *testing.T, ctx context.Context) { e.notGiven.WaitUntilRunning(t, ctx) e.given.WaitUntilRunning(t, ctx) client := util.HTTPClient(t) testExpiry := func(proc *procsentry.Sentry, expTime time.Time) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://localhost:%d/metrics", proc.MetricsPort()), nil) require.NoError(t, err) resp, err := client.Do(req) require.NoError(t, err) respBody, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) for _, line := range bytes.Split(respBody, []byte("\n")) { if len(line) == 0 || line[0] == '#' { continue } split := bytes.Split(line, []byte(" ")) if len(split) != 2 { continue } if string(split[0]) != "dapr_sentry_issuercert_expiry_timestamp" { continue } timestamp, err := strconv.ParseFloat(string(split[1]), 64) require.NoError(t, err) tsTime := time.Unix(int64(timestamp), 0) assert.InDelta(t, expTime.Unix(), tsTime.Unix(), 20, "expected expiry time to be within 20 seconds of expected") return } assert.Fail(t, "metric not found") } // Expect the expiry to be 1 year from now for sentry self generated certs. testExpiry(e.notGiven, time.Now().Add(time.Hour*24*365)) // Expect the expiry to be 1 month from now for sentry certs given by the user. testExpiry(e.given, time.Now().Add(time.Hour*24*30)) }
mikeee/dapr
tests/integration/suite/sentry/metrics/expiry.go
GO
mit
3,194
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh. See the License for the specific language governing permissions and limitations under the License. */ package sentry import ( _ "github.com/dapr/dapr/tests/integration/suite/sentry/metrics" _ "github.com/dapr/dapr/tests/integration/suite/sentry/validator" )
mikeee/dapr
tests/integration/suite/sentry/sentry.go
GO
mit
720
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package insecure import ( "context" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/x509" "encoding/pem" "fmt" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" sentrypbv1 "github.com/dapr/dapr/pkg/proto/sentry/v1" "github.com/dapr/dapr/pkg/sentry/server/ca" "github.com/dapr/dapr/tests/integration/framework" procsentry "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(insecure)) } // insecure tests Sentry with the insecure validator. type insecure struct { proc *procsentry.Sentry } func (m *insecure) Setup(t *testing.T) []framework.Option { m.proc = procsentry.New(t) return []framework.Option{ framework.WithProcesses(m.proc), } } func (m *insecure) Run(t *testing.T, parentCtx context.Context) { const ( defaultAppID = "myapp" defaultNamespace = "default" ) defaultAppSPIFFEID := fmt.Sprintf("spiffe://public/ns/%s/%s", defaultNamespace, defaultAppID) m.proc.WaitUntilRunning(t, parentCtx) // Get a CSR for the app "myapp" pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) require.NoError(t, err) csrDer, err := x509.CreateCertificateRequest(rand.Reader, new(x509.CertificateRequest), pk) require.NoError(t, err) defaultAppCSR := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrDer}) // Connect to Sentry conn := m.proc.DialGRPC(t, parentCtx, "spiffe://localhost/ns/default/dapr-sentry") client := sentrypbv1.NewCAClient(conn) t.Run("fails when passing an invalid validator", func(t *testing.T) { ctx, cancel := context.WithTimeout(parentCtx, 10*time.Second) defer cancel() _, err := client.SignCertificate(ctx, &sentrypbv1.SignCertificateRequest{ Id: defaultAppID, Namespace: defaultNamespace, TokenValidator: sentrypbv1.SignCertificateRequest_TokenValidator(-1), // -1 is an invalid enum value }) require.Error(t, err) grpcStatus, ok := status.FromError(err) require.True(t, ok) require.Equal(t, codes.InvalidArgument, grpcStatus.Code()) require.Contains(t, grpcStatus.Message(), "not enabled") }) t.Run("issue a certificate with insecure validator", func(t *testing.T) { ctx, cancel := context.WithTimeout(parentCtx, 10*time.Second) defer cancel() res, err := client.SignCertificate(ctx, &sentrypbv1.SignCertificateRequest{ Id: defaultAppID, Namespace: defaultNamespace, CertificateSigningRequest: defaultAppCSR, TokenValidator: sentrypbv1.SignCertificateRequest_INSECURE, }) require.NoError(t, err) require.NotEmpty(t, res.GetWorkloadCertificate()) validateCertificateResponse(t, res, m.proc.CABundle(), defaultAppSPIFFEID) }) t.Run("insecure validator is the default", func(t *testing.T) { ctx, cancel := context.WithTimeout(parentCtx, 10*time.Second) defer cancel() res, err := client.SignCertificate(ctx, &sentrypbv1.SignCertificateRequest{ Id: defaultAppID, Namespace: defaultNamespace, CertificateSigningRequest: defaultAppCSR, // TokenValidator: sentrypbv1.SignCertificateRequest_INSECURE, }) require.NoError(t, err) require.NotEmpty(t, res.GetWorkloadCertificate()) validateCertificateResponse(t, res, m.proc.CABundle(), defaultAppSPIFFEID) }) t.Run("fails with missing CSR", func(t *testing.T) { ctx, cancel := context.WithTimeout(parentCtx, 10*time.Second) defer cancel() _, err := client.SignCertificate(ctx, &sentrypbv1.SignCertificateRequest{ Id: defaultAppID, Namespace: defaultNamespace, // CertificateSigningRequest: defaultAppCSR, TokenValidator: sentrypbv1.SignCertificateRequest_INSECURE, }) require.Error(t, err) grpcStatus, ok := status.FromError(err) require.True(t, ok) require.Equal(t, codes.PermissionDenied, grpcStatus.Code()) require.Contains(t, grpcStatus.Message(), "CSR is required") }) t.Run("fails with missing namespace", func(t *testing.T) { ctx, cancel := context.WithTimeout(parentCtx, 10*time.Second) defer cancel() _, err := client.SignCertificate(ctx, &sentrypbv1.SignCertificateRequest{ Id: defaultAppID, // Namespace: defaultNamespace, CertificateSigningRequest: defaultAppCSR, TokenValidator: sentrypbv1.SignCertificateRequest_INSECURE, }) require.Error(t, err) grpcStatus, ok := status.FromError(err) require.True(t, ok) require.Equal(t, codes.PermissionDenied, grpcStatus.Code()) require.Contains(t, grpcStatus.Message(), "namespace is required") }) t.Run("fails with invalid CSR", func(t *testing.T) { ctx, cancel := context.WithTimeout(parentCtx, 10*time.Second) defer cancel() _, err := client.SignCertificate(ctx, &sentrypbv1.SignCertificateRequest{ Id: defaultAppID, Namespace: defaultNamespace, CertificateSigningRequest: []byte("-----BEGIN PRIVATE KEY-----\nMC4CAQBLAHBLAH\n-----END PRIVATE KEY-----"), TokenValidator: sentrypbv1.SignCertificateRequest_INSECURE, }) require.Error(t, err) grpcStatus, ok := status.FromError(err) require.True(t, ok) require.Equal(t, codes.InvalidArgument, grpcStatus.Code()) require.Contains(t, grpcStatus.Message(), "invalid certificate signing request") }) } func validateCertificateResponse(t *testing.T, res *sentrypbv1.SignCertificateResponse, sentryBundle ca.Bundle, expectSPIFFEID string) { t.Helper() require.NotEmpty(t, res.GetWorkloadCertificate()) rest := res.GetWorkloadCertificate() // First block should contain the issued workload certificate var block *pem.Block block, rest = pem.Decode(rest) require.NotEmpty(t, block) require.Equal(t, "CERTIFICATE", block.Type) cert, err := x509.ParseCertificate(block.Bytes) require.NoError(t, err) certURIs := make([]string, len(cert.URIs)) for i, v := range cert.URIs { certURIs[i] = v.String() } assert.Equal(t, []string{expectSPIFFEID}, certURIs) assert.Empty(t, cert.DNSNames) assert.Contains(t, cert.ExtKeyUsage, x509.ExtKeyUsageServerAuth) assert.Contains(t, cert.ExtKeyUsage, x509.ExtKeyUsageClientAuth) // Second block should contain the Sentry CA certificate block, rest = pem.Decode(rest) require.Empty(t, rest) require.NotEmpty(t, block) require.Equal(t, "CERTIFICATE", block.Type) cert, err = x509.ParseCertificate(block.Bytes) require.NoError(t, err) assert.Empty(t, cert.DNSNames) }
mikeee/dapr
tests/integration/suite/sentry/validator/insecure/insecure.go
GO
mit
7,133
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package jwks import ( "encoding/json" "fmt" "net/http" "strconv" "testing" "github.com/stretchr/testify/require" "github.com/dapr/dapr/tests/integration/framework" prochttp "github.com/dapr/dapr/tests/integration/framework/process/http" procsentry "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(httpsCA)) } // httpsCA tests Sentry with the JWKS validator fetching from a HTTPS URL with a custom CA type httpsCA struct { shared } func (m *httpsCA) Setup(t *testing.T) []framework.Option { // Generate a CA and key pair for the JWKS server caCert, caKey := generateCACertificate(t) serverCert, serverKey := generateTLSCertificates(t, caCert, caKey, "localhost") jwksServer := prochttp.New(t, prochttp.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `{"keys":[`+string(jwtSigningKeyPubJSON)+`]}`) })), prochttp.WithTLS(t, serverCert, serverKey), ) caCertJSON, err := json.Marshal(string(caCert)) require.NoError(t, err) jwksConfig := ` kind: Configuration apiVersion: dapr.io/v1alpha1 metadata: name: sentryconfig spec: mtls: enabled: true tokenValidators: - name: jwks options: minRefreshInterval: 2m requestTimeout: 1m source: "https://localhost:` + strconv.Itoa(jwksServer.Port()) + `/" caCertificate: ` + string(caCertJSON) + ` ` m.proc = procsentry.New(t, procsentry.WithConfiguration(jwksConfig)) return []framework.Option{ framework.WithProcesses(jwksServer, m.proc), } }
mikeee/dapr
tests/integration/suite/sentry/validator/jwks/https-ca.go
GO
mit
2,191
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package jwks import ( "testing" "github.com/dapr/dapr/tests/integration/framework" procsentry "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(jwks)) } // jwks tests Sentry with the JWKS validator. type jwks struct { shared } func (m *jwks) Setup(t *testing.T) []framework.Option { jwksConfig := ` kind: Configuration apiVersion: dapr.io/v1alpha1 metadata: name: sentryconfig spec: mtls: enabled: true tokenValidators: - name: jwks options: minRefreshInterval: 2m requestTimeout: 1m source: | {"keys":[` + string(jwtSigningKeyPubJSON) + `]} ` m.proc = procsentry.New(t, procsentry.WithConfiguration(jwksConfig)) return []framework.Option{ framework.WithProcesses(m.proc), } }
mikeee/dapr
tests/integration/suite/sentry/validator/jwks/jwks.go
GO
mit
1,423
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package jwks import ( "context" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "fmt" "testing" "time" "github.com/lestrrat-go/jwx/v2/jwt" "github.com/stretchr/testify/require" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" sentrypbv1 "github.com/dapr/dapr/pkg/proto/sentry/v1" procsentry "github.com/dapr/dapr/tests/integration/framework/process/sentry" ) // Base class for the JWKS tests type shared struct { proc *procsentry.Sentry } func (s shared) Run(t *testing.T, parentCtx context.Context) { const ( defaultAppID = "myapp" defaultNamespace = "default" ) defaultAppSPIFFEID := fmt.Sprintf("spiffe://public/ns/%s/%s", defaultNamespace, defaultAppID) s.proc.WaitUntilRunning(t, parentCtx) // Generate a private privKey that we'll need for tests privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) require.NoError(t, err, "failed to generate private key") // Get a CSR for the app "myapp" defaultAppCSR, err := generateCSR(defaultAppID, privKey) require.NoError(t, err) // Connect to Sentry conn := s.proc.DialGRPC(t, parentCtx, "spiffe://localhost/ns/default/dapr-sentry") client := sentrypbv1.NewCAClient(conn) t.Run("fails when passing an invalid validator", func(t *testing.T) { ctx, cancel := context.WithTimeout(parentCtx, 10*time.Second) defer cancel() _, err = client.SignCertificate(ctx, &sentrypbv1.SignCertificateRequest{ Id: defaultAppID, Namespace: defaultNamespace, TokenValidator: sentrypbv1.SignCertificateRequest_TokenValidator(-1), // -1 is an invalid enum value }) require.Error(t, err) grpcStatus, ok := status.FromError(err) require.True(t, ok) require.Equal(t, codes.InvalidArgument, grpcStatus.Code()) require.Contains(t, grpcStatus.Message(), "not enabled") }) t.Run("fails when passing the insecure validator", func(t *testing.T) { ctx, cancel := context.WithTimeout(parentCtx, 10*time.Second) defer cancel() _, err = client.SignCertificate(ctx, &sentrypbv1.SignCertificateRequest{ Id: defaultAppID, Namespace: defaultNamespace, TokenValidator: sentrypbv1.SignCertificateRequest_INSECURE, }) require.Error(t, err) grpcStatus, ok := status.FromError(err) require.True(t, ok) require.Equal(t, codes.InvalidArgument, grpcStatus.Code()) require.Contains(t, grpcStatus.Message(), "not enabled") }) t.Run("fails when no validator is passed", func(t *testing.T) { ctx, cancel := context.WithTimeout(parentCtx, 10*time.Second) defer cancel() _, err = client.SignCertificate(ctx, &sentrypbv1.SignCertificateRequest{ Id: defaultAppID, Namespace: defaultNamespace, }) require.Error(t, err) grpcStatus, ok := status.FromError(err) require.True(t, ok) require.Equal(t, codes.InvalidArgument, grpcStatus.Code()) require.Contains(t, grpcStatus.Message(), "a validator name must be specified in this environment") }) t.Run("issue a certificate with JWKS validator", func(t *testing.T) { ctx, cancel := context.WithTimeout(parentCtx, 10*time.Second) defer cancel() var token []byte token, err = signJWT(generateJWT(defaultAppSPIFFEID)) require.NoError(t, err) var res *sentrypbv1.SignCertificateResponse res, err = client.SignCertificate(ctx, &sentrypbv1.SignCertificateRequest{ Id: defaultAppID, Namespace: defaultNamespace, CertificateSigningRequest: defaultAppCSR, TokenValidator: sentrypbv1.SignCertificateRequest_JWKS, Token: string(token), }) require.NoError(t, err) require.NotEmpty(t, res.GetWorkloadCertificate()) validateCertificateResponse(t, res, s.proc.CABundle(), defaultAppSPIFFEID) }) testWithTokenError := func(fn func(builder *jwt.Builder), assertErr func(t *testing.T, grpcStatus *status.Status)) func(t *testing.T) { return func(t *testing.T) { ctx, cancel := context.WithTimeout(parentCtx, 10*time.Second) defer cancel() var token []byte builder := generateJWT(defaultAppSPIFFEID) fn(builder) token, err = signJWT(builder) require.NoError(t, err) _, err = client.SignCertificate(ctx, &sentrypbv1.SignCertificateRequest{ Id: defaultAppID, Namespace: defaultNamespace, CertificateSigningRequest: defaultAppCSR, TokenValidator: sentrypbv1.SignCertificateRequest_JWKS, Token: string(token), }) require.Error(t, err) grpcStatus, ok := status.FromError(err) require.True(t, ok) assertErr(t, grpcStatus) } } t.Run("fails when token has invalid audience", testWithTokenError( func(builder *jwt.Builder) { builder.Audience([]string{"invalid"}) }, func(t *testing.T, grpcStatus *status.Status) { require.Equal(t, codes.PermissionDenied, grpcStatus.Code()) require.Contains(t, grpcStatus.Message(), "token validation failed") require.Contains(t, grpcStatus.Message(), `"aud"`) }, )) t.Run("fails when token has invalid subject", testWithTokenError( func(builder *jwt.Builder) { builder.Subject("invalid") }, func(t *testing.T, grpcStatus *status.Status) { require.Equal(t, codes.PermissionDenied, grpcStatus.Code()) require.Contains(t, grpcStatus.Message(), "token validation failed") require.Contains(t, grpcStatus.Message(), `"sub"`) }, )) t.Run("fails when token is expired", testWithTokenError( func(builder *jwt.Builder) { builder.Expiration(time.Now().Add(-1 * time.Hour)) }, func(t *testing.T, grpcStatus *status.Status) { require.Equal(t, codes.PermissionDenied, grpcStatus.Code()) require.Contains(t, grpcStatus.Message(), "token validation failed") require.Contains(t, grpcStatus.Message(), `"exp"`) }, )) t.Run("fails when token is not yet valid", testWithTokenError( func(builder *jwt.Builder) { builder.NotBefore(time.Now().Add(1 * time.Hour)) }, func(t *testing.T, grpcStatus *status.Status) { require.Equal(t, codes.PermissionDenied, grpcStatus.Code()) require.Contains(t, grpcStatus.Message(), "token validation failed") require.Contains(t, grpcStatus.Message(), `"nbf"`) }, )) t.Run("fails with token signed by wrong key", func(t *testing.T) { ctx, cancel := context.WithTimeout(parentCtx, 10*time.Second) defer cancel() //nolint:gosec const token = `eyJhbGciOiJSUzI1NiIsImtpZCI6Im15a2V5IiwidHlwIjoiSldUIn0.eyJhdWQiOlsic3BpZmZlOi8vbG9jYWxob3N0L25zL2RlZmF1bHQvZGFwci1zZW50cnkiXSwiZXhwIjoxOTg5MzEwMjY1LCJpYXQiOjE2ODkzMDY2NjUsInN1YiI6InNwaWZmZTovL3B1YmxpYy9ucy9kZWZhdWx0L215YXBwIn0.JZ5fIss3IWjdvOoUTGyTgIsXqfwj7GClno1kgTDd5KKKY4Qwe16CMM4fk1sDIkm09FCD8sTGJzx3MEb9Ls3blsuu3VSNjTxJZrGs3M9ZAFlaS7OGod-8DYMnF-dfQzY-li7VvXIZT3h92DKdOTqVpNgETGZi_7Qjdkkpz8elkK957VVZXz1q8wAW4tOD8Qe6nGnys2q-ksfC0zR39YSVAxM2hGUklxBOMNhqocBGVmYqwJC31NwKwjLy-Ryorcjv4-DCLgKpvQd-MFJYrJU7ztCdBiIBR51btzRHVbtlx9CeESwcC8pNBzDXABOWhQ4L4Prt4qA3hBLCxPvsE-vgjA` _, err = client.SignCertificate(ctx, &sentrypbv1.SignCertificateRequest{ Id: defaultAppID, Namespace: defaultNamespace, CertificateSigningRequest: defaultAppCSR, TokenValidator: sentrypbv1.SignCertificateRequest_JWKS, Token: token, }) require.Error(t, err) grpcStatus, ok := status.FromError(err) require.True(t, ok) require.Equal(t, codes.PermissionDenied, grpcStatus.Code()) require.Contains(t, grpcStatus.Message(), "token validation failed") require.Contains(t, grpcStatus.Message(), `could not verify message`) }) }
mikeee/dapr
tests/integration/suite/sentry/validator/jwks/shared.go
GO
mit
8,105
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package jwks import ( "crypto" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/x509" "crypto/x509/pkix" "encoding/json" "encoding/pem" "fmt" "log" "math/big" "testing" "time" "github.com/lestrrat-go/jwx/v2/jwa" "github.com/lestrrat-go/jwx/v2/jwk" "github.com/lestrrat-go/jwx/v2/jwt" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" sentrypbv1 "github.com/dapr/dapr/pkg/proto/sentry/v1" "github.com/dapr/dapr/pkg/sentry/server/ca" ) const ( // Trust domain for Sentry sentryTrustDomain = "localhost" // Namespace for sentry sentryNamespace = "default" ) // Keys used to sign and verify JWTs var ( jwtSigningKeyPriv jwk.Key jwtSigningKeyPubJSON []byte ) func init() { // Generate a signing key privK, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { log.Fatalf("failed to generate private key: %v", err) } jwtSigningKeyPriv, err = jwk.FromRaw(privK) if err != nil { log.Fatalf("failed to import private key as JWK: %v", err) } jwtSigningKeyPriv.Set("kid", "mykey") jwtSigningKeyPriv.Set("alg", "ES256") jwtSigningKeyPub, err := jwtSigningKeyPriv.PublicKey() if err != nil { log.Fatalf("failed to get public key from JWK: %v", err) } jwtSigningKeyPubJSON, err = json.Marshal(jwtSigningKeyPub) if err != nil { log.Fatalf("failed to marshal public key from JWK: %v", err) } } // Generate a CSR given a private key. func generateCSR(id string, privKey crypto.PrivateKey) ([]byte, error) { csr := x509.CertificateRequest{ Subject: pkix.Name{CommonName: id}, DNSNames: []string{id}, } csrDer, err := x509.CreateCertificateRequest(rand.Reader, &csr, privKey) if err != nil { return nil, fmt.Errorf("failed to create sidecar csr: %w", err) } csrPem := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrDer}) return csrPem, nil } func generateJWT(sub string) *jwt.Builder { now := time.Now() return jwt.NewBuilder(). Audience([]string{fmt.Sprintf("spiffe://%s/ns/%s/dapr-sentry", sentryTrustDomain, sentryNamespace)}). Expiration(now.Add(time.Hour)). IssuedAt(now). Subject(sub) } func signJWT(builder *jwt.Builder) ([]byte, error) { token, err := builder.Build() if err != nil { return nil, err } return jwt.Sign(token, jwt.WithKey(jwa.ES256, jwtSigningKeyPriv)) } func validateCertificateResponse(t *testing.T, res *sentrypbv1.SignCertificateResponse, sentryBundle ca.Bundle, expectSPIFFEID string) { t.Helper() require.NotEmpty(t, res.GetWorkloadCertificate()) rest := res.GetWorkloadCertificate() // First block should contain the issued workload certificate { var block *pem.Block block, rest = pem.Decode(rest) require.NotEmpty(t, block) require.Equal(t, "CERTIFICATE", block.Type) cert, err := x509.ParseCertificate(block.Bytes) require.NoError(t, err) certURIs := make([]string, len(cert.URIs)) for i, v := range cert.URIs { certURIs[i] = v.String() } assert.Equal(t, []string{expectSPIFFEID}, certURIs) assert.Empty(t, cert.DNSNames) assert.Contains(t, cert.ExtKeyUsage, x509.ExtKeyUsageServerAuth) assert.Contains(t, cert.ExtKeyUsage, x509.ExtKeyUsageClientAuth) } // Second block should contain the Sentry CA certificate { var block *pem.Block block, rest = pem.Decode(rest) require.Empty(t, rest) require.NotEmpty(t, block) require.Equal(t, "CERTIFICATE", block.Type) cert, err := x509.ParseCertificate(block.Bytes) require.NoError(t, err) assert.Empty(t, cert.DNSNames) } } func generateCACertificate(t *testing.T) (caCert []byte, caKey []byte) { // Generate a private key for the CA caPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) require.NoError(t, err) // Create a self-signed CA certificate caTemplate := &x509.Certificate{ SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "CA"}, NotBefore: time.Now().Add(-1 * time.Hour), NotAfter: time.Now().Add(24 * time.Hour), KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true, IsCA: true, } caCertificateDER, err := x509.CreateCertificate(rand.Reader, caTemplate, caTemplate, caPrivateKey.Public(), caPrivateKey) require.NoError(t, err) caCert = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caCertificateDER}) caPrivateKeyDER, err := x509.MarshalPKCS8PrivateKey(caPrivateKey) require.NoError(t, err) caKey = pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: caPrivateKeyDER}) return caCert, caKey } func generateTLSCertificates(t *testing.T, caCert []byte, caKey []byte, dnsName string) (cert []byte, key []byte) { // Load the CA certificate and key caCertBlock, _ := pem.Decode(caCert) caCertificate, err := x509.ParseCertificate(caCertBlock.Bytes) require.NoError(t, err) caKeyBlock, _ := pem.Decode(caKey) caPrivateKey, err := x509.ParsePKCS8PrivateKey(caKeyBlock.Bytes) require.NoError(t, err) // Generate a private key for the new cert privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) require.NoError(t, err) // Create a certificate certData := &x509.Certificate{ SerialNumber: big.NewInt(10), Subject: pkix.Name{Organization: []string{"localhost"}}, NotBefore: time.Now().Add(-1 * time.Hour), NotAfter: time.Now().Add(24 * time.Hour), DNSNames: []string{dnsName}, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, KeyUsage: x509.KeyUsageDigitalSignature, } certDER, err := x509.CreateCertificate(rand.Reader, certData, caCertificate, privKey.Public(), caPrivateKey) require.NoError(t, err) cert = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER}) require.NoError(t, err) keyDER, err := x509.MarshalPKCS8PrivateKey(privKey) require.NoError(t, err) key = pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER}) return cert, key }
mikeee/dapr
tests/integration/suite/sentry/validator/jwks/utils.go
GO
mit
6,614
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package kubernetes import ( "encoding/json" "fmt" "net/http" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" authapi "k8s.io/api/authentication/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" configapi "github.com/dapr/dapr/pkg/apis/configuration/v1alpha1" "github.com/dapr/dapr/pkg/sentry/server/ca" prockube "github.com/dapr/dapr/tests/integration/framework/process/kubernetes" ) type kubeAPIOptions struct { bundle ca.Bundle namespace string serviceAccount string appID string } func kubeAPI(t *testing.T, opts kubeAPIOptions) *prockube.Kubernetes { t.Helper() return prockube.New(t, prockube.WithClusterDaprConfigurationList(t, new(configapi.ConfigurationList)), prockube.WithDaprConfigurationGet(t, &configapi.Configuration{ TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Configuration"}, ObjectMeta: metav1.ObjectMeta{Namespace: "sentrynamespace", Name: "daprsystem"}, Spec: configapi.ConfigurationSpec{ MTLSSpec: &configapi.MTLSSpec{ControlPlaneTrustDomain: "integration.test.dapr.io"}, }, }), prockube.WithSecretGet(t, &corev1.Secret{ TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "Secret"}, ObjectMeta: metav1.ObjectMeta{Namespace: "sentrynamespace", Name: "dapr-trust-bundle"}, Data: map[string][]byte{ "ca.crt": opts.bundle.TrustAnchors, "issuer.crt": opts.bundle.IssChainPEM, "issuer.key": opts.bundle.IssKeyPEM, }, }), prockube.WithConfigMapGet(t, &corev1.ConfigMap{ TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "ConfigMap"}, ObjectMeta: metav1.ObjectMeta{Namespace: "sentrynamespace", Name: "dapr-trust-bundle"}, Data: map[string]string{"ca.crt": string(opts.bundle.TrustAnchors)}, }), prockube.WithClusterPodList(t, &corev1.PodList{ TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "PodList"}, Items: []corev1.Pod{ { TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "Pod"}, ObjectMeta: metav1.ObjectMeta{ Namespace: opts.namespace, Name: "mypod", Annotations: map[string]string{"dapr.io/app-id": opts.appID}, }, Spec: corev1.PodSpec{ServiceAccountName: opts.serviceAccount}, }, }, }), prockube.WithPath("/apis/authentication.k8s.io/v1/tokenreviews", func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, "POST", r.Method) assert.Equal(t, "application/json", r.Header.Get("Content-Type")) var request *authapi.TokenReview require.NoError(t, json.NewDecoder(r.Body).Decode(&request)) require.Len(t, request.Spec.Audiences, 2) assert.Equal(t, "dapr.io/sentry", request.Spec.Audiences[0]) assert.Equal(t, "spiffe://integration.test.dapr.io/ns/sentrynamespace/dapr-sentry", request.Spec.Audiences[1]) resp, err := json.Marshal(&authapi.TokenReview{ Status: authapi.TokenReviewStatus{ Authenticated: true, User: authapi.UserInfo{Username: fmt.Sprintf("system:serviceaccount:%s:%s", opts.namespace, opts.serviceAccount)}, }, }) require.NoError(t, err) w.Header().Add("Content-Type", "application/json") w.Write(resp) }), ) }
mikeee/dapr
tests/integration/suite/sentry/validator/kubernetes/common.go
GO
mit
3,746
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package kubernetes import ( "context" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/x509" "encoding/pem" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" sentrypbv1 "github.com/dapr/dapr/pkg/proto/sentry/v1" "github.com/dapr/dapr/pkg/sentry/server/ca" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/exec" "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" secpem "github.com/dapr/kit/crypto/pem" ) func init() { suite.Register(new(kube)) } // kube tests Sentry with the Kubernetes validator. type kube struct { sentry *sentry.Sentry } func (k *kube) Setup(t *testing.T) []framework.Option { rootKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) require.NoError(t, err) bundle, err := ca.GenerateBundle(rootKey, "integration.test.dapr.io", time.Second*5, nil) require.NoError(t, err) kubeAPI := kubeAPI(t, kubeAPIOptions{ bundle: bundle, namespace: "mynamespace", serviceAccount: "myserviceaccount", appID: "myappid", }) k.sentry = sentry.New(t, sentry.WithWriteConfig(false), sentry.WithKubeconfig(kubeAPI.KubeconfigPath(t)), sentry.WithNamespace("sentrynamespace"), sentry.WithExecOptions( // Enable Kubernetes validator. exec.WithEnvVars(t, "KUBERNETES_SERVICE_HOST", "anything"), ), sentry.WithCABundle(bundle), sentry.WithTrustDomain("integration.test.dapr.io"), ) return []framework.Option{ framework.WithProcesses(k.sentry, kubeAPI), } } func (k *kube) Run(t *testing.T, ctx context.Context) { k.sentry.WaitUntilRunning(t, ctx) conn := k.sentry.DialGRPC(t, ctx, "spiffe://integration.test.dapr.io/ns/sentrynamespace/dapr-sentry") client := sentrypbv1.NewCAClient(conn) pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) require.NoError(t, err) csrDer, err := x509.CreateCertificateRequest(rand.Reader, new(x509.CertificateRequest), pk) require.NoError(t, err) resp, err := client.SignCertificate(ctx, &sentrypbv1.SignCertificateRequest{ Id: "myappid", Namespace: "mynamespace", CertificateSigningRequest: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrDer}), TokenValidator: sentrypbv1.SignCertificateRequest_KUBERNETES, Token: `{"kubernetes.io":{"pod":{"name":"mypod"}}}`, }) require.NoError(t, err) require.NotEmpty(t, resp.GetWorkloadCertificate()) certs, err := secpem.DecodePEMCertificates(resp.GetWorkloadCertificate()) require.NoError(t, err) require.Len(t, certs, 2) require.NoError(t, certs[0].CheckSignatureFrom(certs[1])) require.Len(t, k.sentry.CABundle().IssChain, 1) assert.Equal(t, k.sentry.CABundle().IssChain[0].Raw, certs[1].Raw) trustBundle, err := secpem.DecodePEMCertificates(k.sentry.CABundle().TrustAnchors) require.NoError(t, err) require.Len(t, trustBundle, 1) require.NoError(t, certs[1].CheckSignatureFrom(trustBundle[0])) for _, req := range map[string]*sentrypbv1.SignCertificateRequest{ "wrong app id": { Id: "notmyappid", Namespace: "mynamespace", CertificateSigningRequest: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrDer}), TokenValidator: sentrypbv1.SignCertificateRequest_KUBERNETES, Token: `{"kubernetes.io":{"pod":{"name":"mypod"}}}`, }, "wrong namespace": { Id: "myappid", Namespace: "notmynamespace", CertificateSigningRequest: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrDer}), TokenValidator: sentrypbv1.SignCertificateRequest_KUBERNETES, Token: `{"kubernetes.io":{"pod":{"name":"mypod"}}}`, }, "wrong token validator": { Id: "myappid", Namespace: "mynamespace", CertificateSigningRequest: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrDer}), TokenValidator: sentrypbv1.SignCertificateRequest_JWKS, Token: `{"kubernetes.io":{"pod":{"name":"mypod"}}}`, }, "wrong pod name": { Id: "myappid", Namespace: "mynamespace", CertificateSigningRequest: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrDer}), TokenValidator: sentrypbv1.SignCertificateRequest_KUBERNETES, Token: `{"kubernetes.io":{"pod":{"name":"notmypod"}}}`, }, } { _, err = client.SignCertificate(ctx, req) require.Error(t, err) } }
mikeee/dapr
tests/integration/suite/sentry/validator/kubernetes/kube.go
GO
mit
5,269
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package kubernetes import ( "context" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/x509" "encoding/pem" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" sentrypbv1 "github.com/dapr/dapr/pkg/proto/sentry/v1" "github.com/dapr/dapr/pkg/sentry/server/ca" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/exec" "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(legacyid)) } // legacyid ensures that the legacy '<namespace>:<service account>' ID format // is no longer supported. type legacyid struct { sentry *sentry.Sentry } func (l *legacyid) Setup(t *testing.T) []framework.Option { rootKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) require.NoError(t, err) bundle, err := ca.GenerateBundle(rootKey, "integration.test.dapr.io", time.Second*5, nil) require.NoError(t, err) kubeAPI := kubeAPI(t, kubeAPIOptions{ bundle: bundle, namespace: "myns", serviceAccount: "myaccount", appID: "myappid", }) l.sentry = sentry.New(t, sentry.WithWriteConfig(false), sentry.WithKubeconfig(kubeAPI.KubeconfigPath(t)), sentry.WithExecOptions( // Enable Kubernetes validator. exec.WithEnvVars(t, "KUBERNETES_SERVICE_HOST", "anything"), exec.WithEnvVars(t, "NAMESPACE", "sentrynamespace"), ), sentry.WithCABundle(bundle), sentry.WithTrustDomain("integration.test.dapr.io"), ) return []framework.Option{ framework.WithProcesses(l.sentry, kubeAPI), } } func (l *legacyid) Run(t *testing.T, ctx context.Context) { l.sentry.WaitUntilRunning(t, ctx) conn := l.sentry.DialGRPC(t, ctx, "spiffe://integration.test.dapr.io/ns/sentrynamespace/dapr-sentry") client := sentrypbv1.NewCAClient(conn) pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) require.NoError(t, err) csrDer, err := x509.CreateCertificateRequest(rand.Reader, new(x509.CertificateRequest), pk) require.NoError(t, err) resp, err := client.SignCertificate(ctx, &sentrypbv1.SignCertificateRequest{ Id: "myns:myaccount", Namespace: "myns", CertificateSigningRequest: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrDer}), TokenValidator: sentrypbv1.SignCertificateRequest_KUBERNETES, Token: `{"kubernetes.io":{"pod":{"name":"mypod"}}}`, }) assert.Nil(t, resp) require.Error(t, err) assert.Equal(t, codes.PermissionDenied, status.Code(err)) }
mikeee/dapr
tests/integration/suite/sentry/validator/kubernetes/legacyid.go
GO
mit
3,240
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package kubernetes import ( "context" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/x509" "encoding/pem" "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" sentrypbv1 "github.com/dapr/dapr/pkg/proto/sentry/v1" "github.com/dapr/dapr/pkg/sentry/server/ca" "github.com/dapr/dapr/tests/integration/framework" "github.com/dapr/dapr/tests/integration/framework/process/exec" "github.com/dapr/dapr/tests/integration/framework/process/kubernetes" "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(longname)) } // longname tests that sentry with _not_ authenticate requests with legacy // identities that use namespace + serviceaccount names longer than 253 // characters, or app IDs longer than 64 characters. type longname struct { sentry1 *sentry.Sentry sentry2 *sentry.Sentry sentry3 *sentry.Sentry } func (l *longname) Setup(t *testing.T) []framework.Option { rootKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) require.NoError(t, err) bundle, err := ca.GenerateBundle(rootKey, "integration.test.dapr.io", time.Second*5, nil) require.NoError(t, err) kubeAPI1 := kubeAPI(t, kubeAPIOptions{ bundle: bundle, namespace: strings.Repeat("n", 253), serviceAccount: strings.Repeat("s", 253), appID: "myapp", }) kubeAPI2 := kubeAPI(t, kubeAPIOptions{ bundle: bundle, namespace: strings.Repeat("n", 253), serviceAccount: strings.Repeat("s", 253), appID: strings.Repeat("a", 65), }) kubeAPI3 := kubeAPI(t, kubeAPIOptions{ bundle: bundle, namespace: strings.Repeat("n", 253), serviceAccount: strings.Repeat("s", 253), appID: strings.Repeat("a", 64), }) sentryOpts := func(kubeAPI *kubernetes.Kubernetes) *sentry.Sentry { return sentry.New(t, sentry.WithWriteConfig(false), sentry.WithKubeconfig(kubeAPI.KubeconfigPath(t)), sentry.WithExecOptions( // Enable Kubernetes validator. exec.WithEnvVars(t, "KUBERNETES_SERVICE_HOST", "anything"), exec.WithEnvVars(t, "NAMESPACE", "sentrynamespace"), ), sentry.WithCABundle(bundle), sentry.WithTrustDomain("integration.test.dapr.io"), ) } l.sentry1 = sentryOpts(kubeAPI1) l.sentry2 = sentryOpts(kubeAPI2) l.sentry3 = sentryOpts(kubeAPI3) return []framework.Option{ framework.WithProcesses(kubeAPI1, kubeAPI2, kubeAPI3, l.sentry1, l.sentry2, l.sentry3), } } func (l *longname) Run(t *testing.T, ctx context.Context) { l.sentry1.WaitUntilRunning(t, ctx) l.sentry2.WaitUntilRunning(t, ctx) l.sentry3.WaitUntilRunning(t, ctx) conn1 := l.sentry1.DialGRPC(t, ctx, "spiffe://integration.test.dapr.io/ns/sentrynamespace/dapr-sentry") client1 := sentrypbv1.NewCAClient(conn1) pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) require.NoError(t, err) csrDer, err := x509.CreateCertificateRequest(rand.Reader, new(x509.CertificateRequest), pk) require.NoError(t, err) resp, err := client1.SignCertificate(ctx, &sentrypbv1.SignCertificateRequest{ Id: strings.Repeat("n", 253) + ":" + strings.Repeat("s", 253), Namespace: strings.Repeat("n", 253), CertificateSigningRequest: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrDer}), TokenValidator: sentrypbv1.SignCertificateRequest_KUBERNETES, Token: `{"kubernetes.io":{"pod":{"name":"mypod"}}}`, }) assert.Nil(t, resp) require.ErrorContains(t, err, "app ID must be 64 characters or less") assert.Equal(t, codes.PermissionDenied, status.Code(err)) conn2 := l.sentry2.DialGRPC(t, ctx, "spiffe://integration.test.dapr.io/ns/sentrynamespace/dapr-sentry") client2 := sentrypbv1.NewCAClient(conn2) resp, err = client2.SignCertificate(ctx, &sentrypbv1.SignCertificateRequest{ Id: strings.Repeat("a", 65), Namespace: strings.Repeat("n", 253), CertificateSigningRequest: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrDer}), TokenValidator: sentrypbv1.SignCertificateRequest_KUBERNETES, Token: `{"kubernetes.io":{"pod":{"name":"mypod"}}}`, }) assert.Nil(t, resp) require.ErrorContains(t, err, "app ID must be 64 characters or less") assert.Equal(t, codes.PermissionDenied, status.Code(err)) conn3 := l.sentry3.DialGRPC(t, ctx, "spiffe://integration.test.dapr.io/ns/sentrynamespace/dapr-sentry") client3 := sentrypbv1.NewCAClient(conn3) resp, err = client3.SignCertificate(ctx, &sentrypbv1.SignCertificateRequest{ Id: strings.Repeat("a", 64), Namespace: strings.Repeat("n", 253), CertificateSigningRequest: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrDer}), TokenValidator: sentrypbv1.SignCertificateRequest_KUBERNETES, Token: `{"kubernetes.io":{"pod":{"name":"mypod"}}}`, }) require.NoError(t, err) require.NotEmpty(t, resp.GetWorkloadCertificate()) }
mikeee/dapr
tests/integration/suite/sentry/validator/kubernetes/longname.go
GO
mit
5,729
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package validator import ( _ "github.com/dapr/dapr/tests/integration/suite/sentry/validator/insecure" _ "github.com/dapr/dapr/tests/integration/suite/sentry/validator/jwks" _ "github.com/dapr/dapr/tests/integration/suite/sentry/validator/kubernetes" )
mikeee/dapr
tests/integration/suite/sentry/validator/validator.go
GO
mit
817
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package suite import ( "context" "reflect" "sort" "strings" "testing" "github.com/stretchr/testify/require" "github.com/dapr/dapr/tests/integration/framework" ) var cases []Case // Case is a test case for the integration test suite. type Case interface { Setup(*testing.T) []framework.Option Run(*testing.T, context.Context) } // NamedCase is a test case with a searchable name. type NamedCase struct { name string Case } // Name returns the name of the test case. func (c NamedCase) Name() string { return c.name } // Register registers a test case. func Register(c Case) { cases = append(cases, c) } // All returns all registered test cases. // The returned slice is sorted by name. func All(t *testing.T) []NamedCase { all := make([]NamedCase, len(cases)) for i, tcase := range cases { tof := reflect.TypeOf(tcase).Elem() _, aft, ok := strings.Cut(tof.PkgPath(), "tests/integration/suite/") require.True(t, ok) name := aft + "/" + tof.Name() all[i] = NamedCase{name, tcase} } sort.Slice(all, func(i, j int) bool { return all[i].name < all[j].name }) return all }
mikeee/dapr
tests/integration/suite/suite.go
GO
mit
1,669
//go:build perf // +build perf /* Copyright 2021 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package actor_timer_with_state_perf import ( "encoding/json" "fmt" "os" "strings" "testing" "github.com/dapr/dapr/tests/perf" "github.com/dapr/dapr/tests/perf/utils" kube "github.com/dapr/dapr/tests/platforms/kubernetes" "github.com/dapr/dapr/tests/runner" "github.com/dapr/dapr/tests/runner/summary" "github.com/stretchr/testify/require" ) const ( numHealthChecks = 60 // Number of times to check for endpoint health per app. serviceApplicationName = "perf-actor-activation-service" clientApplicationName = "perf-actor-activation-client" ) var tr *runner.TestRunner func TestMain(m *testing.M) { utils.SetupLogs("actor_activation") testApps := []kube.AppDescription{ { AppName: serviceApplicationName, DaprEnabled: true, ImageName: "perf-actorjava", Replicas: 1, IngressEnabled: true, MetricsEnabled: true, AppPort: 3000, DaprCPULimit: "4.0", DaprCPURequest: "0.1", DaprMemoryLimit: "512Mi", DaprMemoryRequest: "250Mi", AppCPULimit: "4.0", AppCPURequest: "0.1", AppMemoryLimit: "800Mi", AppMemoryRequest: "2500Mi", Labels: map[string]string{ "daprtest": serviceApplicationName, }, }, { AppName: clientApplicationName, DaprEnabled: true, ImageName: "perf-tester", Replicas: 1, IngressEnabled: true, MetricsEnabled: true, AppPort: 3001, DaprCPULimit: "4.0", DaprCPURequest: "0.1", DaprMemoryLimit: "512Mi", DaprMemoryRequest: "250Mi", AppCPULimit: "4.0", AppCPURequest: "0.1", AppMemoryLimit: "800Mi", AppMemoryRequest: "2500Mi", Labels: map[string]string{ "daprtest": clientApplicationName, }, PodAffinityLabels: map[string]string{ "daprtest": serviceApplicationName, }, }, } tr = runner.NewTestRunner("actortimerwithstate", testApps, nil, nil) os.Exit(tr.Start(m)) } func TestActorActivate(t *testing.T) { p := perf.Params( perf.WithQPS(500), perf.WithConnections(8), perf.WithDuration("1m"), perf.WithPayload("{}"), ) // Get the ingress external url of test app testAppURL := tr.Platform.AcquireAppExternalURL(serviceApplicationName) require.NotEmpty(t, testAppURL, "test app external URL must not be empty") // Check if test app endpoint is available t.Logf("test app url: %s", testAppURL+"/health") _, err := utils.HTTPGetNTimes(testAppURL+"/health", numHealthChecks) require.NoError(t, err) // Get the ingress external url of tester app testerAppURL := tr.Platform.AcquireAppExternalURL(clientApplicationName) require.NotEmpty(t, testerAppURL, "tester app external URL must not be empty") // Check if tester app endpoint is available t.Logf("tester app url: %s", testerAppURL) _, err = utils.HTTPGetNTimes(testerAppURL, numHealthChecks) require.NoError(t, err) // Perform dapr test endpoint := fmt.Sprintf("http://127.0.0.1:3500/v1.0/actors/DemoActorTimer/{uuid}/method/noOp") p.TargetEndpoint = endpoint p.StdClient = false body, err := json.Marshal(&p) require.NoError(t, err) t.Logf("running dapr test with params: %s", body) daprResp, err := utils.HTTPPost(fmt.Sprintf("%s/test", testerAppURL), body) t.Log("checking err...") require.NoError(t, err) require.NotEmpty(t, daprResp) // fast fail if daprResp starts with error require.False(t, strings.HasPrefix(string(daprResp), "error")) appUsage, err := tr.Platform.GetAppUsage(serviceApplicationName) require.NoError(t, err) sidecarUsage, err := tr.Platform.GetSidecarUsage(serviceApplicationName) require.NoError(t, err) restarts, err := tr.Platform.GetTotalRestarts(serviceApplicationName) require.NoError(t, err) testerRestarts, err := tr.Platform.GetTotalRestarts(clientApplicationName) require.NoError(t, err) t.Logf("dapr test results: %s", string(daprResp)) t.Logf("target dapr app consumed %vm CPU and %vMb of Memory", appUsage.CPUm, appUsage.MemoryMb) t.Logf("target dapr sidecar consumed %vm CPU and %vMb of Memory", sidecarUsage.CPUm, sidecarUsage.MemoryMb) t.Logf("target dapr app or sidecar restarted %v times", restarts) t.Logf("tester app or sidecar restarted %v times", testerRestarts) var daprResult perf.TestResult err = json.Unmarshal(daprResp, &daprResult) require.NoError(t, err) percentiles := map[int]string{2: "90th", 3: "99th"} for k, v := range percentiles { daprValue := daprResult.DurationHistogram.Percentiles[k].Value t.Logf("%s percentile: %sms", v, fmt.Sprintf("%.2f", daprValue*1000)) } t.Logf("Actual QPS: %.2f, expected QPS: %d", daprResult.ActualQPS, p.QPS) summary.ForTest(t). Service(serviceApplicationName). Client(clientApplicationName). CPU(appUsage.CPUm). Memory(appUsage.MemoryMb). SidecarCPU(sidecarUsage.CPUm). SidecarMemory(sidecarUsage.MemoryMb). Restarts(restarts). ActualQPS(daprResult.ActualQPS). Params(p). OutputFortio(daprResult). Flush() require.Equal(t, 0, daprResult.RetCodes.Num400) require.Equal(t, 0, daprResult.RetCodes.Num500) require.Equal(t, 0, restarts) require.True(t, daprResult.ActualQPS > float64(p.QPS)*0.99) require.True(t, daprResult.DurationHistogram.Percentiles[2].Value*1000 < 15) require.True(t, daprResult.DurationHistogram.Percentiles[3].Value*1000 < 35) }
mikeee/dapr
tests/perf/actor_activation/actor_activation_test.go
GO
mit
5,901
//go:build perf // +build perf /* Copyright 2022 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package actor_double_activation import ( "encoding/json" "os" "testing" "github.com/dapr/dapr/tests/perf/utils" kube "github.com/dapr/dapr/tests/platforms/kubernetes" "github.com/dapr/dapr/tests/runner" "github.com/dapr/dapr/tests/runner/loadtest" "github.com/dapr/dapr/tests/runner/summary" "github.com/stretchr/testify/require" ) const ( numHealthChecks = 60 // Number of times to check for endpoint health per app. serviceApplicationName = "perf-actor-double-activation" ) var ( tr *runner.TestRunner ) func TestMain(m *testing.M) { utils.SetupLogs("actor_double_activation") testApps := []kube.AppDescription{ { AppName: serviceApplicationName, DaprEnabled: true, ImageName: "perf-actor-activation-locker", Config: "redishostconfig", Replicas: 3, IngressEnabled: true, MetricsEnabled: true, AppPort: 3000, DaprCPULimit: "4.0", DaprCPURequest: "0.1", DaprMemoryLimit: "512Mi", DaprMemoryRequest: "250Mi", AppCPULimit: "4.0", AppCPURequest: "0.1", AppMemoryLimit: "512Mi", AppMemoryRequest: "256Mi", }, } tr = runner.NewTestRunner("actordoubleactivation", testApps, nil, nil) os.Exit(tr.Start(m)) } func TestActorDoubleActivation(t *testing.T) { // Get the ingress external url of test app testServiceAppURL := tr.Platform.AcquireAppExternalURL(serviceApplicationName) require.NotEmpty(t, testServiceAppURL, "test app external URL must not be empty") // Check if test app endpoint is available t.Logf("Test app url: %s", testServiceAppURL) err := utils.HealthCheckApps(testServiceAppURL + "/health") require.NoError(t, err, "Health checks failed") k6Test := loadtest.NewK6( "./test.js", loadtest.WithParallelism(3), loadtest.WithRunnerEnvVar("TEST_APP_NAME", serviceApplicationName), ) defer k6Test.Dispose() t.Log("Running the k6 load test...") require.NoError(t, tr.Platform.LoadTest(k6Test)) sm, err := loadtest.K6ResultDefault(k6Test) require.NoError(t, err) require.NotNil(t, sm) bts, err := json.MarshalIndent(sm, "", " ") require.NoError(t, err) appUsage, err := tr.Platform.GetAppUsage(serviceApplicationName) require.NoError(t, err) sidecarUsage, err := tr.Platform.GetSidecarUsage(serviceApplicationName) require.NoError(t, err) restarts, err := tr.Platform.GetTotalRestarts(serviceApplicationName) require.NoError(t, err) summary.ForTest(t). Service(serviceApplicationName). CPU(appUsage.CPUm). Memory(appUsage.MemoryMb). SidecarCPU(sidecarUsage.CPUm). SidecarMemory(sidecarUsage.MemoryMb). Restarts(restarts). OutputK6(sm.RunnersResults). Flush() require.Truef(t, sm.Pass, "test has not passed, results: %s", string(bts)) t.Logf("Test summary `%s`", string(bts)) }
mikeee/dapr
tests/perf/actor_double_activation/actor_double_activation_test.go
GO
mit
3,396
/* Copyright 2022 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { PodDisruptor } from 'k6/x/disruptor' import http from 'k6/http' import { check } from 'k6' import { Counter } from 'k6/metrics' const DoubleActivations = new Counter('double_activations') const singleId = 'SINGLE_ID' export const options = { discardResponseBodies: true, thresholds: { 'double_activations{scenario:base}': ['count==0'], 'double_activations{scenario:faults}': ['count==0'], }, scenarios: { base: { executor: 'ramping-vus', startVUs: 0, stages: [ { duration: '5s', target: 1000 }, { duration: '5s', target: 3000 }, { duration: '5s', target: 5000 }, ], gracefulRampDown: '0s', }, disrupt: { executor: 'shared-iterations', iterations: 1, vus: 1, exec: 'disrupt', startTime: '15s', }, faults: { executor: 'ramping-vus', startVUs: 0, stages: [ { duration: '5s', target: 1000 }, { duration: '5s', target: 3000 }, { duration: '5s', target: 5000 }, ], gracefulRampDown: '0s', startTime: '15s', }, }, } const DAPR_ADDRESS = `http://127.0.0.1:${__ENV.DAPR_HTTP_PORT}/v1.0` function callActorMethod(id, method) { return http.post( `${DAPR_ADDRESS}/actors/fake-actor-type/${id}/method/${method}`, JSON.stringify({}) ) } export default function () { const result = callActorMethod(singleId, 'Lock') if (result.status >= 400) { DoubleActivations.add(1) } } export function teardown(_) { const shutdownResult = http.post(`${DAPR_ADDRESS}/shutdown`) check(shutdownResult, { 'shutdown response status code is 2xx': shutdownResult.status >= 200 && shutdownResult.status < 300, }) } export function handleSummary(data) { return { stdout: JSON.stringify(data), } } // add disruption const selector = { namespace: __ENV.TEST_NAMESPACE, select: { labels: { testapp: __ENV.TEST_APP_NAME, }, }, } export function disrupt() { const podDisruptor = new PodDisruptor(selector) // delay traffic from one random replica of the deployment const fault = { averageDelay: 50, errorCode: 500, errorRate: 0.1, } podDisruptor.injectHTTPFaults(fault, 15) }
mikeee/dapr
tests/perf/actor_double_activation/test.js
JavaScript
mit
3,062
//go:build perf // +build perf /* Copyright 2022 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package actor_id_scale import ( "encoding/json" "fmt" "os" "testing" "github.com/dapr/dapr/tests/perf/utils" kube "github.com/dapr/dapr/tests/platforms/kubernetes" "github.com/dapr/dapr/tests/runner" "github.com/dapr/dapr/tests/runner/loadtest" "github.com/stretchr/testify/require" ) const ( numHealthChecks = 60 // Number of times to check for endpoint health per app. serviceApplicationName = "perf-actor-id" actorType = "scale-id" ) var ( tr *runner.TestRunner ) func TestMain(m *testing.M) { utils.SetupLogs("actor_id_stress_test") testApps := []kube.AppDescription{ { AppName: serviceApplicationName, DaprEnabled: true, ImageName: "perf-actorfeatures", Replicas: 10, IngressEnabled: true, MetricsEnabled: true, AppPort: 3000, DaprCPULimit: "4.0", DaprCPURequest: "0.1", DaprMemoryLimit: "512Mi", DaprMemoryRequest: "250Mi", AppCPULimit: "4.0", AppCPURequest: "0.1", AppMemoryLimit: "512Mi", AppMemoryRequest: "256Mi", AppEnv: map[string]string{ "TEST_APP_ACTOR_TYPE": actorType, }, }, } tr = runner.NewTestRunner("actoridstress", testApps, nil, nil) os.Exit(tr.Start(m)) } func TestActorIdStress(t *testing.T) { t.Skip("skipping due to flakiness") // Get the ingress external url of test app testServiceAppURL := tr.Platform.AcquireAppExternalURL(serviceApplicationName) require.NotEmpty(t, testServiceAppURL, "test app external URL must not be empty") // Check if test app endpoint is available t.Logf("test app url: %s", testServiceAppURL+"/health") _, err := utils.HTTPGetNTimes(testServiceAppURL+"/health", numHealthChecks) require.NoError(t, err) k6Test := loadtest.NewK6("./test.js", loadtest.WithParallelism(5), loadtest.WithRunnerEnvVar("ACTOR_TYPE", actorType)) defer k6Test.Dispose() t.Log("running the k6 load test...") require.NoError(t, tr.Platform.LoadTest(k6Test)) summary, err := loadtest.K6ResultDefault(k6Test) require.NoError(t, err) require.NotNil(t, summary) bts, err := json.MarshalIndent(summary, "", " ") require.NoError(t, err) require.True(t, summary.Pass, fmt.Sprintf("test has not passed, results %s", string(bts))) t.Logf("test summary `%s`", string(bts)) appUsage, err := tr.Platform.GetAppUsage(serviceApplicationName) require.NoError(t, err) sidecarUsage, err := tr.Platform.GetSidecarUsage(serviceApplicationName) require.NoError(t, err) restarts, err := tr.Platform.GetTotalRestarts(serviceApplicationName) require.NoError(t, err) t.Logf("target dapr app consumed %vm CPU and %vMb of Memory", appUsage.CPUm, appUsage.MemoryMb) t.Logf("target dapr sidecar consumed %vm CPU and %vMb of Memory", sidecarUsage.CPUm, sidecarUsage.MemoryMb) t.Logf("target dapr app or sidecar restarted %v times", restarts) require.Equal(t, 0, restarts) }
mikeee/dapr
tests/perf/actor_id_scale/actor_id_scale_test.go
GO
mit
3,479
/* Copyright 2022 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import http from 'k6/http' import { check } from 'k6' import exec from 'k6/execution' const defaultMethod = 'default' const actorType = __ENV.ACTOR_TYPE export const options = { discardResponseBodies: true, thresholds: { checks: ['rate==1'], http_req_duration: ['p(95)<90'], // 95% of requests should be below 70ms }, scenarios: { idStress: { executor: 'ramping-vus', startVUs: 0, stages: [ { duration: '2s', target: 100 }, { duration: '2s', target: 300 }, { duration: '4s', target: 500 }, ], gracefulRampDown: '0s', }, }, } const DAPR_ADDRESS = `http://127.0.0.1:${__ENV.DAPR_HTTP_PORT}/v1.0` function callActorMethod(id, method) { return http.put( `${DAPR_ADDRESS}/actors/${actorType}/${id}/method/${method}`, JSON.stringify({}) ) } export default function () { const result = callActorMethod(exec.scenario.iterationInTest, defaultMethod) check(result, { 'response code was 2xx': (result) => result.status >= 200 && result.status < 300, }) } export function teardown(_) { const shutdownResult = http.post(`${DAPR_ADDRESS}/shutdown`) check(shutdownResult, { 'shutdown response status code is 2xx': shutdownResult.status >= 200 && shutdownResult.status < 300, }) } export function handleSummary(data) { return { stdout: JSON.stringify(data), } }
mikeee/dapr
tests/perf/actor_id_scale/test.js
JavaScript
mit
2,077
//go:build perf // +build perf /* Copyright 2021 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package actor_reminder_perf import ( "encoding/json" "fmt" "os" "strings" "testing" "time" "github.com/dapr/dapr/tests/perf" "github.com/dapr/dapr/tests/perf/utils" kube "github.com/dapr/dapr/tests/platforms/kubernetes" "github.com/dapr/dapr/tests/runner" "github.com/dapr/dapr/tests/runner/summary" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) const ( numHealthChecks = 60 // Number of times to check for endpoint health per app. actorType = "PerfTestActorReminder" appName = "perf-actor-reminder-service" // Target for the QPS - Temporary targetQPS = 50 ) var tr *runner.TestRunner func TestMain(m *testing.M) { utils.SetupLogs("actor_reminder") testApps := []kube.AppDescription{ { AppName: appName, DaprEnabled: true, ImageName: "perf-actorfeatures", Replicas: 1, IngressEnabled: true, AppPort: 3000, DaprCPULimit: "4.0", DaprCPURequest: "0.1", DaprMemoryLimit: "512Mi", DaprMemoryRequest: "250Mi", AppCPULimit: "4.0", AppCPURequest: "0.1", AppMemoryLimit: "800Mi", AppMemoryRequest: "2500Mi", AppEnv: map[string]string{ "TEST_APP_ACTOR_TYPE": actorType, }, }, } tr = runner.NewTestRunner("actorreminder", testApps, nil, nil) os.Exit(tr.Start(m)) } func TestActorReminderRegistrationPerformance(t *testing.T) { p := perf.Params( perf.WithQPS(500), perf.WithConnections(8), perf.WithDuration("1m"), perf.WithPayload("{}"), ) // Get the ingress external url of test app testAppURL := tr.Platform.AcquireAppExternalURL(appName) require.NotEmpty(t, testAppURL, "test app external URL must not be empty") // Check if test app endpoint is available t.Logf("test app url: %s", testAppURL+"/health") _, err := utils.HTTPGetNTimes(testAppURL+"/health", numHealthChecks) require.NoError(t, err) // Perform dapr test endpoint := fmt.Sprintf("http://127.0.0.1:3500/v1.0/actors/%v/{uuid}/reminders/myreminder", actorType) p.TargetEndpoint = endpoint p.Payload = `{"dueTime":"24h","period":"24h"}` body, err := json.Marshal(&p) require.NoError(t, err) t.Logf("running dapr test with params: %s", body) daprResp, err := utils.HTTPPost(fmt.Sprintf("%s/test", testAppURL), body) t.Log("checking err...") require.NoError(t, err) require.NotEmpty(t, daprResp) // fast fail if daprResp starts with error require.False(t, strings.HasPrefix(string(daprResp), "error")) // Let test run for 90s triggering the timers and collect metrics. time.Sleep(90 * time.Second) appUsage, err := tr.Platform.GetAppUsage(appName) require.NoError(t, err) sidecarUsage, err := tr.Platform.GetSidecarUsage(appName) require.NoError(t, err) restarts, err := tr.Platform.GetTotalRestarts(appName) require.NoError(t, err) t.Logf("dapr test results: %s", string(daprResp)) t.Logf("target dapr app consumed %vm CPU and %vMb of Memory", appUsage.CPUm, appUsage.MemoryMb) t.Logf("target dapr sidecar consumed %vm CPU and %vMb of Memory", sidecarUsage.CPUm, sidecarUsage.MemoryMb) t.Logf("target dapr app or sidecar restarted %v times", restarts) var daprResult perf.TestResult err = json.Unmarshal(daprResp, &daprResult) require.NoErrorf(t, err, "Failed to unmarshal: %s", string(daprResp)) percentiles := map[int]string{2: "90th", 3: "99th"} for k, v := range percentiles { daprValue := daprResult.DurationHistogram.Percentiles[k].Value t.Logf("%s percentile: %sms", v, fmt.Sprintf("%.2f", daprValue*1000)) } t.Logf("Actual QPS: %.2f, expected QPS: %d", daprResult.ActualQPS, targetQPS) // TODO: Revert to p.QPS summary.ForTest(t). Service(appName). Client(appName). CPU(appUsage.CPUm). Memory(appUsage.MemoryMb). SidecarCPU(sidecarUsage.CPUm). SidecarMemory(sidecarUsage.MemoryMb). Restarts(restarts). ActualQPS(daprResult.ActualQPS). Params(p). OutputFortio(daprResult). Flush() assert.Equal(t, 0, daprResult.RetCodes.Num400) assert.Equal(t, 0, daprResult.RetCodes.Num500) assert.Equal(t, 0, restarts) assert.True(t, daprResult.ActualQPS > targetQPS) // TODO: Revert to p.QPS }
mikeee/dapr
tests/perf/actor_reminder/actor_reminder_test.go
GO
mit
4,728
//go:build perf // +build perf /* Copyright 2021 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package actor_timer_with_state_perf import ( "encoding/json" "fmt" "os" "strings" "testing" "time" "github.com/dapr/dapr/tests/perf" "github.com/dapr/dapr/tests/perf/utils" kube "github.com/dapr/dapr/tests/platforms/kubernetes" "github.com/dapr/dapr/tests/runner" "github.com/dapr/dapr/tests/runner/summary" "github.com/stretchr/testify/require" ) const ( numHealthChecks = 60 // Number of times to check for endpoint health per app. serviceApplicationName = "perf-actor-timer-service" clientApplicationName = "perf-actor-timer-client" ) var tr *runner.TestRunner func TestMain(m *testing.M) { utils.SetupLogs("actor_timer") testApps := []kube.AppDescription{ { AppName: serviceApplicationName, DaprEnabled: true, ImageName: "perf-actorjava", Replicas: 4, IngressEnabled: true, AppPort: 3000, DaprCPULimit: "4.0", DaprCPURequest: "0.1", DaprMemoryLimit: "512Mi", DaprMemoryRequest: "250Mi", AppCPULimit: "4.0", AppCPURequest: "0.1", AppMemoryLimit: "800Mi", AppMemoryRequest: "2500Mi", Labels: map[string]string{ "daprtest": serviceApplicationName, }, }, { AppName: clientApplicationName, DaprEnabled: true, ImageName: "perf-tester", Replicas: 1, IngressEnabled: true, AppPort: 3001, DaprCPULimit: "4.0", DaprCPURequest: "0.1", DaprMemoryLimit: "512Mi", DaprMemoryRequest: "250Mi", AppCPULimit: "4.0", AppCPURequest: "0.1", AppMemoryLimit: "800Mi", AppMemoryRequest: "2500Mi", Labels: map[string]string{ "daprtest": clientApplicationName, }, PodAffinityLabels: map[string]string{ "daprtest": serviceApplicationName, }, }, } tr = runner.NewTestRunner("actortimerwithstate", testApps, nil, nil) os.Exit(tr.Start(m)) } func TestActorTimerWithStatePerformance(t *testing.T) { p := perf.Params( perf.WithQPS(220), perf.WithConnections(10), perf.WithDuration("1m"), perf.WithPayload("{}"), ) // Get the ingress external url of test app testAppURL := tr.Platform.AcquireAppExternalURL(serviceApplicationName) require.NotEmpty(t, testAppURL, "test app external URL must not be empty") // Check if test app endpoint is available t.Logf("test app url: %s", testAppURL+"/health") _, err := utils.HTTPGetNTimes(testAppURL+"/health", numHealthChecks) require.NoError(t, err) // Get the ingress external url of tester app testerAppURL := tr.Platform.AcquireAppExternalURL(clientApplicationName) require.NotEmpty(t, testerAppURL, "tester app external URL must not be empty") // Check if tester app endpoint is available t.Logf("tester app url: %s", testerAppURL) _, err = utils.HTTPGetNTimes(testerAppURL, numHealthChecks) require.NoError(t, err) // Perform dapr test endpoint := fmt.Sprintf("http://%s:3000/actors", serviceApplicationName) p.TargetEndpoint = endpoint body, err := json.Marshal(&p) require.NoError(t, err) t.Logf("running dapr test with params: %s", body) daprResp, err := utils.HTTPPost(fmt.Sprintf("%s/test", testerAppURL), body) t.Logf("dapr test results: %s", string(daprResp)) t.Log("checking err...") require.NoError(t, err) require.NotEmpty(t, daprResp) // fast fail if daprResp starts with error require.False(t, strings.HasPrefix(string(daprResp), "error")) // Let test run for 10 minutes triggering the timers and collect metrics. t.Log("test is started, wait for 10 minutes...") time.Sleep(10 * time.Minute) appUsage, err := tr.Platform.GetAppUsage(serviceApplicationName) require.NoError(t, err) sidecarUsage, err := tr.Platform.GetSidecarUsage(serviceApplicationName) require.NoError(t, err) restarts, err := tr.Platform.GetTotalRestarts(serviceApplicationName) require.NoError(t, err) t.Logf("dapr test results: %s", string(daprResp)) t.Logf("target dapr app consumed %vm CPU and %vMb of Memory", appUsage.CPUm, appUsage.MemoryMb) t.Logf("target dapr sidecar consumed %vm CPU and %vMb of Memory", sidecarUsage.CPUm, sidecarUsage.MemoryMb) t.Logf("target dapr app or sidecar restarted %v times", restarts) var daprResult perf.TestResult err = json.Unmarshal(daprResp, &daprResult) require.NoError(t, err) percentiles := map[int]string{2: "90th", 3: "99th"} for k, v := range percentiles { daprValue := daprResult.DurationHistogram.Percentiles[k].Value t.Logf("%s percentile: %sms", v, fmt.Sprintf("%.2f", daprValue*1000)) } t.Logf("Actual QPS: %.2f, expected QPS: %d", daprResult.ActualQPS, p.QPS) summary.ForTest(t). Service(serviceApplicationName). Client(clientApplicationName). CPU(appUsage.CPUm). Memory(appUsage.MemoryMb). SidecarCPU(sidecarUsage.CPUm). SidecarMemory(sidecarUsage.MemoryMb). Restarts(restarts). ActualQPS(daprResult.ActualQPS). Params(p). OutputFortio(daprResult). Flush() require.Equal(t, 0, daprResult.RetCodes.Num400) require.Equal(t, 0, daprResult.RetCodes.Num500) require.Equal(t, 0, restarts) require.True(t, daprResult.ActualQPS > float64(p.QPS)*0.99) }
mikeee/dapr
tests/perf/actor_timer/actor_timer_test.go
GO
mit
5,691
//go:build perf // +build perf /* Copyright 2022 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package actor_type_scale import ( "encoding/json" "fmt" "os" "testing" "github.com/dapr/dapr/tests/perf/utils" kube "github.com/dapr/dapr/tests/platforms/kubernetes" "github.com/dapr/dapr/tests/runner" "github.com/dapr/dapr/tests/runner/loadtest" "github.com/dapr/dapr/tests/runner/summary" "github.com/stretchr/testify/require" ) const ( numHealthChecks = 60 // Number of times to check for endpoint health per app. serviceApplicationName = "perf-actor-type" numberOfActors = 100 ) var ( tr *runner.TestRunner actorsTypes string ) func TestMain(m *testing.M) { actorsTypes = "actor_0" for i := 1; i < numberOfActors; i++ { actorsTypes += fmt.Sprintf(",actor_%d", i) } utils.SetupLogs("actor_id_stress_test") testApps := []kube.AppDescription{ { AppName: serviceApplicationName, DaprEnabled: true, ImageName: "perf-actorfeatures", Replicas: 1, IngressEnabled: true, MetricsEnabled: true, AppPort: 3000, DaprCPULimit: "4.0", DaprCPURequest: "0.1", DaprMemoryLimit: "512Mi", DaprMemoryRequest: "250Mi", AppCPULimit: "4.0", AppCPURequest: "0.1", AppMemoryLimit: "512Mi", AppMemoryRequest: "256Mi", AppEnv: map[string]string{ "TEST_APP_ACTOR_TYPE": actorsTypes, }, }, } tr = runner.NewTestRunner("actoridstress", testApps, nil, nil) os.Exit(tr.Start(m)) } func TestActorIdStress(t *testing.T) { // Get the ingress external url of test app testServiceAppURL := tr.Platform.AcquireAppExternalURL(serviceApplicationName) require.NotEmpty(t, testServiceAppURL, "test app external URL must not be empty") // Check if test app endpoint is available t.Logf("test app url: %s", testServiceAppURL+"/health") _, err := utils.HTTPGetNTimes(testServiceAppURL+"/health", numHealthChecks) require.NoError(t, err) k6Test := loadtest.NewK6("./test.js", loadtest.WithParallelism(1), loadtest.WithRunnerEnvVar("ACTORS_TYPES", actorsTypes)) // defer k6Test.Dispose() t.Log("running the k6 load test...") require.NoError(t, tr.Platform.LoadTest(k6Test)) sm, err := loadtest.K6ResultDefault(k6Test) require.NoError(t, err) require.NotNil(t, sm) bts, err := json.MarshalIndent(sm, "", " ") require.NoError(t, err) appUsage, err := tr.Platform.GetAppUsage(serviceApplicationName) require.NoError(t, err) sidecarUsage, err := tr.Platform.GetSidecarUsage(serviceApplicationName) require.NoError(t, err) restarts, err := tr.Platform.GetTotalRestarts(serviceApplicationName) require.NoError(t, err) summary.ForTest(t). Service(serviceApplicationName). CPU(appUsage.CPUm). Memory(appUsage.MemoryMb). SidecarCPU(sidecarUsage.CPUm). SidecarMemory(sidecarUsage.MemoryMb). Restarts(restarts). OutputK6(sm.RunnersResults). Flush() t.Logf("target dapr app consumed %vm CPU and %vMb of Memory", appUsage.CPUm, appUsage.MemoryMb) t.Logf("target dapr sidecar consumed %vm CPU and %vMb of Memory", sidecarUsage.CPUm, sidecarUsage.MemoryMb) t.Logf("target dapr app or sidecar restarted %v times", restarts) require.True(t, sm.Pass, fmt.Sprintf("test has not passed, results %s", string(bts))) require.Equal(t, 0, restarts) t.Logf("test summary `%s`", string(bts)) }
mikeee/dapr
tests/perf/actor_type_scale/actor_type_scale_test.go
GO
mit
3,859