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 http import ( "context" "fmt" "net/http" "strings" "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/app" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(basic)) } // basic tests daprd metrics for the HTTP server type basic struct { daprd *daprd.Daprd } func (b *basic) Setup(t *testing.T) []framework.Option { app := app.New(t, app.WithHandlerFunc("/hi", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "OK") }), ) b.daprd = daprd.New(t, daprd.WithAppPort(app.Port()), daprd.WithAppProtocol("http"), daprd.WithAppID("myapp"), daprd.WithInMemoryStateStore("mystore"), ) return []framework.Option{ framework.WithProcesses(app, b.daprd), } } func (b *basic) Run(t *testing.T, ctx context.Context) { b.daprd.WaitUntilRunning(t, ctx) t.Run("service invocation", func(t *testing.T) { b.daprd.HTTPGet2xx(t, ctx, "/v1.0/invoke/myapp/method/hi") metrics := b.daprd.Metrics(t, ctx) assert.Equal(t, 1, int(metrics["dapr_http_server_request_count|app_id:myapp|method:GET|path:/v1.0/invoke/myapp/method/hi|status:200"])) }) t.Run("state stores", func(t *testing.T) { body := `[{"key":"myvalue", "value":"hello world"}]` b.daprd.HTTPPost2xx(t, ctx, "/v1.0/state/mystore", strings.NewReader(body), "content-type", "application/json") b.daprd.HTTPGet2xx(t, ctx, "/v1.0/state/mystore/myvalue") metrics := b.daprd.Metrics(t, ctx) assert.Equal(t, 1, int(metrics["dapr_http_server_request_count|app_id:myapp|method:POST|path:/v1.0/state/mystore|status:204"])) assert.Equal(t, 1, int(metrics["dapr_http_server_request_count|app_id:myapp|method:GET|path:/v1.0/state/mystore|status:200"])) }) }
mikeee/dapr
tests/integration/suite/daprd/metrics/http/basic.go
GO
mit
2,436
/* 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 cardinality import ( "context" "fmt" "net/http" "strings" "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/app" "github.com/dapr/dapr/tests/integration/framework/process/placement" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(high)) } // high tests daprd metrics for the HTTP server configured with high cardinality type high struct { daprd *daprd.Daprd place *placement.Placement } func (h *high) Setup(t *testing.T) []framework.Option { app := app.New(t, app.WithHandlerFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`OK`)) }), app.WithHandlerFunc("/hi", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "OK") }), app.WithHandlerFunc("/dapr/config", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`{"entities": ["myactortype"]}`)) }), ) h.place = placement.New(t) h.daprd = daprd.New(t, daprd.WithAppPort(app.Port()), daprd.WithAppProtocol("http"), daprd.WithAppID("myapp"), daprd.WithPlacementAddresses(h.place.Address()), daprd.WithInMemoryActorStateStore("mystore"), daprd.WithConfigManifests(t, ` apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: lowcardinality spec: metrics: http: increasedCardinality: true `), ) return []framework.Option{ framework.WithProcesses(app, h.daprd, h.place), } } func (h *high) Run(t *testing.T, ctx context.Context) { h.daprd.WaitUntilRunning(t, ctx) h.place.WaitUntilRunning(t, ctx) t.Run("service invocation", func(t *testing.T) { h.daprd.HTTPGet2xx(t, ctx, "/v1.0/invoke/myapp/method/hi") metrics := h.daprd.Metrics(t, ctx) assert.Equal(t, 1, int(metrics["dapr_http_server_request_count|app_id:myapp|method:GET|path:/v1.0/invoke/myapp/method/hi|status:200"])) assert.Equal(t, 1, int(metrics["dapr_http_server_response_count|app_id:myapp|method:GET|path:/v1.0/healthz|status:204"])) assert.Equal(t, 1, int(metrics["dapr_http_server_response_count|app_id:myapp|method:GET|path:/v1.0/invoke/myapp/method/hi|status:200"])) }) t.Run("state stores", func(t *testing.T) { body := `[{"key":"myvalue", "value":"hello world"}]` h.daprd.HTTPPost2xx(t, ctx, "/v1.0/state/mystore", strings.NewReader(body), "content-type", "application/json") h.daprd.HTTPGet2xx(t, ctx, "/v1.0/state/mystore/myvalue") metrics := h.daprd.Metrics(t, ctx) assert.Equal(t, 1, int(metrics["dapr_http_server_request_count|app_id:myapp|method:POST|path:/v1.0/state/mystore|status:204"])) assert.Equal(t, 1, int(metrics["dapr_http_server_request_count|app_id:myapp|method:GET|path:/v1.0/state/mystore|status:200"])) }) t.Run("actor invocation", func(t *testing.T) { h.daprd.HTTPPost2xx(t, ctx, "/v1.0/actors/myactortype/myactorid/method/foo", nil, "content-type", "application/json") metrics := h.daprd.Metrics(t, ctx) assert.Equal(t, 1, int(metrics["dapr_http_server_request_count|app_id:myapp|method:POST|path:/v1.0/actors/myactortype/{id}/method|status:200"])) assert.NotContains(t, metrics, "method:InvokeActor/myactortype") }) }
mikeee/dapr
tests/integration/suite/daprd/metrics/http/cardinality/high.go
GO
mit
3,807
/* 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 cardinality import ( "context" "fmt" "net/http" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/dapr/dapr/tests/integration/framework/process/placement" "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(low)) } // low tests daprd metrics for the HTTP server configured with low cardinality type low struct { daprd *daprd.Daprd place *placement.Placement } func (l *low) Setup(t *testing.T) []framework.Option { app := app.New(t, app.WithHandlerFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`OK`)) }), app.WithHandlerFunc("/hi", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "OK") }), app.WithHandlerFunc("/dapr/config", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`{"entities": ["myactortype"]}`)) }), ) l.place = placement.New(t) l.daprd = daprd.New(t, daprd.WithAppPort(app.Port()), daprd.WithAppProtocol("http"), daprd.WithAppID("myapp"), daprd.WithPlacementAddresses(l.place.Address()), daprd.WithInMemoryActorStateStore("mystore"), daprd.WithConfigManifests(t, ` apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: lowcardinality spec: metrics: http: increasedCardinality: false `), ) return []framework.Option{ framework.WithProcesses(app, l.daprd, l.place), } } func (l *low) Run(t *testing.T, ctx context.Context) { l.daprd.WaitUntilRunning(t, ctx) l.place.WaitUntilRunning(t, ctx) t.Run("service invocation", func(t *testing.T) { l.daprd.HTTPGet2xx(t, ctx, "/v1.0/invoke/myapp/method/hi") metrics := l.daprd.Metrics(t, ctx) assert.Equal(t, 1, int(metrics["dapr_http_server_request_count|app_id:myapp|method:InvokeService/myapp|status:200"])) assert.NotContains(t, metrics, "dapr_http_server_response_count|app_id:myapp|method:GET|path:/v1.0/invoke/myapp/method/hi|status:200") assert.NotContains(t, metrics, "dapr_http_server_response_count|app_id:myapp|method:GET|path:/v1.0/healthz|status:204 1.000000") }) t.Run("state stores", func(t *testing.T) { body := `[{"key":"myvalue", "value":"hello world"}]` l.daprd.HTTPPost2xx(t, ctx, "/v1.0/state/mystore", strings.NewReader(body), "content-type", "application/json") l.daprd.HTTPGet2xx(t, ctx, "/v1.0/state/mystore/myvalue") metrics := l.daprd.Metrics(t, ctx) assert.Equal(t, 1, int(metrics["dapr_http_server_request_count|app_id:myapp|method:SaveState|status:204"])) assert.Equal(t, 1, int(metrics["dapr_http_server_request_count|app_id:myapp|method:GetState|status:200"])) }) t.Run("actor invocation", func(t *testing.T) { l.daprd.HTTPPost2xx(t, ctx, "/v1.0/actors/myactortype/myactorid/method/foo", nil, "content-type", "application/json") metrics := l.daprd.Metrics(t, ctx) assert.Equal(t, 1, int(metrics["dapr_http_server_request_count|app_id:myapp|method:InvokeActor/myactortype|status:200"])) assert.NotContains(t, metrics, "method:InvokeActor/myactortype.") }) }
mikeee/dapr
tests/integration/suite/daprd/metrics/http/cardinality/low.go
GO
mit
3,730
/* 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 http import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/metrics/http/cardinality" _ "github.com/dapr/dapr/tests/integration/suite/daprd/metrics/http/pathmatching" )
mikeee/dapr
tests/integration/suite/daprd/metrics/http/http.go
GO
mit
749
/* 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 pathmatching import ( "context" "fmt" "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/app" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(defaultCardinality)) } // defaultCardinality tests daprd metrics for the HTTP server configured with path matching and default cardinality. type defaultCardinality struct { daprd *daprd.Daprd } func (h *defaultCardinality) Setup(t *testing.T) []framework.Option { app := app.New(t, app.WithHandlerFunc("/orders/{orderID}", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "OK") }), ) h.daprd = daprd.New(t, daprd.WithAppPort(app.Port()), daprd.WithAppProtocol("http"), daprd.WithAppID("myapp"), daprd.WithInMemoryStateStore("mystore"), daprd.WithConfigManifests(t, ` apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: pathMatching spec: metrics: enabled: true `), ) return []framework.Option{ framework.WithProcesses(app, h.daprd), } } func (h *defaultCardinality) Run(t *testing.T, ctx context.Context) { h.daprd.WaitUntilRunning(t, ctx) t.Run("service invocation - default", func(t *testing.T) { h.daprd.HTTPGet2xx(t, ctx, "/v1.0/invoke/myapp/method/orders/123") metrics := h.daprd.Metrics(t, ctx) assert.Equal(t, 1, int(metrics["dapr_http_server_request_count|app_id:myapp|method:GET|path:/v1.0/invoke/myapp/method/orders/123|status:200"])) }) }
mikeee/dapr
tests/integration/suite/daprd/metrics/http/pathmatching/default.go
GO
mit
2,169
/* 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 pathmatching import ( "context" "fmt" "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/app" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(highCardinality)) } // highCardinality tests daprd metrics for the HTTP server configured with path matching and increased cardinality. type highCardinality struct { daprd *daprd.Daprd } func (h *highCardinality) Setup(t *testing.T) []framework.Option { app := app.New(t, app.WithHandlerFunc("/orders/{orderID}", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "OK") }), app.WithHandlerFunc("/orders", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "OK") }), app.WithHandlerFunc("/items/{itemID}", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "OK") }), app.WithHandlerFunc("/basket", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "OK") }), ) h.daprd = daprd.New(t, daprd.WithAppPort(app.Port()), daprd.WithAppProtocol("http"), daprd.WithAppID("myapp"), daprd.WithInMemoryStateStore("mystore"), daprd.WithConfigManifests(t, ` apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: pathMatching spec: metrics: http: increasedCardinality: true pathMatching: ingress: - /v1.0/invoke/myapp/method/orders/{orderID} - /v1.0/invoke/myapp/method/basket egress: - /v1.0/invoke/myapp/method/orders/1234 - /v1.0/invoke/myapp/method/orders/{orderID} - /v1.0/invoke/myapp/method/orders - /v1.0/invoke/myapp/method/basket `), ) return []framework.Option{ framework.WithProcesses(app, h.daprd), } } func (h *highCardinality) Run(t *testing.T, ctx context.Context) { h.daprd.WaitUntilRunning(t, ctx) t.Run("service invocation - matches ingres/egress", func(t *testing.T) { h.daprd.HTTPGet2xx(t, ctx, "/v1.0/invoke/myapp/method/orders/1111") h.daprd.HTTPGet2xx(t, ctx, "/v1.0/invoke/myapp/method/orders/1234") h.daprd.HTTPGet2xx(t, ctx, "/v1.0/invoke/myapp/method/orders") h.daprd.HTTPGet2xx(t, ctx, "/v1.0/invoke/myapp/method/basket") metrics := h.daprd.Metrics(t, ctx) assert.Equal(t, 1, int(metrics["dapr_http_server_request_count|app_id:myapp|method:GET|path:/v1.0/invoke/myapp/method/orders/{orderID}|status:200"])) assert.Equal(t, 1, int(metrics["dapr_http_server_request_count|app_id:myapp|method:GET|path:/v1.0/invoke/myapp/method/orders/1234|status:200"])) assert.Equal(t, 1, int(metrics["dapr_http_server_request_count|app_id:myapp|method:GET|path:/v1.0/invoke/myapp/method/orders|status:200"])) assert.Equal(t, 1, int(metrics["dapr_http_server_request_count|app_id:myapp|method:GET|path:/v1.0/invoke/myapp/method/basket|status:200"])) assert.Equal(t, 1, int(metrics["dapr_http_server_response_count|app_id:myapp|method:GET|path:/v1.0/healthz|status:204"])) assert.Equal(t, 1, int(metrics["dapr_http_server_response_count|app_id:myapp|method:GET|path:/v1.0/invoke/myapp/method/orders/{orderID}|status:200"])) }) t.Run("service invocation - no match", func(t *testing.T) { h.daprd.HTTPGet2xx(t, ctx, "/v1.0/invoke/myapp/method/items/123") metrics := h.daprd.Metrics(t, ctx) assert.Equal(t, 1, int(metrics["dapr_http_server_request_count|app_id:myapp|method:GET|path:/v1.0/invoke/myapp/method/items/123|status:200"])) assert.Equal(t, 1, int(metrics["dapr_http_server_response_count|app_id:myapp|method:GET|path:/v1.0/healthz|status:204"])) assert.Equal(t, 1, int(metrics["dapr_http_server_response_count|app_id:myapp|method:GET|path:/v1.0/invoke/myapp/method/items/123|status:200"])) }) }
mikeee/dapr
tests/integration/suite/daprd/metrics/http/pathmatching/high.go
GO
mit
4,367
/* 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 pathmatching import ( "context" "fmt" "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/app" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(lowCardinality)) } // lowCardinality tests daprd metrics for the HTTP server configured with path matching and low cardinality. type lowCardinality struct { daprd *daprd.Daprd } func (h *lowCardinality) Setup(t *testing.T) []framework.Option { app := app.New(t, app.WithHandlerFunc("/orders/{orderID}", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "OK") }), app.WithHandlerFunc("/orders", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "OK") }), app.WithHandlerFunc("/items/{itemID}", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "OK") }), app.WithHandlerFunc("/basket", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "OK") }), ) h.daprd = daprd.New(t, daprd.WithAppPort(app.Port()), daprd.WithAppProtocol("http"), daprd.WithAppID("myapp"), daprd.WithInMemoryStateStore("mystore"), daprd.WithConfigManifests(t, ` apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: pathMatching spec: metrics: http: increasedCardinality: false pathMatching: ingress: - /v1.0/invoke/myapp/method/orders/{orderID} - /v1.0/invoke/myapp/method/basket egress: - /v1.0/invoke/myapp/method/orders/1234 - /v1.0/invoke/myapp/method/orders/{orderID} - /v1.0/invoke/myapp/method/orders - /v1.0/invoke/myapp/method/basket `), ) return []framework.Option{ framework.WithProcesses(app, h.daprd), } } func (h *lowCardinality) Run(t *testing.T, ctx context.Context) { h.daprd.WaitUntilRunning(t, ctx) t.Run("service invocation - matches ingres/egress", func(t *testing.T) { h.daprd.HTTPGet2xx(t, ctx, "/v1.0/invoke/myapp/method/orders/1111") h.daprd.HTTPGet2xx(t, ctx, "/v1.0/invoke/myapp/method/orders/1234") h.daprd.HTTPGet2xx(t, ctx, "/v1.0/invoke/myapp/method/orders") h.daprd.HTTPGet2xx(t, ctx, "/v1.0/invoke/myapp/method/basket") metrics := h.daprd.Metrics(t, ctx) assert.Equal(t, 1, int(metrics["dapr_http_server_request_count|app_id:myapp|method:GET|path:/v1.0/invoke/myapp/method/orders/{orderID}|status:200"])) assert.Equal(t, 1, int(metrics["dapr_http_server_request_count|app_id:myapp|method:GET|path:/v1.0/invoke/myapp/method/orders/1234|status:200"])) assert.Equal(t, 1, int(metrics["dapr_http_server_request_count|app_id:myapp|method:GET|path:/v1.0/invoke/myapp/method/orders|status:200"])) assert.Equal(t, 1, int(metrics["dapr_http_server_request_count|app_id:myapp|method:GET|path:/v1.0/invoke/myapp/method/basket|status:200"])) }) t.Run("service invocation - no match - catch all bucket", func(t *testing.T) { h.daprd.HTTPGet2xx(t, ctx, "/v1.0/invoke/myapp/method/items/123") metrics := h.daprd.Metrics(t, ctx) assert.Equal(t, 1, int(metrics["dapr_http_server_request_count|app_id:myapp|method:GET|path:/|status:200"])) }) }
mikeee/dapr
tests/integration/suite/daprd/metrics/http/pathmatching/low.go
GO
mit
3,795
/* 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 metrics import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/metrics/grpc" _ "github.com/dapr/dapr/tests/integration/suite/daprd/metrics/http" )
mikeee/dapr
tests/integration/suite/daprd/metrics/metrics.go
GO
mit
727
/* 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 metrics 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" "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/framework/process/placement" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(workflow)) } // workflow tests daprd metrics for workflows type workflow struct { daprd *daprd.Daprd place *placement.Placement } func (w *workflow) Setup(t *testing.T) []framework.Option { w.place = placement.New(t) app := app.New(t) w.daprd = daprd.New(t, daprd.WithAppPort(app.Port()), daprd.WithAppProtocol("http"), daprd.WithAppID("myapp"), daprd.WithPlacementAddresses(w.place.Address()), daprd.WithInMemoryActorStateStore("mystore"), ) return []framework.Option{ framework.WithProcesses(w.place, app, w.daprd), } } func (w *workflow) Run(t *testing.T, ctx context.Context) { w.place.WaitUntilRunning(t, ctx) w.daprd.WaitUntilRunning(t, ctx) // Register workflow r := task.NewTaskRegistry() r.AddActivityN("activity_success", func(ctx task.ActivityContext) (any, error) { return "success", nil }) r.AddActivityN("activity_failure", func(ctx task.ActivityContext) (any, error) { return nil, fmt.Errorf("failure") }) r.AddOrchestratorN("workflow", func(ctx *task.OrchestrationContext) (any, error) { var input string if err := ctx.GetInput(&input); err != nil { return nil, err } activityName := input err := ctx.CallActivity(activityName).Await(nil) if err != nil { return nil, err } return nil, nil }) taskhubClient := client.NewTaskHubGrpcClient(w.daprd.GRPCConn(t, ctx), backend.DefaultLogger()) taskhubClient.StartWorkItemListener(ctx, r) t.Run("successful workflow execution", func(t *testing.T) { id, err := taskhubClient.ScheduleNewOrchestration(ctx, "workflow", api.WithInput("activity_success")) require.NoError(t, err) metadata, err := taskhubClient.WaitForOrchestrationCompletion(ctx, id, api.WithFetchPayloads(true)) require.NoError(t, err) assert.True(t, metadata.IsComplete()) // Verify metrics metrics := w.daprd.Metrics(t, ctx) assert.Equal(t, 1, int(metrics["dapr_runtime_workflow_operation_count|app_id:myapp|namespace:|operation:create_workflow|status:success"])) assert.Equal(t, 1, int(metrics["dapr_runtime_workflow_execution_count|app_id:myapp|namespace:|status:success|workflow_name:workflow"])) assert.Equal(t, 1, int(metrics["dapr_runtime_workflow_activity_execution_count|activity_name:activity_success|app_id:myapp|namespace:|status:success"])) assert.GreaterOrEqual(t, 1, int(metrics["dapr_runtime_workflow_execution_latency|app_id:myapp|namespace:|status:success|workflow_name:workflow"])) assert.GreaterOrEqual(t, 1, int(metrics["dapr_runtime_workflow_scheduling_latency|app_id:myapp|namespace:|workflow_name:workflow"])) }) t.Run("failed workflow execution", func(t *testing.T) { id, err := taskhubClient.ScheduleNewOrchestration(ctx, "workflow", api.WithInput("activity_failure")) require.NoError(t, err) metadata, err := taskhubClient.WaitForOrchestrationCompletion(ctx, id, api.WithFetchPayloads(true)) require.NoError(t, err) assert.True(t, metadata.IsComplete()) // Verify metrics metrics := w.daprd.Metrics(t, ctx) assert.Equal(t, 2, int(metrics["dapr_runtime_workflow_operation_count|app_id:myapp|namespace:|operation:create_workflow|status:success"])) assert.Equal(t, 1, int(metrics["dapr_runtime_workflow_execution_count|app_id:myapp|namespace:|status:failed|workflow_name:workflow"])) assert.Equal(t, 1, int(metrics["dapr_runtime_workflow_activity_execution_count|activity_name:activity_failure|app_id:myapp|namespace:|status:failed"])) }) }
mikeee/dapr
tests/integration/suite/daprd/metrics/workflow.go
GO
mit
4,621
/* 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 app import ( "context" "os" "path/filepath" "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/suite" ) func init() { suite.Register(new(missing)) } // missing ensures that a config ignores a missing middleware component. type missing struct { daprd *daprd.Daprd } func (m *missing) Setup(t *testing.T) []framework.Option { configFile := filepath.Join(t.TempDir(), "config.yaml") require.NoError(t, os.WriteFile(configFile, []byte(` apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: uppercase spec: appHttpPipeline: handlers: - name: uppercase type: middleware.http.uppercase `), 0o600)) m.daprd = daprd.New(t, daprd.WithConfigs(configFile)) return []framework.Option{ framework.WithProcesses(m.daprd), } } func (m *missing) Run(t *testing.T, ctx context.Context) { m.daprd.WaitUntilRunning(t, ctx) }
mikeee/dapr
tests/integration/suite/daprd/middleware/http/app/missing.go
GO
mit
1,587
/* 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 app import ( "context" "fmt" "io" "net/http" "os" "path/filepath" "testing" "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/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(order)) } type order struct { daprd1 *daprd.Daprd daprd2 *daprd.Daprd } func (o *order) Setup(t *testing.T) []framework.Option { configFile := filepath.Join(t.TempDir(), "config.yaml") require.NoError(t, os.WriteFile(configFile, []byte(` apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: order spec: appHttpPipeline: handlers: - name: routeralias1 type: middleware.http.routeralias - name: routeralias2 type: middleware.http.routeralias `), 0o600)) srv := func(id string) *prochttp.HTTP { handler := http.NewServeMux() handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "%s:%s", id, r.URL.Path) }) return prochttp.New(t, prochttp.WithHandler(handler)) } srv1 := srv("daprd1") srv2 := srv("daprd2") o.daprd1 = daprd.New(t, daprd.WithAppPort(srv1.Port()), ) o.daprd2 = daprd.New(t, daprd.WithConfigs(configFile), daprd.WithResourceFiles(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: routeralias1 spec: type: middleware.http.routeralias version: v1 metadata: - name: routes value: '{ "/helloworld": "/foobar", "/xyz": "/abc" }' --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: routeralias2 spec: type: middleware.http.routeralias version: v1 metadata: - name: routes value: '{ "/helloworld": "/xyz", "/foobar": "/abc" }' `), daprd.WithAppPort(srv2.Port()), ) return []framework.Option{ framework.WithProcesses(srv1, srv2, o.daprd1, o.daprd2), } } func (o *order) Run(t *testing.T, ctx context.Context) { o.daprd1.WaitUntilRunning(t, ctx) o.daprd2.WaitUntilRunning(t, ctx) client := util.HTTPClient(t) o.doReq(t, ctx, client, fmt.Sprintf("/v1.0/invoke/%s/method/helloworld", o.daprd2.AppID()), "daprd2:/abc") } func (o *order) doReq(t require.TestingT, ctx context.Context, client *http.Client, path, expect string) { url := fmt.Sprintf("http://localhost:%d/%s", o.daprd1.HTTPPort(), path) req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, nil) require.NoError(t, err) resp, err := client.Do(req) require.NoError(t, err) defer resp.Body.Close() assert.Equal(t, http.StatusOK, resp.StatusCode) body, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, expect, string(body)) }
mikeee/dapr
tests/integration/suite/daprd/middleware/http/app/order.go
GO
mit
3,368
/* 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 app import ( "context" "fmt" "io" "net/http" "os" "path/filepath" "strings" "testing" "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/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(uppercase)) } type uppercase struct { daprd1 *daprd.Daprd daprd2 *daprd.Daprd } func (u *uppercase) Setup(t *testing.T) []framework.Option { configFile := filepath.Join(t.TempDir(), "config.yaml") require.NoError(t, os.WriteFile(configFile, []byte(` apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: uppercase spec: appHttpPipeline: handlers: - name: uppercase type: middleware.http.uppercase `), 0o600)) handler := http.NewServeMux() handler.HandleFunc("/", func(http.ResponseWriter, *http.Request) {}) handler.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) { _, err := io.Copy(w, r.Body) require.NoError(t, err) }) srv := prochttp.New(t, prochttp.WithHandler(handler)) u.daprd1 = daprd.New(t, daprd.WithConfigs(configFile), daprd.WithResourceFiles(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: uppercase spec: type: middleware.http.uppercase version: v1 `), daprd.WithAppPort(srv.Port()), ) u.daprd2 = daprd.New(t, daprd.WithAppPort(srv.Port())) return []framework.Option{ framework.WithProcesses(srv, u.daprd1, u.daprd2), } } func (u *uppercase) Run(t *testing.T, ctx context.Context) { u.daprd1.WaitUntilRunning(t, ctx) u.daprd2.WaitUntilRunning(t, ctx) client := util.HTTPClient(t) url := fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/foo", u.daprd1.HTTPPort(), u.daprd2.AppID()) req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader("hello")) require.NoError(t, err) resp, err := client.Do(req) require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) assert.Equal(t, "hello", string(body)) url = fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/foo", u.daprd1.HTTPPort(), u.daprd1.AppID()) req, err = http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader("hello")) require.NoError(t, err) resp, err = client.Do(req) require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) body, err = io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) assert.Equal(t, "HELLO", string(body)) url = fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/foo", u.daprd2.HTTPPort(), u.daprd1.AppID()) req, err = http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader("hello")) require.NoError(t, err) resp, err = client.Do(req) require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) body, err = io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) assert.Equal(t, "HELLO", string(body)) }
mikeee/dapr
tests/integration/suite/daprd/middleware/http/app/uppercase.go
GO
mit
3,787
/* 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 http import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/middleware/http/app" )
mikeee/dapr
tests/integration/suite/daprd/middleware/http/http.go
GO
mit
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 implieh. See the License for the specific language governing permissions and limitations under the License. */ package http import ( "context" "os" "path/filepath" "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/suite" ) func init() { suite.Register(new(missing)) } // missing ensures that a config ignores a missing middleware component. type missing struct { daprd *daprd.Daprd } func (m *missing) Setup(t *testing.T) []framework.Option { configFile := filepath.Join(t.TempDir(), "config.yaml") require.NoError(t, os.WriteFile(configFile, []byte(` apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: uppercase spec: httpPipeline: handlers: - name: uppercase type: middleware.http.uppercase `), 0o600)) m.daprd = daprd.New(t, daprd.WithConfigs(configFile)) return []framework.Option{ framework.WithProcesses(m.daprd), } } func (m *missing) Run(t *testing.T, ctx context.Context) { m.daprd.WaitUntilRunning(t, ctx) }
mikeee/dapr
tests/integration/suite/daprd/middleware/http/missing.go
GO
mit
1,585
/* 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 http import ( "context" "fmt" "io" nethttp "net/http" "os" "path/filepath" "testing" "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/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(order)) } type order struct { daprd1 *daprd.Daprd daprd2 *daprd.Daprd } func (o *order) Setup(t *testing.T) []framework.Option { configFile := filepath.Join(t.TempDir(), "config.yaml") require.NoError(t, os.WriteFile(configFile, []byte(` apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: order spec: httpPipeline: handlers: - name: routeralias1 type: middleware.http.routeralias - name: routeralias2 type: middleware.http.routeralias `), 0o600)) srv := func(id string) *prochttp.HTTP { handler := nethttp.NewServeMux() handler.HandleFunc("/", func(w nethttp.ResponseWriter, r *nethttp.Request) { fmt.Fprintf(w, "%s:%s", id, r.URL.Path) }) return prochttp.New(t, prochttp.WithHandler(handler)) } srv1 := srv("daprd1") srv2 := srv("daprd2") o.daprd1 = daprd.New(t, daprd.WithAppPort(srv1.Port()), ) o.daprd2 = daprd.New(t, daprd.WithConfigs(configFile), daprd.WithResourceFiles(fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: routeralias1 spec: type: middleware.http.routeralias version: v1 metadata: - name: routes value: '{ "/helloworld": "/v1.0/invoke/%[1]s/method/foobar" }' --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: routeralias2 spec: type: middleware.http.routeralias version: v1 metadata: - name: routes value: '{ "/helloworld": "/v1.0/invoke/%[1]s/method/barfoo", "/v1.0/invoke/%[1]s/method/foobar": "/v1.0/invoke/%[1]s/method/abc" }' `, o.daprd1.AppID())), daprd.WithAppPort(srv2.Port()), ) return []framework.Option{ framework.WithProcesses(srv1, srv2, o.daprd1, o.daprd2), } } func (o *order) Run(t *testing.T, ctx context.Context) { o.daprd1.WaitUntilRunning(t, ctx) o.daprd2.WaitUntilRunning(t, ctx) client := util.HTTPClient(t) o.doReq(t, ctx, client, "helloworld", "daprd1:/abc") } func (o *order) doReq(t require.TestingT, ctx context.Context, client *nethttp.Client, path, expect string) { url := fmt.Sprintf("http://localhost:%d/%s", o.daprd2.HTTPPort(), path) req, err := nethttp.NewRequestWithContext(ctx, nethttp.MethodPost, url, nil) require.NoError(t, err) resp, err := client.Do(req) require.NoError(t, err) defer resp.Body.Close() assert.Equal(t, nethttp.StatusOK, resp.StatusCode) body, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, expect, string(body)) }
mikeee/dapr
tests/integration/suite/daprd/middleware/http/order.go
GO
mit
3,451
/* 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 http import ( "context" "fmt" "io" nethttp "net/http" "os" "path/filepath" "strings" "testing" "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/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(uppercase)) } type uppercase struct { daprd1 *daprd.Daprd daprd2 *daprd.Daprd daprd3 *daprd.Daprd } func (u *uppercase) Setup(t *testing.T) []framework.Option { configFile := filepath.Join(t.TempDir(), "config.yaml") require.NoError(t, os.WriteFile(configFile, []byte(` apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: uppercase spec: httpPipeline: handlers: - name: uppercase type: middleware.http.uppercase `), 0o600)) handler := nethttp.NewServeMux() handler.HandleFunc("/", func(nethttp.ResponseWriter, *nethttp.Request) {}) handler.HandleFunc("/foo", func(w nethttp.ResponseWriter, r *nethttp.Request) { _, err := io.Copy(w, r.Body) require.NoError(t, err) }) srv := prochttp.New(t, prochttp.WithHandler(handler)) u.daprd1 = daprd.New(t, daprd.WithConfigs(configFile), daprd.WithResourceFiles(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: uppercase spec: type: middleware.http.uppercase version: v1 `), daprd.WithAppPort(srv.Port()), ) u.daprd2 = daprd.New(t, daprd.WithAppPort(srv.Port())) u.daprd3 = daprd.New(t, daprd.WithAppPort(srv.Port())) return []framework.Option{ framework.WithProcesses(srv, u.daprd1, u.daprd2, u.daprd3), } } func (u *uppercase) Run(t *testing.T, ctx context.Context) { u.daprd1.WaitUntilRunning(t, ctx) u.daprd2.WaitUntilRunning(t, ctx) u.daprd3.WaitUntilRunning(t, ctx) client := util.HTTPClient(t) url := fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/foo", u.daprd1.HTTPPort(), u.daprd1.AppID()) req, err := nethttp.NewRequestWithContext(ctx, nethttp.MethodPost, url, strings.NewReader("hello")) require.NoError(t, err) resp, err := client.Do(req) require.NoError(t, err) assert.Equal(t, nethttp.StatusOK, resp.StatusCode) body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) assert.Equal(t, "HELLO", string(body)) url = fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/foo", u.daprd1.HTTPPort(), u.daprd2.AppID()) req, err = nethttp.NewRequestWithContext(ctx, nethttp.MethodPost, url, strings.NewReader("hello")) require.NoError(t, err) resp, err = client.Do(req) require.NoError(t, err) assert.Equal(t, nethttp.StatusOK, resp.StatusCode) body, err = io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) assert.Equal(t, "HELLO", string(body)) url = fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/foo", u.daprd2.HTTPPort(), u.daprd1.AppID()) req, err = nethttp.NewRequestWithContext(ctx, nethttp.MethodPost, url, strings.NewReader("hello")) require.NoError(t, err) resp, err = client.Do(req) require.NoError(t, err) assert.Equal(t, nethttp.StatusOK, resp.StatusCode) body, err = io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) assert.Equal(t, "hello", string(body)) url = fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/foo", u.daprd2.HTTPPort(), u.daprd3.AppID()) req, err = nethttp.NewRequestWithContext(ctx, nethttp.MethodPost, url, strings.NewReader("hello")) require.NoError(t, err) resp, err = client.Do(req) require.NoError(t, err) assert.Equal(t, nethttp.StatusOK, resp.StatusCode) body, err = io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) assert.Equal(t, "hello", string(body)) }
mikeee/dapr
tests/integration/suite/daprd/middleware/http/uppercase.go
GO
mit
4,434
/* 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 middleware import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/middleware/http" )
mikeee/dapr
tests/integration/suite/daprd/middleware/middleware.go
GO
mit
664
/* 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" "os" "path/filepath" "runtime" "strings" "testing" "time" "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/connectivity" "google.golang.org/grpc/credentials/insecure" "github.com/dapr/dapr/pkg/security" "github.com/dapr/dapr/tests/integration/framework" procdaprd "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/grpc/operator" "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(disable)) } // disable tests Kubernetes daprd with mTLS disabled. type disable struct { daprd *procdaprd.Daprd sentry *sentry.Sentry placement *placement.Placement operator *operator.Operator trustAnchors []byte } func (e *disable) Setup(t *testing.T) []framework.Option { e.sentry = sentry.New(t) bundle := e.sentry.CABundle() e.trustAnchors = bundle.TrustAnchors // Control plane services always serves with mTLS in kubernetes mode. taFile := filepath.Join(t.TempDir(), "ca.pem") require.NoError(t, os.WriteFile(taFile, bundle.TrustAnchors, 0o600)) e.placement = placement.New(t, placement.WithEnableTLS(true), placement.WithTrustAnchorsFile(taFile), placement.WithSentryAddress(e.sentry.Address()), ) e.operator = operator.New(t, operator.WithSentry(e.sentry)) e.daprd = procdaprd.New(t, procdaprd.WithAppID("my-app"), procdaprd.WithMode("kubernetes"), procdaprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(bundle.TrustAnchors))), procdaprd.WithSentryAddress(e.sentry.Address()), procdaprd.WithControlPlaneAddress(e.operator.Address(t)), procdaprd.WithDisableK8sSecretStore(true), procdaprd.WithPlacementAddresses(e.placement.Address()), // Disable mTLS procdaprd.WithEnableMTLS(false), ) return []framework.Option{ framework.WithProcesses(e.sentry, e.placement, e.operator, e.daprd), } } func (e *disable) Run(t *testing.T, ctx context.Context) { e.sentry.WaitUntilRunning(t, ctx) e.placement.WaitUntilRunning(t, ctx) e.daprd.WaitUntilRunning(t, ctx) t.Run("trying plain text connection to Dapr API should succeed", func(t *testing.T) { conn, err := grpc.DialContext(ctx, e.daprd.InternalGRPCAddress(), grpc.WithReturnConnectionError(), grpc.WithTransportCredentials(insecure.NewCredentials()), ) require.NoError(t, err) conn.Connect() assert.Equal(t, connectivity.Ready, conn.GetState()) require.NoError(t, conn.Close()) }) t.Run("trying mTLS connection to Dapr API should fail", func(t *testing.T) { sctx, cancel := context.WithCancel(ctx) secProv, err := security.New(sctx, security.Options{ SentryAddress: e.sentry.Address(), ControlPlaneTrustDomain: "localhost", ControlPlaneNamespace: "default", TrustAnchors: e.trustAnchors, AppID: "another-app", MTLSEnabled: true, }) require.NoError(t, err) secProvErr := make(chan error) go func() { secProvErr <- secProv.Run(sctx) }() t.Cleanup(func() { cancel() select { case <-time.After(5 * time.Second): t.Fatal("timed out waiting for security provider to stop") case err = <-secProvErr: require.NoError(t, err) } }) sec, err := secProv.Handler(sctx) require.NoError(t, err) myAppID, err := spiffeid.FromSegments(spiffeid.RequireTrustDomainFromString("public"), "ns", "default", "my-app") require.NoError(t, err) assert.Eventually(t, func() bool { gctx, gcancel := context.WithTimeout(ctx, time.Second) t.Cleanup(gcancel) _, err = grpc.DialContext(gctx, e.daprd.InternalGRPCAddress(), sec.GRPCDialOptionMTLS(myAppID), grpc.WithReturnConnectionError()) require.Error(t, err) if runtime.GOOS == "windows" { return !strings.Contains(err.Error(), "An existing connection was forcibly closed by the remote host.") } return true }, 5*time.Second, 10*time.Millisecond) require.ErrorContains(t, err, "tls: first record does not look like a TLS handshake") }) }
mikeee/dapr
tests/integration/suite/daprd/mtls/kubernetes/disable.go
GO
mit
4,915
/* 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" "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" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/credentials/insecure" "github.com/dapr/dapr/pkg/security" "github.com/dapr/dapr/tests/integration/framework" procdaprd "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/grpc/operator" "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(enable)) } // enable tests Kubernetes daprd with mTLS enabled. type enable struct { daprd *procdaprd.Daprd sentry *sentry.Sentry placement *placement.Placement operator *operator.Operator trustAnchors []byte } func (e *enable) Setup(t *testing.T) []framework.Option { e.sentry = sentry.New(t) bundle := e.sentry.CABundle() e.trustAnchors = bundle.TrustAnchors // Control plane services always serves with mTLS in kubernetes mode. taFile := filepath.Join(t.TempDir(), "ca.pem") require.NoError(t, os.WriteFile(taFile, bundle.TrustAnchors, 0o600)) e.placement = placement.New(t, placement.WithEnableTLS(true), placement.WithTrustAnchorsFile(taFile), placement.WithSentryAddress(e.sentry.Address()), ) e.operator = operator.New(t, operator.WithSentry(e.sentry)) e.daprd = procdaprd.New(t, procdaprd.WithAppID("my-app"), procdaprd.WithMode("kubernetes"), procdaprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(bundle.TrustAnchors))), procdaprd.WithSentryAddress(e.sentry.Address()), procdaprd.WithControlPlaneAddress(e.operator.Address(t)), procdaprd.WithDisableK8sSecretStore(true), procdaprd.WithPlacementAddresses(e.placement.Address()), // Enable mTLS procdaprd.WithEnableMTLS(true), ) return []framework.Option{ framework.WithProcesses(e.sentry, e.placement, e.operator, e.daprd), } } func (e *enable) Run(t *testing.T, ctx context.Context) { e.sentry.WaitUntilRunning(t, ctx) e.placement.WaitUntilRunning(t, ctx) e.daprd.WaitUntilRunning(t, ctx) t.Run("trying plain text connection to Dapr API should fail", func(t *testing.T) { gctx, gcancel := context.WithTimeout(ctx, time.Second) t.Cleanup(gcancel) _, err := grpc.DialContext(gctx, e.daprd.InternalGRPCAddress(), grpc.WithReturnConnectionError(), grpc.WithTransportCredentials(insecure.NewCredentials()), ) require.ErrorContains(t, err, "error reading server preface") }) t.Run("trying mTLS connection to Dapr API should succeed", func(t *testing.T) { sctx, cancel := context.WithCancel(ctx) secProv, err := security.New(sctx, security.Options{ SentryAddress: e.sentry.Address(), ControlPlaneTrustDomain: "localhost", ControlPlaneNamespace: "default", TrustAnchors: e.trustAnchors, AppID: "another-app", MTLSEnabled: true, }) require.NoError(t, err) secProvErr := make(chan error) go func() { secProvErr <- secProv.Run(sctx) }() t.Cleanup(func() { cancel() select { case <-time.After(5 * time.Second): t.Fatal("timed out waiting for security provider to stop") case err = <-secProvErr: require.NoError(t, err) } }) sec, err := secProv.Handler(sctx) require.NoError(t, err) myAppID, err := spiffeid.FromSegments(spiffeid.RequireTrustDomainFromString("public"), "ns", "default", "my-app") require.NoError(t, err) conn, err := grpc.DialContext(ctx, e.daprd.InternalGRPCAddress(), sec.GRPCDialOptionMTLS(myAppID), grpc.WithReturnConnectionError()) require.NoError(t, err) conn.Connect() assert.Equal(t, connectivity.Ready, conn.GetState()) require.NoError(t, conn.Close()) }) }
mikeee/dapr
tests/integration/suite/daprd/mtls/kubernetes/enable.go
GO
mit
4,593
/* 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 mtls import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/mtls/kubernetes" _ "github.com/dapr/dapr/tests/integration/suite/daprd/mtls/standalone" )
mikeee/dapr
tests/integration/suite/daprd/mtls/mtls.go
GO
mit
730
/* 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 mtls import ( "context" "crypto/rand" "crypto/x509" "encoding/pem" "math/big" "net/url" "sync" "sync/atomic" "testing" "time" "github.com/spiffe/go-spiffe/v2/spiffeid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/types/known/timestamppb" sentryv1pb "github.com/dapr/dapr/pkg/proto/sentry/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" "github.com/dapr/dapr/tests/integration/framework/process/grpc/sentry" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(renew)) } type renew struct { daprd *daprd.Daprd sentry *sentry.Sentry lock sync.Mutex renewDuration time.Duration renewCalled atomic.Int64 } func (r *renew) Setup(t *testing.T) []framework.Option { r.sentry = sentry.New(t, sentry.WithSignCertificateFn( func(_ context.Context, req *sentryv1pb.SignCertificateRequest) (*sentryv1pb.SignCertificateResponse, error) { r.lock.Lock() defer r.lock.Unlock() der, _ := pem.Decode(req.GetCertificateSigningRequest()) require.NotNil(t, der) csr, err := x509.ParseCertificateRequest(der.Bytes) require.NoError(t, err) cert := x509.Certificate{ SerialNumber: big.NewInt(1), PublicKey: csr.PublicKey, NotBefore: time.Now(), NotAfter: time.Now().Add(r.renewDuration), URIs: []*url.URL{ spiffeid.RequireFromString("spiffe://localhost/ns/default/" + r.daprd.AppID()).URL(), }, } signed, err := x509.CreateCertificate(rand.Reader, &cert, r.sentry.Bundle().IssChain[0], csr.PublicKey, r.sentry.Bundle().IssKey) require.NoError(t, err) signedPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: signed}) r.renewCalled.Add(1) return &sentryv1pb.SignCertificateResponse{ WorkloadCertificate: append(signedPEM, r.sentry.Bundle().IssChainPEM...), ValidUntil: timestamppb.New(time.Now().Add(r.renewDuration)), }, nil }, )) r.daprd = daprd.New(t, daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(r.sentry.Bundle().TrustAnchors))), daprd.WithSentryAddress(r.sentry.Address(t)), daprd.WithEnableMTLS(true), ) r.renewDuration = time.Millisecond * 10 return []framework.Option{ framework.WithProcesses(r.sentry, r.daprd), } } func (r *renew) Run(t *testing.T, ctx context.Context) { assert.Eventually(t, func() bool { return r.renewCalled.Load() > 5 }, time.Second*5, time.Millisecond*10) r.lock.Lock() called := r.renewCalled.Load() r.renewDuration = time.Hour * 24 r.lock.Unlock() assert.Eventually(t, func() bool { return r.renewCalled.Load() > called }, time.Second*5, time.Millisecond*10) assert.Equal(t, called+1, r.renewCalled.Load()) time.Sleep(time.Millisecond * 100) assert.Equal(t, called+1, r.renewCalled.Load()) }
mikeee/dapr
tests/integration/suite/daprd/mtls/renew.go
GO
mit
3,536
/* 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 standalone import ( "context" "runtime" "strings" "testing" "time" "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/connectivity" "google.golang.org/grpc/credentials/insecure" "github.com/dapr/dapr/pkg/security" "github.com/dapr/dapr/tests/integration/framework" procdaprd "github.com/dapr/dapr/tests/integration/framework/process/daprd" procplacement "github.com/dapr/dapr/tests/integration/framework/process/placement" procsentry "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(disable)) } // disable tests standalone with mTLS disabled. type disable struct { daprd *procdaprd.Daprd sentry *procsentry.Sentry placement *procplacement.Placement trustAnchors []byte } func (e *disable) Setup(t *testing.T) []framework.Option { e.sentry = procsentry.New(t) e.trustAnchors = e.sentry.CABundle().TrustAnchors e.placement = procplacement.New(t, procplacement.WithEnableTLS(false), procplacement.WithSentryAddress(e.sentry.Address()), ) e.daprd = procdaprd.New(t, procdaprd.WithAppID("my-app"), procdaprd.WithMode("standalone"), procdaprd.WithSentryAddress(e.sentry.Address()), procdaprd.WithPlacementAddresses(e.placement.Address()), // Disable mTLS procdaprd.WithEnableMTLS(false), ) return []framework.Option{ framework.WithProcesses(e.sentry, e.placement, e.daprd), } } func (e *disable) Run(t *testing.T, ctx context.Context) { e.placement.WaitUntilRunning(t, ctx) e.daprd.WaitUntilRunning(t, ctx) t.Run("trying plain text connection to Dapr API should succeed", func(t *testing.T) { conn, err := grpc.DialContext(ctx, e.daprd.InternalGRPCAddress(), grpc.WithReturnConnectionError(), grpc.WithTransportCredentials(insecure.NewCredentials()), ) require.NoError(t, err) conn.Connect() assert.Equal(t, connectivity.Ready, conn.GetState()) require.NoError(t, conn.Close()) }) t.Run("trying mTLS connection to Dapr API should fail", func(t *testing.T) { sctx, cancel := context.WithCancel(ctx) secProv, err := security.New(sctx, security.Options{ SentryAddress: e.sentry.Address(), ControlPlaneTrustDomain: "localhost", ControlPlaneNamespace: "default", TrustAnchors: e.trustAnchors, AppID: "another-app", MTLSEnabled: true, }) require.NoError(t, err) secProvErr := make(chan error) go func() { secProvErr <- secProv.Run(sctx) }() t.Cleanup(func() { cancel() select { case <-time.After(5 * time.Second): t.Fatal("timed out waiting for security provider to stop") case err = <-secProvErr: require.NoError(t, err) } }) sec, err := secProv.Handler(sctx) require.NoError(t, err) myAppID, err := spiffeid.FromSegments(spiffeid.RequireTrustDomainFromString("public"), "ns", "default", "my-app") require.NoError(t, err) assert.Eventually(t, func() bool { gctx, gcancel := context.WithTimeout(ctx, time.Second) t.Cleanup(gcancel) _, err = grpc.DialContext(gctx, e.daprd.InternalGRPCAddress(), sec.GRPCDialOptionMTLS(myAppID), grpc.WithReturnConnectionError()) require.Error(t, err) if runtime.GOOS == "windows" { return !strings.Contains(err.Error(), "An existing connection was forcibly closed by the remote host.") } return true }, 5*time.Second, 10*time.Millisecond) require.ErrorContains(t, err, "tls: first record does not look like a TLS handshake") }) }
mikeee/dapr
tests/integration/suite/daprd/mtls/standalone/disable.go
GO
mit
4,199
/* 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 standalone import ( "context" "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" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/credentials/insecure" "github.com/dapr/dapr/pkg/security" "github.com/dapr/dapr/tests/integration/framework" procdaprd "github.com/dapr/dapr/tests/integration/framework/process/daprd" "github.com/dapr/dapr/tests/integration/framework/process/exec" procplacement "github.com/dapr/dapr/tests/integration/framework/process/placement" procsentry "github.com/dapr/dapr/tests/integration/framework/process/sentry" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(enable)) } // enable tests standalone Dapr with mTLS enabled. type enable struct { daprd *procdaprd.Daprd sentry *procsentry.Sentry placement *procplacement.Placement trustAnchors []byte } func (e *enable) Setup(t *testing.T) []framework.Option { e.sentry = procsentry.New(t) bundle := e.sentry.CABundle() e.trustAnchors = bundle.TrustAnchors // Control plane services always serves with mTLS in kubernetes mode. taFile := filepath.Join(t.TempDir(), "ca.pem") require.NoError(t, os.WriteFile(taFile, bundle.TrustAnchors, 0o600)) e.placement = procplacement.New(t, procplacement.WithEnableTLS(true), procplacement.WithTrustAnchorsFile(taFile), procplacement.WithSentryAddress(e.sentry.Address()), ) e.daprd = procdaprd.New(t, procdaprd.WithAppID("my-app"), procdaprd.WithMode("standalone"), procdaprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(bundle.TrustAnchors))), procdaprd.WithSentryAddress(e.sentry.Address()), procdaprd.WithPlacementAddresses(e.placement.Address()), // Enable mTLS procdaprd.WithEnableMTLS(true), ) return []framework.Option{ framework.WithProcesses(e.sentry, e.placement, e.daprd), } } func (e *enable) Run(t *testing.T, ctx context.Context) { e.sentry.WaitUntilRunning(t, ctx) e.placement.WaitUntilRunning(t, ctx) e.daprd.WaitUntilRunning(t, ctx) t.Run("trying plain text connection to Dapr API should fail", func(t *testing.T) { gctx, gcancel := context.WithTimeout(ctx, time.Second) t.Cleanup(gcancel) _, err := grpc.DialContext(gctx, e.daprd.InternalGRPCAddress(), grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithReturnConnectionError(), ) require.ErrorContains(t, err, "error reading server preface:") }) t.Run("trying mTLS connection to Dapr API should succeed", func(t *testing.T) { sctx, cancel := context.WithCancel(ctx) secProv, err := security.New(sctx, security.Options{ SentryAddress: e.sentry.Address(), ControlPlaneTrustDomain: "localhost", ControlPlaneNamespace: "default", TrustAnchors: e.trustAnchors, AppID: "another-app", MTLSEnabled: true, }) require.NoError(t, err) secProvErr := make(chan error) go func() { secProvErr <- secProv.Run(sctx) }() t.Cleanup(func() { cancel() select { case <-time.After(5 * time.Second): t.Fatal("timed out waiting for security provider to stop") case err = <-secProvErr: require.NoError(t, err) } }) sec, err := secProv.Handler(sctx) require.NoError(t, err) myAppID, err := spiffeid.FromSegments(spiffeid.RequireTrustDomainFromString("public"), "ns", "default", "my-app") require.NoError(t, err) conn, err := grpc.DialContext(ctx, e.daprd.InternalGRPCAddress(), sec.GRPCDialOptionMTLS(myAppID), grpc.WithReturnConnectionError()) require.NoError(t, err) conn.Connect() assert.Equal(t, connectivity.Ready, conn.GetState()) require.NoError(t, conn.Close()) }) }
mikeee/dapr
tests/integration/suite/daprd/mtls/standalone/enable.go
GO
mit
4,360
apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: feature1 spec: features: - name: Feature1 enabled: true
mikeee/dapr
tests/integration/suite/daprd/multipleconfigs/fixtures/feature1.yaml
YAML
mit
135
apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: feature2 spec: features: - name: Feature2 enabled: true
mikeee/dapr
tests/integration/suite/daprd/multipleconfigs/fixtures/feature2.yaml
YAML
mit
135
/* 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 multipleconfigs import ( "context" "encoding/json" "fmt" "net/http" "path/filepath" "runtime" "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(multipleconfigs)) } // multipleconfigs tests instantiating daprd with multiple configuration files. type multipleconfigs struct { proc *procdaprd.Daprd } func (m *multipleconfigs) Setup(t *testing.T) []framework.Option { _, goFile, _, ok := runtime.Caller(0) require.True(t, ok, "failed to get current file") fixtures := filepath.Join(filepath.Dir(goFile), "fixtures") m.proc = procdaprd.New(t, procdaprd.WithConfigs( filepath.Join(fixtures, "feature1.yaml"), filepath.Join(fixtures, "feature2.yaml"), ), ) return []framework.Option{ framework.WithProcesses(m.proc), } } func (m *multipleconfigs) Run(t *testing.T, ctx context.Context) { m.proc.WaitUntilRunning(t, ctx) // There are not many options in the Configuration YAML that we can test in an integration test // The simplest one to test is the preview features, since they are exposedd by the /metadata endpoint // These are overridde, so we should only have Feature2 enabled here t.Run("second config overrides features", func(t *testing.T) { features := m.loadFeatures(t, ctx) assert.Contains(t, features, "Feature2") assert.NotContains(t, features, "Feature1") }) } func (m *multipleconfigs) loadFeatures(t *testing.T, ctx context.Context) []string { t.Helper() ctx, cancel := context.WithTimeout(ctx, time.Second*5) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://localhost:%d/v1.0/metadata", m.proc.HTTPPort()), nil) require.NoError(t, err) resp, err := util.HTTPClient(t).Do(req) require.NoError(t, err) defer resp.Body.Close() body := struct { EnabledFeatures []string `json:"enabledFeatures"` }{} err = json.NewDecoder(resp.Body).Decode(&body) require.NoError(t, err) return body.EnabledFeatures }
mikeee/dapr
tests/integration/suite/daprd/multipleconfigs/multipleconfigs.go
GO
mit
2,804
/* 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 grpc import ( "context" "sync" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "github.com/dapr/dapr/pkg/proto/common/v1" 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" "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 lock sync.Mutex msg []byte } func (o *basic) Setup(t *testing.T) []framework.Option { onTopicEvent := func(ctx context.Context, in *runtimev1pb.TopicEventRequest) (*runtimev1pb.TopicEventResponse, error) { o.lock.Lock() defer o.lock.Unlock() o.msg = in.GetData() return &runtimev1pb.TopicEventResponse{ Status: runtimev1pb.TopicEventResponse_SUCCESS, }, nil } srv1 := app.New(t, app.WithOnTopicEventFn(onTopicEvent)) o.daprd = daprd.New(t, daprd.WithAppID("outboxtest"), daprd.WithAppPort(srv1.Port(t)), daprd.WithAppProtocol("grpc"), daprd.WithResourceFiles(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mystore spec: type: state.in-memory version: v1 metadata: - name: outboxPublishPubsub value: "mypubsub" - name: outboxPublishTopic value: "test" `, ` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: 'mypubsub' spec: type: pubsub.in-memory version: v1 `, ` apiVersion: dapr.io/v2alpha1 kind: Subscription metadata: name: 'order' spec: topic: 'test' routes: default: '/test' pubsubname: 'mypubsub' scopes: - outboxtest `)) return []framework.Option{ framework.WithProcesses(srv1, o.daprd), } } func (o *basic) Run(t *testing.T, ctx context.Context) { o.daprd.WaitUntilRunning(t, ctx) conn, err := grpc.DialContext(ctx, o.daprd.GRPCAddress(), grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock()) require.NoError(t, err) t.Cleanup(func() { require.NoError(t, conn.Close()) }) _, err = runtimev1pb.NewDaprClient(conn).ExecuteStateTransaction(ctx, &runtimev1pb.ExecuteStateTransactionRequest{ StoreName: "mystore", Operations: []*runtimev1pb.TransactionalStateOperation{ { OperationType: "upsert", Request: &common.StateItem{ Key: "1", Value: []byte("2"), }, }, }, }) require.NoError(t, err) assert.Eventually(t, func() bool { o.lock.Lock() defer o.lock.Unlock() return string(o.msg) == "2" }, time.Second*5, time.Millisecond*10, "failed to receive message in time") }
mikeee/dapr
tests/integration/suite/daprd/outbox/grpc/basic.go
GO
mit
3,244
/* 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 grpc import ( "context" "sync" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "github.com/dapr/dapr/pkg/proto/common/v1" 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" "github.com/dapr/dapr/tests/integration/framework/process/grpc/app" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(projection)) } type projection struct { daprd *daprd.Daprd lock sync.Mutex msg []byte } func (o *projection) Setup(t *testing.T) []framework.Option { onTopicEvent := func(ctx context.Context, in *runtimev1pb.TopicEventRequest) (*runtimev1pb.TopicEventResponse, error) { o.lock.Lock() defer o.lock.Unlock() o.msg = in.GetData() return &runtimev1pb.TopicEventResponse{ Status: runtimev1pb.TopicEventResponse_SUCCESS, }, nil } srv1 := app.New(t, app.WithOnTopicEventFn(onTopicEvent)) o.daprd = daprd.New(t, daprd.WithAppID("outboxtest"), daprd.WithAppPort(srv1.Port(t)), daprd.WithAppProtocol("grpc"), daprd.WithResourceFiles(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mystore spec: type: state.in-memory version: v1 metadata: - name: outboxPublishPubsub value: "mypubsub" - name: outboxPublishTopic value: "test" `, ` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: 'mypubsub' spec: type: pubsub.in-memory version: v1 `, ` apiVersion: dapr.io/v2alpha1 kind: Subscription metadata: name: 'order' spec: topic: 'test' routes: default: '/test' pubsubname: 'mypubsub' scopes: - outboxtest `)) return []framework.Option{ framework.WithProcesses(srv1, o.daprd), } } func (o *projection) Run(t *testing.T, ctx context.Context) { o.daprd.WaitUntilRunning(t, ctx) conn, err := grpc.DialContext(ctx, o.daprd.GRPCAddress(), grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock()) require.NoError(t, err) t.Cleanup(func() { require.NoError(t, conn.Close()) }) _, err = runtimev1pb.NewDaprClient(conn).ExecuteStateTransaction(ctx, &runtimev1pb.ExecuteStateTransactionRequest{ StoreName: "mystore", Operations: []*runtimev1pb.TransactionalStateOperation{ { OperationType: "upsert", Request: &common.StateItem{ Key: "1", Value: []byte("2"), }, }, { OperationType: "upsert", Request: &common.StateItem{ Key: "1", Value: []byte("3"), Metadata: map[string]string{ "outbox.projection": "true", }, }, }, }, }) require.NoError(t, err) assert.Eventually(t, func() bool { o.lock.Lock() defer o.lock.Unlock() return string(o.msg) == "3" }, time.Second*5, time.Millisecond*10, "failed to receive message in time") assert.Eventually(t, func() bool { o.lock.Lock() defer o.lock.Unlock() resp, err := runtimev1pb.NewDaprClient(conn).GetState(ctx, &runtimev1pb.GetStateRequest{ Key: "1", StoreName: "mystore", }) require.NoError(t, err) return string(resp.GetData()) == "2" }, time.Second*5, time.Millisecond*10, "failed to receive message in time") }
mikeee/dapr
tests/integration/suite/daprd/outbox/grpc/projection.go
GO
mit
3,822
/* 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 http import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/dapr/components-contrib/state" "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(basic)) } type basic struct { daprd *procdaprd.Daprd } func (o *basic) Setup(t *testing.T) []framework.Option { newHTTPServer := func() *prochttp.HTTP { handler := http.NewServeMux() var msg atomic.Value handler.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() b, err := io.ReadAll(r.Body) if err != nil { t.Fatal(err) } msg.Store(b) w.WriteHeader(http.StatusOK) w.Write([]byte("ok")) }) handler.HandleFunc("/getValue", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) m := msg.Load() if m == nil { return } w.Write(msg.Load().([]byte)) }) return prochttp.New(t, prochttp.WithHandler(handler)) } srv1 := newHTTPServer() o.daprd = procdaprd.New(t, procdaprd.WithAppID("outboxtest"), procdaprd.WithAppPort(srv1.Port()), procdaprd.WithResourceFiles(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mystore spec: type: state.in-memory version: v1 metadata: - name: outboxPublishPubsub value: "mypubsub" - name: outboxPublishTopic value: "test" `, ` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: 'mypubsub' spec: type: pubsub.in-memory version: v1 `, ` apiVersion: dapr.io/v2alpha1 kind: Subscription metadata: name: 'order' spec: topic: 'test' routes: default: '/test' pubsubname: 'mypubsub' scopes: - outboxtest `)) return []framework.Option{ framework.WithProcesses(srv1, o.daprd), } } type stateTransactionRequestBody struct { Operations []stateTransactionRequestBodyOperation `json:"operations"` Metadata map[string]string `json:"metadata,omitempty"` } type stateTransactionRequestBodyOperation struct { Operation string `json:"operation"` Request interface{} `json:"request"` } func (o *basic) Run(t *testing.T, ctx context.Context) { o.daprd.WaitUntilRunning(t, ctx) postURL := fmt.Sprintf("http://localhost:%d/v1.0/state/mystore/transaction", o.daprd.HTTPPort()) stateReq := state.SetRequest{ Key: "1", Value: "2", Metadata: map[string]string{"outbox.cloudevent.myapp": "myapp1", "data": "a", "id": "b"}, } tr := stateTransactionRequestBody{ Operations: []stateTransactionRequestBodyOperation{ { Operation: "upsert", Request: stateReq, }, }, } b, err := json.Marshal(&tr) require.NoError(t, err) httpClient := util.HTTPClient(t) req, err := http.NewRequestWithContext(ctx, http.MethodPost, postURL, bytes.NewReader(b)) require.NoError(t, err) resp, err := httpClient.Do(req) require.NoError(t, err) assert.Equal(t, http.StatusNoContent, resp.StatusCode) body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) assert.Empty(t, string(body)) assert.EventuallyWithT(t, func(c *assert.CollectT) { req, err = http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://localhost:%v/getValue", o.daprd.AppPort()), nil) require.NoError(c, err) resp, err = httpClient.Do(req) require.NoError(c, err) t.Cleanup(func() { require.NoError(t, resp.Body.Close()) }) body, err = io.ReadAll(resp.Body) require.NoError(c, err) var ce map[string]string err = json.Unmarshal(body, &ce) //nolint:testifylint assert.NoError(c, err) assert.Equal(c, "2", ce["data"]) assert.Equal(c, "myapp1", ce["outbox.cloudevent.myapp"]) assert.Contains(c, ce["id"], "outbox-") }, time.Second*10, time.Millisecond*10) }
mikeee/dapr
tests/integration/suite/daprd/outbox/http/basic.go
GO
mit
4,625
/* 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 http import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "strconv" "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/dapr/components-contrib/state" "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(projection)) } type projection struct { daprd *procdaprd.Daprd } func (o *projection) Setup(t *testing.T) []framework.Option { newHTTPServer := func() *prochttp.HTTP { handler := http.NewServeMux() var msg atomic.Value handler.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() b, err := io.ReadAll(r.Body) if err != nil { t.Fatal(err) } msg.Store(b) w.WriteHeader(http.StatusOK) w.Write([]byte("ok")) }) handler.HandleFunc("/getValue", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) m := msg.Load() if m == nil { return } w.Write(msg.Load().([]byte)) }) return prochttp.New(t, prochttp.WithHandler(handler)) } srv1 := newHTTPServer() o.daprd = procdaprd.New(t, procdaprd.WithAppID("outboxtest"), procdaprd.WithAppPort(srv1.Port()), procdaprd.WithResourceFiles(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mystore spec: type: state.in-memory version: v1 metadata: - name: outboxPublishPubsub value: "mypubsub" - name: outboxPublishTopic value: "test" `, ` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: 'mypubsub' spec: type: pubsub.in-memory version: v1 `, ` apiVersion: dapr.io/v2alpha1 kind: Subscription metadata: name: 'order' spec: topic: 'test' routes: default: '/test' pubsubname: 'mypubsub' scopes: - outboxtest `)) return []framework.Option{ framework.WithProcesses(srv1, o.daprd), } } func (o *projection) Run(t *testing.T, ctx context.Context) { o.daprd.WaitUntilRunning(t, ctx) postURL := fmt.Sprintf("http://localhost:%d/v1.0/state/mystore/transaction", o.daprd.HTTPPort()) stateReq := state.SetRequest{ Key: "1", Value: "2", } projectionRequest := state.SetRequest{ Key: "1", Value: "3", Metadata: map[string]string{"outbox.projection": "true"}, } tr := stateTransactionRequestBody{ Operations: []stateTransactionRequestBodyOperation{ { Operation: "upsert", Request: stateReq, }, { Operation: "upsert", Request: projectionRequest, }, }, } b, err := json.Marshal(&tr) require.NoError(t, err) httpClient := util.HTTPClient(t) req, err := http.NewRequestWithContext(ctx, http.MethodPost, postURL, bytes.NewReader(b)) require.NoError(t, err) resp, err := httpClient.Do(req) require.NoError(t, err) assert.Equal(t, http.StatusNoContent, resp.StatusCode) body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) assert.Empty(t, string(body)) assert.EventuallyWithT(t, func(c *assert.CollectT) { // validate projection data is reflected in final publish req, err = http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://localhost:%v/getValue", o.daprd.AppPort()), nil) require.NoError(c, err) resp, err = httpClient.Do(req) require.NoError(c, err) t.Cleanup(func() { require.NoError(t, resp.Body.Close()) }) body, err = io.ReadAll(resp.Body) require.NoError(c, err) var ce map[string]string err = json.Unmarshal(body, &ce) //nolint:testifylint assert.NoError(c, err) assert.Equal(c, "3", ce["data"]) }, time.Second*10, time.Millisecond*10) assert.EventuallyWithT(t, func(c *assert.CollectT) { // validate correct state is in the db and not the projection data req, err = http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://localhost:%d/v1.0/state/mystore/1", o.daprd.HTTPPort()), nil) require.NoError(c, err) resp, err = httpClient.Do(req) require.NoError(c, err) t.Cleanup(func() { require.NoError(t, resp.Body.Close()) }) body, err = io.ReadAll(resp.Body) require.NoError(c, err) val, err := strconv.Unquote(string(body)) require.NoError(c, err) require.NoError(c, err) assert.Equal(c, "2", val) }, time.Second*10, time.Millisecond*10) }
mikeee/dapr
tests/integration/suite/daprd/outbox/http/projection.go
GO
mit
5,041
/* 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 outbox import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/outbox/grpc" _ "github.com/dapr/dapr/tests/integration/suite/daprd/outbox/http" )
mikeee/dapr
tests/integration/suite/daprd/outbox/outbox.go
GO
mit
724
/* 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 http import ( "context" "fmt" "runtime" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" commonv1 "github.com/dapr/dapr/pkg/proto/common/v1" 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/statestore" "github.com/dapr/dapr/tests/integration/framework/process/statestore/inmemory" "github.com/dapr/dapr/tests/integration/framework/socket" "github.com/dapr/dapr/tests/integration/framework/util" "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 { if runtime.GOOS == "windows" { t.Skip("skipping unix socket based test on windows") } socket := socket.New(t) store := statestore.New(t, statestore.WithSocket(socket), statestore.WithStateStore(inmemory.New(t)), ) b.daprd = daprd.New(t, daprd.WithResourceFiles(fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mystore spec: type: state.%s version: v1 `, store.SocketName())), daprd.WithSocket(t, socket), ) return []framework.Option{ framework.WithProcesses(store, b.daprd), } } func (b *basic) Run(t *testing.T, ctx context.Context) { b.daprd.WaitUntilRunning(t, ctx) client := util.DaprGRPCClient(t, ctx, b.daprd.GRPCPort()) now := time.Now() _, err := client.SaveState(ctx, &rtv1.SaveStateRequest{ StoreName: "mystore", States: []*commonv1.StateItem{ { Key: "key1", Value: []byte("value1"), }, { Key: "key2", Value: []byte("value2"), Options: &commonv1.StateOptions{ Concurrency: commonv1.StateOptions_CONCURRENCY_FIRST_WRITE, }, }, { Key: "key3", Value: []byte("value3"), Metadata: map[string]string{"ttlInSeconds": "1"}, }, { Key: "key4", Value: []byte("value4"), Metadata: map[string]string{"ttlInSeconds": "1"}, Options: &commonv1.StateOptions{ Concurrency: commonv1.StateOptions_CONCURRENCY_FIRST_WRITE, }, }, }, }) require.NoError(t, err) resp, err := client.GetState(ctx, &rtv1.GetStateRequest{ StoreName: "mystore", Key: "key2", }) require.NoError(t, err) etag2 := resp.GetEtag() resp, err = client.GetState(ctx, &rtv1.GetStateRequest{ StoreName: "mystore", Key: "key4", }) require.NoError(t, err) etag4 := resp.GetEtag() { resp, err := client.GetBulkState(ctx, &rtv1.GetBulkStateRequest{ StoreName: "mystore", Keys: []string{"key1", "key2", "key3", "key4"}, }) require.NoError(t, err) require.Len(t, resp.GetItems(), 4) assert.Equal(t, "key1", resp.GetItems()[0].GetKey()) assert.Equal(t, "value1", string(resp.GetItems()[0].GetData())) assert.Empty(t, resp.GetItems()[0].GetMetadata()) assert.Equal(t, "key2", resp.GetItems()[1].GetKey()) assert.Equal(t, "value2", string(resp.GetItems()[1].GetData())) assert.Equal(t, etag2, resp.GetItems()[1].GetEtag()) assert.Equal(t, "key3", resp.GetItems()[2].GetKey()) assert.Equal(t, "value3", string(resp.GetItems()[2].GetData())) if assert.Contains(t, resp.GetItems()[2].GetMetadata(), "ttlExpireTime") { expireTime, eerr := time.Parse(time.RFC3339, resp.GetItems()[2].GetMetadata()["ttlExpireTime"]) require.NoError(t, eerr) assert.WithinDuration(t, now.Add(time.Second), expireTime, time.Second) } assert.Equal(t, "key4", resp.GetItems()[3].GetKey()) assert.Equal(t, "value4", string(resp.GetItems()[3].GetData())) assert.Equal(t, etag4, resp.GetItems()[3].GetEtag()) if assert.Contains(t, resp.GetItems()[3].GetMetadata(), "ttlExpireTime") { expireTime, eerr := time.Parse(time.RFC3339, resp.GetItems()[3].GetMetadata()["ttlExpireTime"]) require.NoError(t, eerr) assert.WithinDuration(t, now.Add(time.Second), expireTime, time.Second) } _, err = client.DeleteState(ctx, &rtv1.DeleteStateRequest{ StoreName: "mystore", Key: "key1", }) require.NoError(t, err) _, err = client.DeleteBulkState(ctx, &rtv1.DeleteBulkStateRequest{ StoreName: "mystore", States: []*commonv1.StateItem{ { Key: "key2", }, }, }) require.NoError(t, err) } assert.EventuallyWithT(t, func(c *assert.CollectT) { for _, key := range []string{"key3", "key4"} { resp, err := client.GetState(ctx, &rtv1.GetStateRequest{ StoreName: "mystore", Key: key, }) require.NoError(t, err) assert.Empty(c, resp.GetData()) } }, time.Second*2, time.Millisecond*10) }
mikeee/dapr
tests/integration/suite/daprd/pluggable/basic.go
GO
mit
5,186
/* 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 contentlength import ( "context" "fmt" "testing" "github.com/stretchr/testify/require" compv1pb "github.com/dapr/dapr/pkg/proto/components/v1" 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" grpcsub "github.com/dapr/dapr/tests/integration/framework/process/grpc/subscriber" httpsub "github.com/dapr/dapr/tests/integration/framework/process/http/subscriber" "github.com/dapr/dapr/tests/integration/framework/process/pubsub" inmemory "github.com/dapr/dapr/tests/integration/framework/process/pubsub/in-memory" "github.com/dapr/dapr/tests/integration/framework/socket" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(bulk)) } type bulk struct { daprdhttp *daprd.Daprd daprdgrpc *daprd.Daprd apphttp *httpsub.Subscriber appgrpc *grpcsub.Subscriber pmrChHTTP chan *compv1pb.PullMessagesResponse pmrChGRPC chan *compv1pb.PullMessagesResponse } func (b *bulk) Setup(t *testing.T) []framework.Option { b.pmrChHTTP = make(chan *compv1pb.PullMessagesResponse) b.pmrChGRPC = make(chan *compv1pb.PullMessagesResponse) b.apphttp = httpsub.New(t, httpsub.WithBulkRoutes("/abc")) b.appgrpc = grpcsub.New(t) socket1 := socket.New(t) inmem1 := pubsub.New(t, pubsub.WithSocket(socket1), pubsub.WithPullMessagesChannel(b.pmrChHTTP), pubsub.WithPubSub(inmemory.NewWrappedInMemory(t)), ) b.daprdhttp = daprd.New(t, daprd.WithAppPort(b.apphttp.Port()), daprd.WithSocket(t, socket1), daprd.WithResourceFiles(fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: foo spec: type: pubsub.%s version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Subscription metadata: name: mysub1 spec: topic: bar1 route: /abc pubsubname: foo bulkSubscribe: enabled: true `, inmem1.SocketName())), ) socket2 := socket.New(t) inmem2 := pubsub.New(t, pubsub.WithSocket(socket2), pubsub.WithPullMessagesChannel(b.pmrChGRPC), pubsub.WithPubSub(inmemory.NewWrappedInMemory(t)), ) b.daprdgrpc = daprd.New(t, daprd.WithAppPort(b.appgrpc.Port(t)), daprd.WithAppProtocol("grpc"), daprd.WithSocket(t, socket2), daprd.WithResourceFiles(fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: foo spec: type: pubsub.%s version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Subscription metadata: name: mysub1 spec: topic: bar2 route: /abc pubsubname: foo bulkSubscribe: enabled: true `, inmem2.SocketName())), ) return []framework.Option{ framework.WithProcesses(inmem1, inmem2, b.daprdhttp, b.daprdgrpc, b.apphttp, b.appgrpc), } } func (b *bulk) Run(t *testing.T, ctx context.Context) { b.daprdhttp.WaitUntilRunning(t, ctx) b.daprdgrpc.WaitUntilRunning(t, ctx) clientHTTP := b.daprdhttp.GRPCClient(t, ctx) meta, err := clientHTTP.GetMetadata(ctx, new(rtv1.GetMetadataRequest)) require.NoError(t, err) require.Len(t, meta.GetSubscriptions(), 1) b.pmrChHTTP <- &compv1pb.PullMessagesResponse{ Data: []byte(`{"data":"helloworld","datacontenttype":"text/plain","id":"b959cd5a-29e5-42ca-89e2-c66f4402f273","pubsubname":"foo","source":"foo","specversion":"1.0","time":"2024-03-27T23:47:53Z","topic":"bar1","traceid":"00-00000000000000000000000000000000-0000000000000000-00","traceparent":"00-00000000000000000000000000000000-0000000000000000-00","tracestate":"","type":"com.dapr.event.sent"}`), TopicName: "bar", Id: "foo", Metadata: map[string]string{"content-length": "123"}, } b.apphttp.ReceiveBulk(t, ctx) clientGRPC := b.daprdgrpc.GRPCClient(t, ctx) meta, err = clientGRPC.GetMetadata(ctx, new(rtv1.GetMetadataRequest)) require.NoError(t, err) require.Len(t, meta.GetSubscriptions(), 1) b.pmrChGRPC <- &compv1pb.PullMessagesResponse{ Data: []byte(`{"data":"helloworld","datacontenttype":"text/plain","id":"b959cd5a-29e5-42ca-89e2-c66f4402f273","pubsubname":"foo","source":"foo","specversion":"1.0","time":"2024-03-27T23:47:53Z","topic":"bar2","traceid":"00-00000000000000000000000000000000-0000000000000000-00","traceparent":"00-00000000000000000000000000000000-0000000000000000-00","tracestate":"","type":"com.dapr.event.sent"}`), TopicName: "bar", Id: "foo", Metadata: map[string]string{"content-length": "123"}, } b.appgrpc.ReceiveBulk(t, ctx) }
mikeee/dapr
tests/integration/suite/daprd/pubsub/contentlength/bulk.go
GO
mit
4,910
/* 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 contentlength import ( "context" "fmt" "testing" "github.com/stretchr/testify/require" compv1pb "github.com/dapr/dapr/pkg/proto/components/v1" 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" grpcsub "github.com/dapr/dapr/tests/integration/framework/process/grpc/subscriber" httpsub "github.com/dapr/dapr/tests/integration/framework/process/http/subscriber" "github.com/dapr/dapr/tests/integration/framework/process/pubsub" inmemory "github.com/dapr/dapr/tests/integration/framework/process/pubsub/in-memory" "github.com/dapr/dapr/tests/integration/framework/socket" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(singular)) } type singular struct { daprdhttp *daprd.Daprd daprdgrpc *daprd.Daprd apphttp *httpsub.Subscriber appgrpc *grpcsub.Subscriber pmrChHTTP chan *compv1pb.PullMessagesResponse pmrChGRPC chan *compv1pb.PullMessagesResponse } func (s *singular) Setup(t *testing.T) []framework.Option { s.pmrChHTTP = make(chan *compv1pb.PullMessagesResponse) s.pmrChGRPC = make(chan *compv1pb.PullMessagesResponse) s.apphttp = httpsub.New(t, httpsub.WithRoutes("/abc")) s.appgrpc = grpcsub.New(t) socket1 := socket.New(t) inmem1 := pubsub.New(t, pubsub.WithSocket(socket1), pubsub.WithPullMessagesChannel(s.pmrChHTTP), pubsub.WithPubSub(inmemory.NewWrappedInMemory(t)), ) s.daprdhttp = daprd.New(t, daprd.WithAppPort(s.apphttp.Port()), daprd.WithSocket(t, socket1), daprd.WithResourceFiles(fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: foo spec: type: pubsub.%s version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Subscription metadata: name: mysub1 spec: topic: bar1 route: /abc pubsubname: foo `, inmem1.SocketName())), ) socket2 := socket.New(t) inmem2 := pubsub.New(t, pubsub.WithSocket(socket2), pubsub.WithPullMessagesChannel(s.pmrChGRPC), pubsub.WithPubSub(inmemory.NewWrappedInMemory(t)), ) s.daprdgrpc = daprd.New(t, daprd.WithAppPort(s.appgrpc.Port(t)), daprd.WithAppProtocol("grpc"), daprd.WithSocket(t, socket2), daprd.WithResourceFiles(fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: foo spec: type: pubsub.%s version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Subscription metadata: name: mysub1 spec: topic: bar2 route: /abc pubsubname: foo `, inmem2.SocketName())), ) return []framework.Option{ framework.WithProcesses(inmem1, inmem2, s.daprdhttp, s.daprdgrpc, s.apphttp, s.appgrpc), } } func (s *singular) Run(t *testing.T, ctx context.Context) { s.daprdhttp.WaitUntilRunning(t, ctx) s.daprdgrpc.WaitUntilRunning(t, ctx) clientHTTP := s.daprdhttp.GRPCClient(t, ctx) meta, err := clientHTTP.GetMetadata(ctx, new(rtv1.GetMetadataRequest)) require.NoError(t, err) require.Len(t, meta.GetSubscriptions(), 1) s.pmrChHTTP <- &compv1pb.PullMessagesResponse{ Data: []byte(`{"data":{"foo": "helloworld"},"datacontenttype":"application/json","id":"b959cd5a-29e5-42ca-89e2-c66f4402f273","pubsubname":"foo","source":"foo","specversion":"1.0","time":"2024-03-27T23:47:53Z","topic":"bar1","traceid":"00-00000000000000000000000000000000-0000000000000000-00","traceparent":"00-00000000000000000000000000000000-0000000000000000-00","tracestate":"","type":"com.dapr.event.sent"}`), TopicName: "bar", Id: "foo", Metadata: map[string]string{"content-length": "123"}, } s.apphttp.Receive(t, ctx) clientGRPC := s.daprdgrpc.GRPCClient(t, ctx) meta, err = clientGRPC.GetMetadata(ctx, new(rtv1.GetMetadataRequest)) require.NoError(t, err) require.Len(t, meta.GetSubscriptions(), 1) s.pmrChGRPC <- &compv1pb.PullMessagesResponse{ Data: []byte(`{"data":{"foo": "helloworld"},"datacontenttype":"application/json","id":"b959cd5a-29e5-42ca-89e2-c66f4402f273","pubsubname":"foo","source":"foo","specversion":"1.0","time":"2024-03-27T23:47:53Z","topic":"bar2","traceid":"00-00000000000000000000000000000000-0000000000000000-00","traceparent":"00-00000000000000000000000000000000-0000000000000000-00","tracestate":"","type":"com.dapr.event.sent"}`), TopicName: "bar", Id: "foo", Metadata: map[string]string{"content-length": "123"}, } s.appgrpc.Receive(t, ctx) }
mikeee/dapr
tests/integration/suite/daprd/pubsub/contentlength/singular.go
GO
mit
4,880
/* 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 grpc import ( "context" "errors" "fmt" "net/http" "sync/atomic" "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/app" "github.com/dapr/dapr/tests/integration/framework/util" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(appready)) } type appready struct { daprd *daprd.Daprd appHealthy atomic.Bool healthCalled atomic.Int64 topicChan chan string } func (a *appready) Setup(t *testing.T) []framework.Option { srv := app.New(t, app.WithHealthCheckFn(func(context.Context, *emptypb.Empty) (*rtv1.HealthCheckResponse, error) { defer a.healthCalled.Add(1) if a.appHealthy.Load() { return &rtv1.HealthCheckResponse{}, nil } return nil, errors.New("app not healthy") }), app.WithOnTopicEventFn(func(_ context.Context, in *rtv1.TopicEventRequest) (*rtv1.TopicEventResponse, error) { a.topicChan <- in.GetPath() return new(rtv1.TopicEventResponse), nil }), app.WithListTopicSubscriptions(func(context.Context, *emptypb.Empty) (*rtv1.ListTopicSubscriptionsResponse, error) { return &rtv1.ListTopicSubscriptionsResponse{ Subscriptions: []*rtv1.TopicSubscription{ {PubsubName: "mypubsub", Topic: "mytopic", Routes: &rtv1.TopicRoutes{Default: "/myroute"}}, }, }, nil }), ) a.topicChan = make(chan string) a.daprd = daprd.New(t, daprd.WithAppPort(srv.Port(t)), daprd.WithAppProtocol("grpc"), daprd.WithAppHealthCheck(true), daprd.WithAppHealthProbeInterval(1), daprd.WithAppHealthProbeThreshold(1), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypubsub spec: type: pubsub.in-memory version: v1`), ) return []framework.Option{ framework.WithProcesses(srv, a.daprd), } } func (a *appready) Run(t *testing.T, ctx context.Context) { a.daprd.WaitUntilRunning(t, ctx) client := a.daprd.GRPCClient(t, ctx) httpClient := util.HTTPClient(t) reqURL := fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/foo", a.daprd.HTTPPort(), a.daprd.AppID()) req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil) require.NoError(t, err) require.EventuallyWithT(t, func(c *assert.CollectT) { var resp *rtv1.GetMetadataResponse resp, err = client.GetMetadata(ctx, new(rtv1.GetMetadataRequest)) require.NoError(t, err) assert.Len(c, resp.GetRegisteredComponents(), 1) }, time.Second*5, time.Millisecond*10) called := a.healthCalled.Load() require.Eventually(t, func() bool { return a.healthCalled.Load() > called }, time.Second*5, time.Millisecond*10) assert.Eventually(t, func() bool { var resp *http.Response resp, err = httpClient.Do(req) require.NoError(t, err) defer resp.Body.Close() return resp.StatusCode == http.StatusInternalServerError }, time.Second*5, 10*time.Millisecond) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypubsub", Topic: "mytopic", Data: []byte(`{"status": "completed"}`), }) require.NoError(t, err) called = a.healthCalled.Load() require.Eventually(t, func() bool { select { case <-a.topicChan: assert.Fail(t, "unexpected publish") default: } return a.healthCalled.Load() > called }, time.Second*5, time.Millisecond*10) a.appHealthy.Store(true) assert.Eventually(t, func() bool { var resp *http.Response resp, err = util.HTTPClient(t).Do(req) require.NoError(t, err) defer resp.Body.Close() return resp.StatusCode == http.StatusOK }, time.Second*5, 10*time.Millisecond) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypubsub", Topic: "mytopic", Data: []byte(`{"status": "completed"}`), }) require.NoError(t, err) select { case resp := <-a.topicChan: assert.Equal(t, "/myroute", resp) case <-time.After(time.Second * 5): assert.Fail(t, "timeout waiting for topic to return") } // Should stop sending messages to subscribed app when it becomes unhealthy. a.appHealthy.Store(false) assert.Eventually(t, func() bool { var resp *http.Response resp, err = httpClient.Do(req) require.NoError(t, err) defer resp.Body.Close() return resp.StatusCode == http.StatusInternalServerError }, time.Second*5, 10*time.Millisecond) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "mypubsub", Topic: "mytopic", Data: []byte(`{"status": "completed"}`), }) require.NoError(t, err) called = a.healthCalled.Load() require.Eventually(t, func() bool { select { case <-a.topicChan: assert.Fail(t, "unexpected publish") default: } return a.healthCalled.Load() > called }, time.Second*5, time.Millisecond*10) }
mikeee/dapr
tests/integration/suite/daprd/pubsub/grpc/appready.go
GO
mit
5,534
/* 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 grpc import ( "context" "fmt" "regexp" "strings" "testing" fuzz "github.com/google/gofuzz" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "k8s.io/apimachinery/pkg/api/validation/path" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "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(componentName)) } type componentName struct { daprd *procdaprd.Daprd pubsubNames []string topicNames []string } func (c *componentName) Setup(t *testing.T) []framework.Option { const numTests = 1000 takenNames := make(map[string]bool) reg, err := regexp.Compile("^([a-zA-Z].*)$") require.NoError(t, err) fz := fuzz.New().Funcs(func(s *string, c fuzz.Continue) { for *s == "" || takenNames[*s] || len(path.IsValidPathSegmentName(*s)) > 0 || !reg.MatchString(*s) { *s = c.RandString() } takenNames[*s] = true }) c.pubsubNames = make([]string, numTests) c.topicNames = make([]string, numTests) files := make([]string, numTests) for i := 0; i < numTests; i++ { fz.Fuzz(&c.pubsubNames[i]) fz.Fuzz(&c.topicNames[i]) files[i] = fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: '%s' spec: type: pubsub.in-memory version: v1 `, // Escape single quotes in the store name. strings.ReplaceAll(c.pubsubNames[i], "'", "''")) } c.daprd = procdaprd.New(t, procdaprd.WithResourceFiles(files...)) return []framework.Option{ framework.WithProcesses(c.daprd), } } func (c *componentName) Run(t *testing.T, ctx context.Context) { c.daprd.WaitUntilRunning(t, ctx) pt := util.NewParallel(t) for i := range c.pubsubNames { pubsubName := c.pubsubNames[i] topicName := c.topicNames[i] pt.Add(func(col *assert.CollectT) { conn, err := grpc.DialContext(ctx, c.daprd.GRPCAddress(), grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock()) require.NoError(col, err) t.Cleanup(func() { require.NoError(t, conn.Close()) }) client := rtv1.NewDaprClient(conn) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: pubsubName, Topic: topicName, Data: []byte(`{"status": "completed"}`), }) //nolint:testifylint assert.NoError(col, err) }) } }
mikeee/dapr
tests/integration/suite/daprd/pubsub/grpc/compname.go
GO
mit
3,084
/* 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 grpc 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/grpc/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) 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 --- apiVersion: dapr.io/v2alpha1 kind: Subscription metadata: name: mysub spec: pubsubname: mypub topic: a routes: rules: - path: "/a" match: "" `)) return []framework.Option{ framework.WithProcesses(e.sub, e.daprd), } } func (e *emptyroute) 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: "a", Data: []byte(`{"status": "completed"}`), }) require.NoError(t, err) resp := e.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.GetPath()) }
mikeee/dapr
tests/integration/suite/daprd/pubsub/grpc/emptymatch.go
GO
mit
2,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 grpc import ( "context" "errors" "fmt" "runtime" "testing" componentspubsub "github.com/dapr/components-contrib/pubsub" commonv1 "github.com/dapr/dapr/pkg/proto/common/v1" "github.com/dapr/dapr/tests/integration/framework/process/pubsub" inmemory "github.com/dapr/dapr/tests/integration/framework/process/pubsub/in-memory" "github.com/dapr/dapr/tests/integration/framework/socket" "github.com/stretchr/testify/require" "google.golang.org/genproto/googleapis/rpc/errdetails" "google.golang.org/grpc" grpcCodes "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials/insecure" "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/suite" kiterrors "github.com/dapr/kit/errors" ) func init() { suite.Register(new(errorcodes)) } type errorcodes struct { daprd *daprd.Daprd } func (e *errorcodes) Setup(t *testing.T) []framework.Option { if runtime.GOOS == "windows" { t.Skip("skipping unix socket based test on windows") } socket := socket.New(t) pubsubInMem := pubsub.New(t, pubsub.WithSocket(socket), pubsub.WithPubSub(inmemory.NewWrappedInMemory(t, inmemory.WithFeatures(), inmemory.WithPublishFn(func(ctx context.Context, req *componentspubsub.PublishRequest) error { return errors.New("outbox error") }), )), ) // spin up a new daprd with a pubsub component e.daprd = daprd.New(t, daprd.WithResourceFiles(fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypubsub spec: type: pubsub.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: pubsub-outbox spec: type: pubsub.%s version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: state-outbox spec: type: state.in-memory version: v1 metadata: - name: outboxPublishPubsub value: "pubsub-outbox" - name: outboxPublishTopic value: "goodTopic" # force topic mismatch error - name: outboxPubsub value: "pubsub-outbox" - name: outboxDiscardWhenMissingState #Optional. Defaults to false value: false `, pubsubInMem.SocketName())), daprd.WithSocket(t, socket), ) return []framework.Option{ framework.WithProcesses(pubsubInMem, e.daprd), } } func (e *errorcodes) Run(t *testing.T, ctx context.Context) { e.daprd.WaitUntilRunning(t, ctx) conn, connErr := grpc.DialContext(ctx, fmt.Sprintf("localhost:%d", e.daprd.GRPCPort()), grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock()) require.NoError(t, connErr) t.Cleanup(func() { require.NoError(t, conn.Close()) }) client := rtv1.NewDaprClient(conn) // Covers apierrors.PubSubNotFound() t.Run("pubsub doesn't exist", func(t *testing.T) { name := "pubsub-doesn't-exist" req := &rtv1.PublishEventRequest{ PubsubName: name, } _, err := client.PublishEvent(ctx, req) require.Error(t, err) s, ok := status.FromError(err) require.True(t, ok) require.Equal(t, grpcCodes.InvalidArgument, s.Code()) require.Equal(t, fmt.Sprintf("pubsub %s is not found", "pubsub-doesn't-exist"), s.Message()) // Check status details require.Len(t, s.Details(), 1) var errInfo *errdetails.ErrorInfo errInfo, ok = s.Details()[0].(*errdetails.ErrorInfo) require.True(t, ok) require.Equal(t, kiterrors.CodePrefixPubSub+kiterrors.CodeNotFound, errInfo.GetReason()) require.Equal(t, "dapr.io", errInfo.GetDomain()) }) // Covers apierrors.PubSubNameEmpty() t.Run("pubsub name empty", func(t *testing.T) { req := &rtv1.PublishEventRequest{ PubsubName: "", } _, err := client.PublishEvent(ctx, req) require.Error(t, err) s, ok := status.FromError(err) require.True(t, ok) require.Equal(t, grpcCodes.InvalidArgument, s.Code()) require.Equal(t, "pubsub name is empty", s.Message()) // Check status details require.Len(t, s.Details(), 2) var errInfo *errdetails.ErrorInfo var resInfo *errdetails.ResourceInfo for _, detail := range s.Details() { switch d := detail.(type) { case *errdetails.ErrorInfo: errInfo = d case *errdetails.ResourceInfo: resInfo = d default: require.FailNow(t, "unexpected status detail") } } require.NotNil(t, errInfo, "ErrorInfo should be present") require.Equal(t, "DAPR_PUBSUB_NAME_EMPTY", errInfo.GetReason()) require.Equal(t, "dapr.io", errInfo.GetDomain()) require.Nil(t, errInfo.GetMetadata()) require.NotNil(t, resInfo, "ResourceInfo should be present") require.Equal(t, "pubsub", resInfo.GetResourceType()) require.Equal(t, "", resInfo.GetResourceName()) require.Empty(t, resInfo.GetOwner()) }) // Covers apierrors.PubSubTopicEmpty() t.Run("pubsub topic empty", func(t *testing.T) { name := "mypubsub" req := &rtv1.PublishEventRequest{ PubsubName: name, Topic: "", } _, err := client.PublishEvent(ctx, req) require.Error(t, err) s, ok := status.FromError(err) require.True(t, ok) require.Equal(t, grpcCodes.InvalidArgument, s.Code()) require.Equal(t, fmt.Sprintf("topic is empty in pubsub mypubsub"), s.Message()) // Check status details require.Len(t, s.Details(), 2) var errInfo *errdetails.ErrorInfo var resInfo *errdetails.ResourceInfo for _, detail := range s.Details() { switch d := detail.(type) { case *errdetails.ErrorInfo: errInfo = d case *errdetails.ResourceInfo: resInfo = d default: require.FailNow(t, "unexpected status detail") } } require.NotNil(t, errInfo, "ErrorInfo should be present") require.Equal(t, "DAPR_PUBSUB_TOPIC_NAME_EMPTY", errInfo.GetReason()) require.Equal(t, "dapr.io", errInfo.GetDomain()) require.Nil(t, errInfo.GetMetadata()) require.NotNil(t, resInfo, "ResourceInfo should be present") require.Equal(t, "pubsub", resInfo.GetResourceType()) require.Equal(t, name, resInfo.GetResourceName()) require.Empty(t, resInfo.GetOwner()) }) // Covers apierrors.PubSubMetadataDeserialize() t.Run("pubsub metadata deserialization", func(t *testing.T) { name := "mypubsub" metadata := map[string]string{"rawPayload": "invalidBooleanValue"} req := &rtv1.PublishEventRequest{ PubsubName: name, Topic: "topic", Metadata: metadata, } _, err := client.PublishEvent(ctx, req) require.Error(t, err) s, ok := status.FromError(err) require.True(t, ok) require.Equal(t, grpcCodes.InvalidArgument, s.Code()) expectedErr := "rawPayload value must be a valid boolean: actual is 'invalidBooleanValue'" require.Equal(t, fmt.Sprintf("failed deserializing metadata. Error: %s", expectedErr), s.Message()) // Check status details require.Len(t, s.Details(), 2) var errInfo *errdetails.ErrorInfo var resInfo *errdetails.ResourceInfo for _, detail := range s.Details() { switch d := detail.(type) { case *errdetails.ErrorInfo: errInfo = d case *errdetails.ResourceInfo: resInfo = d default: require.FailNow(t, "unexpected status detail") } } require.NotNil(t, errInfo, "ErrorInfo should be present") require.Equal(t, kiterrors.CodePrefixPubSub+"METADATA_DESERIALIZATION", errInfo.GetReason()) require.Equal(t, "dapr.io", errInfo.GetDomain()) require.NotNil(t, errInfo.GetMetadata()) require.NotNil(t, resInfo, "ResourceInfo should be present") require.Equal(t, "pubsub", resInfo.GetResourceType()) require.Equal(t, name, resInfo.GetResourceName()) require.Empty(t, resInfo.GetOwner()) }) // Covers apierrors.PubSubCloudEventCreation() t.Run("pubsub cloud event creation issue", func(t *testing.T) { name := "mypubsub" metadata := map[string]string{"rawPayload": "false"} invalidData := []byte(`{"missing_quote: invalid}`) req := &rtv1.PublishEventRequest{ PubsubName: name, Topic: "topic", Metadata: metadata, Data: invalidData, DataContentType: "application/cloudevents+json", } _, err := client.PublishEvent(ctx, req) require.Error(t, err) s, ok := status.FromError(err) require.True(t, ok) require.Equal(t, grpcCodes.InvalidArgument, s.Code()) require.Equal(t, "cannot create cloudevent", s.Message()) // Check status details require.Len(t, s.Details(), 2) var errInfo *errdetails.ErrorInfo var resInfo *errdetails.ResourceInfo for _, detail := range s.Details() { switch d := detail.(type) { case *errdetails.ErrorInfo: errInfo = d case *errdetails.ResourceInfo: resInfo = d default: require.FailNow(t, "unexpected status detail") } } require.NotNil(t, errInfo, "ErrorInfo should be present") require.Equal(t, kiterrors.CodePrefixPubSub+"CLOUD_EVENT_CREATION", errInfo.GetReason()) require.Equal(t, "dapr.io", errInfo.GetDomain()) require.NotNil(t, errInfo.GetMetadata()) require.NotNil(t, resInfo, "ResourceInfo should be present") require.Equal(t, "pubsub", resInfo.GetResourceType()) require.Equal(t, name, resInfo.GetResourceName()) require.Empty(t, resInfo.GetOwner()) }) // Covers apierrors.PubSubMarshalEvents() t.Run("pubsub marshal events issue", func(t *testing.T) { name := "mypubsub" topic := "topic" req := &rtv1.BulkPublishRequest{ PubsubName: name, Topic: topic, Entries: []*rtv1.BulkPublishRequestEntry{ { EntryId: "", Event: nil, ContentType: "", Metadata: nil, }, }, Metadata: nil, } _, err := client.BulkPublishEventAlpha1(ctx, req) require.Error(t, err) s, ok := status.FromError(err) require.True(t, ok) require.Equal(t, grpcCodes.InvalidArgument, s.Code()) require.Equal(t, fmt.Sprintf("error marshaling events to bytes for topic %s pubsub %s. error: entryId is duplicated or not present for entry", topic, name), s.Message()) // Check status details require.Len(t, s.Details(), 2) var errInfo *errdetails.ErrorInfo var resInfo *errdetails.ResourceInfo for _, detail := range s.Details() { switch d := detail.(type) { case *errdetails.ErrorInfo: errInfo = d case *errdetails.ResourceInfo: resInfo = d default: require.FailNow(t, "unexpected status detail") } } require.NotNil(t, errInfo, "ErrorInfo should be present") require.Equal(t, kiterrors.CodePrefixPubSub+"MARSHAL_EVENTS", errInfo.GetReason()) require.Equal(t, "dapr.io", errInfo.GetDomain()) require.NotNil(t, errInfo.GetMetadata()) require.NotNil(t, resInfo, "ResourceInfo should be present") require.Equal(t, "pubsub", resInfo.GetResourceType()) require.Equal(t, name, resInfo.GetResourceName()) require.Empty(t, resInfo.GetOwner()) }) t.Run("pubsub outbox", func(t *testing.T) { name := "state-outbox" ops := make([]*rtv1.TransactionalStateOperation, 0) ops = append(ops, &rtv1.TransactionalStateOperation{ OperationType: "upsert", Request: &commonv1.StateItem{ Key: "key1", Value: []byte("val1"), }, }, &rtv1.TransactionalStateOperation{ OperationType: "delete", Request: &commonv1.StateItem{ Key: "key2", }, }) req := &rtv1.ExecuteStateTransactionRequest{ StoreName: name, Operations: ops, } _, err := client.ExecuteStateTransaction(ctx, req) require.Error(t, err) s, ok := status.FromError(err) require.True(t, ok) require.Equal(t, grpcCodes.Internal, s.Code()) expectedErrMsg := "error while publishing outbox message: rpc error: code = Unknown desc = outbox error" require.Equal(t, expectedErrMsg, s.Message()) // Check status details require.Len(t, s.Details(), 1) var errInfo *errdetails.ErrorInfo errInfo, ok = s.Details()[0].(*errdetails.ErrorInfo) require.True(t, ok) require.Equal(t, kiterrors.CodePrefixPubSub+"OUTBOX", errInfo.GetReason()) require.Equal(t, "dapr.io", errInfo.GetDomain()) require.NotNil(t, errInfo.GetMetadata()) }) }
mikeee/dapr
tests/integration/suite/daprd/pubsub/grpc/errors.go
GO
mit
12,414
/* 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 http import ( "context" "fmt" "io" "net/http" "net/url" "regexp" "strings" "testing" fuzz "github.com/google/gofuzz" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "k8s.io/apimachinery/pkg/api/validation/path" "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(componentName)) } type componentName struct { daprd *procdaprd.Daprd pubsubNames []string topicNames []string } func (c *componentName) Setup(t *testing.T) []framework.Option { const numTests = 1000 takenNames := make(map[string]bool) reg, err := regexp.Compile("^([a-zA-Z].*)$") require.NoError(t, err) fz := fuzz.New().Funcs(func(s *string, c fuzz.Continue) { for *s == "" || takenNames[*s] || len(path.IsValidPathSegmentName(*s)) > 0 || !reg.MatchString(*s) { *s = c.RandString() } takenNames[*s] = true }) c.pubsubNames = make([]string, numTests) c.topicNames = make([]string, numTests) files := make([]string, numTests) for i := 0; i < numTests; i++ { fz.Fuzz(&c.pubsubNames[i]) fz.Fuzz(&c.topicNames[i]) files[i] = fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: '%s' spec: type: pubsub.in-memory version: v1 `, // Escape single quotes in the store name. strings.ReplaceAll(c.pubsubNames[i], "'", "''")) } c.daprd = procdaprd.New(t, procdaprd.WithResourceFiles(files...)) return []framework.Option{ framework.WithProcesses(c.daprd), } } func (c *componentName) Run(t *testing.T, ctx context.Context) { c.daprd.WaitUntilRunning(t, ctx) httpClient := util.HTTPClient(t) pt := util.NewParallel(t) for i := range c.pubsubNames { pubsubName := c.pubsubNames[i] topicName := c.topicNames[i] pt.Add(func(t *assert.CollectT) { reqURL := fmt.Sprintf("http://127.0.0.1:%d/v1.0/publish/%s/%s", c.daprd.HTTPPort(), url.QueryEscape(pubsubName), url.QueryEscape(topicName)) req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, strings.NewReader(`{"status": "completed"}`)) require.NoError(t, err) req.Header.Set("Content-Type", "application/json") resp, err := httpClient.Do(req) require.NoError(t, err) assert.Equal(t, http.StatusNoContent, resp.StatusCode, reqURL) respBody, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) assert.Empty(t, string(respBody)) }) } }
mikeee/dapr
tests/integration/suite/daprd/pubsub/http/compname.go
GO
mit
3,150
/* 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 http 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"), ) e.daprd = daprd.New(t, daprd.WithAppPort(e.sub.Port()), daprd.WithAppProtocol("http"), daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypub spec: type: pubsub.in-memory version: v1 --- apiVersion: dapr.io/v2alpha1 kind: Subscription metadata: name: mysub spec: pubsubname: mypub topic: a routes: rules: - path: /a match: "" `)) 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", Data: `{"status": "completed"}`, }) resp := e.sub.Receive(t, ctx) assert.Equal(t, "/a", resp.Route) }
mikeee/dapr
tests/integration/suite/daprd/pubsub/http/emptymatch.go
GO
mit
1,935
/* 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 http import ( "context" "encoding/json" "errors" "fmt" "io" "net/http" "runtime" "strings" "testing" "github.com/dapr/dapr/tests/integration/framework/socket" "github.com/stretchr/testify/require" componentspubsub "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/pubsub" inmemory "github.com/dapr/dapr/tests/integration/framework/process/pubsub/in-memory" "github.com/dapr/dapr/tests/integration/framework/util" "github.com/dapr/dapr/tests/integration/suite" kiterrors "github.com/dapr/kit/errors" ) const ( ErrInfoType = "type.googleapis.com/google.rpc.ErrorInfo" ResourceInfoType = "type.googleapis.com/google.rpc.ResourceInfo" ) func init() { suite.Register(new(errorcodes)) } type errorcodes struct { daprd *daprd.Daprd } func (e *errorcodes) Setup(t *testing.T) []framework.Option { if runtime.GOOS == "windows" { t.Skip("skipping unix socket based test on windows") } socket := socket.New(t) pubsubInMem := pubsub.New(t, pubsub.WithSocket(socket), pubsub.WithPubSub(inmemory.NewWrappedInMemory(t, inmemory.WithFeatures(), inmemory.WithPublishFn(func(ctx context.Context, req *componentspubsub.PublishRequest) error { return errors.New("outbox error") }), )), ) // spin up a new daprd with a pubsub component e.daprd = daprd.New(t, daprd.WithResourceFiles(fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mypubsub spec: type: pubsub.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: pubsub-outbox spec: type: pubsub.%s version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: state-outbox spec: type: state.in-memory version: v1 metadata: - name: outboxPublishPubsub value: "pubsub-outbox" - name: outboxPublishTopic value: "goodTopic" # force topic mismatch error - name: outboxPubsub value: "pubsub-outbox" - name: outboxDiscardWhenMissingState #Optional. Defaults to false value: false `, pubsubInMem.SocketName())), daprd.WithSocket(t, socket), ) return []framework.Option{ framework.WithProcesses(pubsubInMem, e.daprd), } } func (e *errorcodes) Run(t *testing.T, ctx context.Context) { e.daprd.WaitUntilRunning(t, ctx) httpClient := util.HTTPClient(t) // Covers apierrors.PubSubNotFound() t.Run("pubsub doesn't exist", func(t *testing.T) { name := "pubsub-doesn't-exist" endpoint := fmt.Sprintf("http://localhost:%d/v1.0/publish/%s/topic", e.daprd.HTTPPort(), name) req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader("")) require.NoError(t, err) resp, err := httpClient.Do(req) require.NoError(t, err) require.Equal(t, "application/json", resp.Header.Get("Content-Type")) require.Equal(t, http.StatusNotFound, resp.StatusCode) body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) var data map[string]interface{} err = json.Unmarshal([]byte(string(body)), &data) require.NoError(t, err) // Confirm that the 'errorCode' field exists and contains the correct error code errCode, exists := data["errorCode"] require.True(t, exists) require.Equal(t, "ERR_PUBSUB_NOT_FOUND", errCode) // Confirm that the 'message' field exists and contains the correct error message errMsg, exists := data["message"] require.True(t, exists) require.Equal(t, fmt.Sprintf("pubsub %s is not found", name), errMsg) // Confirm that the 'details' field exists and has one element details, exists := data["details"] require.True(t, exists) detailsArray, ok := details.([]interface{}) require.True(t, ok) require.Len(t, detailsArray, 1) // Confirm that the first element of the 'details' array has the correct ErrorInfo details detailsObject, ok := detailsArray[0].(map[string]interface{}) require.True(t, ok) require.Equal(t, "dapr.io", detailsObject["domain"]) require.Equal(t, kiterrors.CodePrefixPubSub+kiterrors.CodeNotFound, detailsObject["reason"]) require.Equal(t, ErrInfoType, detailsObject["@type"]) }) t.Run("pubsub unmarshal events", func(t *testing.T) { name := "mypubsub" endpoint := fmt.Sprintf("http://localhost:%d/v1.0-alpha1/publish/bulk/%s/topic", e.daprd.HTTPPort(), name) payload := `{"entryID": "}` req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(payload)) require.NoError(t, err) resp, err := httpClient.Do(req) require.NoError(t, err) require.Equal(t, "application/json", resp.Header.Get("Content-Type")) require.Equal(t, http.StatusBadRequest, resp.StatusCode) body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) var data map[string]interface{} err = json.Unmarshal([]byte(string(body)), &data) require.NoError(t, err) // Confirm that the 'errorCode' field exists and contains the correct error code errCode, exists := data["errorCode"] require.True(t, exists) require.Equal(t, "ERR_PUBSUB_EVENTS_SER", errCode) // Confirm that the 'message' field exists and contains the correct error message errMsg, exists := data["message"] require.True(t, exists) expectedErr := "unexpected end of JSON input" require.Equal(t, fmt.Sprintf("error when unmarshaling the request for topic topic pubsub %s: %s", name, expectedErr), errMsg) //nolint:dupword // Confirm that the 'details' field exists and has one element details, exists := data["details"] require.True(t, exists) detailsArray, ok := details.([]interface{}) require.True(t, ok) require.Len(t, detailsArray, 2) // Parse the json into go objects var errInfo map[string]interface{} var resInfo map[string]interface{} for _, detail := range detailsArray { d, ok := detail.(map[string]interface{}) require.True(t, ok) switch d["@type"] { case ErrInfoType: errInfo = d case ResourceInfoType: resInfo = d default: require.FailNow(t, "unexpected status detail") } } // Confirm that the ErrorInfo details are correct require.NotEmptyf(t, errInfo, "ErrorInfo not found in %+v", detailsArray) require.Equal(t, "dapr.io", errInfo["domain"]) require.Equal(t, kiterrors.CodePrefixPubSub+"UNMARSHAL_EVENTS", errInfo["reason"]) // Confirm that the ResourceInfo details are correct require.NotEmptyf(t, resInfo, "ResourceInfo not found in %+v", detailsArray) require.Equal(t, "pubsub", resInfo["resource_type"]) require.Equal(t, name, resInfo["resource_name"]) }) // Covers apierrors.PubSubMetadataDeserialize() t.Run("pubsub metadata deserialization", func(t *testing.T) { name := "mypubsub" endpoint := fmt.Sprintf("http://localhost:%d/v1.0/publish/%s/topic?metadata.rawPayload=invalidBooleanValue", e.daprd.HTTPPort(), name) req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader("")) require.NoError(t, err) resp, err := httpClient.Do(req) require.NoError(t, err) require.Equal(t, "application/json", resp.Header.Get("Content-Type")) require.Equal(t, http.StatusBadRequest, resp.StatusCode) body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) var data map[string]interface{} err = json.Unmarshal([]byte(string(body)), &data) require.NoError(t, err) // Confirm that the 'errorCode' field exists and contains the correct error code errCode, exists := data["errorCode"] require.True(t, exists) require.Equal(t, "ERR_PUBSUB_REQUEST_METADATA", errCode) // Confirm that the 'message' field exists and contains the correct error message errMsg, exists := data["message"] require.True(t, exists) expectedErr := "rawPayload value must be a valid boolean: actual is 'invalidBooleanValue'" require.Equal(t, fmt.Sprintf("failed deserializing metadata. Error: %s", expectedErr), errMsg) // Confirm that the 'details' field exists and has one element details, exists := data["details"] require.True(t, exists) detailsArray, ok := details.([]interface{}) require.True(t, ok) require.Len(t, detailsArray, 2) // Parse the json into go objects var errInfo map[string]interface{} var resInfo map[string]interface{} for _, detail := range detailsArray { d, ok := detail.(map[string]interface{}) require.True(t, ok) switch d["@type"] { case ErrInfoType: errInfo = d case ResourceInfoType: resInfo = d default: require.FailNow(t, "unexpected status detail") } } // Confirm that the ErrorInfo details are correct require.NotEmptyf(t, errInfo, "ErrorInfo not found in %+v", detailsArray) require.Equal(t, "dapr.io", errInfo["domain"]) require.Equal(t, kiterrors.CodePrefixPubSub+"METADATA_DESERIALIZATION", errInfo["reason"]) // Confirm that the ResourceInfo details are correct require.NotEmptyf(t, resInfo, "ResourceInfo not found in %+v", detailsArray) require.Equal(t, "pubsub", resInfo["resource_type"]) require.Equal(t, name, resInfo["resource_name"]) }) // Covers apierrors.PubSubCloudEventCreation() t.Run("pubsub cloud event creation issue", func(t *testing.T) { payload := `{"}` name := "mypubsub" endpoint := fmt.Sprintf("http://localhost:%d/v1.0/publish/%s/topic?metadata.rawPayload=false", e.daprd.HTTPPort(), name) req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(payload)) require.NoError(t, err) req.Header.Set("Content-Type", "application/cloudevents+json") resp, err := httpClient.Do(req) require.NoError(t, err) require.Equal(t, "application/json", resp.Header.Get("Content-Type")) require.Equal(t, http.StatusInternalServerError, resp.StatusCode) body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) var data map[string]interface{} err = json.Unmarshal([]byte(string(body)), &data) require.NoError(t, err) // Confirm that the 'errorCode' field exists and contains the correct error code errCode, exists := data["errorCode"] require.True(t, exists) require.Equal(t, "ERR_PUBSUB_CLOUD_EVENTS_SER", errCode) // Confirm that the 'message' field exists and contains the correct error message errMsg, exists := data["message"] require.True(t, exists) require.Equal(t, "cannot create cloudevent", errMsg) // Confirm that the 'details' field exists and has one element details, exists := data["details"] require.True(t, exists) detailsArray, ok := details.([]interface{}) require.True(t, ok) require.Len(t, detailsArray, 2) // Parse the json into go objects var errInfo map[string]interface{} var resInfo map[string]interface{} for _, detail := range detailsArray { d, ok := detail.(map[string]interface{}) require.True(t, ok) switch d["@type"] { case ErrInfoType: errInfo = d case ResourceInfoType: resInfo = d default: require.FailNow(t, "unexpected status detail") } } // Confirm that the ErrorInfo details are correct require.NotEmptyf(t, errInfo, "ErrorInfo not found in %+v", detailsArray) require.Equal(t, "dapr.io", errInfo["domain"]) require.Equal(t, kiterrors.CodePrefixPubSub+"CLOUD_EVENT_CREATION", errInfo["reason"]) require.NotNil(t, errInfo["metadata"]) // Confirm that the ResourceInfo details are correct require.NotEmptyf(t, resInfo, "ResourceInfo not found in %+v", detailsArray) require.Equal(t, "pubsub", resInfo["resource_type"]) require.Equal(t, name, resInfo["resource_name"]) }) // Covers apierrors.PubSubMarshalEvents() t.Run("pubsub marshal events issue", func(t *testing.T) { name := "mypubsub" endpoint := fmt.Sprintf("http://localhost:%d/v1.0-alpha1/publish/bulk/%s/topic", e.daprd.HTTPPort(), name) payload := `{"entryID": ""}` req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(payload)) require.NoError(t, err) resp, err := httpClient.Do(req) require.NoError(t, err) require.Equal(t, "application/json", resp.Header.Get("Content-Type")) require.Equal(t, http.StatusBadRequest, resp.StatusCode) body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) var data map[string]interface{} err = json.Unmarshal([]byte(string(body)), &data) require.NoError(t, err) // Confirm that the 'errorCode' field exists and contains the correct error code errCode, exists := data["errorCode"] require.True(t, exists) require.Equal(t, "ERR_PUBSUB_EVENTS_SER", errCode) // Confirm that the 'message' field exists and contains the correct error message errMsg, exists := data["message"] require.True(t, exists) expectedErr := "json: cannot unmarshal object into Go value of type []http.bulkPublishMessageEntry" require.Equal(t, fmt.Sprintf("error when unmarshaling the request for topic topic pubsub %s: %s", name, expectedErr), errMsg) //nolint:dupword // Confirm that the 'details' field exists and has one element details, exists := data["details"] require.True(t, exists) detailsArray, ok := details.([]interface{}) require.True(t, ok) require.Len(t, detailsArray, 2) // Parse the json into go objects var errInfo map[string]interface{} var resInfo map[string]interface{} for _, detail := range detailsArray { d, ok := detail.(map[string]interface{}) require.True(t, ok) switch d["@type"] { case ErrInfoType: errInfo = d case ResourceInfoType: resInfo = d default: require.FailNow(t, "unexpected status detail") } } // Confirm that the ErrorInfo details are correct require.NotEmptyf(t, errInfo, "ErrorInfo not found in %+v", detailsArray) require.Equal(t, "dapr.io", errInfo["domain"]) require.Equal(t, kiterrors.CodePrefixPubSub+"UNMARSHAL_EVENTS", errInfo["reason"]) // Confirm that the ResourceInfo details are correct require.NotEmptyf(t, resInfo, "ResourceInfo not found in %+v", detailsArray) require.Equal(t, "pubsub", resInfo["resource_type"]) require.Equal(t, name, resInfo["resource_name"]) }) t.Run("pubsub outbox", func(t *testing.T) { name := "state-outbox" payload := `{"operations": [{"operation": "upsert","request": {"key": "key1","value": "val1"}},{"operation": "delete","request": {"key": "key2"}}],"metadata": {"partitionKey": "key2"}}` endpoint := fmt.Sprintf("http://localhost:%d/v1.0/state/%s/transaction", e.daprd.HTTPPort(), name) req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(payload)) require.NoError(t, err) resp, err := httpClient.Do(req) require.NoError(t, err) require.Equal(t, "application/json", resp.Header.Get("Content-Type")) require.Equal(t, http.StatusInternalServerError, resp.StatusCode) body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) var data map[string]interface{} err = json.Unmarshal([]byte(string(body)), &data) require.NoError(t, err) // Confirm that the 'errorCode' field exists and contains the correct error code errCode, exists := data["errorCode"] require.True(t, exists) require.Equal(t, "ERR_PUBLISH_OUTBOX", errCode) // Confirm that the 'message' field exists and contains the correct error message errMsg, exists := data["message"] require.True(t, exists) expectedErrMsg := "error while publishing outbox message: rpc error: code = Unknown desc = outbox error" require.Equal(t, expectedErrMsg, errMsg) // Confirm that the 'details' field exists and has one element details, exists := data["details"] require.True(t, exists) detailsArray, ok := details.([]interface{}) require.True(t, ok) require.Len(t, detailsArray, 1) // Confirm that the first element of the 'details' array has the correct ErrorInfo details detailsObject, ok := detailsArray[0].(map[string]interface{}) require.True(t, ok) require.Equal(t, "dapr.io", detailsObject["domain"]) require.Equal(t, kiterrors.CodePrefixPubSub+"OUTBOX", detailsObject["reason"]) require.Equal(t, ErrInfoType, detailsObject["@type"]) }) }
mikeee/dapr
tests/integration/suite/daprd/pubsub/http/errors.go
GO
mit
16,739
/* 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 http import ( "bytes" "context" "crypto/rand" "encoding/base64" "encoding/json" "errors" "fmt" "io" "math/big" "net/http" "net/url" "regexp" "strings" "testing" "time" fuzz "github.com/google/gofuzz" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "k8s.io/apimachinery/pkg/api/validation/path" "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(fuzzpubsubNoRaw)) suite.Register(new(fuzzpubsubRaw)) } type fuzzpubsubNoRaw struct { fuzzpubsub } type fuzzpubsubRaw struct { fuzzpubsub } func (f *fuzzpubsubNoRaw) Setup(t *testing.T) []framework.Option { f.fuzzpubsub = fuzzpubsub{withRaw: false} return f.fuzzpubsub.Setup(t) } func (f *fuzzpubsubNoRaw) Run(t *testing.T, ctx context.Context) { f.fuzzpubsub.Run(t, ctx) } func (f *fuzzpubsubRaw) Setup(t *testing.T) []framework.Option { f.fuzzpubsub = fuzzpubsub{withRaw: true} return f.fuzzpubsub.Setup(t) } func (f *fuzzpubsubRaw) Run(t *testing.T, ctx context.Context) { f.fuzzpubsub.Run(t, ctx) } // TODO: @joshvanl: add error to Dapr pubsub subscribe client to reject when // the app returns multiple routes for the same pubsub component + topic. type testPubSub struct { Name string Topics []testTopic } type testTopic struct { Name string Route string payload string } type fuzzpubsub struct { daprd *procdaprd.Daprd withRaw bool pubSubs []testPubSub respChan map[string]chan []byte } type pubSubMessage struct { DataBase64 string `json:"data_base64"` } type pubSubMessageData struct { Data string `json:"data"` } func (f *fuzzpubsub) Setup(t *testing.T) []framework.Option { const numTests = 20 takenNames := make(map[string]bool) reg, err := regexp.Compile("^([a-zA-Z].*)$") require.NoError(t, err) psNameFz := fuzz.New().Funcs(func(s *string, c fuzz.Continue) { for *s == "" || takenNames[*s] || len(path.IsValidPathSegmentName(*s)) > 0 || !reg.MatchString(*s) { *s = c.RandString() } takenNames[*s] = true }) psTopicFz := fuzz.New().Funcs(func(s *string, c fuzz.Continue) { for *s == "" || takenNames[*s] || len(path.IsValidPathSegmentName(*s)) > 0 || strings.HasPrefix(*s, "/") { *s = c.RandString() } takenNames[*s] = true }) psRouteFz := fuzz.New().Funcs(func(s *string, c fuzz.Continue) { for *s == "" || *s == "/" || takenNames[*s] || strings.HasSuffix(*s, "/") || strings.ContainsAny(*s, ".:=?#*% \t{}\n\r") { *s = "/" + c.RandString() } takenNames[*s] = true }) f.pubSubs = make([]testPubSub, numTests) f.respChan = make(map[string]chan []byte) files := make([]string, numTests) for i := 0; i < numTests; i++ { psNameFz.Fuzz(&f.pubSubs[i].Name) topicsB, err := rand.Int(rand.Reader, big.NewInt(30)) require.NoError(t, err) topics := int(topicsB.Int64() + 1) f.pubSubs[i].Topics = make([]testTopic, topics) for j := 0; j < topics; j++ { psTopicFz.Fuzz(&f.pubSubs[i].Topics[j].Name) psRouteFz.Fuzz(&f.pubSubs[i].Topics[j].Route) f.respChan[f.pubSubs[i].Topics[j].Route] = make(chan []byte, 0) fuzz.New().Fuzz(&f.pubSubs[i].Topics[j].payload) } files[i] = fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: '%s' spec: type: pubsub.in-memory version: v1 `, // Escape single quotes in the store name. strings.ReplaceAll(f.pubSubs[i].Name, "'", "''")) } var topicSubs []string handler := http.NewServeMux() for _, sub := range f.pubSubs { pubsubName, err := json.Marshal(sub.Name) require.NoError(t, err) for _, topic := range sub.Topics { topicName, err := json.Marshal(topic.Name) require.NoError(t, err) route, err := json.Marshal(topic.Route) require.NoError(t, err) if f.withRaw { topicSubs = append(topicSubs, fmt.Sprintf(`{ "pubsubname": %s, "topic": %s, "route": %s, "metadata": { "rawPayload": "true" } }`, pubsubName, topicName, route)) } else { topicSubs = append(topicSubs, fmt.Sprintf(`{ "pubsubname": %s, "topic": %s, "route": %s }`, pubsubName, topicName, route)) } handler.HandleFunc(topic.Route, func(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(r.Body) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } f.respChan[r.URL.Path] <- body }) } } handler.HandleFunc("/dapr/subscribe", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("[" + strings.Join(topicSubs, ",") + "]")) }) srv := prochttp.New(t, prochttp.WithHandler(handler)) f.daprd = procdaprd.New(t, procdaprd.WithAppPort(srv.Port()), procdaprd.WithResourceFiles(files...)) return []framework.Option{ framework.WithProcesses(f.daprd, srv), } } func (f *fuzzpubsub) Run(t *testing.T, ctx context.Context) { f.daprd.WaitUntilRunning(t, ctx) t.Skip("TODO: @joshvanl skipping until pubsub publish is made stable") pt := util.NewParallel(t) for i := range f.pubSubs { pubsubName := f.pubSubs[i].Name for j := range f.pubSubs[i].Topics { topicName := f.pubSubs[i].Topics[j].Name route := f.pubSubs[i].Topics[j].Route payload := f.pubSubs[i].Topics[j].payload pt.Add(func(col *assert.CollectT) { reqURL := fmt.Sprintf("http://127.0.0.1:%d/v1.0/publish/%s/%s", f.daprd.HTTPPort(), url.QueryEscape(pubsubName), url.QueryEscape(topicName)) // TODO: @joshvanl: under heavy load, messages seem to get lost here // with no response from Dapr. Until this is fixed, we use to smaller // timeout, and retry on context deadline exceeded. for { reqCtx, cancel := context.WithTimeout(ctx, time.Second*5) t.Cleanup(cancel) b, err := json.Marshal(payload) require.NoError(col, err) req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, reqURL, bytes.NewReader(b)) require.NoError(col, err) req.Header.Set("Content-Type", "application/json") resp, err := util.HTTPClient(t).Do(req) if errors.Is(err, context.DeadlineExceeded) { // Only retry if we haven't exceeded the test timeout. d, ok := ctx.Deadline() require.True(col, ok) require.True(col, time.Now().After(d)) continue } require.NoError(col, err) assert.Equal(col, http.StatusNoContent, resp.StatusCode, reqURL) var respBody []byte respBody, err = io.ReadAll(resp.Body) require.NoError(col, err) require.NoError(col, resp.Body.Close()) assert.Empty(col, string(respBody)) break } select { case body := <-f.respChan[route]: var data []byte if f.withRaw { var message pubSubMessage require.NoError(col, json.Unmarshal(body, &message)) var err error data, err = base64.StdEncoding.DecodeString(message.DataBase64) require.NoError(col, err) } else { data = body } var messageData pubSubMessageData require.NoError(col, json.Unmarshal(data, &messageData), string(data)) assert.Equal(col, payload, messageData.Data) case <-ctx.Done(): t.Fatal("timed out waiting for message") } }) } } }
mikeee/dapr
tests/integration/suite/daprd/pubsub/http/fuzz.go
GO
mit
7,910
/* 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 pubsub import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/pubsub/contentlength" _ "github.com/dapr/dapr/tests/integration/suite/daprd/pubsub/grpc" _ "github.com/dapr/dapr/tests/integration/suite/daprd/pubsub/http" _ "github.com/dapr/dapr/tests/integration/suite/daprd/pubsub/scopes" )
mikeee/dapr
tests/integration/suite/daprd/pubsub/pubsub.go
GO
mit
871
/* 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 scopes import ( "context" "fmt" "os" "path/filepath" "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/grpc/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(allowedtopics)) } type allowedtopics struct { daprd1 *daprd.Daprd daprd2 *daprd.Daprd daprd3 *daprd.Daprd sub *subscriber.Subscriber } func (a *allowedtopics) Setup(t *testing.T) []framework.Option { a.sub = subscriber.New(t) resDir := t.TempDir() a.daprd1 = daprd.New(t, daprd.WithAppPort(a.sub.Port(t)), daprd.WithAppProtocol("grpc"), daprd.WithResourcesDir(resDir), ) a.daprd2 = daprd.New(t, daprd.WithAppPort(a.sub.Port(t)), daprd.WithAppProtocol("grpc"), daprd.WithResourcesDir(resDir), ) a.daprd3 = daprd.New(t, daprd.WithAppPort(a.sub.Port(t)), daprd.WithAppProtocol("grpc"), daprd.WithResourcesDir(resDir), ) var subYaml string for i, sub := range []struct { pubsub string topic string }{ {"topic12", "topic0"}, {"topic12", "topic1"}, {"topic12", "topic2"}, {"topic34-publishing", "topic3"}, {"topic34-publishing", "topic4"}, {"topic56-subscribing", "topic5"}, {"topic56-subscribing", "topic6"}, {"topic789-publishing-subscribing", "topic7"}, {"topic789-publishing-subscribing", "topic8"}, {"topic789-publishing-subscribing", "topic9"}, } { subYaml += fmt.Sprintf(` --- apiVersion: dapr.io/v1alpha1 kind: Subscription metadata: name: sub%d spec: pubsubname: %s topic: %s route: /a `, i+1, sub.pubsub, sub.topic) } require.NoError(t, os.WriteFile(filepath.Join(resDir, "sub.yaml"), []byte(subYaml), 0o600)) require.NoError(t, os.WriteFile(filepath.Join(resDir, "pubsub.yaml"), []byte(fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: topic12 spec: type: pubsub.in-memory version: v1 metadata: - name: allowedTopics value: "topic1,topic2" --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: topic34-publishing spec: type: pubsub.in-memory version: v1 metadata: - name: allowedTopics value: "topic3,topic4" - name: publishingScopes value: "%[1]s=topic3;%[2]s=topic4" --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: topic56-subscribing spec: type: pubsub.in-memory version: v1 metadata: - name: allowedTopics value: "topic5,topic6" - name: subscriptionScopes value: "%[1]s=topic5;%[2]s=topic6" --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: topic789-publishing-subscribing spec: type: pubsub.in-memory version: v1 metadata: - name: allowedTopics value: "topic7,topic8,topic9" - name: subscriptionScopes value: "%[1]s=topic7,topic9;%[2]s=topic8,topic9" - name: publishingScopes value: "%[1]s=topic8,topic9;%[2]s=topic7,topic9" `, a.daprd1.AppID(), a.daprd2.AppID())), 0o600)) return []framework.Option{ framework.WithProcesses(a.sub, a.daprd1, a.daprd2, a.daprd3), } } func (a *allowedtopics) Run(t *testing.T, ctx context.Context) { a.daprd1.WaitUntilRunning(t, ctx) a.daprd2.WaitUntilRunning(t, ctx) a.daprd3.WaitUntilRunning(t, ctx) for _, daprd := range []*daprd.Daprd{a.daprd1, a.daprd2, a.daprd3} { meta, err := daprd.GRPCClient(t, ctx).GetMetadata(ctx, new(rtv1.GetMetadataRequest)) require.NoError(t, err) assert.Len(t, meta.GetRegisteredComponents(), 4) assert.Len(t, meta.GetSubscriptions(), 10) } newReq := func(pubsub, topic string) *rtv1.PublishEventRequest { return &rtv1.PublishEventRequest{PubsubName: pubsub, Topic: topic, Data: []byte(`{"status": "completed"}`)} } req := newReq("topic12", "topic0") a.sub.ExpectPublishError(t, ctx, a.daprd1, req) a.sub.ExpectPublishError(t, ctx, a.daprd2, req) a.sub.ExpectPublishError(t, ctx, a.daprd3, req) req = newReq("topic12", "topic1") a.sub.ExpectPublishReceive(t, ctx, a.daprd1, req) a.sub.ExpectPublishReceive(t, ctx, a.daprd2, req) a.sub.ExpectPublishReceive(t, ctx, a.daprd3, req) req = newReq("topic12", "topic2") a.sub.ExpectPublishReceive(t, ctx, a.daprd1, req) a.sub.ExpectPublishReceive(t, ctx, a.daprd2, req) a.sub.ExpectPublishReceive(t, ctx, a.daprd3, req) req = newReq("topic12", "topic3") a.sub.ExpectPublishError(t, ctx, a.daprd1, req) a.sub.ExpectPublishError(t, ctx, a.daprd2, req) a.sub.ExpectPublishError(t, ctx, a.daprd3, req) req = newReq("topic34-publishing", "topic3") a.sub.ExpectPublishReceive(t, ctx, a.daprd1, req) a.sub.ExpectPublishError(t, ctx, a.daprd2, req) a.sub.ExpectPublishReceive(t, ctx, a.daprd3, req) req = newReq("topic34-publishing", "topic4") a.sub.ExpectPublishError(t, ctx, a.daprd1, req) a.sub.ExpectPublishReceive(t, ctx, a.daprd2, req) a.sub.ExpectPublishReceive(t, ctx, a.daprd3, req) req = newReq("topic56-subscribing", "topic5") a.sub.ExpectPublishReceive(t, ctx, a.daprd1, req) a.sub.ExpectPublishNoReceive(t, ctx, a.daprd2, req) a.sub.ExpectPublishReceive(t, ctx, a.daprd3, req) req = newReq("topic56-subscribing", "topic6") a.sub.ExpectPublishNoReceive(t, ctx, a.daprd1, req) a.sub.ExpectPublishReceive(t, ctx, a.daprd2, req) a.sub.ExpectPublishReceive(t, ctx, a.daprd3, req) req = newReq("topic789-publishing-subscribing", "topic7") a.sub.ExpectPublishError(t, ctx, a.daprd1, req) a.sub.ExpectPublishNoReceive(t, ctx, a.daprd2, req) a.sub.ExpectPublishReceive(t, ctx, a.daprd3, req) req = newReq("topic789-publishing-subscribing", "topic8") a.sub.ExpectPublishNoReceive(t, ctx, a.daprd1, req) a.sub.ExpectPublishError(t, ctx, a.daprd2, req) a.sub.ExpectPublishReceive(t, ctx, a.daprd3, req) req = newReq("topic789-publishing-subscribing", "topic9") a.sub.ExpectPublishReceive(t, ctx, a.daprd1, req) a.sub.ExpectPublishReceive(t, ctx, a.daprd2, req) a.sub.ExpectPublishReceive(t, ctx, a.daprd3, req) }
mikeee/dapr
tests/integration/suite/daprd/pubsub/scopes/allowedtopics.go
GO
mit
6,538
/* 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 scopes import ( "context" "fmt" "os" "path/filepath" "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/grpc/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(protectedtopics)) } type protectedtopics struct { daprd1 *daprd.Daprd daprd2 *daprd.Daprd daprd3 *daprd.Daprd sub *subscriber.Subscriber } func (p *protectedtopics) Setup(t *testing.T) []framework.Option { p.sub = subscriber.New(t) resDir := t.TempDir() p.daprd1 = daprd.New(t, daprd.WithAppPort(p.sub.Port(t)), daprd.WithAppProtocol("grpc"), daprd.WithResourcesDir(resDir), daprd.WithAppID("app1"), ) p.daprd2 = daprd.New(t, daprd.WithAppPort(p.sub.Port(t)), daprd.WithAppProtocol("grpc"), daprd.WithResourcesDir(resDir), daprd.WithAppID("app2"), ) p.daprd3 = daprd.New(t, daprd.WithAppPort(p.sub.Port(t)), daprd.WithAppProtocol("grpc"), daprd.WithResourcesDir(resDir), daprd.WithAppID("app3"), ) var subYaml string for i, sub := range []struct { pubsub string topic string }{ {"topic12", "topic0"}, {"topic12", "topic1"}, {"topic12", "topic2"}, {"topic34-publishing", "topic3"}, {"topic34-publishing", "topic4"}, {"topic56-subscribing", "topic5"}, {"topic56-subscribing", "topic6"}, {"topic789-publishing-subscribing", "topic7"}, {"topic789-publishing-subscribing", "topic8"}, {"topic789-publishing-subscribing", "topic9"}, {"topic789-publishing-subscribing", "topic10"}, } { subYaml += fmt.Sprintf(` --- apiVersion: dapr.io/v1alpha1 kind: Subscription metadata: name: sub%d spec: pubsubname: %s topic: %s route: /a `, i+1, sub.pubsub, sub.topic) } require.NoError(t, os.WriteFile(filepath.Join(resDir, "sub.yaml"), []byte(subYaml), 0o600)) require.NoError(t, os.WriteFile(filepath.Join(resDir, "pubsub.yaml"), []byte(fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: topic12 spec: type: pubsub.in-memory version: v1 metadata: - name: protectedTopics value: "topic1,topic2" --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: topic34-publishing spec: type: pubsub.in-memory version: v1 metadata: - name: protectedTopics value: "topic3,topic4" - name: publishingScopes value: "%[1]s=topic3;%[2]s=topic4" --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: topic56-subscribing spec: type: pubsub.in-memory version: v1 metadata: - name: protectedTopics value: "topic5,topic6" - name: subscriptionScopes value: "%[1]s=topic5;%[2]s=topic6" --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: topic789-publishing-subscribing spec: type: pubsub.in-memory version: v1 metadata: - name: protectedTopics value: "topic7,topic8,topic9,topic10" - name: allowedTopics value: "topic7,topic8,topic9,topic10" - name: subscriptionScopes value: "%[1]s=topic7,topic9;%[2]s=topic8,topic9" - name: publishingScopes value: "%[1]s=topic8,topic9;%[2]s=topic7,topic9" `, p.daprd1.AppID(), p.daprd2.AppID())), 0o600)) return []framework.Option{ framework.WithProcesses(p.sub, p.daprd1, p.daprd2, p.daprd3), } } func (p *protectedtopics) Run(t *testing.T, ctx context.Context) { p.daprd1.WaitUntilRunning(t, ctx) p.daprd2.WaitUntilRunning(t, ctx) p.daprd3.WaitUntilRunning(t, ctx) for _, daprd := range []*daprd.Daprd{p.daprd1, p.daprd2, p.daprd3} { meta, err := daprd.GRPCClient(t, ctx).GetMetadata(ctx, new(rtv1.GetMetadataRequest)) require.NoError(t, err) assert.Len(t, meta.GetRegisteredComponents(), 4) assert.Len(t, meta.GetSubscriptions(), 11) } newReq := func(pubsub, topic string) *rtv1.PublishEventRequest { return &rtv1.PublishEventRequest{PubsubName: pubsub, Topic: topic, Data: []byte(`{"status": "completed"}`)} } req := newReq("topic12", "topic0") p.sub.ExpectPublishReceive(t, ctx, p.daprd1, req) p.sub.ExpectPublishReceive(t, ctx, p.daprd2, req) p.sub.ExpectPublishReceive(t, ctx, p.daprd3, req) req = newReq("topic12", "topic1") p.sub.ExpectPublishError(t, ctx, p.daprd1, req) p.sub.ExpectPublishError(t, ctx, p.daprd2, req) p.sub.ExpectPublishError(t, ctx, p.daprd3, req) req = newReq("topic12", "topic2") p.sub.ExpectPublishError(t, ctx, p.daprd1, req) p.sub.ExpectPublishError(t, ctx, p.daprd2, req) p.sub.ExpectPublishError(t, ctx, p.daprd3, req) req = newReq("topic34-publishing", "topic3") p.sub.ExpectPublishNoReceive(t, ctx, p.daprd1, req) p.sub.ExpectPublishError(t, ctx, p.daprd2, req) p.sub.ExpectPublishError(t, ctx, p.daprd3, req) req = newReq("topic34-publishing", "topic4") p.sub.ExpectPublishError(t, ctx, p.daprd1, req) p.sub.ExpectPublishNoReceive(t, ctx, p.daprd2, req) p.sub.ExpectPublishError(t, ctx, p.daprd3, req) req = newReq("topic56-subscribing", "topic5") p.sub.ExpectPublishError(t, ctx, p.daprd1, req) p.sub.ExpectPublishError(t, ctx, p.daprd2, req) p.sub.ExpectPublishError(t, ctx, p.daprd3, req) req = newReq("topic56-subscribing", "topic6") p.sub.ExpectPublishError(t, ctx, p.daprd1, req) p.sub.ExpectPublishError(t, ctx, p.daprd2, req) p.sub.ExpectPublishError(t, ctx, p.daprd3, req) req = newReq("topic789-publishing-subscribing", "topic7") p.sub.ExpectPublishError(t, ctx, p.daprd1, req) p.sub.ExpectPublishNoReceive(t, ctx, p.daprd2, req) p.sub.ExpectPublishError(t, ctx, p.daprd3, req) req = newReq("topic789-publishing-subscribing", "topic8") p.sub.ExpectPublishNoReceive(t, ctx, p.daprd1, req) p.sub.ExpectPublishError(t, ctx, p.daprd2, req) p.sub.ExpectPublishError(t, ctx, p.daprd3, req) req = newReq("topic789-publishing-subscribing", "topic9") p.sub.ExpectPublishReceive(t, ctx, p.daprd1, req) p.sub.ExpectPublishReceive(t, ctx, p.daprd2, req) p.sub.ExpectPublishError(t, ctx, p.daprd3, req) req = newReq("topic789-publishing-subscribing", "topic10") p.sub.ExpectPublishError(t, ctx, p.daprd1, req) p.sub.ExpectPublishError(t, ctx, p.daprd2, req) p.sub.ExpectPublishError(t, ctx, p.daprd3, req) }
mikeee/dapr
tests/integration/suite/daprd/pubsub/scopes/protectedtopics.go
GO
mit
6,754
/* 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 scopes import ( "context" "fmt" "os" "path/filepath" "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/grpc/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(publishing)) } type publishing struct { daprd1 *daprd.Daprd daprd2 *daprd.Daprd daprd3 *daprd.Daprd sub *subscriber.Subscriber } func (p *publishing) Setup(t *testing.T) []framework.Option { p.sub = subscriber.New(t) resDir := t.TempDir() p.daprd1 = daprd.New(t, daprd.WithAppPort(p.sub.Port(t)), daprd.WithAppProtocol("grpc"), daprd.WithResourcesDir(resDir), ) p.daprd2 = daprd.New(t, daprd.WithAppPort(p.sub.Port(t)), daprd.WithAppProtocol("grpc"), daprd.WithResourcesDir(resDir), ) p.daprd3 = daprd.New(t, daprd.WithAppPort(p.sub.Port(t)), daprd.WithAppProtocol("grpc"), daprd.WithResourcesDir(resDir), ) var subYaml string for i, sub := range []struct { pubsub string topic string }{ {"all", "topic1"}, {"allempty", "topic2"}, {"app1-topic34", "topic3"}, {"app1-topic34", "topic4"}, {"app2-topic56", "topic5"}, {"app2-topic56", "topic6"}, {"app1-topic7-app2-topic8", "topic7"}, {"app1-topic7-app2-topic8", "topic8"}, {"app1-nil-app2-topic910", "topic9"}, {"app1-nil-app2-topic910", "topic10"}, } { subYaml += fmt.Sprintf(` --- apiVersion: dapr.io/v1alpha1 kind: Subscription metadata: name: sub%d spec: pubsubname: %s topic: %s route: /a `, i+1, sub.pubsub, sub.topic) } require.NoError(t, os.WriteFile(filepath.Join(resDir, "sub.yaml"), []byte(subYaml), 0o600)) require.NoError(t, os.WriteFile(filepath.Join(resDir, "pubsub.yaml"), []byte(fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: all spec: type: pubsub.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: allempty spec: type: pubsub.in-memory version: v1 metadata: - name: publishingScopes value: "" --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: app1-topic34 spec: type: pubsub.in-memory version: v1 metadata: - name: publishingScopes value: "%[1]s=topic3,topic4" --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: app2-topic56 spec: type: pubsub.in-memory version: v1 metadata: - name: publishingScopes value: "%[2]s=topic5,topic6" --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: app1-topic7-app2-topic8 spec: type: pubsub.in-memory version: v1 metadata: - name: publishingScopes value: "%[1]s=topic7;%[2]s=topic8" --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: app1-nil-app2-topic910 spec: type: pubsub.in-memory version: v1 metadata: - name: publishingScopes value: "%[1]s=;%[2]s=topic9,topic10" `, p.daprd1.AppID(), p.daprd2.AppID())), 0o600)) return []framework.Option{ framework.WithProcesses(p.sub, p.daprd1, p.daprd2, p.daprd3), } } func (p *publishing) Run(t *testing.T, ctx context.Context) { p.daprd1.WaitUntilRunning(t, ctx) p.daprd2.WaitUntilRunning(t, ctx) p.daprd3.WaitUntilRunning(t, ctx) for _, daprd := range []*daprd.Daprd{p.daprd1, p.daprd2, p.daprd3} { meta, err := daprd.GRPCClient(t, ctx).GetMetadata(ctx, new(rtv1.GetMetadataRequest)) require.NoError(t, err) assert.Len(t, meta.GetRegisteredComponents(), 6) assert.Len(t, meta.GetSubscriptions(), 10) } newReq := func(pubsub, topic string) *rtv1.PublishEventRequest { return &rtv1.PublishEventRequest{PubsubName: pubsub, Topic: topic, Data: []byte(`{"status": "completed"}`)} } for _, req := range []*rtv1.PublishEventRequest{ newReq("all", "topic1"), newReq("allempty", "topic2"), newReq("app1-topic34", "topic3"), newReq("app1-topic34", "topic4"), newReq("app2-topic56", "topic5"), newReq("app2-topic56", "topic6"), } { t.Run("pubsub="+req.GetPubsubName()+",topic="+req.GetTopic(), func(t *testing.T) { p.sub.ExpectPublishReceive(t, ctx, p.daprd1, req) p.sub.ExpectPublishReceive(t, ctx, p.daprd2, req) p.sub.ExpectPublishReceive(t, ctx, p.daprd3, req) }) } req := newReq("app1-topic7-app2-topic8", "topic7") p.sub.ExpectPublishReceive(t, ctx, p.daprd1, req) p.sub.ExpectPublishError(t, ctx, p.daprd2, req) p.sub.ExpectPublishReceive(t, ctx, p.daprd3, req) req = newReq("app1-topic7-app2-topic8", "topic8") p.sub.ExpectPublishError(t, ctx, p.daprd1, req) p.sub.ExpectPublishReceive(t, ctx, p.daprd2, req) p.sub.ExpectPublishReceive(t, ctx, p.daprd3, req) req = newReq("app1-nil-app2-topic910", "topic9") p.sub.ExpectPublishError(t, ctx, p.daprd1, req) p.sub.ExpectPublishReceive(t, ctx, p.daprd2, req) p.sub.ExpectPublishReceive(t, ctx, p.daprd3, req) req = newReq("app1-nil-app2-topic910", "topic10") p.sub.ExpectPublishError(t, ctx, p.daprd1, req) p.sub.ExpectPublishReceive(t, ctx, p.daprd2, req) p.sub.ExpectPublishReceive(t, ctx, p.daprd3, req) }
mikeee/dapr
tests/integration/suite/daprd/pubsub/scopes/publishing.go
GO
mit
5,662
/* 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 scopes import ( "context" "fmt" "os" "path/filepath" "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/grpc/subscriber" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(subscription)) } type subscription struct { daprd1 *daprd.Daprd daprd2 *daprd.Daprd daprd3 *daprd.Daprd sub *subscriber.Subscriber } func (s *subscription) Setup(t *testing.T) []framework.Option { s.sub = subscriber.New(t) resDir := t.TempDir() s.daprd1 = daprd.New(t, daprd.WithAppPort(s.sub.Port(t)), daprd.WithAppProtocol("grpc"), daprd.WithResourcesDir(resDir), ) s.daprd2 = daprd.New(t, daprd.WithAppPort(s.sub.Port(t)), daprd.WithAppProtocol("grpc"), daprd.WithResourcesDir(resDir), ) s.daprd3 = daprd.New(t, daprd.WithAppPort(s.sub.Port(t)), daprd.WithAppProtocol("grpc"), daprd.WithResourcesDir(resDir), ) var subYaml string for i, sub := range []struct { pubsub string topic string }{ {"all", "topic1"}, {"allempty", "topic2"}, {"app1-topic34", "topic3"}, {"app1-topic34", "topic4"}, {"app2-topic56", "topic5"}, {"app2-topic56", "topic6"}, {"app1-topic7-app2-topic8", "topic7"}, {"app1-topic7-app2-topic8", "topic8"}, {"app1-nil-app2-topic910", "topic9"}, {"app1-nil-app2-topic910", "topic10"}, } { subYaml += fmt.Sprintf(` --- apiVersion: dapr.io/v1alpha1 kind: Subscription metadata: name: sub%d spec: pubsubname: %s topic: %s route: /a `, i+1, sub.pubsub, sub.topic) } require.NoError(t, os.WriteFile(filepath.Join(resDir, "sub.yaml"), []byte(subYaml), 0o600)) require.NoError(t, os.WriteFile(filepath.Join(resDir, "pubsub.yaml"), []byte(fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: all spec: type: pubsub.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: allempty spec: type: pubsub.in-memory version: v1 metadata: - name: subscriptionScopes value: "" --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: app1-topic34 spec: type: pubsub.in-memory version: v1 metadata: - name: subscriptionScopes value: "%[1]s=topic3,topic4" --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: app2-topic56 spec: type: pubsub.in-memory version: v1 metadata: - name: subscriptionScopes value: "%[2]s=topic5,topic6" --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: app1-topic7-app2-topic8 spec: type: pubsub.in-memory version: v1 metadata: - name: subscriptionScopes value: "%[1]s=topic7;%[2]s=topic8" --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: app1-nil-app2-topic910 spec: type: pubsub.in-memory version: v1 metadata: - name: subscriptionScopes value: "%[1]s=;%[2]s=topic9,topic10" `, s.daprd1.AppID(), s.daprd2.AppID())), 0o600)) return []framework.Option{ framework.WithProcesses(s.sub, s.daprd1, s.daprd2, s.daprd3), } } func (s *subscription) Run(t *testing.T, ctx context.Context) { s.daprd1.WaitUntilRunning(t, ctx) s.daprd2.WaitUntilRunning(t, ctx) s.daprd3.WaitUntilRunning(t, ctx) for _, daprd := range []*daprd.Daprd{s.daprd1, s.daprd2, s.daprd3} { meta, err := daprd.GRPCClient(t, ctx).GetMetadata(ctx, new(rtv1.GetMetadataRequest)) require.NoError(t, err) assert.Len(t, meta.GetRegisteredComponents(), 6) assert.Len(t, meta.GetSubscriptions(), 10) } newReq := func(pubsub, topic string) *rtv1.PublishEventRequest { return &rtv1.PublishEventRequest{PubsubName: pubsub, Topic: topic, Data: []byte(`{"status": "completed"}`)} } for _, req := range []*rtv1.PublishEventRequest{ newReq("all", "topic1"), newReq("allempty", "topic2"), newReq("app1-topic34", "topic3"), newReq("app1-topic34", "topic4"), newReq("app2-topic56", "topic5"), newReq("app2-topic56", "topic6"), } { t.Run("pubsub="+req.GetPubsubName()+",topic="+req.GetTopic(), func(t *testing.T) { s.sub.ExpectPublishReceive(t, ctx, s.daprd1, req) s.sub.ExpectPublishReceive(t, ctx, s.daprd2, req) s.sub.ExpectPublishReceive(t, ctx, s.daprd3, req) }) } req := newReq("app1-topic7-app2-topic8", "topic7") s.sub.ExpectPublishReceive(t, ctx, s.daprd1, req) s.sub.ExpectPublishNoReceive(t, ctx, s.daprd2, req) s.sub.ExpectPublishReceive(t, ctx, s.daprd3, req) req = newReq("app1-topic7-app2-topic8", "topic8") s.sub.ExpectPublishNoReceive(t, ctx, s.daprd1, req) s.sub.ExpectPublishReceive(t, ctx, s.daprd2, req) s.sub.ExpectPublishReceive(t, ctx, s.daprd3, req) req = newReq("app1-nil-app2-topic910", "topic9") s.sub.ExpectPublishNoReceive(t, ctx, s.daprd1, req) s.sub.ExpectPublishReceive(t, ctx, s.daprd2, req) s.sub.ExpectPublishReceive(t, ctx, s.daprd3, req) req = newReq("app1-nil-app2-topic910", "topic10") s.sub.ExpectPublishNoReceive(t, ctx, s.daprd1, req) s.sub.ExpectPublishReceive(t, ctx, s.daprd2, req) s.sub.ExpectPublishReceive(t, ctx, s.daprd3, req) }
mikeee/dapr
tests/integration/suite/daprd/pubsub/scopes/subscription.go
GO
mit
5,696
/* 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 apps import ( "context" "fmt" "io" "net/http" "strings" "sync/atomic" "testing" "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/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(defaultretry)) } type defaultretry struct { daprd1 *daprd.Daprd daprd2 *daprd.Daprd callCount map[string]*atomic.Int32 } func (d *defaultretry) Setup(t *testing.T) []framework.Option { handler := http.NewServeMux() handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(r.Method)) }) handler.HandleFunc("/retry", func(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(r.Body) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } key := string(body) if d.callCount[key] == nil { d.callCount[key] = &atomic.Int32{} } d.callCount[key].Add(1) w.Header().Set("x-method", r.Method) w.Header().Set("content-type", "application/json") if key == "success" { w.WriteHeader(http.StatusOK) } else { w.WriteHeader(http.StatusBadRequest) } w.Write(body) }) srv := prochttp.New(t, prochttp.WithHandler(handler)) resiliency := ` apiVersion: dapr.io/v1alpha1 kind: Resiliency metadata: name: myresiliency spec: policies: retries: DefaultAppRetryPolicy: policy: constant duration: 100ms maxRetries: 3 targets: {} ` d.daprd1 = daprd.New(t, daprd.WithAppPort(srv.Port()), daprd.WithResourceFiles(resiliency), ) d.daprd2 = daprd.New(t, daprd.WithAppPort(srv.Port()), daprd.WithResourceFiles(resiliency), ) d.callCount = make(map[string]*atomic.Int32) return []framework.Option{ framework.WithProcesses(srv, d.daprd1, d.daprd2), } } func (d *defaultretry) Run(t *testing.T, ctx context.Context) { d.daprd1.WaitUntilRunning(t, ctx) d.daprd2.WaitUntilRunning(t, ctx) t.Run("no retry on successful statuscode", func(t *testing.T) { reqURL := fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/retry", d.daprd1.HTTPPort(), d.daprd2.AppID()) req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, strings.NewReader("success")) require.NoError(t, err) resp, err := util.HTTPClient(t).Do(req) require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) assert.Equal(t, "POST", resp.Header.Get("x-method")) assert.Equal(t, "application/json", resp.Header.Get("content-type")) assert.Equal(t, "success", string(body)) // CallCount["success"] should be 1 as there would be no retry on successful statuscode assert.Equal(t, int32(1), d.callCount["success"].Load()) }) t.Run("retry on unsuccessful statuscode", func(t *testing.T) { reqURL := fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/retry", d.daprd1.HTTPPort(), d.daprd2.AppID()) req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, strings.NewReader("fail")) require.NoError(t, err) resp, err := util.HTTPClient(t).Do(req) require.NoError(t, err) assert.Equal(t, http.StatusBadRequest, resp.StatusCode) body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) assert.Equal(t, "POST", resp.Header.Get("x-method")) assert.Equal(t, "application/json", resp.Header.Get("content-type")) assert.Equal(t, "fail", string(body)) // Callcount["fail"] should be 4 as there will be 3 retries(maxRetries=3) assert.Equal(t, int32(4), d.callCount["fail"].Load()) }) }
mikeee/dapr
tests/integration/suite/daprd/resiliency/apps/defaultretry.go
GO
mit
4,389
/* 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 apps import ( "context" "fmt" "io" "net/http" "testing" "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/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(defaulttimeout)) } type defaulttimeout struct { daprd1 *daprd.Daprd daprd2 *daprd.Daprd } func (d *defaulttimeout) Setup(t *testing.T) []framework.Option { handler := http.NewServeMux() handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(r.Method)) }) srv := prochttp.New(t, prochttp.WithHandler(handler)) resiliency := ` apiVersion: dapr.io/v1alpha1 kind: Resiliency metadata: name: myresiliency spec: policies: timeouts: DefaultAppTimeoutPolicy: 30s targets: {} ` d.daprd1 = daprd.New(t, daprd.WithAppPort(srv.Port()), daprd.WithResourceFiles(resiliency), daprd.WithLogLevel("debug"), ) d.daprd2 = daprd.New(t, daprd.WithAppPort(srv.Port()), daprd.WithResourceFiles(resiliency), ) return []framework.Option{ framework.WithProcesses(srv, d.daprd1, d.daprd2), } } func (d *defaulttimeout) Run(t *testing.T, ctx context.Context) { d.daprd1.WaitUntilRunning(t, ctx) d.daprd2.WaitUntilRunning(t, ctx) client := util.HTTPClient(t) url := fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/test", d.daprd1.HTTPPort(), d.daprd2.AppID()) req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) require.NoError(t, err) resp, err := client.Do(req) require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) assert.Equal(t, "GET", string(body)) }
mikeee/dapr
tests/integration/suite/daprd/resiliency/apps/defaulttimeout.go
GO
mit
2,508
/* 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 resiliency import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/resiliency/apps" )
mikeee/dapr
tests/integration/suite/daprd/resiliency/resiliency.go
GO
mit
664
/* 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 resources 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/exec" "github.com/dapr/dapr/tests/integration/framework/process/logline" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(dapr)) } // dapr ensures that a component with the name `dapr` can be loaded. type dapr struct { daprd *daprd.Daprd logline *logline.LogLine } func (d *dapr) Setup(t *testing.T) []framework.Option { d.logline = logline.New(t, logline.WithStdoutLineContains( "Component loaded: dapr (state.in-memory/v1)", "Workflow engine initialized.", ), ) d.daprd = daprd.New(t, daprd.WithResourceFiles( `apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: dapr spec: type: state.in-memory version: v1 `), daprd.WithExecOptions( exec.WithStdout(d.logline.Stdout()), ), ) return []framework.Option{ framework.WithProcesses(d.logline, d.daprd), } } func (d *dapr) Run(t *testing.T, ctx context.Context) { d.logline.EventuallyFoundAll(t) }
mikeee/dapr
tests/integration/suite/daprd/resources/dapr.go
GO
mit
1,722
/* 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 namespace import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/resources/namespace/set" _ "github.com/dapr/dapr/tests/integration/suite/daprd/resources/namespace/unset" )
mikeee/dapr
tests/integration/suite/daprd/resources/namespace/namespace.go
GO
mit
753
/* 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 set 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/suite" ) func init() { suite.Register(new(name)) } // name ensures that when the NAMESPACE env var is set, components will only be // loaded if they reside in the same namespace (or when namespace is omitted). type name struct { daprd *daprd.Daprd } func (n *name) Setup(t *testing.T) []framework.Option { n.daprd = daprd.New(t, daprd.WithResourceFiles(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: abc namespace: abc spec: type: state.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: 123 spec: type: state.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: 456 namespace: foobar spec: type: state.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: 789 namespace: mynamespace spec: type: state.in-memory version: v1 `), daprd.WithNamespace("mynamespace"), ) return []framework.Option{ framework.WithProcesses(n.daprd), } } func (n *name) Run(t *testing.T, ctx context.Context) { n.daprd.WaitUntilRunning(t, ctx) resp, err := n.daprd.GRPCClient(t, ctx).GetMetadata(ctx, new(rtv1.GetMetadataRequest)) require.NoError(t, err) assert.ElementsMatch(t, []*rtv1.RegisteredComponents{ { Name: "123", Type: "state.in-memory", Version: "v1", Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"}, }, { Name: "789", Type: "state.in-memory", Version: "v1", Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"}, }, }, resp.GetRegisteredComponents()) }
mikeee/dapr
tests/integration/suite/daprd/resources/namespace/set/name.go
GO
mit
2,479
/* 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 set 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/logline" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(unique)) } // unique tests that components loaded in self hosted mode in the same // namespace and same name will cause a component conflict. type unique struct { daprd *daprd.Daprd logline *logline.LogLine } func (u *unique) Setup(t *testing.T) []framework.Option { u.logline = logline.New(t, logline.WithStdoutLineContains( `Fatal error from runtime: failed to load components: duplicate definition of Component name abc (pubsub.in-memory/v1) with existing abc (state.in-memory/v1)\nduplicate definition of Component name 123 (state.in-memory/v1) with existing 123 (state.in-memory/v1)\nduplicate definition of Component name 123 (pubsub.in-memory/v1) with existing 123 (state.in-memory/v1)`, )) u.daprd = daprd.New(t, daprd.WithResourceFiles(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: abc namespace: mynamespace spec: type: state.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: abc spec: type: pubsub.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: abc namespace: foobar spec: type: state.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: 123 spec: type: state.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: 123 namespace: mynamespace spec: type: state.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: 123 spec: type: pubsub.in-memory version: v1 `), daprd.WithNamespace("mynamespace"), daprd.WithExit1(), daprd.WithLogLineStdout(u.logline), ) return []framework.Option{ framework.WithProcesses(u.logline, u.daprd), } } func (u *unique) Run(t *testing.T, ctx context.Context) { u.logline.EventuallyFoundAll(t) }
mikeee/dapr
tests/integration/suite/daprd/resources/namespace/set/unique.go
GO
mit
2,650
/* 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 unset 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/suite" ) func init() { suite.Register(new(name)) } // name ensures that when the NAMESPACE env var is *not* set, all components will // be loaded into as the default namespace, regardless of whether they have a // namespace set in their metadata. type name struct { daprd *daprd.Daprd } func (n *name) Setup(t *testing.T) []framework.Option { n.daprd = daprd.New(t, daprd.WithResourceFiles(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: abc namespace: abc spec: type: state.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: 123 spec: type: state.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: 456 namespace: foobar spec: type: state.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: 789 namespace: mynamespace spec: type: state.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(n.daprd), } } func (n *name) Run(t *testing.T, ctx context.Context) { n.daprd.WaitUntilRunning(t, ctx) resp, err := n.daprd.GRPCClient(t, ctx).GetMetadata(ctx, new(rtv1.GetMetadataRequest)) require.NoError(t, err) assert.ElementsMatch(t, []*rtv1.RegisteredComponents{ { Name: "abc", Type: "state.in-memory", Version: "v1", Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"}, }, { Name: "123", Type: "state.in-memory", Version: "v1", Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"}, }, { Name: "456", Type: "state.in-memory", Version: "v1", Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"}, }, { Name: "789", Type: "state.in-memory", Version: "v1", Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"}, }, }, resp.GetRegisteredComponents()) }
mikeee/dapr
tests/integration/suite/daprd/resources/namespace/unset/name.go
GO
mit
2,787
/* 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 unset 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/logline" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(unique)) } // unique tests that components loaded in self hosted mode in the same // namespace and same name will cause a component conflict. When the NAMESPACE // environment variable isn't set, all components are loaded into the default // namespace. type unique struct { daprd *daprd.Daprd logline *logline.LogLine } func (u *unique) Setup(t *testing.T) []framework.Option { u.logline = logline.New(t, logline.WithStdoutLineContains( `Fatal error from runtime: failed to load components: duplicate definition of Component name abc (pubsub.in-memory/v1) with existing abc (state.in-memory/v1)\nduplicate definition of Component name abc (state.in-memory/v1) with existing abc (state.in-memory/v1)\nduplicate definition of Component name 123 (state.in-memory/v1) with existing 123 (state.in-memory/v1)\nduplicate definition of Component name 123 (pubsub.in-memory/v1) with existing 123 (state.in-memory/v1)`, )) u.daprd = daprd.New(t, daprd.WithResourceFiles(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: abc namespace: mynamespace spec: type: state.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: abc spec: type: pubsub.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: abc namespace: foobar spec: type: state.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: 123 spec: type: state.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: 123 namespace: mynamespace spec: type: state.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: 123 spec: type: pubsub.in-memory version: v1 `), daprd.WithExit1(), daprd.WithLogLineStdout(u.logline), ) return []framework.Option{ framework.WithProcesses(u.logline, u.daprd), } } func (u *unique) Run(t *testing.T, ctx context.Context) { u.logline.EventuallyFoundAll(t) }
mikeee/dapr
tests/integration/suite/daprd/resources/namespace/unset/unique.go
GO
mit
2,829
/* 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 resources import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/resources/namespace" )
mikeee/dapr
tests/integration/suite/daprd/resources/resource.go
GO
mit
667
/* 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 resources import ( "context" "fmt" "os" "path/filepath" "testing" "time" "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/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(uniquename)) } // uniquename tests dapr will error if a component is registered with a name // that already exists. type uniquename struct { daprd *daprd.Daprd logline *logline.LogLine } func (u *uniquename) Setup(t *testing.T) []framework.Option { filename := filepath.Join(t.TempDir(), "secrets.json") require.NoError(t, os.WriteFile(filename, []byte(`{"key1":"bla"}`), 0o600)) u.logline = logline.New(t, logline.WithStdoutLineContains( "Fatal error from runtime: failed to load components: duplicate definition of Component name foo (state.in-memory/v1) with existing foo (secretstores.local.file/v1)", ), ) u.daprd = daprd.New(t, daprd.WithResourceFiles( fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: foo spec: type: secretstores.local.file version: v1 metadata: - name: secretsFile value: '%s' --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: foo spec: type: state.in-memory version: v1 `, filename)), daprd.WithExecOptions( exec.WithExitCode(1), exec.WithRunError(func(t *testing.T, err error) { require.ErrorContains(t, err, "exit status 1") }), exec.WithStdout(u.logline.Stdout()), ), ) return []framework.Option{ framework.WithProcesses(u.logline, u.daprd), } } func (u *uniquename) Run(t *testing.T, ctx context.Context) { assert.Eventually(t, u.logline.FoundAll, time.Second*5, time.Millisecond*10) }
mikeee/dapr
tests/integration/suite/daprd/resources/uniquename.go
GO
mit
2,490
/* 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 resources import ( "context" "testing" "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(versionv2)) } // versionv2 tests dapr will load v1 and v2 components. type versionv2 struct { proc *procdaprd.Daprd } func (v *versionv2) Setup(t *testing.T) []framework.Option { v.proc = procdaprd.New(t, procdaprd.WithResourceFiles(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: inmem-v1 spec: type: state.in-memory --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: inmem-omitted spec: type: state.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: etcd-v1 spec: type: state.etcd version: v1 metadata: - name: endpoints value: "localhost:12379" - name: keyPrefixPath value: "daprv1" - name: tlsEnable value: "false" --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: etcd-v2 spec: type: state.etcd version: v2 metadata: - name: endpoints value: "localhost:12379" - name: keyPrefixPath value: "daprv2" - name: tlsEnable value: "false" --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: etcd-omitted spec: type: state.etcd metadata: - name: endpoints value: "localhost:12379" - name: keyPrefixPath value: "daprv1" - name: tlsEnable value: "false" `)) return []framework.Option{ framework.WithProcesses(v.proc), } } func (v *versionv2) Run(t *testing.T, ctx context.Context) { v.proc.WaitUntilRunning(t, ctx) }
mikeee/dapr
tests/integration/suite/daprd/resources/versionv2.go
GO
mit
2,261
/* 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 resources 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(workflow)) } // workflow ensures a Component with type `dapr.workflow` cannot be loaded. type workflow struct { daprd *daprd.Daprd logline *logline.LogLine } func (w *workflow) Setup(t *testing.T) []framework.Option { w.logline = logline.New(t, logline.WithStdoutLineContains( "process component myworkflow error: incorrect type workflow.dapr", ), ) w.daprd = daprd.New(t, daprd.WithResourceFiles( `apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: myworkflow spec: type: workflow.dapr version: v1 `), daprd.WithExecOptions( exec.WithExitCode(1), exec.WithRunError(func(t *testing.T, err error) { require.ErrorContains(t, err, "exit status 1") }), exec.WithStdout(w.logline.Stdout()), ), ) return []framework.Option{ framework.WithProcesses(w.logline, w.daprd), } } func (w *workflow) Run(t *testing.T, ctx context.Context) { w.logline.EventuallyFoundAll(t) }
mikeee/dapr
tests/integration/suite/daprd/resources/workflow.go
GO
mit
1,911
/* 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 http import ( "context" "fmt" "io" "net/http" "net/url" "os" "regexp" "strings" "testing" fuzz "github.com/google/gofuzz" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "k8s.io/apimachinery/pkg/api/validation/path" "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(componentName)) } type componentName struct { daprd *procdaprd.Daprd secretStoreNames []string } func (c *componentName) Setup(t *testing.T) []framework.Option { const numTests = 1000 takenNames := make(map[string]bool) reg, err := regexp.Compile("^([a-zA-Z].*)$") require.NoError(t, err) fz := fuzz.New().Funcs(func(s *string, c fuzz.Continue) { for *s == "" || takenNames[*s] || len(path.IsValidPathSegmentName(*s)) > 0 || !reg.MatchString(*s) { *s = c.RandString() } takenNames[*s] = true }) c.secretStoreNames = make([]string, numTests) for i := 0; i < numTests; i++ { fz.Fuzz(&c.secretStoreNames[i]) } secretFileNames := util.FileNames(t, numTests) files := make([]string, numTests) for i, secretFileName := range secretFileNames { require.NoError(t, os.WriteFile(secretFileName, []byte("{}"), 0o600)) files[i] = fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: '%s' spec: type: secretstores.local.file version: v1 metadata: - name: secretsFile value: '%s' `, // Escape single quotes in the store name. strings.ReplaceAll(c.secretStoreNames[i], "'", "''"), strings.ReplaceAll(secretFileName, "'", "''"), ) } c.daprd = procdaprd.New(t, procdaprd.WithResourceFiles(files...)) return []framework.Option{ framework.WithProcesses(c.daprd), } } func (c *componentName) Run(t *testing.T, ctx context.Context) { c.daprd.WaitUntilRunning(t, ctx) client := util.HTTPClient(t) pt := util.NewParallel(t) for _, secretStoreName := range c.secretStoreNames { secretStoreName := secretStoreName pt.Add(func(t *assert.CollectT) { getURL := fmt.Sprintf("http://localhost:%d/v1.0/secrets/%s/key1", c.daprd.HTTPPort(), url.QueryEscape(secretStoreName)) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) require.NoError(t, err) resp, err := client.Do(req) require.NoError(t, err) // TODO: @joshvanl: 500 is obviously the wrong status code here and // should be changed. assert.Equal(t, http.StatusInternalServerError, resp.StatusCode) respBody, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) assert.Contains(t, string(respBody), "ERR_SECRET_GET") assert.Contains(t, string(respBody), "secret key1 not found") }) } }
mikeee/dapr
tests/integration/suite/daprd/secret/http/compname.go
GO
mit
3,424
/* 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 http import ( "context" "encoding/base64" "encoding/json" "fmt" "io" "net/http" "net/url" "os" "strings" "testing" "time" fuzz "github.com/google/gofuzz" "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(fuzzsecret)) } type secretValuesFile map[string]string type fuzzsecret struct { daprd *procdaprd.Daprd secretStoreName string values secretValuesFile } func (f *fuzzsecret) Setup(t *testing.T) []framework.Option { const numTests = 1000 takenNames := make(map[string]bool) f.secretStoreName = util.RandomString(t, 10) f.values = make(map[string]string) for i := 0; i < numTests; i++ { var key, value string for len(key) == 0 || takenNames[key] { fuzz.New().Fuzz(&key) } fuzz.New().Fuzz(&value) // TODO: @joshvanl: resolve string encoding issues for keys and values, so // we don't need to base64 encode here. key = base64.StdEncoding.EncodeToString([]byte(key)) value = base64.StdEncoding.EncodeToString([]byte(value)) f.values[key] = value takenNames[key] = true } secretFileName := util.FileNames(t, 1)[0] file, err := os.Create(secretFileName) require.NoError(t, err) je := json.NewEncoder(file) je.SetEscapeHTML(false) require.NoError(t, je.Encode(f.values)) require.NoError(t, file.Close()) f.daprd = procdaprd.New(t, procdaprd.WithResourceFiles((fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: '%s' spec: type: secretstores.local.file version: v1 metadata: - name: secretsFile value: '%s' `, f.secretStoreName, strings.ReplaceAll(secretFileName, "'", "''"), )))) return []framework.Option{ framework.WithProcesses(f.daprd), } } func (f *fuzzsecret) Run(t *testing.T, ctx context.Context) { f.daprd.WaitUntilRunning(t, ctx) client := util.HTTPClient(t) assert.EventuallyWithT(t, func(c *assert.CollectT) { assert.Len(c, util.GetMetaComponents(c, ctx, client, f.daprd.HTTPPort()), 1) }, time.Second*20, time.Millisecond*10) pt := util.NewParallel(t) for key, value := range f.values { key := key value := value pt.Add(func(t *assert.CollectT) { getURL := fmt.Sprintf("http://localhost:%d/v1.0/secrets/%s/%s", f.daprd.HTTPPort(), url.QueryEscape(f.secretStoreName), url.QueryEscape(key)) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) require.NoError(t, err) resp, err := client.Do(req) require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) respBody, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) assert.Equal(t, `{"`+key+`":"`+value+`"}`, strings.TrimSpace(string(respBody))) }) } // TODO: Bulk APIs, nesting, multi-valued }
mikeee/dapr
tests/integration/suite/daprd/secret/http/fuzz.go
GO
mit
3,562
/* 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 secret import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/secret/http" )
mikeee/dapr
tests/integration/suite/daprd/secret/secret.go
GO
mit
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 implieh. See the License for the specific language governing permissions and limitations under the License. */ package appapitoken import ( "context" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc/metadata" "google.golang.org/protobuf/types/known/anypb" commonv1 "github.com/dapr/dapr/pkg/proto/common/v1" runtimev1 "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" testpb "github.com/dapr/dapr/tests/integration/suite/daprd/serviceinvocation/grpc/proto" ) func init() { suite.Register(new(remotebothtokens)) } type remotebothtokens struct { daprd1 *daprd.Daprd daprd2 *daprd.Daprd ch chan metadata.MD } func (b *remotebothtokens) Setup(t *testing.T) []framework.Option { fn, ch := newServer() b.ch = ch app := app.New(t, app.WithRegister(fn), app.WithOnInvokeFn(func(ctx context.Context, _ *commonv1.InvokeRequest) (*commonv1.InvokeResponse, error) { md, ok := metadata.FromIncomingContext(ctx) require.True(t, ok) b.ch <- md return new(commonv1.InvokeResponse), nil }), ) b.daprd1 = daprd.New(t, daprd.WithAppID("app1"), daprd.WithAppProtocol("grpc"), daprd.WithAppAPIToken(t, "abc"), ) b.daprd2 = daprd.New(t, daprd.WithAppProtocol("grpc"), daprd.WithAppAPIToken(t, "def"), daprd.WithAppPort(app.Port(t)), ) return []framework.Option{ framework.WithProcesses(app, b.daprd1, b.daprd2), } } func (b *remotebothtokens) Run(t *testing.T, ctx context.Context) { b.daprd1.WaitUntilRunning(t, ctx) b.daprd2.WaitUntilRunning(t, ctx) client := testpb.NewTestServiceClient(b.daprd1.GRPCConn(t, ctx)) ctx = metadata.AppendToOutgoingContext(ctx, "dapr-app-id", b.daprd2.AppID()) _, err := client.Ping(ctx, new(testpb.PingRequest)) require.NoError(t, err) select { case md := <-b.ch: require.Equal(t, []string{"def"}, md.Get("dapr-api-token")) case <-time.After(10 * time.Second): assert.Fail(t, "timed out waiting for metadata") } dclient := b.daprd1.GRPCClient(t, ctx) _, err = dclient.InvokeService(ctx, &runtimev1.InvokeServiceRequest{ Id: b.daprd2.AppID(), Message: &commonv1.InvokeRequest{ Method: "helloworld", Data: new(anypb.Any), HttpExtension: &commonv1.HTTPExtension{Verb: commonv1.HTTPExtension_GET}, }, }) require.NoError(t, err) select { case md := <-b.ch: require.Equal(t, []string{"def"}, md.Get("dapr-api-token")) case <-time.After(5 * time.Second): assert.Fail(t, "timed out waiting for metadata") } }
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/grpc/appapitoken/remotebothtokens.go
GO
mit
3,190
/* 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 appapitoken import ( "context" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc/metadata" "google.golang.org/protobuf/types/known/anypb" commonv1 "github.com/dapr/dapr/pkg/proto/common/v1" runtimev1 "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" testpb "github.com/dapr/dapr/tests/integration/suite/daprd/serviceinvocation/grpc/proto" ) func init() { suite.Register(new(remotereceiverhastoken)) } type remotereceiverhastoken struct { daprd1 *daprd.Daprd daprd2 *daprd.Daprd ch chan metadata.MD } func (r *remotereceiverhastoken) Setup(t *testing.T) []framework.Option { fn, ch := newServer() r.ch = ch app := app.New(t, app.WithRegister(fn), app.WithOnInvokeFn(func(ctx context.Context, _ *commonv1.InvokeRequest) (*commonv1.InvokeResponse, error) { md, ok := metadata.FromIncomingContext(ctx) require.True(t, ok) r.ch <- md return new(commonv1.InvokeResponse), nil }), ) r.daprd1 = daprd.New(t) r.daprd2 = daprd.New(t, daprd.WithAppProtocol("grpc"), daprd.WithAppAPIToken(t, "abc"), daprd.WithAppPort(app.Port(t)), ) return []framework.Option{ framework.WithProcesses(app, r.daprd1, r.daprd2), } } func (r *remotereceiverhastoken) Run(t *testing.T, ctx context.Context) { r.daprd1.WaitUntilRunning(t, ctx) r.daprd2.WaitUntilRunning(t, ctx) client := testpb.NewTestServiceClient(r.daprd1.GRPCConn(t, ctx)) ctx = metadata.AppendToOutgoingContext(ctx, "dapr-app-id", r.daprd2.AppID()) _, err := client.Ping(ctx, new(testpb.PingRequest)) require.NoError(t, err) select { case md := <-r.ch: require.Equal(t, []string{"abc"}, md.Get("dapr-api-token")) case <-time.After(5 * time.Second): assert.Fail(t, "timed out waiting for metadata") } dclient := r.daprd1.GRPCClient(t, ctx) _, err = dclient.InvokeService(ctx, &runtimev1.InvokeServiceRequest{ Id: r.daprd2.AppID(), Message: &commonv1.InvokeRequest{ Method: "helloworld", Data: new(anypb.Any), HttpExtension: &commonv1.HTTPExtension{Verb: commonv1.HTTPExtension_GET}, }, }) require.NoError(t, err) select { case md := <-r.ch: require.Equal(t, []string{"abc"}, md.Get("dapr-api-token")) case <-time.After(5 * time.Second): assert.Fail(t, "timed out waiting for metadata") } }
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/grpc/appapitoken/remotereceiverhastoken.go
GO
mit
3,114
/* 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 appapitoken import ( "context" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc/metadata" "google.golang.org/protobuf/types/known/anypb" commonv1 "github.com/dapr/dapr/pkg/proto/common/v1" runtimev1 "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" testpb "github.com/dapr/dapr/tests/integration/suite/daprd/serviceinvocation/grpc/proto" ) func init() { suite.Register(new(remotereceivernotoken)) } type remotereceivernotoken struct { daprd1 *daprd.Daprd daprd2 *daprd.Daprd ch chan metadata.MD } func (n *remotereceivernotoken) Setup(t *testing.T) []framework.Option { fn, ch := newServer() n.ch = ch app := app.New(t, app.WithRegister(fn), app.WithOnInvokeFn(func(ctx context.Context, _ *commonv1.InvokeRequest) (*commonv1.InvokeResponse, error) { md, ok := metadata.FromIncomingContext(ctx) require.True(t, ok) n.ch <- md return new(commonv1.InvokeResponse), nil }), ) n.daprd1 = daprd.New(t, daprd.WithAppProtocol("grpc"), daprd.WithAppAPIToken(t, "abc"), ) n.daprd2 = daprd.New(t, daprd.WithAppProtocol("grpc"), daprd.WithAppPort(app.Port(t)), ) return []framework.Option{ framework.WithProcesses(app, n.daprd1, n.daprd2), } } func (n *remotereceivernotoken) Run(t *testing.T, ctx context.Context) { n.daprd1.WaitUntilRunning(t, ctx) n.daprd2.WaitUntilRunning(t, ctx) client := testpb.NewTestServiceClient(n.daprd1.GRPCConn(t, ctx)) ctx = metadata.AppendToOutgoingContext(ctx, "dapr-app-id", n.daprd2.AppID()) _, err := client.Ping(ctx, new(testpb.PingRequest)) require.NoError(t, err) select { case md := <-n.ch: require.Empty(t, md.Get("dapr-api-token")) case <-time.After(5 * time.Second): assert.Fail(t, "timed out waiting for metadata") } dclient := n.daprd1.GRPCClient(t, ctx) _, err = dclient.InvokeService(ctx, &runtimev1.InvokeServiceRequest{ Id: n.daprd2.AppID(), Message: &commonv1.InvokeRequest{ Method: "helloworld", Data: new(anypb.Any), HttpExtension: &commonv1.HTTPExtension{Verb: commonv1.HTTPExtension_GET}, }, }) require.NoError(t, err) select { case md := <-n.ch: require.Empty(t, md.Get("dapr-api-token")) case <-time.After(5 * time.Second): assert.Fail(t, "timed out waiting for metadata") } }
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/grpc/appapitoken/remotereceivernotoken.go
GO
mit
3,113
/* 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 appapitoken import ( "context" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc/metadata" "google.golang.org/protobuf/types/known/anypb" commonv1 "github.com/dapr/dapr/pkg/proto/common/v1" runtimev1 "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" testpb "github.com/dapr/dapr/tests/integration/suite/daprd/serviceinvocation/grpc/proto" ) func init() { suite.Register(new(selfnotoken)) } type selfnotoken struct { daprd *daprd.Daprd ch chan metadata.MD } func (n *selfnotoken) Setup(t *testing.T) []framework.Option { fn, ch := newServer() n.ch = ch app := app.New(t, app.WithRegister(fn), app.WithOnInvokeFn(func(ctx context.Context, _ *commonv1.InvokeRequest) (*commonv1.InvokeResponse, error) { md, ok := metadata.FromIncomingContext(ctx) require.True(t, ok) n.ch <- md return new(commonv1.InvokeResponse), nil }), ) n.daprd = daprd.New(t, daprd.WithAppProtocol("grpc"), daprd.WithAppPort(app.Port(t)), ) return []framework.Option{ framework.WithProcesses(app, n.daprd), } } func (n *selfnotoken) Run(t *testing.T, ctx context.Context) { n.daprd.WaitUntilRunning(t, ctx) client := testpb.NewTestServiceClient(n.daprd.GRPCConn(t, ctx)) ctx = metadata.AppendToOutgoingContext(ctx, "dapr-app-id", n.daprd.AppID()) _, err := client.Ping(ctx, new(testpb.PingRequest)) require.NoError(t, err) select { case md := <-n.ch: require.Empty(t, md.Get("dapr-api-token")) case <-time.After(5 * time.Second): assert.Fail(t, "timed out waiting for metadata") } dclient := n.daprd.GRPCClient(t, ctx) _, err = dclient.InvokeService(ctx, &runtimev1.InvokeServiceRequest{ Id: n.daprd.AppID(), Message: &commonv1.InvokeRequest{ Method: "helloworld", Data: new(anypb.Any), HttpExtension: &commonv1.HTTPExtension{Verb: commonv1.HTTPExtension_GET}, }, }) require.NoError(t, err) select { case md := <-n.ch: require.Empty(t, md.Get("dapr-api-token")) case <-time.After(5 * time.Second): assert.Fail(t, "timed out waiting for metadata") } }
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/grpc/appapitoken/selfnotoken.go
GO
mit
2,901
/* 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 appapitoken import ( "context" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc/metadata" "google.golang.org/protobuf/types/known/anypb" commonv1 "github.com/dapr/dapr/pkg/proto/common/v1" runtimev1 "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" testpb "github.com/dapr/dapr/tests/integration/suite/daprd/serviceinvocation/grpc/proto" ) func init() { suite.Register(new(selfwithtoken)) } type selfwithtoken struct { daprd *daprd.Daprd ch chan metadata.MD } func (s *selfwithtoken) Setup(t *testing.T) []framework.Option { fn, ch := newServer() s.ch = ch app := app.New(t, app.WithRegister(fn), app.WithOnInvokeFn(func(ctx context.Context, _ *commonv1.InvokeRequest) (*commonv1.InvokeResponse, error) { md, ok := metadata.FromIncomingContext(ctx) require.True(t, ok) s.ch <- md return new(commonv1.InvokeResponse), nil }), ) s.daprd = daprd.New(t, daprd.WithAppProtocol("grpc"), daprd.WithAppAPIToken(t, "abc"), daprd.WithAppPort(app.Port(t)), ) return []framework.Option{ framework.WithProcesses(app, s.daprd), } } func (s *selfwithtoken) Run(t *testing.T, ctx context.Context) { s.daprd.WaitUntilRunning(t, ctx) client := testpb.NewTestServiceClient(s.daprd.GRPCConn(t, ctx)) ctx = metadata.AppendToOutgoingContext(ctx, "dapr-app-id", s.daprd.AppID()) _, err := client.Ping(ctx, new(testpb.PingRequest)) require.NoError(t, err) select { case md := <-s.ch: require.Equal(t, []string{"abc"}, md.Get("dapr-api-token")) case <-time.After(5 * time.Second): assert.Fail(t, "timed out waiting for metadata") } dclient := s.daprd.GRPCClient(t, ctx) _, err = dclient.InvokeService(ctx, &runtimev1.InvokeServiceRequest{ Id: s.daprd.AppID(), Message: &commonv1.InvokeRequest{ Method: "helloworld", Data: new(anypb.Any), HttpExtension: &commonv1.HTTPExtension{Verb: commonv1.HTTPExtension_GET}, }, }) require.NoError(t, err) select { case md := <-s.ch: require.Equal(t, []string{"abc"}, md.Get("dapr-api-token")) case <-time.After(5 * time.Second): assert.Fail(t, "timed out waiting for metadata") } }
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/grpc/appapitoken/selfwithtoken.go
GO
mit
2,978
/* 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 appapitoken import ( "context" "google.golang.org/grpc" "google.golang.org/grpc/metadata" testpb "github.com/dapr/dapr/tests/integration/suite/daprd/serviceinvocation/grpc/proto" ) type pingServer struct { testpb.UnsafeTestServiceServer ch chan metadata.MD } func newServer() (func(*grpc.Server), chan metadata.MD) { ch := make(chan metadata.MD, 1) return func(s *grpc.Server) { testpb.RegisterTestServiceServer(s, &pingServer{ ch: ch, }) }, ch } func (p *pingServer) Ping(ctx context.Context, _ *testpb.PingRequest) (*testpb.PingResponse, error) { md, _ := metadata.FromIncomingContext(ctx) p.ch <- md return new(testpb.PingResponse), nil }
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/grpc/appapitoken/server.go
GO
mit
1,236
/* 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 grpc import ( "context" "errors" "fmt" "net/http" "strconv" "testing" "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/anypb" commonv1 "github.com/dapr/dapr/pkg/proto/common/v1" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "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(basic)) } type basic struct { daprd1 *procdaprd.Daprd daprd2 *procdaprd.Daprd } func (b *basic) Setup(t *testing.T) []framework.Option { onInvoke := func(ctx context.Context, in *commonv1.InvokeRequest) (*commonv1.InvokeResponse, error) { switch in.GetMethod() { case "foo": var verb int var data []byte switch in.GetHttpExtension().GetVerb() { case commonv1.HTTPExtension_PATCH: data = []byte("PATCH") verb = http.StatusNoContent case commonv1.HTTPExtension_POST: data = []byte("POST") verb = http.StatusCreated case commonv1.HTTPExtension_GET: data = []byte("GET") verb = http.StatusOK case commonv1.HTTPExtension_PUT: data = []byte("PUT") verb = http.StatusAccepted case commonv1.HTTPExtension_DELETE: data = []byte("DELETE") verb = http.StatusConflict } return &commonv1.InvokeResponse{ Data: &anypb.Any{Value: data}, ContentType: strconv.Itoa(verb), }, nil case "typed": return &commonv1.InvokeResponse{ Data: &anypb.Any{ Value: []byte(fmt.Sprintf("%s/%s", string(in.GetData().GetValue()), in.GetData().GetTypeUrl())), TypeUrl: "mytype", }, ContentType: "application/json", }, nil case "multiple/segments": return &commonv1.InvokeResponse{ Data: &anypb.Any{Value: []byte("multiple/segments")}, ContentType: "application/json", }, nil default: return nil, errors.New("invalid method") } } srv1 := newGRPCServer(t, onInvoke) srv2 := newGRPCServer(t, onInvoke) b.daprd1 = procdaprd.New(t, procdaprd.WithAppProtocol("grpc"), procdaprd.WithAppPort(srv1.Port(t)), ) b.daprd2 = procdaprd.New(t, procdaprd.WithAppProtocol("grpc"), procdaprd.WithAppPort(srv2.Port(t)), ) return []framework.Option{ framework.WithProcesses(srv1, srv2, b.daprd1, b.daprd2), } } func (b *basic) Run(t *testing.T, ctx context.Context) { b.daprd1.WaitUntilRunning(t, ctx) b.daprd2.WaitUntilRunning(t, ctx) t.Run("invoke host", func(t *testing.T) { doReq := func(host, hostID string, verb commonv1.HTTPExtension_Verb) ([]byte, string) { conn, err := grpc.DialContext(ctx, host, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock(), ) require.NoError(t, err) t.Cleanup(func() { require.NoError(t, conn.Close()) }) resp, err := rtv1.NewDaprClient(conn).InvokeService(ctx, &rtv1.InvokeServiceRequest{ Id: hostID, Message: &commonv1.InvokeRequest{ Method: "foo", HttpExtension: &commonv1.HTTPExtension{Verb: verb}, }, }) require.NoError(t, err) return resp.GetData().GetValue(), resp.GetContentType() } for _, ts := range []struct { host string hostID string }{ {host: b.daprd1.GRPCAddress(), hostID: b.daprd2.AppID()}, {host: b.daprd2.GRPCAddress(), hostID: b.daprd1.AppID()}, } { t.Run(ts.host, func(t *testing.T) { body, contentType := doReq(ts.host, ts.hostID, commonv1.HTTPExtension_GET) assert.Equal(t, "GET", string(body)) assert.Equal(t, "200", contentType) body, contentType = doReq(ts.host, ts.hostID, commonv1.HTTPExtension_POST) assert.Equal(t, "POST", string(body)) assert.Equal(t, "201", contentType) body, contentType = doReq(ts.host, ts.hostID, commonv1.HTTPExtension_PUT) assert.Equal(t, "PUT", string(body)) assert.Equal(t, "202", contentType) body, contentType = doReq(ts.host, ts.hostID, commonv1.HTTPExtension_DELETE) assert.Equal(t, "DELETE", string(body)) assert.Equal(t, "409", contentType) body, contentType = doReq(ts.host, ts.hostID, commonv1.HTTPExtension_PATCH) assert.Equal(t, "PATCH", string(body)) assert.Equal(t, "204", contentType) }) } }) t.Run("method doesn't exist", func(t *testing.T) { host := b.daprd1.GRPCAddress() conn, err := grpc.DialContext(ctx, host, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock(), ) require.NoError(t, err) t.Cleanup(func() { require.NoError(t, conn.Close()) }) resp, err := rtv1.NewDaprClient(conn).InvokeService(ctx, &rtv1.InvokeServiceRequest{ Id: b.daprd2.AppID(), Message: &commonv1.InvokeRequest{ Method: "doesnotexist", HttpExtension: &commonv1.HTTPExtension{Verb: commonv1.HTTPExtension_GET}, }, }) require.Error(t, err) // TODO: this should be codes.NotFound. assert.Equal(t, codes.Unknown, status.Convert(err).Code()) assert.Equal(t, "invalid method", status.Convert(err).Message()) assert.Nil(t, resp) }) t.Run("no method", func(t *testing.T) { host := b.daprd1.GRPCAddress() conn, err := grpc.DialContext(ctx, host, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock(), ) require.NoError(t, err) t.Cleanup(func() { require.NoError(t, conn.Close()) }) resp, err := rtv1.NewDaprClient(conn).InvokeService(ctx, &rtv1.InvokeServiceRequest{ Id: b.daprd2.AppID(), Message: &commonv1.InvokeRequest{ Method: "", HttpExtension: &commonv1.HTTPExtension{Verb: commonv1.HTTPExtension_GET}, }, }) require.Error(t, err) // TODO: this should be codes.InvalidArgument. assert.Equal(t, codes.Unknown, status.Convert(err).Code()) assert.Equal(t, "invalid method", status.Convert(err).Message()) assert.Nil(t, resp) }) t.Run("multiple segments", func(t *testing.T) { host := b.daprd1.GRPCAddress() conn, err := grpc.DialContext(ctx, host, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock(), ) require.NoError(t, err) t.Cleanup(func() { require.NoError(t, conn.Close()) }) resp, err := rtv1.NewDaprClient(conn).InvokeService(ctx, &rtv1.InvokeServiceRequest{ Id: b.daprd2.AppID(), Message: &commonv1.InvokeRequest{ Method: "multiple/segments", HttpExtension: &commonv1.HTTPExtension{Verb: commonv1.HTTPExtension_GET}, }, }) require.NoError(t, err) assert.Equal(t, "multiple/segments", string(resp.GetData().GetValue())) assert.Equal(t, "application/json", resp.GetContentType()) }) pt := util.NewParallel(t) for i := 0; i < 100; i++ { pt.Add(func(c *assert.CollectT) { host := b.daprd1.GRPCAddress() conn, err := grpc.DialContext(ctx, host, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock()) require.NoError(c, err) t.Cleanup(func() { require.NoError(c, conn.Close()) }) resp, err := rtv1.NewDaprClient(conn).InvokeService(ctx, &rtv1.InvokeServiceRequest{ Id: b.daprd2.AppID(), Message: &commonv1.InvokeRequest{ Method: "foo", HttpExtension: &commonv1.HTTPExtension{Verb: commonv1.HTTPExtension_POST}, }, }) require.NoError(c, err) assert.Equal(c, "POST", string(resp.GetData().GetValue())) assert.Equal(c, "201", resp.GetContentType()) }) } t.Run("type URL", func(t *testing.T) { host := b.daprd1.GRPCAddress() conn, err := grpc.DialContext(ctx, host, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock(), ) require.NoError(t, err) t.Cleanup(func() { require.NoError(t, conn.Close()) }) resp, err := rtv1.NewDaprClient(conn).InvokeService(ctx, &rtv1.InvokeServiceRequest{ Id: b.daprd2.AppID(), Message: &commonv1.InvokeRequest{ Method: "typed", Data: &anypb.Any{ Value: []byte("emozioni di settembre"), TypeUrl: "pfm", }, }, }) require.NoError(t, err) require.NotNil(t, resp.GetData()) assert.Equal(t, "emozioni di settembre/pfm", string(resp.GetData().GetValue())) assert.Equal(t, "mytype", resp.GetData().GetTypeUrl()) }) }
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/grpc/basic.go
GO
mit
8,828
/* 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 grpc import ( "context" "fmt" "net/http" "strings" "testing" "github.com/stretchr/testify/require" commonv1 "github.com/dapr/dapr/pkg/proto/common/v1" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" procdaprd "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/framework/util" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(contentlength)) } type contentlength struct { daprd1 *procdaprd.Daprd daprd2 *procdaprd.Daprd } func (c *contentlength) Setup(t *testing.T) []framework.Option { app := app.New(t, app.WithHandlerFunc("/hi", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "OK") }), ) c.daprd1 = procdaprd.New(t, procdaprd.WithAppPort(app.Port())) c.daprd2 = procdaprd.New(t, procdaprd.WithAppPort(app.Port())) return []framework.Option{ framework.WithProcesses(app, c.daprd1, c.daprd2), } } func (c *contentlength) Run(t *testing.T, ctx context.Context) { c.daprd1.WaitUntilRunning(t, ctx) c.daprd2.WaitUntilRunning(t, ctx) client := util.HTTPClient(t) url := fmt.Sprintf("http://%s/v1.0/invoke/%s/method/hi", c.daprd1.HTTPAddress(), c.daprd2.AppID()) req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader("helloworld")) require.NoError(t, err) req.Header.Set("content-length", "1024") resp, err := client.Do(req) require.NoError(t, err) require.Equal(t, http.StatusOK, resp.StatusCode) require.NoError(t, resp.Body.Close()) gclient := c.daprd1.GRPCClient(t, ctx) _, err = gclient.InvokeService(ctx, &rtv1.InvokeServiceRequest{ Id: c.daprd2.AppID(), Message: &commonv1.InvokeRequest{ Method: "hi", HttpExtension: &commonv1.HTTPExtension{Verb: commonv1.HTTPExtension_GET}, }, }) require.NoError(t, err) }
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/grpc/contentlength.go
GO
mit
2,508
/* 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 grpc import ( "context" "fmt" "net/url" "strings" "testing" fuzz "github.com/google/gofuzz" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "google.golang.org/protobuf/types/known/anypb" commonv1 "github.com/dapr/dapr/pkg/proto/common/v1" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "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(fuzzgrpc)) } type fuzzgrpc struct { daprd1 *procdaprd.Daprd daprd2 *procdaprd.Daprd methods []string bodies [][]byte queries []map[string]string } func (f *fuzzgrpc) Setup(t *testing.T) []framework.Option { const numTests = 1000 onInvoke := func(ctx context.Context, in *commonv1.InvokeRequest) (*commonv1.InvokeResponse, error) { return &commonv1.InvokeResponse{ Data: &anypb.Any{Value: in.GetData().GetValue()}, }, nil } srv := newGRPCServer(t, onInvoke) f.daprd1 = procdaprd.New(t, procdaprd.WithAppProtocol("grpc"), procdaprd.WithAppPort(srv.Port(t))) f.daprd2 = procdaprd.New(t) f.methods = make([]string, numTests) f.bodies = make([][]byte, numTests) f.queries = make([]map[string]string, numTests) for i := 0; i < numTests; i++ { fz := fuzz.New() fz.NumElements(0, 100).Fuzz(&f.methods[i]) fz.NumElements(0, 100).Fuzz(&f.bodies[i]) fz.NumElements(0, 100).Fuzz(&f.queries[i]) } return []framework.Option{ framework.WithProcesses(f.daprd1, f.daprd2, srv), } } func (f *fuzzgrpc) Run(t *testing.T, ctx context.Context) { f.daprd1.WaitUntilRunning(t, ctx) f.daprd2.WaitUntilRunning(t, ctx) pt := util.NewParallel(t) for i := 0; i < len(f.methods); i++ { method := f.methods[i] body := f.bodies[i] query := f.queries[i] var queryString []string for k, v := range query { queryString = append(queryString, fmt.Sprintf("%s=%s", k, v)) } pt.Add(func(c *assert.CollectT) { conn, err := grpc.DialContext(ctx, fmt.Sprintf("127.0.0.1:%d", f.daprd2.GRPCPort()), grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock()) require.NoError(c, err) t.Cleanup(func() { require.NoError(t, conn.Close()) }) resp, err := rtv1.NewDaprClient(conn).InvokeService(ctx, &rtv1.InvokeServiceRequest{ Id: f.daprd1.AppID(), Message: &commonv1.InvokeRequest{ Method: url.QueryEscape(method), Data: &anypb.Any{Value: body}, HttpExtension: &commonv1.HTTPExtension{ Verb: commonv1.HTTPExtension_POST, Querystring: strings.Join(queryString, "&"), }, }, }) require.NoError(c, err) if len(body) == 0 { body = nil } assert.Equal(c, body, resp.GetData().GetValue()) }) } }
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/grpc/fuzz.go
GO
mit
3,454
/* 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 grpc import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/serviceinvocation/grpc/appapitoken" )
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/grpc/grpc.go
GO
mit
677
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.32.0 // protoc v4.24.4 // source: test.v1.proto package __ import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type PingRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` } func (x *PingRequest) Reset() { *x = PingRequest{} if protoimpl.UnsafeEnabled { mi := &file_test_v1_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *PingRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*PingRequest) ProtoMessage() {} func (x *PingRequest) ProtoReflect() protoreflect.Message { mi := &file_test_v1_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PingRequest.ProtoReflect.Descriptor instead. func (*PingRequest) Descriptor() ([]byte, []int) { return file_test_v1_proto_rawDescGZIP(), []int{0} } func (x *PingRequest) GetValue() string { if x != nil { return x.Value } return "" } type PingResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Value string `protobuf:"bytes,1,opt,name=Value,proto3" json:"Value,omitempty"` Counter int32 `protobuf:"varint,2,opt,name=counter,proto3" json:"counter,omitempty"` } func (x *PingResponse) Reset() { *x = PingResponse{} if protoimpl.UnsafeEnabled { mi := &file_test_v1_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *PingResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*PingResponse) ProtoMessage() {} func (x *PingResponse) ProtoReflect() protoreflect.Message { mi := &file_test_v1_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PingResponse.ProtoReflect.Descriptor instead. func (*PingResponse) Descriptor() ([]byte, []int) { return file_test_v1_proto_rawDescGZIP(), []int{1} } func (x *PingResponse) GetValue() string { if x != nil { return x.Value } return "" } func (x *PingResponse) GetCounter() int32 { if x != nil { return x.Counter } return 0 } var File_test_v1_proto protoreflect.FileDescriptor var file_test_v1_proto_rawDesc = []byte{ 0x0a, 0x0d, 0x74, 0x65, 0x73, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x11, 0x64, 0x61, 0x70, 0x72, 0x2e, 0x69, 0x6f, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x23, 0x0a, 0x0b, 0x50, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x3e, 0x0a, 0x0c, 0x50, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x07, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x65, 0x72, 0x32, 0x58, 0x0a, 0x0b, 0x54, 0x65, 0x73, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x49, 0x0a, 0x04, 0x50, 0x69, 0x6e, 0x67, 0x12, 0x1e, 0x2e, 0x64, 0x61, 0x70, 0x72, 0x2e, 0x69, 0x6f, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x50, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1f, 0x2e, 0x64, 0x61, 0x70, 0x72, 0x2e, 0x69, 0x6f, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x50, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x42, 0x03, 0x5a, 0x01, 0x2e, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_test_v1_proto_rawDescOnce sync.Once file_test_v1_proto_rawDescData = file_test_v1_proto_rawDesc ) func file_test_v1_proto_rawDescGZIP() []byte { file_test_v1_proto_rawDescOnce.Do(func() { file_test_v1_proto_rawDescData = protoimpl.X.CompressGZIP(file_test_v1_proto_rawDescData) }) return file_test_v1_proto_rawDescData } var file_test_v1_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_test_v1_proto_goTypes = []interface{}{ (*PingRequest)(nil), // 0: dapr.io.testproto.PingRequest (*PingResponse)(nil), // 1: dapr.io.testproto.PingResponse } var file_test_v1_proto_depIdxs = []int32{ 0, // 0: dapr.io.testproto.TestService.Ping:input_type -> dapr.io.testproto.PingRequest 1, // 1: dapr.io.testproto.TestService.Ping:output_type -> dapr.io.testproto.PingResponse 1, // [1:2] is the sub-list for method output_type 0, // [0:1] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } func init() { file_test_v1_proto_init() } func file_test_v1_proto_init() { if File_test_v1_proto != nil { return } if !protoimpl.UnsafeEnabled { file_test_v1_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*PingRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_test_v1_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*PingResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_test_v1_proto_rawDesc, NumEnums: 0, NumMessages: 2, NumExtensions: 0, NumServices: 1, }, GoTypes: file_test_v1_proto_goTypes, DependencyIndexes: file_test_v1_proto_depIdxs, MessageInfos: file_test_v1_proto_msgTypes, }.Build() File_test_v1_proto = out.File file_test_v1_proto_rawDesc = nil file_test_v1_proto_goTypes = nil file_test_v1_proto_depIdxs = nil }
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/grpc/proto/test.v1.pb.go
GO
mit
6,836
syntax = "proto3"; package dapr.io.testproto; option go_package = "."; message PingRequest { string value = 1; } message PingResponse { string Value = 1; int32 counter = 2; } service TestService { rpc Ping(PingRequest) returns (PingResponse) {} }
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/grpc/proto/test.v1.proto
proto
mit
260
// Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: // - protoc-gen-go-grpc v1.3.0 // - protoc v4.24.4 // source: test.v1.proto package __ import ( context "context" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" ) // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. // Requires gRPC-Go v1.32.0 or later. const _ = grpc.SupportPackageIsVersion7 const ( TestService_Ping_FullMethodName = "/dapr.io.testproto.TestService/Ping" ) // TestServiceClient is the client API for TestService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. type TestServiceClient interface { Ping(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (*PingResponse, error) } type testServiceClient struct { cc grpc.ClientConnInterface } func NewTestServiceClient(cc grpc.ClientConnInterface) TestServiceClient { return &testServiceClient{cc} } func (c *testServiceClient) Ping(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (*PingResponse, error) { out := new(PingResponse) err := c.cc.Invoke(ctx, TestService_Ping_FullMethodName, in, out, opts...) if err != nil { return nil, err } return out, nil } // TestServiceServer is the server API for TestService service. // All implementations must embed UnimplementedTestServiceServer // for forward compatibility type TestServiceServer interface { Ping(context.Context, *PingRequest) (*PingResponse, error) mustEmbedUnimplementedTestServiceServer() } // UnimplementedTestServiceServer must be embedded to have forward compatible implementations. type UnimplementedTestServiceServer struct { } func (UnimplementedTestServiceServer) Ping(context.Context, *PingRequest) (*PingResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Ping not implemented") } func (UnimplementedTestServiceServer) mustEmbedUnimplementedTestServiceServer() {} // UnsafeTestServiceServer may be embedded to opt out of forward compatibility for this service. // Use of this interface is not recommended, as added methods to TestServiceServer will // result in compilation errors. type UnsafeTestServiceServer interface { mustEmbedUnimplementedTestServiceServer() } func RegisterTestServiceServer(s grpc.ServiceRegistrar, srv TestServiceServer) { s.RegisterService(&TestService_ServiceDesc, srv) } func _TestService_Ping_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(PingRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(TestServiceServer).Ping(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: TestService_Ping_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TestServiceServer).Ping(ctx, req.(*PingRequest)) } return interceptor(ctx, in, info, handler) } // TestService_ServiceDesc is the grpc.ServiceDesc for TestService service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) var TestService_ServiceDesc = grpc.ServiceDesc{ ServiceName: "dapr.io.testproto.TestService", HandlerType: (*TestServiceServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "Ping", Handler: _TestService_Ping_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "test.v1.proto", }
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/grpc/proto/test.v1_grpc.pb.go
GO
mit
3,674
/* 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 grpc import ( "context" "testing" "google.golang.org/grpc" commonv1 "github.com/dapr/dapr/pkg/proto/common/v1" procgrpc "github.com/dapr/dapr/tests/integration/framework/process/grpc" "github.com/dapr/dapr/tests/integration/framework/process/grpc/app" testpb "github.com/dapr/dapr/tests/integration/suite/daprd/serviceinvocation/grpc/proto" ) type ( invokeFn func(ctx context.Context, in *commonv1.InvokeRequest) (*commonv1.InvokeResponse, error) ) type pingserver struct { testpb.UnsafeTestServiceServer } func newGRPCServer(t *testing.T, onInvoke invokeFn, opts ...procgrpc.Option) *app.App { return app.New(t, app.WithGRPCOptions(opts...), app.WithOnInvokeFn(onInvoke), app.WithRegister(func(s *grpc.Server) { testpb.RegisterTestServiceServer(s, new(pingserver)) }), ) } func (p *pingserver) Ping(context.Context, *testpb.PingRequest) (*testpb.PingResponse, error) { return new(testpb.PingResponse), nil }
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/grpc/server.go
GO
mit
1,508
/* 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 grpc import ( "context" "net" "strconv" "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/protobuf/types/known/anypb" commonv1 "github.com/dapr/dapr/pkg/proto/common/v1" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/integration/framework" procdaprd "github.com/dapr/dapr/tests/integration/framework/process/daprd" procgrpc "github.com/dapr/dapr/tests/integration/framework/process/grpc" "github.com/dapr/dapr/tests/integration/framework/process/grpc/app" "github.com/dapr/dapr/tests/integration/framework/process/ports" "github.com/dapr/dapr/tests/integration/suite" testpb "github.com/dapr/dapr/tests/integration/suite/daprd/serviceinvocation/grpc/proto" ) func init() { suite.Register(new(slowappstartup)) } // slowappstartup is a test to ensure that service invocation does not error if // the app is slow to startup. type slowappstartup struct { daprd *procdaprd.Daprd app *app.App } func (s *slowappstartup) Setup(t *testing.T) []framework.Option { onInvoke := func(ctx context.Context, in *commonv1.InvokeRequest) (*commonv1.InvokeResponse, error) { assert.Equal(t, "Ping", in.GetMethod()) resp, err := anypb.New(new(testpb.PingResponse)) if err != nil { return nil, err } return &commonv1.InvokeResponse{ Data: resp, ContentType: "application/grpc", }, nil } fp := ports.Reserve(t, 1) port := fp.Port(t) s.app = newGRPCServer(t, onInvoke, procgrpc.WithListener(func() (net.Listener, error) { // Simulate a slow startup by not opening the listener until 2 seconds after // the process starts. This sleep value must be more than the health probe // interval. time.Sleep(time.Second * 2) return net.Listen("tcp", "localhost:"+strconv.Itoa(port)) })) s.daprd = procdaprd.New(t, procdaprd.WithAppProtocol("grpc"), procdaprd.WithAppPort(port), procdaprd.WithAppHealthCheck(true), procdaprd.WithAppHealthProbeInterval(1), procdaprd.WithAppHealthProbeThreshold(1), ) return []framework.Option{ framework.WithProcesses(fp, s.app, s.daprd), } } func (s *slowappstartup) Run(t *testing.T, ctx context.Context) { s.daprd.WaitUntilRunning(t, ctx) s.daprd.WaitUntilAppHealth(t, ctx) conn, err := grpc.DialContext(ctx, s.daprd.GRPCAddress(), grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock(), ) require.NoError(t, err) client := rtv1.NewDaprClient(conn) req, err := anypb.New(new(testpb.PingRequest)) require.NoError(t, err) var pingResp testpb.PingResponse var resp *commonv1.InvokeResponse require.EventuallyWithT(t, func(c *assert.CollectT) { resp, err = client.InvokeService(ctx, &rtv1.InvokeServiceRequest{ Id: s.daprd.AppID(), Message: &commonv1.InvokeRequest{ Method: "Ping", Data: req, }, }) // This function must only return that the app is not in a healthy state // until the app is in a healthy state. //nolint:testifylint if !assert.NoError(c, err) { require.ErrorContains(c, err, "app is not in a healthy state") } }, time.Second*3, time.Millisecond*10) require.NoError(t, resp.GetData().UnmarshalTo(&pingResp)) }
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/grpc/slowappstartup.go
GO
mit
3,827
/* 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 appapitoken import ( "context" "net/http" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/types/known/anypb" commonv1 "github.com/dapr/dapr/pkg/proto/common/v1" runtimev1 "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(remotebothtokens)) } type remotebothtokens struct { daprd1 *daprd.Daprd daprd2 *daprd.Daprd ch chan http.Header } func (b *remotebothtokens) Setup(t *testing.T) []framework.Option { b.ch = make(chan http.Header, 1) app := app.New(t, app.WithHandlerFunc("/helloworld", func(w http.ResponseWriter, r *http.Request) { b.ch <- r.Header }), ) b.daprd1 = daprd.New(t, daprd.WithAppID("app1"), daprd.WithAppAPIToken(t, "abc"), ) b.daprd2 = daprd.New(t, daprd.WithAppAPIToken(t, "def"), daprd.WithAppPort(app.Port()), ) return []framework.Option{ framework.WithProcesses(app, b.daprd1, b.daprd2), } } func (b *remotebothtokens) Run(t *testing.T, ctx context.Context) { b.daprd1.WaitUntilRunning(t, ctx) b.daprd2.WaitUntilRunning(t, ctx) b.daprd2.WaitUntilAppHealth(t, ctx) dclient := b.daprd1.GRPCClient(t, ctx) _, err := dclient.InvokeService(ctx, &runtimev1.InvokeServiceRequest{ Id: b.daprd2.AppID(), Message: &commonv1.InvokeRequest{ Method: "helloworld", Data: new(anypb.Any), HttpExtension: &commonv1.HTTPExtension{Verb: commonv1.HTTPExtension_GET}, }, }) require.NoError(t, err) select { case header := <-b.ch: require.Equal(t, "def", header.Get("dapr-api-token")) case <-time.After(5 * time.Second): assert.Fail(t, "timed out waiting for metadata") } }
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/http/appapitoken/remotebothtokens.go
GO
mit
2,480
/* 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 appapitoken import ( "context" "net/http" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/types/known/anypb" commonv1 "github.com/dapr/dapr/pkg/proto/common/v1" runtimev1 "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(remotereceiverhastoken)) } type remotereceiverhastoken struct { daprd1 *daprd.Daprd daprd2 *daprd.Daprd ch chan http.Header } func (r *remotereceiverhastoken) Setup(t *testing.T) []framework.Option { r.ch = make(chan http.Header, 1) app := app.New(t, app.WithHandlerFunc("/helloworld", func(w http.ResponseWriter, req *http.Request) { r.ch <- req.Header }), ) r.daprd1 = daprd.New(t) r.daprd2 = daprd.New(t, daprd.WithAppAPIToken(t, "abc"), daprd.WithAppPort(app.Port()), ) return []framework.Option{ framework.WithProcesses(app, r.daprd1, r.daprd2), } } func (r *remotereceiverhastoken) Run(t *testing.T, ctx context.Context) { r.daprd1.WaitUntilRunning(t, ctx) r.daprd2.WaitUntilRunning(t, ctx) dclient := r.daprd1.GRPCClient(t, ctx) _, err := dclient.InvokeService(ctx, &runtimev1.InvokeServiceRequest{ Id: r.daprd2.AppID(), Message: &commonv1.InvokeRequest{ Method: "helloworld", Data: new(anypb.Any), HttpExtension: &commonv1.HTTPExtension{Verb: commonv1.HTTPExtension_GET}, }, }) require.NoError(t, err) select { case header := <-r.ch: require.Equal(t, "abc", header.Get("dapr-api-token")) case <-time.After(5 * time.Second): assert.Fail(t, "timed out waiting for header") } }
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/http/appapitoken/remotereceiverhastoken.go
GO
mit
2,403
/* 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 appapitoken import ( "context" "net/http" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/types/known/anypb" commonv1 "github.com/dapr/dapr/pkg/proto/common/v1" runtimev1 "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(remotereceivernotoken)) } type remotereceivernotoken struct { daprd1 *daprd.Daprd daprd2 *daprd.Daprd ch chan http.Header } func (n *remotereceivernotoken) Setup(t *testing.T) []framework.Option { n.ch = make(chan http.Header, 1) app := app.New(t, app.WithHandlerFunc("/helloworld", func(w http.ResponseWriter, r *http.Request) { n.ch <- r.Header }), ) n.daprd1 = daprd.New(t, daprd.WithAppAPIToken(t, "abc"), ) n.daprd2 = daprd.New(t, daprd.WithAppPort(app.Port()), ) return []framework.Option{ framework.WithProcesses(app, n.daprd1, n.daprd2), } } func (n *remotereceivernotoken) Run(t *testing.T, ctx context.Context) { n.daprd1.WaitUntilRunning(t, ctx) n.daprd2.WaitUntilRunning(t, ctx) dclient := n.daprd1.GRPCClient(t, ctx) _, err := dclient.InvokeService(ctx, &runtimev1.InvokeServiceRequest{ Id: n.daprd2.AppID(), Message: &commonv1.InvokeRequest{ Method: "helloworld", Data: new(anypb.Any), HttpExtension: &commonv1.HTTPExtension{Verb: commonv1.HTTPExtension_GET}, }, }) require.NoError(t, err) select { case header := <-n.ch: require.Empty(t, header.Values("dapr-api-token")) case <-time.After(5 * time.Second): assert.Fail(t, "timed out waiting for header") } }
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/http/appapitoken/remotereceivernotoken.go
GO
mit
2,395
/* 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 appapitoken import ( "context" "net/http" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/types/known/anypb" commonv1 "github.com/dapr/dapr/pkg/proto/common/v1" runtimev1 "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(selfnotoken)) } type selfnotoken struct { daprd *daprd.Daprd ch chan http.Header } func (n *selfnotoken) Setup(t *testing.T) []framework.Option { n.ch = make(chan http.Header, 1) app := app.New(t, app.WithHandlerFunc("/helloworld", func(w http.ResponseWriter, r *http.Request) { n.ch <- r.Header }), ) n.daprd = daprd.New(t, daprd.WithAppPort(app.Port()), ) return []framework.Option{ framework.WithProcesses(app, n.daprd), } } func (n *selfnotoken) Run(t *testing.T, ctx context.Context) { n.daprd.WaitUntilRunning(t, ctx) dclient := n.daprd.GRPCClient(t, ctx) _, err := dclient.InvokeService(ctx, &runtimev1.InvokeServiceRequest{ Id: n.daprd.AppID(), Message: &commonv1.InvokeRequest{ Method: "helloworld", Data: new(anypb.Any), HttpExtension: &commonv1.HTTPExtension{Verb: commonv1.HTTPExtension_GET}, }, }) require.NoError(t, err) select { case header := <-n.ch: require.Empty(t, header.Values("dapr-api-token")) case <-time.After(5 * time.Second): assert.Fail(t, "timed out waiting for header") } }
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/http/appapitoken/selfnotoken.go
GO
mit
2,218
/* 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 appapitoken import ( "context" "net/http" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/types/known/anypb" commonv1 "github.com/dapr/dapr/pkg/proto/common/v1" runtimev1 "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(selfwithtoken)) } type selfwithtoken struct { daprd *daprd.Daprd ch chan http.Header } func (s *selfwithtoken) Setup(t *testing.T) []framework.Option { s.ch = make(chan http.Header, 1) app := app.New(t, app.WithHandlerFunc("/helloworld", func(w http.ResponseWriter, r *http.Request) { s.ch <- r.Header }), ) s.daprd = daprd.New(t, daprd.WithAppAPIToken(t, "abc"), daprd.WithAppPort(app.Port()), ) return []framework.Option{ framework.WithProcesses(app, s.daprd), } } func (s *selfwithtoken) Run(t *testing.T, ctx context.Context) { s.daprd.WaitUntilRunning(t, ctx) dclient := s.daprd.GRPCClient(t, ctx) _, err := dclient.InvokeService(ctx, &runtimev1.InvokeServiceRequest{ Id: s.daprd.AppID(), Message: &commonv1.InvokeRequest{ Method: "helloworld", Data: new(anypb.Any), HttpExtension: &commonv1.HTTPExtension{Verb: commonv1.HTTPExtension_GET}, }, }) require.NoError(t, err) select { case header := <-s.ch: require.Equal(t, "abc", header.Get("dapr-api-token")) case <-time.After(5 * time.Second): assert.Fail(t, "timed out waiting for header") } }
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/http/appapitoken/selfwithtoken.go
GO
mit
2,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://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 http import ( "context" "fmt" "io" "net/http" "strings" "testing" "github.com/google/uuid" "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(basic)) } type basic struct { daprd1 *procdaprd.Daprd daprd2 *procdaprd.Daprd } func (b *basic) Setup(t *testing.T) []framework.Option { newHTTPServer := func() *prochttp.HTTP { handler := http.NewServeMux() handler.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodPatch: w.WriteHeader(http.StatusBadGateway) case http.MethodPost: w.WriteHeader(http.StatusCreated) case http.MethodGet: w.WriteHeader(http.StatusOK) case http.MethodPut: w.WriteHeader(http.StatusAccepted) case http.MethodDelete: w.WriteHeader(http.StatusConflict) } w.Write([]byte(r.Method)) }) handler.HandleFunc("/echo", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("x-method", r.Method) io.Copy(w, r.Body) }) handler.HandleFunc("/with-headers-and-body", func(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(r.Body) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } if string(body) != "hello" { w.WriteHeader(http.StatusBadRequest) return } if r.Header.Get("foo") != "bar" { w.WriteHeader(http.StatusBadRequest) return } w.WriteHeader(http.StatusOK) }) handler.HandleFunc("/multiple/segments", func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/multiple/segments" { w.WriteHeader(http.StatusBadRequest) return } w.WriteHeader(http.StatusOK) w.Write([]byte("ok")) }) return prochttp.New(t, prochttp.WithHandler(handler)) } srv1 := newHTTPServer() srv2 := newHTTPServer() b.daprd1 = procdaprd.New(t, procdaprd.WithAppPort(srv1.Port())) b.daprd2 = procdaprd.New(t, procdaprd.WithAppPort(srv2.Port())) return []framework.Option{ framework.WithProcesses(srv1, srv2, b.daprd1, b.daprd2), } } func (b *basic) Run(t *testing.T, ctx context.Context) { b.daprd1.WaitUntilRunning(t, ctx) b.daprd2.WaitUntilRunning(t, ctx) httpClient := util.HTTPClient(t) t.Run("invoke url", func(t *testing.T) { doReq := func(method, url string, headers map[string]string) (int, string) { req, err := http.NewRequestWithContext(ctx, method, url, nil) require.NoError(t, err) for k, v := range headers { req.Header.Set(k, v) } 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, string(body) } for _, ts := range []struct { url string headers map[string]string }{ {url: fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/foo", b.daprd1.HTTPPort(), b.daprd2.AppID())}, {url: fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/foo", b.daprd2.HTTPPort(), b.daprd1.AppID())}, {url: fmt.Sprintf("http://localhost:%d/v1.0////invoke/%s/method/foo", b.daprd2.HTTPPort(), b.daprd1.AppID())}, {url: fmt.Sprintf("http://localhost:%d/v1.0//invoke//%s/method//foo", b.daprd1.HTTPPort(), b.daprd2.AppID())}, {url: fmt.Sprintf("http://localhost:%d///foo", b.daprd1.HTTPPort()), headers: map[string]string{ "foo": "bar", "dapr-app-id": b.daprd2.AppID(), }}, } { status, body := doReq(http.MethodGet, ts.url, ts.headers) assert.Equal(t, http.StatusOK, status) assert.Equal(t, "GET", body) status, body = doReq(http.MethodPost, ts.url, ts.headers) assert.Equal(t, http.StatusCreated, status) assert.Equal(t, "POST", body) status, body = doReq(http.MethodPut, ts.url, ts.headers) assert.Equal(t, http.StatusAccepted, status) assert.Equal(t, "PUT", body) status, body = doReq(http.MethodDelete, ts.url, ts.headers) assert.Equal(t, http.StatusConflict, status) assert.Equal(t, "DELETE", body) status, body = doReq(http.MethodPatch, ts.url, ts.headers) assert.Equal(t, http.StatusBadGateway, status) assert.Equal(t, "PATCH", body) } }) t.Run("invoke url with body and headers", func(t *testing.T) { reqURL := fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/with-headers-and-body", b.daprd1.HTTPPort(), b.daprd2.AppID()) req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, strings.NewReader("hello")) require.NoError(t, err) req.Header.Set("foo", "bar") resp, err := util.HTTPClient(t).Do(req) require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) require.NoError(t, resp.Body.Close()) }) t.Run("method doesn't exist", func(t *testing.T) { reqURL := fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/doesntexist", b.daprd1.HTTPPort(), b.daprd2.AppID()) req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, nil) require.NoError(t, err) resp, err := util.HTTPClient(t).Do(req) require.NoError(t, err) assert.Equal(t, http.StatusNotFound, resp.StatusCode) require.NoError(t, resp.Body.Close()) }) t.Run("no method", func(t *testing.T) { reqURL := fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s", b.daprd1.HTTPPort(), b.daprd2.AppID()) req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, nil) require.NoError(t, err) resp, err := util.HTTPClient(t).Do(req) require.NoError(t, err) assert.Equal(t, http.StatusNotFound, resp.StatusCode) require.NoError(t, resp.Body.Close()) reqURL = fmt.Sprintf("http://localhost:%d/", b.daprd1.HTTPPort()) req, err = http.NewRequestWithContext(ctx, http.MethodPost, reqURL, nil) require.NoError(t, err) req.Header.Set("dapr-app-id", b.daprd2.AppID()) resp, err = util.HTTPClient(t).Do(req) require.NoError(t, err) assert.Equal(t, http.StatusNotFound, resp.StatusCode) require.NoError(t, resp.Body.Close()) }) t.Run("multiple segments", func(t *testing.T) { reqURL := fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/multiple/segments", b.daprd1.HTTPPort(), b.daprd2.AppID()) req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, nil) require.NoError(t, err) resp, err := util.HTTPClient(t).Do(req) require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) assert.Equal(t, "ok", string(body)) }) client := util.HTTPClient(t) pt := util.NewParallel(t) for i := 0; i < 100; i++ { pt.Add(func(t *assert.CollectT) { u := uuid.New().String() reqURL := fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/echo", b.daprd1.HTTPPort(), b.daprd2.AppID()) req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, strings.NewReader(u)) require.NoError(t, err) resp, err := client.Do(req) require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) assert.Equal(t, "POST", resp.Header.Get("x-method")) assert.Equal(t, u, string(body)) }) } }
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/http/basic.go
GO
mit
8,001
/* 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 http import ( "bytes" "context" "fmt" "io" "net/http" "strings" "testing" fuzz "github.com/google/gofuzz" "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(fuzzhttp)) } type header struct { name string value string } type fuzzhttp struct { daprd1 *procdaprd.Daprd daprd2 *procdaprd.Daprd methods []string bodies [][]byte headers [][]header queries []map[string]string } func (f *fuzzhttp) Setup(t *testing.T) []framework.Option { const numTests = 1000 handler := http.NewServeMux() handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(r.Body) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } w.WriteHeader(http.StatusOK) w.Write(body) }) srv := prochttp.New(t, prochttp.WithHandler(handler)) f.daprd1 = procdaprd.New(t, procdaprd.WithAppPort(srv.Port()), procdaprd.WithLogLevel("info")) f.daprd2 = procdaprd.New(t, procdaprd.WithLogLevel("info")) var ( alphaNumeric = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" pathChars = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~:/#[]@!$'()+,=") headerNameChars = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~") headerValueChars = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789a_ :;.,\\/\"'?!(){}[]@<>=-+*#$&`|~^%") queryChars = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~:/#[]@!$&'()*+,=") ) methodFuzz := func(s *string, c fuzz.Continue) { n := c.Rand.Intn(100) var sb strings.Builder sb.Grow(n) firstSegment := true for i := 0; i < n; i++ { c := pathChars[c.Rand.Intn(len(pathChars))] // Prevent the first character being a non alpha-numeric character. if (i == 0 || sb.String()[i-1] == '/') && !strings.ContainsRune(alphaNumeric, c) { i-- continue } // Prevent first segment from having a colon. if firstSegment && c == ':' { i-- continue } if c == '/' { firstSegment = false } sb.WriteRune(c) // Prevent last character being a '.' or a ','. if i == n-1 && (c == '.' || c == ',') { i-- continue } } *s = sb.String() } headerFuzz := func(s *header, c fuzz.Continue) { n := c.Rand.Intn(100) + 1 var sb strings.Builder sb.Grow(n) for i := 0; i < n; i++ { sb.WriteRune(headerNameChars[c.Rand.Intn(len(headerNameChars))]) } s.name = sb.String() sb.Reset() sb.Grow(n) for i := 0; i < n; i++ { sb.WriteRune(headerValueChars[c.Rand.Intn(len(headerValueChars))]) } s.value = sb.String() } queryFuzz := func(m map[string]string, c fuzz.Continue) { n := c.Rand.Intn(4) + 1 for i := 0; i < n; i++ { var sb strings.Builder sb.Grow(n) for i := 0; i < n; i++ { sb.WriteRune(queryChars[c.Rand.Intn(len(queryChars))]) } m[sb.String()] = sb.String() } } f.methods = make([]string, numTests) f.bodies = make([][]byte, numTests) f.headers = make([][]header, numTests) f.queries = make([]map[string]string, numTests) for i := 0; i < numTests; i++ { fz := fuzz.New() fz.NumElements(0, 100).Funcs(methodFuzz).Fuzz(&f.methods[i]) fz.NumElements(0, 100).Fuzz(&f.bodies[i]) fz.NumElements(0, 10).Funcs(headerFuzz).Fuzz(&f.headers[i]) fz.NumElements(0, 100).Funcs(queryFuzz).Fuzz(&f.queries[i]) } return []framework.Option{ framework.WithProcesses(f.daprd1, f.daprd2, srv), } } func (f *fuzzhttp) Run(t *testing.T, ctx context.Context) { f.daprd1.WaitUntilRunning(t, ctx) f.daprd2.WaitUntilRunning(t, ctx) httpClient := util.HTTPClient(t) pt := util.NewParallel(t) for i := 0; i < len(f.methods); i++ { method := f.methods[i] body := f.bodies[i] headers := f.headers[i] query := f.queries[i] pt.Add(func(t *assert.CollectT) { for _, ts := range []struct { url string headers map[string]string }{ {url: fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/%s", f.daprd2.HTTPPort(), f.daprd1.AppID(), method)}, {url: fmt.Sprintf("http://localhost:%d/%s", f.daprd2.HTTPPort(), method), headers: map[string]string{"dapr-app-id": f.daprd1.AppID()}}, } { req, err := http.NewRequestWithContext(ctx, http.MethodPost, ts.url, bytes.NewReader(body)) require.NoError(t, err) for _, header := range headers { req.Header.Set(header.name, header.value) } for k, v := range ts.headers { req.Header.Set(k, v) } q := req.URL.Query() for k, v := range query { q.Set(k, v) } req.URL.RawQuery = q.Encode() resp, err := httpClient.Do(req) require.NoError(t, err) respBody, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Equalf(t, string(body), string(respBody), "url=%s, headers=%v", ts.url, req.Header) } }) } }
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/http/fuzz.go
GO
mit
5,865
/* 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 http import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/serviceinvocation/http/appapitoken" )
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/http/http.go
GO
mit
677
/* 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 http import ( "context" "encoding/json" "fmt" "io" "net/http" "strings" "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" cryptotest "github.com/dapr/kit/crypto/test" ) func init() { suite.Register(new(httpendpoints)) } type httpendpoints struct { daprd1 *procdaprd.Daprd daprd2 *procdaprd.Daprd appPort int } func (h *httpendpoints) Setup(t *testing.T) []framework.Option { pki1 := cryptotest.GenPKI(t, cryptotest.PKIOptions{LeafDNS: "localhost"}) pki2 := cryptotest.GenPKI(t, cryptotest.PKIOptions{LeafDNS: "localhost"}) newHTTPServer := func() *prochttp.HTTP { handler := http.NewServeMux() handler.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("ok")) }) return prochttp.New(t, prochttp.WithHandler(handler)) } newHTTPServerTLS := func() *prochttp.HTTP { handler := http.NewServeMux() handler.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("ok-TLS")) }) return prochttp.New(t, prochttp.WithHandler(handler), prochttp.WithMTLS(t, pki1.RootCertPEM, pki1.LeafCertPEM, pki1.LeafPKPEM)) } srv1 := newHTTPServer() srv2 := newHTTPServerTLS() h.daprd1 = procdaprd.New(t, procdaprd.WithResourceFiles(fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: HTTPEndpoint metadata: name: mywebsite spec: version: v1alpha1 baseUrl: http://localhost:%d `, srv1.Port()), fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: HTTPEndpoint metadata: name: mywebsitetls spec: version: v1alpha1 baseUrl: https://localhost:%d clientTLS: rootCA: value: "%s" certificate: value: "%s" privateKey: value: "%s" `, srv2.Port(), strings.ReplaceAll(string(pki1.RootCertPEM), "\n", "\\n"), strings.ReplaceAll(string(pki1.LeafCertPEM), "\n", "\\n"), strings.ReplaceAll(string(pki1.LeafPKPEM), "\n", "\\n")))) h.daprd2 = procdaprd.New(t, procdaprd.WithResourceFiles(fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: HTTPEndpoint metadata: name: mywebsite spec: version: v1alpha1 baseUrl: http://localhost:%d `, srv1.Port()), fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: HTTPEndpoint metadata: name: mywebsitetls spec: version: v1alpha1 baseUrl: https://localhost:%d clientTLS: rootCA: value: "%s" certificate: value: "%s" privateKey: value: "%s" `, srv2.Port(), strings.ReplaceAll(string(pki1.RootCertPEM), "\n", "\\n"), strings.ReplaceAll(string(pki2.LeafCertPEM), "\n", "\\n"), strings.ReplaceAll(string(pki2.LeafPKPEM), "\n", "\\n")))) h.appPort = srv1.Port() return []framework.Option{ framework.WithProcesses(srv1, srv2, h.daprd1, h.daprd2), } } func (h *httpendpoints) Run(t *testing.T, ctx context.Context) { h.daprd1.WaitUntilRunning(t, ctx) h.daprd2.WaitUntilRunning(t, ctx) httpClient := util.HTTPClient(t) invokeTests := func(t *testing.T, expTLSCode int, assertBody func(c *assert.CollectT, body string), daprd *procdaprd.Daprd) { for _, port := range []int{ h.daprd1.HTTPPort(), h.daprd2.HTTPPort(), } { assert.EventuallyWithT(t, func(t *assert.CollectT) { url := fmt.Sprintf("http://localhost:%d/v1.0/metadata", port) req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) require.NoError(t, err) resp, err := httpClient.Do(req) require.NoError(t, err) body := make(map[string]any) require.NoError(t, json.NewDecoder(resp.Body).Decode(&body)) require.NoError(t, resp.Body.Close()) endpoints, ok := body["httpEndpoints"] _ = assert.True(t, ok) && assert.Len(t, endpoints.([]any), 2) }, time.Second*5, time.Millisecond*10) } t.Run("invoke http endpoint", func(t *testing.T) { doReq := func(method, url string, headers map[string]string) (int, string) { req, err := http.NewRequestWithContext(ctx, method, url, nil) require.NoError(t, err) for k, v := range headers { req.Header.Set(k, v) } 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, string(body) } for i, ts := range []struct { url string headers map[string]string }{ {url: fmt.Sprintf("http://localhost:%d/v1.0/invoke/http://localhost:%d/method/hello", daprd.HTTPPort(), h.appPort)}, {url: fmt.Sprintf("http://localhost:%d/v1.0/invoke/mywebsite/method/hello", daprd.HTTPPort())}, } { t.Run(fmt.Sprintf("url %d", i), func(t *testing.T) { status, body := doReq(http.MethodGet, ts.url, ts.headers) assert.Equal(t, http.StatusOK, status) assert.Equal(t, "ok", body) }) } }) t.Run("invoke TLS http endpoint", func(t *testing.T) { doReq := func(method, url string, headers map[string]string) (int, string) { req, err := http.NewRequestWithContext(ctx, method, url, nil) require.NoError(t, err) for k, v := range headers { req.Header.Set(k, v) } 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, string(body) } for i, ts := range []struct { url string headers map[string]string }{ {url: fmt.Sprintf("http://localhost:%d/v1.0/invoke/mywebsitetls/method/hello", daprd.HTTPPort())}, } { t.Run(fmt.Sprintf("url %d", i), func(t *testing.T) { assert.EventuallyWithT(t, func(c *assert.CollectT) { status, body := doReq(http.MethodGet, ts.url, ts.headers) assert.Equal(t, expTLSCode, status) assertBody(c, body) }, time.Second*5, time.Millisecond*10) }) } }) } t.Run("good PKI", func(t *testing.T) { invokeTests(t, http.StatusOK, func(c *assert.CollectT, body string) { assert.Equal(c, "ok-TLS", body) }, h.daprd1) }) t.Run("bad PKI", func(t *testing.T) { invokeTests(t, http.StatusInternalServerError, func(c *assert.CollectT, body string) { assert.Contains(c, body, `"errorCode":"ERR_DIRECT_INVOKE"`) assert.Contains(c, body, "tls: unknown certificate authority") }, h.daprd2) }) }
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/http/httpendpoints.go
GO
mit
7,120
/* 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 serviceinvocation import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/serviceinvocation/grpc" _ "github.com/dapr/dapr/tests/integration/suite/daprd/serviceinvocation/http" )
mikeee/dapr
tests/integration/suite/daprd/serviceinvocation/serviceinvocation.go
GO
mit
757
/* 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 app import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/shutdown/block/app/pubsub" )
mikeee/dapr
tests/integration/suite/daprd/shutdown/block/app/app.go
GO
mit
667
/* 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 app import ( "context" "io" "net/http" "runtime" "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" commonv1 "github.com/dapr/dapr/pkg/proto/common/v1" 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/logline" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(healthy)) } // health tests Daprd's --dapr-block-shutdown-seconds, ensuring shutdown will // occur when the app becomes unhealthy. type healthy struct { daprd *daprd.Daprd logline *logline.LogLine appHealth atomic.Bool healthzCalled atomic.Int64 routeCh chan struct{} } func (h *healthy) Setup(t *testing.T) []framework.Option { if runtime.GOOS == "windows" { t.Skip("Skipping test on windows which relies on unix process signals") } h.appHealth.Store(true) h.routeCh = make(chan struct{}, 1) handler := http.NewServeMux() handler.HandleFunc("/dapr/subscribe", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) io.WriteString(w, `[{"pubsubname":"foo","topic":"topic","route":"route"}]`) }) handler.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { defer h.healthzCalled.Add(1) if h.appHealth.Load() { w.WriteHeader(http.StatusOK) return } w.WriteHeader(http.StatusServiceUnavailable) }) handler.HandleFunc("/route", func(w http.ResponseWriter, r *http.Request) { h.routeCh <- struct{}{} }) app := prochttp.New(t, prochttp.WithHandler(handler), ) h.logline = logline.New(t, logline.WithStdoutLineContains( "Blocking graceful shutdown for 3m0s or until app reports unhealthy...", "App reported unhealthy, entering shutdown...", "Daprd shutdown gracefully", ), ) h.daprd = daprd.New(t, daprd.WithDaprBlockShutdownDuration("180s"), daprd.WithAppPort(app.Port()), daprd.WithAppHealthCheck(true), daprd.WithAppHealthCheckPath("/healthz"), daprd.WithAppHealthProbeInterval(1), daprd.WithAppHealthProbeThreshold(1), daprd.WithExecOptions(exec.WithStdout(h.logline.Stdout())), daprd.WithResourceFiles(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: foo spec: type: pubsub.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: mystore spec: type: state.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(app, h.logline), } } func (h *healthy) Run(t *testing.T, ctx context.Context) { h.daprd.Run(t, ctx) h.daprd.WaitUntilRunning(t, ctx) client := h.daprd.GRPCClient(t, ctx) assert.EventuallyWithT(t, func(c *assert.CollectT) { resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest)) //nolint:testifylint assert.NoError(c, err) assert.Len(c, resp.GetSubscriptions(), 1) }, time.Second*5, time.Millisecond*10) _, err := client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "foo", Topic: "topic", Data: []byte(`{"status":"completed"}`), }) require.NoError(t, err) select { case <-h.routeCh: case <-ctx.Done(): assert.Fail(t, "pubsub did not send message to subscriber") } daprdStopped := make(chan struct{}) go func() { h.daprd.Cleanup(t) close(daprdStopped) }() healthzCalled := h.healthzCalled.Load() assert.Eventually(t, func() bool { return h.healthzCalled.Load() > healthzCalled }, time.Second*5, time.Millisecond*10) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "foo", Topic: "topic", Data: []byte(`{"status":"completed"}`), }) require.NoError(t, err) select { case <-h.routeCh: assert.Fail(t, "pubsub should not have sent message to subscriber") case <-time.After(time.Second): } _, err = client.SaveState(ctx, &rtv1.SaveStateRequest{ StoreName: "mystore", States: []*commonv1.StateItem{ {Key: "key", Value: []byte("value")}, }, }) require.NoError(t, err) healthzCalled = h.healthzCalled.Load() h.appHealth.Store(false) require.Equal(t, healthzCalled, h.healthzCalled.Load()) assert.Eventually(t, func() bool { return h.healthzCalled.Load() > healthzCalled }, time.Second*5, time.Millisecond*10) assert.EventuallyWithT(t, func(c *assert.CollectT) { _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "foo", Topic: "topic", Data: []byte(`{"status":"completed"}`), }) //nolint:testifylint assert.Error(c, err) }, time.Second*5, time.Millisecond*10) _, err = client.SaveState(ctx, &rtv1.SaveStateRequest{ StoreName: "mystore", States: []*commonv1.StateItem{ {Key: "key", Value: []byte("value2")}, }, }) require.Error(t, err) select { case <-daprdStopped: case <-time.After(time.Second * 5): assert.Fail(t, "daprd did not exit in time") } }
mikeee/dapr
tests/integration/suite/daprd/shutdown/block/app/healthy.go
GO
mit
5,648
/* 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 pubsub import ( "context" "fmt" "io" "net/http" "runtime" "sync/atomic" "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" prochttp "github.com/dapr/dapr/tests/integration/framework/process/http" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(bulk)) } // bulk ensures that in-flight bulk messages will continue to be processed when // a SIGTERM is received by daprd. type bulk struct { daprd *daprd.Daprd appHealth atomic.Bool inPublish chan struct{} returnPublish chan struct{} recvRoute2 chan struct{} } func (b *bulk) Setup(t *testing.T) []framework.Option { if runtime.GOOS == "windows" { t.Skip("Skipping test on windows which relies on unix process signals") } b.appHealth.Store(true) b.inPublish = make(chan struct{}) b.returnPublish = make(chan struct{}) b.recvRoute2 = make(chan struct{}) bulkResp := []byte(`{"statuses":[{"entryId":"1","status":"SUCCESS"}]}`) handler := http.NewServeMux() handler.HandleFunc("/dapr/subscribe", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) io.WriteString(w, `[ {"pubsubname":"foo","topic":"abc","route":"route1"}, {"pubsubname":"foo","topic":"def","route":"route2"} ]`) }) handler.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { if b.appHealth.Load() { w.WriteHeader(http.StatusOK) return } w.WriteHeader(http.StatusServiceUnavailable) }) handler.HandleFunc("/route1", func(w http.ResponseWriter, r *http.Request) { close(b.inPublish) <-b.returnPublish w.Write(bulkResp) }) handler.HandleFunc("/route2", func(w http.ResponseWriter, r *http.Request) { select { case b.recvRoute2 <- struct{}{}: case <-r.Context().Done(): } w.Write(bulkResp) }) app := prochttp.New(t, prochttp.WithHandler(handler)) b.daprd = daprd.New(t, daprd.WithDaprBlockShutdownDuration("180s"), daprd.WithAppPort(app.Port()), daprd.WithAppHealthCheck(true), daprd.WithAppHealthCheckPath("/healthz"), daprd.WithAppHealthProbeInterval(1), daprd.WithAppHealthProbeThreshold(1), daprd.WithResourceFiles(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: foo spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(app), } } func (b *bulk) Run(t *testing.T, ctx context.Context) { b.daprd.Run(t, ctx) b.daprd.WaitUntilRunning(t, ctx) client := b.daprd.GRPCClient(t, ctx) assert.Len(t, b.daprd.GetMetaRegistedComponents(t, ctx), 1) _, err := client.BulkPublishEventAlpha1(ctx, &rtv1.BulkPublishRequest{ PubsubName: "foo", Topic: "abc", Entries: []*rtv1.BulkPublishRequestEntry{ {EntryId: "1", Event: []byte(`{"status":"completed"}`), ContentType: "application/json"}, }, }) require.NoError(t, err) select { case <-b.inPublish: case <-time.After(time.Second * 5): assert.Fail(t, "did not receive publish event") } daprdStopped := make(chan struct{}) go func() { b.daprd.Cleanup(t) close(daprdStopped) }() t.Cleanup(func() { select { case <-daprdStopped: case <-time.After(time.Second * 5): assert.Fail(t, "daprd did not exit in time") } }) LOOP: for { _, err := client.BulkPublishEventAlpha1(ctx, &rtv1.BulkPublishRequest{ PubsubName: "foo", Topic: "def", Entries: []*rtv1.BulkPublishRequestEntry{ {EntryId: "1", Event: []byte(`{"status":"completed"}`), ContentType: "application/json"}, }, }) require.NoError(t, err) select { case <-b.recvRoute2: case <-time.After(time.Second / 2): break LOOP } } close(b.returnPublish) egressMetric := fmt.Sprintf("dapr_component_pubsub_egress_bulk_count|app_id:%s|component:foo|namespace:|success:true|topic:abc", b.daprd.AppID()) ingressMetric := fmt.Sprintf("dapr_component_pubsub_ingress_count|app_id:%s|component:foo|namespace:|process_status:success|status:success|topic:abc", b.daprd.AppID()) assert.EventuallyWithT(t, func(c *assert.CollectT) { metrics := b.daprd.Metrics(t, ctx) assert.Equal(c, 1, int(metrics[egressMetric])) assert.Equal(c, 1, int(metrics[ingressMetric])) }, time.Second*5, time.Millisecond*10) b.appHealth.Store(false) }
mikeee/dapr
tests/integration/suite/daprd/shutdown/block/app/pubsub/bulk.go
GO
mit
4,949
/* 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 pubsub import ( "context" "fmt" "io" "net/http" "runtime" "sync/atomic" "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" prochttp "github.com/dapr/dapr/tests/integration/framework/process/http" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(single)) } // single ensures that in-flight messages will continue to be processed when a // SIGTERM is received by daprd. type single struct { daprd *daprd.Daprd appHealth atomic.Bool inPublish chan struct{} returnPublish chan struct{} recvRoute2 chan struct{} } func (s *single) Setup(t *testing.T) []framework.Option { if runtime.GOOS == "windows" { t.Skip("Skipping test on windows which relies on unix process signals") } s.appHealth.Store(true) s.inPublish = make(chan struct{}) s.returnPublish = make(chan struct{}) s.recvRoute2 = make(chan struct{}) handler := http.NewServeMux() handler.HandleFunc("/dapr/subscribe", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) io.WriteString(w, `[ {"pubsubname":"foo","topic":"abc","route":"route1"}, {"pubsubname":"foo","topic":"def","route":"route2"} ]`) }) handler.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { if s.appHealth.Load() { w.WriteHeader(http.StatusOK) return } w.WriteHeader(http.StatusServiceUnavailable) }) handler.HandleFunc("/route1", func(w http.ResponseWriter, r *http.Request) { close(s.inPublish) <-s.returnPublish }) handler.HandleFunc("/route2", func(w http.ResponseWriter, r *http.Request) { select { case s.recvRoute2 <- struct{}{}: case <-r.Context().Done(): } }) app := prochttp.New(t, prochttp.WithHandler(handler)) s.daprd = daprd.New(t, daprd.WithDaprBlockShutdownDuration("180s"), daprd.WithAppPort(app.Port()), daprd.WithAppHealthCheck(true), daprd.WithAppHealthCheckPath("/healthz"), daprd.WithAppHealthProbeInterval(1), daprd.WithAppHealthProbeThreshold(1), daprd.WithResourceFiles(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: foo spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(app), } } func (s *single) Run(t *testing.T, ctx context.Context) { s.daprd.Run(t, ctx) s.daprd.WaitUntilRunning(t, ctx) client := s.daprd.GRPCClient(t, ctx) assert.Len(t, s.daprd.GetMetaRegistedComponents(t, ctx), 1) _, err := client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "foo", Topic: "abc", Data: []byte(`{"status":"completed"}`), }) require.NoError(t, err) select { case <-s.inPublish: case <-time.After(time.Second * 5): assert.Fail(t, "did not receive publish event") } daprdStopped := make(chan struct{}) go func() { s.daprd.Cleanup(t) close(daprdStopped) }() t.Cleanup(func() { select { case <-daprdStopped: case <-time.After(time.Second * 5): assert.Fail(t, "daprd did not exit in time") } }) LOOP: for { _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "foo", Topic: "def", Data: []byte(`{"status":"completed"}`), }) require.NoError(t, err) select { case <-s.recvRoute2: case <-time.After(time.Second / 2): break LOOP } } close(s.returnPublish) egressMetric := fmt.Sprintf("dapr_component_pubsub_egress_count|app_id:%s|component:foo|namespace:|success:true|topic:abc", s.daprd.AppID()) ingressMetric := fmt.Sprintf("dapr_component_pubsub_ingress_count|app_id:%s|component:foo|namespace:|process_status:success|status:success|topic:abc", s.daprd.AppID()) assert.EventuallyWithT(t, func(c *assert.CollectT) { metrics := s.daprd.Metrics(t, ctx) assert.Equal(c, 1, int(metrics[egressMetric])) assert.Equal(c, 1, int(metrics[ingressMetric])) }, time.Second*5, time.Millisecond*10) s.appHealth.Store(false) }
mikeee/dapr
tests/integration/suite/daprd/shutdown/block/app/pubsub/single.go
GO
mit
4,626
/* 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 app import ( "context" "io" "net/http" "runtime" "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" commonv1 "github.com/dapr/dapr/pkg/proto/common/v1" 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/logline" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(unhealthy)) } // unhealth tests Daprd's --dapr-block-shutdown-seconds, ensuring shutdown will // occur straight away if the app is already unhealthy. type unhealthy struct { daprd *daprd.Daprd logline *logline.LogLine appHealth atomic.Bool routeCh chan struct{} } func (u *unhealthy) Setup(t *testing.T) []framework.Option { if runtime.GOOS == "windows" { t.Skip("Skipping test on windows which relies on unix process signals") } u.appHealth.Store(true) u.routeCh = make(chan struct{}, 1) handler := http.NewServeMux() handler.HandleFunc("/dapr/subscribe", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) io.WriteString(w, `[{"pubsubname":"foo","topic":"topic","route":"route"}]`) }) handler.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { if u.appHealth.Load() { w.WriteHeader(http.StatusOK) return } w.WriteHeader(http.StatusServiceUnavailable) }) handler.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) { }) handler.HandleFunc("/route", func(w http.ResponseWriter, r *http.Request) { u.routeCh <- struct{}{} }) app := prochttp.New(t, prochttp.WithHandler(handler), ) u.logline = logline.New(t, logline.WithStdoutLineContains( "Blocking graceful shutdown for 3m0s or until app reports unhealthy...", "App reported unhealthy, entering shutdown...", "Daprd shutdown gracefully", ), ) u.daprd = daprd.New(t, daprd.WithDaprBlockShutdownDuration("180s"), daprd.WithAppPort(app.Port()), daprd.WithAppHealthCheck(true), daprd.WithAppHealthCheckPath("/healthz"), daprd.WithAppHealthProbeInterval(1), daprd.WithAppHealthProbeThreshold(1), daprd.WithExecOptions(exec.WithStdout(u.logline.Stdout())), daprd.WithResourceFiles(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: foo spec: type: pubsub.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(app, u.logline, u.daprd), } } func (u *unhealthy) Run(t *testing.T, ctx context.Context) { u.daprd.WaitUntilRunning(t, ctx) client := u.daprd.GRPCClient(t, ctx) assert.EventuallyWithT(t, func(c *assert.CollectT) { resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest)) //nolint:testifylint assert.NoError(c, err) assert.Len(c, resp.GetSubscriptions(), 1) }, time.Second*5, time.Millisecond*10) _, err := client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "foo", Topic: "topic", Data: []byte(`{"status":"completed"}`), }) require.NoError(t, err) select { case <-u.routeCh: case <-ctx.Done(): assert.Fail(t, "pubsub did not send message to subscriber") } u.appHealth.Store(false) assert.EventuallyWithT(t, func(c *assert.CollectT) { _, err = client.InvokeService(ctx, &rtv1.InvokeServiceRequest{ Id: u.daprd.AppID(), Message: &commonv1.InvokeRequest{ Method: "foo", HttpExtension: &commonv1.HTTPExtension{Verb: commonv1.HTTPExtension_GET}, }, }) //nolint:testifylint assert.ErrorContains(c, err, "app is not in a healthy state") }, time.Second*5, time.Millisecond*10) }
mikeee/dapr
tests/integration/suite/daprd/shutdown/block/app/unhealthy.go
GO
mit
4,364
/* 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 app import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/shutdown/block/app" )
mikeee/dapr
tests/integration/suite/daprd/shutdown/block/block.go
GO
mit
660
/* 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 app import ( "context" "io" "net/http" "runtime" "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" commonv1 "github.com/dapr/dapr/pkg/proto/common/v1" 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/logline" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(timeout)) } // timeout tests Daprd's --dapr-block-shutdown-seconds, ensuring shutdown // procedure will begin when seconds is reached when app still reports healthy. type timeout struct { daprd *daprd.Daprd logline *logline.LogLine routeCh chan struct{} listening atomic.Bool bindingChan chan struct{} } func (i *timeout) Setup(t *testing.T) []framework.Option { if runtime.GOOS == "windows" { t.Skip("Skipping test on windows which relies on unix process signals") } i.routeCh = make(chan struct{}, 1) i.bindingChan = make(chan struct{}) handler := http.NewServeMux() handler.HandleFunc("/dapr/subscribe", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) io.WriteString(w, `[{"pubsubname":"foo","topic":"topic","route":"route"}]`) }) handler.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }) handler.HandleFunc("/route", func(w http.ResponseWriter, r *http.Request) { i.routeCh <- struct{}{} }) handler.HandleFunc("/binding", func(w http.ResponseWriter, r *http.Request) { if i.listening.Load() { i.listening.Store(false) i.bindingChan <- struct{}{} } }) app := prochttp.New(t, prochttp.WithHandler(handler), ) i.logline = logline.New(t, logline.WithStdoutLineContains( "Blocking graceful shutdown for 2s or until app reports unhealthy...", "Block shutdown period expired, entering shutdown...", "Daprd shutdown gracefully", ), ) i.daprd = daprd.New(t, daprd.WithDaprBlockShutdownDuration("2s"), daprd.WithAppPort(app.Port()), daprd.WithAppHealthCheck(true), daprd.WithAppHealthCheckPath("/healthz"), daprd.WithAppHealthProbeInterval(1), daprd.WithAppHealthProbeThreshold(1), daprd.WithExecOptions(exec.WithStdout(i.logline.Stdout())), daprd.WithResourceFiles(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: foo spec: type: pubsub.in-memory version: v1 --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: 'binding' spec: type: bindings.cron version: v1 metadata: - name: schedule value: "@every 100ms" - name: direction value: "input" --- apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: 'mystore' spec: type: state.in-memory version: v1 `)) return []framework.Option{ framework.WithProcesses(app, i.logline), } } func (i *timeout) Run(t *testing.T, ctx context.Context) { i.daprd.Run(t, ctx) i.daprd.WaitUntilRunning(t, ctx) client := i.daprd.GRPCClient(t, ctx) assert.EventuallyWithT(t, func(c *assert.CollectT) { resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest)) //nolint:testifylint assert.NoError(c, err) assert.Len(c, resp.GetSubscriptions(), 1) }, time.Second*5, time.Millisecond*10) _, err := client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "foo", Topic: "topic", Data: []byte(`{"status":"completed"}`), }) require.NoError(t, err) select { case <-i.routeCh: case <-ctx.Done(): assert.Fail(t, "pubsub message should have been sent to subscriber") } i.listening.Store(true) select { case <-i.bindingChan: case <-time.After(time.Second * 5): assert.Fail(t, "timed out waiting for binding event") } _, err = client.SaveState(ctx, &rtv1.SaveStateRequest{ StoreName: "mystore", States: []*commonv1.StateItem{ { Key: "key", Value: []byte("value"), }, }, }) require.NoError(t, err) resp, err := client.GetState(ctx, &rtv1.GetStateRequest{ StoreName: "mystore", Key: "key", }) require.NoError(t, err) assert.Equal(t, "value", string(resp.GetData())) daprdStopped := make(chan struct{}) go func() { i.daprd.Cleanup(t) close(daprdStopped) }() t.Run("daprd APIs should still be available during blocked shutdown, except input bindings and subscriptions", func(t *testing.T) { time.Sleep(time.Second / 2) i.listening.Store(true) select { case <-i.bindingChan: assert.Fail(t, "binding event should not have been sent to subscriber") case <-time.After(time.Second / 2): } _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "foo", Topic: "topic", Data: []byte(`{"status":"completed"}`), }) require.NoError(t, err) select { case <-i.routeCh: assert.Fail(t, "pubsub message should not have been sent to subscriber") case <-time.After(time.Second / 2): } _, err = client.SaveState(ctx, &rtv1.SaveStateRequest{ StoreName: "mystore", States: []*commonv1.StateItem{ { Key: "key", Value: []byte("value2"), }, }, }) require.NoError(t, err) resp, err = client.GetState(ctx, &rtv1.GetStateRequest{ StoreName: "mystore", Key: "key", }) require.NoError(t, err) assert.Equal(t, "value2", string(resp.GetData())) }) t.Run("daprd APIs are no longer available when past blocked shutdown", func(t *testing.T) { time.Sleep(time.Second * 3 / 2) _, err = client.PublishEvent(ctx, &rtv1.PublishEventRequest{ PubsubName: "foo", Topic: "topic", Data: []byte(`{"status":"completed"}`), }) require.Error(t, err) _, err = client.SaveState(ctx, &rtv1.SaveStateRequest{ StoreName: "mystore", States: []*commonv1.StateItem{ { Key: "key", Value: []byte("value3"), }, }, }) require.Error(t, err) _, err = client.GetState(ctx, &rtv1.GetStateRequest{ StoreName: "mystore", Key: "key", }) require.Error(t, err) }) select { case <-daprdStopped: case <-time.After(time.Second * 5): assert.Fail(t, "daprd did not exit in time") } }
mikeee/dapr
tests/integration/suite/daprd/shutdown/block/timeout.go
GO
mit
6,849
/* 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 graceful import ( "context" "net/http" "runtime" "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/exec" prochttp "github.com/dapr/dapr/tests/integration/framework/process/http" "github.com/dapr/dapr/tests/integration/framework/process/logline" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(graceful)) } // graceful tests Daprd's --dapr-graceful-shutdown-seconds gracefully // terminates on all resources closing. type graceful struct { daprd *daprd.Daprd } func (g *graceful) Setup(t *testing.T) []framework.Option { if runtime.GOOS == "windows" { t.Skip("Skipping test on windows which relies on unix process signals") } app := prochttp.New(t, prochttp.WithHandler(http.NewServeMux())) logline := logline.New(t, logline.WithStdoutLineContains( "Daprd shutdown gracefully", ), ) g.daprd = daprd.New(t, daprd.WithDaprGracefulShutdownSeconds(5), daprd.WithAppPort(app.Port()), daprd.WithExecOptions(exec.WithStdout(logline.Stdout())), ) return []framework.Option{ framework.WithProcesses(app, logline, g.daprd), } } func (g *graceful) Run(t *testing.T, ctx context.Context) { g.daprd.WaitUntilRunning(t, ctx) }
mikeee/dapr
tests/integration/suite/daprd/shutdown/graceful/graceful.go
GO
mit
1,897
/* 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 graceful import ( "context" "fmt" "io" "net/http" "runtime" "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" prochttp "github.com/dapr/dapr/tests/integration/framework/process/http" "github.com/dapr/dapr/tests/integration/framework/process/logline" "github.com/dapr/dapr/tests/integration/framework/util" "github.com/dapr/dapr/tests/integration/suite" ) func init() { suite.Register(new(timeout)) } // timeout tests Daprd's --dapr-graceful-shutdown-seconds where Daprd force exits // because the graceful timeout expires. type timeout struct { daprd *daprd.Daprd closeInvoke chan struct{} inInvoke chan struct{} } func (i *timeout) Setup(t *testing.T) []framework.Option { if runtime.GOOS == "windows" { t.Skip("Skipping test on windows which relies on unix process signals") } i.closeInvoke = make(chan struct{}) i.inInvoke = make(chan struct{}) handler := http.NewServeMux() handler.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) { close(i.inInvoke) <-i.closeInvoke }) app := prochttp.New(t, prochttp.WithHandler(handler), ) logline := logline.New(t, logline.WithStdoutLineContains( "Graceful shutdown timeout exceeded, forcing shutdown", ), ) i.daprd = daprd.New(t, daprd.WithAppPort(app.Port()), daprd.WithDaprGracefulShutdownSeconds(1), daprd.WithExecOptions( exec.WithExitCode(1), exec.WithRunError(func(t *testing.T, err error) { require.ErrorContains(t, err, "exit status 1") }), exec.WithStdout(logline.Stdout()), ), ) return []framework.Option{ framework.WithProcesses(app, logline), } } func (i *timeout) Run(t *testing.T, ctx context.Context) { i.daprd.Run(t, ctx) i.daprd.WaitUntilRunning(t, ctx) client := util.HTTPClient(t) reqURL := fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/foo", i.daprd.HTTPPort(), i.daprd.AppID()) req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, nil) require.NoError(t, err) errCh := make(chan error) go func() { resp, cerr := client.Do(req) if resp != nil { resp.Body.Close() } errCh <- cerr }() <-i.inInvoke i.daprd.Cleanup(t) close(i.closeInvoke) require.ErrorIs(t, <-errCh, io.EOF) }
mikeee/dapr
tests/integration/suite/daprd/shutdown/graceful/timeout.go
GO
mit
2,942
/* 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 shutdown import ( _ "github.com/dapr/dapr/tests/integration/suite/daprd/shutdown/block" _ "github.com/dapr/dapr/tests/integration/suite/daprd/shutdown/graceful" )
mikeee/dapr
tests/integration/suite/daprd/shutdown/shutdown.go
GO
mit
735
/* 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 grpc import ( "context" "testing" "github.com/stretchr/testify/require" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" commonv1 "github.com/dapr/dapr/pkg/proto/common/v1" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "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(basic)) } type basic struct { daprd *procdaprd.Daprd } func (b *basic) Setup(t *testing.T) []framework.Option { b.daprd = procdaprd.New(t, procdaprd.WithInMemoryActorStateStore("mystore")) return []framework.Option{ framework.WithProcesses(b.daprd), } } func (b *basic) Run(t *testing.T, ctx context.Context) { b.daprd.WaitUntilRunning(t, ctx) 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()) }) client := rtv1.NewDaprClient(conn) t.Run("bad request", func(t *testing.T) { for _, req := range []*rtv1.SaveStateRequest{ nil, {}, {StoreName: "mystore", States: []*commonv1.StateItem{{}}}, {StoreName: "mystore", States: []*commonv1.StateItem{{Value: []byte("value1")}}}, } { _, err = client.SaveState(ctx, req) require.Error(t, err) } }) t.Run("good request", func(t *testing.T) { for _, req := range []*rtv1.SaveStateRequest{ {StoreName: "mystore"}, {StoreName: "mystore", States: []*commonv1.StateItem{}}, {StoreName: "mystore", States: []*commonv1.StateItem{{Key: "key1"}}}, {StoreName: "mystore", States: []*commonv1.StateItem{{Key: "key1", Value: []byte("value1")}}}, {StoreName: "mystore", States: []*commonv1.StateItem{{Key: "key1", Value: []byte("value1")}, {Key: "key2", Value: []byte("value2")}}}, {StoreName: "mystore", States: []*commonv1.StateItem{ {Key: "key1", Value: []byte("value1")}, {Key: "key2", Value: []byte("value2")}, {Key: "key1", Value: []byte("value1")}, {Key: "key2", Value: []byte("value2")}, }}, } { _, err = client.SaveState(ctx, req) require.NoError(t, err) } }) }
mikeee/dapr
tests/integration/suite/daprd/state/grpc/basic.go
GO
mit
2,787
/* 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 grpc import ( "context" "fmt" "regexp" "strings" "testing" fuzz "github.com/google/gofuzz" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "k8s.io/apimachinery/pkg/api/validation/path" commonv1 "github.com/dapr/dapr/pkg/proto/common/v1" rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1" "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(componentName)) } type componentName struct { daprd *procdaprd.Daprd storeNames []string } func (c *componentName) Setup(t *testing.T) []framework.Option { const numTests = 1000 takenNames := make(map[string]bool) reg, err := regexp.Compile("^([a-zA-Z].*)$") require.NoError(t, err) fz := fuzz.New().Funcs(func(s *string, c fuzz.Continue) { for *s == "" || takenNames[*s] || len(path.IsValidPathSegmentName(*s)) > 0 || !reg.MatchString(*s) { *s = c.RandString() } takenNames[*s] = true }) c.storeNames = make([]string, numTests) files := make([]string, numTests) for i := 0; i < numTests; i++ { fz.Fuzz(&c.storeNames[i]) files[i] = fmt.Sprintf(` apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: '%s' spec: type: state.in-memory version: v1 `, // Escape single quotes in the store name. strings.ReplaceAll(c.storeNames[i], "'", "''")) } c.daprd = procdaprd.New(t, procdaprd.WithResourceFiles(files...)) return []framework.Option{ framework.WithProcesses(c.daprd), } } func (c *componentName) Run(t *testing.T, ctx context.Context) { c.daprd.WaitUntilRunning(t, ctx) pt := util.NewParallel(t) for _, storeName := range c.storeNames { storeName := storeName pt.Add(func(col *assert.CollectT) { conn, err := grpc.DialContext(ctx, c.daprd.GRPCAddress(), grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock()) require.NoError(col, err) t.Cleanup(func() { require.NoError(t, conn.Close()) }) client := rtv1.NewDaprClient(conn) _, err = client.SaveState(ctx, &rtv1.SaveStateRequest{ StoreName: storeName, States: []*commonv1.StateItem{ {Key: "key1", Value: []byte("value1")}, {Key: "key2", Value: []byte("value2")}, }, }) require.NoError(col, err) _, err = client.SaveState(ctx, &rtv1.SaveStateRequest{ StoreName: storeName, States: []*commonv1.StateItem{ {Key: "key1", Value: []byte("value1")}, {Key: "key2", Value: []byte("value2")}, }, }) require.NoError(col, err) resp, err := client.GetState(ctx, &rtv1.GetStateRequest{ StoreName: storeName, Key: "key1", }) require.NoError(col, err) assert.Equal(col, "value1", string(resp.GetData())) resp, err = client.GetState(ctx, &rtv1.GetStateRequest{ StoreName: storeName, Key: "key2", }) require.NoError(col, err) assert.Equal(col, "value2", string(resp.GetData())) }) } }
mikeee/dapr
tests/integration/suite/daprd/state/grpc/compname.go
GO
mit
3,687