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
|
---|---|---|---|---|---|
# Writing an integration test
## Introduction
Integration tests are run against a live running daprd binary locally. Each test
scenario is run against a new instance of daprd, where each scenario modifies
the daprd configuration to suit the test. Tests are expected to complete within
seconds, ideally less than 5, and should not take longer than 30. Binaries are
always built from source within the test.
You can find out more about the background and design decisions of the integration tests through a talk by joshvanl [here](https://www.youtube.com/watch?v=CcaV5_rQBzY).
## Invoking the test
```bash
go test -v -race -tags integration ./tests/integration
```
You can also run a subset of tests by specifying the `-focus` flag, which takes a [Go regular expression](https://github.com/google/re2/wiki/Syntax).
```bash
# Run all sentry related tests.
go test -v -race -tags integration ./tests/integration -focus sentry
# Run all sentry related tests whilst skipping the sentry jwks validator test.
go test -v -race -tags integration ./tests/integration -test.skip Test_Integration/sentry/validator/jwks -focus sentry
```
Rather than building from source, you can also set a custom daprd, sentry, or placement binary path with the environment variables:
- `DAPR_INTEGRATION_DAPRD_PATH`
- `DAPR_INTEGRATION_PLACEMENT_PATH`
- `DAPR_INTEGRATION_SENTRY_PATH`
By default, binary logs will not be printed unless the test fails. You can force
logs to always be printed with the environment variable
`DAPR_INTEGRATION_LOGS=true`.
You can override the directory that is used to read the CRD definitions that are served by the Kubernetes process with the environment variable `DAPR_INTEGRATION_CRD_DIRECTORY`.
## Adding a new test
To add a new test scenario, either create a new subject directory in
`tests/integration/suite` and create a new file there, or use an existing
subject directory if appropriate. Each test scenario is represented by a
`struct` which implements the following interface. The `struct` name is used as
the test name.
```go
type Case interface {
Setup(*testing.T) []framework.RunDaprdOption
Run(*testing.T, *framework.Command)
}
```
To add the test to the suite, add the following `init` function
```go
func init() {
suite.Register(new(MyNewTestScenario))
}
```
Finally, include your integration test directory with a blank identifier to
`tests/integration/integration.go` so that the init function is invoked.
```go
_ "github.com/dapr/dapr/tests/integration/suite/my-new-test-scenario"
```
You may need to extend the framework options to suit your test scenario. These
are defined in `tests/integration/framework`.
Take a look at `tests/integration/suite/ports/ports.go` as a "hello world"
example to base your test on.
|
mikeee/dapr
|
tests/docs/writing-integration-test.md
|
Markdown
|
mit
| 2,762 |
# Writing a perf test
Before writing a perf test, make sure that you have a configured [local test environment](./running-perf-tests.md) ready to run the perf tests.
## The test target
In order to create a performance test for a given functionality you must ensure that the functionality is testable in some way. There are functionalities that might need an intermediate app to act as the user application, others don't, as an example, an outputbinding may not require an app to be tested, you can make calls to daprd and collect the results. But if you have to test a functionality that requires an application, e.g any actors-related feature, you may need a custom app as well.
Follow the same as described in our [e2e-tests docs](./running-e2e-test.md#writing-e2e-test.md) to create custom test apps, make sure that none of the already created apps would serve as your test app, they can be reusable without further problems.
## Types of testing
Now, its time to decide which is the shape of the load you want to create against the target. The load shape defines not only which is the type of performance test that you'll execute but also the best option to be used as a perf tool as in dapr we currently have two, Fortio and k6.
Read more about the types of performance test and how this relates to the load shape [here](https://en.wikipedia.org/wiki/Software_performance_testing).
Once you have enough knowledge to decide your desired test load shape, let's go through the differences between the tools used internally by dapr to test the performance of our functionalities.
## Fortio
Fortio is a QPS(Query per Second) type of testing which generally is used to create a synthetic load without many nuances on it, the typical case of a stress testing.
From Fortio README:
"Fortio runs at a specified query per second (qps) and records an histogram of execution time and calculates percentiles (e.g. p99 ie the response time such as 99% of the requests take less than that number (in seconds, SI unit)). It can run for a set duration, for a fixed number of calls, or until interrupted (at a constant target QPS, or max speed/load per connection/thread)."
On dapr we have our fortio patched version which is built together with the performance test apps. The fortio app is called `perf-tester` and you'll probably see this name when deploying the test infrastructure.
### Testing with Fortio
Once you have decided that Fortio is the right fit for the tests that you're planning to create, let's go through an example.
All our performance tests live in the `./tests/perf` folder, create a new folder with the name of the test as well a `.go` file, do not forget to add the build tags to make sure that the dapr binary will not include those files
```go
//go:build perf
// +build perf
```
The performance test uses the same infrastructure as [our e2e tests](./running-e2e-test.md), the first thing is to create our `TestMain` which will be responsible for deploying the target apps and wait for those to be healthy.
```go
var tr *runner.TestRunner
func TestMain(m *testing.M) {
utils.SetupLogs("my_test")
serviceApplicationName := "target-app"
clientApplicationName := "fortio-tester"
testApps := []kube.AppDescription{
{
AppName: serviceApplicationName,
DaprEnabled: true,
ImageName: "perf-actorjava",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
AppPort: 3000,
DaprCPULimit: "4.0",
DaprCPURequest: "0.1",
DaprMemoryLimit: "512Mi",
DaprMemoryRequest: "250Mi",
AppCPULimit: "4.0",
AppCPURequest: "0.1",
AppMemoryLimit: "800Mi",
AppMemoryRequest: "2500Mi",
Labels: map[string]string{
"daprtest": serviceApplicationName,
},
},
{
AppName: clientApplicationName,
DaprEnabled: true,
ImageName: "perf-tester",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
AppPort: 3001,
DaprCPULimit: "4.0",
DaprCPURequest: "0.1",
DaprMemoryLimit: "512Mi",
DaprMemoryRequest: "250Mi",
AppCPULimit: "4.0",
AppCPURequest: "0.1",
AppMemoryLimit: "800Mi",
AppMemoryRequest: "2500Mi",
Labels: map[string]string{
"daprtest": clientApplicationName,
},
PodAffinityLabels: map[string]string{
"daprtest": serviceApplicationName,
},
},
}
tr = runner.NewTestRunner("mytest", testApps, nil, nil)
os.Exit(tr.Start(m))
}
```
We'll not go through many details on each field but you can assume that the test main is responsible for deploying at least two apps in that case, the `target-app` and the `fortio-tester`. Now its time to create our test driver, which will issue commands to the fortio tester app that will forward them to the target test app.
The first thing you need to do is to configure the test parameters
```go
func TestActorActivate(t *testing.T) {
p := perf.Params(
perf.WithQPS(500), // the desired Query Per Second
perf.WithConnections(8), // the number of http connections
perf.WithDuration("1m"), // the test duration
perf.WithPayload("{}"), // the test payload
)
}
```
They are essential to make sure you have the right load shape for the functionality you want to test.
The next step is to call the perf tester with the serialized body parameters.
```go
endpoint := "target-app-endpoint"
p.TargetEndpoint = endpoint
p.StdClient = false
body, err := json.Marshal(&p)
daprResp, err := utils.HTTPPost(fmt.Sprintf("%s/test", "fortio-tester-app-endpoint"), body)
```
The last thing we need to do is to collect the results,
```go
var daprResult perf.TestResult
err = json.Unmarshal(daprResp, &daprResult)
```
Then you can do any assertion based on the actual QPS, latency percetiles and others metrics that is collected during the test.
### K6
The main difference between k6 and fortio is because k6 is a scriptable load testing tool, so you can actually write scripts using its DSL, in javascript, and execute them on the cloud managed by the k6 operator. So you can easily create a different types of shapes using the same javascript test file and you can add custom metrics aside from the default ones.
I recommend the following links before starting to work with k6.
- [Executors](https://k6.io/docs/using-k6/scenarios/executors/)
- [Scenarios](https://k6.io/docs/using-k6/scenarios/)
- [Virtual users](https://k6.io/docs/misc/glossary/#virtual-user)
- [Extensions](https://k6.io/docs/extensions/)
- [Metrics](https://k6.io/docs/using-k6/metrics/)
- [Checks](https://k6.io/docs/using-k6/checks/)
- [Thresholds](https://k6.io/docs/using-k6/thresholds/)
### Testing with k6
You can use the full power of k6 on dapr and the only difference is that we kept our test driver as is being used for the QPS with Fortio load testing tool. In addition, the k6 load tester also contains a dapr sidecar container within the same pod. To start a new k6 load test create a simple js file inside the same folder as your test driver `.go` with your desired name (`test.js` is preferable).
The dapr specifities:
For k6 loadtesting on dapr perf test at least two methods are required, they are
- teardown - used to shutdown the dapr sidecar ensuring the job will complete with success.
- handleSummary - used to print the result as a JSON to be consumed later by the test framework
```js
const DAPR_ADDRESS = `http://127.0.0.1:${__ENV.DAPR_HTTP_PORT}/v1.0`; // the dapr env are automatically injected
export function teardown(_) {
const shutdownResult = http.post(`${DAPR_ADDRESS}/shutdown`);
check(shutdownResult, {
"shutdown response status code is 2xx":
shutdownResult.status >= 200 && shutdownResult.status < 300,
});
}
export function handleSummary(data) {
return {
stdout: JSON.stringify(data),
};
}
```
> Warning: The javascript runtime used by k6 is very limited, they uses: https://github.com/dop251/goja, that currently follows ECMAScript 5.1(+), things like spread operation (...) does not work, you can't use npm directly, if you want to, you must bundle your module as a single js file using webpack or other js bundling tool.
In the test driver side there are a range of parameters you can set, from level of parallelism to disable logging. Use parallelism to set the number of pods will be used for the test, keep in mind that the test loadshape will continue the same, including the number of virtual users that are divided by the level of parallelism. So let's say you have a target of 1000 request/s and parallelism is set to 2, so you're going to have two pods issuing 500 requests/s each.
> The k6 pod logs are disabled by default, enabling it would be useful to investigate any running issue that you might have, to do that use `loadtest.EnableLog()` option, this will make the test summary break, and should be removed as soon as the test is being merged to master.
Next step is to create the load tester struct and then ask for the platform to run the test,
the platform.LoadTest(test) will stay busy until the test succeeds so it may take a while depending on your test scenarios.
```go
k6Test := loadtest.NewK6("./test.js", loadtest.WithParallelism(1))
require.NoError(t, tr.Platform.LoadTest(k6Test))
```
Now, it's time to collect the test results,
```go
summary, err := loadtest.K6ResultDefault(k6Test)
```
for each pod used (level of parallelism) there are one struct of metrics, you can access them using the `.RunnerResults` property, your test should fail based on the thresholds so, along with the runner results we also provide a flag `.Pass` which should be used to make assertions.
> When using custom metrics you can use the `loadtet.K6Result[T](k6test)` which provides a signature to Unmarshalling the k6 results on any arbitrary struct that you can provide.
### Add test disruption
Test disruptions can be added using the [xk6-disruptor](https://github.com/grafana/xk6-disruptor/tree/main/examples), you can use the full power of the disruptions.
### Prometheus Metrics
If you set the `K6_PROMETHEUS_REMOTE_URL`, `K6_PROMETHEUS_USER`, and `K6_PROMETHEUS_PASSWORD` environments variable, you should be able to send the k6 metrics to a remote prometheus server which might be helpful to have comparisons over time.
### Troubleshooting
When running k6, the errors are reported as exit codes, use the table below to help identify them.
| Error | Reason |
|-------|--------|
| 255 | Compile Error |
| 137 | OOM (out of memory) |
| 107 | Runtime Error |
|
mikeee/dapr
|
tests/docs/writing-perf-test.md
|
Markdown
|
mit
| 10,560 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package activation
import (
"encoding/json"
"fmt"
"os"
"testing"
"time"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
guuid "github.com/google/uuid"
"github.com/stretchr/testify/require"
)
const (
appName = "actorapp" // App name in Dapr.
numHealthChecks = 60 // Number of get calls before starting tests.
secondsToCheckActorRemainsActive = 1 // How much time to wait to make sure actor is deactivated
secondsToCheckActorDeactivation = 20 // How much time to wait to make sure actor is deactivated
actorInvokeURLFormat = "%s/test/testactor/%s/method/actormethod" // URL to invoke a Dapr's actor method in test app.
actorlogsURLFormat = "%s/test/logs" // URL to fetch logs from test app.
)
// represents a response for the APIs in this app.
type actorLogEntry struct {
Action string `json:"action,omitempty"`
ActorType string `json:"actorType,omitempty"`
ActorID string `json:"actorId,omitempty"`
Timestamp int `json:"timestamp,omitempty"`
}
func parseLogEntries(resp []byte) []actorLogEntry {
logEntries := []actorLogEntry{}
err := json.Unmarshal(resp, &logEntries)
if err != nil {
return nil
}
return logEntries
}
func findActorActivation(resp []byte, actorID string) bool {
return findActorAction(resp, actorID, "activation")
}
func findActorDeactivation(resp []byte, actorID string) bool {
return findActorAction(resp, actorID, "deactivation")
}
func findActorMethodInvokation(resp []byte, actorID string) bool {
return findActorAction(resp, actorID, "actormethod")
}
func findActorAction(resp []byte, actorID string, action string) bool {
logEntries := parseLogEntries(resp)
for _, logEntry := range logEntries {
if (logEntry.ActorID == actorID) && (logEntry.Action == action) {
return true
}
}
return false
}
var tr *runner.TestRunner
func TestMain(m *testing.M) {
utils.SetupLogs("actor_activation")
utils.InitHTTPClient(true)
// These apps will be deployed before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: appName,
DaprEnabled: true,
ImageName: "e2e-actorapp",
DebugLoggingEnabled: true,
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
},
}
tr = runner.NewTestRunner(appName, testApps, nil, nil)
os.Exit(tr.Start(m))
}
func TestActorActivation(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL(appName)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
logsURL := fmt.Sprintf(actorlogsURLFormat, externalURL)
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
// Wait until runtime finds the leader of placements.
time.Sleep(15 * time.Second)
t.Run("Actor deactivates due to timeout.", func(t *testing.T) {
actorID := "100"
invokeURL := fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID)
_, err = utils.HTTPPost(invokeURL, []byte{})
require.NoError(t, err)
fmt.Printf("getting logs, the current time is %s\n", time.Now())
resp, err := utils.HTTPGet(logsURL)
require.NoError(t, err)
// there is no longer an activated message
require.False(t, findActorActivation(resp, actorID))
require.True(t, findActorMethodInvokation(resp, actorID))
require.False(t, findActorDeactivation(resp, actorID))
time.Sleep(secondsToCheckActorDeactivation * time.Second)
fmt.Printf("getting logs, the current time is %s\n", time.Now())
resp, err = utils.HTTPGet(logsURL)
require.NoError(t, err)
// there is no longer an activated message
require.False(t, findActorActivation(resp, actorID))
require.True(t, findActorMethodInvokation(resp, actorID))
require.True(t, findActorDeactivation(resp, actorID))
})
t.Run("Actor does not deactivate since there is no timeout.", func(t *testing.T) {
actorID := guuid.New().String()
invokeURL := fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID)
_, err = utils.HTTPPost(invokeURL, []byte{})
require.NoError(t, err)
resp, err := utils.HTTPGet(logsURL)
require.NoError(t, err)
// there is no longer an activate message
require.False(t, findActorActivation(resp, actorID))
require.True(t, findActorMethodInvokation(resp, actorID))
require.False(t, findActorDeactivation(resp, actorID))
time.Sleep(secondsToCheckActorRemainsActive * time.Second)
resp, err = utils.HTTPGet(logsURL)
require.NoError(t, err)
// there is no longer an activate message
require.False(t, findActorActivation(resp, actorID))
require.True(t, findActorMethodInvokation(resp, actorID))
require.False(t, findActorDeactivation(resp, actorID))
})
}
|
mikeee/dapr
|
tests/e2e/actor_activation/actor_activation_test.go
|
GO
|
mit
| 5,730 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package features
import (
"encoding/json"
"fmt"
"log"
"net/url"
"os"
"strconv"
"testing"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
guuid "github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
appName = "actorfeatures" // App name in Dapr.
reminderName = "myReminder" // Reminder name.
timerName = "myTimer" // Timer name.
numHealthChecks = 60 // Number of get calls before starting tests.
secondsToCheckTimerAndReminderResult = 20 // How much time to wait to make sure the result is in logs.
secondsToCheckGetMetadata = 10 // How much time to wait to check metadata.
secondsBetweenChecksForActorFailover = 5 // How much time to wait to make sure the result is in logs.
minimumCallsForTimerAndReminderResult = 10 // How many calls to timer or reminder should be at minimum.
actorsToCheckRebalance = 10 // How many actors to create in the rebalance check test.
appScaleToCheckRebalance = 2 // How many instances of the app to create to validate rebalance.
actorsToCheckMetadata = 5 // How many actors to create in get metdata test.
appScaleToCheckMetadata = 1 // How many instances of the app to test get metadata.
actorInvokeURLFormat = "%s/test/testactorfeatures/%s/%s/%s" // URL to invoke a Dapr's actor method in test app.
actorDeleteURLFormat = "%s/actors/testactorfeatures/%s" // URL to deactivate an actor in test app.
actorlogsURLFormat = "%s/test/logs" // URL to fetch logs from test app.
actorMetadataURLFormat = "%s/test/metadata" // URL to fetch metadata from test app.
shutdownURLFormat = "%s/test/shutdown" // URL to shutdown sidecar and app.
actorInvokeRetriesAfterRestart = 10 // Number of retried to invoke actor after restart.
)
// represents a response for the APIs in this app.
type actorLogEntry struct {
Action string `json:"action,omitempty"`
ActorType string `json:"actorType,omitempty"`
ActorID string `json:"actorId,omitempty"`
StartTimestamp int `json:"startTimestamp,omitempty"`
EndTimestamp int `json:"endTimestamp,omitempty"`
}
type activeActorsCount struct {
Type string `json:"type"`
Count int `json:"count"`
}
type metadata struct {
ID string `json:"id"`
Actors []activeActorsCount `json:"actors"`
}
type actorReminderOrTimer struct {
Data string `json:"data,omitempty"`
DueTime string `json:"dueTime,omitempty"`
Period string `json:"period,omitempty"`
Callback string `json:"callback,omitempty"`
}
func parseLogEntries(resp []byte) []actorLogEntry {
logEntries := []actorLogEntry{}
err := json.Unmarshal(resp, &logEntries)
if err != nil {
return nil
}
return logEntries
}
func countActorAction(resp []byte, actorID string, action string) int {
count := 0
logEntries := parseLogEntries(resp)
for _, logEntry := range logEntries {
if (logEntry.ActorID == actorID) && (logEntry.Action == action) {
count++
}
}
return count
}
func findActorAction(resp []byte, actorID string, action string) *actorLogEntry {
return findNthActorAction(resp, actorID, action, 1)
}
// findNthActorAction scans the logs and returns the n-th match for the given actorID & method.
func findNthActorAction(resp []byte, actorID string, action string, position int) *actorLogEntry {
skips := position - 1
logEntries := parseLogEntries(resp)
for _, logEntry := range logEntries {
if (logEntry.ActorID == actorID) && (logEntry.Action == action) {
if skips == 0 {
return &logEntry
}
skips--
}
}
return nil
}
var tr *runner.TestRunner
func TestMain(m *testing.M) {
utils.SetupLogs("actor_features")
utils.InitHTTPClient(true)
// These apps will be deployed before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: appName,
DaprEnabled: true,
DebugLoggingEnabled: true,
ImageName: "e2e-actorfeatures",
Config: "omithealthchecksconfig",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
DaprCPULimit: "2.0",
DaprCPURequest: "0.1",
AppCPULimit: "2.0",
AppCPURequest: "0.1",
},
{
AppName: "actortestclient",
DaprEnabled: true,
DebugLoggingEnabled: true,
ImageName: "e2e-actorclientapp",
Config: "omithealthchecksconfig",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
DaprCPULimit: "2.0",
DaprCPURequest: "0.1",
AppCPULimit: "2.0",
AppCPURequest: "0.1",
},
}
tr = runner.NewTestRunner(appName, testApps, nil, nil)
os.Exit(tr.Start(m))
}
func TestActorInvocation(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL("actortestclient")
require.NotEmpty(t, externalURL, "external URL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err, "error while waiting for app actortestclient")
t.Run("Actor remote invocation", func(t *testing.T) {
actorID := guuid.New().String()
res, err := utils.HTTPPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "method", "testmethod"), []byte{})
if err != nil {
log.Printf("failed to invoke method testmethod. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to invoke testmethod")
})
}
func urlWithReqID(str string, a ...interface{}) string {
if len(a) > 0 {
str = fmt.Sprintf(str, a...)
}
str = utils.SanitizeHTTPURL(str)
u, _ := url.Parse(str)
qs := u.Query()
qs.Add("reqid", guuid.New().String())
u.RawQuery = qs.Encode()
return u.String()
}
func httpGet(url string) ([]byte, error) {
url = urlWithReqID(url)
start := time.Now()
res, err := utils.HTTPGet(url)
dur := time.Now().Sub(start)
if err != nil {
log.Printf("GET %s ERROR after %s: %v", url, dur, err)
return nil, err
}
log.Printf("GET %s completed in %s", url, dur)
return res, nil
}
func httpPost(url string, data []byte) ([]byte, error) {
url = urlWithReqID(url)
start := time.Now()
res, err := utils.HTTPPost(url, data)
dur := time.Now().Sub(start)
if err != nil {
log.Printf("POST %s ERROR after %s: %v", url, dur, err)
return nil, err
}
log.Printf("POST %s completed in %s", url, dur)
return res, nil
}
func httpDelete(url string) ([]byte, error) {
url = urlWithReqID(url)
start := time.Now()
res, err := utils.HTTPDelete(url)
dur := time.Now().Sub(start)
if err != nil {
log.Printf("DELETE %s ERROR after %s: %v", url, dur, err)
return nil, err
}
log.Printf("DELETE %s completed in %s", url, dur)
return res, nil
}
func TestActorFeatures(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL(appName)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
logsURL := fmt.Sprintf(actorlogsURLFormat, externalURL)
var err error
var res []byte
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err = utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err, "error while waiting for app "+appName)
t.Run("Actor state.", func(t *testing.T) {
// Each test needs to have a different actorID
actorID := guuid.New().String()
res, err = httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "method", "savestatetest"), []byte{})
if err != nil {
log.Printf("failed to invoke method savestatetest. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to invoke method savestatetest")
res, err = httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "method", "getstatetest"), []byte{})
if err != nil {
log.Printf("failed to invoke method getstatetest. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to invoke method getstatetest")
res, err = httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "method", "savestatetest2"), []byte{})
if err != nil {
log.Printf("failed to invoke method savestatetest2. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to invoke method savestatetest2")
res, err = httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "method", "getstatetest2"), []byte{})
if err != nil {
log.Printf("failed to invoke method getstatetest2. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to invoke method getstatetest2")
})
t.Run("Actor reminder.", func(t *testing.T) {
// Each test needs to have a different actorID
actorID := "1001"
// Reset reminder
res, err = httpDelete(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName))
if err != nil {
log.Printf("failed to reset reminder. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to reset reminder")
// Set reminder
req := actorReminderOrTimer{
Data: "reminderdata",
DueTime: "1s",
Period: "1s",
}
var reqBody []byte
reqBody, err = json.Marshal(req)
require.NoError(t, err, "failed to marshal JSON")
res, err = httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName), reqBody)
if err != nil {
log.Printf("failed to set reminder. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to set reminder")
time.Sleep(secondsToCheckTimerAndReminderResult * time.Second)
// Reset reminder
res, err = httpDelete(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName))
if err != nil {
log.Printf("failed to reset reminder. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to reset reminder")
res, err = httpGet(logsURL)
if err != nil {
log.Printf("failed to get logs. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to get logs")
count := countActorAction(res, actorID, reminderName)
require.True(t, count >= 1, "condition failed: %d not >= 1. Response='%s'", count, string(res))
require.True(t, count >= minimumCallsForTimerAndReminderResult, "condition failed: %d not >= %d. Response='%s'", count, minimumCallsForTimerAndReminderResult, string(res))
})
t.Run("Actor single fire reminder.", func(t *testing.T) {
// Each test needs to have a different actorID
actorID := "1001a"
// Reset reminder
res, err = httpDelete(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName))
if err != nil {
log.Printf("failed to reset reminder. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to reset reminder")
// Set reminder
req := actorReminderOrTimer{
Data: "reminderdata",
DueTime: "1s",
}
reqBody, _ := json.Marshal(req)
res, err = httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName), reqBody)
if err != nil {
log.Printf("failed to set reminder. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to set reminder")
time.Sleep(secondsToCheckTimerAndReminderResult * time.Second)
// Reset reminder
res, err = httpDelete(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName))
if err != nil {
log.Printf("failed to reset reminder. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to reset reminder")
res, err = httpGet(logsURL)
if err != nil {
log.Printf("failed to get logs. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to get logs")
require.True(t, countActorAction(res, actorID, reminderName) == 1, "condition failed")
})
t.Run("Actor reset reminder.", func(t *testing.T) {
// Each test needs to have a different actorID
actorID := "1001b"
// Reset reminder
res, err = httpDelete(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName))
if err != nil {
log.Printf("failed to reset reminder. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to reset reminder")
// Set reminder
req := actorReminderOrTimer{
Data: "reminderdata",
DueTime: "1s",
Period: "5s",
}
reqBody, _ := json.Marshal(req)
res, err = httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName), reqBody)
if err != nil {
log.Printf("failed to set reminder. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to set reminder")
time.Sleep(3 * time.Second)
// Reset reminder (before first period trigger)
req.DueTime = "20s"
reqBody, _ = json.Marshal(req)
res, err = httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName), reqBody)
if err != nil {
log.Printf("failed to reset reminder. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to reset reminder")
time.Sleep(10 * time.Second)
// Delete reminder
res, err = httpDelete(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName))
if err != nil {
log.Printf("failed to delete reminder. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to delete reminder")
res, err = httpGet(logsURL)
if err != nil {
log.Printf("failed to get logs. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to get logs")
require.True(t, countActorAction(res, actorID, reminderName) == 1, "condition failed")
})
t.Run("Actor reminder with deactivate.", func(t *testing.T) {
// Each test needs to have a different actorID
actorID := "1001c"
// Reset reminder
res, err = httpDelete(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName))
if err != nil {
log.Printf("failed to set reminder. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to reset reminder")
// Set reminder
req := actorReminderOrTimer{
Data: "reminderdata",
DueTime: "1s",
Period: "1s",
}
reqBody, _ := json.Marshal(req)
res, err = httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName), reqBody)
if err != nil {
log.Printf("failed to set reminder. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to set reminder")
sleepTime := secondsToCheckTimerAndReminderResult / 2 * time.Second
time.Sleep(sleepTime)
res, err = httpGet(logsURL)
if err != nil {
log.Printf("failed to get logs. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to get logs")
firstCount := countActorAction(res, actorID, reminderName)
// Min call is based off of having a 1s period/due time, the amount of seconds we've waited, and a bit of room for timing.
require.GreaterOrEqual(t, firstCount, 9, "condition failed")
_, _ = httpDelete(fmt.Sprintf(actorDeleteURLFormat, externalURL, actorID))
time.Sleep(sleepTime)
// Reset reminder
_, err = httpDelete(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName))
if err != nil {
log.Printf("failed to reset reminder. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to reset reminder")
res, err = httpGet(logsURL)
if err != nil {
log.Printf("failed to get logs. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to get logs")
require.Greater(t, countActorAction(res, actorID, reminderName), firstCount)
require.GreaterOrEqual(t, countActorAction(res, actorID, reminderName), minimumCallsForTimerAndReminderResult)
})
t.Run("Actor reminder with app restart.", func(t *testing.T) {
// Each test needs to have a different actorID
actorID := "1001d"
// Reset reminder
res, err = httpDelete(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName))
if err != nil {
log.Printf("failed to reset reminder. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to reset reminder")
// Set reminder
req := actorReminderOrTimer{
Data: "reminderdata",
DueTime: "1s",
Period: "1s",
}
reqBody, _ := json.Marshal(req)
res, err = httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName), reqBody)
if err != nil {
log.Printf("failed to set reminder. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to set reminder")
sleepTime := secondsToCheckTimerAndReminderResult / 2 * time.Second
time.Sleep(sleepTime)
res, err = httpGet(logsURL)
if err != nil {
log.Printf("failed to get logs. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to get logs")
firstCount := countActorAction(res, actorID, reminderName)
minFirstCount := 9
// Min call is based off of having a 1s period/due time, the amount of seconds we've waited, and a bit of room for timing.
require.GreaterOrEqual(t, firstCount, minFirstCount)
log.Printf("Restarting %s ...", appName)
err := tr.Platform.Restart(appName)
require.NoError(t, err)
err = backoff.Retry(func() error {
time.Sleep(30 * time.Second)
resp, errb := httpGet(logsURL)
if errb != nil {
return errb
}
count := countActorAction(resp, actorID, reminderName)
if count < minimumCallsForTimerAndReminderResult {
return fmt.Errorf("Not enough reminder calls: %d vs %d", count, minimumCallsForTimerAndReminderResult)
}
return nil
}, backoff.WithMaxRetries(backoff.NewExponentialBackOff(), 10))
require.NoError(t, err)
// Reset reminder
res, err = httpDelete(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName))
if err != nil {
log.Printf("failed to reset reminder. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to reset reminder")
})
t.Run("Actor reminder delete self.", func(t *testing.T) {
// Each test needs to have a different actorID
actorID := "1001e"
// Reset reminder
res, err = httpDelete(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName))
if err != nil {
log.Printf("failed to reset reminder. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to reset reminder")
// Set reminder
req := actorReminderOrTimer{
Data: "reminderdata",
DueTime: "1s",
Period: "1s",
}
var reqBody []byte
reqBody, err = json.Marshal(req)
require.NoError(t, err, "failed to marshal JSON")
res, err = httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName), reqBody)
if err != nil {
log.Printf("failed to set reminder. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to set reminder")
time.Sleep(secondsToCheckTimerAndReminderResult * time.Second)
// get reminder
res, err = httpGet(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName))
if err != nil {
log.Printf("failed to get reminder. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to get reminder")
require.True(t, len(res) == 0, "Reminder %s exist", reminderName)
res, err = httpGet(logsURL)
if err != nil {
log.Printf("failed to get logs. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to get logs")
count := countActorAction(res, actorID, reminderName)
require.True(t, count == 1, "condition failed: %d not == 1. Response='%s'", count, string(res))
})
t.Run("Actor timer.", func(t *testing.T) {
// Each test needs to have a different actorID
actorID := "1002"
// Activate actor.
res, err := httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "method", "justToActivate"), []byte{})
if err != nil {
log.Printf("warn: failed to activate actor. Error='%v' Response='%s'", err, string(res))
}
// Reset timer
res, err = httpDelete(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "timers", timerName))
if err != nil {
log.Printf("failed to reset timer. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to reset timer")
// Set timer
req := actorReminderOrTimer{
Data: "timerdata",
DueTime: "1s",
Period: "1s",
}
reqBody, _ := json.Marshal(req)
res, err = httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "timers", timerName), reqBody)
if err != nil {
log.Printf("failed to set timer. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to set timer")
time.Sleep(secondsToCheckTimerAndReminderResult * time.Second)
// Reset timer
_, err = httpDelete(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "timers", timerName))
require.NoError(t, err)
res, err = httpGet(logsURL)
if err != nil {
log.Printf("failed to get logs. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to get logs")
require.True(t, countActorAction(res, actorID, timerName) >= 1)
require.True(t, countActorAction(res, actorID, timerName) >= minimumCallsForTimerAndReminderResult)
})
t.Run("Actor reset timer.", func(t *testing.T) {
// Each test needs to have a different actorID
actorID := "1002a"
// Activate actor.
httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "method", "justToActivate"), []byte{})
// Reset timer
_, err = httpDelete(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "timers", timerName))
require.NoError(t, err)
// Set timer
req := actorReminderOrTimer{
Data: "timerdata",
DueTime: "1s",
Period: "5s",
}
reqBody, _ := json.Marshal(req)
_, err = httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "timers", timerName), reqBody)
require.NoError(t, err)
time.Sleep(3 * time.Second)
// Reset timer (before first period trigger)
req.DueTime = "20s"
reqBody, _ = json.Marshal(req)
_, err = httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "timers", timerName), reqBody)
time.Sleep(10 * time.Second)
// Delete timer
_, err = httpDelete(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "timers", timerName))
require.NoError(t, err)
res, err = httpGet(logsURL)
if err != nil {
log.Printf("failed to get logs. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to get logs")
require.Equal(t, 1, countActorAction(res, actorID, timerName))
})
t.Run("Actor concurrency same actor id.", func(t *testing.T) {
// Each test needs to have a different actorID
actorID := "1003"
// Invoke method call in Actor.
err1 := make(chan error, 1)
err2 := make(chan error, 1)
go func() {
_, err := httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "method", "concurrency"), []byte{})
err1 <- err
}()
go func() {
_, err := httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "method", "concurrency"), []byte{})
err2 <- err
}()
require.NoError(t, <-err1)
require.NoError(t, <-err2)
res, err = httpGet(logsURL)
if err != nil {
log.Printf("failed to get logs. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to get logs")
logOne := findNthActorAction(res, actorID, "concurrency", 1)
logTwo := findNthActorAction(res, actorID, "concurrency", 2)
require.NotNil(t, logOne)
require.NotNil(t, logTwo)
require.True(t, (logOne.StartTimestamp < logOne.EndTimestamp)) // Sanity check on the app response.
require.True(t, (logTwo.StartTimestamp < logTwo.EndTimestamp)) // Sanity check on the app response.
startEndTimeCheck := (logOne.StartTimestamp >= logTwo.EndTimestamp) || (logTwo.StartTimestamp >= logOne.EndTimestamp)
if !startEndTimeCheck {
log.Printf("failed for start/end time check: logOne.StartTimestamp='%d' logOne.EndTimestamp='%d' logTwo.StartTimestamp='%d' logTwo.EndTimestamp='%d'",
logOne.StartTimestamp, logOne.EndTimestamp, logTwo.StartTimestamp, logTwo.EndTimestamp)
}
require.True(t, startEndTimeCheck)
})
t.Run("Actor concurrency different actor ids.", func(t *testing.T) {
// Each test needs to have a different actorID
actorIDOne := "1004a"
actorIDTwo := "1004b"
// Invoke method call in Actors.
err1 := make(chan error, 1)
err2 := make(chan error, 1)
defer close(err1)
defer close(err2)
go func() {
_, err := httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorIDOne, "method", "concurrency"), []byte{})
err1 <- err
}()
go func() {
_, err := httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorIDTwo, "method", "concurrency"), []byte{})
err2 <- err
}()
require.NoError(t, <-err1, "error in equest 1")
require.NoError(t, <-err2, "error in request 2")
res, err = httpGet(logsURL)
if err != nil {
log.Printf("failed to get logs. Error='%v' Response='%s'", err, string(res))
}
require.NoError(t, err, "failed to get logs")
logOne := findActorAction(res, actorIDOne, "concurrency")
logTwo := findActorAction(res, actorIDTwo, "concurrency")
require.NotNil(t, logOne, "logOne is nil")
require.NotNil(t, logTwo, "logTwo is nil")
require.True(t, (logOne.StartTimestamp < logOne.EndTimestamp)) // Sanity check on the app response.
require.True(t, (logTwo.StartTimestamp < logTwo.EndTimestamp)) // Sanity check on the app response.
// Both methods run in parallel, with the sleep time both should start before the other ends.
startEndTimeCheck := (logOne.StartTimestamp <= logTwo.EndTimestamp) && (logTwo.StartTimestamp <= logOne.EndTimestamp)
if !startEndTimeCheck {
log.Printf("failed for start/end time check: logOne.StartTimestamp='%d' logOne.EndTimestamp='%d' logTwo.StartTimestamp='%d' logTwo.EndTimestamp='%d'",
logOne.StartTimestamp, logOne.EndTimestamp, logTwo.StartTimestamp, logTwo.EndTimestamp)
}
require.True(t, startEndTimeCheck)
})
t.Run("Actor fails over to another hostname.", func(t *testing.T) {
// Each test needs to have a different actorID
actorID := "1005"
quit := make(chan struct{})
go func() {
// Keep the actor alive
timer := time.NewTimer(secondsBetweenChecksForActorFailover * time.Second)
defer timer.Stop()
for {
select {
case <-quit:
return
case <-timer.C:
// Ignore errors as this is just to keep the actor alive
_, _ = httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "method", "hostname"), []byte{})
}
}
}()
// In Kubernetes, hostname should be the POD name. Single-node Kubernetes cluster should still be able to reproduce this test.
firstHostname, err := httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "method", "hostname"), []byte{})
require.NoError(t, err, "error getting first hostname")
tr.Platform.Restart(appName)
newHostname := []byte{}
for i := 0; i <= actorInvokeRetriesAfterRestart; i++ {
// wait until actors are redistributed.
time.Sleep(30 * time.Second)
newHostname, err = httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "method", "hostname"), []byte{})
if i == actorInvokeRetriesAfterRestart {
require.NoError(t, err, "error getting hostname")
}
if err == nil {
break
}
}
require.NotEqual(t, string(firstHostname), string(newHostname))
close(quit)
})
t.Run("Actor rebalance to another hostname.", func(t *testing.T) {
// Each test needs to have a different actorID
actorIDBase := "1006Instance"
var hostnameForActor [actorsToCheckRebalance]string
// In Kubernetes, hostname should be the POD name.
// Records all hostnames from pods and compare them with the hostnames from new pods after scaling
for index := 0; index < actorsToCheckRebalance; index++ {
hostname, err := httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorIDBase+strconv.Itoa(index), "method", "hostname"), []byte{})
require.NoError(t, err)
hostnameForActor[index] = string(hostname)
}
tr.Platform.Scale(appName, appScaleToCheckRebalance)
// wait until actors are redistributed.
time.Sleep(30 * time.Second)
anyActorMoved := false
for index := 0; index < actorsToCheckRebalance; index++ {
hostname, err := httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorIDBase+strconv.Itoa(index), "method", "hostname"), []byte{})
require.NoError(t, err, "error getting hostname for actor %d", index)
if hostnameForActor[index] != string(hostname) {
anyActorMoved = true
}
}
require.True(t, anyActorMoved, "no actor moved")
})
t.Run("Get actor metadata", func(t *testing.T) {
tr.Platform.Scale(appName, appScaleToCheckMetadata)
time.Sleep(secondsToCheckGetMetadata * time.Second)
res, err = httpGet(fmt.Sprintf(actorMetadataURLFormat, externalURL))
log.Printf("Got metadata: Error='%v' Response='%s'", err, string(res))
require.NoError(t, err, "failed to get metadata")
var previousMetadata metadata
err = json.Unmarshal(res, &previousMetadata)
require.NoError(t, err, "error marshalling to JSON")
require.NotNil(t, previousMetadata, "previousMetadata object is nil")
// Each test needs to have a different actorID
actorIDBase := "1008Instance"
for index := 0; index < actorsToCheckMetadata; index++ {
res, err = httpPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorIDBase+strconv.Itoa(index), "method", "hostname"), []byte{})
if err != nil {
log.Printf("failed to check metadata for actor %d. Error='%v' Response='%s'", index, err, string(res))
}
require.NoError(t, err, "failed to check metadata for actor %d", index)
}
// Add delay to make the test robust.
time.Sleep(5 * time.Second)
res, err = httpGet(fmt.Sprintf(actorMetadataURLFormat, externalURL))
log.Printf("Got metadata: Error='%v' Response='%s'", err, string(res))
require.NoError(t, err, "failed to get metadata")
var currentMetadata metadata
err = json.Unmarshal(res, ¤tMetadata)
require.NoError(t, err, "error unmarshalling JSON")
assert.NotNil(t, currentMetadata, "metadata object is nil")
assert.Equal(t, appName, currentMetadata.ID)
assert.Equal(t, appName, previousMetadata.ID)
assert.Greater(t, len(previousMetadata.Actors), 0)
assert.Greater(t, len(currentMetadata.Actors), 0)
assert.Equal(t, "testactorfeatures", currentMetadata.Actors[0].Type)
assert.Equal(t, "testactorfeatures", previousMetadata.Actors[0].Type)
assert.Greater(t, currentMetadata.Actors[0].Count, previousMetadata.Actors[0].Count)
})
}
|
mikeee/dapr
|
tests/e2e/actor_features/actor_features_test.go
|
GO
|
mit
| 32,303 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package actor_invocation_e2e
import (
"encoding/json"
"fmt"
"os"
"strconv"
"testing"
"time"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
appName = "actorinvocationapp" // App name in Dapr.
callActorURL = "%s/test/callActorMethod" // URL to force Actor registration
)
type actorCallRequest struct {
ActorType string `json:"actorType"`
ActorID string `json:"actorId"`
Method string `json:"method"`
RemoteActorID string `json:"remoteId,omitempty"`
RemoteActorType string `json:"remoteType,omitempty"`
}
var tr *runner.TestRunner
func TestMain(m *testing.M) {
utils.SetupLogs("actor_invocation")
utils.InitHTTPClient(true)
// This test can be run outside of Kubernetes too
// Run the actorinvocationapp e2e apps using, for example, the Dapr CLI:
// PORT=3001 dapr run --app-id actor1 --resources-path ./resources --app-port 3001 -- go run .
// PORT=3002 dapr run --app-id actor2 --resources-path ./resources --app-port 3002 -- go run .
// Then run this test with the env var "APP1_ENDPOINT" and "APP2_ENDPOINT" pointing to the addresses of the apps. For example:
// APP1_ENDPOINT="http://localhost:3001" APP2_ENDPOINT="http://localhost:3002" DAPR_E2E_TEST="actor_invocation" make test-clean test-e2e-all |& tee test.log
if os.Getenv("APP1_ENDPOINT") == "" && os.Getenv("APP2_ENDPOINT") == "" {
testApps := []kube.AppDescription{
{
AppName: "actor1",
DaprEnabled: true,
ImageName: "e2e-actorinvocationapp",
DebugLoggingEnabled: true,
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
AppEnv: map[string]string{
"TEST_APP_ACTOR_TYPES": "actor1,actor2,resiliencyInvokeActor",
},
},
{
AppName: "actor2",
DaprEnabled: true,
ImageName: "e2e-actorinvocationapp",
DebugLoggingEnabled: true,
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
AppEnv: map[string]string{
"TEST_APP_ACTOR_TYPES": "actor1,actor2",
},
},
}
tr = runner.NewTestRunner(appName, testApps, nil, nil)
os.Exit(tr.Start(m))
} else {
os.Exit(m.Run())
}
}
func getAppEndpoint(t *testing.T, num int) string {
s := strconv.Itoa(num)
if env := os.Getenv("APP" + s + "_ENDPOINT"); env != "" {
return env
}
u := tr.Platform.AcquireAppExternalURL("actor" + s)
require.NotEmptyf(t, u, "external URL for actor%d must not be empty", num)
return u
}
func TestActorInvocation(t *testing.T) {
firstActorURL := getAppEndpoint(t, 1)
secondActorURL := getAppEndpoint(t, 2)
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
require.NoError(t, utils.HealthCheckApps(firstActorURL, secondActorURL))
// This basic test is already covered in actor_feature_tests but serves as a sanity check here to ensure apps are up and the actor subsystem is ready.
t.Run("Actor remote invocation", func(t *testing.T) {
body, _ := json.Marshal(actorCallRequest{
ActorType: "actor1",
ActorID: "10",
Method: "logCall",
})
require.EventuallyWithT(t, func(t *assert.CollectT) {
_, status, err := utils.HTTPPostWithStatus(fmt.Sprintf(callActorURL, firstActorURL), body)
require.NoError(t, err)
assert.Equal(t, 200, status)
}, 15*time.Second, 200*time.Millisecond)
body, _ = json.Marshal(actorCallRequest{
ActorType: "actor2",
ActorID: "20",
Method: "logCall",
})
require.EventuallyWithT(t, func(t *assert.CollectT) {
_, status, err := utils.HTTPPostWithStatus(fmt.Sprintf(callActorURL, secondActorURL), body)
require.NoError(t, err)
assert.Equal(t, 200, status)
}, 15*time.Second, 200*time.Millisecond)
})
// Validates special error handling for actors is working in runtime (.NET SDK case).
t.Run("Actor local invocation with X-DaprErrorResponseHeader + Resiliency", func(t *testing.T) {
request := actorCallRequest{
ActorType: "resiliencyInvokeActor",
ActorID: "981",
Method: "xDaprErrorResponseHeader",
}
body, _ := json.Marshal(request)
resp, status, err := utils.HTTPPostWithStatus(fmt.Sprintf(callActorURL, firstActorURL), body)
require.NoError(t, err)
assert.Equal(t, 200, status)
assert.Equal(t,
"x-DaprErrorResponseHeader call with - actorType: resiliencyInvokeActor, actorId: 981",
string(resp))
})
// Validates special error handling for actors is working in runtime (.NET SDK case).
t.Run("Actor remote invocation with X-DaprErrorResponseHeader + Resiliency", func(t *testing.T) {
request := actorCallRequest{
ActorType: "resiliencyInvokeActor",
ActorID: "789",
Method: "xDaprErrorResponseHeader",
}
body, _ := json.Marshal(request)
resp, status, err := utils.HTTPPostWithStatus(fmt.Sprintf(callActorURL, secondActorURL), body)
require.NoError(t, err)
assert.Equal(t, 200, status)
assert.Equal(t,
"x-DaprErrorResponseHeader call with - actorType: resiliencyInvokeActor, actorId: 789",
string(resp))
})
t.Run("Actor cross actor call (same pod)", func(t *testing.T) {
// Register the 2nd actor on the same pod.
request := actorCallRequest{
ActorType: "actor1",
ActorID: "11",
Method: "logCall",
}
body, _ := json.Marshal(request)
_, status, err := utils.HTTPPostWithStatus(fmt.Sprintf(callActorURL, firstActorURL), body)
require.NoError(t, err)
require.Equal(t, 200, status)
request = actorCallRequest{
ActorType: "actor1",
ActorID: "10",
Method: "callDifferentActor",
RemoteActorID: "11",
RemoteActorType: "actor1",
}
body, _ = json.Marshal(request)
_, status, err = utils.HTTPPostWithStatus(fmt.Sprintf(callActorURL, firstActorURL), body)
require.NoError(t, err)
require.Equal(t, 200, status)
})
t.Run("Actor cross actor call (diff pod)", func(t *testing.T) {
// Register the 2nd actor on a different pod.
request := actorCallRequest{
ActorType: "actor2",
ActorID: "21",
Method: "logCall",
}
body, _ := json.Marshal(request)
_, status, err := utils.HTTPPostWithStatus(fmt.Sprintf(callActorURL, secondActorURL), body)
require.NoError(t, err)
require.Equal(t, 200, status)
request = actorCallRequest{
ActorType: "actor1",
ActorID: "10",
Method: "callDifferentActor",
RemoteActorID: "21",
RemoteActorType: "actor2",
}
body, _ = json.Marshal(request)
_, status, err = utils.HTTPPostWithStatus(fmt.Sprintf(callActorURL, firstActorURL), body)
require.NoError(t, err)
require.Equal(t, 200, status)
})
}
func TestActorNegativeInvocation(t *testing.T) {
firstActorURL := getAppEndpoint(t, 1)
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
require.NoError(t, utils.HealthCheckApps(firstActorURL))
t.Run("Try actor call with non-bound method", func(t *testing.T) {
request := actorCallRequest{
ActorType: "actor1",
ActorID: "10",
Method: "notAMethod",
}
body, _ := json.Marshal(request)
resp, status, err := utils.HTTPPostWithStatus(fmt.Sprintf(callActorURL, firstActorURL), body)
require.NoError(t, err)
require.NotNil(t, resp)
require.Equal(t, 500, status)
})
t.Run("Try actor call with non-registered actor type", func(t *testing.T) {
request := actorCallRequest{
ActorType: "notAType",
ActorID: "10",
Method: "logCall",
}
body, _ := json.Marshal(request)
_, err := utils.HTTPPost(fmt.Sprintf(callActorURL, firstActorURL), body)
require.NoError(t, err)
})
}
|
mikeee/dapr
|
tests/e2e/actor_invocation/actor_invocation_test.go
|
GO
|
mit
| 8,428 |
//go:build e2e
// +build e2e
/*
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 actor_metadata_e2e
import (
"encoding/json"
"fmt"
"log"
"os"
"strconv"
"testing"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
"github.com/stretchr/testify/require"
)
const (
testRunnerName = "actormetadata" // Name of the test runner.
appNameOne = "actormetadata-a" // App name in Dapr.
appNameTwo = "actormetadata-b" // App name in Dapr.
reminderName = "myreminder" // Reminder name
numHealthChecks = 60 // Number of get calls before starting tests.
numActors = 100 // Number of get calls before starting tests.
secondsToCheckReminderResult = 45 // How much time to wait to make sure the result is in logs.
maxNumPartitions = 6 // Maximum number of partitions.
actorName = "testactormetadata" // Actor name
actorInvokeURLFormat = "%s/test/" + actorName + "/%s/%s/%s" // URL to invoke a Dapr's actor method in test app.
actorlogsURLFormat = "%s/test/logs" // URL to fetch logs from test app.
envURLFormat = "%s/test/env/%s" // URL to fetch or set env var from test app.
shutdownSidecarURLFormat = "%s/test/shutdownsidecar" // URL to shutdown sidecar only.
)
// represents a response for the APIs in this app.
type actorLogEntry struct {
Action string `json:"action,omitempty"`
ActorType string `json:"actorType,omitempty"`
ActorID string `json:"actorId,omitempty"`
StartTimestamp int `json:"startTimestamp,omitempty"`
EndTimestamp int `json:"endTimestamp,omitempty"`
}
type actorReminder struct {
Data string `json:"data,omitempty"`
DueTime string `json:"dueTime,omitempty"`
Period string `json:"period,omitempty"`
TTL string `json:"ttl,omitempty"`
Callback string `json:"callback,omitempty"`
}
type reminderResponse struct {
ActorID string `json:"actorID,omitempty"`
ActorType string `json:"actorType,omitempty"`
Name string `json:"name,omitempty"`
Data any `json:"data"`
Period string `json:"period"`
DueTime string `json:"dueTime"`
RegisteredTime string `json:"registeredTime,omitempty"`
ExpirationTime string `json:"expirationTime,omitempty"`
}
func parseLogEntries(resp []byte) []actorLogEntry {
logEntries := []actorLogEntry{}
err := json.Unmarshal(resp, &logEntries)
if err != nil {
return nil
}
return logEntries
}
func countActorAction(resp []byte, actorID string, action string) int {
count := 0
logEntries := parseLogEntries(resp)
for _, logEntry := range logEntries {
if (logEntry.ActorID == actorID) && (logEntry.Action == action) {
count++
}
}
return count
}
var tr *runner.TestRunner
func TestMain(m *testing.M) {
utils.SetupLogs("actor_metadata")
utils.InitHTTPClient(false)
// These apps will be deployed before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: appNameOne,
DaprEnabled: true,
ImageName: "e2e-actorfeatures",
Replicas: 1,
IngressEnabled: true,
Config: "omithealthchecksconfig",
DebugLoggingEnabled: true,
DaprCPULimit: "2.0",
DaprCPURequest: "0.1",
AppCPULimit: "2.0",
AppCPURequest: "0.1",
AppEnv: map[string]string{
"TEST_APP_ACTOR_REMINDERS_PARTITIONS": "0",
"TEST_APP_ACTOR_TYPE": actorName,
},
},
{
AppName: appNameTwo,
DaprEnabled: true,
ImageName: "e2e-actorfeatures",
Replicas: 1,
IngressEnabled: true,
Config: "omithealthchecksconfig",
DebugLoggingEnabled: true,
DaprCPULimit: "2.0",
DaprCPURequest: "0.1",
AppCPULimit: "2.0",
AppCPURequest: "0.1",
AppEnv: map[string]string{
"TEST_APP_ACTOR_REMINDERS_PARTITIONS": "0",
"TEST_APP_ACTOR_TYPE": actorName,
},
},
}
tr = runner.NewTestRunner(testRunnerName, testApps, nil, nil)
os.Exit(tr.Start(m))
}
func TestActorMetadataEtagRace(t *testing.T) {
externalURLOne := tr.Platform.AcquireAppExternalURL(appNameOne)
require.NotEmpty(t, externalURLOne, "external URL #1 must not be empty!")
externalURLTwo := tr.Platform.AcquireAppExternalURL(appNameTwo)
require.NotEmpty(t, externalURLTwo, "external URL #2 must not be empty!")
logsURLOne := fmt.Sprintf(actorlogsURLFormat, externalURLOne)
logsURLTwo := fmt.Sprintf(actorlogsURLFormat, externalURLTwo)
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
t.Log("Checking if apps are healthy")
err := utils.HealthCheckApps(externalURLOne, externalURLTwo)
require.NoError(t, err, "Health checks failed")
// Set reminder
reminder := actorReminder{
Data: "reminderdata",
DueTime: "1s",
Period: "1s",
}
reminderBody, err := json.Marshal(reminder)
require.NoError(t, err)
t.Run("Triggers rebalance of reminders multiple times to validate eTag race on metadata record", func(t *testing.T) {
for actorIDint := 0; actorIDint < numActors; actorIDint++ {
actorID := strconv.Itoa(actorIDint)
t.Logf("Registering reminder: %s %s ...", actorID, reminderName)
// Deleting pre-existing reminder, just in case…
_, err = utils.HTTPDelete(fmt.Sprintf(actorInvokeURLFormat, externalURLOne, actorID, "reminders", reminderName))
require.NoError(t, err)
// Registering reminder
_, err = utils.HTTPPost(fmt.Sprintf(actorInvokeURLFormat, externalURLOne, actorID, "reminders", reminderName), reminderBody)
require.NoError(t, err)
}
for newPartitionCount := 2; newPartitionCount <= maxNumPartitions; newPartitionCount++ {
npc := strconv.Itoa(newPartitionCount)
// The added querystrings serve no purpose besides acting as bookmark in logs
qs := "?partitionCount=" + npc
_, err = utils.HTTPPost(
fmt.Sprintf(envURLFormat, externalURLOne, "TEST_APP_ACTOR_REMINDERS_PARTITIONS")+qs,
[]byte(npc))
require.NoError(t, err)
_, err = utils.HTTPPost(
fmt.Sprintf(envURLFormat, externalURLTwo, "TEST_APP_ACTOR_REMINDERS_PARTITIONS")+qs,
[]byte(npc))
require.NoError(t, err)
// Shutdown the sidecar to load the new partition config
_, err = utils.HTTPPost(fmt.Sprintf(shutdownSidecarURLFormat, externalURLOne)+qs, nil)
require.NoError(t, err)
_, err = utils.HTTPPost(fmt.Sprintf(shutdownSidecarURLFormat, externalURLTwo)+qs, nil)
require.NoError(t, err)
// Reset logs
_, err = utils.HTTPDelete(logsURLOne + qs)
require.NoError(t, err)
_, err = utils.HTTPDelete(logsURLTwo + qs)
require.NoError(t, err)
log.Printf("Waiting for sidecars %s & %s to restart ...", appNameOne, appNameTwo)
t.Logf("Sleeping for %d seconds ...", secondsToCheckReminderResult)
time.Sleep(secondsToCheckReminderResult * time.Second)
// Define the backoff strategy
bo := backoff.NewExponentialBackOff()
bo.InitialInterval = 1 * time.Second
const maxRetries = 20
err = backoff.RetryNotify(
func() error {
rerr := utils.HealthCheckApps(externalURLOne, externalURLTwo)
if rerr != nil {
return rerr
}
t.Logf("Getting logs from %s to see if reminders did trigger ...", logsURLOne)
respOne, rerr := utils.HTTPGet(logsURLOne + qs)
if rerr != nil {
return rerr
}
t.Logf("Getting logs from %s to see if reminders did trigger ...", logsURLTwo)
respTwo, rerr := utils.HTTPGet(logsURLTwo + qs)
if rerr != nil {
return rerr
}
t.Logf("Checking if all reminders did trigger with partition count as %d ...", newPartitionCount)
// Errors below should NOT be considered flakyness and must be investigated.
// If there was no other error until now, there should be reminders triggered.
for actorIDint := 0; actorIDint < numActors; actorIDint++ {
actorID := strconv.Itoa(actorIDint)
count := countActorAction(respOne, actorID, reminderName)
count += countActorAction(respTwo, actorID, reminderName)
// Due to possible load stress, we do not expect all reminders to be called at the same frequency.
// There are other E2E tests that validate the correct frequency of reminders in a happy path.
if count == 0 {
return fmt.Errorf("Reminder %s for Actor %s was invoked %d times with partion count as %d.",
reminderName, actorID, count, newPartitionCount)
}
}
t.Logf("All reminders triggerred with partition count as %d!", newPartitionCount)
return nil
},
backoff.WithMaxRetries(bo, maxRetries),
func(err error, d time.Duration) {
log.Printf("Error while invoking actor: '%v' - retrying in %s", err, d)
},
)
require.NoError(t, err)
}
for actorIDint := 0; actorIDint < numActors; actorIDint++ {
_, err := utils.HTTPGetNTimes(externalURLOne, numHealthChecks)
require.NoError(t, err)
actorID := strconv.Itoa(actorIDint)
// Unregistering reminder
t.Logf("Unregistering reminder: %s %s ...", actorID, reminderName)
_, err = utils.HTTPDelete(fmt.Sprintf(actorInvokeURLFormat, externalURLOne, actorID, "reminders", reminderName))
require.NoError(t, err)
}
t.Log("Done.")
})
}
|
mikeee/dapr
|
tests/e2e/actor_metadata/actor_metadata_test.go
|
GO
|
mit
| 10,340 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package reentrancy
import (
"encoding/json"
"fmt"
"os"
"testing"
"time"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
appName = "reentrantactor" // App name in Dapr.
actorInvokeURLFormat = "%s/test/actors/reentrantActor/%s/%s/%s" // URL to invoke a Dapr's actor method in test app.
actorlogsURLFormat = "%s/test/logs" // URL to fetch logs from test app.
)
// represents a response for the APIs in this app.
type actorLogEntry struct {
Action string `json:"action,omitempty"`
ActorType string `json:"actorType,omitempty"`
ActorID string `json:"actorId,omitempty"`
StartTimestamp int `json:"startTimestamp,omitempty"`
EndTimestamp int `json:"endTimestamp,omitempty"`
}
type reentrantRequest struct {
Calls []actorCall `json:"calls,omitempty"`
}
type actorCall struct {
ActorID string `json:"id"`
ActorType string `json:"type"`
Method string `json:"method"`
}
func parseLogEntries(resp []byte) []actorLogEntry {
logEntries := []actorLogEntry{}
err := json.Unmarshal(resp, &logEntries)
if err != nil {
return nil
}
return logEntries
}
var tr *runner.TestRunner
func TestMain(m *testing.M) {
utils.SetupLogs("actor_reentrancy")
utils.InitHTTPClient(true)
// This test can be run outside of Kubernetes too
// Run the actorreentrancy e2e app using, for example, the Dapr CLI:
// PORT=22222 dapr run --app-id reentrantactor --resources-path ./resources --app-port 22222 -- go run .
// Then run this test with the env var "APP_ENDPOINT" pointing to the address of the app. For example:
// APP_ENDPOINT="http://localhost:22222" DAPR_E2E_TEST="actor_reentrancy" make test-clean test-e2e-all |& tee test.log
if os.Getenv("APP_ENDPOINT") == "" {
testApps := []kube.AppDescription{
{
AppName: appName,
DaprEnabled: true,
DebugLoggingEnabled: true,
ImageName: "e2e-actorreentrancy",
Config: "omithealthchecksconfig",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
DaprCPULimit: "2.0",
DaprCPURequest: "0.1",
AppCPULimit: "2.0",
AppCPURequest: "0.1",
AppPort: 22222,
},
}
tr = runner.NewTestRunner(appName, testApps, nil, nil)
os.Exit(tr.Start(m))
} else {
os.Exit(m.Run())
}
}
func getAppEndpoint(t *testing.T) string {
if env := os.Getenv("APP_ENDPOINT"); env != "" {
return env
}
u := tr.Platform.AcquireAppExternalURL(appName)
require.NotEmpty(t, u, "external URL for for app must not be empty")
return u
}
func TestActorReentrancy(t *testing.T) {
reentrantURL := getAppEndpoint(t)
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
require.NoError(t, utils.HealthCheckApps(reentrantURL))
const (
firstActorID = "1"
secondActorID = "2"
actorType = "reentrantActor"
)
logsURL := fmt.Sprintf(actorlogsURLFormat, reentrantURL)
// This basic test makes it possible to assert that the actor subsystem is ready
t.Run("Readiness", func(t *testing.T) {
body, _ := json.Marshal(actorCall{
ActorType: "actor1",
ActorID: "hi",
Method: "helloMethod",
})
require.EventuallyWithT(t, func(t *assert.CollectT) {
_, status, err := utils.HTTPPostWithStatus(fmt.Sprintf(actorInvokeURLFormat, reentrantURL, "hi", "method", "helloMethod"), body)
require.NoError(t, err)
assert.Equal(t, 200, status)
}, 15*time.Second, 200*time.Millisecond)
})
t.Run("Same Actor Reentrancy", func(t *testing.T) {
utils.HTTPDelete(logsURL)
req := reentrantRequest{
Calls: []actorCall{
{ActorID: firstActorID, ActorType: actorType, Method: "reentrantMethod"},
{ActorID: firstActorID, ActorType: actorType, Method: "standardMethod"},
},
}
reqBody, _ := json.Marshal(req)
_, err := utils.HTTPPost(fmt.Sprintf(actorInvokeURLFormat, reentrantURL, firstActorID, "method", "reentrantMethod"), reqBody)
require.NoError(t, err)
resp, httpErr := utils.HTTPGet(logsURL)
require.NoError(t, httpErr)
require.NotNil(t, resp)
logs := parseLogEntries(resp)
require.Lenf(t, logs, len(req.Calls)*2, "Logs: %v", logs)
index := 0
for i := 0; i < len(req.Calls); i++ {
require.Equal(t, fmt.Sprintf("Enter %s", req.Calls[i].Method), logs[index].Action)
require.Equal(t, req.Calls[i].ActorID, logs[index].ActorID)
require.Equal(t, req.Calls[i].ActorType, logs[index].ActorType)
index++
}
for i := len(req.Calls) - 1; i > -1; i-- {
require.Equal(t, fmt.Sprintf("Exit %s", req.Calls[i].Method), logs[index].Action)
require.Equal(t, req.Calls[i].ActorID, logs[index].ActorID)
require.Equal(t, req.Calls[i].ActorType, logs[index].ActorType)
index++
}
})
t.Run("Multi-actor Reentrancy", func(t *testing.T) {
utils.HTTPDelete(logsURL)
req := reentrantRequest{
Calls: []actorCall{
{ActorID: firstActorID, ActorType: actorType, Method: "reentrantMethod"},
{ActorID: secondActorID, ActorType: actorType, Method: "reentrantMethod"},
{ActorID: firstActorID, ActorType: actorType, Method: "standardMethod"},
},
}
reqBody, _ := json.Marshal(req)
_, err := utils.HTTPPost(fmt.Sprintf(actorInvokeURLFormat, reentrantURL, firstActorID, "method", "reentrantMethod"), reqBody)
require.NoError(t, err)
resp, httpErr := utils.HTTPGet(logsURL)
require.NoError(t, httpErr)
require.NotNil(t, resp)
logs := parseLogEntries(resp)
require.Lenf(t, logs, len(req.Calls)*2, "Logs: %v", logs)
index := 0
for i := 0; i < len(req.Calls); i++ {
require.Equal(t, fmt.Sprintf("Enter %s", req.Calls[i].Method), logs[index].Action)
require.Equal(t, req.Calls[i].ActorID, logs[index].ActorID)
require.Equal(t, req.Calls[i].ActorType, logs[index].ActorType)
index++
}
for i := len(req.Calls) - 1; i > -1; i-- {
require.Equal(t, fmt.Sprintf("Exit %s", req.Calls[i].Method), logs[index].Action)
require.Equal(t, req.Calls[i].ActorID, logs[index].ActorID)
require.Equal(t, req.Calls[i].ActorType, logs[index].ActorType)
index++
}
})
t.Run("Reentrancy Stack Depth Limit", func(t *testing.T) {
utils.HTTPDelete(logsURL)
// Limit is set to 5
req := reentrantRequest{
Calls: []actorCall{
{ActorID: firstActorID, ActorType: actorType, Method: "reentrantMethod"},
{ActorID: firstActorID, ActorType: actorType, Method: "reentrantMethod"},
{ActorID: firstActorID, ActorType: actorType, Method: "reentrantMethod"},
{ActorID: firstActorID, ActorType: actorType, Method: "reentrantMethod"},
{ActorID: firstActorID, ActorType: actorType, Method: "reentrantMethod"},
{ActorID: firstActorID, ActorType: actorType, Method: "standardMethod"},
},
}
reqBody, _ := json.Marshal(req)
_, err := utils.HTTPPost(fmt.Sprintf(actorInvokeURLFormat, reentrantURL, firstActorID, "method", "reentrantMethod"), reqBody)
require.NoError(t, err)
resp, err := utils.HTTPGet(logsURL)
require.NoError(t, err)
require.NotNil(t, resp)
logs := parseLogEntries(resp)
// Should be 2 calls per stack item (limit 5)
require.Len(t, logs, 10)
for index := range logs {
if index < 5 {
require.Equal(t, "Enter reentrantMethod", logs[index].Action)
} else {
require.Equal(t, "Error reentrantMethod", logs[index].Action)
}
}
})
}
|
mikeee/dapr
|
tests/e2e/actor_reentrancy/actor_reentrancy_test.go
|
GO
|
mit
| 8,158 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package actor_reminder_e2e
import (
"encoding/json"
"fmt"
"os"
"sync"
"testing"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
"github.com/stretchr/testify/require"
)
const (
appName = "actorreminder" // App name in Dapr.
actorIDRestartTemplate = "actor-reminder-restart-test-%d" // Template for Actor ID
actorIDPartitionTemplate = "actor-reminder-partition-test-%d" // Template for Actor ID
reminderName = "RestartTestReminder" // Reminder name
actorIDGetTemplate = "actor-reminder-get-test-%d" // Template for Actor ID
reminderNameForGet = "GetTestReminder" // Reminder name for getting tests
numIterations = 7 // Number of times each test should run.
numHealthChecks = 60 // Number of get calls before starting tests.
numActorsPerThread = 10 // Number of get calls before starting tests.
secondsToCheckReminderResult = 20 // How much time to wait to make sure the result is in logs.
actorName = "testactorreminder" // Actor name
actorInvokeURLFormat = "%s/test/" + actorName + "/%s/%s/%s" // URL to invoke a Dapr's actor method in test app.
actorlogsURLFormat = "%s/test/logs" // URL to fetch logs from test app.
shutdownURLFormat = "%s/test/shutdown" // URL to shutdown sidecar and app.
misconfiguredAppName = "actor-reminder-no-state-store" // Actor-reminder app without a state store (should fail to start)
)
// represents a response for the APIs in this app.
type actorLogEntry struct {
Action string `json:"action,omitempty"`
ActorType string `json:"actorType,omitempty"`
ActorID string `json:"actorId,omitempty"`
StartTimestamp int `json:"startTimestamp,omitempty"`
EndTimestamp int `json:"endTimestamp,omitempty"`
}
type actorReminder struct {
Data string `json:"data,omitempty"`
DueTime string `json:"dueTime,omitempty"`
Period string `json:"period,omitempty"`
TTL string `json:"ttl,omitempty"`
Callback string `json:"callback,omitempty"`
}
type reminderResponse struct {
ActorID string `json:"actorID,omitempty"`
ActorType string `json:"actorType,omitempty"`
Name string `json:"name,omitempty"`
Data interface{} `json:"data"`
Period string `json:"period"`
DueTime string `json:"dueTime"`
RegisteredTime string `json:"registeredTime,omitempty"`
ExpirationTime string `json:"expirationTime,omitempty"`
}
func parseLogEntries(resp []byte) []actorLogEntry {
logEntries := []actorLogEntry{}
err := json.Unmarshal(resp, &logEntries)
if err != nil {
return nil
}
return logEntries
}
func countActorAction(resp []byte, actorID string, action string) int {
count := 0
logEntries := parseLogEntries(resp)
for _, logEntry := range logEntries {
if (logEntry.ActorID == actorID) && (logEntry.Action == action) {
count++
}
}
return count
}
var tr *runner.TestRunner
func TestMain(m *testing.M) {
utils.SetupLogs("actor_reminder")
utils.InitHTTPClient(false)
// These apps will be deployed before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: appName,
DaprEnabled: true,
DebugLoggingEnabled: true,
ImageName: "e2e-actorfeatures",
Config: "omithealthchecksconfig",
Replicas: 1,
IngressEnabled: true,
DaprCPULimit: "2.0",
DaprCPURequest: "0.1",
AppCPULimit: "2.0",
AppCPURequest: "0.1",
AppEnv: map[string]string{
"TEST_APP_ACTOR_TYPE": actorName,
},
},
{
AppName: misconfiguredAppName,
DaprEnabled: true,
DebugLoggingEnabled: true,
ImageName: "e2e-actorfeatures",
Config: "omithealthchecksconfig",
Replicas: 1,
IngressEnabled: true,
DaprCPULimit: "2.0",
DaprCPURequest: "0.1",
AppCPULimit: "2.0",
AppCPURequest: "0.1",
AppEnv: map[string]string{
"TEST_APP_ACTOR_TYPE": actorName,
},
},
}
tr = runner.NewTestRunner(appName, testApps, nil, nil)
os.Exit(tr.Start(m))
}
func TestActorMissingStateStore(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL(misconfiguredAppName)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
t.Logf("Checking if app is healthy ...")
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
// Set reminder
reminder := actorReminder{
Data: "reminderdata",
DueTime: "1s",
Period: "1s",
}
reminderBody, err := json.Marshal(reminder)
require.NoError(t, err)
t.Run("Actor service should 500 when no state store is available.", func(t *testing.T) {
_, statusCode, err := utils.HTTPPostWithStatus(fmt.Sprintf(actorInvokeURLFormat, externalURL, "bogon-actor", "reminders", "failed-reminder"), reminderBody)
require.NoError(t, err)
require.True(t, statusCode == 500)
})
}
func TestActorReminder(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL(appName)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
logsURL := fmt.Sprintf(actorlogsURLFormat, externalURL)
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
t.Logf("Checking if app is healthy ...")
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
// Set reminder
reminder := actorReminder{
Data: "reminderdata",
DueTime: "1s",
Period: "1s",
}
reminderBody, err := json.Marshal(reminder)
require.NoError(t, err)
t.Run("Actor reminder unregister then restart should not trigger anymore.", func(t *testing.T) {
var wg sync.WaitGroup
for iteration := 1; iteration <= numIterations; iteration++ {
wg.Add(1)
go func(iteration int) {
defer wg.Done()
t.Logf("Running iteration %d out of %d ...", iteration, numIterations)
for i := 0; i < numActorsPerThread; i++ {
actorID := fmt.Sprintf(actorIDRestartTemplate, i+(1000*iteration))
t.Logf("Registering reminder: %s %s ...", actorID, reminderName)
// Deleting pre-existing reminder, just in case…
_, err = utils.HTTPDelete(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName))
require.NoError(t, err)
// Registering reminder
_, err = utils.HTTPPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName), reminderBody)
require.NoError(t, err)
}
t.Logf("Sleeping for %d seconds ...", secondsToCheckReminderResult)
time.Sleep(secondsToCheckReminderResult * time.Second)
for i := 0; i < numActorsPerThread; i++ {
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
actorID := fmt.Sprintf(actorIDRestartTemplate, i+(1000*iteration))
// Unregistering reminder
t.Logf("Unregistering reminder: %s %s ...", actorID, reminderName)
_, err = utils.HTTPDelete(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName))
require.NoError(t, err)
}
t.Logf("Getting logs from %s to see if reminders did trigger ...", logsURL)
resp, httpErr := utils.HTTPGet(logsURL)
require.NoError(t, httpErr)
t.Log("Checking if all reminders did trigger ...")
// Errors below should NOT be considered flakyness and must be investigated.
// If there was no other error until now, there should be reminders triggered.
for i := 0; i < numActorsPerThread; i++ {
actorID := fmt.Sprintf(actorIDRestartTemplate, i+(1000*iteration))
count := countActorAction(resp, actorID, reminderName)
// Due to possible load stress, we do not expect all reminders to be called at the same frequency.
// There are other E2E tests that validate the correct frequency of reminders in a happy path.
require.True(t, count >= 1, "Reminder %s for Actor %s was invoked %d times.", reminderName, actorID, count)
}
}(iteration)
}
wg.Wait()
err = backoff.RetryNotify(
func() error {
t.Logf("Checking if unregistration of reminders took place in %s ...", appName)
resp1, err := utils.HTTPGet(logsURL)
if err != nil {
return err
}
time.Sleep(secondsToCheckReminderResult * time.Second)
resp2, err := utils.HTTPGet(logsURL)
if err != nil {
return err
}
t.Log("Checking if NO reminder triggered after unregister and before restart ...")
for iteration := 1; iteration <= numIterations; iteration++ {
// This is useful to make sure the unregister call was processed.
for i := 0; i < numActorsPerThread; i++ {
actorID := fmt.Sprintf(actorIDRestartTemplate, i+(1000*iteration))
count1 := countActorAction(resp1, actorID, reminderName)
count2 := countActorAction(resp2, actorID, reminderName)
count := count2 - count1
if count > 0 {
return fmt.Errorf("after unregistration but before restart, reminder %s for Actor %s was invoked %d times.", reminderName, actorID, count)
}
}
}
return nil
},
backoff.WithMaxRetries(backoff.NewConstantBackOff(5*time.Second), 10),
func(err error, d time.Duration) {
t.Logf("Error while validating reminder unregistration logs: '%v' - retrying in %s", err, d)
},
)
require.NoError(t, err)
t.Logf("Restarting %s ...", appName)
// Shutdown the sidecar
_, err = utils.HTTPPost(fmt.Sprintf(shutdownURLFormat, externalURL), []byte(""))
require.NoError(t, err)
t.Logf("Sleeping for %d seconds to see if reminders will trigger ...", secondsToCheckReminderResult)
time.Sleep(secondsToCheckReminderResult * time.Second)
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
t.Logf("Checking if app is healthy ...")
_, err = utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
t.Logf("Getting logs from %s ...", logsURL)
resp, err := utils.HTTPGet(logsURL)
require.NoError(t, err)
t.Log("Checking if NO reminder triggered ...")
for iteration := 1; iteration <= numIterations; iteration++ {
// Errors below should NOT be considered flakyness and must be investigated.
// After the app unregisters a reminder and is restarted, there should be no more reminders triggered.
for i := 0; i < numActorsPerThread; i++ {
actorID := fmt.Sprintf(actorIDRestartTemplate, i+(1000*iteration))
count := countActorAction(resp, actorID, reminderName)
require.True(t, count == 0, "After restart, reminder %s for Actor %s was invoked %d times.", reminderName, actorID, count)
}
}
_, err = utils.HTTPDelete(logsURL)
require.NoError(t, err)
t.Log("Done.")
})
t.Run("Actor reminder register and get should succeed.", func(t *testing.T) {
var wg sync.WaitGroup
for iteration := 1; iteration <= numIterations; iteration++ {
wg.Add(1)
go func(iteration int) {
defer wg.Done()
t.Logf("Running iteration %d out of %d ...", iteration, numIterations)
for i := 0; i < numActorsPerThread; i++ {
actorID := fmt.Sprintf(actorIDGetTemplate, i+(1000*iteration))
// Deleting pre-existing reminder
_, err = utils.HTTPDelete(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderNameForGet))
require.NoError(t, err)
// Registering reminder
_, err = utils.HTTPPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderNameForGet), reminderBody)
require.NoError(t, err)
}
t.Logf("Sleeping for %d seconds ...", secondsToCheckReminderResult)
time.Sleep(secondsToCheckReminderResult * time.Second)
}(iteration)
}
wg.Wait()
t.Log("Checking reminders get succeed ...")
for iteration := 1; iteration <= numIterations; iteration++ {
for i := 0; i < numActorsPerThread; i++ {
actorID := fmt.Sprintf(actorIDGetTemplate, i+(1000*iteration))
resp, err := utils.HTTPGet(
fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderNameForGet))
require.NoError(t, err)
require.True(t, len(resp) != 0, "Reminder %s does not exist", reminderNameForGet)
}
}
_, err = utils.HTTPDelete(logsURL)
require.NoError(t, err)
t.Log("Done.")
})
}
func TestActorReminderPeriod(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL(appName)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
logsURL := fmt.Sprintf(actorlogsURLFormat, externalURL)
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
t.Logf("Checking if app is healthy ...")
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
// Set reminder
reminder := actorReminder{
Data: "reminderdata",
DueTime: "1s",
Period: "R5/PT1S",
}
reminderBody, err := json.Marshal(reminder)
require.NoError(t, err)
t.Run("Actor reminder with repetition should run correct number of times", func(t *testing.T) {
reminderName := "repeatable-reminder"
actorID := "repetable-reminder-actor"
_, err = utils.HTTPDelete(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName))
require.NoError(t, err)
// Registering reminder
_, err = utils.HTTPPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName), reminderBody)
require.NoError(t, err)
t.Logf("Sleeping for %d seconds ...", secondsToCheckReminderResult)
time.Sleep(secondsToCheckReminderResult * time.Second)
t.Logf("Getting logs from %s to see if reminders did trigger ...", logsURL)
resp, err := utils.HTTPGet(logsURL)
require.NoError(t, err)
t.Log("Checking if all reminders did trigger ...")
count := countActorAction(resp, actorID, reminderName)
require.Equal(t, 5, count, "response: %s", string(resp))
})
}
func TestActorReminderTTL(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL(appName)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
logsURL := fmt.Sprintf(actorlogsURLFormat, externalURL)
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
t.Logf("Checking if app is healthy ...")
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
// Set reminder
reminder := actorReminder{
Data: "reminderdata",
DueTime: "10s",
Period: "PT5S",
TTL: "59s",
}
reminderBody, err := json.Marshal(reminder)
require.NoError(t, err)
t.Run("Actor reminder with TTL should run correct number of times", func(t *testing.T) {
reminderName := "ttl-reminder"
actorID := "ttl-reminder-actor"
_, err = utils.HTTPDelete(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName))
require.NoError(t, err)
// Registering reminder
_, err = utils.HTTPPost(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorID, "reminders", reminderName), reminderBody)
require.NoError(t, err)
waitForReminderWithTTLToFinishInSeconds := 60
t.Logf("Sleeping for %d seconds ...", waitForReminderWithTTLToFinishInSeconds)
time.Sleep(time.Duration(waitForReminderWithTTLToFinishInSeconds) * time.Second)
t.Logf("Getting logs from %s to see if reminders did trigger ...", logsURL)
resp, err := utils.HTTPGet(logsURL)
require.NoError(t, err)
t.Log("Checking if all reminders did trigger ...")
count := countActorAction(resp, actorID, reminderName)
require.InDelta(t, 10, count, 2)
})
}
func TestActorReminderNonHostedActor(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL(appName)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
t.Run("Operations on actor reminders should fail if actor type is not hosted", func(t *testing.T) {
// Run the tests
res, err := utils.HTTPPost(externalURL+"/test/nonhosted", nil)
require.NoError(t, err)
require.Equal(t, "OK", string(res))
})
}
|
mikeee/dapr
|
tests/e2e/actor_reminder/actor_reminder_test.go
|
GO
|
mit
| 17,325 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package actor_reminder_e2e
import (
"encoding/json"
"fmt"
"log"
"os"
"strconv"
"testing"
"time"
"github.com/cenkalti/backoff/v4"
"go.uber.org/ratelimit"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
"github.com/stretchr/testify/require"
)
const (
appName = "actorreminderpartition" // App name in Dapr.
actorIDPartitionTemplate = "actor-reminder-partition-test-%d" // Template for Actor ID.
reminderName = "PartitionTestReminder" // Reminder name.
numIterations = 7 // Number of times each test should run.
numActors = 40 // Number of actors to register a reminder.
secondsToCheckReminderResult = 90 // How much time to wait to make sure the result is in logs.
secondsToWaitForAppRestart = 30 // How much time to wait until app has restarted.
reminderUpdateRateLimitRPS = 20 // Sane rate limiting in persisting reminders.
actorName = "testactorreminderpartition" // Actor type.
actorInvokeURLFormat = "%s/test/%s/%s/%s/%s" // URL to invoke a Dapr's actor method in test app.
actorlogsURLFormat = "%s/test/logs" // URL to fetch logs from test app.
envURLFormat = "%s/test/env/%s" // URL to fetch or set env var from test app.
shutdownSidecarURLFormat = "%s/test/shutdownsidecar" // URL to shutdown sidecar.
)
// represents a response for the APIs in this app.
type actorLogEntry struct {
Action string `json:"action,omitempty"`
ActorType string `json:"actorType,omitempty"`
ActorID string `json:"actorId,omitempty"`
StartTimestamp int `json:"startTimestamp,omitempty"`
EndTimestamp int `json:"endTimestamp,omitempty"`
}
type actorReminder struct {
Data string `json:"data,omitempty"`
DueTime string `json:"dueTime,omitempty"`
Period string `json:"period,omitempty"`
Callback string `json:"callback,omitempty"`
}
func parseLogEntries(resp []byte) []actorLogEntry {
logEntries := []actorLogEntry{}
err := json.Unmarshal(resp, &logEntries)
if err != nil {
return nil
}
return logEntries
}
func countActorAction(resp []byte, actorID string, action string) int {
count := 0
logEntries := parseLogEntries(resp)
for _, logEntry := range logEntries {
if logEntry.ActorID == actorID && logEntry.Action == action {
count++
}
}
return count
}
var tr *runner.TestRunner
func TestMain(m *testing.M) {
utils.SetupLogs("actor_reminder_partition")
utils.InitHTTPClient(false)
// These apps will be deployed before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: appName,
DaprEnabled: true,
DebugLoggingEnabled: true,
ImageName: "e2e-actorfeatures",
Replicas: 1,
IngressEnabled: true,
Config: "omithealthchecksconfig",
DaprCPULimit: "2.0",
DaprCPURequest: "0.1",
AppCPULimit: "2.0",
AppCPURequest: "0.1",
AppEnv: map[string]string{
"TEST_APP_ACTOR_REMINDERS_PARTITIONS": "0",
"TEST_APP_ACTOR_TYPE": actorName,
},
},
}
tr = runner.NewTestRunner(appName, testApps, nil, nil)
os.Exit(tr.Start(m))
}
func validateReminderLogs(t *testing.T, numActorsToCheck int) error {
externalURL := ""
logsURL := ""
rerr := backoff.Retry(func() error {
externalURL = tr.Platform.AcquireAppExternalURL(appName)
if externalURL == "" {
return fmt.Errorf("external URL must not be empty!")
}
logsURL = fmt.Sprintf(actorlogsURLFormat, externalURL)
log.Printf("Deleting logs via %s ...", logsURL)
_, err := utils.HTTPDelete(logsURL)
if err != nil {
return err
}
return nil
}, backoff.WithMaxRetries(backoff.NewConstantBackOff(5*time.Second), 10))
if rerr != nil {
return rerr
}
return backoff.RetryNotify(
func() error {
log.Printf("Getting logs from %s to see if reminders did trigger for %d actors ...", logsURL, numActorsToCheck)
resp, errb := utils.HTTPGet(logsURL)
if errb != nil {
return errb
}
log.Print("Checking if all reminders did trigger ...")
// Errors below should NOT be considered flakiness and must be investigated.
// If there was no other error until now, there should be reminders triggered.
for i := 0; i < numActorsToCheck; i++ {
actorID := fmt.Sprintf(actorIDPartitionTemplate, i+1000)
count := countActorAction(resp, actorID, reminderName)
// Due to possible load stress, we do not expect all reminders to be called at the same frequency.
// There are other E2E tests that validate the correct frequency of reminders in a happy path.
if count == 0 {
log.Printf("Reminder %s for Actor %s was not invoked", reminderName, actorID)
return fmt.Errorf("reminder %s for Actor %s was not invoked", reminderName, actorID)
}
}
return nil
},
backoff.WithMaxRetries(backoff.NewConstantBackOff(5*time.Second), 10),
func(err error, d time.Duration) {
log.Printf("Error while getting logs: '%v' - retrying in %s", err, d)
},
)
}
func TestActorReminder(t *testing.T) {
rateLimit := ratelimit.New(reminderUpdateRateLimitRPS)
externalURL := tr.Platform.AcquireAppExternalURL(appName)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
log.Printf("Checking if app is healthy ...")
require.NoError(t, utils.HealthCheckApps(externalURL), "failed to check app's health status")
// Set reminder
reminder := actorReminder{
Data: "reminderdata",
DueTime: "1s",
Period: "1s",
}
reminderBody, err := json.Marshal(reminder)
require.NoError(t, err, "error marshalling JSON")
t.Run("Actor reminder changes number of partitions.", func(t *testing.T) {
for i := 0; i < numActors; i++ {
rateLimit.Take()
actorID := fmt.Sprintf(actorIDPartitionTemplate, i+1000)
// Deleting pre-existing reminder
_, err = utils.HTTPDelete(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorName, actorID, "reminders", reminderName))
require.NoError(t, err)
}
expectedEnvPartitionCount := "0"
mustCheckLogs := true
for i := 0; i < numActors; i++ {
// externalURL = tr.Platform.AcquireAppExternalURL(appName)
// require.NotEmpty(t, externalURL, "external URL must not be empty!")
rateLimit.Take()
actorID := fmt.Sprintf(actorIDPartitionTemplate, i+1000)
newPartitionCount := 0
if i == numActors/4 {
newPartitionCount = 5
mustCheckLogs = true
}
if i == numActors/2 {
newPartitionCount = 7
mustCheckLogs = true
}
if newPartitionCount > 0 {
_, err = utils.HTTPPost(
fmt.Sprintf(envURLFormat, externalURL, "TEST_APP_ACTOR_REMINDERS_PARTITIONS"),
[]byte(strconv.Itoa(newPartitionCount)))
require.NoErrorf(t, err, "i=%d actorID=%s", i, actorID)
// Shutdown the sidecar to load the new partition config
_, err = utils.HTTPPost(fmt.Sprintf(shutdownSidecarURLFormat, externalURL), []byte(""))
err = tr.Platform.SetAppEnv(appName, "TEST_APP_ACTOR_REMINDERS_PARTITIONS", strconv.Itoa(newPartitionCount))
require.NoErrorf(t, err, "i=%d actorID=%s", i, actorID)
log.Printf("Updated partition count to %d", newPartitionCount)
log.Printf("Waiting for app %s to restart ...", appName)
// Sleep for some time to let the sidecar restart.
// Calling the health-check right away might trigger a false-positive health prior to actual restart.
time.Sleep(secondsToWaitForAppRestart * time.Second)
expectedEnvPartitionCount = strconv.Itoa(newPartitionCount)
}
err = backoff.RetryNotify(
func() error {
//externalURL = tr.Platform.AcquireAppExternalURL(appName)
//if externalURL == "" {
// return fmt.Errorf("external URL must not be empty!")
//}
rerr := utils.HealthCheckApps(externalURL)
if rerr != nil {
return rerr
}
envValue, rerr := utils.HTTPGet(fmt.Sprintf(envURLFormat, externalURL, "TEST_APP_ACTOR_REMINDERS_PARTITIONS"))
if rerr != nil {
return rerr
}
if expectedEnvPartitionCount != string(envValue) {
return fmt.Errorf("invalid number of partitions: expected=%s - actual=%s", expectedEnvPartitionCount, string(envValue))
}
return nil
},
backoff.WithMaxRetries(backoff.NewExponentialBackOff(), 10),
func(err error, d time.Duration) {
log.Printf("Error while invoking actor: '%v' - retrying in %s", err, d)
},
)
require.NoErrorf(t, err, "i=%d actorID=%s", i, actorID)
err = backoff.RetryNotify(
func() error {
// Registering reminder
_, httpStatusCode, rerr := utils.HTTPPostWithStatus(
fmt.Sprintf(actorInvokeURLFormat, externalURL, actorName, actorID, "reminders", reminderName),
reminderBody,
)
if rerr != nil {
return rerr
}
if httpStatusCode != 200 && httpStatusCode != 204 {
return fmt.Errorf("invalid status code %d while registering reminder for actorID %s", httpStatusCode, actorID)
}
return nil
},
backoff.WithMaxRetries(backoff.NewExponentialBackOff(), 10),
func(err error, d time.Duration) {
log.Printf("error while registering the reminder: '%v' - retrying in %s", err, d)
},
)
require.NoErrorf(t, err, "i=%d actorID=%s", i, actorID)
if mustCheckLogs {
err = validateReminderLogs(t, i+1)
require.NoErrorf(t, err, "i=%d actorID=%s", i, actorID)
mustCheckLogs = false
}
}
err = validateReminderLogs(t, numActors)
require.NoError(t, err, "failed to validate reminder logs")
for i := 0; i < numActors; i++ {
rateLimit.Take()
actorID := fmt.Sprintf(actorIDPartitionTemplate, i+1000)
// Unregistering reminder
_, err = utils.HTTPDelete(fmt.Sprintf(actorInvokeURLFormat, externalURL, actorName, actorID, "reminders", reminderName))
require.NoError(t, err, "failed to un-register reminder")
}
log.Print("Done.")
})
}
|
mikeee/dapr
|
tests/e2e/actor_reminder_partition/actor_reminder_partition_test.go
|
GO
|
mit
| 10,967 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package actor_sdks_e2e
import (
"fmt"
"os"
"testing"
"time"
"github.com/google/uuid"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
"github.com/stretchr/testify/require"
)
const (
appName = "actorinvocationapp" // App name in Dapr.
numHealthChecks = 60 // Number of get calls before starting tests.
)
var (
tr *runner.TestRunner
apps []kube.AppDescription
)
func healthCheckApp(t *testing.T, externalURL string, numHealthChecks int) {
t.Logf("Starting health check for %s\n", externalURL)
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
t.Logf("Endpoint is healthy: %s\n", externalURL)
}
func TestMain(m *testing.M) {
utils.SetupLogs("actor_sdks")
utils.InitHTTPClient(false)
// These apps will be deployed before starting actual test
// and will be cleaned up after all tests are finished automatically
apps = []kube.AppDescription{
{
AppName: "actordotnet",
DaprEnabled: true,
ImageName: "e2e-actordotnet",
DebugLoggingEnabled: true,
Config: "omithealthchecksconfig",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
AppMemoryLimit: "500Mi",
AppMemoryRequest: "200Mi",
},
{
AppName: "actorpython",
DaprEnabled: true,
ImageName: "e2e-actorpython",
DebugLoggingEnabled: true,
Config: "omithealthchecksconfig",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
AppMemoryLimit: "200Mi",
AppMemoryRequest: "100Mi",
},
}
if utils.TestTargetOS() != "windows" {
apps = append(apps,
// Disables Java test on Windows due to poor support for Java on Windows containers.
kube.AppDescription{
AppName: "actorjava",
DaprEnabled: true,
ImageName: "e2e-actorjava",
DebugLoggingEnabled: true,
Config: "omithealthchecksconfig",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
AppMemoryLimit: "500Mi",
AppMemoryRequest: "200Mi",
},
// Disables PHP test for Windows temporarily due to issues with its Windows container.
// See https://github.com/dapr/dapr/issues/2953
kube.AppDescription{
AppName: "actorphp",
DaprEnabled: true,
ImageName: "e2e-actorphp",
DebugLoggingEnabled: true,
Config: "omithealthchecksconfig",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
AppMemoryLimit: "200Mi",
AppMemoryRequest: "100Mi",
})
}
tr = runner.NewTestRunner(appName, apps, nil, nil)
os.Exit(tr.Start(m))
}
func TestActorInvocationCrossSDKs(t *testing.T) {
actorTypes := []string{"DotNetCarActor", "PythonCarActor"}
if utils.TestTargetOS() != "windows" {
actorTypes = append(actorTypes,
// Disables Java test on Windows due to poor support for Java on Windows containers.
"JavaCarActor",
// Disables PHP test for Windows temporarily due to issues with its Windows container.
// See https://github.com/dapr/dapr/issues/2953
"PHPCarActor",
)
}
scenarios := []struct {
method string
payload string
expectedResponse string
}{
{
"incrementAndGet/%s/%s",
"",
"1",
},
{
"carFromJSON/%s/%s",
`{
"vin": "JTXXX923X71194343",
"maker": "carmaker",
"model": "model123",
"trim": "basic",
"modelYear": 1960,
"buildYear": 1959,
"photo": "R0lGODdhAgACAJEAAAAAAP///wAAAAAAACH5BAkAAAIALAAAAAACAAIAAAICjFMAOw=="
}`,
`{
"vin": "JTXXX923X71194343",
"maker": "carmaker",
"model": "model123",
"trim": "basic",
"modelYear": 1960,
"buildYear": 1959,
"photo": "R0lGODdhAgACAJEAAAAAAP///wAAAAAAACH5BAkAAAIALAAAAAACAAIAAAICjFMAOw=="
}`,
},
{
"carToJSON/%s/%s",
`{
"vin": "JTXXX923X71194343",
"maker": "carmaker",
"model": "model123",
"trim": "basic",
"modelYear": 1960,
"buildYear": 1959,
"photo": "R0lGODdhAgACAJEAAAAAAP///wAAAAAAACH5BAkAAAIALAAAAAACAAIAAAICjFMAOw=="
}`,
`{
"vin": "JTXXX923X71194343",
"maker": "carmaker",
"model": "model123",
"trim": "basic",
"modelYear": 1960,
"buildYear": 1959,
"photo": "R0lGODdhAgACAJEAAAAAAP///wAAAAAAACH5BAkAAAIALAAAAAACAAIAAAICjFMAOw=="
}`,
},
}
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
for _, appSpec := range apps {
app := appSpec.AppName
externalURL := tr.Platform.AcquireAppExternalURL(app)
healthCheckApp(t, externalURL, numHealthChecks)
}
t.Log("Sleeping for 15 seconds ...")
time.Sleep(15 * time.Second)
for _, appSpec := range apps {
app := appSpec.AppName
t.Logf("Getting URL for app %s ...", app)
externalURL := tr.Platform.AcquireAppExternalURL(app)
for _, actorType := range actorTypes {
for _, tt := range scenarios {
method := fmt.Sprintf(tt.method, actorType, uuid.New().String())
name := fmt.Sprintf("Test %s calling %s", app, fmt.Sprintf(tt.method, actorType, "ActorId"))
t.Run(name, func(t *testing.T) {
t.Logf("invoking %s/%s", externalURL, method)
resp, err := utils.HTTPPost(fmt.Sprintf("%s/%s", externalURL, method), []byte(tt.payload))
t.Log("checking err...")
require.NoError(t, err)
appResponse := string(resp)
t.Logf("response: %s\n", appResponse)
require.JSONEq(t, tt.expectedResponse, appResponse)
})
}
}
}
}
|
mikeee/dapr
|
tests/e2e/actor_sdks/actor_sdks_test.go
|
GO
|
mit
| 6,291 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package activation
import (
"encoding/json"
"fmt"
"net/http"
"os"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/anypb"
runtimev1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
)
const (
appName = "actorstate" // App name in Dapr.
numHealthChecks = 60 // Number of get calls before starting tests.
)
var tr *runner.TestRunner
func TestMain(m *testing.M) {
utils.SetupLogs("actor_state")
utils.InitHTTPClient(true)
// These apps will be deployed before starting actual test and will be
// cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: appName,
DaprEnabled: true,
ImageName: "e2e-actorstate",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
// TODO: @joshvanl Remove in Dapr 1.12 when ActorStateTTL is finalized.
Config: "actorstatettl",
},
}
tr = runner.NewTestRunner(appName, testApps, nil, nil)
os.Exit(tr.Start(m))
}
func TestActorState(t *testing.T) {
utils.InitHTTPClient(true)
externalURL := tr.Platform.AcquireAppExternalURL(appName)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
initActorURL := fmt.Sprintf("%s/test/initactor", externalURL)
httpURL := fmt.Sprintf("%s/test/actor_state_http", externalURL)
grpcURL := fmt.Sprintf("%s/test/actor_state_grpc", externalURL)
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
// Wait until runtime finds the leader of placements.
time.Sleep(15 * time.Second)
t.Run("http", func(t *testing.T) {
t.Run("getting state which does not exist should error", func(t *testing.T) {
uuid, err := uuid.NewUUID()
require.NoError(t, err)
actuid := uuid.String()
resp, code, err := utils.HTTPGetWithStatus(fmt.Sprintf("%s/httpMyActorType/%s-myActorID", initActorURL, actuid))
require.NoError(t, err)
assert.Equal(t, http.StatusOK, code)
assert.Empty(t, string(resp))
resp, code, err = utils.HTTPGetWithStatus(fmt.Sprintf("%s/httpMyActorType/%s-myActorID/doesnotexist", httpURL, actuid))
require.NoError(t, err)
assert.Equal(t, http.StatusNoContent, code)
assert.Empty(t, string(resp))
})
t.Run("should be able to save, get, update and delete state", func(t *testing.T) {
uuid, err := uuid.NewUUID()
require.NoError(t, err)
actuid := uuid.String()
_, code, err := utils.HTTPGetWithStatus(fmt.Sprintf("%s/httpMyActorType/%s-myActorID", initActorURL, actuid))
require.NoError(t, err)
assert.Equal(t, http.StatusOK, code)
myData := []byte(`[{"operation":"upsert","request":{"key":"myKey","value":"myData"}}]`)
resp, code, err := utils.HTTPPostWithStatus(fmt.Sprintf("%s/httpMyActorType/%s-myActorID", httpURL, actuid), myData)
require.NoError(t, err)
assert.Equal(t, http.StatusNoContent, code)
assert.Empty(t, string(resp))
resp, code, err = utils.HTTPGetWithStatus(fmt.Sprintf("%s/httpMyActorType/%s-myActorID/myKey", httpURL, actuid))
require.NoError(t, err)
assert.Equal(t, http.StatusOK, code)
assert.Equal(t, `"myData"`, string(resp))
_, code, err = utils.HTTPGetWithStatus(fmt.Sprintf("%s/httpMyActorType/%s-notMyActorID/myKey", httpURL, actuid))
require.NoError(t, err)
assert.Equal(t, http.StatusBadRequest, code)
newData := []byte(`[{"operation":"upsert","request":{"key":"myKey","value":"newData"}}]`)
resp, code, err = utils.HTTPPostWithStatus(fmt.Sprintf("%s/httpMyActorType/%s-myActorID", httpURL, actuid), newData)
require.NoError(t, err)
assert.Equal(t, http.StatusNoContent, code)
resp, code, err = utils.HTTPGetWithStatus(fmt.Sprintf("%s/httpMyActorType/%s-myActorID/myKey", httpURL, actuid))
require.NoError(t, err)
assert.Equal(t, http.StatusOK, code)
assert.Equal(t, `"newData"`, string(resp))
deleteData := []byte(`[{"operation":"delete","request":{"key":"myKey"}}]`)
resp, code, err = utils.HTTPPostWithStatus(fmt.Sprintf("%s/httpMyActorType/%s-myActorID", httpURL, actuid), deleteData)
require.NoError(t, err)
assert.Equal(t, http.StatusNoContent, code)
assert.Empty(t, string(resp))
resp, code, err = utils.HTTPGetWithStatus(fmt.Sprintf("%s/httpMyActorType/%s-myActorID/myKey", httpURL, actuid))
require.NoError(t, err)
assert.Equal(t, http.StatusNoContent, code)
assert.Empty(t, string(resp))
})
t.Run("data saved with TTL should be automatically deleted", func(t *testing.T) {
uuid, err := uuid.NewUUID()
require.NoError(t, err)
actuid := uuid.String()
_, code, err := utils.HTTPGetWithStatus(fmt.Sprintf("%s/httpMyActorType/%s-myActorID", initActorURL, actuid))
require.NoError(t, err)
assert.Equal(t, http.StatusOK, code)
now := time.Now()
myData := []byte(`[{"operation":"upsert","request":{"key":"myTTLKey","value":"myTTLData","metadata":{"ttlInSeconds":"3"}}}]`)
resp, code, err := utils.HTTPPostWithStatus(fmt.Sprintf("%s/httpMyActorType/%s-myActorID", httpURL, actuid), myData)
require.NoError(t, err)
assert.Equal(t, http.StatusNoContent, code)
assert.Empty(t, resp)
// Ensure the data isn't deleted yet.
resp, code, header, err := utils.HTTPGetWithStatusWithMetadata(fmt.Sprintf("%s/httpMyActorType/%s-myActorID/myTTLKey", httpURL, actuid))
require.NoError(t, err)
assert.Equal(t, http.StatusOK, code)
assert.Equal(t, `"myTTLData"`, string(resp))
ttlExpireTimeStr := header.Get("metadata.ttlexpiretime")
require.NotEmpty(t, ttlExpireTimeStr)
ttlExpireTime, err := time.Parse(time.RFC3339, ttlExpireTimeStr)
require.NoError(t, err)
assert.InDelta(t, 3, ttlExpireTime.Sub(now).Seconds(), 1)
// Data should be deleted within 10s, since TTL is 3s
assert.Eventually(t, func() bool {
resp, code, err := utils.HTTPGetWithStatus(fmt.Sprintf("%s/httpMyActorType/%s-myActorID/myTTLKey", httpURL, actuid))
t.Logf("err: %v. received: %s (%d)", err, resp, code)
return err == nil && code == http.StatusNoContent && string(resp) == ""
}, 10*time.Second, time.Second)
})
})
t.Run("grpc", func(t *testing.T) {
t.Run("getting state which does not exist should error", func(t *testing.T) {
uuid, err := uuid.NewUUID()
require.NoError(t, err)
actuid := uuid.String()
_, code, err := utils.HTTPGetWithStatus(fmt.Sprintf("%s/grpcMyActorType/%s-myActorID", initActorURL, actuid))
require.NoError(t, err)
assert.Equal(t, http.StatusOK, code)
b, err := json.Marshal(&runtimev1.GetActorStateRequest{
ActorType: "grpcMyActorType", ActorId: fmt.Sprintf("%s-myActorID", actuid), Key: "doesnotexist",
})
require.NoError(t, err)
resp, code, err := utils.HTTPGetWithStatusWithData(grpcURL, b)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, code)
assert.Equal(t, "{}", string(resp))
})
t.Run("should be able to save, get, update and delete state", func(t *testing.T) {
uuid, err := uuid.NewUUID()
require.NoError(t, err)
actuid := uuid.String()
_, code, err := utils.HTTPGetWithStatus(fmt.Sprintf("%s/grpcMyActorType/%s-myActorID", initActorURL, actuid))
require.NoError(t, err)
assert.Equal(t, http.StatusOK, code)
b, err := json.Marshal(&runtimev1.ExecuteActorStateTransactionRequest{
ActorType: "grpcMyActorType", ActorId: fmt.Sprintf("%s-myActorID", actuid),
Operations: []*runtimev1.TransactionalActorStateOperation{
{
OperationType: "upsert", Key: "myKey",
Value: &anypb.Any{Value: []byte("myData")},
},
},
})
require.NoError(t, err)
_, code, err = utils.HTTPPostWithStatus(grpcURL, b)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, code)
b, err = json.Marshal(&runtimev1.GetActorStateRequest{
ActorType: "grpcMyActorType", ActorId: fmt.Sprintf("%s-myActorID", actuid),
Key: "myKey",
})
require.NoError(t, err)
resp, code, err := utils.HTTPGetWithStatusWithData(grpcURL, b)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, code)
var gresp runtimev1.GetActorStateResponse
require.NoError(t, json.Unmarshal(resp, &gresp))
assert.Equal(t, []byte("myData"), gresp.Data)
b, err = json.Marshal(&runtimev1.GetActorStateRequest{
ActorType: "grpcMyActorType", ActorId: "notmyActorID", Key: "myKey",
})
require.NoError(t, err)
_, code, err = utils.HTTPGetWithStatusWithData(grpcURL, b)
require.NoError(t, err)
assert.Equal(t, http.StatusInternalServerError, code)
b, err = json.Marshal(&runtimev1.ExecuteActorStateTransactionRequest{
ActorType: "grpcMyActorType", ActorId: fmt.Sprintf("%s-myActorID", actuid),
Operations: []*runtimev1.TransactionalActorStateOperation{
{
OperationType: "upsert", Key: "myKey",
Value: &anypb.Any{Value: []byte("newData")},
},
},
})
require.NoError(t, err)
resp, code, err = utils.HTTPPostWithStatus(grpcURL, b)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, code)
assert.Empty(t, string(resp))
b, err = json.Marshal(&runtimev1.GetActorStateRequest{
ActorType: "grpcMyActorType", ActorId: fmt.Sprintf("%s-myActorID", actuid), Key: "myKey",
})
require.NoError(t, err)
resp, code, err = utils.HTTPGetWithStatusWithData(grpcURL, b)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, code)
require.NoError(t, json.Unmarshal(resp, &gresp))
assert.Equal(t, []byte("newData"), gresp.Data)
b, err = json.Marshal(&runtimev1.ExecuteActorStateTransactionRequest{
ActorType: "grpcMyActorType", ActorId: fmt.Sprintf("%s-myActorID", actuid),
Operations: []*runtimev1.TransactionalActorStateOperation{
{OperationType: "delete", Key: "myKey"},
},
})
require.NoError(t, err)
_, code, err = utils.HTTPPostWithStatus(grpcURL, b)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, code)
b, err = json.Marshal(&runtimev1.GetActorStateRequest{
ActorType: "grpcMyActorType", ActorId: fmt.Sprintf("%s-myActorID", actuid), Key: "myKey",
})
require.NoError(t, err)
resp, code, err = utils.HTTPGetWithStatusWithData(grpcURL, b)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, code)
assert.Equal(t, "{}", string(resp))
})
t.Run("data saved with TTL should be automatically deleted", func(t *testing.T) {
uuid, err := uuid.NewUUID()
require.NoError(t, err)
actuid := uuid.String()
_, code, err := utils.HTTPGetWithStatus(fmt.Sprintf("%s/grpcMyActorType/%s-myActorIDTTL", initActorURL, actuid))
require.NoError(t, err)
assert.Equal(t, http.StatusOK, code)
b, err := json.Marshal(&runtimev1.ExecuteActorStateTransactionRequest{
ActorType: "grpcMyActorType", ActorId: fmt.Sprintf("%s-myActorIDTTL", actuid),
Operations: []*runtimev1.TransactionalActorStateOperation{
{
OperationType: "upsert", Key: "myTTLKey",
Value: &anypb.Any{Value: []byte("myData")},
Metadata: map[string]string{"ttlInSeconds": "3"},
},
},
})
require.NoError(t, err)
now := time.Now()
_, code, err = utils.HTTPPostWithStatus(grpcURL, b)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, code)
b, err = json.Marshal(&runtimev1.GetActorStateRequest{
ActorType: "grpcMyActorType", ActorId: fmt.Sprintf("%s-myActorIDTTL", actuid), Key: "myTTLKey",
})
resp, code, err := utils.HTTPGetWithStatusWithData(grpcURL, b)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, code)
var gresp runtimev1.GetActorStateResponse
require.NoError(t, json.Unmarshal(resp, &gresp))
assert.Equal(t, []byte("myData"), gresp.Data)
ttlExpireTimeStr := gresp.Metadata["ttlExpireTime"]
require.NotEmpty(t, ttlExpireTimeStr)
ttlExpireTime, err := time.Parse(time.RFC3339, ttlExpireTimeStr)
require.NoError(t, err)
assert.InDelta(t, 3, ttlExpireTime.Sub(now).Seconds(), 1)
assert.Eventually(t, func() bool {
b, err := json.Marshal(&runtimev1.GetActorStateRequest{
ActorType: "grpcMyActorType",
ActorId: fmt.Sprintf("%s-myActorIDTTL", actuid),
Key: "myTTLKey",
})
require.NoError(t, err)
resp, code, err := utils.HTTPGetWithStatusWithData(grpcURL, b)
t.Logf("err: %v. received: %s (%d)", err, resp, code)
return err == nil && code == http.StatusOK && string(resp) == "{}"
}, 10*time.Second, time.Second)
})
})
}
|
mikeee/dapr
|
tests/e2e/actor_state/actor_state_test.go
|
GO
|
mit
| 13,214 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package allowlists_service_invocation_e2e
import (
"encoding/json"
"fmt"
"os"
"testing"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
"github.com/stretchr/testify/require"
)
type testCommandRequest struct {
RemoteApp string `json:"remoteApp,omitempty"`
Method string `json:"method,omitempty"`
RemoteAppTracing string `json:"remoteAppTracing"`
}
type appResponse struct {
Message string `json:"message,omitempty"`
}
const numHealthChecks = 60 // Number of times to call the endpoint to check for health.
var tr *runner.TestRunner
func TestMain(m *testing.M) {
utils.SetupLogs("allowlists")
utils.InitHTTPClient(false)
// These apps will be deployed for hellodapr test before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: "allowlists-caller",
DaprEnabled: true,
ImageName: "e2e-service_invocation",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
},
{
Config: "allowlistsappconfig",
AppName: "allowlists-callee-http",
DaprEnabled: true,
ImageName: "e2e-service_invocation",
Replicas: 1,
IngressEnabled: false,
MetricsEnabled: true,
},
{
Config: "allowlistsgrpcappconfig",
AppName: "allowlists-callee-grpc",
DaprEnabled: true,
ImageName: "e2e-service_invocation_grpc",
Replicas: 1,
IngressEnabled: false,
MetricsEnabled: true,
AppProtocol: "grpc",
},
{
AppName: "grpcproxyclient",
DaprEnabled: true,
ImageName: "e2e-service_invocation_grpc_proxy_client",
Replicas: 1,
AppProtocol: "grpc",
IngressEnabled: true,
MetricsEnabled: true,
},
{
Config: "allowlistsgrpcappconfig",
AppName: "grpcproxyserver",
DaprEnabled: true,
ImageName: "e2e-service_invocation_grpc_proxy_server",
Replicas: 1,
IngressEnabled: false,
MetricsEnabled: true,
AppProtocol: "grpc",
AppPort: 50051,
},
}
tr = runner.NewTestRunner("allowlists", testApps, nil, nil)
os.Exit(tr.Start(m))
}
var allowListsForServiceInvocationTests = []struct {
in string
path string
remoteApp string
appMethod string
expectedResponse string
calleeSide string
expectedStatusCode int
}{
{
"Test allow with callee side http",
"opAllow",
"allowlists-callee-http",
"opAllow",
"opAllow is called",
"http",
200,
},
{
"Test deny with callee side http",
"opDeny",
"allowlists-callee-http",
"opDeny",
"failed to invoke, id: allowlists-callee-http, err: rpc error: code = PermissionDenied desc = access control policy has denied access to id: spiffe://public/ns/dapr-tests/allowlists-caller operation: opDeny verb: POST",
"http",
403,
},
{
"Test allow with callee side grpc",
"grpctogrpctest",
"allowlists-callee-grpc",
"grpcToGrpcTest",
"success",
"grpc",
200,
},
{
"Test allow with callee side grpc without http verb",
"grpctogrpctest",
"allowlists-callee-grpc",
"grpcToGrpcWithoutVerbTest",
"success",
"grpc",
200,
},
{
"Test deny with callee side grpc",
"httptogrpctest",
"allowlists-callee-grpc",
"httptogrpctest",
"HTTP call failed with failed to invoke, id: allowlists-callee-grpc, err: rpc error: code = PermissionDenied desc = access control policy has denied access to id: spiffe://public/ns/dapr-tests/allowlists-caller operation: httpToGrpcTest verb: NONE",
"grpc",
403,
},
}
var allowListsForServiceInvocationForProxyTests = []struct {
in string
path string
remoteApp string
appMethod string
expectedResponse string
calleeSide string
expectedStatusCode int
}{
{
"Test allow with callee side grpc without http verb by grpc proxy",
"",
"grpcproxyclient",
"",
"success",
"grpc",
200,
},
}
func TestServiceInvocationWithAllowListsForGrpcProxy(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL("grpcproxyclient")
require.NotEmpty(t, externalURL, "external URL must not be empty!")
var err error
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err = utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
t.Logf("externalURL is '%s'\n", externalURL)
for _, tt := range allowListsForServiceInvocationForProxyTests {
t.Run(tt.in, func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: tt.remoteApp,
Method: tt.appMethod,
})
require.NoError(t, err)
resp, err := utils.HTTPPost(
fmt.Sprintf("%s/tests/invoke_test", externalURL), body)
t.Log("checking err...")
require.NoError(t, err)
var appResp appResponse
t.Logf("unmarshalling..%s\n", string(resp))
err = json.Unmarshal(resp, &appResp)
require.NoError(t, err)
require.Equal(t, tt.expectedResponse, appResp.Message)
})
}
}
func TestServiceInvocationWithAllowLists(t *testing.T) {
config, err := tr.Platform.GetConfiguration("daprsystem")
if err != nil {
t.Logf("configuration name: daprsystem, get failed: %s \n", err.Error())
os.Exit(-1)
}
if !config.Spec.MTLSSpec.GetEnabled() {
t.Logf("mtls disabled. can't running unit tests")
return
}
externalURL := tr.Platform.AcquireAppExternalURL("allowlists-caller")
require.NotEmpty(t, externalURL, "external URL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err = utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
t.Logf("externalURL is '%s'\n", externalURL)
for _, tt := range allowListsForServiceInvocationTests {
t.Run(tt.in, func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: tt.remoteApp,
Method: tt.appMethod,
})
require.NoError(t, err)
var url string
if tt.calleeSide == "http" {
url = fmt.Sprintf("%s/tests/invoke_test", externalURL)
} else {
url = fmt.Sprintf("http://%s/%s", externalURL, tt.path)
}
resp, statusCode, err := utils.HTTPPostWithStatus(
url,
body)
t.Log("checking err...")
require.NoError(t, err)
var appResp appResponse
t.Logf("unmarshalling..%s\n", string(resp))
err = json.Unmarshal(resp, &appResp)
require.NoError(t, err)
require.Equal(t, tt.expectedResponse, appResp.Message)
require.Equal(t, tt.expectedStatusCode, statusCode)
})
}
}
|
mikeee/dapr
|
tests/e2e/allowlists/allowlists_service_invocation_test.go
|
GO
|
mit
| 7,315 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package bindings_e2e
import (
"encoding/json"
"fmt"
"net/http"
"os"
"testing"
"time"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
"github.com/stretchr/testify/require"
apiv1 "k8s.io/api/core/v1"
)
type testSendRequest struct {
Messages []messageData `json:"messages,omitempty"`
}
type messageData struct {
Data string `json:"data,omitempty"`
Operation string `json:"operation"`
}
type receivedTopicsResponse struct {
ReceivedMessages []string `json:"received_messages,omitempty"`
FailedMessage string `json:"failed_message,omitempty"`
RoutedMessages []string `json:"routeed_messages,omitempty"`
}
var testMessages = []string{
"This message fails",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
}
const (
// Number of times to call the endpoint to check for health.
numHealthChecks = 60
// Number of seconds to wait for binding travelling throughout the cluster.
inputBindingAppName = "bindinginput"
outputBindingAppName = "bindingoutput"
inputBindingGRPCAppName = "bindinginputgrpc"
e2eInputBindingImage = "e2e-binding_input"
e2eOutputBindingImage = "e2e-binding_output"
e2eInputBindingGRPCImage = "e2e-binding_input_grpc"
inputBindingPluggableAppName = "pluggable-bindinginput"
outputbindingPluggableAppName = "pluggable-bindingoutput"
inputBindingGRPCPluggableAppName = "pluggable-bindinginputgrpc"
kafkaBindingsPluggableComponentImage = "e2e-pluggable_kafka-bindings"
DaprTestTopicEnvVar = "DAPR_TEST_TOPIC_NAME"
DaprTestGRPCTopicEnvVar = "DAPR_TEST_GRPC_TOPIC_NAME"
DaprTestInputBindingServiceEnVar = "DAPR_TEST_INPUT_BINDING_SVC"
DaprTestCustomPathRouteEnvVar = "DAPR_TEST_CUSTOM_PATH_ROUTE"
bindingPropagationDelay = 10
)
var tr *runner.TestRunner
var bindingsApps []struct {
suite string
inputApp string
inputGRPCApp string
outputApp string
} = []struct {
suite string
inputApp string
inputGRPCApp string
outputApp string
}{
{
suite: "built-in",
inputApp: inputBindingAppName,
inputGRPCApp: inputBindingGRPCAppName,
outputApp: outputBindingAppName,
},
}
func TestMain(m *testing.M) {
utils.SetupLogs("bindings")
utils.InitHTTPClient(true)
// These apps will be deployed for hellodapr test before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: inputBindingAppName,
DaprEnabled: true,
ImageName: e2eInputBindingImage,
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
},
{
AppName: outputBindingAppName,
DaprEnabled: true,
ImageName: e2eOutputBindingImage,
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
},
{
AppName: inputBindingGRPCAppName,
DaprEnabled: true,
ImageName: e2eInputBindingGRPCImage,
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
AppProtocol: "grpc",
},
}
if utils.TestTargetOS() != "windows" { // pluggable components feature requires unix socket to work
pluggableComponents := []apiv1.Container{
{
Name: "kafka-pluggable",
Image: runner.BuildTestImageName(kafkaBindingsPluggableComponentImage),
},
}
appEnv := map[string]string{
DaprTestGRPCTopicEnvVar: "pluggable-test-topic-grpc",
DaprTestTopicEnvVar: "pluggable-test-topic",
DaprTestInputBindingServiceEnVar: "pluggable-bindinginputgrpc",
DaprTestCustomPathRouteEnvVar: "pluggable-custom-path",
}
testApps = append(testApps, []kube.AppDescription{
{
AppName: inputBindingPluggableAppName,
DaprEnabled: true,
ImageName: e2eInputBindingImage,
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
PluggableComponents: pluggableComponents,
AppEnv: appEnv,
},
{
AppName: outputbindingPluggableAppName,
DaprEnabled: true,
ImageName: e2eOutputBindingImage,
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
PluggableComponents: pluggableComponents,
AppEnv: appEnv,
},
{
AppName: inputBindingGRPCPluggableAppName,
DaprEnabled: true,
ImageName: e2eInputBindingGRPCImage,
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
AppProtocol: "grpc",
PluggableComponents: pluggableComponents,
AppEnv: appEnv,
},
}...)
bindingsApps = append(bindingsApps, struct {
suite string
inputApp string
inputGRPCApp string
outputApp string
}{
suite: "pluggable",
inputApp: inputBindingPluggableAppName,
inputGRPCApp: inputBindingGRPCPluggableAppName,
outputApp: outputbindingPluggableAppName,
})
}
tr = runner.NewTestRunner("bindings", testApps, nil, nil)
os.Exit(tr.Start(m))
}
func testBindingsForApp(app struct {
suite string
inputApp string
inputGRPCApp string
outputApp string
},
) func(t *testing.T) {
return func(t *testing.T) {
// setup
outputExternalURL := tr.Platform.AcquireAppExternalURL(app.outputApp)
require.NotEmpty(t, outputExternalURL, "bindingoutput external URL must not be empty!")
inputExternalURL := tr.Platform.AcquireAppExternalURL(app.inputApp)
require.NotEmpty(t, inputExternalURL, "bindinginput external URL must not be empty!")
inputGRPCExternalURL := tr.Platform.AcquireAppExternalURL(app.inputGRPCApp)
require.NotEmpty(t, inputGRPCExternalURL, "bindinginput external URL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(outputExternalURL, numHealthChecks)
require.NoError(t, err)
_, err = utils.HTTPGetNTimes(inputExternalURL, numHealthChecks)
require.NoError(t, err)
var req testSendRequest
for _, mes := range testMessages {
req.Messages = append(req.Messages, messageData{Data: mes, Operation: "create"})
}
body, err := json.Marshal(req)
require.NoError(t, err)
// act for http
httpPostWithAssert(t, fmt.Sprintf("%s/tests/send", outputExternalURL), body, http.StatusOK)
// This delay allows all the messages to reach corresponding input bindings.
time.Sleep(bindingPropagationDelay * time.Second)
// assert for HTTP
resp := httpPostWithAssert(t, fmt.Sprintf("%s/tests/get_received_topics", inputExternalURL), nil, http.StatusOK)
var decodedResponse receivedTopicsResponse
err = json.Unmarshal(resp, &decodedResponse)
require.NoError(t, err)
// Only the first message fails, all other messages are successfully consumed.
// nine messages succeed.
require.Equal(t, testMessages[1:], decodedResponse.ReceivedMessages)
// one message fails.
require.Equal(t, testMessages[0], decodedResponse.FailedMessage)
// routed binding will receive all messages
require.Equal(t, testMessages[0:], decodedResponse.RoutedMessages)
// act for gRPC
httpPostWithAssert(t, fmt.Sprintf("%s/tests/sendGRPC", outputExternalURL), body, http.StatusOK)
// This delay allows all the messages to reach corresponding input bindings.
time.Sleep(bindingPropagationDelay * time.Second)
// assert for gRPC
resp = httpPostWithAssert(t, fmt.Sprintf("%s/tests/get_received_topics_grpc", outputExternalURL), nil, http.StatusOK)
// assert for gRPC
err = json.Unmarshal(resp, &decodedResponse)
require.NoError(t, err)
// Only the first message fails, all other messages are successfully consumed.
// nine messages succeed.
require.Equal(t, testMessages[1:], decodedResponse.ReceivedMessages)
// one message fails.
require.Equal(t, testMessages[0], decodedResponse.FailedMessage)
}
}
func TestBindings(t *testing.T) {
for idx := range bindingsApps {
app := bindingsApps[idx]
t.Run(app.suite, testBindingsForApp(app))
}
}
func httpPostWithAssert(t *testing.T, url string, data []byte, status int) []byte {
resp, code, err := utils.HTTPPostWithStatus(url, data)
require.NoError(t, err)
require.Equal(t, status, code)
return resp
}
|
mikeee/dapr
|
tests/e2e/bindings/bindings_test.go
|
GO
|
mit
| 9,040 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package bulkpubsubapp_e2e
import (
"encoding/json"
"fmt"
"log"
"math/rand"
"net/http"
"os"
"sort"
"strings"
"testing"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/ratelimit"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
)
var tr *runner.TestRunner
const (
// Number of get calls before starting tests.
numHealthChecks = 60
// used as the exclusive max of a random number that is used as a suffix to the first message sent. Each subsequent message gets this number+1.
// This is random so the first message name is not the same every time.
randomOffsetMax = 49
numberOfMessagesToPublish = 60
publishRateLimitRPS = 25
receiveMessageRetries = 5
publisherAppName = "pubsub-publisher-bulk-subscribe"
bulkSubscriberAppName = "pubsub-bulk-subscriber"
PubSubEnvVar = "DAPR_TEST_PUBSUB_NAME"
)
var (
offset int
pubsubName string
)
// sent to the publisher app, which will publish data to dapr.
type publishCommand struct {
ReqID string `json:"reqID"`
ContentType string `json:"contentType"`
Topic string `json:"topic"`
Data interface{} `json:"data"`
Protocol string `json:"protocol"`
Metadata map[string]string `json:"metadata"`
}
type callSubscriberMethodRequest struct {
ReqID string `json:"reqID"`
RemoteApp string `json:"remoteApp"`
Protocol string `json:"protocol"`
Method string `json:"method"`
}
// data returned from the subscriber app.
type receivedBulkMessagesResponse struct {
ReceivedByTopicRawSub []string `json:"pubsub-raw-sub-topic"`
ReceivedByTopicCESub []string `json:"pubsub-ce-sub-topic"`
ReceivedByTopicRawBulkSub []string `json:"pubsub-raw-bulk-sub-topic"`
ReceivedByTopicCEBulkSub []string `json:"pubsub-ce-bulk-sub-topic"`
ReceivedByTopicDead []string `json:"pubsub-dead-bulk-topic"`
ReceivedByTopicDeadLetter []string `json:"pubsub-deadletter-bulk-topic"`
}
type cloudEvent struct {
ID string `json:"id"`
Type string `json:"type"`
DataContentType string `json:"datacontenttype"`
Data string `json:"data"`
}
// checks is publishing is working.
func publishHealthCheck(publisherExternalURL string) error {
commandBody := publishCommand{
ContentType: "application/json",
Topic: "pubsub-healthcheck-topic-http",
Protocol: "http",
Data: "health check",
}
// this is the publish app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/tests/publish", publisherExternalURL)
return backoff.Retry(func() error {
commandBody.ReqID = "c-" + uuid.New().String()
jsonValue, _ := json.Marshal(commandBody)
_, err := postSingleMessage(url, jsonValue)
return err
}, backoff.WithMaxRetries(backoff.NewConstantBackOff(5*time.Second), 10))
}
// sends messages to the publisher app. The publisher app does the actual publish.
func sendToPublisher(t *testing.T, publisherExternalURL string, topic string, protocol string, metadata map[string]string, cloudEventType string) ([]string, error) {
var sentMessages []string
contentType := "application/json"
if cloudEventType != "" {
contentType = "application/cloudevents+json"
}
commandBody := publishCommand{
ContentType: contentType,
Topic: fmt.Sprintf("%s-%s", topic, protocol),
Protocol: protocol,
Metadata: metadata,
}
rateLimit := ratelimit.New(publishRateLimitRPS)
for i := offset; i < offset+numberOfMessagesToPublish; i++ {
// create and marshal message
messageID := fmt.Sprintf("msg-%s-%s-%04d", strings.TrimSuffix(topic, "-topic"), protocol, i)
var messageData interface{} = messageID
if cloudEventType != "" {
messageData = &cloudEvent{
ID: messageID,
Type: cloudEventType,
DataContentType: "text/plain",
Data: messageID,
}
}
commandBody.ReqID = "c-" + uuid.New().String()
commandBody.Data = messageData
jsonValue, err := json.Marshal(commandBody)
require.NoError(t, err)
// this is the publish app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/tests/publish", publisherExternalURL)
// debuggability - trace info about the first message. don't trace others so it doesn't flood log.
if i == offset {
log.Printf("Sending first publish app at url %s and body '%s', this log will not print for subsequent messages for same topic", url, jsonValue)
}
rateLimit.Take()
statusCode, err := postSingleMessage(url, jsonValue)
// return on an unsuccessful publish
if statusCode != http.StatusNoContent {
return nil, err
}
// save successful message
sentMessages = append(sentMessages, messageID)
}
return sentMessages, nil
}
func testPublishForBulkSubscribe(t *testing.T, publisherExternalURL string, protocol string) receivedBulkMessagesResponse {
sentTopicCESubMessages, err := sendToPublisher(t, publisherExternalURL, "pubsub-ce-sub-topic", protocol, nil, "")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
sentTopicCEBulkSubMessages, err := sendToPublisher(t, publisherExternalURL, "pubsub-ce-bulk-sub-topic", protocol, nil, "")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
metadata := map[string]string{
"rawPayload": "true",
}
sentTopicRawSubMessages, err := sendToPublisher(t, publisherExternalURL, "pubsub-raw-sub-topic", protocol, metadata, "")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
sentTopicRawBulkSubMessages, err := sendToPublisher(t, publisherExternalURL, "pubsub-raw-bulk-sub-topic", protocol, metadata, "")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
return receivedBulkMessagesResponse{
ReceivedByTopicRawSub: sentTopicRawSubMessages,
ReceivedByTopicCESub: sentTopicCESubMessages,
ReceivedByTopicRawBulkSub: sentTopicRawBulkSubMessages,
ReceivedByTopicCEBulkSub: sentTopicCEBulkSubMessages,
}
}
func postSingleMessage(url string, data []byte) (int, error) {
// HTTPPostWithStatus by default sends with content-type application/json
start := time.Now()
_, statusCode, err := utils.HTTPPostWithStatus(url, data)
if err != nil {
log.Printf("Publish failed with error=%s (body=%s) (duration=%s)", err.Error(), data, utils.FormatDuration(time.Now().Sub(start)))
return http.StatusInternalServerError, err
}
if (statusCode != http.StatusOK) && (statusCode != http.StatusNoContent) {
err = fmt.Errorf("publish failed with StatusCode=%d (body=%s) (duration=%s)", statusCode, data, utils.FormatDuration(time.Now().Sub(start)))
}
return statusCode, err
}
func testPublishBulkSubscribeSuccessfully(t *testing.T, publisherExternalURL, subscriberExternalURL, _, bulkSubscriberAppName, protocol string) string {
callInitialize(t, bulkSubscriberAppName, publisherExternalURL, protocol)
setDesiredResponse(t, bulkSubscriberAppName, "success", publisherExternalURL, protocol)
log.Printf("Test publish bulk subscribe success flow\n")
sentMessages := testPublishForBulkSubscribe(t, publisherExternalURL, protocol)
time.Sleep(5 * time.Second)
validateMessagesReceivedWhenSomeTopicsBulkSubscribed(t, publisherExternalURL, bulkSubscriberAppName, protocol, false, sentMessages)
return subscriberExternalURL
}
func testDropToDeadLetter(t *testing.T, publisherExternalURL, subscriberExternalURL, _, bulkSubscriberAppName, protocol string) string {
callInitialize(t, bulkSubscriberAppName, publisherExternalURL, protocol)
setDesiredResponse(t, bulkSubscriberAppName, "drop", publisherExternalURL, protocol)
// send messages to topic that has dead lettering enabled
sentTopicDeadMessages, err := sendToPublisher(t, publisherExternalURL, "pubsub-dead-bulk-sub-topic-http", protocol, nil, "")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
// send messages to topic that has no dead letter, messages should be dropped
sentTopicCEMessages, err := sendToPublisher(t, publisherExternalURL, "pubsub-ce-bulk-sub-topic", protocol, nil, "")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
time.Sleep(5 * time.Second)
validateMessagesReceivedWhenSomeTopicsBulkSubscribed(t, publisherExternalURL, bulkSubscriberAppName, protocol, true,
receivedBulkMessagesResponse{
ReceivedByTopicRawSub: []string{},
ReceivedByTopicRawBulkSub: []string{},
ReceivedByTopicCESub: []string{},
ReceivedByTopicDead: sentTopicDeadMessages,
ReceivedByTopicDeadLetter: sentTopicDeadMessages,
ReceivedByTopicCEBulkSub: sentTopicCEMessages})
return subscriberExternalURL
}
func callInitialize(t *testing.T, subscriberAppName, publisherExternalURL string, protocol string) {
req := callSubscriberMethodRequest{
ReqID: "c-" + uuid.New().String(),
RemoteApp: subscriberAppName,
Method: "initialize",
Protocol: protocol,
}
// only for the empty-json scenario, initialize empty sets in the subscriber app
reqBytes, _ := json.Marshal(req)
_, code, err := utils.HTTPPostWithStatus(publisherExternalURL+"/tests/callSubscriberMethod", reqBytes)
require.NoError(t, err)
require.Equal(t, http.StatusOK, code)
}
func setDesiredResponse(t *testing.T, subscriberAppName, subscriberResponse, publisherExternalURL, protocol string) {
// set to respond with specified subscriber response
req := callSubscriberMethodRequest{
ReqID: "c-" + uuid.New().String(),
RemoteApp: subscriberAppName,
Method: "set-respond-" + subscriberResponse,
Protocol: protocol,
}
reqBytes, _ := json.Marshal(req)
_, code, err := utils.HTTPPostWithStatus(publisherExternalURL+"/tests/callSubscriberMethod", reqBytes)
require.NoError(t, err)
require.Equal(t, http.StatusOK, code)
}
func validateMessagesReceivedWhenSomeTopicsBulkSubscribed(t *testing.T, publisherExternalURL string, subscriberApp string, protocol string, validateDeadLetter bool, sentMessages receivedBulkMessagesResponse) {
// this is the subscribe app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/tests/callSubscriberMethod", publisherExternalURL)
log.Printf("Getting messages received by bulk subscriber using url %s", url)
request := callSubscriberMethodRequest{
RemoteApp: subscriberApp,
Protocol: protocol,
Method: "getMessages",
}
var appResp receivedBulkMessagesResponse
var err error
for retryCount := 0; retryCount < receiveMessageRetries; retryCount++ {
request.ReqID = "c-" + uuid.New().String()
rawReq, _ := json.Marshal(request)
var resp []byte
start := time.Now()
resp, err = utils.HTTPPost(url, rawReq)
log.Printf("(reqID=%s) Attempt %d complete; took %s", request.ReqID, retryCount, utils.FormatDuration(time.Now().Sub(start)))
if err != nil {
log.Printf("(reqID=%s) Error in response: %v", request.ReqID, err)
time.Sleep(10 * time.Second)
continue
}
err = json.Unmarshal(resp, &appResp)
if err != nil {
err = fmt.Errorf("(reqID=%s) failed to unmarshal JSON. Error: %v. Raw data: %s", request.ReqID, err, string(resp))
log.Printf("Error in response: %v", err)
time.Sleep(10 * time.Second)
continue
}
log.Printf(
"subscriber received %d/%d on raw sub topic and %d/%d on ce sub topic and %d/%d on bulk raw sub topic and %d/%d on bulk ce sub topic ",
len(appResp.ReceivedByTopicRawSub), len(sentMessages.ReceivedByTopicRawSub),
len(appResp.ReceivedByTopicCESub), len(sentMessages.ReceivedByTopicCESub),
len(appResp.ReceivedByTopicRawBulkSub), len(sentMessages.ReceivedByTopicRawBulkSub),
len(appResp.ReceivedByTopicCEBulkSub), len(sentMessages.ReceivedByTopicCEBulkSub),
)
if len(appResp.ReceivedByTopicRawSub) != len(sentMessages.ReceivedByTopicRawSub) ||
len(appResp.ReceivedByTopicCESub) != len(sentMessages.ReceivedByTopicCESub) ||
len(appResp.ReceivedByTopicRawBulkSub) != len(sentMessages.ReceivedByTopicRawBulkSub) ||
len(appResp.ReceivedByTopicCEBulkSub) != len(sentMessages.ReceivedByTopicCEBulkSub) {
log.Printf("Differing lengths in received vs. sent messages, retrying.")
time.Sleep(10 * time.Second)
} else {
break
}
}
require.NoError(t, err, "too many failed attempts")
sort.Strings(sentMessages.ReceivedByTopicRawSub)
sort.Strings(appResp.ReceivedByTopicRawSub)
sort.Strings(sentMessages.ReceivedByTopicCESub)
sort.Strings(appResp.ReceivedByTopicCESub)
sort.Strings(sentMessages.ReceivedByTopicRawBulkSub)
sort.Strings(appResp.ReceivedByTopicRawBulkSub)
sort.Strings(sentMessages.ReceivedByTopicCEBulkSub)
sort.Strings(appResp.ReceivedByTopicCEBulkSub)
assert.Equal(t, sentMessages.ReceivedByTopicRawSub, appResp.ReceivedByTopicRawSub, "different messages received in Topic Raw Sub")
assert.Equal(t, sentMessages.ReceivedByTopicCESub, appResp.ReceivedByTopicCESub, "different messages received in Topic CE Sub")
assert.Equal(t, sentMessages.ReceivedByTopicRawBulkSub, appResp.ReceivedByTopicRawBulkSub, "different messages received in Topic Raw Bulk Sub")
assert.Equal(t, sentMessages.ReceivedByTopicCEBulkSub, appResp.ReceivedByTopicCEBulkSub, "different messages received in Topic CE Bulk Sub")
}
var apps []struct {
suite string
publisher string
subscriber string
} = []struct {
suite string
publisher string
subscriber string
}{
{
suite: "built-in-bulk",
publisher: publisherAppName,
subscriber: bulkSubscriberAppName,
},
}
func TestMain(m *testing.M) {
utils.SetupLogs("pubsub")
utils.InitHTTPClient(true)
// These apps will be deployed before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: publisherAppName,
DaprEnabled: true,
ImageName: "e2e-pubsub-publisher",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
AppMemoryLimit: "200Mi",
AppMemoryRequest: "100Mi",
},
{
AppName: bulkSubscriberAppName,
DaprEnabled: true,
ImageName: "e2e-pubsub-bulk-subscriber",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
AppMemoryLimit: "200Mi",
AppMemoryRequest: "100Mi",
},
}
log.Printf("Creating TestRunner")
tr = runner.NewTestRunner("pubsubtest", testApps, nil, nil)
log.Printf("Starting TestRunner")
os.Exit(tr.Start(m))
}
var pubsubTests = []struct {
name string
handler func(*testing.T, string, string, string, string, string) string
subscriberResponse string
}{
{
name: "publish and bulk subscribe messages successfully",
handler: testPublishBulkSubscribeSuccessfully,
}, {
name: "drop message will be published to dlq if configured",
handler: testDropToDeadLetter,
},
}
func TestBulkPubSubHTTP(t *testing.T) {
for _, app := range apps {
t.Log("Enter TestBulkPubSubHTTP")
publisherExternalURL := tr.Platform.AcquireAppExternalURL(app.publisher)
require.NotEmpty(t, publisherExternalURL, "publisherExternalURL must not be empty!")
subscriberExternalURL := tr.Platform.AcquireAppExternalURL(app.subscriber)
require.NotEmpty(t, subscriberExternalURL, "subscriberExternalURLHTTP must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
err := utils.HealthCheckApps(publisherExternalURL, subscriberExternalURL)
require.NoError(t, err)
err = publishHealthCheck(publisherExternalURL)
require.NoError(t, err)
protocol := "http"
//nolint: gosec
offset = rand.Intn(randomOffsetMax) + 1
log.Printf("initial %s offset: %d", app.suite, offset)
for _, tc := range pubsubTests {
t.Run(fmt.Sprintf("%s_%s_%s", app.suite, tc.name, protocol), func(t *testing.T) {
subscriberExternalURL = tc.handler(t, publisherExternalURL, subscriberExternalURL, tc.subscriberResponse, app.subscriber, protocol)
})
}
}
}
|
mikeee/dapr
|
tests/e2e/bulk-pubsub/bulk_pubsub_test.go
|
GO
|
mit
| 16,565 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package configuration_e2e
import (
"encoding/json"
"fmt"
"log"
"os"
"strconv"
"strings"
"testing"
"time"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
)
const (
appName = "configurationapp"
componentNameEnvVar = "DAPR_TEST_CONFIGURATION"
v1 = "1.0.0"
numHealthChecks = 60 // Number of times to check for endpoint health per app.
defaultWaitTime = 5 * time.Second // Time to wait for app to receive the updates
configStore = "configstore"
)
var (
componentName string = "redis"
subscriptionId string = ""
runID string = strings.ReplaceAll(uuid.Must(uuid.NewRandom()).String(), "-", "_")
counter int = 0
tr *runner.TestRunner
subscribedKeyValues map[string]*Item
)
type testCommandRequest struct {
Message string `json:"message,omitempty"`
}
type receivedMessagesResponse struct {
ReceivedUpdates []string `json:"received-messages"`
}
type Item struct {
Value string `json:"value,omitempty"`
Version string `json:"version,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
}
type appResponse struct {
Message string `json:"message,omitempty"`
StartTime int `json:"start_time,omitempty"`
EndTime int `json:"end_time,omitempty"`
}
func TestMain(m *testing.M) {
utils.SetupLogs("configuration e2e")
utils.InitHTTPClient(true)
p := os.Getenv(componentNameEnvVar)
if p != "" {
componentName = p
}
// These apps will be deployed for hellodapr test before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: "configurationapp",
DaprEnabled: true,
ImageName: "e2e-configurationapp",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
DaprMemoryLimit: "200Mi",
DaprMemoryRequest: "100Mi",
AppMemoryLimit: "200Mi",
AppMemoryRequest: "100Mi",
},
}
log.Printf("Creating TestRunner\n")
tr = runner.NewTestRunner("configuration", testApps, nil, nil)
os.Exit(tr.Start(m))
}
var configurationTests = []struct {
name string
handler func(t *testing.T, appExternalUrl string, protocol string, endpointType string, component componentType)
}{
{
name: "testGet",
handler: testGet,
},
{
name: "testSubscribe",
handler: testSubscribe,
},
{
name: "testUnsubscribe",
handler: testUnsubscribe,
},
}
// Generates key-value pairs
func generateKeyValues(keyCount int, version string) map[string]*Item {
m := make(map[string]*Item, keyCount)
k := counter
for ; k < counter+keyCount; k++ {
key := runID + "_key_" + strconv.Itoa(k)
val := runID + "_val_" + strconv.Itoa(k)
m[key] = &Item{
Value: val,
Version: version,
Metadata: map[string]string{},
}
}
counter = k
return m
}
// Updates `mymap` with new values for every key
func updateKeyValues(mymap map[string]*Item, version string) map[string]*Item {
m := make(map[string]*Item, len(mymap))
k := counter
for key := range mymap {
updatedVal := runID + "_val_" + strconv.Itoa(k)
m[key] = &Item{
Value: updatedVal,
Version: version,
Metadata: map[string]string{},
}
k++
}
counter = k
return m
}
// returns the keys of a map
func getKeys(mymap map[string]*Item) []string {
keys := []string{}
for key := range mymap {
keys = append(keys, key)
}
return keys
}
func testGet(t *testing.T, appExternalUrl string, protocol string, endpointType string, component componentType) {
updateUrl := fmt.Sprintf("http://%s/update-key-values/add", appExternalUrl)
items := generateKeyValues(10, v1)
itemsInBytes, _ := json.Marshal(items)
resp, statusCode, err := utils.HTTPPostWithStatus(updateUrl, itemsInBytes)
require.NoError(t, err, "error updating key values")
require.Equalf(t, 200, statusCode, "expected statuscode 200, got %d. Error: %s", statusCode, string(resp))
keys := getKeys(items)
keysInBytes, _ := json.Marshal(keys)
url := fmt.Sprintf("http://%s/get-key-values/%s/%s/%s", appExternalUrl, protocol, endpointType, component.configStore)
resp, statusCode, err = utils.HTTPPostWithStatus(url, keysInBytes)
require.NoError(t, err, "error getting key values")
var appResp appResponse
err = json.Unmarshal(resp, &appResp)
require.NoError(t, err, "error unmarshalling response")
expectedItemsInBytes, _ := json.Marshal(items)
expectedItems := string(expectedItemsInBytes)
require.Equalf(t, 200, statusCode, "expected statuscode 200, got %d. Error: %s", statusCode, appResp.Message)
require.Equalf(t, expectedItems, appResp.Message, "expected %s, got %s", expectedItems, appResp.Message)
}
func testSubscribe(t *testing.T, appExternalUrl string, protocol string, endpointType string, component componentType) {
items := generateKeyValues(10, v1)
keys := getKeys(items)
keysInBytes, _ := json.Marshal(keys)
url := fmt.Sprintf("http://%s/subscribe/%s/%s/%s/%s", appExternalUrl, protocol, endpointType, component.configStore, component.name)
resp, statusCode, err := utils.HTTPPostWithStatus(url, keysInBytes)
require.NoError(t, err, "error subscribing to key values")
subscribedKeyValues = items
var appResp appResponse
err = json.Unmarshal(resp, &appResp)
require.NoError(t, err, "error unmarshalling response")
require.Equalf(t, 200, statusCode, "expected statuscode 200, got %d. Error: %s", statusCode, appResp.Message)
subscriptionId = appResp.Message
time.Sleep(defaultWaitTime) // Waiting for subscribe operation to complete
updateUrl := fmt.Sprintf("http://%s/update-key-values/add", appExternalUrl)
itemsInBytes, _ := json.Marshal(items)
resp, statusCode, err = utils.HTTPPostWithStatus(updateUrl, itemsInBytes)
require.NoError(t, err, "error updating key values")
require.Equalf(t, 200, statusCode, "expected statuscode 200, got %d. Error: %s", statusCode, string(resp))
time.Sleep(defaultWaitTime) // Waiting for update operation to complete
expectedUpdates := make([]string, len(items))
for key, item := range items {
update := map[string]*Item{
key: item,
}
updateInBytes, err := json.Marshal(update)
require.NoError(t, err, "error marshalling update")
expectedUpdates = append(expectedUpdates, string(updateInBytes))
}
getMessagesUrl := fmt.Sprintf("http://%s/get-received-updates/%s", appExternalUrl, subscriptionId)
getResp, err := utils.HTTPGet(getMessagesUrl)
require.NoError(t, err, "error getting received messages")
var receivedMessages receivedMessagesResponse
err = json.Unmarshal(getResp, &receivedMessages)
require.NoErrorf(t, err, "error unmarshalling received messages response, got %s", string(getResp))
require.ElementsMatch(t, expectedUpdates, receivedMessages.ReceivedUpdates, "expected %s, got %s", expectedUpdates, receivedMessages.ReceivedUpdates)
}
func testUnsubscribe(t *testing.T, appExternalUrl string, protocol string, endpointType string, component componentType) {
// Unsubscribe with incorrect subscriptionId
url := fmt.Sprintf("http://%s/unsubscribe/%s/%s/%s/%s", appExternalUrl, "incorrect-id", protocol, endpointType, component.configStore)
resp, err := utils.HTTPGet(url)
require.NoError(t, err, "error unsubscribing to key values")
require.Contains(t, string(resp), "error subscriptionID not found")
// Unsubscribe with correct subscriptionId
url = fmt.Sprintf("http://%s/unsubscribe/%s/%s/%s/%s", appExternalUrl, subscriptionId, protocol, endpointType, component.configStore)
_, err = utils.HTTPGet(url)
require.NoError(t, err, "error unsubscribing to key values")
items := updateKeyValues(subscribedKeyValues, v1)
updateUrl := fmt.Sprintf("http://%s/update-key-values/update", appExternalUrl)
itemsInBytes, _ := json.Marshal(items)
resp, statusCode, err := utils.HTTPPostWithStatus(updateUrl, itemsInBytes)
require.NoError(t, err, "error updating key values")
require.Equal(t, 200, statusCode, "expected statuscode 200, got %d. Error: %s", statusCode, string(resp))
time.Sleep(defaultWaitTime)
expectedUpdates := make([]string, len(items))
getMessagesUrl := fmt.Sprintf("http://%s/get-received-updates/%s", appExternalUrl, subscriptionId)
getResp, err := utils.HTTPGet(getMessagesUrl)
require.NoError(t, err, "error getting received messages")
var receivedMessages receivedMessagesResponse
err = json.Unmarshal(getResp, &receivedMessages)
require.NoError(t, err, "error unmarshalling received messages response, got %s", string(getResp))
require.Equalf(t, expectedUpdates, receivedMessages.ReceivedUpdates, "expected %s, got %s", expectedUpdates, receivedMessages.ReceivedUpdates)
}
var apps []struct {
name string
} = []struct {
name string
}{
{
name: appName,
},
}
type componentType struct {
name string
configStore string
}
var protocols []string = []string{
"http",
"grpc",
}
var endpointTypes []string = []string{
"stable",
"alpha1",
}
func TestConfiguration(t *testing.T) {
for _, app := range apps {
// Get the ingress external url of test app
externalURL := tr.Platform.AcquireAppExternalURL(app.name)
require.NotEmpty(t, externalURL, "external URL must not be empty")
// Check if test app endpoint is available
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
component := componentType{
name: os.Getenv("DAPR_TEST_CONFIG_STORE"),
configStore: configStore,
}
if component.name == "" {
component.name = "redis"
}
// Initialize the configuration updater
url := fmt.Sprintf("http://%s/initialize-updater", externalURL)
componentNameInBytes, _ := json.Marshal(component.name)
resp, statusCode, err := utils.HTTPPostWithStatus(url, componentNameInBytes)
require.NoError(t, err, "error initializing configuration updater")
require.Equalf(t, 200, statusCode, "expected statuscode 200, got %d. Error: %s", statusCode, string(resp))
for _, protocol := range protocols {
t.Run(protocol, func(t *testing.T) {
for _, endpointType := range endpointTypes {
t.Run(endpointType, func(t *testing.T) {
for _, tt := range configurationTests {
t.Run(tt.name, func(t *testing.T) {
tt.handler(t, externalURL, protocol, endpointType, component)
})
}
})
}
})
}
}
}
|
mikeee/dapr
|
tests/e2e/configuration/configuration_test.go
|
GO
|
mit
| 11,009 |
//go:build e2e
// +build e2e
/*
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 crypto_e2e
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"log"
"net/http"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
runtimev1pb "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
)
var tr *runner.TestRunner
const (
// Number of get calls before starting tests.
numHealthChecks = 10
// Name of the test file
testFileName = "gunnar-ridderstrom-LhuSa4p41uI-unsplash.jpg"
)
var (
testComponents []string
httpClient *http.Client
// TODO: Remove when the SubtleCrypto feature is finalized
subtleCryptoEnabled bool
)
func TestMain(m *testing.M) {
utils.SetupLogs("cryptoapp")
utils.InitHTTPClient(true)
log.Printf("AZURE_KEY_VAULT_NAME=%s", os.Getenv("AZURE_KEY_VAULT_NAME"))
// These apps will be deployed before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: "cryptoapp",
DaprEnabled: true,
ImageName: "e2e-crypto",
Replicas: 1,
IngressEnabled: true,
// This is used by the azurekeyvault component envRef. It will be empty if not running on Azure
DaprEnv: "AZURE_KEY_VAULT_NAME=" + os.Getenv("AZURE_KEY_VAULT_NAME"),
},
}
// This test uses the Azure Key Vault component only if running on Azure
testComponents = []string{"jwks"}
if e := os.Getenv("DAPR_TEST_CRYPTO"); e != "" {
testComponents = []string{e}
}
// We need the test HTTP client
httpClient = utils.GetHTTPClient()
log.Print("Creating TestRunner")
tr = runner.NewTestRunner("metadatatest", testApps, nil, nil)
log.Print("Starting TestRunner")
os.Exit(tr.Start(m))
}
func TestWaitReady(t *testing.T) {
appExternalURL := tr.Platform.AcquireAppExternalURL("cryptoapp")
require.NotEmpty(t, appExternalURL, "appExternalURL must not be empty")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(appExternalURL, numHealthChecks)
require.NoError(t, err)
// Check if the SubtleCrypto features are enabled
// TODO: Remove when the SubtleCrypto feature is finalized
u := fmt.Sprintf("http://%s/getSubtleCryptoEnabled", appExternalURL)
res, err := httpClient.Get(utils.SanitizeHTTPURL(u))
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusOK, res.StatusCode)
resData, err := io.ReadAll(res.Body)
require.NoError(t, err)
switch string(resData) {
case "0":
subtleCryptoEnabled = false
case "1":
subtleCryptoEnabled = true
default:
t.Fatalf("Invalid response from /getSubtleCryptoEnabled: %s", string(resData))
}
t.Logf("Subtle Crypto APIs enabled: %v", subtleCryptoEnabled)
}
func TestCrypto(t *testing.T) {
appExternalURL := tr.Platform.AcquireAppExternalURL("cryptoapp")
require.NotEmpty(t, appExternalURL, "appExternalURL must not be empty")
// Read the test file and keep it in memory while also computing its SHA-256 checksum
testFileData, testFileHash := readTestFile(t)
testFn := func(protocol, component string) func(t *testing.T) {
return func(t *testing.T) {
var encFile []byte
t.Run("encrypt", func(t *testing.T) {
// Encrypt the file and store the result in-memory
u := fmt.Sprintf("http://%s/test/%s/%s/encrypt?key=rsakey&alg=RSA", appExternalURL, protocol, component)
res, err := httpClient.Post(utils.SanitizeHTTPURL(u), "", bytes.NewReader(testFileData))
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusOK, res.StatusCode)
encFile, err = io.ReadAll(res.Body)
require.NoError(t, err)
// Encrypted file starts with the right "magic numbers" and is larger than the plaintext
assert.True(t, bytes.HasPrefix(encFile, []byte("dapr.io/enc/v1\n")))
assert.Greater(t, len(encFile), len(testFileData))
})
t.Run("decrypt", func(t *testing.T) {
// Decrypt the encrypted file
u := fmt.Sprintf("http://%s/test/%s/%s/decrypt", appExternalURL, protocol, component)
res, err := httpClient.Post(utils.SanitizeHTTPURL(u), "", bytes.NewReader(encFile))
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusOK, res.StatusCode)
// Read the response
h := sha256.New()
_, err = io.Copy(h, res.Body)
require.NoError(t, err)
// Compare the checksum
require.Equal(t, testFileHash, h.Sum(nil), "checksum of decrypted file does not match")
})
}
}
// Encrypt a file using the high-level APIs, then decrypt it
for _, protocol := range []string{"grpc", "http"} {
t.Run(protocol, func(t *testing.T) {
for _, component := range testComponents {
t.Run(component, testFn(protocol, component))
}
})
}
}
func TestSubtleCrypto(t *testing.T) {
if !subtleCryptoEnabled {
t.Skip("Skipping Subtle Crypto APIs test because they are not enabled in the binary")
}
appExternalURL := tr.Platform.AcquireAppExternalURL("cryptoapp")
require.NotEmpty(t, appExternalURL, "appExternalURL must not be empty")
testFn := func(protocol, component string) func(t *testing.T) {
return func(t *testing.T) {
const message = "La nebbia agli irti colli Piovigginando sale"
messageDigest := sha256.Sum256([]byte(message))
nonce, _ := hex.DecodeString("000102030405060708090A0B")
aad, _ := hex.DecodeString("AABBCC")
var (
tempData1 []byte
tempData2 []byte
)
testOpFn := func(method string, getProtos func() (proto.Message, proto.Message), assertFn func(t *testing.T, res proto.Message)) func(t *testing.T) {
return func(t *testing.T) {
reqData, resData := getProtos()
reqBody, err := protojson.Marshal(reqData)
require.NoError(t, err)
u := fmt.Sprintf("http://%s/test/subtle/%s/%s", appExternalURL, protocol, method)
res, err := httpClient.Post(utils.SanitizeHTTPURL(u), "", bytes.NewReader(reqBody))
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusOK, res.StatusCode)
resBody, err := io.ReadAll(res.Body)
require.NoError(t, err)
err = protojson.Unmarshal(resBody, resData)
require.NoError(t, err)
assertFn(t, resData)
}
}
type testDef struct {
testName string
method string
getProtos func() (proto.Message, proto.Message)
assertFn func(t *testing.T, res proto.Message)
}
tests := []testDef{
{
"get key as PEM",
"getkey",
func() (proto.Message, proto.Message) {
return &runtimev1pb.SubtleGetKeyRequest{
ComponentName: component,
Name: "rsakey",
// PEM is the default format
//Format: runtimev1pb.SubtleGetKeyRequest_PEM,
},
&runtimev1pb.SubtleGetKeyResponse{}
},
func(t *testing.T, resAny proto.Message) {
t.Helper()
res := resAny.(*runtimev1pb.SubtleGetKeyResponse)
require.NotEmpty(t, res.Name)
assert.Contains(t, res.Name, "rsakey")
require.NotEmpty(t, res.PublicKey)
block, _ := pem.Decode([]byte(res.PublicKey))
require.NotEmpty(t, block)
assert.Equal(t, "PUBLIC KEY", block.Type)
},
},
{
"get key as JSON",
"getkey",
func() (proto.Message, proto.Message) {
return &runtimev1pb.SubtleGetKeyRequest{
ComponentName: component,
Name: "rsakey",
Format: runtimev1pb.SubtleGetKeyRequest_JSON,
},
&runtimev1pb.SubtleGetKeyResponse{}
},
func(t *testing.T, resAny proto.Message) {
t.Helper()
res := resAny.(*runtimev1pb.SubtleGetKeyResponse)
require.NotEmpty(t, res.Name)
assert.Contains(t, res.Name, "rsakey")
require.NotEmpty(t, res.PublicKey)
key := map[string]any{}
err := json.Unmarshal([]byte(res.PublicKey), &key)
require.NoError(t, err)
require.Equal(t, "RSA", key["kty"])
// Public parameters are included
require.NotEmpty(t, key["n"])
require.NotEmpty(t, key["e"])
// Private parameters are not included
require.Empty(t, key["d"])
},
},
{
"encrypt",
"encrypt",
func() (proto.Message, proto.Message) {
return &runtimev1pb.SubtleEncryptRequest{
ComponentName: component,
Plaintext: []byte(message),
Algorithm: "RSA-OAEP",
KeyName: "rsakey",
},
&runtimev1pb.SubtleEncryptResponse{}
},
func(t *testing.T, resAny proto.Message) {
t.Helper()
res := resAny.(*runtimev1pb.SubtleEncryptResponse)
require.NotEmpty(t, res.Ciphertext)
tempData1 = res.Ciphertext
},
},
{
"decrypt",
"decrypt",
func() (proto.Message, proto.Message) {
return &runtimev1pb.SubtleDecryptRequest{
ComponentName: component,
Ciphertext: tempData1,
Algorithm: "RSA-OAEP",
KeyName: "rsakey",
},
&runtimev1pb.SubtleDecryptResponse{}
},
func(t *testing.T, resAny proto.Message) {
t.Helper()
res := resAny.(*runtimev1pb.SubtleDecryptResponse)
require.NotEmpty(t, res.Plaintext)
require.Equal(t, message, string(res.Plaintext))
},
},
{
"wrap key",
"wrapkey",
func() (proto.Message, proto.Message) {
return &runtimev1pb.SubtleWrapKeyRequest{
ComponentName: component,
PlaintextKey: []byte(message),
Algorithm: "RSA-OAEP",
KeyName: "rsakey",
},
&runtimev1pb.SubtleWrapKeyResponse{}
},
func(t *testing.T, resAny proto.Message) {
t.Helper()
res := resAny.(*runtimev1pb.SubtleWrapKeyResponse)
require.NotEmpty(t, res.WrappedKey)
tempData1 = res.WrappedKey
},
},
{
"unwrap key",
"unwrapkey",
func() (proto.Message, proto.Message) {
return &runtimev1pb.SubtleUnwrapKeyRequest{
ComponentName: component,
WrappedKey: tempData1,
Algorithm: "RSA-OAEP",
KeyName: "rsakey",
},
&runtimev1pb.SubtleUnwrapKeyResponse{}
},
func(t *testing.T, resAny proto.Message) {
t.Helper()
res := resAny.(*runtimev1pb.SubtleUnwrapKeyResponse)
require.NotEmpty(t, res.PlaintextKey)
require.Equal(t, message, string(res.PlaintextKey))
},
},
{
"sign",
"sign",
func() (proto.Message, proto.Message) {
return &runtimev1pb.SubtleSignRequest{
ComponentName: component,
Digest: messageDigest[:],
Algorithm: "PS256",
KeyName: "rsakey",
},
&runtimev1pb.SubtleSignResponse{}
},
func(t *testing.T, resAny proto.Message) {
t.Helper()
res := resAny.(*runtimev1pb.SubtleSignResponse)
require.NotEmpty(t, res.Signature)
tempData1 = res.Signature
},
},
{
"verify",
"verify",
func() (proto.Message, proto.Message) {
return &runtimev1pb.SubtleVerifyRequest{
ComponentName: component,
Digest: messageDigest[:],
Signature: tempData1,
Algorithm: "PS256",
KeyName: "rsakey",
},
&runtimev1pb.SubtleVerifyResponse{}
},
func(t *testing.T, resAny proto.Message) {
t.Helper()
res := resAny.(*runtimev1pb.SubtleVerifyResponse)
require.True(t, res.Valid)
},
},
}
// The following tests require symmetric keys and do not work on Azure Key Vault (because we're not using a Managed HSM)
if component == "jwks" {
tests = append(tests,
testDef{
"encrypt with symmetric key",
"encrypt",
func() (proto.Message, proto.Message) {
return &runtimev1pb.SubtleEncryptRequest{
ComponentName: component,
Plaintext: []byte(message),
Algorithm: "C20P",
KeyName: "symmetrickey",
Nonce: nonce,
AssociatedData: aad,
},
&runtimev1pb.SubtleEncryptResponse{}
},
func(t *testing.T, resAny proto.Message) {
t.Helper()
res := resAny.(*runtimev1pb.SubtleEncryptResponse)
require.NotEmpty(t, res.Ciphertext)
require.NotEmpty(t, res.Tag)
tempData1 = res.Ciphertext
tempData2 = res.Tag
},
},
testDef{
"decrypt with symmetric key",
"decrypt",
func() (proto.Message, proto.Message) {
return &runtimev1pb.SubtleDecryptRequest{
ComponentName: component,
Ciphertext: tempData1,
Tag: tempData2,
Algorithm: "C20P",
KeyName: "symmetrickey",
Nonce: nonce,
AssociatedData: aad,
},
&runtimev1pb.SubtleDecryptResponse{}
},
func(t *testing.T, resAny proto.Message) {
t.Helper()
res := resAny.(*runtimev1pb.SubtleDecryptResponse)
require.NotEmpty(t, res.Plaintext)
require.Equal(t, message, string(res.Plaintext))
},
},
testDef{
"wrap key with symmetric key",
"wrapkey",
func() (proto.Message, proto.Message) {
return &runtimev1pb.SubtleWrapKeyRequest{
ComponentName: component,
PlaintextKey: []byte(message[0:16]),
Algorithm: "A256KW",
KeyName: "symmetrickey",
},
&runtimev1pb.SubtleWrapKeyResponse{}
},
func(t *testing.T, resAny proto.Message) {
t.Helper()
res := resAny.(*runtimev1pb.SubtleWrapKeyResponse)
require.NotEmpty(t, res.WrappedKey)
tempData1 = res.WrappedKey
},
},
testDef{
"unwrap key with symmetric key",
"unwrapkey",
func() (proto.Message, proto.Message) {
return &runtimev1pb.SubtleUnwrapKeyRequest{
ComponentName: component,
WrappedKey: tempData1,
Algorithm: "A256KW",
KeyName: "symmetrickey",
},
&runtimev1pb.SubtleUnwrapKeyResponse{}
},
func(t *testing.T, resAny proto.Message) {
t.Helper()
res := resAny.(*runtimev1pb.SubtleUnwrapKeyResponse)
require.NotEmpty(t, res.PlaintextKey)
require.Equal(t, message[0:16], string(res.PlaintextKey))
},
},
)
}
for _, tc := range tests {
t.Run(tc.testName, testOpFn(tc.method, tc.getProtos, tc.assertFn))
}
}
}
// Run tests for HTTP and gRPC
for _, protocol := range []string{"grpc", "http"} {
t.Run(protocol, func(t *testing.T) {
for _, component := range testComponents {
t.Run(component, testFn(protocol, component))
}
})
}
}
// Read the test file and keep it in memory while also computing its SHA-256 checksum
func readTestFile(t *testing.T) (testFileData []byte, testFileHash []byte) {
t.Helper()
f, err := os.Open(testFileName)
require.NoError(t, err, "failed to open test file")
defer f.Close()
testFileData, err = io.ReadAll(f)
require.NoError(t, err, "failed to read test file")
require.NotEmpty(t, testFileData)
h := sha256.New()
_, err = h.Write(testFileData)
require.NoError(t, err, "failed to hash test file")
testFileHash = h.Sum(nil)
return
}
|
mikeee/dapr
|
tests/e2e/crypto/crypto_test.go
|
GO
|
mit
| 15,991 |
//go:build e2e
// +build e2e
/*
Copyright 2022 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package healthcheck_e2e
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
)
var tr *runner.TestRunner
const (
// Number of get calls before starting tests.
numHealthChecks = 60
)
func TestMain(m *testing.M) {
utils.SetupLogs("healthcheck")
utils.InitHTTPClient(true)
// These apps will be deployed before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: "healthapp-http",
AppPort: 4000,
AppProtocol: "http",
DaprEnabled: true,
ImageName: "e2e-healthapp",
Replicas: 1,
IngressEnabled: true,
IngressPort: 3000,
MetricsEnabled: true,
EnableAppHealthCheck: true,
AppHealthCheckPath: "/healthz",
AppHealthProbeInterval: 3,
AppHealthProbeTimeout: 200,
AppHealthThreshold: 3,
DaprEnv: `CRON_SCHEDULE="@every 1s"`, // Test envRef for components
AppEnv: map[string]string{
"APP_PORT": "4000",
"CONTROL_PORT": "3000",
"EXPECT_APP_PROTOCOL": "http",
},
},
{
AppName: "healthapp-grpc",
AppPort: 4000,
AppProtocol: "grpc",
DaprEnabled: true,
ImageName: "e2e-healthapp",
Replicas: 1,
IngressEnabled: true,
IngressPort: 3000,
MetricsEnabled: true,
EnableAppHealthCheck: true,
AppHealthCheckPath: "/healthz",
AppHealthProbeInterval: 3,
AppHealthProbeTimeout: 200,
AppHealthThreshold: 3,
DaprEnv: `CRON_SCHEDULE="@every 1s"`,
AppEnv: map[string]string{
"APP_PORT": "4000",
"CONTROL_PORT": "3000",
"EXPECT_APP_PROTOCOL": "grpc",
},
},
{
AppName: "healthapp-h2c",
AppPort: 4000,
AppProtocol: "h2c",
DaprEnabled: true,
ImageName: "e2e-healthapp",
Replicas: 1,
IngressEnabled: true,
IngressPort: 3000,
MetricsEnabled: true,
EnableAppHealthCheck: true,
AppHealthCheckPath: "/healthz",
AppHealthProbeInterval: 3,
AppHealthProbeTimeout: 200,
AppHealthThreshold: 3,
DaprEnv: `CRON_SCHEDULE="@every 1s"`,
AppEnv: map[string]string{
"APP_PORT": "4000",
"CONTROL_PORT": "3000",
"EXPECT_APP_PROTOCOL": "h2c",
},
},
}
log.Print("Creating TestRunner")
tr = runner.NewTestRunner("healthchecktest", testApps, nil, nil)
log.Print("Starting TestRunner")
os.Exit(tr.Start(m))
}
func TestAppHealthCheckHTTP(t *testing.T) {
testAppHealthCheckProtocol(t, "http")
}
func TestAppHealthCheckGRPC(t *testing.T) {
testAppHealthCheckProtocol(t, "grpc")
}
func TestAppHealthCheckH2C(t *testing.T) {
testAppHealthCheckProtocol(t, "h2c")
}
func testAppHealthCheckProtocol(t *testing.T, protocol string) {
appName := "healthapp-" + protocol
appExternalURL := tr.Platform.AcquireAppExternalURL(appName)
require.NotEmpty(t, appExternalURL, "appExternalURL must not be empty!")
if !strings.HasPrefix(appExternalURL, "http://") && !strings.HasPrefix(appExternalURL, "https://") {
appExternalURL = "http://" + appExternalURL
}
appExternalURL = strings.TrimSuffix(appExternalURL, "/")
log.Println("App external URL", appExternalURL)
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(appExternalURL, numHealthChecks)
require.NoError(t, err)
getCountAndLast := func(t *testing.T, method string) (obj countAndLast) {
u := appExternalURL + "/" + method
log.Println("Invoking method", "GET", u)
res, err := utils.HTTPGet(u)
require.NoError(t, err)
err = json.Unmarshal(res, &obj)
require.NoError(t, err)
assert.NotEmpty(t, obj.Count)
return obj
}
invokeFoo := func(t *testing.T) (res []byte, status int) {
u := fmt.Sprintf("%s/invoke/%s/foo", appExternalURL, appName)
log.Println("Invoking method", "POST", u)
res, status, err := utils.HTTPPostWithStatus(u, []byte{})
require.NoError(t, err)
return res, status
}
t.Run("last health check within 3s", func(t *testing.T) {
obj := getCountAndLast(t, "last-health-check")
_ = assert.NotNil(t, obj.Last) &&
assert.Less(t, *obj.Last, int64(3500)) // Adds .5s to reduce flakiness on slow runners
})
t.Run("invoke method should work on healthy app", func(t *testing.T) {
res, status := invokeFoo(t)
require.Equal(t, http.StatusOK, status)
require.Equal(t, "🤗", string(res))
})
t.Run("last input binding within 1s", func(t *testing.T) {
obj := getCountAndLast(t, "last-input-binding")
_ = assert.NotNil(t, obj.Last) &&
assert.Less(t, *obj.Last, int64(1500)) // Adds .5s to reduce flakiness on slow runners
})
t.Run("last topic message within 1s", func(t *testing.T) {
obj := getCountAndLast(t, "last-topic-message")
_ = assert.NotNil(t, obj.Last) &&
assert.Less(t, *obj.Last, int64(1500)) // Adds .5s to reduce flakiness on slow runners
})
t.Run("set plan and trigger failures", func(t *testing.T) {
u := fmt.Sprintf("%s/set-plan", appExternalURL)
log.Println("Invoking method", "POST", u)
plan, _ := json.Marshal([]bool{false, false, false, false, false, false})
_, err := utils.HTTPPost(u, plan)
require.NoError(t, err)
// We will need to wait for 11 seconds (3 failed probes at 3 seconds interval + 2s buffer)
wait := time.After(11 * time.Second)
// Get the last counts
var (
lastInputBinding countAndLast
lastTopicMessage countAndLast
lastHealthCheck countAndLast
)
wg := sync.WaitGroup{}
t.Run("retrieve counts after failures", func(t *testing.T) {
wg.Add(3)
go func() {
lastInputBinding = getCountAndLast(t, "last-input-binding")
wg.Done()
}()
go func() {
lastTopicMessage = getCountAndLast(t, "last-topic-message")
wg.Done()
}()
go func() {
lastHealthCheck = getCountAndLast(t, "last-health-check")
wg.Done()
}()
wg.Wait()
// Ensure we have the result of last-input-binding and last-health-check
require.NotEmpty(t, lastInputBinding.Count)
require.NotEmpty(t, lastHealthCheck.Count)
})
t.Run("after delay, get updated counters and service invocation fails", func(t *testing.T) {
// Wait for the remainder of the time
<-wait
// Get the last values
wg.Add(4)
go func() {
obj := getCountAndLast(t, "last-input-binding")
require.Greater(t, obj.Count, lastInputBinding.Count)
lastInputBinding = obj
wg.Done()
}()
go func() {
obj := getCountAndLast(t, "last-topic-message")
require.Greater(t, obj.Count, lastTopicMessage.Count)
lastTopicMessage = obj
wg.Done()
}()
go func() {
obj := getCountAndLast(t, "last-health-check")
require.Greater(t, obj.Count, lastHealthCheck.Count)
lastHealthCheck = obj
wg.Done()
}()
// Service invocation should fail
go func() {
res, status := invokeFoo(t)
require.Contains(t, string(res), "ERR_DIRECT_INVOKE")
require.Greater(t, status, 299)
wg.Done()
}()
wg.Wait()
})
t.Run("after delay, counters aren't increasing", func(t *testing.T) {
// Wait 5 seconds then repeat, expecting the same results for counters
time.Sleep(5 * time.Second)
wg.Add(4)
go func() {
obj := getCountAndLast(t, "last-input-binding")
require.Equal(t, lastInputBinding.Count, obj.Count)
require.Greater(t, *obj.Last, int64(5000))
lastInputBinding = obj
wg.Done()
}()
go func() {
obj := getCountAndLast(t, "last-topic-message")
require.Equal(t, lastTopicMessage.Count, obj.Count)
require.Greater(t, *obj.Last, int64(5000))
lastTopicMessage = obj
wg.Done()
}()
go func() {
obj := getCountAndLast(t, "last-health-check")
require.Greater(t, obj.Count, lastHealthCheck.Count)
require.Less(t, *obj.Last, int64(3000))
lastHealthCheck = obj
wg.Done()
}()
// Service invocation should fail again
go func() {
res, status := invokeFoo(t)
require.Greater(t, status, 299)
require.Contains(t, string(res), "ERR_DIRECT_INVOKE")
wg.Done()
}()
wg.Wait()
})
t.Run("app resumes after health probes pass", func(t *testing.T) {
// Wait another 12 seconds, when everything should have resumed
time.Sleep(12 * time.Second)
wg.Add(4)
go func() {
obj := getCountAndLast(t, "last-input-binding")
require.Greater(t, obj.Count, lastInputBinding.Count)
require.Less(t, *obj.Last, int64(1500)) // Adds .5s to reduce flakiness on slow runners
lastInputBinding = obj
wg.Done()
}()
go func() {
obj := getCountAndLast(t, "last-topic-message")
require.Greater(t, obj.Count, lastTopicMessage.Count)
require.Less(t, *obj.Last, int64(1500)) // Adds .5s to reduce flakiness on slow runners
lastTopicMessage = obj
wg.Done()
}()
go func() {
obj := getCountAndLast(t, "last-health-check")
require.Greater(t, obj.Count, lastHealthCheck.Count)
require.Less(t, *obj.Last, int64(3500)) // Adds .5s to reduce flakiness on slow runners
lastHealthCheck = obj
wg.Done()
}()
// Service invocation works
go func() {
res, status := invokeFoo(t)
require.Equal(t, 200, status)
require.Equal(t, "🤗", string(res))
wg.Done()
}()
wg.Wait()
})
})
}
type countAndLast struct {
// Total number of actions
Count int64 `json:"count"`
// Time since last action, in ms
Last *int64 `json:"last"`
}
|
mikeee/dapr
|
tests/e2e/healthcheck/healthcheck_test.go
|
GO
|
mit
| 10,503 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package hellodapr_e2e
import (
"encoding/json"
"fmt"
"os"
"testing"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
"github.com/stretchr/testify/require"
)
type testCommandRequest struct {
Message string `json:"message,omitempty"`
}
type appResponse struct {
Message string `json:"message,omitempty"`
StartTime int `json:"start_time,omitempty"`
EndTime int `json:"end_time,omitempty"`
}
const numHealthChecks = 60 // Number of times to check for endpoint health per app.
var tr *runner.TestRunner
func TestMain(m *testing.M) {
utils.SetupLogs("hellodapr")
utils.InitHTTPClient(true)
// This test shows how to deploy the multiple test apps, validate the side-car injection
// and validate the response by using test app's service endpoint
// These apps will be deployed for hellodapr test before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: "hellobluedapr",
DaprEnabled: true,
ImageName: "e2e-hellodapr",
Replicas: 1,
IngressEnabled: true,
DaprMemoryLimit: "200Mi",
DaprMemoryRequest: "100Mi",
AppMemoryLimit: "200Mi",
AppMemoryRequest: "100Mi",
},
{
AppName: "hellogreendapr",
DaprEnabled: true,
ImageName: "e2e-hellodapr",
Replicas: 1,
IngressEnabled: true,
DaprMemoryLimit: "200Mi",
DaprMemoryRequest: "100Mi",
AppMemoryLimit: "200Mi",
AppMemoryRequest: "100Mi",
},
{
AppName: "helloenvtestdapr",
DaprEnabled: true,
ImageName: "e2e-hellodapr",
Replicas: 1,
IngressEnabled: true,
DaprMemoryLimit: "200Mi",
DaprMemoryRequest: "100Mi",
AppMemoryLimit: "200Mi",
AppMemoryRequest: "100Mi",
},
}
// Append test apps for Dapr versions N-2 and N-1 if present
// These are used to detect regressions in the control plane
if os.Getenv("DAPR_TEST_N_MINUS_2_IMAGE") != "" {
testApps = append(testApps, kube.AppDescription{
AppName: "hellon2dapr",
DaprEnabled: true,
ImageName: "e2e-hellodapr",
SidecarImage: os.Getenv("DAPR_TEST_N_MINUS_2_IMAGE"),
Replicas: 1,
IngressEnabled: true,
DaprMemoryLimit: "200Mi",
DaprMemoryRequest: "100Mi",
AppMemoryLimit: "200Mi",
AppMemoryRequest: "100Mi",
})
}
if os.Getenv("DAPR_TEST_N_MINUS_1_IMAGE") != "" {
testApps = append(testApps, kube.AppDescription{
AppName: "hellon1dapr",
DaprEnabled: true,
ImageName: "e2e-hellodapr",
SidecarImage: os.Getenv("DAPR_TEST_N_MINUS_1_IMAGE"),
Replicas: 1,
IngressEnabled: true,
DaprMemoryLimit: "200Mi",
DaprMemoryRequest: "100Mi",
AppMemoryLimit: "200Mi",
AppMemoryRequest: "100Mi",
})
}
tr = runner.NewTestRunner("hellodapr", testApps, nil, nil)
os.Exit(tr.Start(m))
}
func TestHelloDapr(t *testing.T) {
helloAppTests := []struct {
testName string
app string
testCommand string
expectedResponse string
condition bool
}{
{
"green dapr",
"hellogreendapr",
"green",
"Hello green dapr!",
true,
},
{
"blue dapr",
"hellobluedapr",
"blue",
"Hello blue dapr!",
true,
},
{
"n minus 2",
"hellon2dapr",
"blue",
"Hello blue dapr!",
os.Getenv("DAPR_TEST_N_MINUS_2_IMAGE") != "",
},
{
"n minus 1",
"hellon1dapr",
"blue",
"Hello blue dapr!",
os.Getenv("DAPR_TEST_N_MINUS_1_IMAGE") != "",
},
{
"envTest dapr",
"helloenvtestdapr",
"envTest",
"3500 50001",
true,
},
}
for _, tt := range helloAppTests {
t.Run(tt.testName, func(t *testing.T) {
if !tt.condition {
t.Skip("Skipped because condition is false")
}
// Get the ingress external url of test app
externalURL := tr.Platform.AcquireAppExternalURL(tt.app)
require.NotEmpty(t, externalURL, "external URL must not be empty")
// Check if test app endpoint is available
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
// Trigger test
body, err := json.Marshal(testCommandRequest{
Message: "Hello Dapr.",
})
require.NoError(t, err)
resp, err := utils.HTTPPost(fmt.Sprintf("%s/tests/%s", externalURL, tt.testCommand), body)
require.NoError(t, err)
var appResp appResponse
err = json.Unmarshal(resp, &appResp)
require.NoError(t, err)
require.Equal(t, tt.expectedResponse, appResp.Message)
})
}
}
func TestScaleReplicas(t *testing.T) {
err := tr.Platform.Scale("hellobluedapr", 3)
require.NoError(t, err, "fails to scale hellobluedapr app to 3 replicas")
}
func TestScaleAndRestartInstances(t *testing.T) {
err := tr.Platform.Scale("hellobluedapr", 3)
require.NoError(t, err, "fails to scale hellobluedapr app to 3 replicas")
err = tr.Platform.Restart("hellobluedapr")
require.NoError(t, err, "fails to restart hellobluedapr pods")
}
|
mikeee/dapr
|
tests/e2e/hellodapr/hellodapr_test.go
|
GO
|
mit
| 5,684 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package hotreloading_tests
import (
"context"
"fmt"
"net/http"
"os"
"testing"
"time"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
commonapi "github.com/dapr/dapr/pkg/apis/common"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
httpendapi "github.com/dapr/dapr/pkg/apis/httpEndpoint/v1alpha1"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var (
tr *runner.TestRunner
)
func TestMain(m *testing.M) {
utils.SetupLogs("hotreloading")
utils.InitHTTPClient(false)
testApps := []kube.AppDescription{
{
AppName: "hotreloading-state",
DaprEnabled: true,
ImageName: "e2e-stateapp",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
Config: "hotreloading",
},
}
tr = runner.NewTestRunner("hotreloading", testApps, nil, nil)
os.Exit(tr.Start(m))
}
func TestState(t *testing.T) {
platform, ok := tr.Platform.(*runner.KubeTestPlatform)
if !ok {
t.Skip("skipping test; only supported on kubernetes")
}
scheme := runtime.NewScheme()
assert.NoError(t, compapi.AddToScheme(scheme))
assert.NoError(t, httpendapi.AddToScheme(scheme))
cl, err := client.New(platform.KubeClient.GetClientConfig(), client.Options{Scheme: scheme})
require.NoError(t, err)
ctx := context.Background()
externalURL := tr.Platform.AcquireAppExternalURL("hotreloading-state")
// Wait for app to be available.
_, err = utils.HTTPGetNTimes(externalURL, 60)
require.NoError(t, err)
const connectionString = `"host=dapr-postgres-postgresql.dapr-tests.svc.cluster.local user=postgres password=example port=5432 connect_timeout=10 database=dapr_test"`
t.Run("Create state Component and save/get state", func(t *testing.T) {
cl.Delete(ctx, &compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "hotreloading-state",
Namespace: kube.DaprTestNamespace,
},
}, &client.DeleteOptions{})
require.NoError(t, cl.Create(ctx, &compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "hotreloading-state",
Namespace: kube.DaprTestNamespace,
},
Scoped: commonapi.Scoped{
Scopes: []string{
"hotreloading-state",
},
},
Spec: compapi.ComponentSpec{
Type: "state.postgres",
Version: "v1",
Metadata: []commonapi.NameValuePair{
{Name: "connectionString", Value: commonapi.DynamicValue{JSON: apiextensionsv1.JSON{Raw: []byte(connectionString)}}},
{Name: "table", Value: commonapi.DynamicValue{JSON: apiextensionsv1.JSON{Raw: []byte(`"hotreloadtable"`)}}},
},
},
}, &client.CreateOptions{}))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
url := fmt.Sprintf("%s/test/http/save/hotreloading-state", externalURL)
_, status, err := utils.HTTPPostWithStatus(url, []byte(`{"states":[{"key":"foo","value":{"data":"LXcgYmFyCg=="}}]}`))
assert.NoError(c, err)
assert.Equal(c, http.StatusNoContent, status)
}, 30*time.Second, 500*time.Millisecond)
url := fmt.Sprintf("%s/test/http/get/hotreloading-state", externalURL)
resp, code, err := utils.HTTPPostWithStatus(url, []byte(`{"states":[{"key":"foo"}]}`))
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, code)
assert.Contains(t, string(resp), `{"states":[{"key":"foo","value":{"data":"LXcgYmFyCg=="},`)
})
t.Run("Update state component to another type and wait for it to become unavailable", func(t *testing.T) {
var comp compapi.Component
require.NoError(t, cl.Get(ctx, client.ObjectKey{Namespace: kube.DaprTestNamespace, Name: "hotreloading-state"}, &comp))
comp.Spec = compapi.ComponentSpec{
Type: "pubsub.in-memory",
Version: "v1",
Metadata: []commonapi.NameValuePair{},
}
require.NoError(t, cl.Update(ctx, &comp))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
url := fmt.Sprintf("%s/test/http/save/hotreloading-state", externalURL)
_, code, err := utils.HTTPPostWithStatus(url, []byte(`{"states":[{"key":"foo","value":{"data":"xyz"}}]}`))
assert.NoError(c, err)
assert.Equal(c, http.StatusBadRequest, code)
}, 30*time.Second, 500*time.Millisecond)
})
t.Run("Update component to be state store again and be available", func(t *testing.T) {
var comp compapi.Component
require.NoError(t, cl.Get(ctx, client.ObjectKey{Namespace: kube.DaprTestNamespace, Name: "hotreloading-state"}, &comp))
comp.Spec = compapi.ComponentSpec{
Type: "state.postgres",
Version: "v1",
Metadata: []commonapi.NameValuePair{
{Name: "connectionString", Value: commonapi.DynamicValue{JSON: apiextensionsv1.JSON{Raw: []byte(connectionString)}}},
{Name: "table", Value: commonapi.DynamicValue{JSON: apiextensionsv1.JSON{Raw: []byte(`"hotreloadtable"`)}}},
},
}
require.NoError(t, cl.Update(ctx, &comp))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
url := fmt.Sprintf("%s/test/http/save/hotreloading-state", externalURL)
_, status, err := utils.HTTPPostWithStatus(url, []byte(`{"states":[{"key":"foo","value":{"data":"LXcgeHl6Cg=="}}]}`))
assert.NoError(c, err)
assert.Equal(c, http.StatusNoContent, status)
}, 30*time.Second, 500*time.Millisecond)
url := fmt.Sprintf("%s/test/http/get/hotreloading-state", externalURL)
resp, code, err := utils.HTTPPostWithStatus(url, []byte(`{"states":[{"key":"foo"}]}`))
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, code)
assert.Contains(t, string(resp), `{"states":[{"key":"foo","value":{"data":"LXcgeHl6Cg=="},`)
})
t.Run("Delete state Component and wait until no longer available", func(t *testing.T) {
cl.Delete(ctx, &compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "hotreloading-state",
Namespace: kube.DaprTestNamespace,
},
}, &client.DeleteOptions{})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
url := fmt.Sprintf("%s/test/http/save/hotreloading-state", externalURL)
_, code, err := utils.HTTPPostWithStatus(url, []byte(`{"states":[{"key":"foo","value":{"data":"LXcgYmFyCg=="}}]}`))
assert.NoError(c, err)
assert.Equal(c, http.StatusInternalServerError, code)
}, 30*time.Second, 500*time.Millisecond)
})
}
|
mikeee/dapr
|
tests/e2e/hotreloading/hotreloading_test.go
|
GO
|
mit
| 6,961 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package injector_e2e
import (
"encoding/json"
"fmt"
"os"
"testing"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
"github.com/stretchr/testify/require"
apiv1 "k8s.io/api/core/v1"
)
const (
appName = "injectorapp"
numHealthChecks = 60 // Number of get calls before starting tests.
)
// requestResponse represents a request or response for the APIs in the app.
type requestResponse struct {
Message string `json:"message,omitempty"`
StartTime int `json:"start_time,omitempty"`
EndTime int `json:"end_time,omitempty"`
}
var tr *runner.TestRunner
func TestMain(m *testing.M) {
utils.SetupLogs(appName)
utils.InitHTTPClient(true)
// These apps will be deployed for injector test before starting actual test
// and will be cleaned up after all tests are finished automatically
comps := []kube.ComponentDescription{
{
Name: "local-secret-store",
TypeName: "secretstores.local.file",
MetaData: map[string]kube.MetadataValue{
"secretsFile": {Raw: `"/tmp/testdata/secrets.json"`},
},
Scopes: []string{appName},
},
{
Name: "secured-binding",
TypeName: "bindings.http",
MetaData: map[string]kube.MetadataValue{
"url": {Raw: `"https://localhost:3001"`},
},
Scopes: []string{appName},
},
}
testApps := []kube.AppDescription{
{
AppName: appName,
DaprEnabled: true,
ImageName: fmt.Sprintf("e2e-%s", appName),
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
DaprMemoryLimit: "200Mi",
DaprMemoryRequest: "100Mi",
AppMemoryLimit: "200Mi",
AppMemoryRequest: "100Mi",
DaprVolumeMounts: "storage-volume:/tmp/testdata/",
DaprEnv: "SSL_CERT_DIR=/tmp/testdata/certs",
Volumes: []apiv1.Volume{
{
Name: "storage-volume",
VolumeSource: apiv1.VolumeSource{
EmptyDir: &apiv1.EmptyDirVolumeSource{},
},
},
},
AppVolumeMounts: []apiv1.VolumeMount{
{
Name: "storage-volume",
MountPath: "/tmp/testdata/",
ReadOnly: true,
},
},
InitContainers: []apiv1.Container{
{
Name: fmt.Sprintf("%s-init", appName),
Image: runner.BuildTestImageName(fmt.Sprintf("e2e-%s-init", appName)),
ImagePullPolicy: apiv1.PullAlways,
VolumeMounts: []apiv1.VolumeMount{
{
Name: "storage-volume",
MountPath: "/tmp/testdata",
},
},
},
},
},
}
tr = runner.NewTestRunner(appName, testApps, comps, nil)
os.Exit(tr.Start(m))
}
func TestDaprVolumeMount(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL(appName)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
// setup
url := fmt.Sprintf("%s/tests/testVolumeMount", externalURL)
// act
resp, statusCode, err := utils.HTTPPostWithStatus(url, []byte{})
// assert
require.NoError(t, err)
var appResp requestResponse
err = json.Unmarshal(resp, &appResp)
require.NoError(t, err)
require.Equal(t, 200, statusCode)
require.Equal(t, "secret-value", appResp.Message)
}
func TestDaprSslCertInstallation(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL(appName)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
// setup
url := fmt.Sprintf("%s/tests/testBinding", externalURL)
// act
_, statusCode, err := utils.HTTPPostWithStatus(url, []byte{})
// assert
require.NoError(t, err)
require.Equal(t, 200, statusCode)
}
|
mikeee/dapr
|
tests/e2e/injector/injector_test.go
|
GO
|
mit
| 4,591 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package job
import (
"encoding/json"
"fmt"
"log"
"os"
"testing"
"time"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
"github.com/stretchr/testify/require"
)
var tr *runner.TestRunner
type callSubscriberMethodRequest struct {
RemoteApp string `json:"remoteApp"`
Protocol string `json:"protocol"`
Method string `json:"method"`
}
// data returned from the subscriber app.
type receivedMessagesResponse struct {
ReceivedByTopicJob []string `json:"pubsub-job-topic"`
}
const (
receiveMessageRetries = 25
publisherAppName = "job-publisher"
subscriberAppName = "job-subscriber"
)
func TestMain(m *testing.M) {
utils.SetupLogs("job")
utils.InitHTTPClient(true)
// These apps will be deployed for hellodapr test before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: subscriberAppName,
DaprEnabled: true,
ImageName: "e2e-pubsub-subscriber",
Replicas: 1,
IngressEnabled: true,
},
{
AppName: publisherAppName,
DaprEnabled: true,
ImageName: "e2e-job-publisher",
Replicas: 1,
IngressEnabled: false,
IsJob: true,
},
}
tr = runner.NewTestRunner("job", testApps, nil, nil)
os.Exit(tr.Start(m))
}
func TestJobPublishMessage(t *testing.T) {
// Get the ingress external url of test app
externalURL := tr.Platform.AcquireAppExternalURL(subscriberAppName)
require.NotEmpty(t, externalURL, "external URL must not be empty")
// this is the subscribe app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/getMessages", externalURL)
log.Printf("Getting messages received by subscriber using url %s", url)
request := callSubscriberMethodRequest{
RemoteApp: subscriberAppName,
Protocol: "http",
Method: "getMessages",
}
rawReq, _ := json.Marshal(request)
var appResp receivedMessagesResponse
for retryCount := 0; retryCount < receiveMessageRetries; retryCount++ {
resp, err := utils.HTTPPost(url, rawReq)
if err != nil {
continue
}
err = json.Unmarshal(resp, &appResp)
if err != nil {
continue
}
log.Printf("Subscriber receieved %d messages on pubsub-job-topic-http", len(appResp.ReceivedByTopicJob))
if len(appResp.ReceivedByTopicJob) == 0 {
log.Printf("No message received, retrying.")
time.Sleep(2 * time.Second)
} else {
break
}
}
require.Len(t, appResp.ReceivedByTopicJob, 1)
require.Equal(t, "message-from-job", appResp.ReceivedByTopicJob[0])
}
|
mikeee/dapr
|
tests/e2e/job/job_test.go
|
GO
|
mit
| 3,198 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package metadata_e2e
import (
"encoding/json"
"fmt"
"log"
"os"
"testing"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
)
var tr *runner.TestRunner
const (
// Number of get calls before starting tests.
numHealthChecks = 60
appName = "metadataapp" // App name in Dapr.
)
type mockMetadata struct {
ID string `json:"id"`
ActiveActorsCount []activeActorsCount `json:"actors"`
Extended map[string]string `json:"extended"`
RegisteredComponents []mockRegisteredComponent `json:"components"`
EnabledFeatures []string `json:"enabledFeatures"`
}
type activeActorsCount struct {
Type string `json:"type"`
Count int `json:"count"`
}
type mockRegisteredComponent struct {
Name string `json:"name"`
Type string `json:"type"`
Version string `json:"version"`
Capabilities []string `json:"capabilities"`
}
func testSetMetadata(t *testing.T, protocol, metadataAppExternalURL string) {
t.Log("Setting sidecar metadata")
url := fmt.Sprintf("%s/test/%s/set", metadataAppExternalURL, protocol)
resp, err := utils.HTTPPost(url, []byte(`{"key":"newkey","value":"newvalue"}`))
require.NoError(t, err)
require.NotEmpty(t, resp, "response must not be empty!")
}
func testGetMetadata(t *testing.T, protocol, metadataAppExternalURL string) {
t.Log("Getting sidecar metadata")
url := fmt.Sprintf("%s/test/%s/get", metadataAppExternalURL, protocol)
resp, err := utils.HTTPPost(url, nil)
require.NoError(t, err)
require.NotEmpty(t, resp, "response must not be empty!")
var metadata mockMetadata
err = json.Unmarshal(resp, &metadata)
require.NoError(t, err)
for _, comp := range metadata.RegisteredComponents {
require.NotEmpty(t, comp.Name, "component name must not be empty")
require.NotEmpty(t, comp.Type, "component type must not be empty")
require.True(t, len(comp.Capabilities) >= 0, "component capabilities key must be present!")
}
require.NotEmpty(t, metadata.Extended)
require.NotEmpty(t, metadata.Extended["daprRuntimeVersion"])
require.Equal(t, "newvalue", metadata.Extended["newkey"])
require.Contains(t, metadata.EnabledFeatures, "IsEnabled")
require.NotContains(t, metadata.EnabledFeatures, "NotEnabled")
}
func TestMain(m *testing.M) {
utils.SetupLogs(appName)
utils.InitHTTPClient(true)
// These apps will be deployed before starting actual test
// and will be cleaned up after all tests are finished automatically
testApp := kube.AppDescription{
AppName: appName,
DaprEnabled: true,
ImageName: "e2e-metadata",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
Config: "previewconfig",
}
if utils.TestTargetOS() != "windows" {
// On Linux, we use Unix Domain Sockets for the servers
testApp.UnixDomainSocketPath = "/var/dapr/"
testApp.AppEnv = map[string]string{
"DAPR_GRPC_SOCKET_ADDR": "/var/dapr/dapr-" + appName + "-grpc.socket",
"DAPR_HTTP_SOCKET_ADDR": "/var/dapr/dapr-" + appName + "-http.socket",
}
}
testApps := []kube.AppDescription{testApp}
log.Printf("Creating TestRunner")
tr = runner.NewTestRunner("metadatatest", testApps, nil, nil)
log.Printf("Starting TestRunner")
os.Exit(tr.Start(m))
}
func TestMetadata(t *testing.T) {
metadataAppExternalURL := tr.Platform.AcquireAppExternalURL(appName)
require.NotEmpty(t, metadataAppExternalURL, "metadataAppExternalURL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(metadataAppExternalURL, numHealthChecks)
require.NoError(t, err)
t.Run("HTTP", func(t *testing.T) {
testSetMetadata(t, "http", metadataAppExternalURL)
testGetMetadata(t, "http", metadataAppExternalURL)
})
t.Run("gRPC", func(t *testing.T) {
testSetMetadata(t, "grpc", metadataAppExternalURL)
testGetMetadata(t, "grpc", metadataAppExternalURL)
})
}
|
mikeee/dapr
|
tests/e2e/metadata/metadata_test.go
|
GO
|
mit
| 4,697 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package metrics_e2e
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"testing"
commonv1pb "github.com/dapr/dapr/pkg/proto/common/v1"
pb "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
io_prometheus_client "github.com/prometheus/client_model/go"
"github.com/prometheus/common/expfmt"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type testCommandRequest struct {
Message string `json:"message,omitempty"`
}
const numHealthChecks = 60 // Number of times to check for endpoint health per app.
var tr *runner.TestRunner
func TestMain(m *testing.M) {
utils.SetupLogs("metrics")
utils.InitHTTPClient(false)
// This test shows how to deploy the multiple test apps, validate the side-car injection
// and validate the response by using test app's service endpoint
// These apps will be deployed for hellodapr test before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: "httpmetrics",
DaprEnabled: true,
ImageName: "e2e-hellodapr",
Config: "metrics-config",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
},
{
AppName: "grpcmetrics",
DaprEnabled: true,
ImageName: "e2e-stateapp",
Config: "metrics-config",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
},
{
AppName: "disabledmetric",
Config: "disable-telemetry",
DaprEnabled: true,
ImageName: "e2e-hellodapr",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
},
}
tr = runner.NewTestRunner("metrics", testApps, nil, nil)
os.Exit(tr.Start(m))
}
type testCase struct {
name string
app string
protocol string
action func(t *testing.T, app string, n, port int)
actionInvokes int
evaluate func(t *testing.T, app string, res *http.Response)
}
var metricsTests = []testCase{
{
"http metrics",
"httpmetrics",
"http",
invokeDaprHTTP,
3,
testHTTPMetrics,
},
{
"grpc metrics",
"grpcmetrics",
"grpc",
invokeDaprGRPC,
10,
testGRPCMetrics,
},
{
"metric off",
"disabledmetric",
"http",
invokeDaprHTTP,
3,
testMetricDisabled,
},
}
func TestMetrics(t *testing.T) {
for _, tt := range metricsTests {
// Open connection to the app on the dapr port and metrics port.
// These will only be closed when the test runner is disposed after
// all tests are run.
var targetDaprPort int
if tt.protocol == "http" {
targetDaprPort = 3500
} else if tt.protocol == "grpc" {
targetDaprPort = 50001
}
localPorts, err := tr.Platform.PortForwardToApp(tt.app, targetDaprPort, 9090)
require.NoError(t, err)
// Port order is maintained when opening connection
daprPort := localPorts[0]
metricsPort := localPorts[1]
t.Run(tt.name, func(t *testing.T) {
// Perform an action n times using the Dapr API
tt.action(t, tt.app, tt.actionInvokes, daprPort)
// Get the metrics from the metrics endpoint
res, err := utils.HTTPGetRawNTimes(fmt.Sprintf("http://localhost:%v", metricsPort), numHealthChecks)
require.NoError(t, err)
defer func() {
// Drain before closing
_, _ = io.Copy(io.Discard, res.Body)
res.Body.Close()
}()
// Evaluate the metrics are as expected
tt.evaluate(t, tt.app, res)
})
}
}
func invokeDaprHTTP(t *testing.T, app string, n, daprPort int) {
body, err := json.Marshal(testCommandRequest{
Message: "Hello Dapr.",
})
require.NoError(t, err)
for i := 0; i < n; i++ {
// We don't evaluate the response here as we're only testing the metrics
_, err = utils.HTTPPost(fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/tests/green", daprPort, app), body)
require.NoError(t, err)
}
}
func testHTTPMetrics(t *testing.T, app string, res *http.Response) {
require.NotNil(t, res)
foundMetric := findHTTPMetricFromPrometheus(t, app, res)
// Check metric was found
require.True(t, foundMetric)
}
func testMetricDisabled(t *testing.T, app string, res *http.Response) {
require.NotNil(t, res)
foundMetric := findHTTPMetricFromPrometheus(t, app, res)
// Check metric was found
require.False(t, foundMetric)
}
func findHTTPMetricFromPrometheus(t *testing.T, app string, res *http.Response) (foundMetric bool) {
rfmt := expfmt.ResponseFormat(res.Header)
require.NotEqual(t, rfmt, expfmt.FmtUnknown)
decoder := expfmt.NewDecoder(res.Body, rfmt)
// This test will loop through each of the metrics and look for a specifc
// metric `dapr_http_server_request_count`.
var foundHealthz, foundInvocation bool
for {
mf := &io_prometheus_client.MetricFamily{}
err := decoder.Decode(mf)
if err == io.EOF {
break
}
require.NoError(t, err)
if strings.ToLower(mf.GetName()) == "dapr_http_server_request_count" {
foundMetric = true
for _, m := range mf.GetMetric() {
if m == nil {
continue
}
count := m.GetCounter()
// check metrics with expected method exists
for _, l := range m.GetLabel() {
if l == nil {
continue
}
val := l.GetValue()
switch strings.ToLower(l.GetName()) {
case "app_id":
assert.Equal(t, "httpmetrics", val)
case "method":
if count.GetValue() > 0 {
switch val {
case "Healthz":
foundHealthz = true
case "InvokeService/httpmetrics":
foundInvocation = true
}
}
}
}
}
}
}
if foundMetric {
require.True(t, foundHealthz)
require.True(t, foundInvocation)
}
return foundMetric
}
func invokeDaprGRPC(t *testing.T, app string, n, daprPort int) {
daprAddress := fmt.Sprintf("localhost:%d", daprPort)
conn, err := grpc.Dial(daprAddress, grpc.WithTransportCredentials(insecure.NewCredentials()))
require.NoError(t, err)
defer conn.Close()
client := pb.NewDaprClient(conn)
for i := 0; i < n; i++ {
_, err = client.SaveState(context.Background(), &pb.SaveStateRequest{
StoreName: "statestore",
States: []*commonv1pb.StateItem{
{
Key: "myKey",
Value: []byte("My State"),
},
},
})
require.NoError(t, err)
}
}
func testGRPCMetrics(t *testing.T, app string, res *http.Response) {
require.NotNil(t, res)
rfmt := expfmt.ResponseFormat(res.Header)
require.NotEqual(t, rfmt, expfmt.FmtUnknown)
decoder := expfmt.NewDecoder(res.Body, rfmt)
// This test will loop through each of the metrics and look for a specifc
// metric `dapr_grpc_io_server_completed_rpcs`. This metric will exist for
// multiple `grpc_server_method` labels, therefore, we loop through the labels
// to find the instance that has `grpc_server_method="SaveState". Once we
// find the desired metric entry, we check the metric's value is as expected.`
var foundMetric bool
var foundMethod bool
for {
mf := &io_prometheus_client.MetricFamily{}
err := decoder.Decode(mf)
if err == io.EOF {
break
}
require.NoError(t, err)
if strings.EqualFold(mf.GetName(), "dapr_grpc_io_server_completed_rpcs") {
foundMetric = true
for _, m := range mf.GetMetric() {
if m == nil {
continue
}
// Check path label is as expected
for _, l := range m.GetLabel() {
if l == nil {
continue
}
if strings.EqualFold(l.GetName(), "grpc_server_method") {
if strings.EqualFold(l.GetValue(), "/dapr.proto.runtime.v1.Dapr/SaveState") {
foundMethod = true
// Check value is as expected
require.Equal(t, 10, int(m.GetCounter().GetValue()))
break
}
}
}
}
}
}
// Check metric was found
require.True(t, foundMetric)
// Check path label was found
require.True(t, foundMethod)
}
|
mikeee/dapr
|
tests/e2e/metrics/metrics_test.go
|
GO
|
mit
| 8,512 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package middleware_e2e
import (
"encoding/json"
"fmt"
"os"
"testing"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
"github.com/stretchr/testify/require"
)
type testResponse struct {
Input string `json:"input"`
Output string `json:"output"`
}
var tr *runner.TestRunner
func getExternalURL(t *testing.T, appName string) string {
externalURL := tr.Platform.AcquireAppExternalURL(appName)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
return externalURL
}
func TestMain(m *testing.M) {
utils.SetupLogs("middleware")
utils.InitHTTPClient(true)
// These apps will be deployed before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: "middlewareapp",
DaprEnabled: true,
ImageName: "e2e-middleware",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
Config: "pipeline",
},
{
AppName: "app-channel-middleware",
DaprEnabled: true,
ImageName: "e2e-middleware",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
Config: "app-channel-pipeline",
},
{
AppName: "no-middleware",
DaprEnabled: true,
ImageName: "e2e-middleware",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
},
}
tr = runner.NewTestRunner("middleware", testApps, nil, nil)
os.Exit(tr.Start(m))
}
func TestSimpleMiddleware(t *testing.T) {
middlewareURL := getExternalURL(t, "middlewareapp")
appMiddlewareURL := getExternalURL(t, "app-channel-middleware")
noMiddlewareURL := getExternalURL(t, "no-middleware")
// Makes the test wait for the apps and load balancers to be ready
err := utils.HealthCheckApps(middlewareURL, noMiddlewareURL, appMiddlewareURL)
require.NoError(t, err, "Health checks failed")
t.Logf("middlewareURL is '%s'", middlewareURL)
t.Logf("appMiddlewareURL is '%s'", appMiddlewareURL)
t.Logf("noMiddlewareURL is '%s'", noMiddlewareURL)
t.Run("test_basicMiddleware", func(t *testing.T) {
resp, status, err := utils.HTTPPostWithStatus(fmt.Sprintf("http://%s/test/logCall/%s", middlewareURL, "middlewareapp"), []byte{})
require.NoError(t, err)
require.Equal(t, 200, status)
require.NotNil(t, resp)
var results testResponse
json.Unmarshal(resp, &results)
require.Equal(t, "hello", results.Input)
require.Equal(t, "HELLO", results.Output)
})
t.Run("test_basicAppChannelMiddleware", func(t *testing.T) {
resp, status, err := utils.HTTPPostWithStatus(fmt.Sprintf("http://%s/test/logCall/%s", appMiddlewareURL, "app-channel-middleware"), []byte{})
require.NoError(t, err)
require.Equal(t, 200, status)
require.NotNil(t, resp)
var results testResponse
json.Unmarshal(resp, &results)
require.Equal(t, "hello", results.Input)
require.Equal(t, "HELLO", results.Output)
})
t.Run("test_noMiddleware", func(t *testing.T) {
resp, status, err := utils.HTTPPostWithStatus(fmt.Sprintf("http://%s/test/logCall/%s", noMiddlewareURL, "no-middleware"), []byte{})
require.NoError(t, err)
require.Equal(t, 200, status)
require.NotNil(t, resp)
var results testResponse
json.Unmarshal(resp, &results)
require.Equal(t, "hello", results.Input)
require.Equal(t, "hello", results.Output)
})
}
|
mikeee/dapr
|
tests/e2e/middleware/middleware_test.go
|
GO
|
mit
| 3,995 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package hellodapr_e2e
import (
"log"
"os"
"testing"
"github.com/stretchr/testify/require"
"k8s.io/apimachinery/pkg/api/errors"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
)
const (
appName = "hellodapr"
daprServiceName = appName + "-dapr"
appIDAnnotationKey = "dapr.io/app-id"
)
var tr *runner.TestRunner
func TestMain(m *testing.M) {
utils.SetupLogs(appName)
utils.InitHTTPClient(true)
// These apps will be deployed for hellodapr test before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: appName,
DaprEnabled: true,
ImageName: "e2e-hellodapr",
Replicas: 1,
IngressEnabled: false,
MetricsEnabled: true,
DaprMemoryLimit: "200Mi",
DaprMemoryRequest: "100Mi",
AppMemoryLimit: "200Mi",
AppMemoryRequest: "100Mi",
},
}
tr = runner.NewTestRunner(appName, testApps, nil, nil)
code := tr.Start(m)
for _, app := range testApps {
_, err := tr.Platform.GetService(daprServiceName)
if err == nil {
log.Fatalf("the dapr service %s still exists after app %s deleted", daprServiceName, app.AppName)
} else if !errors.IsNotFound(err) {
log.Fatalf("failed to get dapr service %s, err: %v", daprServiceName, err)
}
}
os.Exit(code)
}
func TestHelloDapr(t *testing.T) {
service, err := tr.Platform.GetService(daprServiceName)
require.NoError(t, err)
require.Equal(t, appName, service.Annotations[appIDAnnotationKey])
}
|
mikeee/dapr
|
tests/e2e/operator/operator_test.go
|
GO
|
mit
| 2,210 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package pubsubapp_e2e
import (
"encoding/json"
"fmt"
"log"
"math/rand"
"net/http"
"os"
"sort"
"strings"
"testing"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/ratelimit"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
apiv1 "k8s.io/api/core/v1"
)
var tr *runner.TestRunner
const (
// used as the exclusive max of a random number that is used as a suffix to the first message sent. Each subsequent message gets this number+1.
// This is random so the first message name is not the same every time.
randomOffsetMax = 49
numberOfMessagesToPublish = 60
publishRateLimitRPS = 25
receiveMessageRetries = 5
metadataPrefix = "metadata."
publisherAppName = "pubsub-publisher"
subscriberAppName = "pubsub-subscriber"
publisherPluggableAppName = "pubsub-publisher-pluggable"
subscriberPluggableAppName = "pubsub-subscriber-pluggable"
redisPubSubPluggableApp = "e2e-pluggable_redis-pubsub"
PubSubEnvVar = "DAPR_TEST_PUBSUB_NAME"
PubSubPluggableName = "pluggable-messagebus"
pubsubKafka = "kafka-messagebus"
bulkPubsubMetaKey = "bulkPublishPubsubName"
)
var (
offset int
pubsubName string
)
// sent to the publisher app, which will publish data to dapr.
type publishCommand struct {
ReqID string `json:"reqID"`
ContentType string `json:"contentType"`
Topic string `json:"topic"`
Data interface{} `json:"data"`
Protocol string `json:"protocol"`
Metadata map[string]string `json:"metadata"`
}
type callSubscriberMethodRequest struct {
ReqID string `json:"reqID"`
RemoteApp string `json:"remoteApp"`
Protocol string `json:"protocol"`
Method string `json:"method"`
}
// data returned from the subscriber app.
type receivedMessagesResponse struct {
ReceivedByTopicA []string `json:"pubsub-a-topic"`
ReceivedByTopicB []string `json:"pubsub-b-topic"`
ReceivedByTopicC []string `json:"pubsub-c-topic"`
ReceivedByTopicBulk []string `json:"pubsub-bulk-topic"`
ReceivedByTopicRawBulk []string `json:"pubsub-raw-bulk-topic"`
ReceivedByTopicCEBulk []string `json:"pubsub-ce-bulk-topic"`
ReceivedByTopicDefBulk []string `json:"pubsub-def-bulk-topic"`
ReceivedByTopicRaw []string `json:"pubsub-raw-topic"`
ReceivedByTopicDead []string `json:"pubsub-dead-topic"`
ReceivedByTopicDeadLetter []string `json:"pubsub-deadletter-topic"`
}
type cloudEvent struct {
ID string `json:"id"`
Type string `json:"type"`
DataContentType string `json:"datacontenttype"`
Data string `json:"data"`
}
// checks is publishing is working.
func publishHealthCheck(publisherExternalURL string) error {
commandBody := publishCommand{
ContentType: "application/json",
Topic: "pubsub-healthcheck-topic-http",
Protocol: "http",
Data: "health check",
}
// this is the publish app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/tests/publish", publisherExternalURL)
return backoff.Retry(func() error {
commandBody.ReqID = "c-" + uuid.New().String()
jsonValue, _ := json.Marshal(commandBody)
_, err := postSingleMessage(url, jsonValue)
return err
}, backoff.WithMaxRetries(backoff.NewConstantBackOff(5*time.Second), 10))
}
func setMetadataBulk(url string, reqMeta map[string]string) string {
qArgs := []string{}
for k, v := range reqMeta {
qArg := fmt.Sprintf("%s%s=%s", metadataPrefix, k, v)
qArgs = append(qArgs, qArg)
}
concatenated := strings.Join(qArgs, "&")
log.Printf("setting query args %s", concatenated)
return url + "?" + concatenated
}
// sends messages to the publisher app. The publisher app does the actual publish.
func sendToPublisherBulk(t *testing.T, publisherExternalURL string, topic string, protocol string, reqMetadata map[string]string, cloudEventType string) ([]string, error) {
var individualMessages []string
commands := make([]publishCommand, numberOfMessagesToPublish)
for i := 0; i < numberOfMessagesToPublish; i++ {
contentType := "text/plain"
if cloudEventType != "" {
contentType = "application/cloudevents+json"
}
commandBody := publishCommand{
ContentType: contentType,
Topic: fmt.Sprintf("%s-%s", topic, protocol),
Protocol: protocol,
}
// create and marshal command
messageID := fmt.Sprintf("msg-%s-%s-%04d", strings.TrimSuffix(topic, "-topic"), protocol, i)
var messageData interface{} = messageID
if cloudEventType != "" {
messageData = &cloudEvent{
ID: messageID,
Type: cloudEventType,
DataContentType: "text/plain",
Data: messageID,
}
}
commandBody.ReqID = "c-" + uuid.New().String()
commandBody.Data = messageData
commands[i] = commandBody
individualMessages = append(individualMessages, messageID)
}
jsonValue, err := json.Marshal(commands)
// this is the publish app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/tests/bulkpublish", publisherExternalURL)
url = setMetadataBulk(url, reqMetadata)
// debuggability - trace info about the first message. don't trace others so it doesn't flood log.
log.Printf("Sending bulk publish, app at url %s and body '%s', this log will not print for subsequent messages for same topic", url, jsonValue)
statusCode, err := postSingleMessage(url, jsonValue)
// return on an unsuccessful publish
if statusCode != http.StatusNoContent {
return nil, err
}
// return successfully sent individual messages
return individualMessages, nil
}
// sends messages to the publisher app. The publisher app does the actual publish.
func sendToPublisher(t *testing.T, publisherExternalURL string, topic string, protocol string, metadata map[string]string, cloudEventType string) ([]string, error) {
var sentMessages []string
contentType := "application/json"
if cloudEventType != "" {
contentType = "application/cloudevents+json"
}
commandBody := publishCommand{
ContentType: contentType,
Topic: fmt.Sprintf("%s-%s", topic, protocol),
Protocol: protocol,
Metadata: metadata,
}
rateLimit := ratelimit.New(publishRateLimitRPS)
for i := offset; i < offset+numberOfMessagesToPublish; i++ {
// create and marshal message
messageID := fmt.Sprintf("msg-%s-%s-%04d", strings.TrimSuffix(topic, "-topic"), protocol, i)
var messageData interface{} = messageID
if cloudEventType != "" {
messageData = &cloudEvent{
ID: messageID,
Type: cloudEventType,
DataContentType: "text/plain",
Data: messageID,
}
}
commandBody.ReqID = "c-" + uuid.New().String()
commandBody.Data = messageData
jsonValue, err := json.Marshal(commandBody)
require.NoError(t, err)
// this is the publish app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/tests/publish", publisherExternalURL)
// debuggability - trace info about the first message. don't trace others so it doesn't flood log.
if i == offset {
log.Printf("Sending first publish app at url %s and body '%s', this log will not print for subsequent messages for same topic", url, jsonValue)
}
rateLimit.Take()
statusCode, err := postSingleMessage(url, jsonValue)
// return on an unsuccessful publish
if statusCode != http.StatusNoContent {
return nil, err
}
// save successful message
sentMessages = append(sentMessages, messageID)
}
return sentMessages, nil
}
func testPublishBulk(t *testing.T, publisherExternalURL string, protocol string) receivedMessagesResponse {
meta := map[string]string{
bulkPubsubMetaKey: pubsubKafka,
}
sentTopicBulkMessages, err := sendToPublisherBulk(t, publisherExternalURL, "pubsub-bulk-topic", protocol, meta, "")
require.NoError(t, err)
sentTopicBulkCEMessages, err := sendToPublisherBulk(t, publisherExternalURL, "pubsub-ce-bulk-topic", protocol, meta, "myevent.CE")
require.NoError(t, err)
meta = map[string]string{
bulkPubsubMetaKey: pubsubKafka,
"rawPayload": "true",
}
sentTopicBulkRawMessages, err := sendToPublisherBulk(t, publisherExternalURL, "pubsub-raw-bulk-topic", protocol, meta, "")
require.NoError(t, err)
// empty pubsub will default to existing pubsub via redis
sentTopicBulkDefMessages, err := sendToPublisherBulk(t, publisherExternalURL, "pubsub-def-bulk-topic", protocol, nil, "myevent.CE")
require.NoError(t, err)
return receivedMessagesResponse{
ReceivedByTopicBulk: sentTopicBulkMessages,
ReceivedByTopicRawBulk: sentTopicBulkRawMessages,
ReceivedByTopicCEBulk: sentTopicBulkCEMessages,
ReceivedByTopicDefBulk: sentTopicBulkDefMessages,
}
}
func testPublish(t *testing.T, publisherExternalURL string, protocol string) receivedMessagesResponse {
sentTopicDeadMessages, err := sendToPublisher(t, publisherExternalURL, "pubsub-dead-topic", protocol, nil, "")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
sentTopicAMessages, err := sendToPublisher(t, publisherExternalURL, "pubsub-a-topic", protocol, nil, "")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
sentTopicBMessages, err := sendToPublisher(t, publisherExternalURL, "pubsub-b-topic", protocol, nil, "")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
sentTopicCMessages, err := sendToPublisher(t, publisherExternalURL, "pubsub-c-topic", protocol, nil, "")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
metadata := map[string]string{
"rawPayload": "true",
}
sentTopicRawMessages, err := sendToPublisher(t, publisherExternalURL, "pubsub-raw-topic", protocol, metadata, "")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
return receivedMessagesResponse{
ReceivedByTopicA: sentTopicAMessages,
ReceivedByTopicB: sentTopicBMessages,
ReceivedByTopicC: sentTopicCMessages,
ReceivedByTopicRaw: sentTopicRawMessages,
ReceivedByTopicDead: sentTopicDeadMessages,
ReceivedByTopicDeadLetter: sentTopicDeadMessages,
}
}
func testDropToDeadLetter(t *testing.T, publisherExternalURL, subscriberExternalURL, _, subscriberAppName, protocol string) string {
setDesiredResponse(t, subscriberAppName, "drop", publisherExternalURL, protocol)
callInitialize(t, subscriberAppName, publisherExternalURL, protocol)
sentTopicDeadMessages, err := sendToPublisher(t, publisherExternalURL, "pubsub-dead-topic", protocol, nil, "")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
sentTopicNormal, err := sendToPublisher(t, publisherExternalURL, "pubsub-a-topic", protocol, nil, "")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
time.Sleep(5 * time.Second)
received := receivedMessagesResponse{
ReceivedByTopicA: sentTopicNormal,
ReceivedByTopicB: []string{},
ReceivedByTopicC: []string{},
ReceivedByTopicRaw: []string{},
ReceivedByTopicDead: sentTopicDeadMessages,
ReceivedByTopicDeadLetter: sentTopicDeadMessages,
}
validateMessagesReceivedBySubscriber(t, publisherExternalURL, subscriberAppName, protocol, true, received)
return subscriberExternalURL
}
func postSingleMessage(url string, data []byte) (int, error) {
// HTTPPostWithStatus by default sends with content-type application/json
start := time.Now()
body, statusCode, err := utils.HTTPPostWithStatus(url, data)
if err != nil {
log.Printf("Publish failed with error=%s (response=%s) (request=%s) (duration=%s)", err.Error(), string(body), string(data), utils.FormatDuration(time.Since(start)))
return http.StatusInternalServerError, err
}
if (statusCode != http.StatusOK) && (statusCode != http.StatusNoContent) {
log.Printf("publish failed with StatusCode=%d (response=%s) (request=%s) (duration=%s)", statusCode, string(body), string(data), utils.FormatDuration(time.Since(start)))
err = fmt.Errorf("publish failed with StatusCode=%d (response=%s) (request=%s) (duration=%s)", statusCode, string(body), string(data), utils.FormatDuration(time.Since(start)))
}
return statusCode, err
}
func testBulkPublishSuccessfully(t *testing.T, publisherExternalURL, subscriberExternalURL, _, subscriberAppName, protocol string) string {
// set to respond with success
setDesiredResponse(t, subscriberAppName, "success", publisherExternalURL, protocol)
log.Printf("Test bulkPublish and normal subscribe success flow")
sentMessages := testPublishBulk(t, publisherExternalURL, protocol)
time.Sleep(5 * time.Second)
validateBulkMessagesReceivedBySubscriber(t, publisherExternalURL, subscriberAppName, protocol, sentMessages)
return subscriberExternalURL
}
func testPublishSubscribeSuccessfully(t *testing.T, publisherExternalURL, subscriberExternalURL, _, subscriberAppName, protocol string) string {
// set to respond with success
setDesiredResponse(t, subscriberAppName, "success", publisherExternalURL, protocol)
log.Print("Test publish subscribe success flow")
sentMessages := testPublish(t, publisherExternalURL, protocol)
time.Sleep(5 * time.Second)
validateMessagesReceivedBySubscriber(t, publisherExternalURL, subscriberAppName, protocol, false, sentMessages)
return subscriberExternalURL
}
func testPublishWithoutTopic(t *testing.T, publisherExternalURL, subscriberExternalURL, _, _, protocol string) string {
log.Print("Test publish without topic")
commandBody := publishCommand{
ReqID: "c-" + uuid.New().String(),
Protocol: protocol,
}
commandBody.Data = "unsuccessful message"
jsonValue, err := json.Marshal(commandBody)
require.NoError(t, err)
// this is the publish app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/tests/publish", publisherExternalURL)
// debuggability - trace info about the first message. don't trace others so it doesn't flood log.
log.Printf("Sending first publish app at url %s and body '%s', this log will not print for subsequent messages for same topic", url, jsonValue)
statusCode, err := postSingleMessage(url, jsonValue)
require.Error(t, err)
// without topic, response should be 404
require.Equal(t, http.StatusNotFound, statusCode)
return subscriberExternalURL
}
func testValidateRedeliveryOrEmptyJSON(t *testing.T, publisherExternalURL, subscriberExternalURL, subscriberResponse, subscriberAppName, protocol string) string {
log.Printf("Set subscriber to respond with %s\n", subscriberResponse)
log.Println("Initialize the sets for this scenario ...")
callInitialize(t, subscriberAppName, publisherExternalURL, protocol)
// set to respond with specified subscriber response
setDesiredResponse(t, subscriberAppName, subscriberResponse, publisherExternalURL, protocol)
sentMessages := testPublish(t, publisherExternalURL, protocol)
if subscriberResponse == "empty-json" {
// on empty-json response case immediately validate the received messages
time.Sleep(10 * time.Second)
validateMessagesReceivedBySubscriber(t, publisherExternalURL, subscriberAppName, protocol, false, sentMessages)
callInitialize(t, subscriberAppName, publisherExternalURL, protocol)
} else {
// Sleep a few seconds to ensure there's time for all messages to be delivered at least once, so if they have to be sent to the DLQ, they can be before we change the desired response status
time.Sleep(5 * time.Second)
}
// set to respond with success
setDesiredResponse(t, subscriberAppName, "success", publisherExternalURL, protocol)
if subscriberResponse == "empty-json" {
// validate that there is no redelivery of messages
log.Printf("Validating no redelivered messages...")
time.Sleep(30 * time.Second)
validateMessagesReceivedBySubscriber(t, publisherExternalURL, subscriberAppName, protocol, false, receivedMessagesResponse{
// empty string slices
ReceivedByTopicA: []string{},
ReceivedByTopicB: []string{},
ReceivedByTopicC: []string{},
ReceivedByTopicRaw: []string{},
ReceivedByTopicDead: []string{},
})
} else if subscriberResponse == "error" {
log.Printf("Validating redelivered messages...")
time.Sleep(30 * time.Second)
validateMessagesReceivedBySubscriber(t, publisherExternalURL, subscriberAppName, protocol, true, sentMessages)
} else {
// validate redelivery of messages
log.Printf("Validating redelivered messages...")
time.Sleep(30 * time.Second)
validateMessagesReceivedBySubscriber(t, publisherExternalURL, subscriberAppName, protocol, false, sentMessages)
}
return subscriberExternalURL
}
func callInitialize(t *testing.T, subscriberAppName, publisherExternalURL string, protocol string) {
req := callSubscriberMethodRequest{
ReqID: "c-" + uuid.New().String(),
RemoteApp: subscriberAppName,
Method: "initialize",
Protocol: protocol,
}
// only for the empty-json scenario, initialize empty sets in the subscriber app
reqBytes, _ := json.Marshal(req)
_, code, err := utils.HTTPPostWithStatus(publisherExternalURL+"/tests/callSubscriberMethod", reqBytes)
require.NoError(t, err)
require.Equal(t, http.StatusOK, code)
}
func setDesiredResponse(t *testing.T, subscriberAppName, subscriberResponse, publisherExternalURL, protocol string) {
// set to respond with specified subscriber response
req := callSubscriberMethodRequest{
ReqID: "c-" + uuid.New().String(),
RemoteApp: subscriberAppName,
Method: "set-respond-" + subscriberResponse,
Protocol: protocol,
}
reqBytes, _ := json.Marshal(req)
_, code, err := utils.HTTPPostWithStatus(publisherExternalURL+"/tests/callSubscriberMethod", reqBytes)
require.NoError(t, err)
require.Equal(t, http.StatusOK, code)
}
func validateBulkMessagesReceivedBySubscriber(t *testing.T, publisherExternalURL string, subscriberApp string, protocol string, sentMessages receivedMessagesResponse) {
// this is the subscribe app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/tests/callSubscriberMethod", publisherExternalURL)
log.Printf("Getting messages received by subscriber using url %s", url)
request := callSubscriberMethodRequest{
RemoteApp: subscriberApp,
Protocol: protocol,
Method: "getMessages",
}
var appResp receivedMessagesResponse
var err error
for retryCount := 0; retryCount < receiveMessageRetries; retryCount++ {
request.ReqID = "c-" + uuid.New().String()
rawReq, _ := json.Marshal(request)
var resp []byte
start := time.Now()
resp, err = utils.HTTPPost(url, rawReq)
log.Printf("(reqID=%s) Attempt %d complete; took %s", request.ReqID, retryCount, utils.FormatDuration(time.Now().Sub(start)))
if err != nil {
log.Printf("(reqID=%s) Error in response: %v", request.ReqID, err)
time.Sleep(10 * time.Second)
continue
}
err = json.Unmarshal(resp, &appResp)
if err != nil {
err = fmt.Errorf("(reqID=%s) failed to unmarshal JSON. Error: %v. Raw data: %s", request.ReqID, err, string(resp))
log.Printf("Error in response: %v", err)
time.Sleep(10 * time.Second)
continue
}
log.Printf(
"subscriber received %d/%d messages on pubsub-bulk-topic, %d/%d messages on pubsub-raw-bulk-topic "+
", %d/%d messages on pubsub-ce-bulk-topic and %d/%d messages on pubsub-def-bulk-topic",
len(appResp.ReceivedByTopicBulk), len(sentMessages.ReceivedByTopicBulk),
len(appResp.ReceivedByTopicRawBulk), len(sentMessages.ReceivedByTopicRawBulk),
len(appResp.ReceivedByTopicCEBulk), len(sentMessages.ReceivedByTopicCEBulk),
len(appResp.ReceivedByTopicDefBulk), len(sentMessages.ReceivedByTopicDefBulk),
)
if len(appResp.ReceivedByTopicBulk) != len(sentMessages.ReceivedByTopicBulk) ||
len(appResp.ReceivedByTopicRawBulk) != len(sentMessages.ReceivedByTopicRawBulk) ||
len(appResp.ReceivedByTopicCEBulk) != len(sentMessages.ReceivedByTopicCEBulk) ||
len(appResp.ReceivedByTopicDefBulk) != len(sentMessages.ReceivedByTopicDefBulk) {
log.Printf("Differing lengths in received vs. sent messages, retrying.")
time.Sleep(10 * time.Second)
} else {
break
}
}
require.NoError(t, err, "too many failed attempts")
// Sort messages first because the delivered messages cannot be ordered.
sort.Strings(sentMessages.ReceivedByTopicBulk)
sort.Strings(appResp.ReceivedByTopicBulk)
sort.Strings(sentMessages.ReceivedByTopicRawBulk)
sort.Strings(appResp.ReceivedByTopicRawBulk)
sort.Strings(sentMessages.ReceivedByTopicCEBulk)
sort.Strings(appResp.ReceivedByTopicCEBulk)
sort.Strings(sentMessages.ReceivedByTopicDefBulk)
sort.Strings(appResp.ReceivedByTopicDefBulk)
assert.Equal(t, sentMessages.ReceivedByTopicBulk, appResp.ReceivedByTopicBulk, "different messages received in Topic Bulk")
assert.Equal(t, sentMessages.ReceivedByTopicRawBulk, appResp.ReceivedByTopicRawBulk, "different messages received in Topic Raw Bulk")
assert.Equal(t, sentMessages.ReceivedByTopicCEBulk, appResp.ReceivedByTopicCEBulk, "different messages received in Topic CE Bulk")
assert.Equal(t, sentMessages.ReceivedByTopicDefBulk, appResp.ReceivedByTopicDefBulk, "different messages received in Topic Def Bulk impl redis")
}
func validateMessagesReceivedBySubscriber(t *testing.T, publisherExternalURL string, subscriberApp string, protocol string, validateDeadLetter bool, sentMessages receivedMessagesResponse) {
// this is the subscribe app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/tests/callSubscriberMethod", publisherExternalURL)
log.Printf("Getting messages received by subscriber using url %s", url)
request := callSubscriberMethodRequest{
RemoteApp: subscriberApp,
Protocol: protocol,
Method: "getMessages",
}
var appResp receivedMessagesResponse
var err error
for retryCount := 0; retryCount < receiveMessageRetries; retryCount++ {
request.ReqID = "c-" + uuid.New().String()
rawReq, _ := json.Marshal(request)
var resp []byte
start := time.Now()
resp, err = utils.HTTPPost(url, rawReq)
log.Printf("(reqID=%s) Attempt %d complete; took %s", request.ReqID, retryCount, utils.FormatDuration(time.Now().Sub(start)))
if err != nil {
log.Printf("(reqID=%s) Error in response: %v", request.ReqID, err)
time.Sleep(10 * time.Second)
continue
}
err = json.Unmarshal(resp, &appResp)
if err != nil {
err = fmt.Errorf("(reqID=%s) failed to unmarshal JSON. Error: %v. Raw data: %s", request.ReqID, err, string(resp))
log.Printf("Error in response: %v", err)
time.Sleep(10 * time.Second)
continue
}
log.Printf(
"subscriber received %d/%d messages on pubsub-a-topic, %d/%d on pubsub-b-topic and %d/%d on pubsub-c-topic, %d/%d on pubsub-raw-topic and %d/%d on dead letter topic",
len(appResp.ReceivedByTopicA), len(sentMessages.ReceivedByTopicA),
len(appResp.ReceivedByTopicB), len(sentMessages.ReceivedByTopicB),
len(appResp.ReceivedByTopicC), len(sentMessages.ReceivedByTopicC),
len(appResp.ReceivedByTopicRaw), len(sentMessages.ReceivedByTopicRaw),
len(appResp.ReceivedByTopicDeadLetter), len(sentMessages.ReceivedByTopicDeadLetter),
)
if len(appResp.ReceivedByTopicA) != len(sentMessages.ReceivedByTopicA) ||
len(appResp.ReceivedByTopicB) != len(sentMessages.ReceivedByTopicB) ||
len(appResp.ReceivedByTopicC) != len(sentMessages.ReceivedByTopicC) ||
len(appResp.ReceivedByTopicRaw) != len(sentMessages.ReceivedByTopicRaw) ||
(validateDeadLetter && len(appResp.ReceivedByTopicDeadLetter) != len(sentMessages.ReceivedByTopicDeadLetter)) {
log.Printf("Differing lengths in received vs. sent messages, retrying.")
time.Sleep(10 * time.Second)
} else {
break
}
}
require.NoError(t, err, "too many failed attempts")
// Sort messages first because the delivered messages cannot be ordered.
sort.Strings(sentMessages.ReceivedByTopicA)
sort.Strings(appResp.ReceivedByTopicA)
sort.Strings(sentMessages.ReceivedByTopicB)
sort.Strings(appResp.ReceivedByTopicB)
sort.Strings(sentMessages.ReceivedByTopicC)
sort.Strings(appResp.ReceivedByTopicC)
sort.Strings(sentMessages.ReceivedByTopicRaw)
sort.Strings(appResp.ReceivedByTopicRaw)
assert.Equal(t, sentMessages.ReceivedByTopicA, appResp.ReceivedByTopicA, "different messages received in Topic A")
assert.Equal(t, sentMessages.ReceivedByTopicB, appResp.ReceivedByTopicB, "different messages received in Topic B")
assert.Equal(t, sentMessages.ReceivedByTopicC, appResp.ReceivedByTopicC, "different messages received in Topic C")
assert.Equal(t, sentMessages.ReceivedByTopicRaw, appResp.ReceivedByTopicRaw, "different messages received in Topic Raw")
if validateDeadLetter {
// only error response is expected to validate dead letter
sort.Strings(sentMessages.ReceivedByTopicDeadLetter)
sort.Strings(appResp.ReceivedByTopicDeadLetter)
assert.Equal(t, sentMessages.ReceivedByTopicDeadLetter, appResp.ReceivedByTopicDeadLetter, "different messages received in Topic Dead")
}
}
var apps []struct {
suite string
publisher string
subscriber string
} = []struct {
suite string
publisher string
subscriber string
}{
{
suite: "built-in",
publisher: publisherAppName,
subscriber: subscriberAppName,
},
}
func TestMain(m *testing.M) {
utils.SetupLogs("pubsub")
utils.InitHTTPClient(true)
components := []kube.ComponentDescription{}
// These apps will be deployed before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: publisherAppName,
DaprEnabled: true,
ImageName: "e2e-pubsub-publisher",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
AppMemoryLimit: "200Mi",
AppMemoryRequest: "100Mi",
},
{
AppName: subscriberAppName,
DaprEnabled: true,
ImageName: "e2e-pubsub-subscriber",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
AppMemoryLimit: "200Mi",
AppMemoryRequest: "100Mi",
},
}
if utils.TestTargetOS() != "windows" { // pluggable components feature requires unix socket to work
redisPubsubPluggableComponent := apiv1.Container{
Name: "redis-pubsub-pluggable",
Image: runner.BuildTestImageName(redisPubSubPluggableApp),
}
container, _ := json.Marshal(redisPubsubPluggableComponent)
components = append(components, kube.ComponentDescription{
Name: PubSubPluggableName,
Namespace: &kube.DaprTestNamespace,
TypeName: "pubsub.redis-pluggable",
ContainerAsJSON: string(container),
MetaData: map[string]kube.MetadataValue{
"redisHost": {
FromSecretRef: &kube.SecretRef{
Name: "redissecret",
Key: "host",
},
},
"redisPassword": {Raw: `""`},
"processingTimeout": {Raw: `"1s"`},
"redeliverInterval": {Raw: `"1s"`},
"idleCheckFrequency": {Raw: `"1s"`},
"readTimeout": {Raw: `"1s"`},
},
Scopes: []string{publisherPluggableAppName, subscriberPluggableAppName},
})
pluggableTestApps := []kube.AppDescription{
{
AppName: publisherPluggableAppName,
DaprEnabled: true,
ImageName: "e2e-pubsub-publisher",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
AppMemoryLimit: "200Mi",
AppMemoryRequest: "100Mi",
InjectPluggableComponents: true,
AppEnv: map[string]string{
PubSubEnvVar: PubSubPluggableName,
},
},
{
AppName: subscriberPluggableAppName,
DaprEnabled: true,
ImageName: "e2e-pubsub-subscriber",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
AppMemoryLimit: "200Mi",
AppMemoryRequest: "100Mi",
InjectPluggableComponents: true,
AppEnv: map[string]string{
PubSubEnvVar: PubSubPluggableName,
},
},
}
testApps = append(testApps, pluggableTestApps...)
apps = append(apps, struct {
suite string
publisher string
subscriber string
}{
suite: "pluggable",
publisher: publisherPluggableAppName,
subscriber: subscriberPluggableAppName,
})
}
log.Printf("Creating TestRunner")
tr = runner.NewTestRunner("pubsubtest", testApps, components, nil)
log.Printf("Starting TestRunner")
os.Exit(tr.Start(m))
}
var pubsubTests = []struct {
name string
handler func(*testing.T, string, string, string, string, string) string
subscriberResponse string
}{
{
name: "publish and subscribe message successfully",
handler: testPublishSubscribeSuccessfully,
},
{
name: "publish with subscriber returning empty json test delivery of message once",
handler: testValidateRedeliveryOrEmptyJSON,
subscriberResponse: "empty-json",
},
{
name: "publish with no topic",
handler: testPublishWithoutTopic,
},
{
name: "publish with subscriber error test redelivery of messages",
handler: testValidateRedeliveryOrEmptyJSON,
subscriberResponse: "error",
},
{
name: "publish with subscriber retry test redelivery of messages",
handler: testValidateRedeliveryOrEmptyJSON,
subscriberResponse: "retry",
},
{
name: "publish with subscriber invalid status test redelivery of messages",
handler: testValidateRedeliveryOrEmptyJSON,
subscriberResponse: "invalid-status",
},
{
name: "bulk publish and normal subscribe successfully",
handler: testBulkPublishSuccessfully,
},
{
name: "drop message will be published to dlq if configured",
handler: testDropToDeadLetter,
},
}
func TestPubSubHTTP(t *testing.T) {
for _, app := range apps {
t.Log("Enter TestPubSubHTTP")
publisherExternalURL := tr.Platform.AcquireAppExternalURL(app.publisher)
require.NotEmpty(t, publisherExternalURL, "publisherExternalURL must not be empty!")
subscriberExternalURL := tr.Platform.AcquireAppExternalURL(app.subscriber)
require.NotEmpty(t, subscriberExternalURL, "subscriberExternalURLHTTP must not be empty!")
// Makes the test wait for the apps and load balancers to be ready
err := utils.HealthCheckApps(publisherExternalURL, subscriberExternalURL)
require.NoError(t, err, "Health checks failed")
err = publishHealthCheck(publisherExternalURL)
require.NoError(t, err)
protocol := "http"
//nolint: gosec
offset = rand.Intn(randomOffsetMax) + 1
log.Printf("initial %s offset: %d", app.suite, offset)
for _, tc := range pubsubTests {
t.Run(fmt.Sprintf("%s_%s_%s", app.suite, tc.name, protocol), func(t *testing.T) {
subscriberExternalURL = tc.handler(t, publisherExternalURL, subscriberExternalURL, tc.subscriberResponse, app.subscriber, protocol)
})
}
}
}
|
mikeee/dapr
|
tests/e2e/pubsub/pubsub_test.go
|
GO
|
mit
| 31,435 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package pubsubapp
import (
"encoding/json"
"fmt"
"log"
"math/rand"
"net/http"
"os"
"sort"
"strings"
"testing"
"time"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
"github.com/cenkalti/backoff/v4"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/ratelimit"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
var tr *runner.TestRunner
const (
// used as the exclusive max of a random number that is used as a suffix to the first message sent. Each subsequent message gets this number+1.
// This is random so the first message name is not the same every time.
randomOffsetMax = 49
numberOfMessagesToPublish = 60
publishRateLimitRPS = 25
receiveMessageRetries = 5
metadataPrefix = "metadata."
publisherAppName = "pubsub-publisher-grpc"
subscriberAppName = "pubsub-subscriber-grpc"
pubsubKafka = "kafka-messagebus"
bulkPubsubMetaKey = "bulkPublishPubsubName"
)
var offset int
// sent to the publisher app, which will publish data to dapr.
type publishCommand struct {
ReqID string `json:"reqID"`
ContentType string `json:"contentType"`
Topic string `json:"topic"`
Data interface{} `json:"data"`
Protocol string `json:"protocol"`
Metadata map[string]string `json:"metadata"`
}
type callSubscriberMethodRequest struct {
ReqID string `json:"reqID"`
RemoteApp string `json:"remoteApp"`
Protocol string `json:"protocol"`
Method string `json:"method"`
}
// data returned from the subscriber app.
type receivedMessagesResponse struct {
ReceivedByTopicA []string `json:"pubsub-a-topic"`
ReceivedByTopicB []string `json:"pubsub-b-topic"`
ReceivedByTopicC []string `json:"pubsub-c-topic"`
ReceivedByTopicRaw []string `json:"pubsub-raw-topic"`
ReceivedByTopicBulk []string `json:"pubsub-bulk-topic"`
ReceivedByTopicRawBulk []string `json:"pubsub-raw-bulk-topic"`
ReceivedByTopicCEBulk []string `json:"pubsub-ce-bulk-topic"`
ReceivedByTopicDefBulk []string `json:"pubsub-def-bulk-topic"`
}
type receivedBulkMessagesResponse struct {
ReceivedByTopicRawSub []string `json:"pubsub-raw-sub-topic"`
ReceivedByTopicCESub []string `json:"pubsub-ce-sub-topic"`
ReceivedByTopicRawBulkSub []string `json:"pubsub-raw-bulk-sub-topic"`
ReceivedByTopicCEBulkSub []string `json:"pubsub-ce-bulk-sub-topic"`
}
type cloudEvent struct {
ID string `json:"id"`
Type string `json:"type"`
DataContentType string `json:"datacontenttype"`
Data interface{} `json:"data"`
}
// checks is publishing is working.
func publishHealthCheck(publisherExternalURL string) error {
commandBody := publishCommand{
ContentType: "application/json",
Topic: "pubsub-healthcheck-topic-grpc",
Protocol: "grpc",
Data: "health check",
}
// this is the publish app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/tests/publish", publisherExternalURL)
return backoff.Retry(func() error {
commandBody.ReqID = "c-" + uuid.New().String()
jsonValue, _ := json.Marshal(commandBody)
_, err := postSingleMessage(url, jsonValue)
return err
}, backoff.WithMaxRetries(backoff.NewConstantBackOff(5*time.Second), 10))
}
func setMetadataBulk(url string, reqMeta map[string]string) string {
qArgs := []string{}
for k, v := range reqMeta {
qArg := fmt.Sprintf("%s%s=%s", metadataPrefix, k, v)
qArgs = append(qArgs, qArg)
}
concatenated := strings.Join(qArgs, "&")
log.Printf("setting query args %s", concatenated)
return url + "?" + concatenated
}
// sends messages to the publisher app. The publisher app does the actual publish.
func sendToPublisherBulk(t *testing.T, publisherExternalURL string, topic string, protocol string, reqMetadata map[string]string, cloudEventType string) ([]string, error) {
var individualMessages []string
commands := make([]publishCommand, numberOfMessagesToPublish)
for i := 0; i < numberOfMessagesToPublish; i++ {
contentType := "text/plain"
if cloudEventType != "" {
contentType = "application/cloudevents+json"
}
commandBody := publishCommand{
ContentType: contentType,
Topic: fmt.Sprintf("%s-%s", topic, protocol),
Protocol: protocol,
}
// create and marshal command
messageID := fmt.Sprintf("msg-%s-%s-%04d", strings.TrimSuffix(topic, "-topic"), protocol, i)
var messageData interface{} = messageID
if cloudEventType != "" {
messageData = &cloudEvent{
ID: messageID,
Type: cloudEventType,
DataContentType: "text/plain",
Data: messageID,
}
}
commandBody.ReqID = "c-" + uuid.New().String()
commandBody.Data = messageData
commands[i] = commandBody
individualMessages = append(individualMessages, messageID)
}
jsonValue, _ := json.Marshal(commands)
// this is the publish app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/tests/bulkpublish", publisherExternalURL)
url = setMetadataBulk(url, reqMetadata)
// debuggability - trace info about the first message. don't trace others so it doesn't flood log.
log.Printf("Sending bulk publish, app at url %s and body '%s', this log will not print for subsequent messages for same topic", url, jsonValue)
statusCode, err := postSingleMessage(url, jsonValue)
// return on an unsuccessful publish
if statusCode != http.StatusOK {
return nil, err
}
// return successfully sent individual messages
return individualMessages, nil
}
// sends messages to the publisher app. The publisher app does the actual publish.
func sendToPublisher(t *testing.T, publisherExternalURL string, topic string, protocol string, metadata map[string]string, cloudEventType string) ([]string, error) {
var sentMessages []string
contentType := "application/json"
if cloudEventType != "" {
contentType = "application/cloudevents+json"
}
commandBody := publishCommand{
ContentType: contentType,
Topic: fmt.Sprintf("%s-%s", topic, protocol),
Protocol: protocol,
Metadata: metadata,
}
rateLimit := ratelimit.New(publishRateLimitRPS)
for i := offset; i < offset+numberOfMessagesToPublish; i++ {
// create and marshal message
messageID := fmt.Sprintf("msg-%s-%s-%04d", strings.TrimSuffix(topic, "-topic"), protocol, i)
var messageData interface{} = messageID
if cloudEventType != "" {
messageData = &cloudEvent{
ID: messageID,
Type: cloudEventType,
DataContentType: "text/plain",
Data: messageID,
}
}
commandBody.ReqID = "c-" + uuid.New().String()
commandBody.Data = messageData
jsonValue, err := json.Marshal(commandBody)
require.NoError(t, err)
// this is the publish app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/tests/publish", publisherExternalURL)
// debuggability - trace info about the first message. don't trace others so it doesn't flood log.
if i == offset {
log.Printf("Sending first publish app at url %s and body '%s', this log will not print for subsequent messages for same topic", url, jsonValue)
}
rateLimit.Take()
statusCode, err := postSingleMessage(url, jsonValue)
// return on an unsuccessful publish
if statusCode != http.StatusNoContent {
return nil, err
}
// save successful message
sentMessages = append(sentMessages, messageID)
}
return sentMessages, nil
}
func callInitialize(t *testing.T, publisherExternalURL string, protocol string) {
req := callSubscriberMethodRequest{
ReqID: "c-" + uuid.New().String(),
RemoteApp: subscriberAppName,
Method: "initialize",
Protocol: protocol,
}
// only for the empty-json scenario, initialize empty sets in the subscriber app
reqBytes, _ := json.Marshal(req)
_, code, err := utils.HTTPPostWithStatus(publisherExternalURL+"/tests/callSubscriberMethod", reqBytes)
require.NoError(t, err)
require.Equal(t, http.StatusOK, code)
}
func testPublishBulk(t *testing.T, publisherExternalURL string, protocol string) receivedMessagesResponse {
meta := map[string]string{
bulkPubsubMetaKey: pubsubKafka,
}
sentTopicBulkMessages, err := sendToPublisherBulk(t, publisherExternalURL, "pubsub-bulk-topic", protocol, meta, "")
require.NoError(t, err)
sentTopicBulkCEMessages, err := sendToPublisherBulk(t, publisherExternalURL, "pubsub-ce-bulk-topic", protocol, meta, "myevent.CE")
require.NoError(t, err)
meta = map[string]string{
bulkPubsubMetaKey: pubsubKafka,
"rawPayload": "true",
}
sentTopicBulkRawMessages, err := sendToPublisherBulk(t, publisherExternalURL, "pubsub-raw-bulk-topic", protocol, meta, "")
require.NoError(t, err)
sentTopicBulkDefMessages, err := sendToPublisherBulk(t, publisherExternalURL, "pubsub-def-bulk-topic", protocol, nil, "")
require.NoError(t, err)
return receivedMessagesResponse{
ReceivedByTopicBulk: sentTopicBulkMessages,
ReceivedByTopicRawBulk: sentTopicBulkRawMessages,
ReceivedByTopicCEBulk: sentTopicBulkCEMessages,
ReceivedByTopicDefBulk: sentTopicBulkDefMessages,
}
}
func testPublish(t *testing.T, publisherExternalURL string, protocol string) receivedMessagesResponse {
metadataContentLengthConflict := map[string]string{
"content-length": "9999999",
}
sentTopicAMessages, err := sendToPublisher(t, publisherExternalURL, "pubsub-a-topic", protocol, metadataContentLengthConflict, "")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
sentTopicBMessages, err := sendToPublisher(t, publisherExternalURL, "pubsub-b-topic", protocol, nil, "")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
sentTopicCMessages, err := sendToPublisher(t, publisherExternalURL, "pubsub-c-topic", protocol, nil, "")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
metadataRawPayload := map[string]string{
"rawPayload": "true",
}
sentTopicRawMessages, err := sendToPublisher(t, publisherExternalURL, "pubsub-raw-topic", protocol, metadataRawPayload, "")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
return receivedMessagesResponse{
ReceivedByTopicA: sentTopicAMessages,
ReceivedByTopicB: sentTopicBMessages,
ReceivedByTopicC: sentTopicCMessages,
ReceivedByTopicRaw: sentTopicRawMessages,
}
}
func testPublishForBulkSubscribe(t *testing.T, publisherExternalURL string, protocol string) receivedBulkMessagesResponse {
sentTopicCESubMessages, err := sendToPublisher(t, publisherExternalURL, "pubsub-ce-sub-topic", protocol, nil, "")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
sentTopicCEBulkSubMessages, err := sendToPublisher(t, publisherExternalURL, "pubsub-ce-bulk-sub-topic", protocol, nil, "")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
metadata := map[string]string{
"rawPayload": "true",
}
sentTopicRawSubMessages, err := sendToPublisher(t, publisherExternalURL, "pubsub-raw-sub-topic", protocol, metadata, "")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
sentTopicRawBulkSubMessages, err := sendToPublisher(t, publisherExternalURL, "pubsub-raw-bulk-sub-topic", protocol, metadata, "")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
return receivedBulkMessagesResponse{
ReceivedByTopicRawSub: sentTopicRawSubMessages,
ReceivedByTopicCESub: sentTopicCESubMessages,
ReceivedByTopicRawBulkSub: sentTopicRawBulkSubMessages,
ReceivedByTopicCEBulkSub: sentTopicCEBulkSubMessages,
}
}
func postSingleMessage(url string, data []byte) (int, error) {
// HTTPPostWithStatus by default sends with content-type application/json
start := time.Now()
_, statusCode, err := utils.HTTPPostWithStatus(url, data)
if err != nil {
log.Printf("Publish failed with error=%s (body=%s) (duration=%s)", err.Error(), data, utils.FormatDuration(time.Now().Sub(start)))
return http.StatusInternalServerError, err
}
if (statusCode != http.StatusOK) && (statusCode != http.StatusNoContent) {
err = fmt.Errorf("publish failed with StatusCode=%d (body=%s) (duration=%s)", statusCode, data, utils.FormatDuration(time.Now().Sub(start)))
}
return statusCode, err
}
func testBulkPublishSuccessfully(t *testing.T, publisherExternalURL, subscriberExternalURL, _, subscriberAppName, protocol string) string {
// set to respond with success
setDesiredResponse(t, subscriberAppName, "success", publisherExternalURL, protocol)
log.Printf("Test bulkPublish and normal subscribe success flow")
sentMessages := testPublishBulk(t, publisherExternalURL, protocol)
time.Sleep(5 * time.Second)
validateBulkMessagesReceivedBySubscriber(t, publisherExternalURL, subscriberAppName, protocol, sentMessages)
return subscriberExternalURL
}
func testPublishSubscribeSuccessfully(t *testing.T, publisherExternalURL, subscriberExternalURL, _, subscriberAppName, protocol string) string {
log.Printf("Test publish subscribe success flow")
sentMessages := testPublish(t, publisherExternalURL, protocol)
validateMessagesReceivedBySubscriber(t, publisherExternalURL, subscriberAppName, protocol, sentMessages)
return subscriberExternalURL
}
func testPublishBulkSubscribeSuccessfully(t *testing.T, publisherExternalURL, subscriberExternalURL, _, subscriberAppName, protocol string) string {
callInitialize(t, publisherExternalURL, protocol)
log.Printf("Test publish bulk subscribe success flow\n")
sentMessages := testPublishForBulkSubscribe(t, publisherExternalURL, protocol)
time.Sleep(5 * time.Second)
validateMessagesReceivedWhenSomeTopicsBulkSubscribed(t, publisherExternalURL, subscriberAppName, protocol, sentMessages)
return subscriberExternalURL
}
func testPublishWithoutTopic(t *testing.T, publisherExternalURL, subscriberExternalURL, _, _, protocol string) string {
log.Printf("Test publish without topic")
commandBody := publishCommand{
ReqID: "c-" + uuid.New().String(),
Protocol: protocol,
}
commandBody.Data = "unsuccessful message"
jsonValue, err := json.Marshal(commandBody)
require.NoError(t, err)
// this is the publish app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/tests/publish", publisherExternalURL)
// debuggability - trace info about the first message. don't trace others so it doesn't flood log.
log.Printf("Sending first publish app at url %s and body '%s', this log will not print for subsequent messages for same topic", url, jsonValue)
statusCode, err := postSingleMessage(url, jsonValue)
require.Error(t, err)
// without topic, response should be 404
require.Equal(t, http.StatusNotFound, statusCode)
return subscriberExternalURL
}
//nolint:staticcheck
func testValidateRedeliveryOrEmptyJSON(t *testing.T, publisherExternalURL, subscriberExternalURL, subscriberResponse, subscriberAppName, protocol string) string {
var err error
var code int
log.Print("Validating publisher health...")
err = utils.HealthCheckApps(publisherExternalURL)
require.NoError(t, err, "Health checks failed")
log.Printf("Set subscriber to respond with %s\n", subscriberResponse)
if subscriberResponse == "empty-json" {
log.Println("Initialize the sets again in the subscriber application for this scenario ...")
callInitialize(t, publisherExternalURL, protocol)
}
// set to respond with specified subscriber response
req := callSubscriberMethodRequest{
ReqID: "c-" + uuid.New().String(),
RemoteApp: subscriberAppName,
Method: "set-respond-" + subscriberResponse,
Protocol: protocol,
}
reqBytes, _ := json.Marshal(req)
var lastRetryError error
for retryCount := 0; retryCount < receiveMessageRetries; retryCount++ {
if retryCount > 0 {
time.Sleep(10 * time.Second)
}
lastRetryError = nil
_, code, err = utils.HTTPPostWithStatus(publisherExternalURL+"/tests/callSubscriberMethod", reqBytes)
if err != nil {
lastRetryError = err
continue
}
if code != http.StatusOK {
lastRetryError = fmt.Errorf("unexpected http code: %v", code)
continue
}
break
}
require.Nil(t, lastRetryError, "error calling /tests/callSubscriberMethod: %v", lastRetryError)
sentMessages := testPublish(t, publisherExternalURL, protocol)
if subscriberResponse == "empty-json" {
// on empty-json response case immediately validate the received messages
validateMessagesReceivedBySubscriber(t, publisherExternalURL, subscriberAppName, protocol, sentMessages)
}
// restart application
log.Printf("Restarting subscriber application to check redelivery...\n")
err = tr.Platform.Restart(subscriberAppName)
require.NoError(t, err, "error restarting subscriber")
subscriberExternalURL = tr.Platform.AcquireAppExternalURL(subscriberAppName)
require.NotEmpty(t, subscriberExternalURL, "subscriberExternalURL must not be empty!")
if protocol == "http" {
err = utils.HealthCheckApps(subscriberExternalURL)
require.NoError(t, err, "Health checks failed")
} else {
conn, err := grpc.Dial(subscriberExternalURL, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Printf("Could not connect to app %s: %s", subscriberExternalURL, err.Error())
}
defer conn.Close()
}
if subscriberResponse == "empty-json" {
// validate that there is no redelivery of messages
log.Printf("Validating no redelivered messages...")
validateMessagesReceivedBySubscriber(t, publisherExternalURL, subscriberAppName, protocol, receivedMessagesResponse{
// empty string slices
ReceivedByTopicA: []string{},
ReceivedByTopicB: []string{},
ReceivedByTopicC: []string{},
ReceivedByTopicRaw: []string{},
})
} else {
// validate redelivery of messages
log.Printf("Validating redelivered messages...")
validateMessagesReceivedBySubscriber(t, publisherExternalURL, subscriberAppName, protocol, sentMessages)
}
return subscriberExternalURL
}
func setDesiredResponse(t *testing.T, subscriberAppName, subscriberResponse, publisherExternalURL, protocol string) {
// set to respond with specified subscriber response
req := callSubscriberMethodRequest{
ReqID: "c-" + uuid.New().String(),
RemoteApp: subscriberAppName,
Method: "set-respond-" + subscriberResponse,
Protocol: protocol,
}
reqBytes, _ := json.Marshal(req)
var lastRetryError error
for retryCount := 0; retryCount < receiveMessageRetries; retryCount++ {
if retryCount > 0 {
time.Sleep(10 * time.Second)
}
lastRetryError = nil
_, code, err := utils.HTTPPostWithStatus(publisherExternalURL+"/tests/callSubscriberMethod", reqBytes)
if err != nil {
lastRetryError = err
continue
}
if code != http.StatusOK {
lastRetryError = fmt.Errorf("unexpected http code: %v", code)
continue
}
break
}
require.Nil(t, lastRetryError, "error calling /tests/callSubscriberMethod: %v", lastRetryError)
}
func validateBulkMessagesReceivedBySubscriber(t *testing.T, publisherExternalURL string, subscriberApp string, protocol string, sentMessages receivedMessagesResponse) {
// this is the subscribe app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/tests/callSubscriberMethod", publisherExternalURL)
log.Printf("Getting messages received by subscriber using url %s", url)
request := callSubscriberMethodRequest{
RemoteApp: subscriberApp,
Protocol: protocol,
Method: "getMessages",
}
var appResp receivedMessagesResponse
var err error
for retryCount := 0; retryCount < receiveMessageRetries; retryCount++ {
request.ReqID = "c-" + uuid.New().String()
rawReq, _ := json.Marshal(request)
var resp []byte
start := time.Now()
resp, err = utils.HTTPPost(url, rawReq)
log.Printf("(reqID=%s) Attempt %d complete; took %s", request.ReqID, retryCount, utils.FormatDuration(time.Now().Sub(start)))
if err != nil {
log.Printf("(reqID=%s) Error in response: %v", request.ReqID, err)
time.Sleep(10 * time.Second)
continue
}
err = json.Unmarshal(resp, &appResp)
if err != nil {
err = fmt.Errorf("(reqID=%s) failed to unmarshal JSON. Error: %v. Raw data: %s", request.ReqID, err, string(resp))
log.Printf("Error in response: %v", err)
time.Sleep(10 * time.Second)
continue
}
log.Printf(
"subscriber received %d/%d messages on pubsub-bulk-topic, %d/%d messages on pubsub-raw-bulk-topic "+
", %d/%d messages on pubsub-ce-bulk-topic and %d/%d message on pubsub-def-bulk-topic",
len(appResp.ReceivedByTopicBulk), len(sentMessages.ReceivedByTopicBulk),
len(appResp.ReceivedByTopicRawBulk), len(sentMessages.ReceivedByTopicRawBulk),
len(appResp.ReceivedByTopicCEBulk), len(sentMessages.ReceivedByTopicCEBulk),
len(appResp.ReceivedByTopicDefBulk), len(sentMessages.ReceivedByTopicDefBulk),
)
if len(appResp.ReceivedByTopicBulk) != len(sentMessages.ReceivedByTopicBulk) ||
len(appResp.ReceivedByTopicRawBulk) != len(sentMessages.ReceivedByTopicRawBulk) ||
len(appResp.ReceivedByTopicCEBulk) != len(sentMessages.ReceivedByTopicCEBulk) ||
len(appResp.ReceivedByTopicDefBulk) != len(sentMessages.ReceivedByTopicDefBulk) {
log.Printf("Differing lengths in received vs. sent messages, retrying.")
time.Sleep(10 * time.Second)
} else {
break
}
}
require.NoError(t, err, "too many failed attempts")
// Sort messages first because the delivered messages cannot be ordered.
sort.Strings(sentMessages.ReceivedByTopicBulk)
sort.Strings(appResp.ReceivedByTopicBulk)
sort.Strings(sentMessages.ReceivedByTopicRawBulk)
sort.Strings(appResp.ReceivedByTopicRawBulk)
sort.Strings(sentMessages.ReceivedByTopicCEBulk)
sort.Strings(appResp.ReceivedByTopicCEBulk)
sort.Strings(sentMessages.ReceivedByTopicDefBulk)
sort.Strings(appResp.ReceivedByTopicDefBulk)
assert.Equal(t, sentMessages.ReceivedByTopicBulk, appResp.ReceivedByTopicBulk, "different messages received in Topic Bulk")
assert.Equal(t, sentMessages.ReceivedByTopicRawBulk, appResp.ReceivedByTopicRawBulk, "different messages received in Topic Raw Bulk")
assert.Equal(t, sentMessages.ReceivedByTopicCEBulk, appResp.ReceivedByTopicCEBulk, "different messages received in Topic CE Bulk")
assert.Equal(t, sentMessages.ReceivedByTopicDefBulk, appResp.ReceivedByTopicDefBulk, "different messages received in Topic defult Bulk on redis")
}
func validateMessagesReceivedBySubscriber(
t *testing.T, publisherExternalURL string, subscriberApp string, protocol string, sentMessages receivedMessagesResponse,
) {
// this is the subscribe app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/tests/callSubscriberMethod", publisherExternalURL)
log.Printf("Getting messages received by subscriber using url %s", url)
request := callSubscriberMethodRequest{
RemoteApp: subscriberApp,
Protocol: protocol,
Method: "getMessages",
}
var appResp receivedMessagesResponse
var err error
for retryCount := 0; retryCount < receiveMessageRetries; retryCount++ {
request.ReqID = "c-" + uuid.New().String()
rawReq, _ := json.Marshal(request)
var resp []byte
start := time.Now()
resp, err = utils.HTTPPost(url, rawReq)
log.Printf("(reqID=%s) Attempt %d complete; took %s", request.ReqID, retryCount, utils.FormatDuration(time.Now().Sub(start)))
if err != nil {
log.Printf("(reqID=%s) Error in response: %v", request.ReqID, err)
time.Sleep(10 * time.Second)
continue
}
err = json.Unmarshal(resp, &appResp)
if err != nil {
err = fmt.Errorf("(reqID=%s) failed to unmarshal JSON. Error: %v. Raw data: %s", request.ReqID, err, string(resp))
log.Printf("Error in response: %v", err)
time.Sleep(10 * time.Second)
continue
}
log.Printf(
"subscriber received %d/%d messages on pubsub-a-topic, %d/%d on pubsub-b-topic and %d/%d on pubsub-c-topic and %d/%d on pubsub-raw-topic",
len(appResp.ReceivedByTopicA), len(sentMessages.ReceivedByTopicA),
len(appResp.ReceivedByTopicB), len(sentMessages.ReceivedByTopicB),
len(appResp.ReceivedByTopicC), len(sentMessages.ReceivedByTopicC),
len(appResp.ReceivedByTopicRaw), len(sentMessages.ReceivedByTopicRaw),
)
if len(appResp.ReceivedByTopicA) != len(sentMessages.ReceivedByTopicA) ||
len(appResp.ReceivedByTopicB) != len(sentMessages.ReceivedByTopicB) ||
len(appResp.ReceivedByTopicC) != len(sentMessages.ReceivedByTopicC) ||
len(appResp.ReceivedByTopicRaw) != len(sentMessages.ReceivedByTopicRaw) {
log.Printf("Differing lengths in received vs. sent messages, retrying.")
time.Sleep(5 * time.Second)
} else {
break
}
}
require.NoError(t, err, "too many failed attempts")
// Sort messages first because the delivered messages might not be ordered.
sort.Strings(sentMessages.ReceivedByTopicA)
sort.Strings(appResp.ReceivedByTopicA)
sort.Strings(sentMessages.ReceivedByTopicB)
sort.Strings(appResp.ReceivedByTopicB)
sort.Strings(sentMessages.ReceivedByTopicC)
sort.Strings(appResp.ReceivedByTopicC)
sort.Strings(sentMessages.ReceivedByTopicRaw)
sort.Strings(appResp.ReceivedByTopicRaw)
assert.Equal(t, sentMessages.ReceivedByTopicA, appResp.ReceivedByTopicA, "different messages received in Topic A")
assert.Equal(t, sentMessages.ReceivedByTopicB, appResp.ReceivedByTopicB, "different messages received in Topic B")
assert.Equal(t, sentMessages.ReceivedByTopicC, appResp.ReceivedByTopicC, "different messages received in Topic C")
assert.Equal(t, sentMessages.ReceivedByTopicRaw, appResp.ReceivedByTopicRaw, "different messages received in Topic Raw")
}
func validateMessagesReceivedWhenSomeTopicsBulkSubscribed(
t *testing.T, publisherExternalURL string, subscriberApp string, protocol string, sentMessages receivedBulkMessagesResponse,
) {
// this is the subscribe app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/tests/callSubscriberMethod", publisherExternalURL)
log.Printf("Getting messages received by subscriber using url %s", url)
request := callSubscriberMethodRequest{
RemoteApp: subscriberApp,
Protocol: protocol,
Method: "getMessages",
}
var appResp receivedBulkMessagesResponse
var err error
for retryCount := 0; retryCount < receiveMessageRetries; retryCount++ {
request.ReqID = "c-" + uuid.New().String()
rawReq, _ := json.Marshal(request)
var resp []byte
start := time.Now()
resp, err = utils.HTTPPost(url, rawReq)
log.Printf("(reqID=%s) Attempt %d complete; took %s", request.ReqID, retryCount, utils.FormatDuration(time.Now().Sub(start)))
if err != nil {
log.Printf("(reqID=%s) Error in response: %v", request.ReqID, err)
time.Sleep(10 * time.Second)
continue
}
err = json.Unmarshal(resp, &appResp)
if err != nil {
err = fmt.Errorf("(reqID=%s) failed to unmarshal JSON. Error: %v. Raw data: %s", request.ReqID, err, string(resp))
log.Printf("Error in response: %v", err)
time.Sleep(10 * time.Second)
continue
}
log.Printf(
"subscriber received %d/%d on raw sub topic and %d/%d on ce sub topic and %d/%d on bulk raw sub topic and %d/%d on bulk ce sub topic",
len(appResp.ReceivedByTopicRawSub), len(sentMessages.ReceivedByTopicRawSub),
len(appResp.ReceivedByTopicCESub), len(sentMessages.ReceivedByTopicCESub),
len(appResp.ReceivedByTopicRawBulkSub), len(sentMessages.ReceivedByTopicRawBulkSub),
len(appResp.ReceivedByTopicCEBulkSub), len(sentMessages.ReceivedByTopicCEBulkSub),
)
if len(appResp.ReceivedByTopicRawSub) != len(sentMessages.ReceivedByTopicRawSub) ||
len(appResp.ReceivedByTopicCESub) != len(sentMessages.ReceivedByTopicCESub) ||
len(appResp.ReceivedByTopicRawBulkSub) != len(sentMessages.ReceivedByTopicRawBulkSub) ||
len(appResp.ReceivedByTopicCEBulkSub) != len(sentMessages.ReceivedByTopicCEBulkSub) {
log.Printf("Differing lengths in received vs. sent messages, retrying.")
time.Sleep(5 * time.Second)
} else {
break
}
}
require.NoError(t, err, "too many failed attempts")
// Sort messages first because the delivered messages might not be ordered.
sort.Strings(sentMessages.ReceivedByTopicRawSub)
sort.Strings(appResp.ReceivedByTopicRawSub)
sort.Strings(sentMessages.ReceivedByTopicCESub)
sort.Strings(appResp.ReceivedByTopicCESub)
sort.Strings(sentMessages.ReceivedByTopicRawBulkSub)
sort.Strings(appResp.ReceivedByTopicRawBulkSub)
sort.Strings(sentMessages.ReceivedByTopicCEBulkSub)
sort.Strings(appResp.ReceivedByTopicCEBulkSub)
assert.Equal(t, sentMessages.ReceivedByTopicRawSub, appResp.ReceivedByTopicRawSub, "different messages received in Topic Raw Sub")
assert.Equal(t, sentMessages.ReceivedByTopicCESub, appResp.ReceivedByTopicCESub, "different messages received in Topic CE Sub")
assert.Equal(t, sentMessages.ReceivedByTopicRawBulkSub, appResp.ReceivedByTopicRawBulkSub, "different messages received in Topic Raw Bulk Sub")
assert.Equal(t, sentMessages.ReceivedByTopicCEBulkSub, appResp.ReceivedByTopicCEBulkSub, "different messages received in Topic CE Bulk Sub")
}
func TestMain(m *testing.M) {
utils.SetupLogs("pubsub_grpc")
utils.InitHTTPClient(true)
//nolint: gosec
offset = rand.Intn(randomOffsetMax) + 1
log.Printf("initial offset: %d", offset)
// These apps will be deployed before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: publisherAppName,
DaprEnabled: true,
ImageName: "e2e-pubsub-publisher",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
},
{
AppName: subscriberAppName,
DaprEnabled: true,
ImageName: "e2e-pubsub-subscriber_grpc",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
AppProtocol: "grpc",
},
}
log.Printf("Creating TestRunner\n")
tr = runner.NewTestRunner("pubsubtest", testApps, nil, nil)
log.Printf("Starting TestRunner\n")
os.Exit(tr.Start(m))
}
var pubsubTests = []struct {
name string
handler func(*testing.T, string, string, string, string, string) string
subscriberResponse string
}{
{
name: "publish and subscribe message successfully",
handler: testPublishSubscribeSuccessfully,
},
{
name: "publish and bulk subscribe messages successfully",
handler: testPublishBulkSubscribeSuccessfully,
},
{
name: "publish with subscriber returning empty json test delivery of message once",
handler: testValidateRedeliveryOrEmptyJSON,
subscriberResponse: "empty-json",
},
{
name: "publish with no topic",
handler: testPublishWithoutTopic,
},
{
name: "publish with subscriber error test redelivery of messages",
handler: testValidateRedeliveryOrEmptyJSON,
subscriberResponse: "error",
},
{
name: "publish with subscriber retry test redelivery of messages",
handler: testValidateRedeliveryOrEmptyJSON,
subscriberResponse: "retry",
},
{
name: "publish with subscriber invalid status test redelivery of messages",
handler: testValidateRedeliveryOrEmptyJSON,
subscriberResponse: "invalid-status",
},
{
name: "bulk publish and normal subscribe successfully",
handler: testBulkPublishSuccessfully,
},
}
func TestPubSubGRPC(t *testing.T) {
log.Println("Enter TestPubSubGRPC")
publisherExternalURL := tr.Platform.AcquireAppExternalURL(publisherAppName)
require.NotEmpty(t, publisherExternalURL, "publisherExternalURL must not be empty!")
subscriberExternalURL := tr.Platform.AcquireAppExternalURL(subscriberAppName)
require.NotEmpty(t, subscriberExternalURL, "subscriberExternalURL must not be empty!")
// Makes the test wait for the apps and load balancers to be ready
err := utils.HealthCheckApps(publisherExternalURL)
require.NoError(t, err, "Health checks failed")
err = publishHealthCheck(publisherExternalURL)
require.NoError(t, err)
protocol := "grpc"
callInitialize(t, publisherExternalURL, protocol)
for _, tc := range pubsubTests {
t.Run(fmt.Sprintf("%s_%s", tc.name, protocol), func(t *testing.T) {
tc.handler(t, publisherExternalURL, subscriberExternalURL, tc.subscriberResponse, subscriberAppName, protocol)
})
}
}
|
mikeee/dapr
|
tests/e2e/pubsub_grpc/pubsub_grpc_test.go
|
GO
|
mit
| 32,626 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package pubsubapp_e2e
import (
"encoding/json"
"fmt"
"log"
"math/rand"
"net/http"
"os"
"sort"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/ratelimit"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
)
var tr *runner.TestRunner
const (
// used as the exclusive max of a random number that is used as a suffix to the first message sent. Each subsequent message gets this number+1.
// This is random so the first message name is not the same every time.
randomOffsetMax = 49
numberOfMessagesToPublish = 60
publishRateLimitRPS = 25
receiveMessageRetries = 5
publisherAppName = "pubsub-publisher-routing"
subscriberAppName = "pubsub-subscriber-routing"
)
// sent to the publisher app, which will publish data to dapr.
type publishCommand struct {
ReqID string `json:"reqID"`
ContentType string `json:"contentType"`
Topic string `json:"topic"`
Data interface{} `json:"data"`
Protocol string `json:"protocol"`
Metadata map[string]string `json:"metadata"`
}
type callSubscriberMethodRequest struct {
ReqID string `json:"reqID"`
RemoteApp string `json:"remoteApp"`
Protocol string `json:"protocol"`
Method string `json:"method"`
}
// data returned from the subscriber-routing app.
type routedMessagesResponse struct {
RouteA []string `json:"route-a"`
RouteB []string `json:"route-b"`
RouteC []string `json:"route-c"`
RouteD []string `json:"route-d"`
RouteE []string `json:"route-e"`
RouteF []string `json:"route-f"`
}
type cloudEvent struct {
ID string `json:"id"`
Type string `json:"type"`
DataContentType string `json:"datacontenttype"`
Data string `json:"data"`
}
// sends messages to the publisher app. The publisher app does the actual publish.
func sendToPublisher(t *testing.T, offset int, publisherExternalURL string, topic string, protocol string, metadata map[string]string, cloudEventType string) ([]string, error) {
var sentMessages []string
contentType := "application/json"
if cloudEventType != "" {
contentType = "application/cloudevents+json"
}
commandBody := publishCommand{
ContentType: contentType,
Topic: fmt.Sprintf("%s-%s", topic, protocol),
Protocol: protocol,
Metadata: metadata,
}
rateLimit := ratelimit.New(publishRateLimitRPS)
for i := offset; i < offset+numberOfMessagesToPublish; i++ {
// create and marshal message
messageID := fmt.Sprintf("msg-%s-%s-%04d", strings.TrimSuffix(topic, "-topic"), protocol, i)
var messageData interface{} = messageID
if cloudEventType != "" {
messageData = &cloudEvent{
ID: messageID,
Type: cloudEventType,
DataContentType: "text/plain",
Data: messageID,
}
}
commandBody.ReqID = "c-" + uuid.New().String()
commandBody.Data = messageData
jsonValue, err := json.Marshal(commandBody)
require.NoError(t, err)
// this is the publish app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/tests/publish", publisherExternalURL)
// debuggability - trace info about the first message. don't trace others so it doesn't flood log.
if i == offset {
log.Printf("Sending first publish app at url %s and body '%s', this log will not print for subsequent messages for same topic", url, jsonValue)
}
rateLimit.Take()
statusCode, err := postSingleMessage(url, jsonValue)
// return on an unsuccessful publish
if statusCode != http.StatusNoContent {
return nil, err
}
// save successful message
sentMessages = append(sentMessages, messageID)
}
return sentMessages, nil
}
func postSingleMessage(url string, data []byte) (int, error) {
// HTTPPostWithStatus by default sends with content-type application/json
start := time.Now()
_, statusCode, err := utils.HTTPPostWithStatus(url, data)
if err != nil {
log.Printf("Publish failed with error=%s (body=%s) (duration=%s)", err.Error(), data, utils.FormatDuration(time.Now().Sub(start)))
return http.StatusInternalServerError, err
}
if statusCode != http.StatusOK {
err = fmt.Errorf("publish failed with StatusCode=%d (body=%s) (duration=%s)", statusCode, data, utils.FormatDuration(time.Now().Sub(start)))
}
return statusCode, err
}
func callInitialize(t *testing.T, publisherExternalURL string, protocol string) {
req := callSubscriberMethodRequest{
ReqID: "c-" + uuid.New().String(),
RemoteApp: subscriberAppName,
Method: "initialize",
Protocol: protocol,
}
// only for the empty-json scenario, initialize empty sets in the subscriber app
reqBytes, _ := json.Marshal(req)
_, code, err := utils.HTTPPostWithStatus(publisherExternalURL+"/tests/callSubscriberMethod", reqBytes)
require.NoError(t, err)
require.Equal(t, http.StatusOK, code)
}
func testPublishSubscribeRouting(t *testing.T, publisherExternalURL, subscriberExternalURL, subscriberAppName, protocol string) string {
log.Printf("Test publish subscribe routing flow\n")
callInitialize(t, publisherExternalURL, protocol)
sentMessages := testPublishRouting(t, publisherExternalURL, protocol)
time.Sleep(5 * time.Second)
validateMessagesRouted(t, publisherExternalURL, subscriberAppName, protocol, sentMessages)
return subscriberExternalURL
}
func testPublishRouting(t *testing.T, publisherExternalURL string, protocol string) routedMessagesResponse {
//nolint: gosec
offset := rand.Intn(randomOffsetMax) + 1
log.Printf("initial offset: %d", offset)
// set to respond with success
sentRouteAMessages, err := sendToPublisher(t, offset, publisherExternalURL, "pubsub-routing", protocol, nil, "myevent.A")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
sentRouteBMessages, err := sendToPublisher(t, offset, publisherExternalURL, "pubsub-routing", protocol, nil, "myevent.B")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
sentRouteCMessages, err := sendToPublisher(t, offset, publisherExternalURL, "pubsub-routing", protocol, nil, "myevent.C")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
sentRouteDMessages, err := sendToPublisher(t, offset, publisherExternalURL, "pubsub-routing-crd", protocol, nil, "myevent.D")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
sentRouteEMessages, err := sendToPublisher(t, offset, publisherExternalURL, "pubsub-routing-crd", protocol, nil, "myevent.E")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
sentRouteFMessages, err := sendToPublisher(t, offset, publisherExternalURL, "pubsub-routing-crd", protocol, nil, "myevent.F")
require.NoError(t, err)
return routedMessagesResponse{
RouteA: sentRouteAMessages,
RouteB: sentRouteBMessages,
RouteC: sentRouteCMessages,
RouteD: sentRouteDMessages,
RouteE: sentRouteEMessages,
RouteF: sentRouteFMessages,
}
}
func validateMessagesRouted(t *testing.T, publisherExternalURL string, subscriberApp string, protocol string, sentMessages routedMessagesResponse) {
// this is the subscribe app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/tests/callSubscriberMethod", publisherExternalURL)
log.Printf("Getting messages received by subscriber using url %s", url)
request := callSubscriberMethodRequest{
RemoteApp: subscriberApp,
Protocol: protocol,
Method: "getMessages",
}
var appResp routedMessagesResponse
var err error
for retryCount := 0; retryCount < receiveMessageRetries; retryCount++ {
request.ReqID = "c-" + uuid.New().String()
rawReq, _ := json.Marshal(request)
var resp []byte
start := time.Now()
resp, err = utils.HTTPPost(url, rawReq)
log.Printf("(reqID=%s) Attempt %d complete; took %s", request.ReqID, retryCount, utils.FormatDuration(time.Now().Sub(start)))
if err != nil {
log.Printf("(reqID=%s) Error in response: %v", request.ReqID, err)
time.Sleep(10 * time.Second)
continue
}
err = json.Unmarshal(resp, &appResp)
if err != nil {
err = fmt.Errorf("(reqID=%s) failed to unmarshal JSON. Error: %v. Raw data: %s", request.ReqID, err, string(resp))
log.Printf("Error in response: %v", err)
time.Sleep(10 * time.Second)
continue
}
log.Printf(
"subscriber received messages: route-a %d/%d, route-b %d/%d, route-c %d/%d, route-d %d/%d, route-e %d/%d, route-f %d/%d",
len(appResp.RouteA), len(sentMessages.RouteA),
len(appResp.RouteB), len(sentMessages.RouteB),
len(appResp.RouteC), len(sentMessages.RouteC),
len(appResp.RouteD), len(sentMessages.RouteD),
len(appResp.RouteE), len(sentMessages.RouteE),
len(appResp.RouteF), len(sentMessages.RouteF),
)
if len(appResp.RouteA) != len(sentMessages.RouteA) ||
len(appResp.RouteB) != len(sentMessages.RouteB) ||
len(appResp.RouteD) != len(sentMessages.RouteC) ||
len(appResp.RouteD) != len(sentMessages.RouteD) ||
len(appResp.RouteE) != len(sentMessages.RouteE) ||
len(appResp.RouteF) != len(sentMessages.RouteF) {
log.Printf("Differing lengths in received vs. sent messages, retrying.")
time.Sleep(5 * time.Second)
} else {
break
}
}
require.NoError(t, err, "too many failed attempts")
// Sort messages first because the delivered messages cannot be ordered.
sort.Strings(sentMessages.RouteA)
sort.Strings(appResp.RouteA)
sort.Strings(sentMessages.RouteB)
sort.Strings(appResp.RouteB)
sort.Strings(sentMessages.RouteC)
sort.Strings(appResp.RouteC)
sort.Strings(sentMessages.RouteD)
sort.Strings(appResp.RouteD)
sort.Strings(sentMessages.RouteE)
sort.Strings(appResp.RouteE)
sort.Strings(sentMessages.RouteF)
sort.Strings(appResp.RouteF)
assert.Equal(t, sentMessages.RouteA, appResp.RouteA, "different messages received in route A")
assert.Equal(t, sentMessages.RouteB, appResp.RouteB, "different messages received in route B")
assert.Equal(t, sentMessages.RouteC, appResp.RouteC, "different messages received in route C")
assert.Equal(t, sentMessages.RouteD, appResp.RouteD, "different messages received in route D")
assert.Equal(t, sentMessages.RouteE, appResp.RouteE, "different messages received in route E")
assert.Equal(t, sentMessages.RouteF, appResp.RouteF, "different messages received in route F")
}
func TestMain(m *testing.M) {
utils.SetupLogs("pubsub_routing")
utils.InitHTTPClient(true)
// These apps will be deployed before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: publisherAppName,
DaprEnabled: true,
ImageName: "e2e-pubsub-publisher",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
AppMemoryLimit: "200Mi",
AppMemoryRequest: "100Mi",
},
{
AppName: subscriberAppName,
DaprEnabled: true,
ImageName: "e2e-pubsub-subscriber-routing",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
AppMemoryLimit: "200Mi",
AppMemoryRequest: "100Mi",
},
}
log.Printf("Creating TestRunner")
tr = runner.NewTestRunner("pubsubtest", testApps, nil, nil)
log.Printf("Starting TestRunner")
os.Exit(tr.Start(m))
}
func TestPubSubHTTPRouting(t *testing.T) {
t.Log("Enter TestPubSubHTTPRouting")
publisherExternalURL := tr.Platform.AcquireAppExternalURL(publisherAppName)
require.NotEmpty(t, publisherExternalURL, "publisherExternalURL must not be empty!")
subscriberRoutingExternalURL := tr.Platform.AcquireAppExternalURL(subscriberAppName)
require.NotEmpty(t, subscriberRoutingExternalURL, "subscriberRoutingExternalURL must not be empty!")
// Makes the test wait for the apps and load balancers to be ready
err := utils.HealthCheckApps(publisherExternalURL, subscriberRoutingExternalURL)
require.NoError(t, err, "Health checks failed")
testPublishSubscribeRouting(t, publisherExternalURL, subscriberRoutingExternalURL, subscriberAppName, "http")
}
|
mikeee/dapr
|
tests/e2e/pubsub_routing/pubsub_routing_test.go
|
GO
|
mit
| 12,619 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package pubsubapp
import (
"encoding/json"
"fmt"
"log"
"math/rand"
"net/http"
"os"
"sort"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/ratelimit"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
)
var tr *runner.TestRunner
const (
// Number of get calls before starting tests.
numHealthChecks = 60
// used as the exclusive max of a random number that is used as a suffix to the first message sent. Each subsequent message gets this number+1.
// This is random so the first message name is not the same every time.
randomOffsetMax = 49
numberOfMessagesToPublish = 60
publishRateLimitRPS = 25
receiveMessageRetries = 5
publisherAppName = "pubsub-publisher-routing-grpc"
subscriberAppName = "pubsub-subscriber-routing-grpc"
)
// sent to the publisher app, which will publish data to dapr.
type publishCommand struct {
ReqID string `json:"reqID"`
ContentType string `json:"contentType"`
Topic string `json:"topic"`
Data interface{} `json:"data"`
Protocol string `json:"protocol"`
Metadata map[string]string `json:"metadata"`
}
type callSubscriberMethodRequest struct {
ReqID string `json:"reqID"`
RemoteApp string `json:"remoteApp"`
Protocol string `json:"protocol"`
Method string `json:"method"`
}
// data returned from the subscriber-routing_grpc app.
type routedMessagesResponse struct {
RouteA []string `json:"route-a"`
RouteB []string `json:"route-b"`
RouteC []string `json:"route-c"`
RouteD []string `json:"route-d"`
RouteE []string `json:"route-e"`
RouteF []string `json:"route-f"`
}
type cloudEvent struct {
ID string `json:"id"`
Type string `json:"type"`
DataContentType string `json:"datacontenttype"`
Data interface{} `json:"data"`
}
// sends messages to the publisher app. The publisher app does the actual publish.
func sendToPublisher(t *testing.T, offset int, publisherExternalURL string, topic string, protocol string, metadata map[string]string, cloudEventType string) ([]string, error) {
var sentMessages []string
contentType := "application/json"
if cloudEventType != "" {
contentType = "application/cloudevents+json"
}
commandBody := publishCommand{
ContentType: contentType,
Topic: fmt.Sprintf("%s-%s", topic, protocol),
Protocol: protocol,
Metadata: metadata,
}
rateLimit := ratelimit.New(publishRateLimitRPS)
for i := offset; i < offset+numberOfMessagesToPublish; i++ {
// create and marshal message
messageID := fmt.Sprintf("msg-%s-%s-%04d", strings.TrimSuffix(topic, "-topic"), protocol, i)
var messageData interface{} = messageID
if cloudEventType != "" {
messageData = &cloudEvent{
ID: messageID,
Type: cloudEventType,
DataContentType: "text/plain",
Data: messageID,
}
}
commandBody.ReqID = "c-" + uuid.New().String()
commandBody.Data = messageData
jsonValue, err := json.Marshal(commandBody)
require.NoError(t, err)
// this is the publish app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/tests/publish", publisherExternalURL)
// debuggability - trace info about the first message. don't trace others so it doesn't flood log.
if i == offset {
log.Printf("Sending first publish app at url %s and body '%s', this log will not print for subsequent messages for same topic", url, jsonValue)
}
rateLimit.Take()
statusCode, err := postSingleMessage(url, jsonValue)
// return on an unsuccessful publish
if statusCode != http.StatusNoContent {
return nil, err
}
// save successful message
sentMessages = append(sentMessages, messageID)
}
return sentMessages, nil
}
func callInitialize(t *testing.T, publisherExternalURL string, protocol string) {
req := callSubscriberMethodRequest{
ReqID: "c-" + uuid.New().String(),
RemoteApp: subscriberAppName,
Method: "initialize",
Protocol: protocol,
}
// only for the empty-json scenario, initialize empty sets in the subscriber app
reqBytes, _ := json.Marshal(req)
_, code, err := utils.HTTPPostWithStatus(publisherExternalURL+"/tests/callSubscriberMethod", reqBytes)
require.NoError(t, err)
require.Equal(t, http.StatusOK, code)
}
func postSingleMessage(url string, data []byte) (int, error) {
// HTTPPostWithStatus by default sends with content-type application/json
start := time.Now()
_, statusCode, err := utils.HTTPPostWithStatus(url, data)
if err != nil {
log.Printf("Publish failed with error=%s (body=%s) (duration=%s)", err.Error(), data, utils.FormatDuration(time.Now().Sub(start)))
return http.StatusInternalServerError, err
}
if statusCode != http.StatusOK {
err = fmt.Errorf("publish failed with StatusCode=%d (body=%s) (duration=%s)", statusCode, data, utils.FormatDuration(time.Now().Sub(start)))
}
return statusCode, err
}
func testPublishSubscribeRouting(t *testing.T, publisherExternalURL, subscriberExternalURL, subscriberAppName, protocol string) string {
log.Printf("Test publish subscribe routing flow\n")
callInitialize(t, publisherExternalURL, protocol)
sentMessages := testPublishRouting(t, publisherExternalURL, protocol)
time.Sleep(5 * time.Second)
validateMessagesRouted(t, publisherExternalURL, subscriberAppName, protocol, sentMessages)
return subscriberExternalURL
}
func testPublishRouting(t *testing.T, publisherExternalURL string, protocol string) routedMessagesResponse {
//nolint: gosec
offset := rand.Intn(randomOffsetMax) + 1
log.Printf("initial offset: %d", offset)
// set to respond with success
sentRouteAMessages, err := sendToPublisher(t, offset, publisherExternalURL, "pubsub-routing", protocol, nil, "myevent.A")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
sentRouteBMessages, err := sendToPublisher(t, offset, publisherExternalURL, "pubsub-routing", protocol, nil, "myevent.B")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
sentRouteCMessages, err := sendToPublisher(t, offset, publisherExternalURL, "pubsub-routing", protocol, nil, "myevent.C")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
sentRouteDMessages, err := sendToPublisher(t, offset, publisherExternalURL, "pubsub-routing-crd", protocol, nil, "myevent.D")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
sentRouteEMessages, err := sendToPublisher(t, offset, publisherExternalURL, "pubsub-routing-crd", protocol, nil, "myevent.E")
require.NoError(t, err)
offset += numberOfMessagesToPublish + 1
sentRouteFMessages, err := sendToPublisher(t, offset, publisherExternalURL, "pubsub-routing-crd", protocol, nil, "myevent.F")
require.NoError(t, err)
return routedMessagesResponse{
RouteA: sentRouteAMessages,
RouteB: sentRouteBMessages,
RouteC: sentRouteCMessages,
RouteD: sentRouteDMessages,
RouteE: sentRouteEMessages,
RouteF: sentRouteFMessages,
}
}
func validateMessagesRouted(t *testing.T, publisherExternalURL string, subscriberApp string, protocol string, sentMessages routedMessagesResponse) {
// this is the subscribe app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/tests/callSubscriberMethod", publisherExternalURL)
log.Printf("Getting messages received by subscriber using url %s", url)
request := callSubscriberMethodRequest{
RemoteApp: subscriberApp,
Protocol: protocol,
Method: "getMessages",
}
var appResp routedMessagesResponse
var err error
for retryCount := 0; retryCount < receiveMessageRetries; retryCount++ {
request.ReqID = "c-" + uuid.New().String()
rawReq, _ := json.Marshal(request)
var resp []byte
start := time.Now()
resp, err = utils.HTTPPost(url, rawReq)
log.Printf("(reqID=%s) Attempt %d complete; took %s", request.ReqID, retryCount, utils.FormatDuration(time.Now().Sub(start)))
if err != nil {
log.Printf("(reqID=%s) Error in response: %v", request.ReqID, err)
time.Sleep(10 * time.Second)
continue
}
err = json.Unmarshal(resp, &appResp)
if err != nil {
err = fmt.Errorf("(reqID=%s) failed to unmarshal JSON. Error: %v. Raw data: %s", request.ReqID, err, string(resp))
log.Printf("Error in response: %v", err)
time.Sleep(10 * time.Second)
continue
}
log.Printf(
"subscriber received messages: route-a %d/%d, route-b %d/%d, route-c %d/%d, route-d %d/%d, route-e %d/%d, route-f %d/%d",
len(appResp.RouteA), len(sentMessages.RouteA),
len(appResp.RouteB), len(sentMessages.RouteB),
len(appResp.RouteC), len(sentMessages.RouteC),
len(appResp.RouteD), len(sentMessages.RouteD),
len(appResp.RouteE), len(sentMessages.RouteE),
len(appResp.RouteF), len(sentMessages.RouteF),
)
if len(appResp.RouteA) != len(sentMessages.RouteA) ||
len(appResp.RouteB) != len(sentMessages.RouteB) ||
len(appResp.RouteC) != len(sentMessages.RouteC) ||
len(appResp.RouteD) != len(sentMessages.RouteD) ||
len(appResp.RouteE) != len(sentMessages.RouteE) ||
len(appResp.RouteF) != len(sentMessages.RouteF) {
log.Printf("Differing lengths in received vs. sent messages, retrying.")
time.Sleep(5 * time.Second)
} else {
break
}
}
require.NoError(t, err, "too many failed attempts")
// Sort messages first because the delivered messages cannot be ordered.
sort.Strings(sentMessages.RouteA)
sort.Strings(appResp.RouteA)
sort.Strings(sentMessages.RouteB)
sort.Strings(appResp.RouteB)
sort.Strings(sentMessages.RouteC)
sort.Strings(appResp.RouteC)
sort.Strings(sentMessages.RouteD)
sort.Strings(appResp.RouteD)
sort.Strings(sentMessages.RouteE)
sort.Strings(appResp.RouteE)
sort.Strings(sentMessages.RouteF)
sort.Strings(appResp.RouteF)
assert.Equal(t, sentMessages.RouteA, appResp.RouteA, "different messages received in route A")
assert.Equal(t, sentMessages.RouteB, appResp.RouteB, "different messages received in route B")
assert.Equal(t, sentMessages.RouteC, appResp.RouteC, "different messages received in route C")
assert.Equal(t, sentMessages.RouteD, appResp.RouteD, "different messages received in route D")
assert.Equal(t, sentMessages.RouteE, appResp.RouteE, "different messages received in route E")
assert.Equal(t, sentMessages.RouteF, appResp.RouteF, "different messages received in route F")
}
func TestMain(m *testing.M) {
utils.SetupLogs("pubsub_routing_grpc")
utils.InitHTTPClient(true)
// These apps will be deployed before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: publisherAppName,
DaprEnabled: true,
ImageName: "e2e-pubsub-publisher",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
},
{
AppName: subscriberAppName,
DaprEnabled: true,
ImageName: "e2e-pubsub-subscriber-routing_grpc",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
AppProtocol: "grpc",
},
}
log.Printf("Creating TestRunner")
tr = runner.NewTestRunner("pubsubtest", testApps, nil, nil)
log.Printf("Starting TestRunner")
os.Exit(tr.Start(m))
}
func TestPubSubGRPCRouting(t *testing.T) {
t.Log("Enter TestPubSubGRPCRouting")
publisherExternalURL := tr.Platform.AcquireAppExternalURL(publisherAppName)
require.NotEmpty(t, publisherExternalURL, "publisherExternalURL must not be empty!")
subscriberRoutingExternalURL := tr.Platform.AcquireAppExternalURL(subscriberAppName)
require.NotEmpty(t, subscriberRoutingExternalURL, "subscriberRoutingExternalURL must not be empty!")
// Makes the test wait for the apps and load balancers to be ready
err := utils.HealthCheckApps(publisherExternalURL)
require.NoError(t, err, "Health checks failed")
testPublishSubscribeRouting(t, publisherExternalURL, subscriberRoutingExternalURL, subscriberAppName, "grpc")
}
|
mikeee/dapr
|
tests/e2e/pubsub_routing_grpc/pubsub_routing_grpc_test.go
|
GO
|
mit
| 12,583 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package resiliencyapp
import (
"encoding/json"
"fmt"
"net/url"
"os"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
"github.com/dapr/kit/ptr"
)
type FailureMessage struct {
ID string `json:"id"`
MaxFailureCount *int `json:"maxFailureCount,omitempty"`
Timeout *time.Duration `json:"timeout,omitempty"`
ResponseCode *int `json:"responseCode,omitempty"`
}
type CallRecord struct {
Count int
TimeSeen time.Time
}
const (
// Number of times to call the endpoint to check for health.
numHealthChecks = 60
)
var tr *runner.TestRunner
func TestMain(m *testing.M) {
utils.SetupLogs("resiliency")
utils.InitHTTPClient(true)
testApps := []kube.AppDescription{
{
AppName: "resiliencyapp",
DaprEnabled: true,
ImageName: "e2e-resiliencyapp",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
},
{
AppName: "resiliencyappgrpc",
DaprEnabled: true,
ImageName: "e2e-resiliencyapp_grpc",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
AppProtocol: "grpc",
},
}
tr = runner.NewTestRunner("resiliencytest", testApps, nil, nil)
os.Exit(tr.Start(m))
}
func TestInputBindingResiliency(t *testing.T) {
testCases := []struct {
Name string
FailureCount *int
Timeout *time.Duration
shouldFail bool
binding string
}{
{
Name: "Test sending input binding to app recovers from failure",
FailureCount: ptr.Of(3),
shouldFail: false,
binding: "dapr-resiliency-binding",
},
{
Name: "Test sending input binding to app recovers from timeout",
FailureCount: ptr.Of(3),
Timeout: ptr.Of(time.Second * 2),
shouldFail: false,
binding: "dapr-resiliency-binding",
},
{
Name: "Test exhausting retries leads to failure",
FailureCount: ptr.Of(10),
shouldFail: true,
binding: "dapr-resiliency-binding",
},
{
Name: "Test sending input binding to grpc app recovers from failure",
FailureCount: ptr.Of(3),
shouldFail: false,
binding: "dapr-resiliency-binding-grpc",
},
{
Name: "Test sending input binding to grpc app recovers from timeout",
FailureCount: ptr.Of(3),
Timeout: ptr.Of(time.Second * 2),
shouldFail: false,
binding: "dapr-resiliency-binding-grpc",
},
{
Name: "Test exhausting retries leads to failure in grpc app",
FailureCount: ptr.Of(10),
shouldFail: true,
binding: "dapr-resiliency-binding-grpc",
},
}
// Get application URLs/wait for healthy.
externalURL := tr.Platform.AcquireAppExternalURL("resiliencyapp")
require.NotEmpty(t, externalURL, "resiliency external URL must not be empty!")
externalURLGRPC := tr.Platform.AcquireAppExternalURL("resiliencyappgrpc")
require.NotEmpty(t, externalURLGRPC, "resiliencygrpc external URL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
message := createFailureMessage(tc.FailureCount, tc.Timeout)
b, _ := json.Marshal(message)
_, code, err := utils.HTTPPostWithStatus(fmt.Sprintf("%s/tests/invokeBinding/%s", externalURL, tc.binding), b)
require.NoError(t, err)
require.Equal(t, 200, code)
// Let the binding propagate and give time for retries/timeout.
time.Sleep(time.Second * 5)
var callCount map[string][]CallRecord
var getCallsURL string
if strings.Contains(tc.binding, "grpc") {
getCallsURL = "tests/getCallCountGRPC"
} else {
getCallsURL = "tests/getCallCount"
}
resp, err := utils.HTTPGet(fmt.Sprintf("%s/%s", externalURL, getCallsURL))
require.NoError(t, err)
err = json.Unmarshal(resp, &callCount)
require.NoError(t, err)
if tc.shouldFail {
// First call + 5 retries and no more.
require.GreaterOrEqual(t, len(callCount[message.ID]), 6, fmt.Sprintf("Call count mismatch for message %s", message.ID))
// TODO: Remove this once we can control Kafka's retry count.
// We have to do this because we can't currently control Kafka's retries. So, we make sure that anything past the resiliency
// retries have a wide enough gap in them to be considered OK.
if len(callCount[message.ID]) > 6 {
// This is the default Kafka retry time. Our policy time is 10ms so it should be much faster.
require.Greater(t, callCount[message.ID][6].TimeSeen.Sub(callCount[message.ID][5].TimeSeen), time.Millisecond*100)
}
} else {
// First call + 3 retries and recovery.
require.Equal(t, 4, len(callCount[message.ID]), fmt.Sprintf("Call count mismatch for message %s", message.ID))
}
})
}
}
func TestPubsubSubscriptionResiliency(t *testing.T) {
testCases := []struct {
Name string
FailureCount *int
Timeout *time.Duration
shouldFail bool
pubsub string
topic string
}{
{
Name: "Test sending event to app recovers from failure",
FailureCount: ptr.Of(3),
shouldFail: false,
pubsub: "dapr-resiliency-pubsub",
topic: "resiliency-topic-http",
},
{
Name: "Test sending event to app recovers from timeout",
FailureCount: ptr.Of(3),
Timeout: ptr.Of(time.Second * 2),
shouldFail: false,
pubsub: "dapr-resiliency-pubsub",
topic: "resiliency-topic-http",
},
{
Name: "Test exhausting retries leads to failure",
FailureCount: ptr.Of(10),
shouldFail: true,
pubsub: "dapr-resiliency-pubsub",
topic: "resiliency-topic-http",
},
{
Name: "Test sending event to grpc app recovers from failure",
FailureCount: ptr.Of(3),
shouldFail: false,
pubsub: "dapr-resiliency-pubsub",
topic: "resiliency-topic-grpc",
},
{
Name: "Test sending event to grpc app recovers from timeout",
FailureCount: ptr.Of(3),
Timeout: ptr.Of(time.Second * 2),
shouldFail: false,
pubsub: "dapr-resiliency-pubsub",
topic: "resiliency-topic-grpc",
},
{
Name: "Test exhausting retries leads to failure in grpc app",
FailureCount: ptr.Of(10),
shouldFail: true,
pubsub: "dapr-resiliency-pubsub",
topic: "resiliency-topic-grpc",
},
}
// Get application URLs/wait for healthy.
externalURL := tr.Platform.AcquireAppExternalURL("resiliencyapp")
require.NotEmpty(t, externalURL, "resiliency external URL must not be empty!")
externalURLGRPC := tr.Platform.AcquireAppExternalURL("resiliencyappgrpc")
require.NotEmpty(t, externalURLGRPC, "resiliencygrpc external URL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
message := createFailureMessage(tc.FailureCount, tc.Timeout)
b, _ := json.Marshal(message)
_, code, err := utils.HTTPPostWithStatus(fmt.Sprintf("%s/tests/publishMessage/%s/%s", externalURL, tc.pubsub, tc.topic), b)
require.NoError(t, err)
require.Equal(t, 200, code)
// Let the binding propagate and give time for retries/timeout.
time.Sleep(time.Second * 10)
var callCount map[string][]CallRecord
var getCallsURL string
if strings.Contains(tc.topic, "grpc") {
getCallsURL = "tests/getCallCountGRPC"
} else {
getCallsURL = "tests/getCallCount"
}
resp, err := utils.HTTPGet(fmt.Sprintf("%s/%s", externalURL, getCallsURL))
require.NoError(t, err)
err = json.Unmarshal(resp, &callCount)
require.NoError(t, err)
if tc.shouldFail {
// First call + 5 retries and no more.
require.Equal(t, 6, len(callCount[message.ID]), fmt.Sprintf("Call count mismatch for message %s", message.ID))
} else {
// First call + 3 retries and recovery.
require.Equal(t, 4, len(callCount[message.ID]), fmt.Sprintf("Call count mismatch for message %s", message.ID))
}
})
}
}
func TestServiceInvocationResiliency(t *testing.T) {
testCases := []struct {
Name string
FailureCount *int
Timeout *time.Duration
shouldFail bool
callType string
targetApp string
expectCount *int
expectStatus *int
}{
{
Name: "Test invoking app method recovers from failure",
FailureCount: ptr.Of(3),
shouldFail: false,
callType: "http",
},
{
Name: "Test invoking app method recovers from timeout",
FailureCount: ptr.Of(3),
Timeout: ptr.Of(time.Second * 2),
shouldFail: false,
callType: "http",
},
{
Name: "Test exhausting retries leads to failure",
FailureCount: ptr.Of(10),
shouldFail: true,
callType: "http",
},
{
Name: "Test invoking grpc app method recovers from failure",
FailureCount: ptr.Of(3),
shouldFail: false,
callType: "grpc",
},
{
Name: "Test invoking grpc app method recovers from timeout",
FailureCount: ptr.Of(3),
Timeout: ptr.Of(time.Second * 2),
shouldFail: false,
callType: "grpc",
},
{
Name: "Test exhausting retries leads to failure in grpc app",
FailureCount: ptr.Of(10),
shouldFail: true,
callType: "grpc",
},
{
Name: "Test invoking grpc proxy method recovers from failure",
FailureCount: ptr.Of(3),
shouldFail: false,
callType: "grpc_proxy",
},
{
Name: "Test invoking grpc proxy method recovers from timeout",
FailureCount: ptr.Of(3),
Timeout: ptr.Of(time.Second * 2),
shouldFail: false,
callType: "grpc_proxy",
},
{
Name: "Test exhausting retries leads to failure in grpc proxy",
FailureCount: ptr.Of(10),
shouldFail: true,
callType: "grpc_proxy",
},
{
Name: "Test invoking non-existent app http",
FailureCount: ptr.Of(3),
expectStatus: ptr.Of(500),
callType: "http",
targetApp: "badapp",
expectCount: ptr.Of(0),
},
{
Name: "Test invoking non-existent app grpc",
FailureCount: ptr.Of(3),
expectStatus: ptr.Of(500),
callType: "grpc",
targetApp: "badapp",
expectCount: ptr.Of(0),
},
}
// Get application URLs/wait for healthy.
externalURL := tr.Platform.AcquireAppExternalURL("resiliencyapp")
require.NotEmpty(t, externalURL, "resiliency external URL must not be empty!")
externalURLGRPC := tr.Platform.AcquireAppExternalURL("resiliencyappgrpc")
require.NotEmpty(t, externalURLGRPC, "resiliencygrpc external URL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
message := createFailureMessage(tc.FailureCount, tc.Timeout)
b, _ := json.Marshal(message)
u := fmt.Sprintf("%s/tests/invokeService/%s", externalURL, tc.callType)
if tc.targetApp != "" {
qs := url.Values{
"target_app": []string{tc.targetApp},
}
u += "?" + qs.Encode()
}
_, code, err := utils.HTTPPostWithStatus(u, b)
require.NoError(t, err)
switch {
case tc.expectStatus != nil:
require.Equal(t, *tc.expectStatus, code)
case tc.shouldFail:
require.Equal(t, 500, code)
default:
require.Equal(t, 200, code)
}
var callCount map[string][]CallRecord
getCallsURL := "tests/getCallCount"
if strings.Contains(tc.callType, "grpc") {
getCallsURL = "tests/getCallCountGRPC"
}
resp, err := utils.HTTPGet(fmt.Sprintf("%s/%s", externalURL, getCallsURL))
require.NoError(t, err)
err = json.Unmarshal(resp, &callCount)
require.NoError(t, err)
switch {
case tc.expectCount != nil:
require.Equal(t, *tc.expectCount, len(callCount[message.ID]), fmt.Sprintf("Call count mismatch for message %s", message.ID))
case tc.shouldFail:
// First call + 5 retries and no more.
require.Equal(t, 6, len(callCount[message.ID]), fmt.Sprintf("Call count mismatch for message %s", message.ID))
default:
// First call + 3 retries and recovery.
require.Equal(t, 4, len(callCount[message.ID]), fmt.Sprintf("Call count mismatch for message %s", message.ID))
}
})
}
}
func TestActorResiliency(t *testing.T) {
testCases := []struct {
Name string
FailureCount *int
Timeout *time.Duration
shouldFail bool
protocol string
}{
{
Name: "Test invoking actor recovers from failure",
FailureCount: ptr.Of(3),
shouldFail: false,
protocol: "http",
},
{
Name: "Test invoking actor recovers from timeout",
FailureCount: ptr.Of(3),
Timeout: ptr.Of(time.Second * 2),
shouldFail: false,
protocol: "http",
},
{
Name: "Test exhausting retries leads to failure",
FailureCount: ptr.Of(10),
shouldFail: true,
protocol: "http",
},
{
Name: "Test invoking actor with grpc recovers from failure",
FailureCount: ptr.Of(3),
shouldFail: false,
protocol: "grpc",
},
{
Name: "Test invoking actor with grpc recovers from timeout",
FailureCount: ptr.Of(3),
Timeout: ptr.Of(time.Second * 2),
shouldFail: false,
protocol: "grpc",
},
{
Name: "Test exhausting retries leads to failure in grpc actor call",
FailureCount: ptr.Of(10),
shouldFail: true,
protocol: "grpc",
},
}
// Get application URLs/wait for healthy.
externalURL := tr.Platform.AcquireAppExternalURL("resiliencyapp")
require.NotEmpty(t, externalURL, "resiliency external URL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
message := createFailureMessage(tc.FailureCount, tc.Timeout)
b, _ := json.Marshal(message)
_, code, err := utils.HTTPPostWithStatus(fmt.Sprintf("%s/tests/invokeActor/%s", externalURL, tc.protocol), b)
require.NoError(t, err)
if !tc.shouldFail {
require.Equal(t, 200, code)
} else {
require.Equal(t, 500, code)
}
// Let the binding propagate and give time for retries/timeout.
time.Sleep(time.Second * 5)
var callCount map[string][]CallRecord
resp, err := utils.HTTPGet(fmt.Sprintf("%s/tests/getCallCount", externalURL))
require.NoError(t, err)
err = json.Unmarshal(resp, &callCount)
require.NoError(t, err)
if tc.shouldFail {
// First call + 5 retries and no more.
require.GreaterOrEqual(t, len(callCount[message.ID]), 6, fmt.Sprintf("Call count mismatch for message %s", message.ID))
// TODO: Remove this once we can control Kafka's retry count.
// We have to do this because we can't currently control Kafka's retries. So, we make sure that anything past the resiliency
// retries have a wide enough gap in them to be considered OK.
if len(callCount[message.ID]) > 6 {
// This is the default Kafka retry time. Our policy time is 10ms so it should be much faster.
require.Greater(t, callCount[message.ID][6].TimeSeen.Sub(callCount[message.ID][5].TimeSeen), time.Millisecond*100)
}
} else {
// First call + 3 retries and recovery.
require.Equal(t, 4, len(callCount[message.ID]), fmt.Sprintf("Call count mismatch for message %s", message.ID))
}
})
}
}
func TestResiliencyCircuitBreakers(t *testing.T) {
testCases := []struct {
Name string
CallType string
}{
{
Name: "Test http service invocation circuit breaker trips",
CallType: "http",
},
{
Name: "Test grpc service invocation circuit breaker trips",
CallType: "grpc",
},
{
Name: "Test grpc proxy invocation circuit breaker trips",
CallType: "grpc_proxy",
},
}
// Get application URLs/wait for healthy.
externalURL := tr.Platform.AcquireAppExternalURL("resiliencyapp")
require.NotEmpty(t, externalURL, "resiliency external URL must not be empty!")
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
// Do a successful request to start to make sure our CB is cleared.
passingMessage := createFailureMessage(nil, nil)
passingBody, _ := json.Marshal(passingMessage)
_, code, err := utils.HTTPPostWithStatus(fmt.Sprintf("%s/tests/invokeService/%s", externalURL, tc.CallType), passingBody)
require.NoError(t, err)
require.Equal(t, 200, code)
failureCount := 20
message := createFailureMessage(&failureCount, nil)
b, _ := json.Marshal(message)
// The Circuit Breaker will trip after 15 consecutive errors each request is retried 5 times. Send the message 3 times to hit the breaker.
for i := 0; i < 3; i++ {
_, code, err := utils.HTTPPostWithStatus(fmt.Sprintf("%s/tests/invokeService/%s", externalURL, tc.CallType), b)
require.NoError(t, err)
require.Equal(t, 500, code)
}
// Validate the call count. Circuit Breaker trips at >15, so 16 should be max.
var callCount map[string][]CallRecord
getCallsURL := "tests/getCallCount"
if strings.Contains(tc.CallType, "grpc") {
getCallsURL = "tests/getCallCountGRPC"
}
resp, err := utils.HTTPGet(fmt.Sprintf("%s/%s", externalURL, getCallsURL))
require.NoError(t, err)
err = json.Unmarshal(resp, &callCount)
require.NoError(t, err)
require.Equal(t, 16, len(callCount[message.ID]), fmt.Sprintf("Call count mismatch for message %s", message.ID))
// We shouldn't be able to call the app anymore.
body, code, err := utils.HTTPPostWithStatus(fmt.Sprintf("%s/tests/invokeService/%s", externalURL, "http"), b)
require.NoError(t, err)
require.Equal(t, 500, code)
require.Contains(t, string(body), "circuit breaker is open")
// We shouldn't even see a call recorded.
resp, err = utils.HTTPGet(fmt.Sprintf("%s/tests/getCallCount", externalURL))
require.NoError(t, err)
err = json.Unmarshal(resp, &callCount)
require.NoError(t, err)
require.Equal(t, 16, len(callCount[message.ID]), fmt.Sprintf("Call count mismatch for message %s", message.ID))
})
}
}
func createFailureMessage(maxFailure *int, timeout *time.Duration) FailureMessage {
message := FailureMessage{
ID: uuid.New().String(),
}
if maxFailure != nil {
message.MaxFailureCount = maxFailure
}
if timeout != nil {
message.Timeout = timeout
}
return message
}
|
mikeee/dapr
|
tests/e2e/resiliency/resiliency_test.go
|
GO
|
mit
| 19,600 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package runtime_e2e
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"testing"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
)
const numHealthChecks = 60 // Number of get calls before starting tests.
var tr *runner.TestRunner
const (
runtimeAppName = "runtime"
runtimeInitAppName = "runtime-init"
numPubsubMessages = 10
)
type daprAPIResponse struct {
DaprHTTPSuccess int `json:"dapr_http_success"`
DaprHTTPError int `json:"dapr_http_error"`
DaprGRPCSuccess int `json:"dapr_grpc_success"`
DaprGRPCError int `json:"dapr_grpc_error"`
}
func getAPIResponse(t *testing.T, testName, runtimeExternalURL string) (*daprAPIResponse, error) {
// this is the publish app's endpoint, not a dapr endpoint
url := fmt.Sprintf("http://%s/tests/%s", runtimeExternalURL, testName)
resp, err := utils.HTTPGetRaw(url)
require.NoError(t, err)
defer func() {
// Drain before closing
_, _ = io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}()
require.Equal(t, resp.StatusCode, http.StatusOK)
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var appResp daprAPIResponse
err = json.Unmarshal(body, &appResp)
require.NoError(t, err)
return &appResp, nil
}
func TestMain(m *testing.M) {
utils.SetupLogs("runtime")
utils.InitHTTPClient(false)
// These apps and components will be deployed before starting actual test
// and will be cleaned up after all tests are finished automatically
comps := []kube.ComponentDescription{
{
Name: "runtime-bindings-http",
TypeName: "bindings.kafka",
MetaData: map[string]kube.MetadataValue{
"brokers": {Raw: `"dapr-kafka:9092"`},
"topics": {Raw: `"runtime-bindings-http"`},
"consumerGroup": {Raw: `"group1"`},
"authRequired": {Raw: `"false"`},
},
},
}
initApps := []kube.AppDescription{
{
AppName: runtimeInitAppName,
DaprEnabled: true,
ImageName: "e2e-runtime_init",
Replicas: 1,
IngressEnabled: false,
MetricsEnabled: true,
AppPort: -1,
},
}
testApps := []kube.AppDescription{
{
AppName: runtimeAppName,
DaprEnabled: true,
ImageName: "e2e-runtime",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
},
}
log.Printf("Creating TestRunner\n")
tr = runner.NewTestRunner("runtimetest", testApps, comps, initApps)
log.Printf("Starting TestRunner\n")
os.Exit(tr.Start(m))
}
func TestRuntimeInitPubsub(t *testing.T) {
t.Log("Enter TestRuntimeInitPubsub")
// Get subscriber app URL
runtimeExternalURL := tr.Platform.AcquireAppExternalURL(runtimeAppName)
require.NotEmpty(t, runtimeExternalURL, "runtimeExternalURL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(runtimeExternalURL, numHealthChecks)
require.NoError(t, err)
// Get API responses from subscriber
apiResponse, err := getAPIResponse(t, "pubsub", runtimeExternalURL)
require.NoError(t, err)
// Assert that all message handler invocations had access to the API
require.Equal(t, 0, apiResponse.DaprHTTPError)
require.GreaterOrEqual(t, numPubsubMessages, apiResponse.DaprHTTPSuccess)
require.Equal(t, 0, apiResponse.DaprGRPCError)
require.GreaterOrEqual(t, numPubsubMessages, apiResponse.DaprGRPCSuccess)
}
func TestRuntimeInitBindings(t *testing.T) {
t.Log("Enter TestRuntimeInitBindings")
// Get subscriber app URL
runtimeExternalURL := tr.Platform.AcquireAppExternalURL(runtimeAppName)
require.NotEmpty(t, runtimeExternalURL, "runtimeExternalURL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(runtimeExternalURL, numHealthChecks)
require.NoError(t, err)
// Get API responses from subscriber
apiResponse, err := getAPIResponse(t, "bindings", runtimeExternalURL)
require.NoError(t, err)
// Assert that the binding was not invoked by prior messages
require.Equal(t, 0, apiResponse.DaprHTTPError)
require.Equal(t, 0, apiResponse.DaprHTTPSuccess)
require.Equal(t, 0, apiResponse.DaprGRPCError)
require.Equal(t, 0, apiResponse.DaprGRPCSuccess)
}
|
mikeee/dapr
|
tests/e2e/runtime/runtime_test.go
|
GO
|
mit
| 5,001 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package secretapp_e2e
import (
"encoding/json"
"fmt"
"os"
"reflect"
"testing"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
)
const (
// Although Kubernetes secret store components are disabled, this is the built-in one that will work anyways
secretStore = "kubernetes"
badSecretStore = "vault"
nonexistentStore = "nonexistent"
appName = "secretapp" // App name in Dapr.
numHealthChecks = 60 // Number of get calls before starting tests.
allowedSecret = "daprsecret"
unallowedSecret = "daprsecret2"
nonExistentSecret = "nonexistentsecret"
emptySecret = "emptysecret"
testCase1Value = "admin"
redisSecret = "redissecret"
)
var (
redisSecretValue = map[string]string{"host": "dapr-redis-master:6379"}
daprSecretValue = map[string]string{"username": "admin"}
)
// daprSecret represents a secret in Dapr.
type daprSecret struct {
Key string `json:"key,omitempty"`
Value *map[string]string `json:"value,omitempty"`
Store string `json:"store,omitempty"`
}
// Stringer interface impl for test logging.
func (d daprSecret) String() string {
s := "key: " + d.Key + ", store: " + d.Store + ", value: {"
if d.Value != nil {
for k, v := range *d.Value {
s += k + ": " + v + ", "
}
}
s += "}"
return s
}
// requestResponse represents a request or response for the APIs in the app.
type requestResponse struct {
Secrets []daprSecret `json:"secrets,omitempty"`
}
// represents each step in a test since it can make multiple calls.
type testCase struct {
name string
request requestResponse
expectedResponse requestResponse
errorExpected bool
statusCode int
errorString string
isBulk bool
}
func generateDaprSecret(kv utils.SimpleKeyValue, store string) daprSecret {
if kv.Key == nil {
return daprSecret{}
}
key := fmt.Sprintf("%v", kv.Key)
if kv.Value == nil {
return daprSecret{key, nil, ""}
}
value := map[string]string{}
switch val := kv.Value.(type) {
case map[string]string:
value = val
case string:
if val != "" {
value["username"] = val
}
default:
// This should not happen in tests
panic(fmt.Sprintf("unexpected type %v", reflect.TypeOf(val)))
}
return daprSecret{key, &value, store}
}
// creates a requestResponse based on an array of key value pairs.
func newRequestResponse(store string, keyValues ...utils.SimpleKeyValue) requestResponse {
daprSecrets := make([]daprSecret, 0, len(keyValues))
for _, keyValue := range keyValues {
daprSecrets = append(daprSecrets, generateDaprSecret(keyValue, store))
}
return requestResponse{
daprSecrets,
}
}
// Just for readability.
func newRequest(store string, keyValues ...utils.SimpleKeyValue) requestResponse {
return newRequestResponse(store, keyValues...)
}
// Just for readability.
func newResponse(store string, keyValues ...utils.SimpleKeyValue) requestResponse {
return newRequestResponse(store, keyValues...)
}
func generateTestCases() []testCase {
// Just for readability
emptyRequest := requestResponse{}
// Just for readability
emptyResponse := requestResponse{}
return []testCase{
{
// No comma since this will become the name of the test without spaces.
"empty request",
emptyRequest,
emptyResponse,
false,
200,
"", // no error
false,
},
{
"empty secret",
newRequest(secretStore, utils.SimpleKeyValue{Key: emptySecret, Value: ""}),
newResponse(secretStore, utils.SimpleKeyValue{Key: emptySecret, Value: ""}),
false,
200,
"", // no error
false,
},
{
"allowed secret",
newRequest(secretStore, utils.SimpleKeyValue{Key: allowedSecret, Value: testCase1Value}),
newResponse(secretStore, utils.SimpleKeyValue{Key: allowedSecret, Value: testCase1Value}),
false,
200,
"", // no error
false,
},
{
"unallowed secret",
newRequest(secretStore, utils.SimpleKeyValue{Key: unallowedSecret, Value: ""}),
newResponse("", utils.SimpleKeyValue{Key: unallowedSecret, Value: ""}),
true,
403,
"ERR_PERMISSION_DENIED",
false,
},
{
"nonexistent secret",
newRequest(secretStore, utils.SimpleKeyValue{Key: nonExistentSecret, Value: ""}),
newResponse("", utils.SimpleKeyValue{Key: nonExistentSecret, Value: ""}),
true,
500,
"ERR_SECRET_GET",
false,
},
{
"secret from nonexistent secret store",
newRequest(nonexistentStore, utils.SimpleKeyValue{Key: allowedSecret, Value: ""}),
newResponse("", utils.SimpleKeyValue{Key: allowedSecret, Value: ""}),
true,
401,
"ERR_SECRET_STORE_NOT_FOUND",
false,
},
{
"secret from the disabled secret store",
newRequest(badSecretStore, utils.SimpleKeyValue{Key: allowedSecret, Value: ""}),
newResponse("", utils.SimpleKeyValue{Key: allowedSecret, Value: ""}),
true,
401,
"ERR_SECRET_STORE_NOT_FOUND",
false,
},
{
"bulk get secret",
// Request does not matter, only the secretStore from request matters.
newRequest(secretStore, utils.SimpleKeyValue{Key: allowedSecret, Value: testCase1Value}),
newResponse(secretStore,
utils.SimpleKeyValue{Key: allowedSecret, Value: daprSecretValue},
utils.SimpleKeyValue{Key: emptySecret, Value: ""},
utils.SimpleKeyValue{Key: redisSecret, Value: redisSecretValue}),
false,
200,
"", // no error
true, // bulk get
},
}
}
func generateTestCasesForDisabledSecretStore() []testCase {
return []testCase{
{
"valid secret but secret store should not be found",
newRequest(secretStore, utils.SimpleKeyValue{allowedSecret, testCase1Value}),
newResponse(secretStore, utils.SimpleKeyValue{allowedSecret, testCase1Value}),
true,
500,
"ERR_SECRET_STORES_NOT_CONFIGURED",
false,
},
}
}
var secretAppTests = []struct {
app string
testCases []testCase
}{
{
"secretapp",
generateTestCases(),
},
{
"secretapp-disable",
generateTestCasesForDisabledSecretStore(),
},
}
var tr *runner.TestRunner
func TestMain(m *testing.M) {
utils.SetupLogs("secretapp")
utils.InitHTTPClient(true)
// These apps will be deployed before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
// "secretappconfig" restricts access to the Kubernetes secret store, but the built-in one (called "kubernetes") should work anyways
Config: "secretappconfig",
AppName: appName,
DaprEnabled: true,
ImageName: "e2e-secretapp",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
},
{
Config: "secretappconfig",
AppName: "secretapp-disable",
DaprEnabled: true,
ImageName: "e2e-secretapp",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
SecretStoreDisable: true,
},
}
tr = runner.NewTestRunner(appName, testApps, nil, nil)
os.Exit(tr.Start(m))
}
func TestSecretApp(t *testing.T) {
for _, tt := range secretAppTests {
externalURL := tr.Platform.AcquireAppExternalURL(tt.app)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
testCases := tt.testCases
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
// Now we are ready to run the actual tests
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// setup
body, err := json.Marshal(tc.request)
require.NoError(t, err)
var url string
if !tc.isBulk {
t.Log("Single test")
url = fmt.Sprintf("%s/test/get", externalURL)
} else {
t.Log("Bulk test")
url = fmt.Sprintf("%s/test/bulk", externalURL)
}
// act
resp, statusCode, err := utils.HTTPPostWithStatus(url, body)
// assert
if !tc.errorExpected {
require.NoError(t, err)
var appResp requestResponse
err = json.Unmarshal(resp, &appResp)
require.NoError(t, err, "Failed to unmarshal. Response (%d) was: %s", statusCode, string(resp))
t.Log("App Response", appResp)
t.Log("Expected Response", tc.expectedResponse)
// For bulk get order does not matter
require.ElementsMatch(t, tc.expectedResponse.Secrets, appResp.Secrets, "Expected response to match")
require.Equal(t, tc.statusCode, statusCode, "Expected statusCode to be equal")
} else {
require.Contains(t, string(resp), tc.errorString, "Expected error string to match")
require.Equal(t, tc.statusCode, statusCode, "Expected statusCode to be equal")
}
})
}
}
}
|
mikeee/dapr
|
tests/e2e/secretapp/secretapp_test.go
|
GO
|
mit
| 9,373 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package serviceinvocation_tests
import (
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
"testing"
guuid "github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
diag "github.com/dapr/dapr/pkg/diagnostics"
diagUtils "github.com/dapr/dapr/pkg/diagnostics/utils"
invokev1 "github.com/dapr/dapr/pkg/messaging/v1"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
cryptotest "github.com/dapr/kit/crypto/test"
kitUtils "github.com/dapr/kit/utils"
apiv1 "k8s.io/api/core/v1"
)
type testCommandRequest struct {
RemoteApp string `json:"remoteApp,omitempty"`
Method string `json:"method,omitempty"`
RemoteAppTracing string `json:"remoteAppTracing"`
Message *string `json:"message"`
}
type testCommandRequestExternal struct {
testCommandRequest `json:",inline"`
ExternalIP string `json:"externalIP,omitempty"`
}
type appResponse struct {
Message string `json:"message,omitempty"`
}
type negativeTestResult struct {
MainCallSuccessful bool `json:"callSuccessful"`
RawBody []byte `json:"rawBody"`
RawError string `json:"rawError"`
Results []individualTestResult `json:"results"`
}
type individualTestResult struct {
TestCase string `json:"case"`
CallSuccessful bool `json:"callSuccessful"`
}
const (
numHealthChecks = 60 // Number of times to call the endpoint to check for health.
)
var (
tr *runner.TestRunner
secondaryNamespace = "dapr-tests-2"
)
func TestMain(m *testing.M) {
utils.SetupLogs("service_invocation")
utils.InitHTTPClient(false)
pki, err := cryptotest.GenPKIError(cryptotest.PKIOptions{
LeafDNS: "service-invocation-external",
})
if err != nil {
fmt.Println(err)
os.Exit(-1)
}
secrets := []kube.SecretDescription{
{
Name: "external-tls",
Namespace: kube.DaprTestNamespace,
Data: map[string][]byte{
"ca.crt": pki.RootCertPEM,
"tls.crt": pki.LeafCertPEM,
"tls.key": pki.LeafPKPEM,
},
},
{
Name: "dapr-tls-client",
Namespace: kube.DaprTestNamespace,
Data: map[string][]byte{
"ca.crt": pki.RootCertPEM,
"tls.crt": pki.ClientCertPEM,
"tls.key": pki.ClientPKPEM,
},
},
}
// These apps will be deployed for hellodapr test before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: "serviceinvocation-caller",
DaprEnabled: true,
ImageName: "e2e-service_invocation",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
},
{
AppName: "serviceinvocation-callee-0",
DaprEnabled: true,
ImageName: "e2e-service_invocation",
Replicas: 1,
MetricsEnabled: true,
},
{
AppName: "serviceinvocation-callee-1",
DaprEnabled: true,
ImageName: "e2e-service_invocation",
Replicas: 1,
MetricsEnabled: true,
},
{
AppName: "serviceinvocation-callee-2",
DaprEnabled: true,
ImageName: "e2e-service_invocation",
Replicas: 2,
MetricsEnabled: true,
Config: "app-channel-pipeline",
},
{
AppName: "grpcapp",
DaprEnabled: true,
ImageName: "e2e-service_invocation_grpc",
Replicas: 1,
MetricsEnabled: true,
AppProtocol: "grpc",
},
{
AppName: "secondary-ns-http",
DaprEnabled: true,
ImageName: "e2e-service_invocation",
Replicas: 1,
MetricsEnabled: true,
Namespace: &secondaryNamespace,
},
{
AppName: "secondary-ns-grpc",
DaprEnabled: true,
ImageName: "e2e-service_invocation_grpc",
Replicas: 1,
MetricsEnabled: true,
Namespace: &secondaryNamespace,
AppProtocol: "grpc",
},
{
AppName: "grpcproxyclient",
DaprEnabled: true,
ImageName: "e2e-service_invocation_grpc_proxy_client",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
MaxRequestSizeMB: 6,
},
{
AppName: "grpcproxyserver",
DaprEnabled: true,
ImageName: "e2e-service_invocation_grpc_proxy_server",
Replicas: 1,
MetricsEnabled: true,
AppProtocol: "grpc",
AppPort: 50051,
AppChannelAddress: "grpcproxyserver-app",
MaxRequestSizeMB: 6,
},
{
AppName: "grpcproxyserverexternal",
DaprEnabled: false,
ImageName: "e2e-service_invocation_grpc_proxy_server",
Replicas: 1,
MetricsEnabled: true,
AppProtocol: "grpc",
AppPort: 50051,
},
}
if !kitUtils.IsTruthy(os.Getenv("SKIP_EXTERNAL_INVOCATION")) {
testApps = append(testApps,
kube.AppDescription{
AppName: "serviceinvocation-callee-external",
DaprEnabled: false,
ImageName: "e2e-service_invocation_external",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
AppProtocol: "http",
Volumes: []apiv1.Volume{
{
Name: "secret-volume",
VolumeSource: apiv1.VolumeSource{
Secret: &apiv1.SecretVolumeSource{
SecretName: "external-tls",
},
},
},
},
AppVolumeMounts: []apiv1.VolumeMount{
{
Name: "secret-volume",
MountPath: "/tmp/testdata/certs",
},
},
},
)
}
tr = runner.NewTestRunner("hellodapr", testApps, nil, nil)
tr.AddSecrets(secrets)
os.Exit(tr.Start(m))
}
var serviceinvocationTests = []struct {
in string
remoteApp string
appMethod string
expectedResponse string
}{
{
"Test singlehop for callee-0",
"serviceinvocation-callee-0",
"singlehop",
"singlehop is called",
},
{
"Test singlehop for callee-1",
"serviceinvocation-callee-1",
"singlehop",
"singlehop is called",
},
{
"Test multihop",
"serviceinvocation-callee-0",
"multihop",
"singlehop is called",
},
}
var serviceinvocationPathTests = []struct {
in string
remoteApp string
appMethod string
expectedResponse string
}{
{
"Test call double encoded path",
"serviceinvocation-callee",
"path/value%252F123",
"/path/value%252F123",
},
{
"Test call encoded path",
"serviceinvocation-callee",
"path/value%2F123",
"/path/value%2F123",
},
{
"Test call normal path",
"serviceinvocation-callee",
"path/value/123",
"/path/value/123",
},
}
var serviceInvocationRedirectTests = []struct {
in string
remoteApp string
appMethod string
expectedResponse string
expectedStatusCode int
}{
{
"Test call redirect 307 Api",
"serviceinvocation-callee",
"opRedirect",
"opRedirect is called",
307,
},
}
var moreServiceinvocationTests = []struct {
in string
path string
remoteApp string
appMethod string
expectedResponse string
}{
// For descriptions, see corresponding methods in dapr/tests/apps/service_invocation/app.go
{
"Test HTTP to HTTP",
"httptohttptest",
"serviceinvocation-callee-1",
"httptohttptest",
"success",
},
{
"Test HTTP to gRPC",
"httptogrpctest",
"grpcapp",
"httptogrpctest",
"success",
},
{
"Test gRPC to HTTP",
"grpctohttptest",
"serviceinvocation-callee-1",
"grpctohttptest",
"success",
},
{
"Test gRPC to gRPC",
"grpctogrpctest",
"grpcapp",
"grpcToGrpcTest",
"success",
},
}
var externalServiceInvocationTests = []struct {
in string
path string
remoteApp string
appMethod string
expectedResponse string
testType string
}{
// For descriptions, see corresponding methods in dapr/tests/apps/service_invocation/app.go
{
"Test HTTP to HTTP Externally using overwritten URLs",
"/httptohttptest_external",
"serviceinvocation-callee-external",
"externalInvocation",
"success",
"URL",
},
{
"Test HTTP to HTTP Externally using HTTP Endpoint CRD",
"/httptohttptest_external",
"external-http-endpoint",
"externalInvocation",
"success",
"CRD",
},
{
"Test HTTP to HTTPS Externally using HTTP Endpoint CRD",
"/httptohttptest_external",
"external-http-endpoint-tls",
"externalInvocation",
"success",
"TLS",
},
}
var crossNamespaceTests = []struct {
in string
path string
remoteApp string
appMethod string
expectedResponse string
}{
// For descriptions, see corresponding methods in dapr/tests/apps/service_invocation/app.go
{
"Test HTTP to HTTP",
"httptohttptest",
"secondary-ns-http",
"httptohttptest",
"success",
},
{
"Test HTTP to gRPC",
"httptogrpctest",
"secondary-ns-grpc",
"httptogrpctest",
"success",
},
{
"Test gRPC to HTTP",
"grpctohttptest",
"secondary-ns-http",
"grpctohttptest",
"success",
},
{
"Test gRPC to gRPC",
"grpctogrpctest",
"secondary-ns-grpc",
"grpcToGrpcTest",
"success",
},
}
var grpcProxyTests = []struct {
in string
remoteApp string
appMethod string
expectedResponse string
}{
{
"Test grpc proxy",
"grpcproxyclient",
"",
"success",
},
{
"Test grpc proxy",
"grpcproxyclient",
"maxsize",
"success",
},
}
func TestServiceInvocation(t *testing.T) {
testFn := func(targetApp string) func(t *testing.T) {
return func(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL(targetApp)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
var err error
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err = utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
t.Logf("externalURL is '%s'", externalURL)
for _, tt := range serviceinvocationTests {
t.Run(tt.in, func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: tt.remoteApp,
Method: tt.appMethod,
})
require.NoError(t, err)
resp, err := utils.HTTPPost(
fmt.Sprintf("%s/tests/invoke_test", externalURL), body)
t.Log("checking err...")
require.NoError(t, err)
var appResp appResponse
t.Logf("unmarshalling..%s", string(resp))
err = json.Unmarshal(resp, &appResp)
require.NoError(t, err)
require.Equal(t, tt.expectedResponse, appResp.Message)
})
}
for _, tt := range moreServiceinvocationTests {
t.Run(tt.in, func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: tt.remoteApp,
Method: tt.appMethod,
})
require.NoError(t, err)
url := fmt.Sprintf("http://%s/%s", externalURL, tt.path)
t.Logf("url is '%s'", url)
resp, err := utils.HTTPPost(
url,
body)
t.Log("checking err...")
require.NoError(t, err)
var appResp appResponse
t.Logf("unmarshalling..%s", string(resp))
err = json.Unmarshal(resp, &appResp)
require.NoError(t, err)
require.Equal(t, tt.expectedResponse, appResp.Message)
})
}
// make sure dapr do not auto unescape path
for _, tt := range serviceinvocationPathTests {
t.Run(tt.in, func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: tt.remoteApp,
Method: tt.appMethod,
})
require.NoError(t, err)
url := fmt.Sprintf("http://%s/%s", externalURL, tt.appMethod)
t.Logf("url is '%s'", url)
resp, err := utils.HTTPPost(
url,
body)
t.Log("checking err...")
require.NoError(t, err)
var appResp appResponse
t.Logf("unmarshalling..%s", string(resp))
err = json.Unmarshal(resp, &appResp)
require.NoError(t, err)
require.Equal(t, tt.expectedResponse, appResp.Message)
})
}
// test redirect
for _, tt := range serviceInvocationRedirectTests {
t.Run(tt.in, func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: tt.remoteApp,
Method: tt.appMethod,
})
require.NoError(t, err)
url := fmt.Sprintf("http://%s/%s", externalURL, tt.appMethod)
t.Logf("url is '%s'", url)
resp, code, err := utils.HTTPPostWithStatus(
url,
body)
t.Log("checking err...")
require.NoError(t, err)
var appResp appResponse
t.Logf("unmarshalling..%s", string(resp))
err = json.Unmarshal(resp, &appResp)
require.NoError(t, err)
require.Equal(t, tt.expectedResponse, appResp.Message)
require.Equal(t, tt.expectedStatusCode, code)
})
}
}
}
t.Run("serviceinvocation-caller", testFn("serviceinvocation-caller"))
}
func TestServiceInvocationExternally(t *testing.T) {
if kitUtils.IsTruthy(os.Getenv("SKIP_EXTERNAL_INVOCATION")) {
t.Skip()
}
testFn := func(targetApp string) func(t *testing.T) {
return func(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL(targetApp)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
t.Logf("ExternalURL is '%s'", externalURL)
healthCheckURLs := []string{externalURL}
// External address is hardcoded
invokeExternalServiceAddress := "http://service-invocation-external:80"
if kubePlatform, ok := tr.Platform.(*runner.KubeTestPlatform); ok {
// To perform healthchecks, we need to first get the Load Balancer address
// Our tests will still use the hostname within the cluster for reliability reasons
app := kubePlatform.AppResources.FindActiveResource("serviceinvocation-callee-external").(*kube.AppManager)
svc, err := app.WaitUntilServiceState("service-invocation-external", app.IsServiceIngressReady)
require.NoError(t, err)
extURL := app.AcquireExternalURLFromService(svc)
if extURL != "" {
t.Logf("External service's load balancer is '%s'", extURL)
healthCheckURLs = append(healthCheckURLs, extURL)
}
}
// Perform healthchecks to ensure apps are ready
err := utils.HealthCheckApps(healthCheckURLs...)
require.NoError(t, err)
// invoke via overwritten URL to non-Daprized service
for _, tt := range externalServiceInvocationTests {
testCommandReq := testCommandRequest{
RemoteApp: tt.remoteApp,
Method: tt.appMethod,
}
switch tt.testType {
case "URL":
// test using overwritten URLs
t.Run(tt.in, func(t *testing.T) {
body, err := json.Marshal(testCommandRequestExternal{
testCommandRequest: testCommandReq,
ExternalIP: invokeExternalServiceAddress,
})
require.NoError(t, err)
t.Logf("invoking post to http://%s%s", externalURL, tt.path)
resp, err := utils.HTTPPost(
fmt.Sprintf("http://%s%s", externalURL, tt.path), body)
t.Log("checking err...")
require.NoError(t, err)
var appResp appResponse
t.Logf("unmarshalling..%s", string(resp))
err = json.Unmarshal(resp, &appResp)
t.Logf("appResp %s", appResp)
require.NoError(t, err)
require.Equal(t, tt.expectedResponse, appResp.Message)
})
case "CRD":
// invoke via HTTPEndpoint CRD
t.Run(tt.in, func(t *testing.T) {
body, err := json.Marshal(testCommandRequestExternal{
testCommandRequest: testCommandReq,
})
require.NoError(t, err)
resp, err := utils.HTTPPost(
fmt.Sprintf("http://%s%s", externalURL, tt.path), body)
t.Log("checking err...")
require.NoError(t, err)
var appResp appResponse
t.Logf("unmarshalling..%s", string(resp))
err = json.Unmarshal(resp, &appResp)
t.Logf("appResp %s", appResp)
require.NoError(t, err)
require.Equal(t, tt.expectedResponse, appResp.Message)
})
case "TLS":
// invoke via HTTPEndpoint CRD with TLS
t.Run(tt.in, func(t *testing.T) {
body, err := json.Marshal(testCommandRequestExternal{
testCommandRequest: testCommandReq,
})
require.NoError(t, err)
resp, err := utils.HTTPPost(
fmt.Sprintf("http://%s%s", externalURL, tt.path), body)
t.Log("checking err...")
require.NoError(t, err)
var appResp appResponse
t.Logf("unmarshalling..%s", string(resp))
err = json.Unmarshal(resp, &appResp)
t.Logf("appResp %s", appResp)
require.NoError(t, err)
require.Equal(t, tt.expectedResponse, appResp.Message)
})
}
}
}
}
t.Run("serviceinvocation-callee-external", testFn("serviceinvocation-caller"))
}
func TestGRPCProxy(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL("grpcproxyclient")
require.NotEmpty(t, externalURL, "external URL must not be empty!")
var err error
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err = utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
t.Logf("externalURL is '%s'\n", externalURL)
for _, tt := range grpcProxyTests {
t.Run(tt.in, func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: tt.remoteApp,
Method: tt.appMethod,
})
require.NoError(t, err)
resp, err := utils.HTTPPost(
fmt.Sprintf("%s/tests/invoke_test", externalURL), body)
t.Log("checking err...")
require.NoError(t, err)
var appResp appResponse
t.Logf("unmarshalling..%s\n", string(resp))
err = json.Unmarshal(resp, &appResp)
require.NoError(t, err)
require.Equal(t, tt.expectedResponse, appResp.Message)
})
}
}
func TestHeadersExternal(t *testing.T) {
if kitUtils.IsTruthy(os.Getenv("SKIP_EXTERNAL_INVOCATION")) {
t.Skip()
}
targetApp := "serviceinvocation-caller"
externalURL := tr.Platform.AcquireAppExternalURL(targetApp)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
hostname := "serviceinvocation-callee-external"
hostnameCRD := "external-http-endpoint"
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
t.Logf("externalURL is '%s'\n", externalURL)
t.Run("http-to-http-v1-using-external-invocation-overwritten-url", func(t *testing.T) {
url := fmt.Sprintf("http://%s/tests/v1_httptohttptest_external", externalURL)
verifyHTTPToHTTPExternal(t, externalURL, targetApp, url, hostname)
})
t.Run("http-to-http-v1-using-external-invocation-crd", func(t *testing.T) {
url := fmt.Sprintf("http://%s/tests/v1_httptohttptest_external", externalURL)
verifyHTTPToHTTPExternal(t, externalURL, targetApp, url, hostnameCRD)
})
}
func TestHeaders(t *testing.T) {
testFn := func(targetApp string) func(t *testing.T) {
return func(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL(targetApp)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
hostname, hostIP, err := tr.Platform.GetAppHostDetails(targetApp)
require.NoError(t, err, "error retrieving host details: %s", err)
expectedForwarded := fmt.Sprintf("for=%s;by=%s;host=%s", hostIP, hostIP, hostname)
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err = utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
t.Logf("externalURL is '%s'\n", externalURL)
t.Run("http-to-http-v1", func(t *testing.T) {
url := fmt.Sprintf("http://%s/tests/v1_httptohttptest", externalURL)
verifyHTTPToHTTP(t, hostIP, hostname, url, expectedForwarded, "serviceinvocation-callee-0")
})
t.Run("http-to-http-dapr-app-id", func(t *testing.T) {
url := fmt.Sprintf("http://%s/tests/dapr_id_httptohttptest", externalURL)
verifyHTTPToHTTP(t, hostIP, hostname, url, expectedForwarded, "serviceinvocation-callee-0")
})
t.Run("grpc-to-grpc", func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: "grpcapp",
Method: "grpc-to-grpc",
})
require.NoError(t, err)
resp, err := utils.HTTPPost(
fmt.Sprintf("http://%s/tests/v1_grpctogrpctest", externalURL), body)
t.Log("checking err...")
require.NoError(t, err)
var appResp appResponse
t.Logf("unmarshalling..%s\n", string(resp))
err = json.Unmarshal(resp, &appResp)
actualHeaders := struct {
Request string `json:"request"`
Response string `json:"response"`
Trailers string `json:"trailers"`
}{}
err = json.Unmarshal([]byte(appResp.Message), &actualHeaders)
require.NoError(t, err, "failed to unmarshal response: %s", appResp.Message)
requestHeaders := map[string][]string{}
responseHeaders := map[string][]string{}
trailerHeaders := map[string][]string{}
json.Unmarshal([]byte(actualHeaders.Request), &requestHeaders)
json.Unmarshal([]byte(actualHeaders.Response), &responseHeaders)
json.Unmarshal([]byte(actualHeaders.Trailers), &trailerHeaders)
require.NoError(t, err)
_ = assert.NotEmpty(t, requestHeaders["content-type"]) &&
assert.Equal(t, "application/grpc", requestHeaders["content-type"][0])
_ = assert.NotEmpty(t, requestHeaders[":authority"]) &&
assert.Equal(t, "127.0.0.1:3000", requestHeaders[":authority"][0])
_ = assert.NotEmpty(t, requestHeaders["daprtest-request-1"]) &&
assert.Equal(t, "DaprValue1", requestHeaders["daprtest-request-1"][0])
_ = assert.NotEmpty(t, requestHeaders["daprtest-request-2"]) &&
assert.Equal(t, "DaprValue2", requestHeaders["daprtest-request-2"][0])
_ = assert.NotEmpty(t, requestHeaders["daprtest-multi"]) &&
assert.Equal(t, []string{"M'illumino", "d'immenso"}, requestHeaders["daprtest-multi"])
_ = assert.NotEmpty(t, requestHeaders["user-agent"]) &&
assert.NotNil(t, requestHeaders["user-agent"][0])
grpcTraceBinRq := requestHeaders["grpc-trace-bin"]
if assert.NotNil(t, grpcTraceBinRq, "grpc-trace-bin is missing from the request") {
if assert.Equal(t, 1, len(grpcTraceBinRq), "grpc-trace-bin is missing from the request") {
assert.NotEqual(t, "", grpcTraceBinRq[0], "grpc-trace-bin is missing from the request")
}
}
traceParentRq := requestHeaders["traceparent"]
if assert.NotNil(t, traceParentRq, "traceparent is missing from the request") {
if assert.Equal(t, 1, len(traceParentRq), "traceparent is missing from the request") {
assert.NotEqual(t, "", traceParentRq[0], "traceparent is missing from the request")
}
}
_ = assert.NotEmpty(t, requestHeaders["x-forwarded-for"]) &&
assert.Equal(t, hostIP, requestHeaders["x-forwarded-for"][0])
_ = assert.NotEmpty(t, requestHeaders["x-forwarded-host"]) &&
assert.Equal(t, hostname, requestHeaders["x-forwarded-host"][0])
_ = assert.NotEmpty(t, requestHeaders["forwarded"]) &&
assert.Equal(t, expectedForwarded, requestHeaders["forwarded"][0])
_ = assert.NotEmpty(t, requestHeaders[invokev1.CallerIDHeader]) &&
assert.Equal(t, targetApp, requestHeaders[invokev1.CallerIDHeader][0])
_ = assert.NotEmpty(t, requestHeaders[invokev1.CalleeIDHeader]) &&
assert.Equal(t, "grpcapp", requestHeaders[invokev1.CalleeIDHeader][0])
_ = assert.NotEmpty(t, responseHeaders["content-type"]) &&
assert.Equal(t, "application/grpc", responseHeaders["content-type"][0])
_ = assert.NotEmpty(t, responseHeaders["daprtest-response-1"]) &&
assert.Equal(t, "DaprTest-Response-Value-1", responseHeaders["daprtest-response-1"][0])
_ = assert.NotEmpty(t, responseHeaders["daprtest-response-2"]) &&
assert.Equal(t, "DaprTest-Response-Value-2", responseHeaders["daprtest-response-2"][0])
_ = assert.NotEmpty(t, responseHeaders["daprtest-response-multi"]) &&
assert.Equal(t, []string{"DaprTest-Response-Multi-1", "DaprTest-Response-Multi-2"}, responseHeaders["daprtest-response-multi"])
grpcTraceBinRs := responseHeaders["grpc-trace-bin"]
if assert.NotNil(t, grpcTraceBinRs, "grpc-trace-bin is missing from the response") {
if assert.Equal(t, 1, len(grpcTraceBinRs), "grpc-trace-bin is missing from the response") {
assert.NotEqual(t, "", grpcTraceBinRs[0], "grpc-trace-bin is missing from the response")
}
}
traceParentRs := responseHeaders["traceparent"]
if assert.NotNil(t, traceParentRs, "traceparent is missing from the response") {
if assert.Equal(t, 1, len(traceParentRs), "traceparent is missing from the response") {
assert.NotEqual(t, "", traceParentRs[0], "traceparent is missing from the response")
}
}
_ = assert.NotEmpty(t, trailerHeaders["daprtest-trailer-1"]) &&
assert.Equal(t, "DaprTest-Trailer-Value-1", trailerHeaders["daprtest-trailer-1"][0])
_ = assert.NotEmpty(t, trailerHeaders["daprtest-trailer-2"]) &&
assert.Equal(t, "DaprTest-Trailer-Value-2", trailerHeaders["daprtest-trailer-2"][0])
_ = assert.NotEmpty(t, trailerHeaders["daprtest-trailer-multi"]) &&
assert.Equal(t, []string{"DaprTest-Trailer-Multi-1", "DaprTest-Trailer-Multi-2"}, trailerHeaders["daprtest-trailer-multi"])
})
t.Run("grpc-to-http", func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: "serviceinvocation-callee-0",
Method: "grpc-to-http",
})
require.NoError(t, err)
resp, err := utils.HTTPPost(
fmt.Sprintf("http://%s/tests/v1_grpctohttptest", externalURL), body)
t.Log("checking err...")
require.NoError(t, err)
var appResp appResponse
t.Logf("unmarshalling..%s\n", string(resp))
err = json.Unmarshal(resp, &appResp)
actualHeaders := struct {
Request string `json:"request"`
Response string `json:"response"`
}{}
err = json.Unmarshal([]byte(appResp.Message), &actualHeaders)
require.NoError(t, err, "failed to unmarshal response: %s", appResp.Message)
requestHeaders := map[string][]string{}
responseHeaders := map[string][]string{}
json.Unmarshal([]byte(actualHeaders.Request), &requestHeaders)
json.Unmarshal([]byte(actualHeaders.Response), &responseHeaders)
require.NoError(t, err)
_ = assert.NotEmpty(t, requestHeaders["Content-Type"]) &&
assert.Equal(t, "text/plain; utf-8", requestHeaders["Content-Type"][0])
_ = assert.NotEmpty(t, requestHeaders["Dapr-Authority"]) &&
assert.Equal(t, "localhost:50001", requestHeaders["Dapr-Authority"][0])
_ = assert.NotEmpty(t, requestHeaders["Daprtest-Request-1"]) &&
assert.Equal(t, "DaprValue1", requestHeaders["Daprtest-Request-1"][0])
_ = assert.NotEmpty(t, requestHeaders["Daprtest-Request-2"]) &&
assert.Equal(t, "DaprValue2", requestHeaders["Daprtest-Request-2"][0])
_ = assert.NotEmpty(t, requestHeaders["Daprtest-Multi"]) &&
assert.Equal(t, []string{"M'illumino", "d'immenso"}, requestHeaders["Daprtest-Multi"])
_ = assert.NotEmpty(t, requestHeaders["Traceparent"]) &&
assert.NotNil(t, requestHeaders["Traceparent"][0])
_ = assert.NotEmpty(t, requestHeaders["User-Agent"]) &&
assert.NotNil(t, requestHeaders["User-Agent"][0])
_ = assert.NotEmpty(t, requestHeaders["X-Forwarded-For"]) &&
assert.Equal(t, hostIP, requestHeaders["X-Forwarded-For"][0])
_ = assert.NotEmpty(t, requestHeaders["X-Forwarded-Host"]) &&
assert.Equal(t, hostname, requestHeaders["X-Forwarded-Host"][0])
_ = assert.NotEmpty(t, requestHeaders["Forwarded"]) &&
assert.Equal(t, expectedForwarded, requestHeaders["Forwarded"][0])
_ = assert.NotEmpty(t, requestHeaders["Dapr-Caller-App-Id"]) &&
assert.Equal(t, targetApp, requestHeaders["Dapr-Caller-App-Id"][0])
_ = assert.NotEmpty(t, requestHeaders["Dapr-Callee-App-Id"]) &&
assert.Equal(t, "serviceinvocation-callee-0", requestHeaders["Dapr-Callee-App-Id"][0])
_ = assert.NotEmpty(t, responseHeaders["content-type"]) &&
assert.Equal(t, "application/grpc", responseHeaders["content-type"][0])
_ = assert.NotEmpty(t, responseHeaders["dapr-content-type"]) &&
assert.True(t, strings.HasPrefix(responseHeaders["dapr-content-type"][0], "application/json"))
_ = assert.NotEmpty(t, responseHeaders["dapr-date"]) &&
assert.NotNil(t, responseHeaders["dapr-date"][0])
_ = assert.NotEmpty(t, responseHeaders["daprtest-response-1"]) &&
assert.Equal(t, "DaprTest-Response-Value-1", responseHeaders["daprtest-response-1"][0])
_ = assert.NotEmpty(t, responseHeaders["daprtest-response-2"]) &&
assert.Equal(t, "DaprTest-Response-Value-2", responseHeaders["daprtest-response-2"][0])
_ = assert.NotEmpty(t, responseHeaders["daprtest-response-multi"]) &&
assert.Equal(t, []string{"DaprTest-Response-Multi-1", "DaprTest-Response-Multi-2"}, responseHeaders["daprtest-response-multi"])
grpcTraceBinRs := responseHeaders["grpc-trace-bin"]
if assert.NotNil(t, grpcTraceBinRs, "grpc-trace-bin is missing from the response") {
if assert.Equal(t, 1, len(grpcTraceBinRs), "grpc-trace-bin is missing from the response") {
assert.NotEqual(t, "", grpcTraceBinRs[0], "grpc-trace-bin is missing from the response")
}
}
})
t.Run("http-to-grpc", func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: "grpcapp",
Method: "http-to-grpc",
})
require.NoError(t, err)
resp, err := utils.HTTPPost(
fmt.Sprintf("http://%s/tests/v1_httptogrpctest", externalURL), body)
t.Log("checking err...")
require.NoError(t, err)
var appResp appResponse
t.Logf("unmarshalling..%s\n", string(resp))
err = json.Unmarshal(resp, &appResp)
actualHeaders := struct {
Request string `json:"request"`
Response string `json:"response"`
}{}
err = json.Unmarshal([]byte(appResp.Message), &actualHeaders)
require.NoError(t, err, "failed to unmarshal response: %s", appResp.Message)
requestHeaders := map[string][]string{}
responseHeaders := map[string][]string{}
json.Unmarshal([]byte(actualHeaders.Request), &requestHeaders)
json.Unmarshal([]byte(actualHeaders.Response), &responseHeaders)
require.NoError(t, err)
_ = assert.NotEmpty(t, requestHeaders["content-type"]) &&
assert.Equal(t, "application/grpc", requestHeaders["content-type"][0])
_ = assert.NotEmpty(t, requestHeaders[":authority"]) &&
assert.True(t, strings.HasPrefix(requestHeaders[":authority"][0], "127.0.0.1:"))
_ = assert.NotEmpty(t, requestHeaders["daprtest-request-1"]) &&
assert.Equal(t, "DaprValue1", requestHeaders["daprtest-request-1"][0])
_ = assert.NotEmpty(t, requestHeaders["daprtest-request-1"]) &&
assert.Equal(t, "DaprValue2", requestHeaders["daprtest-request-2"][0])
_ = assert.NotEmpty(t, requestHeaders["daprtest-multi"]) &&
assert.Equal(t, []string{"M'illumino", "d'immenso"}, requestHeaders["daprtest-multi"])
_ = assert.NotEmpty(t, requestHeaders["user-agent"]) &&
assert.NotNil(t, requestHeaders["user-agent"][0])
grpcTraceBinRq := requestHeaders["grpc-trace-bin"]
if assert.NotNil(t, grpcTraceBinRq, "grpc-trace-bin is missing from the request") {
if assert.Equal(t, 1, len(grpcTraceBinRq), "grpc-trace-bin is missing from the request") {
assert.NotEqual(t, "", grpcTraceBinRq[0], "grpc-trace-bin is missing from the request")
}
}
traceParentRq := requestHeaders["traceparent"]
if assert.NotNil(t, traceParentRq, "traceparent is missing from the request") {
if assert.Equal(t, 1, len(traceParentRq), "traceparent is missing from the request") {
assert.NotEqual(t, "", traceParentRq[0], "traceparent is missing from the request")
}
}
_ = assert.NotEmpty(t, requestHeaders["x-forwarded-for"]) &&
assert.Equal(t, hostIP, requestHeaders["x-forwarded-for"][0])
_ = assert.NotEmpty(t, requestHeaders["x-forwarded-host"]) &&
assert.Equal(t, hostname, requestHeaders["x-forwarded-host"][0])
_ = assert.NotEmpty(t, requestHeaders["forwarded"]) &&
assert.Equal(t, expectedForwarded, requestHeaders["forwarded"][0])
assert.Equal(t, targetApp, requestHeaders[invokev1.CallerIDHeader][0])
assert.Equal(t, "grpcapp", requestHeaders[invokev1.CalleeIDHeader][0])
_ = assert.NotEmpty(t, responseHeaders["Content-Type"]) &&
assert.True(t, strings.HasPrefix(responseHeaders["Content-Type"][0], "application/json"))
_ = assert.NotEmpty(t, responseHeaders["Date"]) &&
assert.NotNil(t, responseHeaders["Date"][0])
_ = assert.NotEmpty(t, responseHeaders["Daprtest-Response-1"]) &&
assert.Equal(t, "DaprTest-Response-Value-1", responseHeaders["Daprtest-Response-1"][0])
_ = assert.NotEmpty(t, responseHeaders["Daprtest-Response-2"]) &&
assert.Equal(t, "DaprTest-Response-Value-2", responseHeaders["Daprtest-Response-2"][0])
_ = assert.NotEmpty(t, responseHeaders["Daprtest-Response-Multi"]) &&
assert.Equal(t, []string{"DaprTest-Response-Multi-1", "DaprTest-Response-Multi-2"}, responseHeaders["Daprtest-Response-Multi"])
_ = assert.NotEmpty(t, responseHeaders["Traceparent"]) &&
assert.NotNil(t, responseHeaders["Traceparent"][0])
})
/* Tracing specific tests */
/*
// following is the span context of expectedTraceID
trace.SpanContext{
TraceID: trace.TraceID{75, 249, 47, 53, 119, 179, 77, 166, 163, 206, 146, 157, 14, 14, 71, 54},
SpanID: trace.SpanID{0, 240, 103, 170, 11, 169, 2, 183},
TraceOptions: trace.TraceOptions(1),
}
string representation of span context : "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
all the -bin headers are stored in Dapr as base64 encoded string.
for the above span context when passed in grpc-trace-bin header, Dapr retrieved binary header and stored as encoded string.
the encoded string for the above span context is :
"AABL+S81d7NNpqPOkp0ODkc2AQDwZ6oLqQK3AgE="
*/
expectedTraceID := "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
expectedEncodedTraceID := "AABL+S81d7NNpqPOkp0ODkc2AQDwZ6oLqQK3AgE="
t.Run("http-to-http-tracing-v1", func(t *testing.T) {
url := fmt.Sprintf("http://%s/tests/v1_httptohttptest", externalURL)
verifyHTTPToHTTPTracing(t, url, expectedTraceID, "serviceinvocation-callee-0")
})
t.Run("http-to-http-tracing-dapr-id", func(t *testing.T) {
url := fmt.Sprintf("http://%s/tests/dapr_id_httptohttptest", externalURL)
verifyHTTPToHTTPTracing(t, url, expectedTraceID, "serviceinvocation-callee-0")
})
t.Run("grpc-to-grpc-tracing", func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: "grpcapp",
Method: "grpc-to-grpc-tracing",
RemoteAppTracing: "true",
})
require.NoError(t, err)
resp, err := utils.HTTPPost(
fmt.Sprintf("http://%s/tests/v1_grpctogrpctest", externalURL), body)
t.Log("checking err...")
require.NoError(t, err)
var appResp appResponse
t.Logf("unmarshalling..%s\n", string(resp))
err = json.Unmarshal(resp, &appResp)
actualHeaders := struct {
Request string `json:"request"`
Response string `json:"response"`
Trailers string `json:"trailers"`
}{}
err = json.Unmarshal([]byte(appResp.Message), &actualHeaders)
require.NoError(t, err, "failed to unmarshal response: %s", appResp.Message)
requestHeaders := map[string][]string{}
responseHeaders := map[string][]string{}
trailerHeaders := map[string][]string{}
json.Unmarshal([]byte(actualHeaders.Request), &requestHeaders)
json.Unmarshal([]byte(actualHeaders.Response), &responseHeaders)
json.Unmarshal([]byte(actualHeaders.Trailers), &trailerHeaders)
require.NoError(t, err)
grpcTraceBinRq := requestHeaders["grpc-trace-bin"]
if assert.NotNil(t, grpcTraceBinRq, "grpc-trace-bin is missing from the request") {
if assert.Equal(t, 1, len(grpcTraceBinRq), "grpc-trace-bin is missing from the request") {
assert.NotEqual(t, "", grpcTraceBinRq[0], "grpc-trace-bin is missing from the request")
}
}
traceParentRq := requestHeaders["traceparent"]
if assert.NotNil(t, traceParentRq, "traceparent is missing from the request") {
if assert.Equal(t, 1, len(traceParentRq), "traceparent is missing from the request") {
assert.NotEqual(t, "", traceParentRq[0], "traceparent is missing from the request")
}
}
grpcTraceBinRs := responseHeaders["grpc-trace-bin"]
if assert.NotNil(t, grpcTraceBinRs) {
if assert.Equal(t, 1, len(grpcTraceBinRs)) {
traceContext := grpcTraceBinRs[0]
t.Logf("received response grpc header..%s\n", traceContext)
assert.Equal(t, expectedEncodedTraceID, traceContext)
decoded, _ := base64.StdEncoding.DecodeString(traceContext)
gotSc, ok := diagUtils.SpanContextFromBinary(decoded)
assert.True(t, ok)
assert.NotNil(t, gotSc)
assert.Equal(t, expectedTraceID, diag.SpanContextToW3CString(gotSc))
}
}
traceParentRs := responseHeaders["traceparent"]
if assert.NotNil(t, traceParentRs, "traceparent is missing from the response") {
if assert.Equal(t, 1, len(traceParentRs), "traceparent is missing from the response") {
assert.Equal(t, expectedTraceID, traceParentRs[0], "traceparent value was not expected")
}
}
})
t.Run("http-to-grpc-tracing", func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: "grpcapp",
Method: "http-to-grpc-tracing",
RemoteAppTracing: "true",
})
require.NoError(t, err)
resp, err := utils.HTTPPost(
fmt.Sprintf("http://%s/tests/v1_httptogrpctest", externalURL), body)
t.Log("checking err...")
require.NoError(t, err)
var appResp appResponse
t.Logf("unmarshalling..%s\n", string(resp))
err = json.Unmarshal(resp, &appResp)
actualHeaders := struct {
Request string `json:"request"`
Response string `json:"response"`
}{}
err = json.Unmarshal([]byte(appResp.Message), &actualHeaders)
require.NoError(t, err, "failed to unmarshal response: %s", appResp.Message)
requestHeaders := map[string][]string{}
responseHeaders := map[string][]string{}
json.Unmarshal([]byte(actualHeaders.Request), &requestHeaders)
json.Unmarshal([]byte(actualHeaders.Response), &responseHeaders)
require.NoError(t, err)
grpcTraceBinRq := requestHeaders["grpc-trace-bin"]
if assert.NotNil(t, grpcTraceBinRq, "grpc-trace-bin is missing from the request") {
if assert.Equal(t, 1, len(grpcTraceBinRq), "grpc-trace-bin is missing from the request") {
assert.NotEqual(t, "", grpcTraceBinRq[0], "grpc-trace-bin is missing from the request")
}
}
})
t.Run("grpc-to-http-tracing", func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: "serviceinvocation-callee-0",
Method: "grpc-to-http-tracing",
RemoteAppTracing: "true",
})
require.NoError(t, err)
resp, err := utils.HTTPPost(
fmt.Sprintf("http://%s/tests/v1_grpctohttptest", externalURL), body)
t.Log("checking err...")
require.NoError(t, err)
var appResp appResponse
t.Logf("unmarshalling..%s\n", string(resp))
err = json.Unmarshal(resp, &appResp)
actualHeaders := struct {
Request string `json:"request"`
Response string `json:"response"`
}{}
err = json.Unmarshal([]byte(appResp.Message), &actualHeaders)
require.NoError(t, err, "failed to unmarshal response: %s", appResp.Message)
requestHeaders := map[string][]string{}
responseHeaders := map[string][]string{}
json.Unmarshal([]byte(actualHeaders.Request), &requestHeaders)
json.Unmarshal([]byte(actualHeaders.Response), &responseHeaders)
require.NoError(t, err)
_ = assert.NotEmpty(t, requestHeaders["Traceparent"]) &&
assert.NotNil(t, requestHeaders["Traceparent"][0])
_ = assert.NotEmpty(t, requestHeaders["Daprtest-Traceid"]) &&
assert.Equal(t, expectedTraceID, requestHeaders["Daprtest-Traceid"][0])
grpcTraceBinRs := responseHeaders["grpc-trace-bin"]
if assert.NotNil(t, grpcTraceBinRs, "grpc-trace-bin is missing from the response") {
if assert.Equal(t, 1, len(grpcTraceBinRs), "grpc-trace-bin is missing from the response") {
traceContext := grpcTraceBinRs[0]
assert.NotEqual(t, "", traceContext)
t.Logf("received response grpc header..%s\n", traceContext)
assert.Equal(t, expectedEncodedTraceID, traceContext)
decoded, _ := base64.StdEncoding.DecodeString(traceContext)
gotSc, ok := diagUtils.SpanContextFromBinary(decoded)
assert.True(t, ok)
assert.NotNil(t, gotSc)
assert.Equal(t, expectedTraceID, diag.SpanContextToW3CString(gotSc))
}
}
})
}
}
t.Run("serviceinvocation-caller", testFn("serviceinvocation-caller"))
}
func verifyHTTPToHTTPTracing(t *testing.T, url string, expectedTraceID string, remoteApp string) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: remoteApp,
Method: "http-to-http-tracing",
RemoteAppTracing: "true",
})
require.NoError(t, err)
resp, err := utils.HTTPPost(url, body)
t.Log("checking err...")
require.NoError(t, err)
var appResp appResponse
t.Logf("unmarshalling..%s\n", string(resp))
err = json.Unmarshal(resp, &appResp)
actualHeaders := struct {
Request string `json:"request"`
Response string `json:"response"`
}{}
err = json.Unmarshal([]byte(appResp.Message), &actualHeaders)
require.NoError(t, err, "failed to unmarshal response: %s", appResp.Message)
requestHeaders := map[string][]string{}
responseHeaders := map[string][]string{}
json.Unmarshal([]byte(actualHeaders.Request), &requestHeaders)
json.Unmarshal([]byte(actualHeaders.Response), &responseHeaders)
require.NoError(t, err)
_ = assert.NotEmpty(t, requestHeaders["Traceparent"]) &&
assert.NotNil(t, requestHeaders["Traceparent"][0])
_ = assert.NotEmpty(t, requestHeaders["Daprtest-Traceid"]) &&
assert.Equal(t, expectedTraceID, requestHeaders["Daprtest-Traceid"][0])
traceParentRs := responseHeaders["Traceparent"]
if assert.NotNil(t, traceParentRs, "Traceparent is missing from the response") {
if assert.Equal(t, 1, len(traceParentRs), "Traceparent is missing from the response") {
assert.Equal(t, expectedTraceID, traceParentRs[0], "Traceparent value was not expected")
}
}
}
func verifyHTTPToHTTP(t *testing.T, hostIP string, hostname string, url string, expectedForwarded string, remoteApp string) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: remoteApp,
Method: "http-to-http",
})
require.NoError(t, err)
resp, err := utils.HTTPPost(url, body)
t.Log("checking err...")
require.NoError(t, err)
var appResp appResponse
t.Logf("unmarshalling..%s\n", string(resp))
err = json.Unmarshal(resp, &appResp)
actualHeaders := struct {
Request string `json:"request"`
Response string `json:"response"`
}{}
err = json.Unmarshal([]byte(appResp.Message), &actualHeaders)
require.NoError(t, err, "failed to unmarshal response: %s", appResp.Message)
requestHeaders := map[string][]string{}
responseHeaders := map[string][]string{}
json.Unmarshal([]byte(actualHeaders.Request), &requestHeaders)
json.Unmarshal([]byte(actualHeaders.Response), &responseHeaders)
t.Logf("requestHeaders: [%#v] - responseHeaders: [%#v]", requestHeaders, responseHeaders)
require.NoError(t, err)
_ = assert.NotEmpty(t, requestHeaders["Content-Type"]) &&
assert.True(t, strings.HasPrefix(requestHeaders["Content-Type"][0], "application/json"))
_ = assert.NotEmpty(t, requestHeaders["Daprtest-Request-1"]) &&
assert.Equal(t, "DaprValue1", requestHeaders["Daprtest-Request-1"][0])
_ = assert.NotEmpty(t, requestHeaders["Daprtest-Request-2"]) &&
assert.Equal(t, "DaprValue2", requestHeaders["Daprtest-Request-2"][0])
_ = assert.NotEmpty(t, requestHeaders["Daprtest-Multi"]) &&
assert.Equal(t, []string{"M'illumino", "d'immenso"}, requestHeaders["Daprtest-Multi"])
_ = assert.NotEmpty(t, requestHeaders["Traceparent"]) &&
assert.NotNil(t, requestHeaders["Traceparent"][0])
_ = assert.NotEmpty(t, requestHeaders["User-Agent"]) &&
assert.NotNil(t, requestHeaders["User-Agent"][0])
_ = assert.NotEmpty(t, requestHeaders["X-Forwarded-For"]) &&
assert.Equal(t, hostIP, requestHeaders["X-Forwarded-For"][0])
_ = assert.NotEmpty(t, requestHeaders["X-Forwarded-Host"]) &&
assert.Equal(t, hostname, requestHeaders["X-Forwarded-Host"][0])
_ = assert.NotEmpty(t, requestHeaders["Forwarded"]) &&
assert.Equal(t, expectedForwarded, requestHeaders["Forwarded"][0])
_ = assert.NotEmpty(t, responseHeaders["Content-Type"]) &&
assert.True(t, strings.HasPrefix(responseHeaders["Content-Type"][0], "application/json"))
_ = assert.NotEmpty(t, responseHeaders["Daprtest-Response-1"]) &&
assert.Equal(t, "DaprTest-Response-Value-1", responseHeaders["Daprtest-Response-1"][0])
_ = assert.NotEmpty(t, responseHeaders["Daprtest-Response-2"]) &&
assert.Equal(t, "DaprTest-Response-Value-2", responseHeaders["Daprtest-Response-2"][0])
_ = assert.NotEmpty(t, responseHeaders["Daprtest-Response-Multi"]) &&
assert.Equal(t, []string{"DaprTest-Response-Multi-1", "DaprTest-Response-Multi-2"}, responseHeaders["Daprtest-Response-Multi"])
_ = assert.NotEmpty(t, responseHeaders["Traceparent"]) &&
assert.NotNil(t, responseHeaders["Traceparent"][0])
}
func verifyHTTPToHTTPExternal(t *testing.T, hostIP string, hostname string, url string, remoteApp string) {
invokeExternalServiceIP := "http://service-invocation-external"
body, err := json.Marshal(testCommandRequestExternal{
testCommandRequest: testCommandRequest{
RemoteApp: remoteApp,
Method: "/retrieve_request_object",
RemoteAppTracing: "true",
},
ExternalIP: invokeExternalServiceIP,
})
require.NoError(t, err)
resp, err := utils.HTTPPost(url, body)
t.Log("checking err...")
require.NoError(t, err)
var appResp appResponse
t.Logf("unmarshalling..%s\n", string(resp))
err = json.Unmarshal(resp, &appResp)
actualHeaders := struct {
Request string `json:"request"`
Response string `json:"response"`
}{}
err = json.Unmarshal([]byte(appResp.Message), &actualHeaders)
require.NoError(t, err, "failed to unmarshal response: %s", appResp.Message)
requestHeaders := map[string][]string{}
responseHeaders := map[string][]string{}
json.Unmarshal([]byte(actualHeaders.Request), &requestHeaders)
json.Unmarshal([]byte(actualHeaders.Response), &responseHeaders)
t.Logf("requestHeaders: [%#v] - responseHeaders: [%#v]", requestHeaders, responseHeaders)
require.NoError(t, err)
_ = assert.NotEmpty(t, requestHeaders["Content-Type"]) &&
assert.True(t, strings.HasPrefix(requestHeaders["Content-Type"][0], "application/json"))
_ = assert.NotEmpty(t, requestHeaders["Daprtest-Request-1"]) &&
assert.Equal(t, "DaprValue1", requestHeaders["Daprtest-Request-1"][0])
_ = assert.NotEmpty(t, requestHeaders["Daprtest-Request-2"]) &&
assert.Equal(t, "DaprValue2", requestHeaders["Daprtest-Request-2"][0])
_ = assert.NotEmpty(t, requestHeaders["Daprtest-Multi"]) &&
assert.Equal(t, []string{"M'illumino", "d'immenso"}, requestHeaders["Daprtest-Multi"])
_ = assert.NotEmpty(t, requestHeaders["Traceparent"]) &&
assert.NotNil(t, requestHeaders["Traceparent"][0])
_ = assert.NotEmpty(t, requestHeaders["User-Agent"]) &&
assert.NotNil(t, requestHeaders["User-Agent"][0])
_ = assert.NotEmpty(t, responseHeaders["Content-Type"]) &&
assert.True(t, strings.HasPrefix(responseHeaders["Content-Type"][0], "application/json"))
_ = assert.NotEmpty(t, responseHeaders["Daprtest-Response-1"]) &&
assert.Equal(t, "DaprTest-Response-Value-1", responseHeaders["Daprtest-Response-1"][0])
_ = assert.NotEmpty(t, responseHeaders["Daprtest-Response-2"]) &&
assert.Equal(t, "DaprTest-Response-Value-2", responseHeaders["Daprtest-Response-2"][0])
_ = assert.NotEmpty(t, responseHeaders["Daprtest-Response-Multi"]) &&
assert.Equal(t, []string{"DaprTest-Response-Multi-1", "DaprTest-Response-Multi-2"}, responseHeaders["Daprtest-Response-Multi"])
_ = assert.NotEmpty(t, responseHeaders["Traceparent"]) &&
assert.NotNil(t, responseHeaders["Traceparent"][0])
}
func TestUppercaseMiddlewareServiceInvocation(t *testing.T) {
testFn := func(targetApp string) func(t *testing.T) {
return func(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL(targetApp)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
t.Run("uppercase middleware should be applied", func(t *testing.T) {
testMessage := guuid.New().String()
body, err := json.Marshal(testCommandRequest{
RemoteApp: "serviceinvocation-callee-2",
Method: "httptohttptest",
Message: &testMessage,
})
require.NoError(t, err)
resp, err := utils.HTTPPost(
fmt.Sprintf("%s/httptohttptest", externalURL), body)
t.Log("checking err...")
require.NoError(t, err)
var appResp appResponse
t.Logf("unmarshalling..%s\n", string(resp))
err = json.Unmarshal(resp, &appResp)
require.NoError(t, err)
uppercaseMsg := strings.ToUpper(testMessage)
require.Contains(t, appResp.Message, uppercaseMsg)
})
}
}
t.Run("serviceinvocation-caller", testFn("serviceinvocation-caller"))
}
func TestLoadBalancing(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL("serviceinvocation-caller")
require.NotEmpty(t, externalURL, "external URL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
// Make 50 invocations and make sure that we get responses from both apps
foundPIDs := map[string]int{}
var total int
for i := 0; i < 50; i++ {
resp, err := utils.HTTPPost(fmt.Sprintf("%s/tests/loadbalancing", externalURL), nil)
require.NoError(t, err)
var appResp appResponse
err = json.Unmarshal(resp, &appResp)
require.NoErrorf(t, err, "Failed to unmarshal response: %s", string(resp))
require.NotEmpty(t, appResp.Message)
foundPIDs[appResp.Message]++
total++
}
t.Logf("Found PIDs: %v", foundPIDs)
assert.Equal(t, 50, total)
assert.Len(t, foundPIDs, 2)
for pid, count := range foundPIDs {
// We won't have a perfect 50/50 distribution, so ensure that at least 5 requests (10%) hit each one
assert.GreaterOrEqualf(t, count, 5, "Instance with PID %s did not get at least 5 requests", pid)
}
}
func TestNegativeCases(t *testing.T) {
testFn := func(targetApp string) func(t *testing.T) {
return func(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL(targetApp)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
t.Logf("externalURL is '%s'\n", externalURL)
t.Run("missing_method_http", func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: "serviceinvocation-callee-0",
Method: "missing",
RemoteAppTracing: "true",
})
require.NoError(t, err)
resp, status, err := utils.HTTPPostWithStatus(fmt.Sprintf("http://%s/badservicecalltesthttp", externalURL), body)
var testResults negativeTestResult
json.Unmarshal(resp, &testResults)
// TODO: This doesn't return as an error, it should be handled more gracefully in dapr
require.False(t, testResults.MainCallSuccessful)
require.Equal(t, 404, status)
require.Contains(t, string(testResults.RawBody), "404 page not found")
require.Nil(t, err)
})
t.Run("missing_method_grpc", func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: "serviceinvocation-callee-0",
Method: "missing",
RemoteAppTracing: "true",
})
require.NoError(t, err)
resp, status, err := utils.HTTPPostWithStatus(fmt.Sprintf("http://%s/badservicecalltestgrpc", externalURL), body)
var testResults negativeTestResult
json.Unmarshal(resp, &testResults)
// TODO: This doesn't return as an error, it should be handled more gracefully in dapr
require.False(t, testResults.MainCallSuccessful)
require.Equal(t, 500, status)
require.Nil(t, testResults.RawBody)
require.Nil(t, err)
require.NotNil(t, testResults.RawError)
require.Contains(t, testResults.RawError, "rpc error: code = NotFound desc = Not Found")
})
t.Run("missing_service_http", func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: "missing-service-0",
Method: "posthandler",
RemoteAppTracing: "true",
})
require.NoError(t, err)
resp, status, err := utils.HTTPPostWithStatus(fmt.Sprintf("http://%s/badservicecalltesthttp", externalURL), body)
var testResults negativeTestResult
json.Unmarshal(resp, &testResults)
// TODO: This doesn't return as an error, it should be handled more gracefully in dapr
require.False(t, testResults.MainCallSuccessful)
require.Equal(t, 500, status)
require.Contains(t, string(testResults.RawBody), "failed to resolve address for 'missing-service-0-dapr.dapr-tests.svc.cluster.local'")
require.Nil(t, err)
})
t.Run("missing_service_grpc", func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: "missing-service-0",
Method: "posthandler",
RemoteAppTracing: "true",
})
require.NoError(t, err)
resp, status, err := utils.HTTPPostWithStatus(fmt.Sprintf("http://%s/badservicecalltestgrpc", externalURL), body)
var testResults negativeTestResult
json.Unmarshal(resp, &testResults)
// TODO: This doesn't return as an error, it should be handled more gracefully in dapr
require.False(t, testResults.MainCallSuccessful)
require.Equal(t, 500, status)
require.Nil(t, testResults.RawBody)
require.Nil(t, err)
require.NotNil(t, testResults.RawError)
require.Contains(t, testResults.RawError, "failed to resolve address for 'missing-service-0-dapr.dapr-tests.svc.cluster.local'")
})
t.Run("service_timeout_http", func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: "serviceinvocation-callee-0",
Method: "timeouterror",
RemoteAppTracing: "true",
})
require.NoError(t, err)
resp, status, _ := utils.HTTPPostWithStatus(fmt.Sprintf("http://%s/badservicecalltesthttp", externalURL), body)
var testResults negativeTestResult
json.Unmarshal(resp, &testResults)
require.False(t, testResults.MainCallSuccessful)
require.Equal(t, 500, status)
require.Contains(t, testResults.RawError, "Client.Timeout exceeded while awaiting headers")
require.NotContains(t, testResults.RawError, "Client waited longer than it should have.")
})
t.Run("service_timeout_grpc", func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: "serviceinvocation-callee-0",
Method: "timeouterror",
RemoteAppTracing: "true",
})
require.NoError(t, err)
resp, status, _ := utils.HTTPPostWithStatus(fmt.Sprintf("http://%s/badservicecalltestgrpc", externalURL), body)
var testResults negativeTestResult
json.Unmarshal(resp, &testResults)
require.False(t, testResults.MainCallSuccessful)
require.Equal(t, 500, status)
// This error could have code either DeadlineExceeded or Internal, depending on where the context timeout was caught
// Valid errors are:
// - `rpc error: code = Internal desc = failed to invoke, id: serviceinvocation-callee-0, err: rpc error: code = Internal desc = error invoking app channel: Post \"http://127.0.0.1:3000/timeouterror\": context deadline exceeded``
// - `rpc error: code = DeadlineExceeded desc = context deadline exceeded`
assert.Contains(t, testResults.RawError, "rpc error:")
assert.Contains(t, testResults.RawError, "context deadline exceeded")
assert.NotContains(t, testResults.RawError, "Client waited longer than it should have.")
})
t.Run("service_parse_error_http", func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: "serviceinvocation-callee-0",
Method: "parseerror",
RemoteAppTracing: "true",
})
require.NoError(t, err)
resp, status, err := utils.HTTPPostWithStatus(fmt.Sprintf("http://%s/badservicecalltesthttp", externalURL), body)
var testResults negativeTestResult
json.Unmarshal(resp, &testResults)
require.False(t, testResults.MainCallSuccessful)
require.Equal(t, 500, status)
require.Contains(t, string(testResults.RawBody), "serialization failed with json")
require.Nil(t, err)
})
t.Run("service_parse_error_grpc", func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: "serviceinvocation-callee-0",
Method: "parseerror",
RemoteAppTracing: "true",
})
require.NoError(t, err)
resp, status, err := utils.HTTPPostWithStatus(fmt.Sprintf("http://%s/badservicecalltestgrpc", externalURL), body)
var testResults negativeTestResult
json.Unmarshal(resp, &testResults)
require.False(t, testResults.MainCallSuccessful)
require.Equal(t, 500, status)
require.Nil(t, err)
require.Nil(t, testResults.RawBody)
require.Contains(t, testResults.RawError, "rpc error: code = Unknown desc = Internal Server Error")
})
t.Run("service_large_data_http", func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: "serviceinvocation-callee-0",
Method: "largedatahttp",
RemoteAppTracing: "true",
})
require.NoError(t, err)
resp, err := utils.HTTPPost(fmt.Sprintf("http://%s/badservicecalltesthttp", externalURL), body)
var testResults negativeTestResult
json.Unmarshal(resp, &testResults)
require.NoError(t, err)
require.True(t, testResults.MainCallSuccessful)
require.Len(t, testResults.Results, 4)
for _, result := range testResults.Results {
switch result.TestCase {
case "1MB":
assert.True(t, result.CallSuccessful)
case "4MB":
assert.True(t, result.CallSuccessful)
case "4MB+":
assert.False(t, result.CallSuccessful)
case "8MB":
assert.False(t, result.CallSuccessful)
}
}
})
t.Run("service_large_data_grpc", func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: "serviceinvocation-callee-0",
Method: "largedatagrpc",
RemoteAppTracing: "true",
})
require.NoError(t, err)
resp, err := utils.HTTPPost(fmt.Sprintf("http://%s/badservicecalltestgrpc", externalURL), body)
var testResults negativeTestResult
json.Unmarshal(resp, &testResults)
require.NoError(t, err)
require.True(t, testResults.MainCallSuccessful)
require.Len(t, testResults.Results, 4)
for _, result := range testResults.Results {
switch result.TestCase {
case "1MB":
assert.True(t, result.CallSuccessful)
case "4MB":
assert.True(t, result.CallSuccessful)
case "4MB+":
assert.False(t, result.CallSuccessful)
case "8MB":
assert.False(t, result.CallSuccessful)
}
}
})
}
}
t.Run("serviceinvocation-caller", testFn("serviceinvocation-caller"))
}
func TestNegativeCasesExternal(t *testing.T) {
if kitUtils.IsTruthy(os.Getenv("SKIP_EXTERNAL_INVOCATION")) {
t.Skip()
}
testFn := func(targetApp string) func(t *testing.T) {
return func(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL(targetApp)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
externalServiceName := "serviceinvocation-callee-external"
invokeExternalServiceIP := tr.Platform.AcquireAppExternalURL(externalServiceName)
// hostNameCRD := "service-invocation-external-via-crd"
// // This initial probe makes the test wait a little bit longer when needed,
// // making this test less flaky due to delays in the deployment.
// _, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
// require.NoError(t, err)
// t.Logf("externalURL is '%s'\n", externalURL)
t.Run("missing_method_http", func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: utils.SanitizeHTTPURL(invokeExternalServiceIP),
Method: "missing",
RemoteAppTracing: "true",
})
require.NoError(t, err)
resp, status, err := utils.HTTPPostWithStatus(fmt.Sprintf("http://%s/badservicecalltesthttp", externalURL), body)
var testResults negativeTestResult
require.NoError(t, json.Unmarshal(resp, &testResults))
// TODO: This doesn't return as an error, it should be handled more gracefully in dapr
require.False(t, testResults.MainCallSuccessful)
require.Equal(t, http.StatusNotFound, status)
require.Contains(t, string(testResults.RawBody), "404 page not found")
require.Nil(t, err)
})
/*TODO(@Sam): this is giving a 500 not 404
t.Run("missing_method_http - http endpoint CRD name", func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: hostNameCRD,
Method: "missing",
RemoteAppTracing: "true",
})
require.NoError(t, err)
resp, status, err := utils.HTTPPostWithStatus(fmt.Sprintf("http://%s/badservicecalltesthttp", externalURL), body)
var testResults negativeTestResult
require.NoError(t, json.Unmarshal(resp, &testResults), err)
// TODO: This doesn't return as an error, it should be handled more gracefully in dapr
require.False(t, testResults.MainCallSuccessful)
require.Equal(t, http.StatusNotFound, status)
require.Contains(t, string(testResults.RawBody), "404 page not found")
require.Nil(t, err)
})*/
//TODO(@Sam): test service timeout, parse error from service, and large data
}
}
t.Run("serviceinvocation-caller", testFn("serviceinvocation-caller"))
}
func TestCrossNamespaceCases(t *testing.T) {
testFn := func(targetApp string) func(t *testing.T) {
return func(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL(targetApp)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
t.Logf("externalURL is '%s'\n", externalURL)
for _, tt := range crossNamespaceTests {
remoteAppFQ := fmt.Sprintf("%s.%s", tt.remoteApp, secondaryNamespace)
t.Run(tt.in, func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: remoteAppFQ,
Method: tt.appMethod,
})
require.NoError(t, err)
url := fmt.Sprintf("http://%s/%s", externalURL, tt.path)
t.Logf("url is '%s'\n", url)
resp, err := utils.HTTPPost(
url,
body)
t.Log("checking err...")
require.NoError(t, err)
var appResp appResponse
t.Logf("unmarshalling..%s\n", string(resp))
err = json.Unmarshal(resp, &appResp)
require.NoError(t, err)
require.Equal(t, tt.expectedResponse, appResp.Message)
})
}
}
}
t.Run("serviceinvocation-caller", testFn("serviceinvocation-caller"))
}
func TestPathURLNormalization(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL("serviceinvocation-caller")
require.NotEmpty(t, externalURL, "external URL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
t.Logf("externalURL is '%s'\n", externalURL)
for path, exp := range map[string]string{
`/foo/%2Fbbb%2F%2E`: `/foo/%2Fbbb%2F%2E`,
`//foo/%2Fb/bb%2F%2E`: `/foo/%2Fb/bb%2F%2E`,
`//foo/%2Fb///bb%2F%2E`: `/foo/%2Fb/bb%2F%2E`,
`/foo/%2E`: `/foo/%2E`,
`///foo///%2E`: `/foo/%2E`,
} {
t.Run(path, func(t *testing.T) {
body, err := json.Marshal(testCommandRequest{
RemoteApp: "serviceinvocation-callee-0",
Method: "normalization",
})
require.NoError(t, err)
url := fmt.Sprintf("http://%s/%s", externalURL, path)
resp, err := utils.HTTPPost(url, body)
require.NoError(t, err)
t.Logf("checking piped path..%s\n", string(resp))
assert.Contains(t, exp, string(resp))
})
}
}
|
mikeee/dapr
|
tests/e2e/service_invocation/service_invocation_test.go
|
GO
|
mit
| 65,648 |
[
{
"key": "1",
"value": {
"person": {
"org": "Dev Ops",
"id": 1036
},
"city": "Seattle",
"state": "WA"
}
},
{
"key": "2",
"value": {
"person": {
"org": "Hardware",
"id": 1028
},
"city": "Portland",
"state": "OR"
}
},
{
"key": "3",
"value": {
"person": {
"org": "Finance",
"id": 1071
},
"city": "Sacramento",
"state": "CA"
}
},
{
"key": "4",
"value": {
"person": {
"org": "Dev Ops",
"id": 1042
},
"city": "Spokane",
"state": "WA"
}
},
{
"key": "5",
"value": {
"person": {
"org": "Hardware",
"id": 1007
},
"city": "Los Angeles",
"state": "CA"
}
},
{
"key": "6",
"value": {
"person": {
"org": "Finance",
"id": 1094
},
"city": "Eugene",
"state": "OR"
}
},
{
"key": "7",
"value": {
"person": {
"org": "Dev Ops",
"id": 1015
},
"city": "San Francisco",
"state": "CA"
}
},
{
"key": "8",
"value": {
"person": {
"org": "Hardware",
"id": 1077
},
"city": "Redmond",
"state": "WA"
}
},
{
"key": "9",
"value": {
"person": {
"org": "Finance",
"id": 1002
},
"city": "San Diego",
"state": "CA"
}
},
{
"key": "10",
"value": {
"person": {
"org": "Dev Ops",
"id": 1054
},
"city": "New York",
"state": "NY"
}
}
]
|
mikeee/dapr
|
tests/e2e/stateapp/query-data/dataset.json
|
JSON
|
mit
| 2,213 |
{
"filter": {
"OR": [
{
"EQ": { "person.org": "Dev Ops" }
},
{
"AND": [
{
"EQ": { "person.org": "Finance" }
},
{
"IN": { "state": ["CA", "WA"] }
}
]
}
]
},
"page": {
"limit": 3
}
}
|
mikeee/dapr
|
tests/e2e/stateapp/query-data/query.json
|
JSON
|
mit
| 445 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package stateapp_e2e
import (
"encoding/json"
"fmt"
"net/http"
"os"
"reflect"
"strings"
"testing"
guuid "github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
apiv1 "k8s.io/api/core/v1"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
)
const (
appName = "stateapp" // App name in Dapr.
appNamePluggable = "stateapp-pluggable" // App name with pluggable components in Dapr.
redisPluggableApp = "e2e-pluggable_redis-statestore" // The name of the pluggable component app.
numHealthChecks = 60 // Number of get calls before starting tests.
testManyEntriesCount = 5 // Anything between 1 and the number above (inclusive).
)
type testCommandRequest struct {
RemoteApp string `json:"remoteApp,omitempty"`
Method string `json:"method,omitempty"`
}
// appState represents a state in this app.
type appState struct {
Data []byte `json:"data,omitempty"`
}
// daprState represents a state in Dapr.
type daprState struct {
Key string `json:"key,omitempty"`
Value *appState `json:"value,omitempty"`
}
// requestResponse represents a request or response for the APIs in the app.
type requestResponse struct {
States []daprState `json:"states,omitempty"`
}
// represents each step in a test since it can make multiple calls.
type testStep struct {
command string
request requestResponse
expectedResponse requestResponse
expectedStatusCode int
}
// stateTransactionRequest represents a request for state transactions
type stateTransaction struct {
Key string `json:"key,omitempty"`
Value *appState `json:"value,omitempty"`
OperationType string `json:"operationType,omitempty"`
}
// represents each step in a test for state transactions
type stateTransactionTestStep struct {
command string
request stateTransactionRequestResponse
expectedResponse requestResponse
}
type stateTransactionRequestResponse struct {
States []stateTransaction
}
type testCase struct {
name string
steps []testStep
protocol string
}
type testStateTransactionCase struct {
steps []stateTransactionTestStep
}
func generateDaprState(kv utils.SimpleKeyValue) daprState {
if kv.Key == nil {
return daprState{}
}
key := fmt.Sprintf("%v", kv.Key)
if kv.Value == nil {
return daprState{key, nil}
}
value := []byte(fmt.Sprintf("%v", kv.Value))
return daprState{key, &appState{value}}
}
// creates a requestResponse based on an array of key value pairs.
func newRequestResponse(keyValues ...utils.SimpleKeyValue) requestResponse {
daprStates := make([]daprState, 0, len(keyValues))
for _, keyValue := range keyValues {
daprStates = append(daprStates, generateDaprState(keyValue))
}
return requestResponse{
daprStates,
}
}
// creates a requestResponse based on an array of key value pairs.
func newStateTransactionRequestResponse(keyValues ...utils.StateTransactionKeyValue) stateTransactionRequestResponse {
daprStateTransactions := make([]stateTransaction, 0, len(keyValues))
for _, keyValue := range keyValues {
daprStateTransactions = append(daprStateTransactions, stateTransaction{
keyValue.Key, &appState{[]byte(keyValue.Value)}, keyValue.OperationType,
})
}
return stateTransactionRequestResponse{
daprStateTransactions,
}
}
// Just for readability.
func newRequest(keyValues ...utils.SimpleKeyValue) requestResponse {
return newRequestResponse(keyValues...)
}
// Just for readability.
func newResponse(keyValues ...utils.SimpleKeyValue) requestResponse {
return newRequestResponse(keyValues...)
}
func generateTestCases(isHTTP bool) []testCase {
protocol := "grpc"
if isHTTP {
protocol = "http"
}
// Just for readability
emptyRequest := requestResponse{}
emptyResponse := requestResponse{}
testCase1Key := guuid.New().String()
testCase1Value := "The best song ever is 'Highwayman' by 'The Highwaymen'."
testCaseManyKeys := utils.GenerateRandomStringKeys(testManyEntriesCount)
testCaseManyKeyValues := utils.GenerateRandomStringValues(testCaseManyKeys)
return []testCase{
{
// No comma since this will become the name of the test without spaces.
"Test get save delete with empty request response for single app and single hop " + protocol,
[]testStep{
{
"get",
emptyRequest,
emptyResponse,
200,
},
{
"save",
emptyRequest,
emptyResponse,
204,
},
{
"delete",
emptyRequest,
emptyResponse,
204,
},
},
protocol,
},
{
// No comma since this will become the name of the test without spaces.
"Test save get and delete a single item for single app and single hop " + protocol,
[]testStep{
{
"get",
newRequest(utils.SimpleKeyValue{testCase1Key, nil}),
newResponse(utils.SimpleKeyValue{testCase1Key, nil}),
200,
},
{
"save",
newRequest(utils.SimpleKeyValue{testCase1Key, testCase1Value}),
emptyResponse,
204,
},
{
"get",
newRequest(utils.SimpleKeyValue{testCase1Key, nil}),
newResponse(utils.SimpleKeyValue{testCase1Key, testCase1Value}),
200,
},
{
"delete",
newRequest(utils.SimpleKeyValue{testCase1Key, nil}),
emptyResponse,
204,
},
{
"get",
newRequest(utils.SimpleKeyValue{testCase1Key, nil}),
newResponse(utils.SimpleKeyValue{testCase1Key, nil}),
200,
},
},
protocol,
},
{
// No comma since this will become the name of the test without spaces.
"Test save get getbulk and delete on multiple items for single app and single hop " + protocol,
[]testStep{
{
"get",
newRequest(testCaseManyKeys...),
newResponse(testCaseManyKeys...),
200,
},
{
"save",
newRequest(testCaseManyKeyValues...),
emptyResponse,
204,
},
{
"get",
newRequest(testCaseManyKeys...),
newResponse(testCaseManyKeyValues...),
200,
},
{
"getbulk",
newRequest(testCaseManyKeys...),
newResponse(testCaseManyKeyValues...),
200,
},
{
"delete",
newRequest(testCaseManyKeys...),
emptyResponse,
204,
},
{
"get",
newRequest(testCaseManyKeys...),
newResponse(testCaseManyKeys...),
200,
},
},
protocol,
},
{
// No comma since this will become the name of the test without spaces.
"Test data size edges (1MB < limit < 4MB) " + protocol,
[]testStep{
{
"save",
generateSpecificLengthSample(1024 * 1024), // Less than limit
emptyResponse,
204,
},
{
"save",
generateSpecificLengthSample(1024*1024*4 + 1), // Limit + 1
emptyResponse,
500,
},
{
"save",
generateSpecificLengthSample(1024 * 1024 * 8), // Greater than limit
emptyResponse,
500,
},
},
protocol,
},
}
}
func generateStateTransactionCases(protocolType string) testStateTransactionCase {
testCase1Key, testCase2Key := guuid.New().String()+protocolType, guuid.New().String()+protocolType
testCase1Value := "The best song ever is 'Highwayman' by 'The Highwaymen'."
testCase2Value := "Hello World"
// Just for readability
emptyResponse := requestResponse{}
testStateTransactionCase := testStateTransactionCase{
[]stateTransactionTestStep{
{
// Transaction order should be tested in conformance tests: https://github.com/dapr/components-contrib/issues/1210
"transact",
newStateTransactionRequestResponse(
utils.StateTransactionKeyValue{testCase1Key, testCase1Value, "upsert"},
),
emptyResponse,
},
{
"transact",
newStateTransactionRequestResponse(
utils.StateTransactionKeyValue{testCase1Key, "", "delete"},
utils.StateTransactionKeyValue{testCase2Key, testCase2Value, "upsert"},
),
emptyResponse,
},
{
"get",
newStateTransactionRequestResponse(
utils.StateTransactionKeyValue{testCase1Key, "", ""},
),
newResponse(utils.SimpleKeyValue{testCase1Key, nil}),
},
{
"get",
newStateTransactionRequestResponse(
utils.StateTransactionKeyValue{testCase2Key, "", ""},
),
newResponse(utils.SimpleKeyValue{testCase2Key, testCase2Value}),
},
{
"transact",
newStateTransactionRequestResponse(
utils.StateTransactionKeyValue{testCase1Key, testCase1Value, "upsert"},
utils.StateTransactionKeyValue{testCase1Key, testCase2Value, "upsert"},
),
emptyResponse,
},
{
"get",
newStateTransactionRequestResponse(
utils.StateTransactionKeyValue{testCase1Key, "", ""},
),
newResponse(utils.SimpleKeyValue{testCase1Key, testCase2Value}),
},
},
}
return testStateTransactionCase
}
func generateSpecificLengthSample(sizeInBytes int) requestResponse {
key := guuid.New().String()
val := make([]byte, sizeInBytes)
state := []daprState{
{
key,
&appState{val},
},
}
return requestResponse{
state,
}
}
var (
tr *runner.TestRunner
stateStoreApps []struct {
name string
stateStore string
} = []struct {
name string
stateStore string
}{
{
name: appName,
stateStore: "statestore",
},
}
)
func TestMain(m *testing.M) {
utils.SetupLogs("stateapp")
utils.InitHTTPClient(true)
// These apps will be deployed before starting actual test
// and will be cleaned up after all tests are finished automatically
testApps := []kube.AppDescription{
{
AppName: appName,
DaprEnabled: true,
ImageName: "e2e-stateapp",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
},
}
if utils.TestTargetOS() != "windows" { // pluggable components feature requires unix socket to work
testApps = append(testApps, kube.AppDescription{
AppName: appNamePluggable,
DaprEnabled: true,
ImageName: "e2e-stateapp",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
PluggableComponents: []apiv1.Container{
{
Name: "redis-pluggable", // e2e-pluggable_redis
Image: runner.BuildTestImageName(redisPluggableApp),
},
},
})
stateStoreApps = append(stateStoreApps, struct {
name string
stateStore string
}{
name: appNamePluggable,
stateStore: "pluggable-statestore",
})
}
tr = runner.NewTestRunner(appName, testApps, nil, nil)
os.Exit(tr.Start(m))
}
func TestStateApp(t *testing.T) {
testCases := generateTestCases(true) // For HTTP
testCases = append(testCases, generateTestCases(false)...) // For gRPC
for _, app := range stateStoreApps {
externalURL := tr.Platform.AcquireAppExternalURL(app.name)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
// Now we are ready to run the actual tests
for _, tt := range testCases {
tt := tt
t.Run(fmt.Sprintf("%s-%s", tt.name, app.stateStore), func(t *testing.T) {
for _, step := range tt.steps {
body, err := json.Marshal(step.request)
require.NoError(t, err)
url := fmt.Sprintf("%s/test/%s/%s/%s", externalURL, tt.protocol, step.command, app.stateStore)
resp, statusCode, err := utils.HTTPPostWithStatus(url, body)
require.NoError(t, err)
require.Equal(t, step.expectedStatusCode, statusCode, url)
var appResp requestResponse
if statusCode != 204 {
err = json.Unmarshal(resp, &appResp)
require.NoError(t, err)
}
for _, er := range step.expectedResponse.States {
for _, ri := range appResp.States {
if er.Key == ri.Key {
require.True(t, reflect.DeepEqual(er.Key, ri.Key))
if er.Value != nil {
require.True(t, reflect.DeepEqual(er.Value.Data, ri.Value.Data))
}
}
}
}
}
})
}
}
}
func TestStateTransactionApps(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL(appName)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
transactionTests := []struct {
protocol string
in testStateTransactionCase
}{
{"HTTP", generateStateTransactionCases("HTTP")},
{"GRPC", generateStateTransactionCases("GRPC")},
}
// Now we are ready to run the actual tests
for _, tt := range transactionTests {
t.Run(fmt.Sprintf("Test State Transactions using %s protocol", tt.protocol), func(t *testing.T) {
for _, step := range tt.in.steps {
body, err := json.Marshal(step.request)
require.NoError(t, err)
var url string
if tt.protocol == "HTTP" || step.command == "get" {
url = strings.TrimSpace(fmt.Sprintf("%s/test/http/%s/statestore", externalURL, step.command))
} else {
url = strings.TrimSpace(fmt.Sprintf("%s/test/grpc/%s/statestore", externalURL, step.command))
}
resp, err := utils.HTTPPost(url, body)
require.NoError(t, err)
var appResp requestResponse
err = json.Unmarshal(resp, &appResp)
require.NoError(t, err)
require.Equal(t, len(step.expectedResponse.States), len(appResp.States))
for _, er := range step.expectedResponse.States {
for _, ri := range appResp.States {
if er.Key == ri.Key {
require.Equal(t, er.Key, ri.Key)
require.Equal(t, er.Value != nil, ri.Value != nil)
if er.Value != nil {
require.True(t, reflect.DeepEqual(er.Value.Data, ri.Value.Data))
}
}
}
}
}
})
}
}
func TestMissingKeyDirect(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL(appName)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
for _, protocol := range []string{"http", "grpc"} {
t.Run(fmt.Sprintf("missing_key_%s", protocol), func(t *testing.T) {
stateURL := fmt.Sprintf("%s/test/%s/%s/statestore", externalURL, protocol, "get")
key := guuid.New().String()
request := newRequest(utils.SimpleKeyValue{key, nil})
body, _ := json.Marshal(request)
resp, status, err := utils.HTTPPostWithStatus(stateURL, body)
var states requestResponse
json.Unmarshal(resp, &states)
require.Equal(t, 200, status)
require.Nil(t, err)
require.Len(t, states.States, 1)
require.Equal(t, states.States[0].Key, key)
require.Nil(t, states.States[0].Value)
})
}
}
func TestMissingAndMisconfiguredStateStore(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL(appName)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
testCases := []struct {
statestore, protocol, errorMessage string
status int
}{
{
statestore: "missingstore",
protocol: "http",
errorMessage: "expected status code 204, got 400",
status: 500,
},
{
statestore: "missingstore",
protocol: "grpc",
errorMessage: "state store missingstore is not found",
status: 500,
},
{
statestore: "badhost-store",
protocol: "http",
errorMessage: "expected status code 204, got 400",
status: 500,
},
{
statestore: "badhost-store",
protocol: "grpc",
errorMessage: "state store badhost-store is not found",
status: 500,
},
{
statestore: "badpass-store",
protocol: "http",
errorMessage: "expected status code 204, got 400",
status: 500,
},
{
statestore: "badpass-store",
protocol: "grpc",
errorMessage: "state store badpass-store is not found",
status: 500,
},
}
for _, tc := range testCases {
t.Run(fmt.Sprintf("store_%s_%s", tc.statestore, tc.protocol), func(t *testing.T) {
// Define state URL for statestore that does not exist.
stateURL := fmt.Sprintf("%s/test/%s/%s/%s", externalURL, tc.protocol, "save", tc.statestore)
request := newRequest(utils.SimpleKeyValue{guuid.New().String(), nil})
body, _ := json.Marshal(request)
resp, status, err := utils.HTTPPostWithStatus(stateURL, body)
// The state app doesn't persist the real error other than this message
require.Contains(t, string(resp), tc.errorMessage)
require.Equal(t, tc.status, status)
require.Nil(t, err)
})
}
}
func TestQueryStateStore(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL(appName)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
// This initial probe makes the test wait a little bit longer when needed,
// making this test less flaky due to delays in the deployment.
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
for _, storename := range []string{"querystatestore", "querystatestore2"} {
// Populate store.
body, err := os.ReadFile("query-data/dataset.json")
require.NoError(t, err)
url := fmt.Sprintf("%s/test/http/load/%s?contentType=application/json", externalURL, storename)
_, status, err := utils.HTTPPostWithStatus(url, body)
require.NoError(t, err)
require.Equal(t, 204, status)
tests := []struct {
path string
keys int
}{
{
path: "./query-data/query.json",
keys: 3,
},
}
for _, test := range tests {
body, err := os.ReadFile(test.path)
require.NoError(t, err)
for _, protocol := range []string{"http", "grpc"} {
url := fmt.Sprintf("%s/test/%s/query/%s?contentType=application/json&queryIndexName=orgIndx", externalURL, protocol, storename)
resp, status, err := utils.HTTPPostWithStatus(url, body)
require.NoError(t, err)
require.Equal(t, 200, status, "got response: "+string(resp))
var states requestResponse
err = json.Unmarshal(resp, &states)
require.NoError(t, err)
require.Equal(t, test.keys, len(states.States))
}
}
}
}
func TestEtags(t *testing.T) {
externalURL := tr.Platform.AcquireAppExternalURL(appName)
require.NotEmpty(t, externalURL, "external URL must not be empty!")
testCases := []struct {
protocol string
}{
{protocol: "http"},
{protocol: "grpc"},
}
// Now we are ready to run the actual tests
for _, tt := range testCases {
t.Run(fmt.Sprintf("Test Etags using %s protocol", tt.protocol), func(t *testing.T) {
url := strings.TrimSpace(fmt.Sprintf("%s/test-etag/%s/statestore", externalURL, tt.protocol))
resp, status, err := utils.HTTPPostWithStatus(url, nil)
require.NoError(t, err)
// The test passes with 204 if there's no error
assert.Equalf(t, http.StatusNoContent, status, "Test failed. Body is: %q", string(resp))
})
}
}
|
mikeee/dapr
|
tests/e2e/stateapp/stateapp_test.go
|
GO
|
mit
| 19,947 |
//go:build e2e
// +build e2e
/*
Copyright 2022 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package tracing_zipkin_e2e
import (
"encoding/json"
"fmt"
"log"
"os"
"testing"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
"github.com/stretchr/testify/require"
)
type appResponse struct {
Message string `json:"message,omitempty"`
SpanName string `json:"spanName,omitempty"`
}
const numHealthChecks = 60 // Number of times to check for endpoint health per app.
var tr *runner.TestRunner
func TestMain(m *testing.M) {
utils.SetupLogs("tracing")
utils.InitHTTPClient(true)
testApps := []kube.AppDescription{
{
AppName: "tracingapp-a",
DaprEnabled: true,
ImageName: "e2e-tracingapp",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
DaprMemoryLimit: "200Mi",
DaprMemoryRequest: "100Mi",
AppMemoryLimit: "200Mi",
AppMemoryRequest: "100Mi",
Config: "tracingconfig-zipkin",
},
{
AppName: "tracingapp-b",
DaprEnabled: true,
ImageName: "e2e-tracingapp",
Replicas: 1,
IngressEnabled: true,
MetricsEnabled: true,
DaprMemoryLimit: "200Mi",
DaprMemoryRequest: "100Mi",
AppMemoryLimit: "200Mi",
AppMemoryRequest: "100Mi",
Config: "tracingconfig-zipkin",
},
}
tr = runner.NewTestRunner("tracing", testApps, nil, nil)
os.Exit(tr.Start(m))
}
func TestInvoke(t *testing.T) {
t.Run("Simple HTTP invoke with tracing", func(t *testing.T) {
// Get the ingress external url of test app
externalURL := tr.Platform.AcquireAppExternalURL("tracingapp-a")
require.NotEmpty(t, externalURL, "external URL must not be empty")
// Check if test app endpoint is available
_, err := utils.HTTPGetNTimes(externalURL, numHealthChecks)
require.NoError(t, err)
// Get the ingress external url of test app 2
externalURL2 := tr.Platform.AcquireAppExternalURL("tracingapp-b")
require.NotEmpty(t, externalURL, "external URL must not be empty")
// Check if test app 2 endpoint is available
_, err = utils.HTTPGetNTimes(externalURL2, numHealthChecks)
require.NoError(t, err)
// Trigger test
resp, err := utils.HTTPPost(externalURL+"/triggerInvoke?appId=tracingapp-b", nil)
require.NoError(t, err)
var appResp appResponse
err = json.Unmarshal(resp, &appResp)
require.NoError(t, err)
require.Equal(t, "OK", appResp.Message)
// Validate tracers
spanName := appResp.SpanName
err = backoff.Retry(func() error {
respV, errV := utils.HTTPPost(externalURL+"/validate?spanName="+spanName, nil)
if errV != nil {
return errV
}
log.Printf("Response from validate: %s", string(respV))
var appRespV appResponse
errV = json.Unmarshal(respV, &appRespV)
if errV != nil {
return fmt.Errorf("error parsing appResponse: %v", errV)
}
if appRespV.Message != "OK" {
return fmt.Errorf("tracers validation failed")
}
return nil
}, backoff.WithMaxRetries(backoff.NewConstantBackOff(5*time.Second), 10))
require.NoError(t, err)
})
}
|
mikeee/dapr
|
tests/e2e/tracing_zipkin/tracing_zipkin_test.go
|
GO
|
mit
| 3,707 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils
import (
"errors"
"fmt"
"os"
"runtime"
"time"
guuid "github.com/google/uuid"
)
const (
// Environment variable for setting the target OS where tests are running on.
TargetOsEnvVar = "TARGET_OS"
// Max number of healthcheck calls before starting tests.
numHealthChecks = 60
)
// SimpleKeyValue can be used to simplify code, providing simple key-value pairs.
type SimpleKeyValue struct {
Key any
Value any
}
// StateTransactionKeyValue is a key-value pair with an operation type.
type StateTransactionKeyValue struct {
Key string
Value string
OperationType string
}
// GenerateRandomStringKeys generates random string keys (values are nil).
func GenerateRandomStringKeys(num int) []SimpleKeyValue {
if num < 0 {
return make([]SimpleKeyValue, 0)
}
output := make([]SimpleKeyValue, 0, num)
for i := 1; i <= num; i++ {
key := guuid.New().String()
output = append(output, SimpleKeyValue{key, nil})
}
return output
}
// GenerateRandomStringValues sets random string values for the keys passed in.
func GenerateRandomStringValues(keyValues []SimpleKeyValue) []SimpleKeyValue {
output := make([]SimpleKeyValue, 0, len(keyValues))
for i, keyValue := range keyValues {
key := keyValue.Key
value := fmt.Sprintf("Value for entry #%d with key %v.", i+1, key)
output = append(output, SimpleKeyValue{key, value})
}
return output
}
// GenerateRandomStringKeyValues generates random string key-values pairs.
func GenerateRandomStringKeyValues(num int) []SimpleKeyValue {
keys := GenerateRandomStringKeys(num)
return GenerateRandomStringValues(keys)
}
// TestTargetOS returns the name of the OS that the tests are targeting (which could be different from the local OS).
func TestTargetOS() string {
// Check if we have an env var first
if v, ok := os.LookupEnv(TargetOsEnvVar); ok {
return v
}
// Fallback to the runtime
return runtime.GOOS
}
// FormatDuration formats the duration in ms
func FormatDuration(d time.Duration) string {
return fmt.Sprintf("%dms", d.Truncate(100*time.Microsecond).Milliseconds())
}
// HealthCheckApps performs healthchecks for multiple apps, waiting for them to be ready.
func HealthCheckApps(urls ...string) error {
count := len(urls)
if count == 0 {
return nil
}
// Run the checks in parallel
errCh := make(chan error, count)
for _, u := range urls {
go func(u string) {
_, err := HTTPGetNTimes(u, numHealthChecks)
errCh <- err
}(u)
}
// Collect all errors
errs := make([]error, count)
for i := 0; i < count; i++ {
errs[i] = <-errCh
}
// Will be nil if no error
return errors.Join(errs...)
}
|
mikeee/dapr
|
tests/e2e/utils/helpers.go
|
GO
|
mit
| 3,192 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils
import (
"bytes"
"crypto/tls"
"io"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
"golang.org/x/net/http2"
"github.com/dapr/kit/utils"
)
const (
// DefaultProbeTimeout is the a timeout used in HTTPGetNTimes() and
// HTTPGetRawNTimes() to avoid cases where early requests hang and
// block all subsequent requests.
DefaultProbeTimeout = 30 * time.Second
)
var httpClient *http.Client
// InitHTTPClient inits the shared httpClient object.
func InitHTTPClient(allowHTTP2 bool) {
httpClient = NewHTTPClient(allowHTTP2)
}
// NewHTTPClient initializes a new *http.Client.
// This should not be used except in rare circumstances. Developers should use the shared httpClient instead to re-use sockets as much as possible.
func NewHTTPClient(allowHTTP2 bool) *http.Client {
// HTTP/2 is allowed only if the DAPR_TESTS_HTTP2 env var is set
allowHTTP2 = allowHTTP2 && utils.IsTruthy(os.Getenv("DAPR_TESTS_HTTP2"))
if allowHTTP2 {
return &http.Client{
Timeout: DefaultProbeTimeout,
// Configure for HTT/2 Cleartext (without TLS) and with prior knowledge
// (RFC7540 Section 3.2)
Transport: &http2.Transport{
// Make the transport accept scheme "http:"
AllowHTTP: true,
// Pretend we are dialing a TLS endpoint
DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
return net.Dial(network, addr)
},
},
// disable test app client auto redirect handle
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
}
return &http.Client{
Timeout: DefaultProbeTimeout,
Transport: &http.Transport{
MaxIdleConns: 2,
MaxIdleConnsPerHost: 1,
},
// disable test app client auto redirect handle
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
}
// HTTPGetNTimes calls the url n times and returns the first success
// or last error.
func HTTPGetNTimes(url string, n int) ([]byte, error) {
var res []byte
var err error
for i := n - 1; i >= 0; i-- {
res, err = HTTPGet(url)
if err == nil {
return res, nil
}
if i == 0 {
break
}
time.Sleep(time.Second)
}
return res, err
}
// HTTPGet is a helper to make GET request call to url.
func HTTPGet(url string) ([]byte, error) {
body, _, _, err := HTTPGetWithStatusWithMetadata(url)
return body, err
}
// HTTPGetWithStatus is a helper to make GET request call to url.
func HTTPGetWithStatus(url string) ([]byte, int, error) {
body, status, _, err := HTTPGetWithStatusWithMetadata(url)
return body, status, err
}
// HTTPGetWithStatusWithMetadata is a helper to make GET request call to url.
func HTTPGetWithStatusWithMetadata(url string) ([]byte, int, http.Header, error) {
resp, err := HTTPGetRaw(url)
if err != nil {
return nil, 0, nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, 0, nil, err
}
return body, resp.StatusCode, resp.Header, nil
}
// HTTPGetWithStatusWithData is a helper to make GET request call to url.
func HTTPGetWithStatusWithData(surl string, data []byte) ([]byte, int, error) {
url, err := url.Parse(SanitizeHTTPURL(surl))
if err != nil {
return nil, 0, err
}
resp, err := httpClient.Do(&http.Request{
Method: http.MethodGet,
URL: url,
Body: io.NopCloser(bytes.NewReader(data)),
})
if err != nil {
return nil, 0, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, 0, err
}
return body, resp.StatusCode, nil
}
// HTTPGetRawNTimes calls the url n times and returns the first
// success or last error.
func HTTPGetRawNTimes(url string, n int) (*http.Response, error) {
var res *http.Response
var err error
for i := n - 1; i >= 0; i-- {
res, err = HTTPGetRaw(url)
if err == nil {
return res, nil
}
if res != nil && res.Body != nil {
// Drain before closing
_, _ = io.Copy(io.Discard, res.Body)
_ = res.Body.Close()
}
if i == 0 {
break
}
time.Sleep(time.Second)
}
return res, err
}
// HTTPGetRaw is a helper to make GET request call to url.
func HTTPGetRaw(url string) (*http.Response, error) {
return httpClient.Get(SanitizeHTTPURL(url))
}
func HTTPGetRawWithHeaders(url string, header http.Header) (*http.Response, error) {
req, err := http.NewRequest(http.MethodGet, SanitizeHTTPURL(url), nil)
if err != nil {
return nil, err
}
req.Header = header
return httpClient.Do(req)
}
// HTTPPost is a helper to make POST request call to url.
func HTTPPost(url string, data []byte) ([]byte, error) {
resp, err := httpClient.Post(SanitizeHTTPURL(url), "application/json", bytes.NewReader(data))
if err != nil {
return nil, err
}
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}
// HTTPPatch is a helper to make PATCH request call to url.
func HTTPPatch(url string, data []byte) ([]byte, error) {
req, err := http.NewRequest(http.MethodPatch, SanitizeHTTPURL(url), bytes.NewReader(data))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}
// HTTPPostWithStatus is a helper to make POST request call to url.
func HTTPPostWithStatus(url string, data []byte) ([]byte, int, error) {
resp, err := httpClient.Post(SanitizeHTTPURL(url), "application/json", bytes.NewReader(data))
if err != nil {
// From the Do method for the client.Post
// An error is returned if caused by client policy (such as
// CheckRedirect), or failure to speak HTTP (such as a network
// connectivity problem). A non-2xx status code doesn't cause an
// error.
if resp != nil {
return nil, resp.StatusCode, err
}
return nil, http.StatusInternalServerError, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
return body, resp.StatusCode, err
}
// HTTPDelete calls a given URL with the HTTP DELETE method.
func HTTPDelete(url string) ([]byte, error) {
req, err := http.NewRequest(http.MethodDelete, SanitizeHTTPURL(url), nil)
if err != nil {
return nil, err
}
res, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
return io.ReadAll(res.Body)
}
// HTTPDeleteWithStatus calls a given URL with the HTTP DELETE method.
func HTTPDeleteWithStatus(url string) ([]byte, int, error) {
req, err := http.NewRequest(http.MethodDelete, SanitizeHTTPURL(url), nil)
if err != nil {
return nil, 0, err
}
res, err := httpClient.Do(req)
if err != nil {
return nil, 0, err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, 0, err
}
return body, res.StatusCode, nil
}
// SanitizeHTTPURL prepends the prefix "http://" to a URL if not present
func SanitizeHTTPURL(url string) string {
if !strings.HasPrefix(url, "http") {
url = "http://" + url
}
return url
}
// GetHTTPClient returns the shared httpClient object.
func GetHTTPClient() *http.Client {
return httpClient
}
|
mikeee/dapr
|
tests/e2e/utils/http.go
|
GO
|
mit
| 7,613 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils
import (
"io"
"log"
"os"
"path/filepath"
"time"
)
// SetupLogs sets up the target for the built-in "log" package.
// Logs are always written to STDOUT.
// If the DAPR_TEST_LOG_PATH environmental variable is set, logs are also written to a file in that folder.
func SetupLogs(testName string) {
logPath := os.Getenv("DAPR_TEST_LOG_PATH")
if logPath != "" {
err := os.MkdirAll(logPath, os.ModePerm)
if err != nil {
log.Printf("Failed to create output log directory '%s' Error was: '%s'", logPath, err)
return
}
date := time.Now().Format("20060102_150405")
target := filepath.Join(logPath, testName+"_"+date+".log")
logFile, err := os.OpenFile(target, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0o666) //nolint:nosnakecase
if err != nil {
log.Printf("Failed to open log file '%s' Error was: '%s'", target, err)
return
}
log.Printf("Saving test %s logs to %s", testName, target)
log.SetOutput(io.MultiWriter(os.Stdout, logFile))
}
}
|
mikeee/dapr
|
tests/e2e/utils/logging.go
|
GO
|
mit
| 1,538 |
//go:build e2e
// +build e2e
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package workflows_e2e
import (
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"os"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/e2e/utils"
kube "github.com/dapr/dapr/tests/platforms/kubernetes"
"github.com/dapr/dapr/tests/runner"
)
var (
tr *runner.TestRunner
backends = []string{"actors", "sqlite"}
appNamePrefix = "workflowsapp"
)
func TestMain(m *testing.M) {
utils.SetupLogs("workflowtestdapr")
utils.InitHTTPClient(true)
// This test can be run outside of Kubernetes too
// Run the workflow e2e app using, for example, the Dapr CLI:
// ASPNETCORE_URLS=http://*:3000 dapr run --app-id workflowsapp --resources-path ./resources -- dotnet run
// Then run this test with the env var "WORKFLOW_APP_ENDPOINT" pointing to the address of the app. For example:
// WORKFLOW_APP_ENDPOINT=http://localhost:3000 DAPR_E2E_TEST="workflows" make test-clean test-e2e-all |& tee test.log
if os.Getenv("WORKFLOW_APP_ENDPOINT") == "" {
// Set the configuration as environment variables for the test app.
var testApps []kube.AppDescription
for _, backend := range backends {
testApps = append(testApps, getTestApp(backend))
}
comps := []kube.ComponentDescription{
{
Name: "sqlitebackend",
TypeName: "workflowbackend.sqlite",
MetaData: map[string]kube.MetadataValue{
"connectionString": {Raw: `""`},
},
Scopes: []string{appNamePrefix + "-sqlite"},
},
}
tr = runner.NewTestRunner("workflowsapp", testApps, comps, nil)
os.Exit(tr.Start(m))
} else {
os.Exit(m.Run())
}
}
func getTestApp(backend string) kube.AppDescription {
testApps := kube.AppDescription{
AppName: appNamePrefix + "-" + backend,
DaprEnabled: true,
ImageName: "e2e-workflowsapp",
Replicas: 1,
IngressEnabled: true,
IngressPort: 3000,
DaprMemoryLimit: "200Mi",
DaprMemoryRequest: "100Mi",
AppMemoryLimit: "200Mi",
AppMemoryRequest: "100Mi",
AppPort: -1,
DebugLoggingEnabled: true,
}
return testApps
}
func getAppEndpoint(testAppName string) string {
if env := os.Getenv("WORKFLOW_APP_ENDPOINT"); env != "" {
return env
}
return tr.Platform.AcquireAppExternalURL(testAppName)
}
func startTest(url string, instanceID string) func(t *testing.T) {
return func(t *testing.T) {
getString := fmt.Sprintf("%s/dapr/%s", url, instanceID)
// Start the workflow and check that it is running
resp, err := utils.HTTPPost(fmt.Sprintf("%s/StartWorkflow/dapr/placeOrder/%s", url, instanceID), nil)
require.NoError(t, err, "failure starting workflow")
require.EventuallyWithT(t, func(t *assert.CollectT) {
resp, err = utils.HTTPGet(getString)
require.NoError(t, err, "failure getting info on workflow")
assert.Equalf(t, "Running", string(resp), "expected workflow to be Running, actual workflow state is: %s", string(resp))
}, 5*time.Second, 100*time.Millisecond)
}
}
func pauseResumeTest(url string, instanceID string) func(t *testing.T) {
return func(t *testing.T) {
getString := fmt.Sprintf("%s/dapr/%s", url, instanceID)
// Start the workflow and check that it is running
resp, err := utils.HTTPPost(fmt.Sprintf("%s/StartWorkflow/dapr/placeOrder/%s", url, instanceID), nil)
require.NoError(t, err, "failure starting workflow")
require.EventuallyWithT(t, func(t *assert.CollectT) {
resp, err = utils.HTTPGet(getString)
require.NoError(t, err, "failure getting info on workflow")
assert.Equalf(t, "Running", string(resp), "expected workflow to be Running, actual workflow state is: %s", string(resp))
}, 5*time.Second, 100*time.Millisecond)
// Raise an event on the workflow
resp, err = utils.HTTPPost(fmt.Sprintf("%s/RaiseWorkflowEvent/dapr/%s/ChangePurchaseItem/1", url, instanceID), nil)
require.NoError(t, err, "failure raising event on workflow")
// Raise parallel events on the workflow
resp, err = utils.HTTPPost(fmt.Sprintf("%s/RaiseWorkflowEvent/dapr/%s/ConfirmSize/1", url, instanceID), nil)
require.NoError(t, err, "failure raising event on workflow")
resp, err = utils.HTTPPost(fmt.Sprintf("%s/RaiseWorkflowEvent/dapr/%s/ConfirmColor/1", url, instanceID), nil)
require.NoError(t, err, "failure raising event on workflow")
resp, err = utils.HTTPPost(fmt.Sprintf("%s/RaiseWorkflowEvent/dapr/%s/ConfirmAddress/1", url, instanceID), nil)
require.NoError(t, err, "failure raising event on workflow")
// Pause the workflow
resp, err = utils.HTTPPost(fmt.Sprintf("%s/PauseWorkflow/dapr/%s", url, instanceID), nil)
require.NoError(t, err, "failure pausing workflow")
require.EventuallyWithT(t, func(t *assert.CollectT) {
resp, err = utils.HTTPGet(getString)
require.NoError(t, err, "failure getting info on workflow")
assert.Equalf(t, "Suspended", string(resp), "expected workflow to be Suspended, actual workflow state is: %s", string(resp))
}, 5*time.Second, 100*time.Millisecond)
// Resume the workflow
resp, err = utils.HTTPPost(fmt.Sprintf("%s/ResumeWorkflow/dapr/%s", url, instanceID), nil)
require.NoError(t, err, "failure resuming workflow")
// Raise a parallel event on the workflow
resp, err = utils.HTTPPost(fmt.Sprintf("%s/RaiseWorkflowEvent/dapr/%s/PayByCard/1", url, instanceID), nil)
require.NoError(t, err, "failure raising event on workflow")
time.Sleep(5 * time.Second)
require.EventuallyWithT(t, func(t *assert.CollectT) {
resp, err = utils.HTTPGet(getString)
require.NoError(t, err, "failure getting info on workflow")
assert.Equalf(t, "Running", string(resp), "expected workflow to be Running, actual workflow state is: %s", string(resp))
}, 5*time.Second, 100*time.Millisecond)
}
}
func raiseEventTest(url string, instanceID string) func(t *testing.T) {
return func(t *testing.T) {
getString := fmt.Sprintf("%s/dapr/%s", url, instanceID)
// Start the workflow and check that it is running
resp, err := utils.HTTPPost(fmt.Sprintf("%s/StartWorkflow/dapr/placeOrder/%s", url, instanceID), nil)
require.NoError(t, err, "failure starting workflow")
require.EventuallyWithT(t, func(t *assert.CollectT) {
resp, err = utils.HTTPGet(getString)
require.NoError(t, err, "failure getting info on workflow")
assert.Equalf(t, "Running", string(resp), "expected workflow to be Running, actual workflow state is: %s", string(resp))
}, 5*time.Second, 100*time.Millisecond)
// Raise an event on the workflow
resp, err = utils.HTTPPost(fmt.Sprintf("%s/RaiseWorkflowEvent/dapr/%s/ChangePurchaseItem/1", url, instanceID), nil)
require.NoError(t, err, "failure raising event on workflow")
// Raise parallel events on the workflow
resp, err = utils.HTTPPost(fmt.Sprintf("%s/RaiseWorkflowEvent/dapr/%s/ConfirmSize/1", url, instanceID), nil)
require.NoError(t, err, "failure raising event on workflow")
resp, err = utils.HTTPPost(fmt.Sprintf("%s/RaiseWorkflowEvent/dapr/%s/ConfirmColor/1", url, instanceID), nil)
require.NoError(t, err, "failure raising event on workflow")
resp, err = utils.HTTPPost(fmt.Sprintf("%s/RaiseWorkflowEvent/dapr/%s/ConfirmAddress/1", url, instanceID), nil)
require.NoError(t, err, "failure raising event on workflow")
// Raise a parallel event on the workflow
resp, err = utils.HTTPPost(fmt.Sprintf("%s/RaiseWorkflowEvent/dapr/%s/PayByCard/1", url, instanceID), nil)
require.NoError(t, err, "failure raising event on workflow")
time.Sleep(10 * time.Second)
require.EventuallyWithT(t, func(t *assert.CollectT) {
resp, err = utils.HTTPGet(getString)
require.NoError(t, err, "failure getting info on workflow")
assert.Equalf(t, "Completed", string(resp), "expected workflow to be Completed, actual workflow state is: %s", string(resp))
}, 5*time.Second, 100*time.Millisecond)
}
}
// Functions for each test case
func purgeTest(url string, instanceID string) func(t *testing.T) {
return func(t *testing.T) {
getString := fmt.Sprintf("%s/dapr/%s", url, instanceID)
// Start the workflow and check that it is running
resp, err := utils.HTTPPost(fmt.Sprintf("%s/StartWorkflow/dapr/placeOrder/%s", url, instanceID), nil)
require.NoError(t, err, "failure starting workflow")
require.EventuallyWithT(t, func(t *assert.CollectT) {
resp, err = utils.HTTPGet(getString)
require.NoError(t, err, "failure getting info on workflow")
assert.Equalf(t, "Running", string(resp), "expected workflow to be Running, actual workflow state is: %s", string(resp))
}, 5*time.Second, 100*time.Millisecond)
// Raise an event on the workflow
resp, err = utils.HTTPPost(fmt.Sprintf("%s/RaiseWorkflowEvent/dapr/%s/ChangePurchaseItem/1", url, instanceID), nil)
require.NoError(t, err, "failure raising event on workflow")
// Raise parallel events on the workflow
resp, err = utils.HTTPPost(fmt.Sprintf("%s/RaiseWorkflowEvent/dapr/%s/ConfirmSize/1", url, instanceID), nil)
require.NoError(t, err, "failure raising event on workflow")
resp, err = utils.HTTPPost(fmt.Sprintf("%s/RaiseWorkflowEvent/dapr/%s/ConfirmColor/1", url, instanceID), nil)
require.NoError(t, err, "failure raising event on workflow")
resp, err = utils.HTTPPost(fmt.Sprintf("%s/RaiseWorkflowEvent/dapr/%s/ConfirmAddress/1", url, instanceID), nil)
require.NoError(t, err, "failure raising event on workflow")
// Terminate the workflow
resp, err = utils.HTTPPost(fmt.Sprintf("%s/TerminateWorkflow/dapr/%s", url, instanceID), nil)
require.NoError(t, err, "failure terminating workflow")
require.EventuallyWithT(t, func(t *assert.CollectT) {
resp, err = utils.HTTPGet(getString)
require.NoError(t, err, "failure getting info on workflow")
assert.Equalf(t, "Terminated", string(resp), "expected workflow to be Terminated, actual workflow state is: %s", string(resp))
}, 5*time.Second, 100*time.Millisecond)
// Purge the workflow
resp, err = utils.HTTPPost(fmt.Sprintf("%s/PurgeWorkflow/dapr/%s", url, instanceID), nil)
require.NoError(t, err, "failure purging workflow")
// Start a new workflow with the same instanceID to ensure that it is available
resp, err = utils.HTTPPost(fmt.Sprintf("%s/StartWorkflow/dapr/placeOrder/%s", url, instanceID), nil)
require.NoError(t, err, "failure starting workflow")
require.Equal(t, instanceID, string(resp))
require.EventuallyWithT(t, func(t *assert.CollectT) {
resp, err = utils.HTTPGet(getString)
require.NoError(t, err, "failure getting info on workflow")
assert.Equalf(t, "Running", string(resp), "expected workflow to be Running, actual workflow state is: %s", string(resp))
}, 5*time.Second, 100*time.Millisecond)
// Raise a parallel event on the workflow
resp, err = utils.HTTPPost(fmt.Sprintf("%s/RaiseWorkflowEvent/dapr/%s/PayByCard/1", url, instanceID), nil)
require.NoError(t, err, "failure raising event on workflow")
time.Sleep(5 * time.Second)
// Purge will clear the instance data. There are insufficient triggered events which lead to the failure.
require.EventuallyWithT(t, func(t *assert.CollectT) {
resp, err = utils.HTTPGet(getString)
require.NoError(t, err, "failure getting info on workflow")
assert.NotEqualf(t, "Completed", string(resp), "expected workflow not to be Completed, actual workflow state is: %s", string(resp))
}, 5*time.Second, 100*time.Millisecond)
}
}
// Functions for each test case
func monitorTest(url string, instanceID string) func(t *testing.T) {
return func(t *testing.T) {
getString := fmt.Sprintf("%s/dapr/%s", url, instanceID)
// Start the workflow and check that it is running
resp, err := utils.HTTPPost(fmt.Sprintf("%s/StartWorkflow/dapr/placeOrder/%s", url, instanceID), nil)
require.NoError(t, err, "failure starting workflow")
require.EventuallyWithT(t, func(t *assert.CollectT) {
resp, err = utils.HTTPGet(getString)
assert.NoError(t, err, "failure getting info on workflow")
assert.Equalf(t, "Running", string(resp), "expected workflow to be Running, actual workflow state is: %s", string(resp))
}, 5*time.Second, 100*time.Millisecond)
// Start the monitor workflow
monitorInstanceID := "m-" + instanceID
resp, err = utils.HTTPPost(fmt.Sprintf("%s/StartMonitorWorkflow/dapr/%s/%s", url, instanceID, monitorInstanceID), nil)
require.NoError(t, err, "failure starting workflow")
getMonitorString := fmt.Sprintf("%s/dapr/%s", url, monitorInstanceID)
require.EventuallyWithT(t, func(t *assert.CollectT) {
resp, err = utils.HTTPGet(getMonitorString)
assert.NoError(t, err, "failure getting info on workflow")
assert.Equalf(t, "Running", string(resp), "expected workflow to be Running, actual workflow state is: %s", string(resp))
}, 5*time.Second, 100*time.Millisecond)
// Raise an event on the workflow
resp, err = utils.HTTPPost(fmt.Sprintf("%s/RaiseWorkflowEvent/dapr/%s/ChangePurchaseItem/1", url, instanceID), nil)
require.NoError(t, err, "failure raising event on workflow")
// Raise parallel events on the workflow
resp, err = utils.HTTPPost(fmt.Sprintf("%s/RaiseWorkflowEvent/dapr/%s/ConfirmSize/1", url, instanceID), nil)
require.NoError(t, err, "failure raising event on workflow")
resp, err = utils.HTTPPost(fmt.Sprintf("%s/RaiseWorkflowEvent/dapr/%s/ConfirmColor/1", url, instanceID), nil)
require.NoError(t, err, "failure raising event on workflow")
resp, err = utils.HTTPPost(fmt.Sprintf("%s/RaiseWorkflowEvent/dapr/%s/ConfirmAddress/1", url, instanceID), nil)
require.NoError(t, err, "failure raising event on workflow")
// Raise a parallel event on the workflow
resp, err = utils.HTTPPost(fmt.Sprintf("%s/RaiseWorkflowEvent/dapr/%s/PayByCard/1", url, instanceID), nil)
require.NoError(t, err, "failure raising event on workflow")
time.Sleep(15 * time.Second)
require.EventuallyWithT(t, func(t *assert.CollectT) {
resp, err = utils.HTTPGet(getString)
assert.NoError(t, err, "failure getting info on workflow")
assert.Equalf(t, "Completed", string(resp), "expected workflow to be Completed, actual workflow state is: %s", string(resp))
}, 5*time.Second, 100*time.Millisecond)
require.EventuallyWithT(t, func(t *assert.CollectT) {
resp, err = utils.HTTPGet(getMonitorString)
assert.NoError(t, err, "failure getting info on workflow")
assert.Equalf(t, "Completed", string(resp), "expected workflow to be Completed, actual workflow state is: %s", string(resp))
}, 5*time.Second, 100*time.Millisecond)
}
}
func TestWorkflow(t *testing.T) {
for _, backend := range backends {
t.Run(backend, func(t *testing.T) {
// Get the ingress external url of test app
externalURL := getAppEndpoint(appNamePrefix + "-" + backend)
require.NotEmpty(t, externalURL, "external URL must not be empty")
// Check if test app endpoint is available
require.NoError(t, utils.HealthCheckApps(externalURL))
// Generate a unique test suffix for this test
suffixBytes := make([]byte, 7)
_, err := io.ReadFull(rand.Reader, suffixBytes)
require.NoError(t, err)
suffix := hex.EncodeToString(suffixBytes)
// Run tests
t.Run("Start", startTest(externalURL, "start-"+suffix))
t.Run("Pause and Resume", pauseResumeTest(externalURL, "pause-"+suffix))
t.Run("Purge", purgeTest(externalURL, "purge-"+suffix))
t.Run("Raise event", raiseEventTest(externalURL, "raiseEvent-"+suffix))
t.Run("Start monitor", monitorTest(externalURL, "monitor-"+suffix))
})
}
}
|
mikeee/dapr
|
tests/e2e/workflows/workflow_test.go
|
GO
|
mit
| 15,998 |
{
"annotations": {
"list": [
{
"builtIn": 1,
"datasource": {
"type": "grafana",
"uid": "-- Grafana --"
},
"enable": true,
"hide": true,
"iconColor": "rgba(0, 211, 255, 1)",
"name": "Annotations & Alerts",
"type": "dashboard"
}
]
},
"editable": true,
"fiscalYearStartMonth": 0,
"graphTooltip": 0,
"id": 1,
"links": [],
"liveNow": true,
"panels": [
{
"collapsed": false,
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 0
},
"id": 123129,
"panels": [],
"title": "Application",
"type": "row"
},
{
"datasource": {
"type": "prometheus",
"uid": "edf213dd-f753-41cd-9666-cc2d18daaa45"
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 0,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 5,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "auto",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
},
"unit": "ms"
},
"overrides": []
},
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 1
},
"id": 123124,
"options": {
"legend": {
"calcs": [],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "single",
"sort": "none"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "edf213dd-f753-41cd-9666-cc2d18daaa45"
},
"editorMode": "builder",
"expr": "BASELINE_RESPONSE_TIME{perf_test=\"$perf_test\"}",
"instant": false,
"range": true,
"refId": "A"
},
{
"datasource": {
"type": "prometheus",
"uid": "edf213dd-f753-41cd-9666-cc2d18daaa45"
},
"editorMode": "builder",
"expr": "DAPR_RESPONSE_TIME{perf_test=\"$perf_test\"}",
"hide": false,
"instant": false,
"range": true,
"refId": "B"
},
{
"datasource": {
"type": "prometheus",
"uid": "edf213dd-f753-41cd-9666-cc2d18daaa45"
},
"editorMode": "builder",
"expr": "LATENCY_BY_DAPR{perf_test=\"$perf_test\"}",
"hide": false,
"instant": false,
"range": true,
"refId": "C"
}
],
"title": "Latency",
"type": "timeseries"
},
{
"datasource": {
"type": "prometheus",
"uid": "edf213dd-f753-41cd-9666-cc2d18daaa45"
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "Actual QPS",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 25,
"gradientMode": "hue",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 5,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "auto",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
}
},
"overrides": [
{
"matcher": {
"id": "byName",
"options": "APPLICATION_THROUGHPUT{building_block=\"service-invocation-http\", job=\"service-invocation-http\"}"
},
"properties": [
{
"id": "color",
"value": {
"fixedColor": "dark-purple",
"mode": "fixed"
}
}
]
},
{
"matcher": {
"id": "byName",
"options": "APPLICATION_THROUGHPUT{building_block=\"state_get_http\", component=\"inmemory\", job=\"state_get_http\"}"
},
"properties": [
{
"id": "color",
"value": {
"fixedColor": "dark-purple",
"mode": "fixed"
}
}
]
},
{
"matcher": {
"id": "byName",
"options": "APPLICATION_THROUGHPUT{job=\"service-invocation-http\", perf_test=\"service-invocation-http\"}"
},
"properties": [
{
"id": "color",
"value": {
"fixedColor": "dark-blue",
"mode": "fixed"
}
}
]
},
{
"matcher": {
"id": "byName",
"options": "APPLICATION_THROUGHPUT{component=\"inmemory\", job=\"state_get_http\", perf_test=\"state_get_http\"}"
},
"properties": [
{
"id": "color",
"value": {
"fixedColor": "dark-blue",
"mode": "fixed"
}
}
]
}
]
},
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 1
},
"id": 123126,
"options": {
"legend": {
"calcs": [],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "single",
"sort": "none"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "edf213dd-f753-41cd-9666-cc2d18daaa45"
},
"editorMode": "builder",
"expr": "APPLICATION_THROUGHPUT{perf_test=\"$perf_test\"}",
"instant": false,
"range": true,
"refId": "A"
}
],
"title": "Throughput",
"type": "timeseries"
},
{
"datasource": {
"type": "prometheus",
"uid": "edf213dd-f753-41cd-9666-cc2d18daaa45"
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 25,
"gradientMode": "hue",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 5,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "auto",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
},
"unit": "milliCPU"
},
"overrides": [
{
"matcher": {
"id": "byName",
"options": "APP_CPU_USAGE{building_block=\"state_get_http\", component=\"inmemory\", job=\"state_get_http\"}"
},
"properties": [
{
"id": "color",
"value": {
"fixedColor": "super-light-yellow",
"mode": "fixed"
}
}
]
},
{
"matcher": {
"id": "byName",
"options": "APP_CPU_USAGE{building_block=\"service-invocation-http\", job=\"service-invocation-http\"}"
},
"properties": [
{
"id": "color",
"value": {
"fixedColor": "super-light-yellow",
"mode": "fixed"
}
}
]
},
{
"matcher": {
"id": "byName",
"options": "APP_CPU_USAGE{job=\"service-invocation-http\", perf_test=\"service-invocation-http\"}"
},
"properties": [
{
"id": "color",
"value": {
"fixedColor": "super-light-yellow",
"mode": "fixed"
}
}
]
},
{
"matcher": {
"id": "byName",
"options": "APP_CPU_USAGE{component=\"inmemory\", job=\"state_get_http\", perf_test=\"state_get_http\"}"
},
"properties": [
{
"id": "color",
"value": {
"fixedColor": "super-light-yellow",
"mode": "fixed"
}
}
]
}
]
},
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 9
},
"id": 123127,
"options": {
"legend": {
"calcs": [],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "single",
"sort": "none"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "edf213dd-f753-41cd-9666-cc2d18daaa45"
},
"editorMode": "builder",
"expr": "APP_CPU_USAGE{perf_test=\"$perf_test\"}",
"instant": false,
"range": true,
"refId": "A"
}
],
"title": "CPU Usage",
"type": "timeseries"
},
{
"datasource": {
"type": "prometheus",
"uid": "edf213dd-f753-41cd-9666-cc2d18daaa45"
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 25,
"gradientMode": "hue",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 5,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "auto",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
},
"unit": "decmbytes"
},
"overrides": [
{
"matcher": {
"id": "byName",
"options": "APP_MEMORY_USAGE{building_block=\"service-invocation-http\", job=\"service-invocation-http\"}"
},
"properties": [
{
"id": "color",
"value": {
"fixedColor": "dark-red",
"mode": "fixed"
}
}
]
},
{
"matcher": {
"id": "byName",
"options": "APP_MEMORY_USAGE{building_block=\"state_get_http\", component=\"inmemory\", job=\"state_get_http\"}"
},
"properties": [
{
"id": "color",
"value": {
"fixedColor": "dark-red",
"mode": "fixed"
}
}
]
},
{
"matcher": {
"id": "byName",
"options": "APP_MEMORY_USAGE{job=\"service-invocation-http\", perf_test=\"service-invocation-http\"}"
},
"properties": [
{
"id": "color",
"value": {
"fixedColor": "dark-red",
"mode": "fixed"
}
}
]
},
{
"matcher": {
"id": "byName",
"options": "APP_MEMORY_USAGE{component=\"inmemory\", job=\"state_get_http\", perf_test=\"state_get_http\"}"
},
"properties": [
{
"id": "color",
"value": {
"fixedColor": "dark-red",
"mode": "fixed"
}
}
]
}
]
},
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 9
},
"id": 123128,
"options": {
"legend": {
"calcs": [],
"displayMode": "list",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "single",
"sort": "none"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "edf213dd-f753-41cd-9666-cc2d18daaa45"
},
"editorMode": "builder",
"expr": "APP_MEMORY_USAGE{perf_test=\"$perf_test\"}",
"instant": false,
"range": true,
"refId": "A"
}
],
"title": "Memory Usage",
"type": "timeseries"
},
{
"collapsed": false,
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 17
},
"id": 123125,
"panels": [],
"title": "Dapr Sidecar",
"type": "row"
},
{
"datasource": {
"type": "prometheus",
"uid": "edf213dd-f753-41cd-9666-cc2d18daaa45"
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 25,
"gradientMode": "hue",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 5,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "auto",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
},
"unit": "milliCPU"
},
"overrides": [
{
"matcher": {
"id": "byName",
"options": "DAPR_SIDECAR_CPU_USAGE{building_block=\"service-invocation-http\", job=\"service-invocation-http\"}"
},
"properties": [
{
"id": "color",
"value": {
"fixedColor": "dark-orange",
"mode": "fixed"
}
}
]
},
{
"matcher": {
"id": "byName",
"options": "DAPR_SIDECAR_CPU_USAGE{building_block=\"state_get_http\", component=\"inmemory\", job=\"state_get_http\"}"
},
"properties": [
{
"id": "color",
"value": {
"fixedColor": "dark-orange",
"mode": "fixed"
}
}
]
},
{
"matcher": {
"id": "byName",
"options": "DAPR_SIDECAR_CPU_USAGE{job=\"service-invocation-http\", perf_test=\"service-invocation-http\"}"
},
"properties": [
{
"id": "color",
"value": {
"fixedColor": "dark-orange",
"mode": "fixed"
}
}
]
},
{
"matcher": {
"id": "byName",
"options": "DAPR_SIDECAR_CPU_USAGE{component=\"inmemory\", job=\"state_get_http\", perf_test=\"state_get_http\"}"
},
"properties": [
{
"id": "color",
"value": {
"fixedColor": "dark-orange",
"mode": "fixed"
}
}
]
}
]
},
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 18
},
"id": 123130,
"options": {
"legend": {
"calcs": [],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "single",
"sort": "none"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "edf213dd-f753-41cd-9666-cc2d18daaa45"
},
"editorMode": "builder",
"expr": "DAPR_SIDECAR_CPU_USAGE{perf_test=\"$perf_test\"}",
"instant": false,
"range": true,
"refId": "A"
}
],
"title": "CPU Usage",
"type": "timeseries"
},
{
"datasource": {
"type": "prometheus",
"uid": "edf213dd-f753-41cd-9666-cc2d18daaa45"
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 25,
"gradientMode": "hue",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 5,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "auto",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
},
"unit": "decmbytes"
},
"overrides": [
{
"matcher": {
"id": "byName",
"options": "DAPR_SIDECAR_MEMORY_USAGE{building_block=\"service-invocation-http\", job=\"service-invocation-http\"}"
},
"properties": [
{
"id": "color",
"value": {
"fixedColor": "semi-dark-green",
"mode": "fixed"
}
}
]
},
{
"matcher": {
"id": "byName",
"options": "DAPR_SIDECAR_MEMORY_USAGE{building_block=\"state_get_http\", component=\"inmemory\", job=\"state_get_http\"}"
},
"properties": [
{
"id": "color",
"value": {
"fixedColor": "semi-dark-green",
"mode": "fixed"
}
}
]
},
{
"matcher": {
"id": "byName",
"options": "DAPR_SIDECAR_MEMORY_USAGE{job=\"service-invocation-http\", perf_test=\"service-invocation-http\"}"
},
"properties": [
{
"id": "color",
"value": {
"fixedColor": "semi-dark-green",
"mode": "fixed"
}
}
]
},
{
"matcher": {
"id": "byName",
"options": "DAPR_SIDECAR_MEMORY_USAGE{component=\"inmemory\", job=\"state_get_http\", perf_test=\"state_get_http\"}"
},
"properties": [
{
"id": "color",
"value": {
"fixedColor": "semi-dark-green",
"mode": "fixed"
}
}
]
}
]
},
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 18
},
"id": 123131,
"options": {
"legend": {
"calcs": [],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "single",
"sort": "none"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "edf213dd-f753-41cd-9666-cc2d18daaa45"
},
"editorMode": "builder",
"expr": "DAPR_SIDECAR_MEMORY_USAGE{perf_test=\"$perf_test\"}",
"instant": false,
"range": true,
"refId": "A"
}
],
"title": "Memory Usage",
"type": "timeseries"
}
],
"refresh": "",
"schemaVersion": 38,
"style": "dark",
"tags": [],
"templating": {
"list": [
{
"current": {
"selected": false,
"text": "service-invocation-http",
"value": "service-invocation-http"
},
"datasource": {
"type": "prometheus",
"uid": "edf213dd-f753-41cd-9666-cc2d18daaa45"
},
"definition": "label_values(perf_test)",
"hide": 0,
"includeAll": false,
"multi": false,
"name": "perf_test",
"options": [],
"query": {
"query": "label_values(perf_test)",
"refId": "PrometheusVariableQueryEditor-VariableQuery"
},
"refresh": 1,
"regex": "",
"skipUrlSync": false,
"sort": 0,
"type": "query"
}
]
},
"time": {
"from": "now-12h",
"to": "now"
},
"timepicker": {
"hidden": false,
"refresh_intervals": [
"5s"
],
"time_options": [
"5m",
"15m",
"1h",
"6h",
"12h",
"24h",
"2d",
"7d",
"30d"
],
"type": "timepicker"
},
"timezone": "browser",
"title": "Dapr_Perf_Test",
"uid": "aad72cef-667a-402f-b850-241f6d92d943",
"version": 26,
"weekStart": ""
}
|
mikeee/dapr
|
tests/grafana/grafana-perf-test-dashboard.json
|
JSON
|
mit
| 25,692 |
/*
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 binary
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"testing"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/integration/framework/iowriter"
)
func BuildAll(t *testing.T) {
t.Helper()
binaryNames := []string{"daprd", "placement", "sentry", "operator", "injector"}
var wg sync.WaitGroup
wg.Add(len(binaryNames))
for _, name := range binaryNames {
if runtime.GOOS == "windows" {
Build(t, name)
wg.Done()
} else {
go func(name string) {
defer wg.Done()
Build(t, name)
}(name)
}
}
wg.Wait()
}
func Build(t *testing.T, name string) {
t.Helper()
if _, ok := os.LookupEnv(EnvKey(name)); !ok {
t.Logf("%q not set, building %q binary", EnvKey(name), name)
_, tfile, _, ok := runtime.Caller(0)
require.True(t, ok)
rootDir := filepath.Join(filepath.Dir(tfile), "../../../..")
// Use a consistent temp dir for the binary so that the binary is cached on
// subsequent runs.
var tmpdir string
if runtime.GOOS == "darwin" {
tmpdir = "/tmp"
} else {
tmpdir = os.TempDir()
}
binPath := filepath.Join(tmpdir, "dapr_integration_tests/"+name)
if runtime.GOOS == "windows" {
binPath += ".exe"
}
ioout := iowriter.New(t, name)
ioerr := iowriter.New(t, name)
t.Logf("Root dir: %q", rootDir)
t.Logf("Compiling %q binary to: %q", name, binPath)
cmd := exec.Command("go", "build", "-tags=allcomponents,wfbackendsqlite", "-v", "-o", binPath, "./cmd/"+name)
cmd.Dir = rootDir
cmd.Stdout = ioout
cmd.Stderr = ioerr
// Ensure CGO is disabled to avoid linking against system libraries.
cmd.Env = append(os.Environ(), "CGO_ENABLED=0")
require.NoError(t, cmd.Run())
require.NoError(t, ioout.Close())
require.NoError(t, ioerr.Close())
require.NoError(t, os.Setenv(EnvKey(name), binPath))
} else {
t.Logf("%q set, using %q pre-built binary", EnvKey(name), EnvValue(name))
}
}
func EnvValue(name string) string {
return os.Getenv(EnvKey(name))
}
func EnvKey(name string) string {
return fmt.Sprintf("DAPR_INTEGRATION_%s_PATH", strings.ToUpper(name))
}
|
mikeee/dapr
|
tests/integration/framework/binary/binary.go
|
GO
|
mit
| 2,661 |
/*
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 framework
import (
"context"
"testing"
"github.com/dapr/dapr/tests/integration/framework/process"
)
type options struct {
procs []process.Interface
}
// Option is a function that configures the Framework's options.
type Option func(*options)
func Run(t *testing.T, ctx context.Context, opts ...Option) {
t.Helper()
o := options{}
for _, opt := range opts {
opt(&o)
}
t.Logf("starting %d processes", len(o.procs))
for i, proc := range o.procs {
i := i
proc.Run(t, ctx)
t.Cleanup(func() { o.procs[i].Cleanup(t) })
}
}
|
mikeee/dapr
|
tests/integration/framework/framework.go
|
GO
|
mit
| 1,112 |
/*
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 iowriter
import (
"bytes"
"errors"
"io"
"os"
"strings"
"sync"
"github.com/dapr/kit/utils"
)
// Logger is an interface that provides a Log method and a Name method. The Log
// method is used to write a log message to the logger. The Name method returns
// the name of the logger which will be prepended to each log message.
type Logger interface {
Log(args ...any)
Name() string
Cleanup(func())
Failed() bool
}
// stdwriter is an io.WriteCloser that writes to the test logger. It buffers
// writes until a newline is encountered, at which point it flushes the buffer
// to the test logger.
type stdwriter struct {
t Logger
procName string
buf bytes.Buffer
lock sync.Mutex
}
func New(t Logger, procName string) io.WriteCloser {
s := &stdwriter{
t: t,
procName: procName,
}
t.Cleanup(s.flush)
return s
}
// Write writes the input bytes to the buffer. If the input contains a newline,
// the buffer is flushed to the test logger.
func (w *stdwriter) Write(inp []byte) (n int, err error) {
w.lock.Lock()
defer w.lock.Unlock()
return w.buf.Write(inp)
}
// Close flushes the buffer and marks the writer as closed.
func (w *stdwriter) Close() error {
w.flush()
return nil
}
// flush writes the buffer to the test logger. Expects the lock to be held
// before calling.
func (w *stdwriter) flush() {
w.lock.Lock()
defer w.lock.Unlock()
defer w.buf.Reset()
// Don't log if the test hasn't failed and the user hasn't requested logs to
// always be printed.
if !w.t.Failed() &&
!utils.IsTruthy(os.Getenv("DAPR_INTEGRATION_LOGS")) {
return
}
for {
line, err := w.buf.ReadBytes('\n')
if len(line) > 0 {
w.t.Log(w.t.Name() + "/" + w.procName + ": " +
strings.TrimSuffix(string(line), "\n"))
}
if err != nil {
if !errors.Is(err, io.EOF) {
w.t.Log(w.t.Name() + "/" + w.procName + ": " + err.Error())
}
break
}
}
}
|
mikeee/dapr
|
tests/integration/framework/iowriter/iowriter.go
|
GO
|
mit
| 2,471 |
/*
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 iowriter
import (
"fmt"
"io"
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type mockLogger struct {
msgs []string
failed bool
t *testing.T
}
func (m *mockLogger) Log(args ...any) {
m.msgs = append(m.msgs, args[0].(string))
}
func (m mockLogger) Name() string {
return "TestLogger"
}
func (m mockLogger) Cleanup(fn func()) {
m.t.Cleanup(fn)
}
func (m mockLogger) Failed() bool {
return m.failed
}
func TestNew(t *testing.T) {
t.Run("should return new stdwriter", func(t *testing.T) {
writer := New(&mockLogger{t: t}, "proc")
_, ok := writer.(*stdwriter)
assert.True(t, ok)
})
}
func TestWrite(t *testing.T) {
t.Run("should write to buffer", func(t *testing.T) {
logger := &mockLogger{t: t, failed: true}
writer := New(logger, "proc").(*stdwriter)
_, err := writer.Write([]byte("test"))
require.NoError(t, err)
assert.Equal(t, "test", writer.buf.String())
})
t.Run("should not flush on newline but on close", func(t *testing.T) {
logger := &mockLogger{t: t, failed: true}
writer := New(logger, "proc").(*stdwriter)
_, err := writer.Write([]byte("test\n"))
require.NoError(t, err)
assert.Equal(t, 5, writer.buf.Len())
assert.Empty(t, logger.msgs)
require.NoError(t, writer.Close())
_ = assert.Len(t, logger.msgs, 1) && assert.Equal(t, "TestLogger/proc: test", logger.msgs[0])
})
t.Run("should not return error on write when closed", func(t *testing.T) {
writer := New(&mockLogger{t: t}, "proc").(*stdwriter)
require.NoError(t, writer.Close())
_, err := writer.Write([]byte("test\n"))
require.NotErrorIs(t, err, io.ErrClosedPipe)
assert.Equal(t, "test\n", writer.buf.String())
})
}
func TestClose(t *testing.T) {
t.Run("should flush and close", func(t *testing.T) {
logger := &mockLogger{t: t, failed: true}
writer := New(logger, "proc").(*stdwriter)
writer.Write([]byte("test"))
writer.Close()
assert.Equal(t, 0, writer.buf.Len())
_ = assert.Len(t, logger.msgs, 1) &&
assert.Equal(t, "TestLogger/proc: test", logger.msgs[0])
})
}
func TestNotFailed(t *testing.T) {
t.Run("if test has not failed it should not print output", func(t *testing.T) {
logger := &mockLogger{t: t, failed: false}
writer := New(logger, "proc").(*stdwriter)
writer.Write([]byte("test"))
writer.Close()
assert.Equal(t, 0, writer.buf.Len())
assert.Empty(t, logger.msgs)
})
t.Run("if test has not failed but `DAPR_INTEGRATION_LOGS=true`, print output", func(t *testing.T) {
t.Setenv("DAPR_INTEGRATION_LOGS", "true")
logger := &mockLogger{t: t, failed: false}
writer := New(logger, "proc").(*stdwriter)
writer.Write([]byte("test"))
writer.Close()
assert.Equal(t, 0, writer.buf.Len())
_ = assert.Len(t, logger.msgs, 1) &&
assert.Equal(t, "TestLogger/proc: test", logger.msgs[0])
})
t.Run("if test has not failed but `DAPR_INTEGRATION_LOGS=TRUE`, print output", func(t *testing.T) {
t.Setenv("DAPR_INTEGRATION_LOGS", "true")
logger := &mockLogger{t: t, failed: false}
writer := New(logger, "proc").(*stdwriter)
writer.Write([]byte("test"))
writer.Close()
assert.Equal(t, 0, writer.buf.Len())
_ = assert.Len(t, logger.msgs, 1) &&
assert.Equal(t, "TestLogger/proc: test", logger.msgs[0])
})
}
func TestConcurrency(t *testing.T) {
t.Run("should handle concurrent writes", func(t *testing.T) {
logger := &mockLogger{t: t, failed: true}
writer := New(logger, "proc").(*stdwriter)
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
defer wg.Done()
for i := 0; i < 1000; i++ {
fmt.Fprintf(writer, "test %d\n", i)
}
}()
go func() {
defer wg.Done()
for i := 0; i < 1000; i++ {
fmt.Fprintf(writer, "test %d\n", i)
}
}()
wg.Wait()
require.NoError(t, writer.Close())
assert.Equal(t, 0, writer.buf.Len())
assert.Len(t, logger.msgs, 2000)
for _, msg := range logger.msgs {
assert.Contains(t, msg, "TestLogger/proc: test ")
}
})
}
|
mikeee/dapr
|
tests/integration/framework/iowriter/iowriter_test.go
|
GO
|
mit
| 4,522 |
/*
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 framework
import (
"github.com/dapr/dapr/tests/integration/framework/process"
"github.com/dapr/dapr/tests/integration/framework/process/once"
)
func WithProcesses(procs ...process.Interface) Option {
return func(o *options) {
for _, proc := range procs {
var found bool
for _, d := range o.procs {
if d == proc {
found = true
break
}
}
if !found {
o.procs = append(o.procs, once.Wrap(proc))
}
}
}
}
|
mikeee/dapr
|
tests/integration/framework/options.go
|
GO
|
mit
| 1,015 |
/*
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 daprd
import (
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/prometheus/common/expfmt"
"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/emptypb"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework/binary"
"github.com/dapr/dapr/tests/integration/framework/process"
"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/ports"
"github.com/dapr/dapr/tests/integration/framework/util"
)
type Daprd struct {
exec process.Interface
appHTTP process.Interface
ports *ports.Ports
httpClient *http.Client
appID string
namespace string
appProtocol string
appPort int
grpcPort int
httpPort int
internalGRPCPort int
publicPort int
metricsPort int
profilePort int
}
func New(t *testing.T, fopts ...Option) *Daprd {
t.Helper()
uid, err := uuid.NewRandom()
require.NoError(t, err)
appHTTP := prochttp.New(t)
fp := ports.Reserve(t, 6)
opts := options{
appID: uid.String(),
appPort: appHTTP.Port(),
appProtocol: "http",
grpcPort: fp.Port(t),
httpPort: fp.Port(t),
internalGRPCPort: fp.Port(t),
publicPort: fp.Port(t),
metricsPort: fp.Port(t),
profilePort: fp.Port(t),
logLevel: "info",
mode: "standalone",
}
for _, fopt := range fopts {
fopt(&opts)
}
dir := t.TempDir()
for i, file := range opts.resourceFiles {
require.NoError(t, os.WriteFile(filepath.Join(dir, strconv.Itoa(i)+".yaml"), []byte(file), 0o600))
}
args := []string{
"--log-level=" + opts.logLevel,
"--app-id=" + opts.appID,
"--app-port=" + strconv.Itoa(opts.appPort),
"--app-protocol=" + opts.appProtocol,
"--dapr-grpc-port=" + strconv.Itoa(opts.grpcPort),
"--dapr-http-port=" + strconv.Itoa(opts.httpPort),
"--dapr-internal-grpc-port=" + strconv.Itoa(opts.internalGRPCPort),
"--dapr-internal-grpc-listen-address=127.0.0.1",
"--dapr-listen-addresses=127.0.0.1",
"--dapr-public-port=" + strconv.Itoa(opts.publicPort),
"--dapr-public-listen-address=127.0.0.1",
"--metrics-port=" + strconv.Itoa(opts.metricsPort),
"--metrics-listen-address=127.0.0.1",
"--profile-port=" + strconv.Itoa(opts.profilePort),
"--enable-app-health-check=" + strconv.FormatBool(opts.appHealthCheck),
"--app-health-probe-interval=" + strconv.Itoa(opts.appHealthProbeInterval),
"--app-health-threshold=" + strconv.Itoa(opts.appHealthProbeThreshold),
"--mode=" + opts.mode,
"--enable-mtls=" + strconv.FormatBool(opts.enableMTLS),
}
if opts.appHealthCheckPath != "" {
args = append(args, "--app-health-check-path="+opts.appHealthCheckPath)
}
if len(opts.resourceFiles) > 0 {
args = append(args, "--resources-path="+dir)
}
for _, dir := range opts.resourceDirs {
args = append(args, "--resources-path="+dir)
}
if len(opts.configs) > 0 {
for _, c := range opts.configs {
args = append(args, "--config="+c)
}
}
if len(opts.placementAddresses) > 0 {
args = append(args, "--placement-host-address="+strings.Join(opts.placementAddresses, ","))
}
if len(opts.sentryAddress) > 0 {
args = append(args, "--sentry-address="+opts.sentryAddress)
}
if len(opts.controlPlaneAddress) > 0 {
args = append(args, "--control-plane-address="+opts.controlPlaneAddress)
}
if opts.disableK8sSecretStore != nil {
args = append(args, "--disable-builtin-k8s-secret-store="+strconv.FormatBool(*opts.disableK8sSecretStore))
}
if opts.gracefulShutdownSeconds != nil {
args = append(args, "--dapr-graceful-shutdown-seconds="+strconv.Itoa(*opts.gracefulShutdownSeconds))
}
if opts.blockShutdownDuration != nil {
args = append(args, "--dapr-block-shutdown-duration="+*opts.blockShutdownDuration)
}
if opts.controlPlaneTrustDomain != nil {
args = append(args, "--control-plane-trust-domain="+*opts.controlPlaneTrustDomain)
}
ns := "default"
if opts.namespace != nil {
ns = *opts.namespace
opts.execOpts = append(opts.execOpts, exec.WithEnvVars(t, "NAMESPACE", *opts.namespace))
}
return &Daprd{
exec: exec.New(t, binary.EnvValue("daprd"), args, opts.execOpts...),
ports: fp,
httpClient: util.HTTPClient(t),
appHTTP: appHTTP,
appID: opts.appID,
namespace: ns,
appProtocol: opts.appProtocol,
appPort: opts.appPort,
grpcPort: opts.grpcPort,
httpPort: opts.httpPort,
internalGRPCPort: opts.internalGRPCPort,
publicPort: opts.publicPort,
metricsPort: opts.metricsPort,
profilePort: opts.profilePort,
}
}
func (d *Daprd) Run(t *testing.T, ctx context.Context) {
d.appHTTP.Run(t, ctx)
d.ports.Free(t)
d.exec.Run(t, ctx)
}
func (d *Daprd) Cleanup(t *testing.T) {
d.exec.Cleanup(t)
d.appHTTP.Cleanup(t)
}
func (d *Daprd) WaitUntilTCPReady(t *testing.T, ctx context.Context) {
assert.Eventually(t, func() bool {
dialer := net.Dialer{Timeout: time.Second}
net, err := dialer.DialContext(ctx, "tcp", d.HTTPAddress())
if err != nil {
return false
}
net.Close()
return true
}, 10*time.Second, 10*time.Millisecond)
}
func (d *Daprd) WaitUntilRunning(t *testing.T, ctx context.Context) {
client := util.HTTPClient(t)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://%s/v1.0/healthz", d.HTTPAddress()), nil)
require.NoError(t, err)
require.Eventually(t, func() bool {
resp, err := client.Do(req)
if err != nil {
return false
}
defer resp.Body.Close()
return http.StatusNoContent == resp.StatusCode
}, 30*time.Second, 10*time.Millisecond)
}
func (d *Daprd) WaitUntilAppHealth(t *testing.T, ctx context.Context) {
switch d.appProtocol {
case "http":
client := util.HTTPClient(t)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://%s/v1.0/healthz", d.HTTPAddress()), nil)
require.NoError(t, err)
assert.Eventually(t, func() bool {
resp, err := client.Do(req)
if err != nil {
return false
}
defer resp.Body.Close()
return http.StatusNoContent == resp.StatusCode
}, 10*time.Second, 10*time.Millisecond)
case "grpc":
assert.Eventually(t, func() bool {
conn, err := grpc.Dial(d.AppAddress(),
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithBlock())
if conn != nil {
defer conn.Close()
}
if err != nil {
return false
}
in := emptypb.Empty{}
out := rtv1.HealthCheckResponse{}
err = conn.Invoke(ctx, "/dapr.proto.runtime.v1.AppCallbackHealthCheck/HealthCheck", &in, &out)
return err == nil
}, 10*time.Second, 10*time.Millisecond)
}
}
func (d *Daprd) GRPCConn(t *testing.T, ctx context.Context) *grpc.ClientConn {
conn, err := grpc.DialContext(ctx, d.GRPCAddress(),
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithBlock(),
)
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, conn.Close()) })
return conn
}
func (d *Daprd) GRPCClient(t *testing.T, ctx context.Context) rtv1.DaprClient {
return rtv1.NewDaprClient(d.GRPCConn(t, ctx))
}
func (d *Daprd) AppID() string {
return d.appID
}
func (d *Daprd) Namespace() string {
return d.namespace
}
func (d *Daprd) ipPort(port int) string {
return "127.0.0.1:" + strconv.Itoa(port)
}
func (d *Daprd) AppPort() int {
return d.appPort
}
func (d *Daprd) AppAddress() string {
return d.ipPort(d.AppPort())
}
func (d *Daprd) GRPCPort() int {
return d.grpcPort
}
func (d *Daprd) GRPCAddress() string {
return d.ipPort(d.GRPCPort())
}
func (d *Daprd) HTTPPort() int {
return d.httpPort
}
func (d *Daprd) HTTPAddress() string {
return d.ipPort(d.HTTPPort())
}
func (d *Daprd) InternalGRPCPort() int {
return d.internalGRPCPort
}
func (d *Daprd) InternalGRPCAddress() string {
return d.ipPort(d.InternalGRPCPort())
}
func (d *Daprd) PublicPort() int {
return d.publicPort
}
func (d *Daprd) MetricsPort() int {
return d.metricsPort
}
func (d *Daprd) MetricsAddress() string {
return d.ipPort(d.MetricsPort())
}
func (d *Daprd) ProfilePort() int {
return d.profilePort
}
// Returns a subset of metrics scraped from the metrics endpoint
func (d *Daprd) Metrics(t *testing.T, ctx context.Context) map[string]float64 {
t.Helper()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://%s/metrics", d.MetricsAddress()), nil)
require.NoError(t, err)
resp, err := d.httpClient.Do(req)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
// Extract the metrics
parser := expfmt.TextParser{}
metricFamilies, err := parser.TextToMetricFamilies(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
metrics := make(map[string]float64)
for _, mf := range metricFamilies {
for _, m := range mf.GetMetric() {
key := mf.GetName()
for _, l := range m.GetLabel() {
key += "|" + l.GetName() + ":" + l.GetValue()
}
metrics[key] = m.GetCounter().GetValue()
}
}
return metrics
}
func (d *Daprd) HTTPGet2xx(t *testing.T, ctx context.Context, path string) {
t.Helper()
d.http2xx(t, ctx, http.MethodGet, path, nil)
}
func (d *Daprd) HTTPPost2xx(t *testing.T, ctx context.Context, path string, body io.Reader, headers ...string) {
t.Helper()
d.http2xx(t, ctx, http.MethodPost, path, body, headers...)
}
func (d *Daprd) http2xx(t *testing.T, ctx context.Context, method, path string, body io.Reader, headers ...string) {
t.Helper()
require.Zero(t, len(headers)%2, "headers must be key-value pairs")
path = strings.TrimPrefix(path, "/")
url := fmt.Sprintf("http://%s/%s", d.HTTPAddress(), path)
req, err := http.NewRequestWithContext(ctx, method, url, body)
require.NoError(t, err)
for i := 0; i < len(headers); i += 2 {
req.Header.Set(headers[i], headers[i+1])
}
resp, err := d.httpClient.Do(req)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.GreaterOrEqual(t, resp.StatusCode, 200, "expected 2xx status code")
require.Less(t, resp.StatusCode, 300, "expected 2xx status code")
}
func (d *Daprd) GetMetaRegistedComponents(t assert.TestingT, ctx context.Context) []*rtv1.RegisteredComponents {
return d.meta(t, ctx).RegisteredComponents
}
func (d *Daprd) GetMetaSubscriptions(t assert.TestingT, ctx context.Context) []any {
return d.meta(t, ctx).Subscriptions
}
type metaResponse struct {
RegisteredComponents []*rtv1.RegisteredComponents `json:"components,omitempty"`
Subscriptions []any `json:"subscriptions,omitempty"`
}
func (d *Daprd) meta(t assert.TestingT, ctx context.Context) metaResponse {
url := fmt.Sprintf("http://%s/v1.0/metadata", d.HTTPAddress())
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
//nolint:testifylint
if !assert.NoError(t, err) {
return metaResponse{}
}
var meta metaResponse
resp, err := d.httpClient.Do(req)
//nolint:testifylint
if assert.NoError(t, err) {
defer resp.Body.Close()
assert.NoError(t, json.NewDecoder(resp.Body).Decode(&meta))
}
return meta
}
|
mikeee/dapr
|
tests/integration/framework/process/daprd/daprd.go
|
GO
|
mit
| 11,936 |
/*
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 daprd
import (
"fmt"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/logline"
"github.com/dapr/dapr/tests/integration/framework/socket"
)
// Option is a function that configures the dapr process.
type Option func(*options)
// options contains the options for running Daprd in integration tests.
type options struct {
execOpts []exec.Option
appID string
namespace *string
appPort int
grpcPort int
httpPort int
internalGRPCPort int
publicPort int
metricsPort int
profilePort int
appProtocol string
appHealthCheck bool
appHealthCheckPath string
appHealthProbeInterval int
appHealthProbeThreshold int
resourceFiles []string
resourceDirs []string
configs []string
placementAddresses []string
logLevel string
mode string
enableMTLS bool
sentryAddress string
controlPlaneAddress string
disableK8sSecretStore *bool
gracefulShutdownSeconds *int
blockShutdownDuration *string
controlPlaneTrustDomain *string
}
func WithExecOptions(execOptions ...exec.Option) Option {
return func(o *options) {
o.execOpts = append(o.execOpts, execOptions...)
}
}
func WithAppID(appID string) Option {
return func(o *options) {
o.appID = appID
}
}
func WithNamespace(namespace string) Option {
return func(o *options) {
o.namespace = &namespace
}
}
func WithLogLineStdout(ll *logline.LogLine) Option {
return WithExecOptions(exec.WithStdout(ll.Stdout()))
}
func WithExit1() Option {
return WithExecOptions(
exec.WithExitCode(1),
exec.WithRunError(func(t *testing.T, err error) {
require.ErrorContains(t, err, "exit status 1")
}),
)
}
func WithAppPort(port int) Option {
return func(o *options) {
o.appPort = port
}
}
func WithAppProtocol(protocol string) Option {
return func(o *options) {
o.appProtocol = protocol
}
}
func WithGRPCPort(port int) Option {
return func(o *options) {
o.grpcPort = port
}
}
func WithHTTPPort(port int) Option {
return func(o *options) {
o.httpPort = port
}
}
func WithInternalGRPCPort(port int) Option {
return func(o *options) {
o.internalGRPCPort = port
}
}
func WithPublicPort(port int) Option {
return func(o *options) {
o.publicPort = port
}
}
func WithMetricsPort(port int) Option {
return func(o *options) {
o.metricsPort = port
}
}
func WithProfilePort(port int) Option {
return func(o *options) {
o.profilePort = port
}
}
func WithAppHealthCheck(enabled bool) Option {
return func(o *options) {
o.appHealthCheck = enabled
}
}
func WithAppHealthCheckPath(path string) Option {
return func(o *options) {
o.appHealthCheckPath = path
}
}
func WithAppHealthProbeInterval(interval int) Option {
return func(o *options) {
o.appHealthProbeInterval = interval
}
}
func WithAppHealthProbeThreshold(threshold int) Option {
return func(o *options) {
o.appHealthProbeThreshold = threshold
}
}
func WithResourceFiles(files ...string) Option {
return func(o *options) {
o.resourceFiles = append(o.resourceFiles, files...)
}
}
func WithInMemoryStateStore(storeName string) Option {
return WithResourceFiles(`apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: ` + storeName + `
spec:
type: state.in-memory
version: v1
`)
}
// WithInMemoryActorStateStore adds an in-memory state store component, which is also enabled as actor state store.
func WithInMemoryActorStateStore(storeName string) Option {
return WithResourceFiles(`apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: ` + storeName + `
spec:
type: state.in-memory
version: v1
metadata:
- name: actorStateStore
value: true
`)
}
func WithResourcesDir(dirs ...string) Option {
return func(o *options) {
o.resourceDirs = dirs
}
}
func WithConfigs(configs ...string) Option {
return func(o *options) {
o.configs = append(o.configs, configs...)
}
}
func WithConfigManifests(t *testing.T, manifests ...string) Option {
configs := make([]string, len(manifests))
for i, manifest := range manifests {
f := filepath.Join(t.TempDir(), fmt.Sprintf("config-%d.yaml", i))
require.NoError(t, os.WriteFile(f, []byte(manifest), 0o600))
configs[i] = f
}
return func(o *options) {
o.configs = append(o.configs, configs...)
}
}
func WithPlacementAddresses(addresses ...string) Option {
return func(o *options) {
o.placementAddresses = addresses
}
}
func WithLogLevel(logLevel string) Option {
return func(o *options) {
o.logLevel = logLevel
}
}
func WithMode(mode string) Option {
return func(o *options) {
o.mode = mode
}
}
func WithEnableMTLS(enable bool) Option {
return func(o *options) {
o.enableMTLS = enable
}
}
func WithSentryAddress(address string) Option {
return func(o *options) {
o.sentryAddress = address
}
}
func WithControlPlaneAddress(address string) Option {
return func(o *options) {
o.controlPlaneAddress = address
}
}
func WithDisableK8sSecretStore(disable bool) Option {
return func(o *options) {
o.disableK8sSecretStore = &disable
}
}
func WithDaprGracefulShutdownSeconds(seconds int) Option {
return func(o *options) {
o.gracefulShutdownSeconds = &seconds
}
}
func WithDaprBlockShutdownDuration(duration string) Option {
return func(o *options) {
o.blockShutdownDuration = &duration
}
}
func WithControlPlaneTrustDomain(trustDomain string) Option {
return func(o *options) {
o.controlPlaneTrustDomain = &trustDomain
}
}
func WithSocket(t *testing.T, socket *socket.Socket) Option {
return WithExecOptions(exec.WithEnvVars(t,
"DAPR_COMPONENTS_SOCKETS_FOLDER", socket.Directory(),
))
}
func WithAppAPIToken(t *testing.T, token string) Option {
return WithExecOptions(exec.WithEnvVars(t,
"APP_API_TOKEN", token,
))
}
|
mikeee/dapr
|
tests/integration/framework/process/daprd/options.go
|
GO
|
mit
| 6,606 |
/*
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 exec
import (
"context"
"io"
oexec "os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/integration/framework/iowriter"
"github.com/dapr/dapr/tests/integration/framework/process/exec/kill"
)
type Option func(*options)
type exec struct {
lock sync.Mutex
cmd *oexec.Cmd
args []string
binPath string
runErrorFn func(*testing.T, error)
exitCode int
envs map[string]string
stdoutpipe io.WriteCloser
stderrpipe io.WriteCloser
}
func New(t *testing.T, binPath string, args []string, fopts ...Option) *exec {
t.Helper()
defaultExitCode := 0
if runtime.GOOS == "windows" {
// Windows returns 1 when we kill the process.
defaultExitCode = 1
}
opts := options{
stdout: iowriter.New(t, filepath.Base(binPath)),
stderr: iowriter.New(t, filepath.Base(binPath)),
runErrorFn: func(t *testing.T, err error) {
t.Helper()
if runtime.GOOS == "windows" {
// Windows returns 1 when we kill the process.
require.ErrorContains(t, err, "exit status 1")
} else {
require.NoError(t, err, "expected %q to run without error", binPath)
}
},
exitCode: defaultExitCode,
}
for _, fopt := range fopts {
fopt(&opts)
}
return &exec{
binPath: binPath,
args: args,
envs: opts.envs,
stdoutpipe: opts.stdout,
stderrpipe: opts.stderr,
runErrorFn: opts.runErrorFn,
exitCode: opts.exitCode,
}
}
func (e *exec) Run(t *testing.T, ctx context.Context) {
t.Helper()
e.lock.Lock()
defer e.lock.Unlock()
t.Logf("Running %q with args: %s %s", filepath.Base(e.binPath), e.binPath, strings.Join(e.args, " "))
//nolint:gosec
e.cmd = oexec.CommandContext(ctx, e.binPath, e.args...)
e.cmd.Stdout = e.stdoutpipe
e.cmd.Stderr = e.stderrpipe
// Wait for a few seconds before killing the process completely.
e.cmd.WaitDelay = time.Second * 5
for k, v := range e.envs {
e.cmd.Env = append(e.cmd.Env, k+"="+v)
}
require.NoError(t, e.cmd.Start())
}
func (e *exec) Cleanup(t *testing.T) {
t.Helper()
e.lock.Lock()
defer e.lock.Unlock()
kill.Kill(t, e.cmd)
e.checkExit(t)
require.NoError(t, e.stderrpipe.Close())
require.NoError(t, e.stdoutpipe.Close())
}
func (e *exec) checkExit(t *testing.T) {
t.Helper()
t.Logf("waiting for %q process to exit", filepath.Base(e.binPath))
e.runErrorFn(t, e.cmd.Wait())
require.NotNil(t, e.cmd.ProcessState, "process state should not be nil")
assert.Equalf(t, e.exitCode, e.cmd.ProcessState.ExitCode(), "expected exit code to be %d", e.exitCode)
t.Logf("%q process exited", filepath.Base(e.binPath))
}
|
mikeee/dapr
|
tests/integration/framework/process/exec/exec.go
|
GO
|
mit
| 3,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 implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kill
import (
"os/exec"
"testing"
)
func Kill(t *testing.T, cmd *exec.Cmd) {
t.Helper()
if cmd == nil || cmd.ProcessState != nil {
return
}
t.Log("interrupting daprd process")
interrupt(t, cmd)
}
|
mikeee/dapr
|
tests/integration/framework/process/exec/kill/kill.go
|
GO
|
mit
| 779 |
//go:build !windows
// +build !windows
/*
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 kill
import (
"os"
"os/exec"
"testing"
"github.com/stretchr/testify/require"
)
func interrupt(t *testing.T, cmd *exec.Cmd) {
require.NoError(t, cmd.Process.Signal(os.Interrupt))
}
|
mikeee/dapr
|
tests/integration/framework/process/exec/kill/kill_posix.go
|
GO
|
mit
| 797 |
//go:build windows
// +build windows
/*
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 kill
import (
"os"
"os/exec"
"strconv"
"testing"
)
func interrupt(_ *testing.T, cmd *exec.Cmd) {
kill := exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(cmd.Process.Pid))
kill.Stdout = os.Stdout
kill.Stderr = os.Stderr
kill.Run()
}
|
mikeee/dapr
|
tests/integration/framework/process/exec/kill/kill_windows.go
|
GO
|
mit
| 859 |
/*
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 exec
import (
"io"
"testing"
"github.com/stretchr/testify/require"
)
type options struct {
stdout io.WriteCloser
stderr io.WriteCloser
runErrorFn func(*testing.T, error)
exitCode int
envs map[string]string
}
func WithStdout(stdout io.WriteCloser) Option {
return func(o *options) {
o.stdout = stdout
}
}
func WithStderr(stderr io.WriteCloser) Option {
return func(o *options) {
o.stderr = stderr
}
}
func WithRunError(ferr func(*testing.T, error)) Option {
return func(o *options) {
o.runErrorFn = ferr
}
}
func WithExitCode(code int) Option {
return func(o *options) {
o.exitCode = code
}
}
// WithEnvVars sets the environment variables for the command. Expects a list
// of key value pairs.
func WithEnvVars(t *testing.T, envs ...string) Option {
return func(o *options) {
require.Equal(t, 0, len(envs)%2, "envs must be a list of key value pairs")
if o.envs == nil {
o.envs = make(map[string]string)
}
for i := 0; i < len(envs); i += 2 {
o.envs[envs[i]] = envs[i+1]
}
}
}
|
mikeee/dapr
|
tests/integration/framework/process/exec/options.go
|
GO
|
mit
| 1,602 |
/*
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"
"testing"
"google.golang.org/grpc"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
procgrpc "github.com/dapr/dapr/tests/integration/framework/process/grpc"
)
// Option is a function that configures the process.
type Option func(*options)
// App is a wrapper around a grpc.Server that implements a Dapr App.
type App struct {
grpc *procgrpc.GRPC
}
func New(t *testing.T, fopts ...Option) *App {
t.Helper()
var opts options
for _, fopt := range fopts {
fopt(&opts)
}
return &App{
grpc: procgrpc.New(t, append(opts.grpcopts, procgrpc.WithRegister(func(s *grpc.Server) {
srv := &server{
onInvokeFn: opts.onInvokeFn,
onTopicEventFn: opts.onTopicEventFn,
onBulkTopicEventFn: opts.onBulkTopicEventFn,
listTopicSubFn: opts.listTopicSubFn,
listInputBindFn: opts.listInputBindFn,
onBindingEventFn: opts.onBindingEventFn,
healthCheckFn: opts.healthCheckFn,
}
rtv1.RegisterAppCallbackServer(s, srv)
rtv1.RegisterAppCallbackAlphaServer(s, srv)
rtv1.RegisterAppCallbackHealthCheckServer(s, srv)
if opts.withRegister != nil {
opts.withRegister(s)
}
}))...),
}
}
func (a *App) Run(t *testing.T, ctx context.Context) {
a.grpc.Run(t, ctx)
}
func (a *App) Cleanup(t *testing.T) {
a.grpc.Cleanup(t)
}
func (a *App) Port(t *testing.T) int {
return a.grpc.Port(t)
}
|
mikeee/dapr
|
tests/integration/framework/process/grpc/app/app.go
|
GO
|
mit
| 1,948 |
/*
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"
"google.golang.org/grpc"
"google.golang.org/protobuf/types/known/emptypb"
commonv1 "github.com/dapr/dapr/pkg/proto/common/v1"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
procgrpc "github.com/dapr/dapr/tests/integration/framework/process/grpc"
)
// options contains the options for running a GRPC server app in integration
// tests.
type options struct {
grpcopts []procgrpc.Option
withRegister func(s *grpc.Server)
onTopicEventFn func(context.Context, *rtv1.TopicEventRequest) (*rtv1.TopicEventResponse, error)
onBulkTopicEventFn func(context.Context, *rtv1.TopicEventBulkRequest) (*rtv1.TopicEventBulkResponse, error)
onInvokeFn func(context.Context, *commonv1.InvokeRequest) (*commonv1.InvokeResponse, error)
listTopicSubFn func(ctx context.Context, in *emptypb.Empty) (*rtv1.ListTopicSubscriptionsResponse, error)
listInputBindFn func(context.Context, *emptypb.Empty) (*rtv1.ListInputBindingsResponse, error)
onBindingEventFn func(context.Context, *rtv1.BindingEventRequest) (*rtv1.BindingEventResponse, error)
healthCheckFn func(context.Context, *emptypb.Empty) (*rtv1.HealthCheckResponse, error)
}
func WithGRPCOptions(opts ...procgrpc.Option) func(*options) {
return func(o *options) {
o.grpcopts = opts
}
}
func WithOnTopicEventFn(fn func(context.Context, *rtv1.TopicEventRequest) (*rtv1.TopicEventResponse, error)) func(*options) {
return func(opts *options) {
opts.onTopicEventFn = fn
}
}
func WithOnBulkTopicEventFn(fn func(context.Context, *rtv1.TopicEventBulkRequest) (*rtv1.TopicEventBulkResponse, error)) func(*options) {
return func(opts *options) {
opts.onBulkTopicEventFn = fn
}
}
func WithOnInvokeFn(fn func(ctx context.Context, in *commonv1.InvokeRequest) (*commonv1.InvokeResponse, error)) func(*options) {
return func(opts *options) {
opts.onInvokeFn = fn
}
}
func WithListTopicSubscriptions(fn func(ctx context.Context, in *emptypb.Empty) (*rtv1.ListTopicSubscriptionsResponse, error)) func(*options) {
return func(opts *options) {
opts.listTopicSubFn = fn
}
}
func WithListInputBindings(fn func(context.Context, *emptypb.Empty) (*rtv1.ListInputBindingsResponse, error)) func(*options) {
return func(opts *options) {
opts.listInputBindFn = fn
}
}
func WithOnBindingEventFn(fn func(context.Context, *rtv1.BindingEventRequest) (*rtv1.BindingEventResponse, error)) func(*options) {
return func(opts *options) {
opts.onBindingEventFn = fn
}
}
func WithHealthCheckFn(fn func(context.Context, *emptypb.Empty) (*rtv1.HealthCheckResponse, error)) func(*options) {
return func(opts *options) {
opts.healthCheckFn = fn
}
}
func WithRegister(fn func(s *grpc.Server)) func(*options) {
return func(opts *options) {
opts.withRegister = fn
}
}
|
mikeee/dapr
|
tests/integration/framework/process/grpc/app/options.go
|
GO
|
mit
| 3,354 |
/*
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"
"google.golang.org/protobuf/types/known/emptypb"
commonv1 "github.com/dapr/dapr/pkg/proto/common/v1"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
)
type server struct {
onInvokeFn func(context.Context, *commonv1.InvokeRequest) (*commonv1.InvokeResponse, error)
onTopicEventFn func(context.Context, *rtv1.TopicEventRequest) (*rtv1.TopicEventResponse, error)
onBulkTopicEventFn func(context.Context, *rtv1.TopicEventBulkRequest) (*rtv1.TopicEventBulkResponse, error)
listTopicSubFn func(context.Context, *emptypb.Empty) (*rtv1.ListTopicSubscriptionsResponse, error)
listInputBindFn func(context.Context, *emptypb.Empty) (*rtv1.ListInputBindingsResponse, error)
onBindingEventFn func(context.Context, *rtv1.BindingEventRequest) (*rtv1.BindingEventResponse, error)
healthCheckFn func(context.Context, *emptypb.Empty) (*rtv1.HealthCheckResponse, error)
}
func (s *server) OnInvoke(ctx context.Context, in *commonv1.InvokeRequest) (*commonv1.InvokeResponse, error) {
if s.onInvokeFn == nil {
return new(commonv1.InvokeResponse), nil
}
return s.onInvokeFn(ctx, in)
}
func (s *server) ListInputBindings(context.Context, *emptypb.Empty) (*rtv1.ListInputBindingsResponse, error) {
if s.listInputBindFn == nil {
return new(rtv1.ListInputBindingsResponse), nil
}
return s.listInputBindFn(context.Background(), new(emptypb.Empty))
}
func (s *server) ListTopicSubscriptions(context.Context, *emptypb.Empty) (*rtv1.ListTopicSubscriptionsResponse, error) {
if s.listTopicSubFn == nil {
return new(rtv1.ListTopicSubscriptionsResponse), nil
}
return s.listTopicSubFn(context.Background(), new(emptypb.Empty))
}
func (s *server) OnBindingEvent(ctx context.Context, in *rtv1.BindingEventRequest) (*rtv1.BindingEventResponse, error) {
if s.onBindingEventFn == nil {
return new(rtv1.BindingEventResponse), nil
}
return s.onBindingEventFn(ctx, in)
}
func (s *server) OnTopicEvent(ctx context.Context, in *rtv1.TopicEventRequest) (*rtv1.TopicEventResponse, error) {
if s.onTopicEventFn == nil {
return new(rtv1.TopicEventResponse), nil
}
return s.onTopicEventFn(ctx, in)
}
func (s *server) OnBulkTopicEventAlpha1(ctx context.Context, in *rtv1.TopicEventBulkRequest) (*rtv1.TopicEventBulkResponse, error) {
if s.onBulkTopicEventFn == nil {
return new(rtv1.TopicEventBulkResponse), nil
}
return s.onBulkTopicEventFn(ctx, in)
}
func (s *server) HealthCheck(ctx context.Context, e *emptypb.Empty) (*rtv1.HealthCheckResponse, error) {
if s.healthCheckFn == nil {
return new(rtv1.HealthCheckResponse), nil
}
return s.healthCheckFn(ctx, e)
}
|
mikeee/dapr
|
tests/integration/framework/process/grpc/app/server.go
|
GO
|
mit
| 3,190 |
/*
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 grpc
import (
"context"
"errors"
"net"
"net/http"
"strconv"
"testing"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"github.com/dapr/dapr/tests/integration/framework/process/ports"
)
// Option is a function that configures the process.
type Option func(*options)
// GRPC is a GRPC server that can be used in integration tests.
type GRPC struct {
registerFns []func(*grpc.Server)
serverOpts []func(*testing.T, context.Context) grpc.ServerOption
listener func() (net.Listener, error)
srvErrCh chan error
stopCh chan struct{}
}
func New(t *testing.T, fopts ...Option) *GRPC {
t.Helper()
var opts options
for _, fopt := range fopts {
fopt(&opts)
}
ln := opts.listener
if ln == nil {
fpln := ports.Reserve(t, 1).Listener(t)
ln = func() (net.Listener, error) {
return fpln, nil
}
}
return &GRPC{
listener: ln,
registerFns: opts.registerFns,
serverOpts: opts.serverOpts,
srvErrCh: make(chan error),
stopCh: make(chan struct{}),
}
}
func (g *GRPC) Port(t *testing.T) int {
ln, err := g.listener()
require.NoError(t, err)
return ln.Addr().(*net.TCPAddr).Port
}
func (g *GRPC) Address(t *testing.T) string {
return "localhost:" + strconv.Itoa(g.Port(t))
}
func (g *GRPC) Run(t *testing.T, ctx context.Context) {
ctx, cancel := context.WithCancel(ctx)
opts := make([]grpc.ServerOption, len(g.serverOpts))
for i, opt := range g.serverOpts {
opts[i] = opt(t, ctx)
}
server := grpc.NewServer(opts...)
for _, rfs := range g.registerFns {
rfs(server)
}
go func() {
ln, err := g.listener()
if err != nil {
g.srvErrCh <- err
return
}
g.srvErrCh <- server.Serve(ln)
}()
go func() {
<-g.stopCh
cancel()
server.GracefulStop()
}()
}
func (g *GRPC) Cleanup(t *testing.T) {
close(g.stopCh)
err := <-g.srvErrCh
if errors.Is(err, http.ErrServerClosed) || errors.Is(err, grpc.ErrServerStopped) {
err = nil
}
require.NoError(t, err)
}
|
mikeee/dapr
|
tests/integration/framework/process/grpc/grpc.go
|
GO
|
mit
| 2,523 |
/*
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 operator
import (
"context"
"encoding/json"
"errors"
"strconv"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
subapi "github.com/dapr/dapr/pkg/apis/subscriptions/v2alpha1"
"github.com/dapr/dapr/pkg/operator/api"
operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1"
"github.com/dapr/dapr/pkg/security"
procgrpc "github.com/dapr/dapr/tests/integration/framework/process/grpc"
)
// Option is a function that configures the process.
type Option func(*options)
// Operator is a wrapper around a grpc.Server that implements the Operator API.
type Operator struct {
*procgrpc.GRPC
closech chan struct{}
lock sync.RWMutex
updateCompCh chan *api.ComponentUpdateEvent
updateSubCh chan *api.SubscriptionUpdateEvent
srvCompUpdateCh []chan *api.ComponentUpdateEvent
srvSubUpdateCh []chan *api.SubscriptionUpdateEvent
currentComponents []compapi.Component
currentSubscriptions []subapi.Subscription
}
func New(t *testing.T, fopts ...Option) *Operator {
t.Helper()
o := &Operator{
closech: make(chan struct{}),
updateCompCh: make(chan *api.ComponentUpdateEvent),
updateSubCh: make(chan *api.SubscriptionUpdateEvent),
}
opts := options{
listComponentsFn: func(ctx context.Context, req *operatorv1.ListComponentsRequest) (*operatorv1.ListComponentResponse, error) {
o.lock.Lock()
defer o.lock.Unlock()
var comps [][]byte
for _, comp := range o.currentComponents {
if comp.Namespace != req.GetNamespace() {
continue
}
compB, err := json.Marshal(comp)
if err != nil {
return nil, err
}
comps = append(comps, compB)
}
return &operatorv1.ListComponentResponse{Components: comps}, nil
},
componentUpdateFn: func(req *operatorv1.ComponentUpdateRequest, srv operatorv1.Operator_ComponentUpdateServer) error {
o.lock.Lock()
updateCh := make(chan *api.ComponentUpdateEvent)
o.srvCompUpdateCh = append(o.srvCompUpdateCh, updateCh)
o.lock.Unlock()
for {
select {
case <-srv.Context().Done():
return nil
case <-o.closech:
return errors.New("operator closed")
case comp := <-updateCh:
if len(comp.Component.Namespace) == 0 {
comp.Component.Namespace = "default"
}
if comp.Component.Namespace != req.GetNamespace() {
continue
}
compB, err := json.Marshal(comp.Component)
if err != nil {
return err
}
if err := srv.Send(&operatorv1.ComponentUpdateEvent{
Component: compB,
Type: comp.EventType,
}); err != nil {
return err
}
}
}
},
subscriptionUpdateFn: func(req *operatorv1.SubscriptionUpdateRequest, srv operatorv1.Operator_SubscriptionUpdateServer) error {
o.lock.Lock()
updateCh := make(chan *api.SubscriptionUpdateEvent)
o.srvSubUpdateCh = append(o.srvSubUpdateCh, updateCh)
o.lock.Unlock()
for {
select {
case <-srv.Context().Done():
return nil
case <-o.closech:
return errors.New("operator closed")
case sub := <-updateCh:
if len(sub.Subscription.Namespace) == 0 {
sub.Subscription.Namespace = "default"
}
if sub.Subscription.Namespace != req.GetNamespace() {
continue
}
subB, err := json.Marshal(sub.Subscription)
if err != nil {
return err
}
if err := srv.Send(&operatorv1.SubscriptionUpdateEvent{
Subscription: subB,
Type: sub.EventType,
}); err != nil {
return err
}
}
}
},
}
for _, fopt := range fopts {
fopt(&opts)
}
require.NotNil(t, opts.sentry, "must provide sentry")
o.GRPC = procgrpc.New(t, append(opts.grpcopts,
procgrpc.WithServerOption(func(t *testing.T, ctx context.Context) grpc.ServerOption {
secProv, err := security.New(ctx, security.Options{
SentryAddress: "localhost:" + strconv.Itoa(opts.sentry.Port()),
ControlPlaneTrustDomain: "localhost",
ControlPlaneNamespace: "default",
TrustAnchors: opts.sentry.CABundle().TrustAnchors,
AppID: "dapr-operator",
MTLSEnabled: true,
})
require.NoError(t, err)
secProvErr := make(chan error)
t.Cleanup(func() {
select {
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for security provider to stop")
case err = <-secProvErr:
require.NoError(t, err)
}
})
go func() {
secProvErr <- secProv.Run(ctx)
}()
sec, err := secProv.Handler(ctx)
require.NoError(t, err)
return sec.GRPCServerOptionMTLS()
}),
procgrpc.WithRegister(func(s *grpc.Server) {
srv := &server{
componentUpdateFn: opts.componentUpdateFn,
getConfigurationFn: opts.getConfigurationFn,
getResiliencyFn: opts.getResiliencyFn,
httpEndpointUpdateFn: opts.httpEndpointUpdateFn,
listComponentsFn: opts.listComponentsFn,
listHTTPEndpointsFn: opts.listHTTPEndpointsFn,
listResiliencyFn: opts.listResiliencyFn,
listSubscriptionsFn: opts.listSubscriptionsFn,
listSubscriptionsV2Fn: opts.listSubscriptionsV2Fn,
subscriptionUpdateFn: opts.subscriptionUpdateFn,
}
operatorv1.RegisterOperatorServer(s, srv)
if opts.withRegister != nil {
opts.withRegister(s)
}
}))...)
return o
}
func (o *Operator) Cleanup(t *testing.T) {
close(o.closech)
o.GRPC.Cleanup(t)
}
// Add Component adds a component to the publish list of installed components.
func (o *Operator) AddComponents(cs ...compapi.Component) {
o.lock.Lock()
defer o.lock.Unlock()
o.currentComponents = append(o.currentComponents, cs...)
}
// SetComponents sets the list of installed components.
func (o *Operator) SetComponents(cs ...compapi.Component) {
o.lock.Lock()
defer o.lock.Unlock()
o.currentComponents = cs
}
// Components returns the list of installed components.
func (o *Operator) Components() []compapi.Component {
o.lock.RLock()
defer o.lock.RUnlock()
return o.currentComponents
}
// ComponentUpdateEvent sends a component update event to the operator which
// will be piped to clients listening on ComponentUpdate.
func (o *Operator) ComponentUpdateEvent(t *testing.T, ctx context.Context, event *api.ComponentUpdateEvent) {
t.Helper()
o.lock.Lock()
defer o.lock.Unlock()
for _, ch := range o.srvCompUpdateCh {
select {
case <-ctx.Done():
t.Fatal("timed out waiting for component update event")
case <-o.closech:
t.Fatal("operator closed")
case ch <- event:
}
}
}
func (o *Operator) AddSubscriptions(subs ...subapi.Subscription) {
o.lock.Lock()
defer o.lock.Unlock()
o.currentSubscriptions = append(o.currentSubscriptions, subs...)
}
func (o *Operator) SubscriptionUpdateEvent(t *testing.T, ctx context.Context, event *api.SubscriptionUpdateEvent) {
t.Helper()
o.lock.Lock()
defer o.lock.Unlock()
for _, ch := range o.srvSubUpdateCh {
select {
case <-ctx.Done():
t.Fatal("timed out waiting for subscption update event")
case <-o.closech:
t.Fatal("operator closed")
case ch <- event:
}
}
}
func (o *Operator) Subscriptions() []subapi.Subscription {
o.lock.RLock()
defer o.lock.RUnlock()
return o.currentSubscriptions
}
func (o *Operator) SetSubscriptions(subs ...subapi.Subscription) {
o.lock.Lock()
defer o.lock.Unlock()
o.currentSubscriptions = subs
}
|
mikeee/dapr
|
tests/integration/framework/process/grpc/operator/operator.go
|
GO
|
mit
| 7,972 |
/*
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 operator
import (
"context"
"google.golang.org/grpc"
"google.golang.org/protobuf/types/known/emptypb"
operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1"
procgrpc "github.com/dapr/dapr/tests/integration/framework/process/grpc"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
)
// options contains the options for running a GRPC server in integration tests.
type options struct {
grpcopts []procgrpc.Option
sentry *sentry.Sentry
withRegister func(*grpc.Server)
componentUpdateFn func(*operatorv1.ComponentUpdateRequest, operatorv1.Operator_ComponentUpdateServer) error
getConfigurationFn func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error)
getResiliencyFn func(context.Context, *operatorv1.GetResiliencyRequest) (*operatorv1.GetResiliencyResponse, error)
httpEndpointUpdateFn func(*operatorv1.HTTPEndpointUpdateRequest, operatorv1.Operator_HTTPEndpointUpdateServer) error
listComponentsFn func(context.Context, *operatorv1.ListComponentsRequest) (*operatorv1.ListComponentResponse, error)
listHTTPEndpointsFn func(context.Context, *operatorv1.ListHTTPEndpointsRequest) (*operatorv1.ListHTTPEndpointsResponse, error)
listResiliencyFn func(context.Context, *operatorv1.ListResiliencyRequest) (*operatorv1.ListResiliencyResponse, error)
listSubscriptionsFn func(context.Context, *emptypb.Empty) (*operatorv1.ListSubscriptionsResponse, error)
listSubscriptionsV2Fn func(context.Context, *operatorv1.ListSubscriptionsRequest) (*operatorv1.ListSubscriptionsResponse, error)
subscriptionUpdateFn func(*operatorv1.SubscriptionUpdateRequest, operatorv1.Operator_SubscriptionUpdateServer) error
}
func WithGRPCOptions(opts ...procgrpc.Option) func(*options) {
return func(o *options) {
o.grpcopts = opts
}
}
func WithSentry(sentry *sentry.Sentry) func(*options) {
return func(o *options) {
o.sentry = sentry
}
}
func WithComponentUpdateFn(fn func(*operatorv1.ComponentUpdateRequest, operatorv1.Operator_ComponentUpdateServer) error) func(*options) {
return func(opts *options) {
opts.componentUpdateFn = fn
}
}
func WithGetConfigurationFn(fn func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error)) func(*options) {
return func(opts *options) {
opts.getConfigurationFn = fn
}
}
func WithGetResiliencyFn(fn func(context.Context, *operatorv1.GetResiliencyRequest) (*operatorv1.GetResiliencyResponse, error)) func(*options) {
return func(opts *options) {
opts.getResiliencyFn = fn
}
}
func WithHTTPEndpointUpdateFn(fn func(*operatorv1.HTTPEndpointUpdateRequest, operatorv1.Operator_HTTPEndpointUpdateServer) error) func(*options) {
return func(opts *options) {
opts.httpEndpointUpdateFn = fn
}
}
func WithListComponentsFn(fn func(context.Context, *operatorv1.ListComponentsRequest) (*operatorv1.ListComponentResponse, error)) func(*options) {
return func(opts *options) {
opts.listComponentsFn = fn
}
}
func WithListHTTPEndpointsFn(fn func(context.Context, *operatorv1.ListHTTPEndpointsRequest) (*operatorv1.ListHTTPEndpointsResponse, error)) func(*options) {
return func(opts *options) {
opts.listHTTPEndpointsFn = fn
}
}
func WithListResiliencyFn(fn func(context.Context, *operatorv1.ListResiliencyRequest) (*operatorv1.ListResiliencyResponse, error)) func(*options) {
return func(opts *options) {
opts.listResiliencyFn = fn
}
}
func WithListSubscriptionsFn(fn func(context.Context, *emptypb.Empty) (*operatorv1.ListSubscriptionsResponse, error)) func(*options) {
return func(opts *options) {
opts.listSubscriptionsFn = fn
}
}
func WithListSubscriptionsV2Fn(fn func(context.Context, *operatorv1.ListSubscriptionsRequest) (*operatorv1.ListSubscriptionsResponse, error)) func(*options) {
return func(opts *options) {
opts.listSubscriptionsV2Fn = fn
}
}
func WithSubscriptionUpdateFn(fn func(*operatorv1.SubscriptionUpdateRequest, operatorv1.Operator_SubscriptionUpdateServer) error) func(*options) {
return func(opts *options) {
opts.subscriptionUpdateFn = fn
}
}
|
mikeee/dapr
|
tests/integration/framework/process/grpc/operator/options.go
|
GO
|
mit
| 4,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 implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package operator
import (
"context"
"google.golang.org/protobuf/types/known/emptypb"
operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1"
)
type server struct {
componentUpdateFn func(*operatorv1.ComponentUpdateRequest, operatorv1.Operator_ComponentUpdateServer) error
getConfigurationFn func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error)
getResiliencyFn func(context.Context, *operatorv1.GetResiliencyRequest) (*operatorv1.GetResiliencyResponse, error)
httpEndpointUpdateFn func(*operatorv1.HTTPEndpointUpdateRequest, operatorv1.Operator_HTTPEndpointUpdateServer) error
listComponentsFn func(context.Context, *operatorv1.ListComponentsRequest) (*operatorv1.ListComponentResponse, error)
listHTTPEndpointsFn func(context.Context, *operatorv1.ListHTTPEndpointsRequest) (*operatorv1.ListHTTPEndpointsResponse, error)
listResiliencyFn func(context.Context, *operatorv1.ListResiliencyRequest) (*operatorv1.ListResiliencyResponse, error)
listSubscriptionsFn func(context.Context, *emptypb.Empty) (*operatorv1.ListSubscriptionsResponse, error)
listSubscriptionsV2Fn func(context.Context, *operatorv1.ListSubscriptionsRequest) (*operatorv1.ListSubscriptionsResponse, error)
subscriptionUpdateFn func(*operatorv1.SubscriptionUpdateRequest, operatorv1.Operator_SubscriptionUpdateServer) error
}
func (s *server) ComponentUpdate(req *operatorv1.ComponentUpdateRequest, srv operatorv1.Operator_ComponentUpdateServer) error {
if s.componentUpdateFn != nil {
return s.componentUpdateFn(req, srv)
}
return nil
}
func (s *server) GetConfiguration(ctx context.Context, in *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error) {
if s.getConfigurationFn != nil {
return s.getConfigurationFn(ctx, in)
}
return new(operatorv1.GetConfigurationResponse), nil
}
func (s *server) GetResiliency(ctx context.Context, in *operatorv1.GetResiliencyRequest) (*operatorv1.GetResiliencyResponse, error) {
if s.getConfigurationFn != nil {
return s.getResiliencyFn(ctx, in)
}
return nil, nil
}
func (s *server) HTTPEndpointUpdate(in *operatorv1.HTTPEndpointUpdateRequest, srv operatorv1.Operator_HTTPEndpointUpdateServer) error {
if s.httpEndpointUpdateFn != nil {
return s.httpEndpointUpdateFn(in, srv)
}
return nil
}
func (s *server) ListComponents(ctx context.Context, in *operatorv1.ListComponentsRequest) (*operatorv1.ListComponentResponse, error) {
if s.listComponentsFn != nil {
return s.listComponentsFn(ctx, in)
}
return new(operatorv1.ListComponentResponse), nil
}
func (s *server) ListHTTPEndpoints(ctx context.Context, in *operatorv1.ListHTTPEndpointsRequest) (*operatorv1.ListHTTPEndpointsResponse, error) {
if s.listHTTPEndpointsFn != nil {
return s.listHTTPEndpointsFn(ctx, in)
}
return new(operatorv1.ListHTTPEndpointsResponse), nil
}
func (s *server) ListResiliency(ctx context.Context, in *operatorv1.ListResiliencyRequest) (*operatorv1.ListResiliencyResponse, error) {
if s.listResiliencyFn != nil {
return s.listResiliencyFn(ctx, in)
}
return new(operatorv1.ListResiliencyResponse), nil
}
func (s *server) ListSubscriptions(ctx context.Context, in *emptypb.Empty) (*operatorv1.ListSubscriptionsResponse, error) {
if s.listSubscriptionsFn != nil {
return s.listSubscriptionsFn(ctx, in)
}
return new(operatorv1.ListSubscriptionsResponse), nil
}
func (s *server) ListSubscriptionsV2(ctx context.Context, in *operatorv1.ListSubscriptionsRequest) (*operatorv1.ListSubscriptionsResponse, error) {
if s.listSubscriptionsV2Fn != nil {
return s.listSubscriptionsV2Fn(ctx, in)
}
return new(operatorv1.ListSubscriptionsResponse), nil
}
func (s *server) SubscriptionUpdate(req *operatorv1.SubscriptionUpdateRequest, srv operatorv1.Operator_SubscriptionUpdateServer) error {
if s.subscriptionUpdateFn != nil {
return s.subscriptionUpdateFn(req, srv)
}
return nil
}
|
mikeee/dapr
|
tests/integration/framework/process/grpc/operator/server.go
|
GO
|
mit
| 4,491 |
/*
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 grpc
import (
"context"
"net"
"testing"
"google.golang.org/grpc"
)
// options contains the options for running a GRPC server in integration tests.
type options struct {
registerFns []func(*grpc.Server)
serverOpts []func(*testing.T, context.Context) grpc.ServerOption
listener func() (net.Listener, error)
}
func WithRegister(f func(*grpc.Server)) Option {
return func(o *options) {
o.registerFns = append(o.registerFns, f)
}
}
func WithServerOption(opt func(t *testing.T, ctx context.Context) grpc.ServerOption) Option {
return func(o *options) {
o.serverOpts = append(o.serverOpts, opt)
}
}
func WithListener(l func() (net.Listener, error)) Option {
return func(o *options) {
o.listener = l
}
}
|
mikeee/dapr
|
tests/integration/framework/process/grpc/options.go
|
GO
|
mit
| 1,294 |
/*
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 sentry
import (
"context"
sentryv1pb "github.com/dapr/dapr/pkg/proto/sentry/v1"
)
type options struct {
signCertificateFn func(context.Context, *sentryv1pb.SignCertificateRequest) (*sentryv1pb.SignCertificateResponse, error)
}
func WithSignCertificateFn(fn func(context.Context, *sentryv1pb.SignCertificateRequest) (*sentryv1pb.SignCertificateResponse, error)) func(*options) {
return func(o *options) {
o.signCertificateFn = fn
}
}
|
mikeee/dapr
|
tests/integration/framework/process/grpc/sentry/options.go
|
GO
|
mit
| 1,013 |
/*
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 sentry
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"math/big"
"net/url"
"testing"
"time"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
sentryv1pb "github.com/dapr/dapr/pkg/proto/sentry/v1"
"github.com/dapr/dapr/pkg/sentry/server/ca"
procgrpc "github.com/dapr/dapr/tests/integration/framework/process/grpc"
)
type Option func(*options)
type Sentry struct {
grpc *procgrpc.GRPC
bundle ca.Bundle
}
func New(t *testing.T, fopts ...Option) *Sentry {
t.Helper()
rootKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
bundle, err := ca.GenerateBundle(rootKey, "integration.test.dapr.io", time.Second*20, nil)
require.NoError(t, err)
leafKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
leafCert := &x509.Certificate{
SerialNumber: big.NewInt(1),
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Second * 20),
URIs: []*url.URL{
spiffeid.RequireFromString("spiffe://localhost/ns/default/dapr-sentry").URL(),
},
}
leafCertDer, err := x509.CreateCertificate(rand.Reader, leafCert, bundle.IssChain[0], &leafKey.PublicKey, bundle.IssKey)
require.NoError(t, err)
tlsConfig := &tls.Config{
MinVersion: tls.VersionTLS13,
Certificates: []tls.Certificate{
{
Certificate: [][]byte{leafCertDer, bundle.IssChain[0].Raw},
PrivateKey: leafKey,
},
},
}
s := &Sentry{
bundle: bundle,
}
opts := options{
signCertificateFn: func(context.Context, *sentryv1pb.SignCertificateRequest) (*sentryv1pb.SignCertificateResponse, error) {
return nil, nil
},
}
for _, fopt := range fopts {
fopt(&opts)
}
s.grpc = procgrpc.New(t,
procgrpc.WithServerOption(func(t *testing.T, ctx context.Context) grpc.ServerOption {
return grpc.Creds(credentials.NewTLS(tlsConfig))
}),
procgrpc.WithRegister(
func(s *grpc.Server) {
srv := &server{
signCertificateFn: opts.signCertificateFn,
}
sentryv1pb.RegisterCAServer(s, srv)
},
))
return s
}
func (s *Sentry) Cleanup(t *testing.T) {
s.grpc.Cleanup(t)
}
func (s *Sentry) Run(t *testing.T, ctx context.Context) {
s.grpc.Run(t, ctx)
}
func (s *Sentry) Bundle() ca.Bundle {
return s.bundle
}
func (s *Sentry) Address(t *testing.T) string {
return s.grpc.Address(t)
}
|
mikeee/dapr
|
tests/integration/framework/process/grpc/sentry/sentry.go
|
GO
|
mit
| 2,996 |
/*
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 sentry
import (
"context"
sentryv1pb "github.com/dapr/dapr/pkg/proto/sentry/v1"
)
type server struct {
signCertificateFn func(context.Context, *sentryv1pb.SignCertificateRequest) (*sentryv1pb.SignCertificateResponse, error)
}
func (s *server) SignCertificate(ctx context.Context, req *sentryv1pb.SignCertificateRequest) (*sentryv1pb.SignCertificateResponse, error) {
return s.signCertificateFn(ctx, req)
}
|
mikeee/dapr
|
tests/integration/framework/process/grpc/sentry/server.go
|
GO
|
mit
| 983 |
/*
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 subscriber
import (
"context"
"google.golang.org/protobuf/types/known/emptypb"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
)
// options contains the options for running a pubsub subscriber gRPC server app.
type options struct {
listTopicSubFn func(ctx context.Context, in *emptypb.Empty) (*rtv1.ListTopicSubscriptionsResponse, error)
}
func WithListTopicSubscriptions(fn func(ctx context.Context, in *emptypb.Empty) (*rtv1.ListTopicSubscriptionsResponse, error)) func(*options) {
return func(opts *options) {
opts.listTopicSubFn = fn
}
}
|
mikeee/dapr
|
tests/integration/framework/process/grpc/subscriber/options.go
|
GO
|
mit
| 1,125 |
/*
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 subscriber
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/app"
)
type Option func(*options)
type Subscriber struct {
app *app.App
inCh chan *rtv1.TopicEventRequest
inBulkCh chan *rtv1.TopicEventBulkRequest
closeCh chan struct{}
}
func New(t *testing.T, fopts ...Option) *Subscriber {
t.Helper()
var opts options
for _, fopt := range fopts {
fopt(&opts)
}
inCh := make(chan *rtv1.TopicEventRequest, 100)
inBulkCh := make(chan *rtv1.TopicEventBulkRequest, 100)
closeCh := make(chan struct{})
return &Subscriber{
inCh: inCh,
inBulkCh: inBulkCh,
closeCh: closeCh,
app: app.New(t,
app.WithListTopicSubscriptions(opts.listTopicSubFn),
app.WithOnTopicEventFn(func(ctx context.Context, in *rtv1.TopicEventRequest) (*rtv1.TopicEventResponse, error) {
select {
case inCh <- in:
case <-ctx.Done():
case <-closeCh:
}
return new(rtv1.TopicEventResponse), nil
}),
app.WithOnBulkTopicEventFn(func(ctx context.Context, in *rtv1.TopicEventBulkRequest) (*rtv1.TopicEventBulkResponse, error) {
select {
case inBulkCh <- in:
case <-ctx.Done():
case <-closeCh:
}
stats := make([]*rtv1.TopicEventBulkResponseEntry, len(in.GetEntries()))
for i, e := range in.GetEntries() {
stats[i] = &rtv1.TopicEventBulkResponseEntry{
EntryId: e.GetEntryId(),
Status: rtv1.TopicEventResponse_SUCCESS,
}
}
return &rtv1.TopicEventBulkResponse{Statuses: stats}, nil
}),
),
}
}
func (s *Subscriber) Run(t *testing.T, ctx context.Context) {
t.Helper()
s.app.Run(t, ctx)
}
func (s *Subscriber) Cleanup(t *testing.T) {
t.Helper()
close(s.closeCh)
s.app.Cleanup(t)
}
func (s *Subscriber) Port(t *testing.T) int {
t.Helper()
return s.app.Port(t)
}
func (s *Subscriber) Receive(t *testing.T, ctx context.Context) *rtv1.TopicEventRequest {
t.Helper()
ctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
select {
case <-ctx.Done():
require.Fail(t, "timed out waiting for event response")
return nil
case in := <-s.inCh:
return in
}
}
func (s *Subscriber) ReceiveBulk(t *testing.T, ctx context.Context) *rtv1.TopicEventBulkRequest {
t.Helper()
ctx, cancel := context.WithTimeout(ctx, time.Second*3)
defer cancel()
select {
case <-ctx.Done():
require.Fail(t, "timed out waiting for event response")
return nil
case in := <-s.inBulkCh:
return in
}
}
func (s *Subscriber) AssertEventChanLen(t *testing.T, l int) {
t.Helper()
assert.Len(t, s.inCh, l)
}
func (s *Subscriber) AssertBulkEventChanLen(t *testing.T, l int) {
t.Helper()
assert.Len(t, s.inBulkCh, l)
}
func (s *Subscriber) ExpectPublishReceive(t *testing.T, ctx context.Context, daprd *daprd.Daprd, req *rtv1.PublishEventRequest) {
t.Helper()
_, err := daprd.GRPCClient(t, ctx).PublishEvent(ctx, req)
require.NoError(t, err)
s.Receive(t, ctx)
s.AssertEventChanLen(t, 0)
}
func (s *Subscriber) ExpectPublishError(t *testing.T, ctx context.Context, daprd *daprd.Daprd, req *rtv1.PublishEventRequest) {
t.Helper()
_, err := daprd.GRPCClient(t, ctx).PublishEvent(ctx, req)
require.Error(t, err)
}
func (s *Subscriber) ExpectPublishNoReceive(t *testing.T, ctx context.Context, daprd *daprd.Daprd, req *rtv1.PublishEventRequest) {
t.Helper()
_, err := daprd.GRPCClient(t, ctx).PublishEvent(ctx, req)
require.NoError(t, err)
s.AssertEventChanLen(t, 0)
}
|
mikeee/dapr
|
tests/integration/framework/process/grpc/subscriber/subscriber.go
|
GO
|
mit
| 4,196 |
/*
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 (
"context"
nethttp "net/http"
"sync/atomic"
"testing"
"github.com/dapr/dapr/tests/integration/framework/process/http"
)
type Option func(*options)
type App struct {
http *http.HTTP
healthz *atomic.Bool
}
func New(t *testing.T, fopts ...Option) *App {
t.Helper()
opts := options{
subscribe: "[]",
config: "{}",
initialHealth: true,
}
for _, fopt := range fopts {
fopt(&opts)
}
var healthz atomic.Bool
healthz.Store(opts.initialHealth)
httpopts := []http.Option{
http.WithHandlerFunc("/dapr/config", func(w nethttp.ResponseWriter, r *nethttp.Request) {
w.Write([]byte(opts.config))
}),
http.WithHandlerFunc("/dapr/subscribe", func(w nethttp.ResponseWriter, r *nethttp.Request) {
w.Write([]byte(opts.subscribe))
}),
http.WithHandlerFunc("/healthz", func(w nethttp.ResponseWriter, r *nethttp.Request) {
if healthz.Load() {
w.WriteHeader(nethttp.StatusOK)
} else {
w.WriteHeader(nethttp.StatusServiceUnavailable)
}
}),
}
httpopts = append(httpopts, opts.handlerFuncs...)
return &App{
http: http.New(t, httpopts...),
healthz: &healthz,
}
}
func (a *App) Run(t *testing.T, ctx context.Context) {
a.http.Run(t, ctx)
}
func (a *App) Cleanup(t *testing.T) {
a.http.Cleanup(t)
}
func (a *App) Port() int {
return a.http.Port()
}
|
mikeee/dapr
|
tests/integration/framework/process/http/app/app.go
|
GO
|
mit
| 1,897 |
/*
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 (
nethttp "net/http"
"github.com/dapr/dapr/tests/integration/framework/process/http"
)
type options struct {
subscribe string
config string
initialHealth bool
handlerFuncs []http.Option
}
func WithSubscribe(subscribe string) Option {
return func(o *options) {
o.subscribe = subscribe
}
}
func WithConfig(config string) Option {
return func(o *options) {
o.config = config
}
}
func WithHandlerFunc(path string, fn nethttp.HandlerFunc) Option {
return func(o *options) {
o.handlerFuncs = append(o.handlerFuncs, http.WithHandlerFunc(path, fn))
}
}
func WithInitialHealth(initialHealth bool) Option {
return func(o *options) {
o.initialHealth = initialHealth
}
}
|
mikeee/dapr
|
tests/integration/framework/process/http/app/options.go
|
GO
|
mit
| 1,280 |
/*
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 http
import (
"context"
"errors"
"net"
"net/http"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/integration/framework/process/ports"
)
// Option is a function that configures the process.
type Option func(*options)
// HTTP is a HTTP server that can be used in integration tests.
type HTTP struct {
listener net.Listener
server *http.Server
srvErrCh chan error
stopCh chan struct{}
}
func New(t *testing.T, fopts ...Option) *HTTP {
t.Helper()
var opts options
for _, fopt := range fopts {
fopt(&opts)
}
require.False(t, len(opts.handlerFuncs) > 0 && opts.handler != nil,
"handler and handlerFuncs are mutually exclusive, handlerFuncs: %d, handler: %v",
len(opts.handlerFuncs), opts.handler)
if opts.handler == nil {
handler := http.NewServeMux()
for path, fn := range opts.handlerFuncs {
handler.HandleFunc(path, fn)
}
opts.handler = handler
}
fp := ports.Reserve(t, 1)
return &HTTP{
listener: fp.Listener(t),
srvErrCh: make(chan error, 2),
stopCh: make(chan struct{}),
server: &http.Server{
ReadHeaderTimeout: time.Second,
Handler: opts.handler,
TLSConfig: opts.tlsConfig,
},
}
}
func (h *HTTP) Port() int {
return h.listener.Addr().(*net.TCPAddr).Port
}
func (h *HTTP) Run(t *testing.T, ctx context.Context) {
h.server.BaseContext = func(_ net.Listener) context.Context {
return ctx
}
go func() {
var err error
if h.server.TLSConfig != nil {
err = h.server.ServeTLS(h.listener, "", "")
} else {
err = h.server.Serve(h.listener)
}
if !errors.Is(err, http.ErrServerClosed) {
h.srvErrCh <- err
} else {
h.srvErrCh <- nil
}
}()
go func() {
<-h.stopCh
h.srvErrCh <- h.server.Shutdown(ctx)
}()
}
func (h *HTTP) Cleanup(t *testing.T) {
close(h.stopCh)
for i := 0; i < 2; i++ {
require.NoError(t, <-h.srvErrCh)
}
}
|
mikeee/dapr
|
tests/integration/framework/process/http/http.go
|
GO
|
mit
| 2,456 |
/*
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 http
import (
"crypto/tls"
"crypto/x509"
"net/http"
"testing"
"github.com/stretchr/testify/require"
)
// options contains the options for running a HTTP server in integration tests.
type options struct {
handler http.Handler
handlerFuncs map[string]http.HandlerFunc
tlsConfig *tls.Config
}
func WithHandler(handler http.Handler) Option {
return func(o *options) {
o.handler = handler
}
}
func WithHandlerFunc(path string, fn http.HandlerFunc) Option {
return func(o *options) {
if o.handlerFuncs == nil {
o.handlerFuncs = make(map[string]http.HandlerFunc)
}
o.handlerFuncs[path] = fn
}
}
func WithTLS(t *testing.T, cert, key []byte) Option {
return func(o *options) {
kp, err := tls.X509KeyPair(cert, key)
require.NoError(t, err)
tlsConfig := &tls.Config{
MinVersion: tls.VersionTLS12,
Certificates: []tls.Certificate{kp},
}
o.tlsConfig = tlsConfig
}
}
func WithMTLS(t *testing.T, ca, cert, key []byte) Option {
return func(o *options) {
caCertPool := x509.NewCertPool()
require.True(t, caCertPool.AppendCertsFromPEM(ca))
cert, err := tls.X509KeyPair(cert, key)
require.NoError(t, err)
tlsConfig := &tls.Config{
MinVersion: tls.VersionTLS12,
ClientCAs: caCertPool,
ClientAuth: tls.RequireAndVerifyClientCert,
Certificates: []tls.Certificate{cert},
}
o.tlsConfig = tlsConfig
}
}
|
mikeee/dapr
|
tests/integration/framework/process/http/options.go
|
GO
|
mit
| 1,945 |
/*
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 subscriber
type (
SubscriptionJSON struct {
PubsubName string `json:"pubsubname"`
Topic string `json:"topic"`
DeadLetterTopic string `json:"deadLetterTopic"`
Metadata map[string]string `json:"metadata,omitempty"`
Route string `json:"route"` // Single route from v1alpha1
Routes RoutesJSON `json:"routes"` // Multiple routes from v2alpha1
BulkSubscribe BulkSubscribeJSON `json:"bulkSubscribe,omitempty"`
}
RoutesJSON struct {
Rules []*RuleJSON `json:"rules,omitempty"`
Default string `json:"default,omitempty"`
}
BulkSubscribeJSON struct {
Enabled bool `json:"enabled"`
MaxMessagesCount int32 `json:"maxMessagesCount,omitempty"`
MaxAwaitDurationMs int32 `json:"maxAwaitDurationMs,omitempty"`
}
RuleJSON struct {
Match string `json:"match"`
Path string `json:"path"`
}
)
|
mikeee/dapr
|
tests/integration/framework/process/http/subscriber/json.go
|
GO
|
mit
| 1,495 |
/*
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 subscriber
import (
"net/http"
"github.com/dapr/dapr/tests/integration/framework/process/http/app"
)
type options struct {
routes []string
bulkRoutes []string
handlerFuncs []app.Option
progSubs *[]SubscriptionJSON
}
func WithRoutes(routes ...string) Option {
return func(o *options) {
o.routes = append(o.routes, routes...)
}
}
func WithBulkRoutes(routes ...string) Option {
return func(o *options) {
o.bulkRoutes = append(o.bulkRoutes, routes...)
}
}
func WithHandlerFunc(path string, fn http.HandlerFunc) Option {
return func(o *options) {
o.handlerFuncs = append(o.handlerFuncs, app.WithHandlerFunc(path, fn))
}
}
func WithProgrammaticSubscriptions(subs ...SubscriptionJSON) Option {
return func(o *options) {
if o.progSubs == nil {
o.progSubs = new([]SubscriptionJSON)
}
*o.progSubs = append(*o.progSubs, subs...)
}
}
|
mikeee/dapr
|
tests/integration/framework/process/http/subscriber/options.go
|
GO
|
mit
| 1,439 |
/*
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 subscriber
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"testing"
"time"
"github.com/cloudevents/sdk-go/v2/event"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/pkg/runtime/pubsub"
"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"
)
type Option func(*options)
type RouteEvent struct {
Route string
*event.Event
}
type PublishRequest struct {
Daprd *daprd.Daprd
PubSubName string
Topic string
Data string
DataContentType *string
}
type PublishBulkRequestEntry struct {
EntryID string `json:"entryId"`
Event string `json:"event"`
ContentType string `json:"contentType,omitempty"`
}
type PublishBulkRequest struct {
Daprd *daprd.Daprd
PubSubName string
Topic string
Entries []PublishBulkRequestEntry
}
type Subscriber struct {
app *app.App
client *http.Client
inCh chan *RouteEvent
inBulk chan *pubsub.BulkSubscribeEnvelope
closeCh chan struct{}
}
func New(t *testing.T, fopts ...Option) *Subscriber {
t.Helper()
var opts options
for _, fopt := range fopts {
fopt(&opts)
}
inCh := make(chan *RouteEvent, 100)
inBulk := make(chan *pubsub.BulkSubscribeEnvelope, 100)
closeCh := make(chan struct{})
appOpts := make([]app.Option, 0, len(opts.routes)+len(opts.bulkRoutes)+len(opts.handlerFuncs))
for _, route := range opts.routes {
appOpts = append(appOpts, app.WithHandlerFunc(route, func(w http.ResponseWriter, r *http.Request) {
var ce event.Event
require.NoError(t, json.NewDecoder(r.Body).Decode(&ce))
select {
case inCh <- &RouteEvent{Route: r.URL.Path, Event: &ce}:
case <-closeCh:
case <-r.Context().Done():
}
}))
}
for _, route := range opts.bulkRoutes {
appOpts = append(appOpts, app.WithHandlerFunc(route, func(w http.ResponseWriter, r *http.Request) {
var ce pubsub.BulkSubscribeEnvelope
require.NoError(t, json.NewDecoder(r.Body).Decode(&ce))
select {
case inBulk <- &ce:
case <-closeCh:
case <-r.Context().Done():
}
type statusT struct {
EntryID string `json:"entryId"`
Status string `json:"status"`
}
type respT struct {
Statuses []statusT `json:"statuses"`
}
var resp respT
for _, entry := range ce.Entries {
resp.Statuses = append(resp.Statuses, statusT{EntryID: entry.EntryId, Status: "SUCCESS"})
}
json.NewEncoder(w).Encode(resp)
}))
}
if opts.progSubs != nil {
appOpts = append(appOpts, app.WithHandlerFunc("/dapr/subscribe", func(w http.ResponseWriter, r *http.Request) {
require.NoError(t, json.NewEncoder(w).Encode(*opts.progSubs))
}))
}
appOpts = append(appOpts, opts.handlerFuncs...)
return &Subscriber{
app: app.New(t, appOpts...),
client: util.HTTPClient(t),
inCh: inCh,
inBulk: inBulk,
closeCh: closeCh,
}
}
func (s *Subscriber) Run(t *testing.T, ctx context.Context) {
t.Helper()
s.app.Run(t, ctx)
}
func (s *Subscriber) Cleanup(t *testing.T) {
t.Helper()
close(s.closeCh)
s.app.Cleanup(t)
}
func (s *Subscriber) Port() int {
return s.app.Port()
}
func (s *Subscriber) Receive(t *testing.T, ctx context.Context) *RouteEvent {
t.Helper()
ctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
select {
case <-ctx.Done():
require.Fail(t, "timed out waiting for event response")
return nil
case in := <-s.inCh:
return in
}
}
func (s *Subscriber) ReceiveBulk(t *testing.T, ctx context.Context) *pubsub.BulkSubscribeEnvelope {
t.Helper()
ctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
select {
case <-ctx.Done():
require.Fail(t, "timed out waiting for event response")
return nil
case in := <-s.inBulk:
return in
}
}
func (s *Subscriber) AssertEventChanLen(t *testing.T, l int) {
t.Helper()
assert.Len(t, s.inCh, l)
}
func (s *Subscriber) ExpectPublishReceive(t *testing.T, ctx context.Context, req PublishRequest) {
t.Helper()
s.Publish(t, ctx, req)
s.Receive(t, ctx)
s.AssertEventChanLen(t, 0)
}
func (s *Subscriber) ExpectPublishError(t *testing.T, ctx context.Context, req PublishRequest) {
t.Helper()
//nolint:bodyclose
resp := s.publish(t, ctx, req)
require.Equal(t, http.StatusNotFound, resp.StatusCode)
s.AssertEventChanLen(t, 0)
}
func (s *Subscriber) ExpectPublishNoReceive(t *testing.T, ctx context.Context, req PublishRequest) {
t.Helper()
s.Publish(t, ctx, req)
s.AssertEventChanLen(t, 0)
}
func (s *Subscriber) Publish(t *testing.T, ctx context.Context, req PublishRequest) {
t.Helper()
//nolint:bodyclose
resp := s.publish(t, ctx, req)
require.Equal(t, http.StatusNoContent, resp.StatusCode)
}
func (s *Subscriber) PublishBulk(t *testing.T, ctx context.Context, req PublishBulkRequest) {
t.Helper()
//nolint:bodyclose
resp := s.publishBulk(t, ctx, req)
require.Equal(t, http.StatusNoContent, resp.StatusCode)
}
func (s *Subscriber) publish(t *testing.T, ctx context.Context, req PublishRequest) *http.Response {
t.Helper()
reqURL := fmt.Sprintf("http://%s/v1.0/publish/%s/%s", req.Daprd.HTTPAddress(), req.PubSubName, req.Topic)
hreq, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, strings.NewReader(req.Data))
require.NoError(t, err)
if req.DataContentType != nil {
hreq.Header.Add("Content-Type", *req.DataContentType)
}
resp, err := s.client.Do(hreq)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
return resp
}
func (s *Subscriber) publishBulk(t *testing.T, ctx context.Context, req PublishBulkRequest) *http.Response {
t.Helper()
payload, err := json.Marshal(req.Entries)
require.NoError(t, err)
reqURL := fmt.Sprintf("http://%s/v1.0-alpha1/publish/bulk/%s/%s", req.Daprd.HTTPAddress(), req.PubSubName, req.Topic)
hreq, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, bytes.NewReader(payload))
require.NoError(t, err)
hreq.Header.Add("Content-Type", "application/json")
resp, err := s.client.Do(hreq)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
return resp
}
|
mikeee/dapr
|
tests/integration/framework/process/http/subscriber/subscriber.go
|
GO
|
mit
| 6,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 injector
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
"testing"
"time"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
"github.com/dapr/dapr/tests/integration/framework/binary"
"github.com/dapr/dapr/tests/integration/framework/process"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/kubernetes"
"github.com/dapr/dapr/tests/integration/framework/process/ports"
"github.com/dapr/dapr/tests/integration/framework/util"
)
type Injector struct {
kubeapi *kubernetes.Kubernetes
exec process.Interface
freeport *ports.Ports
port int
namespace string
metricsPort int
healthzPort int
}
func New(t *testing.T, fopts ...Option) *Injector {
t.Helper()
fp := ports.Reserve(t, 3)
opts := options{
logLevel: "info",
enableMetrics: true,
port: fp.Port(t),
metricsPort: fp.Port(t),
healthzPort: fp.Port(t),
sidecarImage: "integration.dapr.io/dapr",
}
for _, fopt := range fopts {
fopt(&opts)
}
require.NotNil(t, opts.sentry, "sentry is required")
require.NotNil(t, opts.namespace, "namespace is required")
mobj, err := json.Marshal(new(admissionregistrationv1.MutatingWebhookConfiguration))
require.NoError(t, err)
kubeapi := kubernetes.New(t, kubernetes.WithBaseOperatorAPI(t,
spiffeid.RequireTrustDomainFromString(opts.sentry.TrustDomain(t)),
*opts.namespace,
opts.sentry.Port(),
),
kubernetes.WithPath("/apis/admissionregistration.k8s.io/v1/mutatingwebhookconfigurations/dapr-sidecar-injector", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
w.Write(mobj)
}),
)
args := []string{
"-log-level=" + opts.logLevel,
"-port=" + strconv.Itoa(opts.port),
"-metrics-port=" + strconv.Itoa(opts.metricsPort),
"-metrics-listen-address=127.0.0.1",
"-healthz-port=" + strconv.Itoa(opts.healthzPort),
"-healthz-listen-address=127.0.0.1",
"-listen-address=127.0.0.1",
"-kubeconfig=" + kubeapi.KubeconfigPath(t),
}
return &Injector{
kubeapi: kubeapi,
exec: exec.New(t,
binary.EnvValue("injector"), args,
append(
opts.execOpts,
exec.WithEnvVars(t,
"KUBERNETES_SERVICE_HOST", "anything",
"NAMESPACE", *opts.namespace,
"SIDECAR_IMAGE", opts.sidecarImage,
"DAPR_TRUST_ANCHORS_FILE", opts.sentry.TrustAnchorsFile(t),
"DAPR_CONTROL_PLANE_TRUST_DOMAIN", opts.sentry.TrustDomain(t),
"DAPR_SENTRY_ADDRESS", opts.sentry.Address(),
),
)...,
),
freeport: fp,
port: opts.port,
metricsPort: opts.metricsPort,
healthzPort: opts.healthzPort,
namespace: *opts.namespace,
}
}
func (i *Injector) Run(t *testing.T, ctx context.Context) {
i.kubeapi.Run(t, ctx)
i.freeport.Free(t)
i.exec.Run(t, ctx)
}
func (i *Injector) Cleanup(t *testing.T) {
i.exec.Cleanup(t)
i.freeport.Cleanup(t)
i.kubeapi.Cleanup(t)
}
func (i *Injector) WaitUntilRunning(t *testing.T, ctx context.Context) {
client := util.HTTPClient(t)
//nolint:testifylint
assert.EventuallyWithT(t, func(t *assert.CollectT) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://localhost:%d/healthz", i.healthzPort), nil)
if !assert.NoError(t, err) {
return
}
resp, err := client.Do(req)
if !assert.NoError(t, err) {
return
}
assert.NoError(t, resp.Body.Close())
assert.Equal(t, http.StatusOK, resp.StatusCode)
}, time.Second*5, 10*time.Millisecond)
}
func (i *Injector) Port() int {
return i.port
}
func (i *Injector) Address() string {
return "localhost:" + strconv.Itoa(i.port)
}
func (i *Injector) MetricsPort() int {
return i.metricsPort
}
func (i *Injector) HealthzPort() int {
return i.healthzPort
}
|
mikeee/dapr
|
tests/integration/framework/process/injector/injector.go
|
GO
|
mit
| 4,437 |
/*
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 injector
import (
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
)
// options contains the options for running Injector in integration tests.
type options struct {
execOpts []exec.Option
logLevel string
namespace *string
port int
enableMetrics bool
metricsPort int
healthzPort int
sidecarImage string
sentry *sentry.Sentry
}
// Option is a function that configures the process.
type Option func(*options)
func WithExecOptions(execOptions ...exec.Option) Option {
return func(o *options) {
o.execOpts = execOptions
}
}
func WithLogLevel(level string) Option {
return func(o *options) {
o.logLevel = level
}
}
func WithNamespace(namespace string) Option {
return func(o *options) {
o.namespace = &namespace
}
}
func WithPort(port int) Option {
return func(o *options) {
o.port = port
}
}
func WithMetricsPort(port int) Option {
return func(o *options) {
o.metricsPort = port
}
}
func WithEnableMetrics(enable bool) Option {
return func(o *options) {
o.enableMetrics = enable
}
}
func WithHealthzPort(port int) Option {
return func(o *options) {
o.healthzPort = port
}
}
func WithSidecarImage(image string) Option {
return func(o *options) {
o.sidecarImage = image
}
}
func WithSentry(sentry *sentry.Sentry) Option {
return func(o *options) {
o.sentry = sentry
}
}
|
mikeee/dapr
|
tests/integration/framework/process/injector/options.go
|
GO
|
mit
| 1,998 |
/*
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 informer
import (
"encoding/json"
"net/http"
"strings"
"sync"
"testing"
"github.com/stretchr/testify/require"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/watch"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
configapi "github.com/dapr/dapr/pkg/apis/configuration/v1alpha1"
httpendapi "github.com/dapr/dapr/pkg/apis/httpEndpoint/v1alpha1"
resiliencyapi "github.com/dapr/dapr/pkg/apis/resiliency/v1alpha1"
subapi "github.com/dapr/dapr/pkg/apis/subscriptions/v2alpha1"
)
// Informer is a fake informer that adds events to the Kubernetes API server to
// send events to clients.
type Informer struct {
lock sync.Mutex
active map[string][][]byte
}
func New() *Informer {
return &Informer{
active: make(map[string][][]byte),
}
}
func (i *Informer) Handler(t *testing.T, wrapped http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !r.URL.Query().Has("watch") || r.URL.Query().Get("watch") != "true" {
wrapped.ServeHTTP(w, r)
return
}
i.lock.Lock()
path := strings.TrimPrefix(strings.TrimPrefix(r.URL.Path, "/apis/"), "/api/")
var gvk schema.GroupVersionKind
split := strings.Split(path, "/")
require.GreaterOrEqual(t, len(split), 2, "invalid path: %s", path)
if split[0] == "v1" {
gvk = schema.GroupVersionKind{Group: "", Version: "v1"}
split = split[1:]
} else {
gvk = schema.GroupVersionKind{Group: strings.Split(path, "/")[0], Version: strings.Split(path, "/")[1]}
split = split[2:]
}
if split[0] == "namespaces" {
split = split[2:]
}
gvk.Kind = split[0]
w.Header().Add("Transfer-Encoding", "chunked")
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if len(i.active[gvk.String()]) > 0 {
w.Write(i.active[gvk.String()][0])
i.active[gvk.String()] = i.active[gvk.String()][1:]
}
w.(http.Flusher).Flush()
i.lock.Unlock()
}
}
func (i *Informer) Add(t *testing.T, obj runtime.Object) {
t.Helper()
i.inform(t, obj, string(watch.Added))
}
func (i *Informer) Modify(t *testing.T, obj runtime.Object) {
t.Helper()
i.inform(t, obj, string(watch.Modified))
}
func (i *Informer) Delete(t *testing.T, obj runtime.Object) {
t.Helper()
i.inform(t, obj, string(watch.Deleted))
}
func (i *Informer) inform(t *testing.T, obj runtime.Object, event string) {
t.Helper()
i.lock.Lock()
defer i.lock.Unlock()
gvk := i.objToGVK(t, obj)
watchObjB, err := json.Marshal(obj)
require.NoError(t, err)
watchEvent, err := json.Marshal(&metav1.WatchEvent{
Type: event,
Object: runtime.RawExtension{Raw: watchObjB, Object: obj},
})
require.NoError(t, err)
i.active[gvk.String()] = append(i.active[gvk.String()], watchEvent)
}
func (i *Informer) objToGVK(t *testing.T, obj runtime.Object) schema.GroupVersionKind {
t.Helper()
switch obj.(type) {
case *appsv1.Deployment:
return schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "deployments"}
case *compapi.Component:
return schema.GroupVersionKind{Group: "dapr.io", Version: "v1alpha1", Kind: "components"}
case *configapi.Configuration:
return schema.GroupVersionKind{Group: "dapr.io", Version: "v1alpha1", Kind: "configurations"}
case *httpendapi.HTTPEndpoint:
return schema.GroupVersionKind{Group: "dapr.io", Version: "v1alpha1", Kind: "httpendpoints"}
case *resiliencyapi.Resiliency:
return schema.GroupVersionKind{Group: "dapr.io", Version: "v1alpha1", Kind: "resiliencies"}
case *subapi.Subscription:
return schema.GroupVersionKind{Group: "dapr.io", Version: "v2alpha1", Kind: "subscriptions"}
case *corev1.Pod:
return schema.GroupVersionKind{Group: "", Version: "v1", Kind: "pods"}
case *corev1.Service:
return schema.GroupVersionKind{Group: "", Version: "v1", Kind: "services"}
case *corev1.Secret:
return schema.GroupVersionKind{Group: "", Version: "v1", Kind: "secrets"}
case *corev1.ConfigMap:
return schema.GroupVersionKind{Group: "", Version: "v1", Kind: "configmaps"}
default:
require.Fail(t, "unknown type: %T", obj)
return schema.GroupVersionKind{}
}
}
|
mikeee/dapr
|
tests/integration/framework/process/kubernetes/informer/informer.go
|
GO
|
mit
| 4,774 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubernetes
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/json"
"fmt"
"math/big"
"net/http"
"os"
"path/filepath"
"runtime"
"testing"
"time"
"github.com/stretchr/testify/require"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"sigs.k8s.io/yaml"
"github.com/dapr/dapr/pkg/sentry/server/ca"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/kubernetes/informer"
cryptopem "github.com/dapr/kit/crypto/pem"
)
const (
EnvVarCRDDirectory = "DAPR_INTEGRATION_CRD_DIRECTORY"
)
// Option is a function that configures the mock Kubernetes process.
type Option func(*options)
// Kubernetes is a mock Kubernetes API server process.
type Kubernetes struct {
http *prochttp.HTTP
bundle ca.Bundle
informer *informer.Informer
}
func New(t *testing.T, fopts ...Option) *Kubernetes {
t.Helper()
opts := options{
handlers: make(map[string]http.HandlerFunc),
}
for _, fopt := range fopts {
fopt(&opts)
}
handler := http.NewServeMux()
handler.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json;g=apidiscovery.k8s.io;v=v2beta1;as=APIGroupDiscoveryList")
w.Write([]byte(apiDiscovery))
})
handler.HandleFunc("/apis", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json;g=apidiscovery.k8s.io;v=v2beta1;as=APIGroupDiscoveryList")
w.Write([]byte(apisDiscovery))
})
handler.HandleFunc("/apis/dapr.io/v1alpha1", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(apisDaprV1alpha1))
})
handler.HandleFunc("/apis/dapr.io/v2alpha1", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(apisDaprV2alpha1))
})
handler.HandleFunc("/apis/apps/v1", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(apisAppsV1))
})
handler.HandleFunc("/api/v1", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(apiV1))
})
for crdName, crd := range parseCRDs(t) {
handler.HandleFunc("/apis/apiextensions.k8s.io/v1/customresourcedefinitions/"+crdName, func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
w.Write(crd)
})
}
informer := informer.New()
for path, handle := range opts.handlers {
handler.HandleFunc(path, informer.Handler(t, handle))
}
handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
})
// We need to run the Kubernetes API server with TLS so that HTTP/2.0 is
// enabled, which is required for informers.
pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
bundle, err := ca.GenerateBundle(pk, "kubernetes.integration.dapr.io", time.Second*5, nil)
require.NoError(t, err)
leafpk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
leafCert := &x509.Certificate{
SerialNumber: big.NewInt(1),
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Minute * 5),
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
DNSNames: []string{"cluster.local"},
SignatureAlgorithm: x509.ECDSAWithSHA256,
}
leafCertDER, err := x509.CreateCertificate(rand.Reader, leafCert, bundle.IssChain[0], leafpk.Public(), bundle.IssKey)
require.NoError(t, err)
leafCert, err = x509.ParseCertificate(leafCertDER)
require.NoError(t, err)
chainPEM, err := cryptopem.EncodeX509Chain(append([]*x509.Certificate{leafCert}, bundle.IssChain...))
require.NoError(t, err)
keyPEM, err := cryptopem.EncodePrivateKey(leafpk)
require.NoError(t, err)
return &Kubernetes{
http: prochttp.New(t,
prochttp.WithHandler(handler),
prochttp.WithMTLS(t, bundle.TrustAnchors, chainPEM, keyPEM),
),
bundle: bundle,
informer: informer,
}
}
func (k *Kubernetes) Port() int {
return k.http.Port()
}
func (k *Kubernetes) Run(t *testing.T, ctx context.Context) {
t.Helper()
k.http.Run(t, ctx)
}
func (k *Kubernetes) KubeconfigPath(t *testing.T) string {
t.Helper()
caPath := filepath.Join(t.TempDir(), "ca.crt")
certPath := filepath.Join(t.TempDir(), "tls.crt")
keyPath := filepath.Join(t.TempDir(), "tls.key")
require.NoError(t, os.WriteFile(caPath, k.bundle.TrustAnchors, 0o600))
require.NoError(t, os.WriteFile(certPath, k.bundle.IssChainPEM, 0o600))
require.NoError(t, os.WriteFile(keyPath, k.bundle.IssKeyPEM, 0o600))
path := filepath.Join(t.TempDir(), "kubeconfig")
kubeconfig := fmt.Sprintf(`
apiVersion: v1
kind: Config
clusters:
- name: default
cluster:
server: https://localhost:%[1]d
certificate-authority: %[2]s
# This is because the sentry CA generative code still marks all issuer
# certs as 'cluster.local'.
tls-server-name: cluster.local
contexts:
- name: default
context:
cluster: default
user: default
users:
- name: default
user:
client-certificate: %[3]s
client-key: %[4]s
current-context: default
`, k.Port(), caPath, certPath, keyPath)
require.NoError(t, os.WriteFile(path, []byte(kubeconfig), 0o600))
return path
}
func (k *Kubernetes) Informer() *informer.Informer {
return k.informer
}
func (k *Kubernetes) Cleanup(t *testing.T) {
t.Helper()
k.http.Cleanup(t)
}
func parseCRDs(t *testing.T) map[string][]byte {
t.Helper()
_, tfile, _, ok := runtime.Caller(0)
require.True(t, ok)
defaultPath := filepath.Join(filepath.Dir(tfile), "../../../../../charts/dapr/crds")
dir, ok := os.LookupEnv(EnvVarCRDDirectory)
if !ok {
t.Logf("environment variable %s not set, using default CRD location %s", EnvVarCRDDirectory, defaultPath)
dir = defaultPath
}
crds := make(map[string][]byte)
filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() || filepath.Ext(path) != ".yaml" {
return nil
}
f, err := os.ReadFile(path)
if err != nil {
return err
}
var crd apiextensionsv1.CustomResourceDefinition
if err = yaml.Unmarshal(f, &crd); err != nil {
return err
}
// Set conversion webhook client config to non-nil to allow operator to
// patch subscriptions.
crd.Spec.Conversion = new(apiextensionsv1.CustomResourceConversion)
crd.Spec.Conversion.Webhook = new(apiextensionsv1.WebhookConversion)
crd.Spec.Conversion.Webhook.ClientConfig = new(apiextensionsv1.WebhookClientConfig)
fjson, err := json.Marshal(crd)
if err != nil {
return err
}
crds[crd.Name] = fjson
return nil
})
return crds
}
|
mikeee/dapr
|
tests/integration/framework/process/kubernetes/kubernetes.go
|
GO
|
mit
| 7,235 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubernetes
import (
"encoding/json"
"net/http"
"path"
"strconv"
"testing"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/stretchr/testify/require"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
configapi "github.com/dapr/dapr/pkg/apis/configuration/v1alpha1"
httpendapi "github.com/dapr/dapr/pkg/apis/httpEndpoint/v1alpha1"
resapi "github.com/dapr/dapr/pkg/apis/resiliency/v1alpha1"
subv1api "github.com/dapr/dapr/pkg/apis/subscriptions/v1alpha1"
subv2api "github.com/dapr/dapr/pkg/apis/subscriptions/v2alpha1"
"github.com/dapr/dapr/tests/integration/framework/process/kubernetes/store"
)
// options contains the options for running a mock Kubernetes API server.
type options struct {
handlers map[string]http.HandlerFunc
}
func WithPath(path string, handler http.HandlerFunc) Option {
return func(o *options) {
o.handlers[path] = handler
}
}
func WithClusterDaprConfigurationList(t *testing.T, configs *configapi.ConfigurationList) Option {
return handleClusterListResource(t, "/apis/dapr.io/v1alpha1/configurations", configs)
}
func WithClusterDaprResiliencyList(t *testing.T, res *resapi.ResiliencyList) Option {
return handleClusterListResource(t, "/apis/dapr.io/v1alpha1/resiliencies", res)
}
func WithClusterDaprSubscriptionList(t *testing.T, subs *subv1api.SubscriptionList) Option {
subv2List := new(subv2api.SubscriptionList)
for _, s := range subs.Items {
subv2 := new(subv2api.Subscription)
require.NoError(t, subv2.ConvertFrom(s.DeepCopy()))
subv2List.Items = append(subv2List.Items, *subv2)
}
return handleClusterListResource(t, "/apis/dapr.io/v2alpha1/subscriptions", subv2List)
}
func WithClusterDaprSubscriptionListV2(t *testing.T, subs *subv2api.SubscriptionList) Option {
return handleClusterListResource(t, "/apis/dapr.io/v2alpha1/subscriptions", subs)
}
func WithClusterDaprComponentList(t *testing.T, comps *compapi.ComponentList) Option {
return handleClusterListResource(t, "/apis/dapr.io/v1alpha1/components", comps)
}
func WithClusterDaprComponentListFromStore(t *testing.T, store *store.Store) Option {
return handleClusterListResourceFromStore(t, "/apis/dapr.io/v1alpha1/components", store)
}
func WithClusterDaprSubscriptionListFromStore(t *testing.T, store *store.Store) Option {
return handleClusterListResourceFromStore(t, "/apis/dapr.io/v2alpha1/subscriptions", store)
}
func WithClusterDaprSubscriptionV2ListFromStore(t *testing.T, store *store.Store) Option {
return handleClusterListResourceFromStore(t, "/apis/dapr.io/v2alpha1/subscriptions", store)
}
func WithClusterDaprHTTPEndpointList(t *testing.T, endpoints *httpendapi.HTTPEndpointList) Option {
return handleClusterListResource(t, "/apis/dapr.io/v1alpha1/httpendpoints", endpoints)
}
func WithClusterPodList(t *testing.T, pods *corev1.PodList) Option {
return handleClusterListResource(t, "/api/v1/pods", pods)
}
func WithClusterServiceList(t *testing.T, services *corev1.ServiceList) Option {
return handleClusterListResource(t, "/api/v1/services", services)
}
func WithClusterDeploymentList(t *testing.T, deploys *appsv1.DeploymentList) Option {
return handleClusterListResource(t, "/apis/apps/v1/deployments", deploys)
}
func WithClusterStatefulSetList(t *testing.T, ss *appsv1.StatefulSetList) Option {
return handleClusterListResource(t, "/apis/apps/v1/statefulsets", ss)
}
func WithClusterServiceAccountList(t *testing.T, services *corev1.ServiceAccountList) Option {
return handleClusterListResource(t, "/api/v1/serviceaccounts", services)
}
func WithDaprConfigurationGet(t *testing.T, config *configapi.Configuration) Option {
return handleGetResource(t, "/apis/dapr.io/v1alpha1", "configurations", config.Namespace, config.Name, config)
}
func WithSecretGet(t *testing.T, secret *corev1.Secret) Option {
return handleGetResource(t, "/api/v1", "secrets", secret.Namespace, secret.Name, secret)
}
func WithDaprResiliencyGet(t *testing.T, ns, name string, res *resapi.Resiliency) Option {
return handleGetResource(t, "/apis/dapr.io/v1alpha1", "resiliencies", ns, name, res)
}
func WithConfigMapGet(t *testing.T, configmap *corev1.ConfigMap) Option {
return handleGetResource(t, "/api/v1", "configmaps", configmap.Namespace, configmap.Name, configmap)
}
func WithBaseOperatorAPI(t *testing.T, td spiffeid.TrustDomain, ns string, sentryPort int) Option {
return func(o *options) {
for _, op := range []Option{
WithDaprConfigurationGet(t, &configapi.Configuration{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Configuration"},
ObjectMeta: metav1.ObjectMeta{Name: "daprsystem", Namespace: ns},
Spec: configapi.ConfigurationSpec{
MTLSSpec: &configapi.MTLSSpec{
ControlPlaneTrustDomain: td.String(),
SentryAddress: "localhost:" + strconv.Itoa(sentryPort),
},
},
}),
WithClusterServiceList(t, &corev1.ServiceList{TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "ServiceList"}}),
WithClusterStatefulSetList(t, &appsv1.StatefulSetList{TypeMeta: metav1.TypeMeta{APIVersion: "apps/v1", Kind: "StatefulSetList"}}),
WithClusterDeploymentList(t, &appsv1.DeploymentList{TypeMeta: metav1.TypeMeta{APIVersion: "apps/v1", Kind: "DeploymentList"}}),
WithClusterServiceAccountList(t, &corev1.ServiceAccountList{TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "ServiceAccountList"}}),
WithClusterDaprComponentList(t, &compapi.ComponentList{TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "ComponentList"}}),
WithClusterDaprSubscriptionListV2(t, &subv2api.SubscriptionList{TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v2alpha1", Kind: "SubscriptionList"}}),
WithClusterDaprHTTPEndpointList(t, &httpendapi.HTTPEndpointList{TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "HTTPEndpointList"}}),
WithClusterDaprResiliencyList(t, &resapi.ResiliencyList{TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "ResiliencyList"}}),
} {
op(o)
}
}
}
func handleClusterListResource(t *testing.T, path string, obj runtime.Object) Option {
return func(o *options) {
o.handlers[path] = handleObj(t, obj)
}
}
func handleClusterListResourceFromStore(t *testing.T, path string, store *store.Store) Option {
return func(o *options) {
o.handlers[path] = handleObjFromStore(t, store)
}
}
func handleGetResource(t *testing.T, apigv, resource, ns, name string, obj runtime.Object) Option {
return func(o *options) {
o.handlers[path.Join(apigv, "namespaces", ns, resource, name)] = handleObj(t, obj)
}
}
// func handleObj(t *testing.T, gvk metav1.GroupVersionKind, obj runtime.Object) http.HandlerFunc {
func handleObj(t *testing.T, obj runtime.Object) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
objB, err := json.Marshal(obj)
require.NoError(t, err)
w.Header().Add("Content-Length", strconv.Itoa(len(objB)))
w.Header().Add("Content-Type", "application/json")
w.Write(objB)
}
}
func handleObjFromStore(t *testing.T, store *store.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
objB, err := json.Marshal(store.Objects())
require.NoError(t, err)
w.Header().Add("Content-Length", strconv.Itoa(len(objB)))
w.Header().Add("Content-Type", "application/json")
w.Write(objB)
}
}
|
mikeee/dapr
|
tests/integration/framework/process/kubernetes/options.go
|
GO
|
mit
| 7,986 |
/*
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 store
import (
"sync"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// Store is a fake Kubernetes store for a resource type.
type Store struct {
lock sync.RWMutex
objs map[string]client.Object
gvk metav1.GroupVersionKind
}
func New(gvk metav1.GroupVersionKind) *Store {
return &Store{
gvk: gvk,
objs: make(map[string]client.Object),
}
}
func (s *Store) Add(objs ...client.Object) {
s.lock.Lock()
defer s.lock.Unlock()
if s.objs == nil {
s.objs = make(map[string]client.Object)
}
for _, obj := range objs {
s.objs[obj.GetNamespace()+"/"+obj.GetName()] = obj
}
}
func (s *Store) Set(objs ...client.Object) {
s.lock.Lock()
defer s.lock.Unlock()
s.objs = make(map[string]client.Object)
for _, obj := range objs {
s.objs[obj.GetNamespace()+"/"+obj.GetName()] = obj
}
}
func (s *Store) Objects() map[string]any {
s.lock.RLock()
defer s.lock.RUnlock()
objs := make([]client.Object, 0, len(s.objs))
for _, obj := range s.objs {
objs = append(objs, obj)
}
if len(objs) == 0 {
objs = nil
}
return map[string]any{
"apiVersion": s.gvk.Group + "/" + s.gvk.Version,
"kind": s.gvk.Kind + "List",
"items": objs,
}
}
|
mikeee/dapr
|
tests/integration/framework/process/kubernetes/store/store.go
|
GO
|
mit
| 1,785 |
/*
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 logline
import (
"bufio"
"context"
"errors"
"io"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/integration/framework/iowriter"
)
// Option is a function that configures the process.
type Option func(*options)
// LogLine is a HTTP server that can be used in integration tests.
type LogLine struct {
stdout io.Reader
stdoutExp io.WriteCloser
stdoutLineContains map[string]bool
stderr io.Reader
stderrExp io.WriteCloser
stderrLinContains map[string]bool
outCheck chan map[string]bool
closeCh chan struct{}
done atomic.Int32
}
func New(t *testing.T, fopts ...Option) *LogLine {
t.Helper()
opts := options{}
for _, fopt := range fopts {
fopt(&opts)
}
stdoutLineContains := make(map[string]bool)
for _, stdout := range opts.stdoutContains {
stdoutLineContains[stdout] = false
}
stderrLineContains := make(map[string]bool)
for _, stderr := range opts.stderrContains {
stderrLineContains[stderr] = false
}
stdoutReader, stdoutWriter := io.Pipe()
stderrReader, stderrWriter := io.Pipe()
return &LogLine{
stdout: io.TeeReader(stdoutReader, iowriter.New(t, "logline:stdout")),
stdoutExp: stdoutWriter,
stdoutLineContains: stdoutLineContains,
stderr: io.TeeReader(stderrReader, iowriter.New(t, "logline:stderr")),
stderrExp: stderrWriter,
stderrLinContains: stderrLineContains,
outCheck: make(chan map[string]bool),
closeCh: make(chan struct{}),
}
}
func (l *LogLine) Run(t *testing.T, ctx context.Context) {
go func() {
res := l.checkOut(t, ctx, l.stdoutLineContains, l.stdoutExp, l.stdout)
l.outCheck <- res
}()
go func() {
res := l.checkOut(t, ctx, l.stderrLinContains, l.stderrExp, l.stderr)
l.outCheck <- res
}()
}
func (l *LogLine) FoundAll() bool {
return l.done.Load() == 2
}
func (l *LogLine) Cleanup(t *testing.T) {
close(l.closeCh)
for i := 0; i < 2; i++ {
for expLine := range <-l.outCheck {
assert.Fail(t, "expected to log line", expLine)
}
}
}
func (l *LogLine) checkOut(t *testing.T, ctx context.Context, expLines map[string]bool, closer io.WriteCloser, reader io.Reader) map[string]bool {
t.Helper()
if len(expLines) == 0 {
l.done.Add(1)
return expLines
}
go func() {
select {
case <-ctx.Done():
closer.Close()
case <-l.closeCh:
}
}()
var once sync.Once
breader := bufio.NewReader(reader)
for {
if len(expLines) == 0 {
once.Do(func() { l.done.Add(1) })
}
line, _, err := breader.ReadLine()
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrClosedPipe) {
break
}
require.NoError(t, err)
for expLine := range expLines {
if strings.Contains(string(line), expLine) {
delete(expLines, expLine)
}
}
}
return expLines
}
func (l *LogLine) Stdout() io.WriteCloser {
return l.stdoutExp
}
func (l *LogLine) Stderr() io.WriteCloser {
return l.stderrExp
}
func (l *LogLine) EventuallyFoundAll(t *testing.T) {
assert.Eventually(t, l.FoundAll, time.Second*7, time.Millisecond*10)
}
|
mikeee/dapr
|
tests/integration/framework/process/logline/logline.go
|
GO
|
mit
| 3,722 |
/*
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 logline
// options contains the options for checking the log lines of a process.
type options struct {
stdoutContains []string
stderrContains []string
}
func WithStdoutLineContains(lines ...string) func(*options) {
return func(o *options) {
o.stdoutContains = append(o.stdoutContains, lines...)
}
}
func WithStderrLineContains(lines ...string) func(*options) {
return func(o *options) {
o.stderrContains = append(o.stderrContains, lines...)
}
}
|
mikeee/dapr
|
tests/integration/framework/process/logline/options.go
|
GO
|
mit
| 1,027 |
/*
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 once
import (
"context"
"sync/atomic"
"testing"
"github.com/dapr/dapr/tests/integration/framework/process"
)
// once ensures that a process is only run and cleaned up once.
type once struct {
process.Interface
runOnce atomic.Bool
cleanOnce atomic.Bool
failRun func(t *testing.T)
failCleanup func(t *testing.T)
}
func Wrap(proc process.Interface) process.Interface {
return &once{
Interface: proc,
failRun: func(t *testing.T) {
t.Fatal("process has already been run")
},
failCleanup: func(t *testing.T) {
t.Fatal("process has already been cleaned up")
},
}
}
func (o *once) Run(t *testing.T, ctx context.Context) {
if !o.runOnce.CompareAndSwap(false, true) {
o.failRun(t)
return
}
o.Interface.Run(t, ctx)
}
func (o *once) Cleanup(t *testing.T) {
if !o.cleanOnce.CompareAndSwap(false, true) {
o.failCleanup(t)
return
}
o.Interface.Cleanup(t)
}
|
mikeee/dapr
|
tests/integration/framework/process/once/once.go
|
GO
|
mit
| 1,467 |
/*
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 once
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
)
type mockProcess struct {
runCalled int
cleanupCalled int
}
func (mp *mockProcess) Run(t *testing.T, ctx context.Context) {
mp.runCalled++
}
func (mp *mockProcess) Cleanup(t *testing.T) {
mp.cleanupCalled++
}
func (mp *mockProcess) Dispose() error {
return nil
}
func TestOnce(t *testing.T) {
mockProc := &mockProcess{}
onceProc := Wrap(mockProc)
runFailedCalled := false
cleanupFailedCalled := false
onceProc.(*once).failRun = func(*testing.T) {
runFailedCalled = true
}
onceProc.(*once).failCleanup = func(*testing.T) {
cleanupFailedCalled = true
}
t.Run("Run", func(t *testing.T) {
ctx := context.Background()
// First call should succeed
onceProc.Run(t, ctx)
assert.Equal(t, 1, mockProc.runCalled)
assert.False(t, runFailedCalled)
// Second call should fail
onceProc.Run(t, ctx)
assert.True(t, runFailedCalled)
})
t.Run("Cleanup", func(t *testing.T) {
// First call should succeed
onceProc.Cleanup(t)
assert.Equal(t, 1, mockProc.cleanupCalled)
assert.False(t, cleanupFailedCalled)
// Second call should fail
onceProc.Cleanup(t)
assert.True(t, cleanupFailedCalled)
})
}
|
mikeee/dapr
|
tests/integration/framework/process/once/once_test.go
|
GO
|
mit
| 1,786 |
/*
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 operator
import (
"context"
"fmt"
"net/http"
"strconv"
"testing"
"time"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"github.com/dapr/dapr/pkg/modes"
operatorv1pb "github.com/dapr/dapr/pkg/proto/operator/v1"
"github.com/dapr/dapr/pkg/security"
"github.com/dapr/dapr/tests/integration/framework/binary"
"github.com/dapr/dapr/tests/integration/framework/process"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/ports"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/kit/ptr"
)
type Operator struct {
exec process.Interface
ports *ports.Ports
port int
metricsPort int
healthzPort int
namespace string
}
func New(t *testing.T, fopts ...Option) *Operator {
t.Helper()
fp := ports.Reserve(t, 4)
opts := options{
logLevel: "info",
disableLeaderElection: true,
port: fp.Port(t),
metricsPort: fp.Port(t),
healthzPort: fp.Port(t),
}
for _, fopt := range fopts {
fopt(&opts)
}
require.NotNil(t, opts.trustAnchorsFile, "trustAnchorsFile is required")
require.NotNil(t, opts.kubeconfigPath, "kubeconfigPath is required")
require.NotNil(t, opts.namespace, "namespace is required")
args := []string{
"-log-level=" + opts.logLevel,
"-port=" + strconv.Itoa(opts.port),
"-listen-address=127.0.0.1",
"-healthz-port=" + strconv.Itoa(opts.healthzPort),
"-healthz-listen-address=127.0.0.1",
"-metrics-port=" + strconv.Itoa(opts.metricsPort),
"-metrics-listen-address=127.0.0.1",
"-trust-anchors-file=" + *opts.trustAnchorsFile,
"-disable-leader-election=" + strconv.FormatBool(opts.disableLeaderElection),
"-kubeconfig=" + *opts.kubeconfigPath,
"-webhook-server-port=" + strconv.Itoa(fp.Port(t)),
"-webhook-server-listen-address=127.0.0.1",
}
if opts.configPath != nil {
args = append(args, "-config-path="+*opts.configPath)
}
return &Operator{
exec: exec.New(t,
binary.EnvValue("operator"), args,
append(
opts.execOpts,
exec.WithEnvVars(t,
"KUBERNETES_SERVICE_HOST", "anything",
"NAMESPACE", *opts.namespace,
),
)...,
),
ports: fp,
port: opts.port,
metricsPort: opts.metricsPort,
healthzPort: opts.healthzPort,
namespace: *opts.namespace,
}
}
func (o *Operator) Run(t *testing.T, ctx context.Context) {
o.ports.Free(t)
o.exec.Run(t, ctx)
}
func (o *Operator) Cleanup(t *testing.T) {
o.exec.Cleanup(t)
}
func (o *Operator) WaitUntilRunning(t *testing.T, ctx context.Context) {
client := util.HTTPClient(t)
assert.Eventually(t, func() bool {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://localhost:%d/healthz", o.healthzPort), nil)
if err != nil {
return false
}
resp, err := client.Do(req)
if err != nil {
return false
}
defer resp.Body.Close()
return http.StatusOK == resp.StatusCode
}, time.Second*10, 10*time.Millisecond)
}
func (o *Operator) Port() int {
return o.port
}
func (o *Operator) Address() string {
return "localhost:" + strconv.Itoa(o.port)
}
func (o *Operator) MetricsPort() int {
return o.metricsPort
}
func (o *Operator) HealthzPort() int {
return o.healthzPort
}
func (o *Operator) Dial(t *testing.T, ctx context.Context, sentry *sentry.Sentry, appID string) operatorv1pb.OperatorClient {
sec, err := security.New(ctx, security.Options{
SentryAddress: "localhost:" + strconv.Itoa(sentry.Port()),
ControlPlaneTrustDomain: "integration.test.dapr.io",
ControlPlaneNamespace: o.namespace,
TrustAnchorsFile: ptr.Of(sentry.TrustAnchorsFile(t)),
AppID: appID,
Mode: modes.StandaloneMode,
MTLSEnabled: true,
})
require.NoError(t, err)
errCh := make(chan error)
ctx, cancel := context.WithCancel(ctx)
go func() {
errCh <- sec.Run(ctx)
}()
t.Cleanup(func() {
cancel()
require.NoError(t, <-errCh)
})
sech, err := sec.Handler(ctx)
require.NoError(t, err)
id, err := spiffeid.FromSegments(sech.ControlPlaneTrustDomain(), "ns", o.namespace, "dapr-operator")
require.NoError(t, err)
conn, err := grpc.DialContext(ctx, "localhost:"+strconv.Itoa(o.Port()), sech.GRPCDialOptionMTLS(id))
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, conn.Close()) })
return operatorv1pb.NewOperatorClient(conn)
}
|
mikeee/dapr
|
tests/integration/framework/process/operator/operator.go
|
GO
|
mit
| 5,117 |
/*
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 operator
import (
"github.com/dapr/dapr/tests/integration/framework/process/exec"
)
// options contains the options for running Operator in integration tests.
type options struct {
execOpts []exec.Option
logLevel string
namespace *string
port int
healthzPort int
metricsPort int
kubeconfigPath *string
configPath *string
disableLeaderElection bool
trustAnchorsFile *string
}
// Option is a function that configures the process.
type Option func(*options)
func WithExecOptions(execOptions ...exec.Option) Option {
return func(o *options) {
o.execOpts = execOptions
}
}
func WithLogLevel(level string) Option {
return func(o *options) {
o.logLevel = level
}
}
func WithAPIPort(port int) Option {
return func(o *options) {
o.port = port
}
}
func WithHealthzPort(port int) Option {
return func(o *options) {
o.healthzPort = port
}
}
func WithMetricsPort(port int) Option {
return func(o *options) {
o.metricsPort = port
}
}
func WithKubeconfigPath(path string) Option {
return func(o *options) {
o.kubeconfigPath = &path
}
}
func WithConfigPath(path string) Option {
return func(o *options) {
o.configPath = &path
}
}
func WithDisableLeaderElection(disable bool) Option {
return func(o *options) {
o.disableLeaderElection = disable
}
}
func WithTrustAnchorsFile(path string) Option {
return func(o *options) {
o.trustAnchorsFile = &path
}
}
func WithNamespace(namespace string) Option {
return func(o *options) {
o.namespace = &namespace
}
}
|
mikeee/dapr
|
tests/integration/framework/process/operator/options.go
|
GO
|
mit
| 2,157 |
/*
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 placement
import "github.com/dapr/dapr/tests/integration/framework/process/exec"
// Option is a function that configures the process.
type Option func(*options)
// options contains the options for running Placement in integration tests.
type options struct {
execOpts []exec.Option
id string
logLevel string
port int
healthzPort int
metricsPort int
initialCluster string
initialClusterPorts []int
tlsEnabled bool
sentryAddress *string
trustAnchorsFile *string
maxAPILevel *int
minAPILevel *int
metadataEnabled bool
}
func WithExecOptions(execOptions ...exec.Option) Option {
return func(o *options) {
o.execOpts = execOptions
}
}
func WithPort(port int) Option {
return func(o *options) {
o.port = port
}
}
func WithID(id string) Option {
return func(o *options) {
o.id = id
}
}
func WithLogLevel(level string) Option {
return func(o *options) {
o.logLevel = level
}
}
func WithHealthzPort(port int) Option {
return func(o *options) {
o.healthzPort = port
}
}
func WithMetricsPort(port int) Option {
return func(o *options) {
o.metricsPort = port
}
}
func WithInitialCluster(initialCluster string) Option {
return func(o *options) {
o.initialCluster = initialCluster
}
}
func WithEnableTLS(enable bool) Option {
return func(o *options) {
o.tlsEnabled = enable
}
}
func WithSentryAddress(sentryAddress string) Option {
return func(o *options) {
o.sentryAddress = &sentryAddress
}
}
func WithTrustAnchorsFile(file string) Option {
return func(o *options) {
o.trustAnchorsFile = &file
}
}
func WithInitialClusterPorts(ports ...int) Option {
return func(o *options) {
o.initialClusterPorts = ports
}
}
func WithMaxAPILevel(val int) Option {
return func(o *options) {
o.maxAPILevel = &val
}
}
func WithMinAPILevel(val int) Option {
return func(o *options) {
o.minAPILevel = &val
}
}
func WithMetadataEnabled(enabled bool) Option {
return func(o *options) {
o.metadataEnabled = enabled
}
}
|
mikeee/dapr
|
tests/integration/framework/process/placement/options.go
|
GO
|
mit
| 2,643 |
/*
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 placement
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
"sync/atomic"
"testing"
"time"
"google.golang.org/grpc/metadata"
"github.com/google/uuid"
"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"
placementv1pb "github.com/dapr/dapr/pkg/proto/placement/v1"
"github.com/dapr/dapr/tests/integration/framework/binary"
"github.com/dapr/dapr/tests/integration/framework/process"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/ports"
"github.com/dapr/dapr/tests/integration/framework/util"
)
type Placement struct {
exec process.Interface
ports *ports.Ports
running atomic.Bool
id string
port int
healthzPort int
metricsPort int
initialCluster string
initialClusterPorts []int
}
func New(t *testing.T, fopts ...Option) *Placement {
t.Helper()
uid, err := uuid.NewUUID()
require.NoError(t, err)
fp := ports.Reserve(t, 4)
port := fp.Port(t)
opts := options{
id: uid.String(),
logLevel: "info",
port: fp.Port(t),
healthzPort: fp.Port(t),
metricsPort: fp.Port(t),
initialCluster: uid.String() + "=127.0.0.1:" + strconv.Itoa(port),
initialClusterPorts: []int{port},
metadataEnabled: false,
}
for _, fopt := range fopts {
fopt(&opts)
}
args := []string{
"--log-level=" + opts.logLevel,
"--id=" + opts.id,
"--port=" + strconv.Itoa(opts.port),
"--listen-address=127.0.0.1",
"--healthz-port=" + strconv.Itoa(opts.healthzPort),
"--healthz-listen-address=127.0.0.1",
"--metrics-port=" + strconv.Itoa(opts.metricsPort),
"--metrics-listen-address=127.0.0.1",
"--initial-cluster=" + opts.initialCluster,
"--tls-enabled=" + strconv.FormatBool(opts.tlsEnabled),
"--metadata-enabled=" + strconv.FormatBool(opts.metadataEnabled),
}
if opts.maxAPILevel != nil {
args = append(args, "--max-api-level="+strconv.Itoa(*opts.maxAPILevel))
}
if opts.minAPILevel != nil {
args = append(args, "--min-api-level="+strconv.Itoa(*opts.minAPILevel))
}
if opts.sentryAddress != nil {
args = append(args, "--sentry-address="+*opts.sentryAddress)
}
if opts.trustAnchorsFile != nil {
args = append(args, "--trust-anchors-file="+*opts.trustAnchorsFile)
}
return &Placement{
exec: exec.New(t, binary.EnvValue("placement"), args, opts.execOpts...),
ports: fp,
id: opts.id,
port: opts.port,
healthzPort: opts.healthzPort,
metricsPort: opts.metricsPort,
initialCluster: opts.initialCluster,
initialClusterPorts: opts.initialClusterPorts,
}
}
func (p *Placement) Run(t *testing.T, ctx context.Context) {
if !p.running.CompareAndSwap(false, true) {
t.Fatal("Process is already running")
}
p.ports.Free(t)
p.exec.Run(t, ctx)
}
func (p *Placement) Cleanup(t *testing.T) {
if !p.running.CompareAndSwap(true, false) {
return
}
p.exec.Cleanup(t)
}
func (p *Placement) WaitUntilRunning(t *testing.T, ctx context.Context) {
client := util.HTTPClient(t)
assert.Eventually(t, func() bool {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/healthz", p.healthzPort), nil)
if err != nil {
return false
}
resp, err := client.Do(req)
if err != nil {
return false
}
defer resp.Body.Close()
return http.StatusOK == resp.StatusCode
}, time.Second*5, 10*time.Millisecond)
}
func (p *Placement) ID() string {
return p.id
}
func (p *Placement) Port() int {
return p.port
}
func (p *Placement) Address() string {
return "127.0.0.1:" + strconv.Itoa(p.port)
}
func (p *Placement) HealthzPort() int {
return p.healthzPort
}
func (p *Placement) MetricsPort() int {
return p.metricsPort
}
func (p *Placement) InitialCluster() string {
return p.initialCluster
}
func (p *Placement) InitialClusterPorts() []int {
return p.initialClusterPorts
}
func (p *Placement) CurrentActorsAPILevel() int {
return 20 // Defined in pkg/actors/internal/api_level.go
}
func (p *Placement) RegisterHostWithMetadata(t *testing.T, parentCtx context.Context, msg *placementv1pb.Host, contextMetadata map[string]string) chan *placementv1pb.PlacementTables {
conn, err := grpc.DialContext(parentCtx, p.Address(),
grpc.WithBlock(),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
require.NoError(t, err)
client := placementv1pb.NewPlacementClient(conn)
for k, v := range contextMetadata {
parentCtx = metadata.AppendToOutgoingContext(parentCtx, k, v)
}
var stream placementv1pb.Placement_ReportDaprStatusClient
require.EventuallyWithT(t, func(c *assert.CollectT) {
stream, err = client.ReportDaprStatus(parentCtx)
//nolint:testifylint
if !assert.NoError(c, err) {
return
}
//nolint:testifylint
if !assert.NoError(c, stream.Send(msg)) {
_ = stream.CloseSend()
return
}
_, err = stream.Recv()
//nolint:testifylint
if !assert.NoError(c, err) {
_ = stream.CloseSend()
return
}
}, time.Second*15, time.Millisecond*10)
doneCh := make(chan error)
placementUpdateCh := make(chan *placementv1pb.PlacementTables)
ctx, cancel := context.WithCancel(parentCtx)
t.Cleanup(func() {
cancel()
select {
case err := <-doneCh:
require.NoError(t, err)
case <-time.After(time.Second * 5):
assert.Fail(t, "timeout waiting for stream to close")
}
})
// Send dapr status messages every second
go func() {
for {
select {
case <-ctx.Done():
doneCh <- stream.CloseSend()
return
case <-time.After(500 * time.Millisecond):
if err := stream.Send(msg); err != nil {
doneCh <- err
return
}
}
}
}()
go func() {
defer close(placementUpdateCh)
defer cancel()
for {
in, err := stream.Recv()
if err != nil {
return
}
if in.GetOperation() == "update" {
tables := in.GetTables()
require.NotEmptyf(t, tables, "Placement table is empty")
select {
case placementUpdateCh <- tables:
case <-ctx.Done():
}
}
}
}()
return placementUpdateCh
}
// RegisterHost Registers a host with the placement service using default context metadata
func (p *Placement) RegisterHost(t *testing.T, ctx context.Context, msg *placementv1pb.Host) chan *placementv1pb.PlacementTables {
ctx = metadata.AppendToOutgoingContext(ctx, "dapr-accept-vnodes", "false")
return p.RegisterHostWithMetadata(t, ctx, msg, nil)
}
// AssertRegisterHostFails Expect the registration to fail with FailedPrecondition.
func (p *Placement) AssertRegisterHostFails(t *testing.T, ctx context.Context, apiLevel int) {
msg := &placementv1pb.Host{
Name: "myapp-fail",
Port: 1234,
Entities: []string{"someactor"},
Id: "myapp",
ApiLevel: uint32(apiLevel),
}
conn, err := grpc.DialContext(ctx, p.Address(),
grpc.WithBlock(),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
require.NoError(t, err)
client := placementv1pb.NewPlacementClient(conn)
stream, err := client.ReportDaprStatus(ctx)
require.NoError(t, err, "failed to establish stream")
err = stream.Send(msg)
require.NoError(t, err, "failed to send message")
// Should fail here
_, err = stream.Recv()
require.Error(t, err)
require.Equalf(t, codes.FailedPrecondition, status.Code(err), "error was: %v", err)
}
// CheckAPILevelInState Checks the API level reported in the state table matched.
func (p *Placement) CheckAPILevelInState(t require.TestingT, client *http.Client, expectedAPILevel int) (tableVersion int) {
res, err := client.Get(fmt.Sprintf("http://localhost:%d/placement/state", p.HealthzPort()))
require.NoError(t, err)
defer res.Body.Close()
stateRes := struct {
APILevel int `json:"apiLevel"`
TableVersion int `json:"tableVersion"`
}{}
err = json.NewDecoder(res.Body).Decode(&stateRes)
require.NoError(t, err)
assert.Equal(t, expectedAPILevel, stateRes.APILevel)
return stateRes.TableVersion
}
|
mikeee/dapr
|
tests/integration/framework/process/placement/placement.go
|
GO
|
mit
| 8,703 |
/*
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 ports
import (
"context"
"errors"
"net"
"strconv"
"sync"
"sync/atomic"
"testing"
"github.com/stretchr/testify/require"
)
var (
lock sync.Mutex
resvPLen int
resvPIx int
last = 1024
resvP []*reservedPort
)
// Ports reserves network ports, and then frees them when the test is ready to
// run so a process can bind to them at runtime.
type Ports struct {
idx int
start int
end int
freed atomic.Bool
}
type reservedPort struct {
ln net.Listener
port int
}
func Reserve(t *testing.T, count int) *Ports {
t.Helper()
lock.Lock()
defer lock.Unlock()
require.GreaterOrEqual(t, count, 1)
require.LessOrEqual(t, count, 10)
resvPLen -= count
if count > resvPLen || resvPLen < 10 {
t.Logf("reserving 300 more ports")
for i := 0; i < 300; i++ {
last++
if last+i > 65535 {
last = 1024
}
ln, err := net.Listen("tcp", "127.0.0.1:"+strconv.Itoa(last))
if err != nil {
i--
continue
}
tcp, ok := ln.Addr().(*net.TCPAddr)
require.True(t, ok)
resvP = append(resvP, &reservedPort{ln, tcp.Port})
}
resvPLen += 300
}
p := &Ports{
idx: resvPIx,
start: resvPIx,
end: resvPIx + count,
}
resvPIx += count
t.Cleanup(func() { p.Free(t) })
return p
}
func (p *Ports) Port(t *testing.T) int {
t.Helper()
lock.Lock()
defer func() {
p.idx++
lock.Unlock()
}()
require.Less(t, p.idx, p.end, "request for more ports than reserved")
return resvP[p.idx].port
}
func (p *Ports) Listener(t *testing.T) net.Listener {
t.Helper()
lock.Lock()
defer func() {
p.idx++
lock.Unlock()
}()
require.Less(t, p.idx, p.end, "request for more ports than reserved")
return resvP[p.idx].ln
}
func (p *Ports) Free(t *testing.T) {
t.Helper()
if p.freed.CompareAndSwap(false, true) {
lock.Lock()
defer lock.Unlock()
for i := p.start; i < p.end; i++ {
err := resvP[i].ln.Close()
if !errors.Is(err, net.ErrClosed) {
require.NoError(t, err)
}
}
}
}
func (p *Ports) Run(t *testing.T, _ context.Context) {
t.Helper()
p.Free(t)
}
func (p *Ports) Cleanup(t *testing.T) {
p.Free(t)
}
|
mikeee/dapr
|
tests/integration/framework/process/ports/ports.go
|
GO
|
mit
| 2,662 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package process
import (
"context"
"testing"
)
// Interface is an interface for running and cleaning up a process.
type Interface interface {
// Run runs the process.
Run(*testing.T, context.Context)
// Cleanup cleans up the process.
Cleanup(*testing.T)
}
|
mikeee/dapr
|
tests/integration/framework/process/process.go
|
GO
|
mit
| 826 |
/*
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 pubsub
import (
"context"
"io"
"testing"
"github.com/dapr/components-contrib/metadata"
"github.com/dapr/components-contrib/pubsub"
compv1pb "github.com/dapr/dapr/pkg/proto/components/v1"
)
// component is an implementation of the pubsub pluggable component
// interface.
type component struct {
impl pubsub.PubSub
pmrCh <-chan *compv1pb.PullMessagesResponse
}
func newComponent(t *testing.T, opts options) *component {
return &component{
impl: opts.pubsub,
pmrCh: opts.pmrCh,
}
}
func (c *component) Init(ctx context.Context, req *compv1pb.PubSubInitRequest) (*compv1pb.PubSubInitResponse, error) {
return new(compv1pb.PubSubInitResponse), c.impl.Init(ctx, pubsub.Metadata{
Base: metadata.Base{
Name: "pubsub.in-memory",
Properties: req.GetMetadata().GetProperties(),
},
})
}
func (c *component) Features(context.Context, *compv1pb.FeaturesRequest) (*compv1pb.FeaturesResponse, error) {
implF := c.impl.Features()
features := make([]string, len(implF))
for i, f := range implF {
features[i] = string(f)
}
return &compv1pb.FeaturesResponse{
Features: features,
}, nil
}
func (c *component) Publish(ctx context.Context, req *compv1pb.PublishRequest) (*compv1pb.PublishResponse, error) {
var contentType *string
if len(req.GetContentType()) != 0 {
contentType = &req.ContentType
}
err := c.impl.Publish(ctx, &pubsub.PublishRequest{
Data: req.GetData(),
PubsubName: req.GetPubsubName(),
Topic: req.GetTopic(),
Metadata: req.GetMetadata(),
ContentType: contentType,
})
if err != nil {
return nil, err
}
return new(compv1pb.PublishResponse), nil
}
func (c *component) BulkPublish(ctx context.Context, req *compv1pb.BulkPublishRequest) (*compv1pb.BulkPublishResponse, error) {
// TODO:
return new(compv1pb.BulkPublishResponse), nil
}
func (c *component) PullMessages(req compv1pb.PubSub_PullMessagesServer) error {
for {
select {
case pmr := <-c.pmrCh:
if err := req.Send(pmr); err != nil {
return err
}
case <-req.Context().Done():
return nil
}
}
}
func (c *component) Ping(ctx context.Context, req *compv1pb.PingRequest) (*compv1pb.PingResponse, error) {
return new(compv1pb.PingResponse), nil
}
func (c *component) Close() error {
return c.impl.(io.Closer).Close()
}
|
mikeee/dapr
|
tests/integration/framework/process/pubsub/component.go
|
GO
|
mit
| 2,855 |
/*
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 inmemory
import (
"context"
"io"
"sync"
"testing"
"github.com/dapr/components-contrib/pubsub"
inmemory "github.com/dapr/components-contrib/pubsub/in-memory"
"github.com/dapr/kit/logger"
)
// Option is a function that configures the process.
type Option func(*options)
// Wrapped is a wrapper around inmemory pubsub to ensure that Init
// and Close are called only once.
type WrappedInMemory struct {
pubsub.PubSub
features []pubsub.Feature
lock sync.Mutex
hasInit bool
hasClosed bool
publishFn func(ctx context.Context, req *pubsub.PublishRequest) error
}
func NewWrappedInMemory(t *testing.T, fopts ...Option) pubsub.PubSub {
opts := options{
features: []pubsub.Feature{pubsub.FeatureBulkPublish, pubsub.FeatureMessageTTL, pubsub.FeatureSubscribeWildcards},
}
for _, fopt := range fopts {
fopt(&opts)
}
impl := inmemory.New(logger.NewLogger(t.Name() + "_pubsub"))
return &WrappedInMemory{
PubSub: impl,
features: opts.features,
publishFn: opts.publishFn,
}
}
func (w *WrappedInMemory) Publish(ctx context.Context, req *pubsub.PublishRequest) error {
if w.publishFn != nil {
return w.publishFn(ctx, req)
}
return w.PubSub.Publish(ctx, req)
}
func (w *WrappedInMemory) Init(ctx context.Context, metadata pubsub.Metadata) error {
w.lock.Lock()
defer w.lock.Unlock()
if !w.hasInit {
w.hasInit = true
return w.PubSub.Init(ctx, metadata)
}
return nil
}
func (w *WrappedInMemory) Close() error {
w.lock.Lock()
defer w.lock.Unlock()
if !w.hasClosed {
w.hasClosed = true
return w.PubSub.(io.Closer).Close()
}
return nil
}
|
mikeee/dapr
|
tests/integration/framework/process/pubsub/in-memory/inmemory.go
|
GO
|
mit
| 2,158 |
/*
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 inmemory
import (
"context"
"github.com/dapr/components-contrib/pubsub"
)
// options contains the options for running an in-memory pubsub.
type options struct {
publishFn func(ctx context.Context, req *pubsub.PublishRequest) error
features []pubsub.Feature
}
func WithFeatures(features ...pubsub.Feature) Option {
return func(o *options) {
o.features = features
}
}
func WithPublishFn(fn func(ctx context.Context, req *pubsub.PublishRequest) error) Option {
return func(o *options) {
o.publishFn = fn
}
}
|
mikeee/dapr
|
tests/integration/framework/process/pubsub/in-memory/options.go
|
GO
|
mit
| 1,092 |
/*
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 pubsub
import (
"github.com/dapr/components-contrib/pubsub"
compv1pb "github.com/dapr/dapr/pkg/proto/components/v1"
"github.com/dapr/dapr/tests/integration/framework/socket"
)
type options struct {
socket *socket.Socket
pubsub pubsub.PubSub
pmrCh <-chan *compv1pb.PullMessagesResponse
}
func WithSocket(socket *socket.Socket) Option {
return func(o *options) {
o.socket = socket
}
}
func WithPubSub(pubsub pubsub.PubSub) Option {
return func(o *options) {
o.pubsub = pubsub
}
}
func WithPullMessagesChannel(ch <-chan *compv1pb.PullMessagesResponse) Option {
return func(o *options) {
o.pmrCh = ch
}
}
|
mikeee/dapr
|
tests/integration/framework/process/pubsub/options.go
|
GO
|
mit
| 1,194 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package pubsub
import (
"context"
"io"
"net"
"testing"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
"github.com/dapr/components-contrib/pubsub"
compv1pb "github.com/dapr/dapr/pkg/proto/components/v1"
)
// Option is a function that configures the process.
type Option func(*options)
// PubSub is a pluggable pubsub component for Dapr.
type PubSub struct {
listener net.Listener
socketName string
component *component
srvErrCh chan error
stopCh chan struct{}
}
func New(t *testing.T, fopts ...Option) *PubSub {
t.Helper()
opts := options{
pmrCh: make(chan *compv1pb.PullMessagesResponse),
}
for _, fopts := range fopts {
fopts(&opts)
}
require.NotNil(t, opts.socket)
require.NotNil(t, opts.pubsub)
// Start the listener in New, so we can sit on the path immediately, and
// keep it for the entire test case.
socketFile := opts.socket.File(t)
listener, err := net.Listen("unix", socketFile.Filename())
require.NoError(t, err)
return &PubSub{
listener: listener,
component: newComponent(t, opts),
socketName: socketFile.Name(),
srvErrCh: make(chan error),
stopCh: make(chan struct{}),
}
}
func (p *PubSub) SocketName() string {
return p.socketName
}
func (p *PubSub) Run(t *testing.T, ctx context.Context) {
p.component.impl.Init(ctx, pubsub.Metadata{})
server := grpc.NewServer()
compv1pb.RegisterPubSubServer(server, p.component)
reflection.Register(server)
go func() {
p.srvErrCh <- server.Serve(p.listener)
}()
go func() {
<-p.stopCh
server.GracefulStop()
}()
}
func (p *PubSub) Cleanup(t *testing.T) {
close(p.stopCh)
require.NoError(t, <-p.srvErrCh)
require.NoError(t, p.component.impl.(io.Closer).Close())
}
|
mikeee/dapr
|
tests/integration/framework/process/pubsub/pubsub.go
|
GO
|
mit
| 2,320 |
/*
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 sentry
import (
"github.com/dapr/dapr/pkg/sentry/server/ca"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
)
// options contains the options for running Sentry in integration tests.
type options struct {
execOpts []exec.Option
bundle *ca.Bundle
writeBundle bool
port int
healthzPort int
metricsPort int
configuration string
writeConfig bool
kubeconfig *string
trustDomain *string
namespace *string
}
// Option is a function that configures the process.
type Option func(*options)
func WithExecOptions(execOptions ...exec.Option) Option {
return func(o *options) {
o.execOpts = execOptions
}
}
func WithPort(port int) Option {
return func(o *options) {
o.port = port
}
}
func WithMetricsPort(port int) Option {
return func(o *options) {
o.metricsPort = port
}
}
func WithHealthzPort(port int) Option {
return func(o *options) {
o.healthzPort = port
}
}
func WithCABundle(bundle ca.Bundle) Option {
return func(o *options) {
o.bundle = &bundle
}
}
func WithConfiguration(config string) Option {
return func(o *options) {
o.configuration = config
}
}
func WithWriteTrustBundle(writeBundle bool) Option {
return func(o *options) {
o.writeBundle = writeBundle
}
}
func WithKubeconfig(kubeconfig string) Option {
return func(o *options) {
o.kubeconfig = &kubeconfig
}
}
func WithTrustDomain(trustDomain string) Option {
return func(o *options) {
o.trustDomain = &trustDomain
}
}
func WithWriteConfig(write bool) Option {
return func(o *options) {
o.writeConfig = write
}
}
func WithNamespace(namespace string) Option {
return func(o *options) {
o.namespace = &namespace
}
}
|
mikeee/dapr
|
tests/integration/framework/process/sentry/options.go
|
GO
|
mit
| 2,259 |
/*
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 sentry
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"fmt"
"net/http"
"os"
"path/filepath"
"strconv"
"testing"
"time"
"github.com/spiffe/go-spiffe/v2/bundle/x509bundle"
"github.com/spiffe/go-spiffe/v2/spiffegrpc/grpccredentials"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/spiffe/go-spiffe/v2/spiffetls/tlsconfig"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"github.com/dapr/dapr/pkg/sentry/server/ca"
"github.com/dapr/dapr/tests/integration/framework/binary"
"github.com/dapr/dapr/tests/integration/framework/process"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/ports"
"github.com/dapr/dapr/tests/integration/framework/util"
)
type Sentry struct {
exec process.Interface
ports *ports.Ports
bundle *ca.Bundle
port int
healthzPort int
metricsPort int
trustDomain *string
}
func New(t *testing.T, fopts ...Option) *Sentry {
t.Helper()
fp := ports.Reserve(t, 3)
opts := options{
port: fp.Port(t),
healthzPort: fp.Port(t),
metricsPort: fp.Port(t),
writeBundle: true,
writeConfig: true,
}
for _, fopt := range fopts {
fopt(&opts)
}
// Only generate a bundle if one was not provided.
if opts.bundle == nil {
td := spiffeid.RequireTrustDomainFromString("default").String()
if opts.trustDomain != nil {
td = *opts.trustDomain
}
pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
bundle, err := ca.GenerateBundle(pk, td, time.Second*5, nil)
require.NoError(t, err)
opts.bundle = &bundle
}
args := []string{
"-log-level=" + "info",
"-port=" + strconv.Itoa(opts.port),
"-issuer-ca-filename=ca.crt",
"-issuer-certificate-filename=issuer.crt",
"-issuer-key-filename=issuer.key",
"-metrics-port=" + strconv.Itoa(opts.metricsPort),
"-metrics-listen-address=127.0.0.1",
"-healthz-port=" + strconv.Itoa(opts.healthzPort),
"-healthz-listen-address=127.0.0.1",
"-listen-address=127.0.0.1",
}
if opts.writeBundle {
tmpDir := t.TempDir()
caPath := filepath.Join(tmpDir, "ca.crt")
issuerKeyPath := filepath.Join(tmpDir, "issuer.key")
issuerCertPath := filepath.Join(tmpDir, "issuer.crt")
for _, pair := range []struct {
path string
data []byte
}{
{caPath, opts.bundle.TrustAnchors},
{issuerKeyPath, opts.bundle.IssKeyPEM},
{issuerCertPath, opts.bundle.IssChainPEM},
} {
require.NoError(t, os.WriteFile(pair.path, pair.data, 0o600))
}
args = append(args, "-issuer-credentials="+tmpDir)
} else {
args = append(args, "-issuer-credentials="+t.TempDir())
}
if opts.kubeconfig != nil {
args = append(args, "-kubeconfig="+*opts.kubeconfig)
}
if opts.trustDomain != nil {
args = append(args, "-trust-domain="+*opts.trustDomain)
}
if opts.writeConfig {
configPath := filepath.Join(t.TempDir(), "sentry-config.yaml")
require.NoError(t, os.WriteFile(configPath, []byte(opts.configuration), 0o600))
args = append(args, "-config="+configPath)
}
if opts.namespace != nil {
opts.execOpts = append(opts.execOpts, exec.WithEnvVars(t, "NAMESPACE", *opts.namespace))
}
return &Sentry{
exec: exec.New(t, binary.EnvValue("sentry"), args, opts.execOpts...),
ports: fp,
bundle: opts.bundle,
port: opts.port,
metricsPort: opts.metricsPort,
healthzPort: opts.healthzPort,
trustDomain: opts.trustDomain,
}
}
func (s *Sentry) Run(t *testing.T, ctx context.Context) {
s.ports.Free(t)
s.exec.Run(t, ctx)
}
func (s *Sentry) Cleanup(t *testing.T) {
s.exec.Cleanup(t)
}
func (s *Sentry) WaitUntilRunning(t *testing.T, ctx context.Context) {
client := util.HTTPClient(t)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://localhost:%d/healthz", s.healthzPort), nil)
require.NoError(t, err)
assert.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.Do(req)
//nolint:testifylint
if assert.NoError(c, err) {
defer resp.Body.Close()
assert.Equal(c, http.StatusOK, resp.StatusCode)
}
}, time.Second*20, 10*time.Millisecond)
}
func (s *Sentry) TrustAnchorsFile(t *testing.T) string {
t.Helper()
taf := filepath.Join(t.TempDir(), "ca.pem")
require.NoError(t, os.WriteFile(taf, s.CABundle().TrustAnchors, 0o600))
return taf
}
func (s *Sentry) CABundle() ca.Bundle {
return *s.bundle
}
func (s *Sentry) Port() int {
return s.port
}
func (s *Sentry) Address() string {
return "localhost:" + strconv.Itoa(s.Port())
}
func (s *Sentry) MetricsPort() int {
return s.metricsPort
}
func (s *Sentry) HealthzPort() int {
return s.healthzPort
}
func (s *Sentry) TrustDomain(t *testing.T) string {
require.NotNil(t, s.trustDomain)
return *s.trustDomain
}
// DialGRPC dials the sentry using the given context and returns a grpc client
// connection.
func (s *Sentry) DialGRPC(t *testing.T, ctx context.Context, sentryID string) *grpc.ClientConn {
bundle := s.CABundle()
sentrySPIFFEID, err := spiffeid.FromString(sentryID)
require.NoError(t, err)
x509bundle, err := x509bundle.Parse(sentrySPIFFEID.TrustDomain(), bundle.TrustAnchors)
require.NoError(t, err)
transportCredentials := grpccredentials.TLSClientCredentials(x509bundle, tlsconfig.AuthorizeID(sentrySPIFFEID))
ctx, cancel := context.WithTimeout(ctx, time.Second*5)
defer cancel()
conn, err := grpc.DialContext(
ctx,
fmt.Sprintf("127.0.0.1:%d", s.Port()),
grpc.WithTransportCredentials(transportCredentials),
grpc.WithReturnConnectionError(),
grpc.WithBlock(),
)
require.NoError(t, err)
t.Cleanup(func() {
require.NoError(t, conn.Close())
})
return conn
}
|
mikeee/dapr
|
tests/integration/framework/process/sentry/sentry.go
|
GO
|
mit
| 6,254 |
/*
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 sqlite
// options contains the options for using a SQLite database in integration tests.
type options struct {
name string
isActorStateStore bool
metadata map[string]string
migrations []string
execs []string
}
// WithName sets the name for the state store.
// Default is "mystore".
func WithName(name string) Option {
return func(o *options) {
o.name = name
}
}
// WithActorStateStore configures whether the state store is enabled as actor state store.
func WithActorStateStore(enabled bool) Option {
return func(o *options) {
o.isActorStateStore = enabled
}
}
// WithMetadata adds a metadata option to the component.
// This can be invoked multiple times.
func WithMetadata(key, value string) Option {
return func(o *options) {
if o.metadata == nil {
o.metadata = make(map[string]string)
}
o.metadata[key] = value
}
}
// WithCreateStateTables configures whether the state store should create the state tables.
func WithCreateStateTables() Option {
return func(o *options) {
o.migrations = append(o.migrations, `
CREATE TABLE metadata (
key text NOT NULL PRIMARY KEY,
value text NOT NULL
);
INSERT INTO metadata VALUES('migrations','1');
CREATE TABLE state (
key TEXT NOT NULL PRIMARY KEY,
value TEXT NOT NULL,
is_binary BOOLEAN NOT NULL,
etag TEXT NOT NULL,
expiration_time TIMESTAMP DEFAULT NULL,
update_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);`)
}
}
// WithExecs defines the execs to run against the database on Run.
func WithExecs(execs ...string) Option {
return func(o *options) {
o.execs = execs
}
}
|
mikeee/dapr
|
tests/integration/framework/process/sqlite/options.go
|
GO
|
mit
| 2,183 |
/*
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 sqlite
import (
"context"
"database/sql"
"encoding/json"
"path/filepath"
"strconv"
"testing"
// Blank import for the sqlite driver
_ "modernc.org/sqlite"
"github.com/stretchr/testify/require"
v1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
commonapi "github.com/dapr/dapr/pkg/apis/common"
componentsv1alpha1 "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
)
// Option is a function that configures the process.
type Option func(*options)
// SQLite database that can be used in integration tests.
// Consumers should always run this Process before any other Framework
// Processes which consume it so all migrations are applied.
type SQLite struct {
dbPath string
name string
metadata map[string]string
migrations []string
isActorStateStore bool
execs []string
conn *sql.DB
}
func New(t *testing.T, fopts ...Option) *SQLite {
t.Helper()
opts := options{
name: "mystore",
}
for _, fopt := range fopts {
fopt(&opts)
}
// Create a SQLite database in the test's temporary directory
dbPath := filepath.Join(t.TempDir(), "test-data.db")
t.Logf("Storing SQLite database at %s", dbPath)
return &SQLite{
dbPath: dbPath,
name: opts.name,
metadata: opts.metadata,
migrations: opts.migrations,
isActorStateStore: opts.isActorStateStore,
execs: opts.execs,
}
}
func (s *SQLite) Run(t *testing.T, ctx context.Context) {
for _, migration := range s.migrations {
_, err := s.GetConnection(t).ExecContext(ctx, migration)
require.NoError(t, err)
}
for _, exec := range s.execs {
_, err := s.GetConnection(t).ExecContext(ctx, exec)
require.NoError(t, err)
}
}
func (s *SQLite) Cleanup(t *testing.T) {
if s.conn != nil {
require.NoError(t, s.conn.Close())
}
}
// GetConnection returns the connection to the SQLite database.
func (s *SQLite) GetConnection(t *testing.T) *sql.DB {
if s.conn != nil {
return s.conn
}
conn, err := sql.Open("sqlite", "file://"+s.dbPath+"?_txlock=immediate&_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)")
require.NoError(t, err, "Failed to connect to SQLite database")
s.conn = conn
return conn
}
// GetComponent returns the Component resource.
func (s *SQLite) GetComponent(t *testing.T) string {
c := componentsv1alpha1.Component{
TypeMeta: metav1.TypeMeta{
Kind: "Component",
APIVersion: "dapr.io/v1alpha1",
},
ObjectMeta: metav1.ObjectMeta{
Name: s.name,
},
Spec: componentsv1alpha1.ComponentSpec{
Type: "state.sqlite",
Version: "v1",
Metadata: []commonapi.NameValuePair{
{Name: "connectionString", Value: toDynamicValue(t, "file:"+s.dbPath)},
{Name: "actorStateStore", Value: toDynamicValue(t, strconv.FormatBool(s.isActorStateStore))},
},
},
}
for k, v := range s.metadata {
c.Spec.Metadata = append(c.Spec.Metadata, commonapi.NameValuePair{
Name: k,
Value: toDynamicValue(t, v),
})
}
enc, err := json.Marshal(c)
require.NoError(t, err)
return string(enc)
}
func toDynamicValue(t *testing.T, val string) commonapi.DynamicValue {
j, err := json.Marshal(val)
require.NoError(t, err)
return commonapi.DynamicValue{JSON: v1.JSON{Raw: j}}
}
|
mikeee/dapr
|
tests/integration/framework/process/sqlite/sqlite.go
|
GO
|
mit
| 3,866 |
/*
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 statestore
import (
"context"
"fmt"
"io"
"testing"
"github.com/dapr/components-contrib/metadata"
"github.com/dapr/components-contrib/state"
compv1pb "github.com/dapr/dapr/pkg/proto/components/v1"
)
// component is an implementation of the state store pluggable component
// interface.
type component struct {
impl state.Store
}
func newComponent(t *testing.T, opts options) *component {
return &component{
impl: opts.statestore,
}
}
func (c *component) BulkDelete(ctx context.Context, req *compv1pb.BulkDeleteRequest) (*compv1pb.BulkDeleteResponse, error) {
dr := make([]state.DeleteRequest, len(req.GetItems()))
for i, item := range req.GetItems() {
dr[i] = state.DeleteRequest{
Key: item.GetKey(),
ETag: &item.GetEtag().Value,
Metadata: item.GetMetadata(),
Options: state.DeleteStateOption{
Concurrency: concurrencyOf(item.GetOptions().GetConcurrency()),
Consistency: consistencyOf(item.GetOptions().GetConsistency()),
},
}
}
err := c.impl.BulkDelete(ctx, dr, state.BulkStoreOpts{})
if err != nil {
return nil, fmt.Errorf("error performing bulk delete: %s", err)
}
return new(compv1pb.BulkDeleteResponse), nil
}
func (c *component) BulkGet(ctx context.Context, req *compv1pb.BulkGetRequest) (*compv1pb.BulkGetResponse, error) {
gr := make([]state.GetRequest, len(req.GetItems()))
for i, item := range req.GetItems() {
gr[i] = state.GetRequest{
Key: item.GetKey(),
Metadata: item.GetMetadata(),
Options: state.GetStateOption{
Consistency: consistencyOf(item.GetConsistency()),
},
}
}
resp, err := c.impl.BulkGet(ctx, gr, state.BulkGetOpts{})
if err != nil {
return nil, fmt.Errorf("error performing bulk get: %s", err)
}
var gresp compv1pb.BulkGetResponse
for _, item := range resp {
gitem := &compv1pb.BulkStateItem{
Key: item.Key,
Data: item.Data,
Metadata: item.Metadata,
}
if item.ETag != nil {
gitem.Etag = &compv1pb.Etag{
Value: *item.ETag,
}
}
gresp.Items = append(gresp.GetItems(), gitem)
}
return &gresp, nil
}
func (c *component) Query(ctx context.Context, req *compv1pb.QueryRequest) (*compv1pb.QueryResponse, error) {
// TODO: @joshvanl implement query API transformation, rather than just
// sending nothing and returning error.
_, err := c.impl.(state.Querier).Query(ctx, &state.QueryRequest{})
return nil, err
}
func (c *component) MultiMaxSize(context.Context, *compv1pb.MultiMaxSizeRequest) (*compv1pb.MultiMaxSizeResponse, error) {
return &compv1pb.MultiMaxSizeResponse{
MaxSize: int64(c.impl.(state.TransactionalStoreMultiMaxSize).MultiMaxSize()),
}, nil
}
func (c *component) BulkSet(ctx context.Context, req *compv1pb.BulkSetRequest) (*compv1pb.BulkSetResponse, error) {
sr := make([]state.SetRequest, len(req.GetItems()))
for i, item := range req.GetItems() {
var etag *string
if item.GetEtag() != nil {
etag = &item.GetEtag().Value
}
sr[i] = state.SetRequest{
Key: item.GetKey(),
Value: item.GetValue(),
ETag: etag,
Metadata: item.GetMetadata(),
Options: state.SetStateOption{
Concurrency: concurrencyOf(item.GetOptions().GetConcurrency()),
Consistency: consistencyOf(item.GetOptions().GetConsistency()),
},
}
}
err := c.impl.BulkSet(ctx, sr, state.BulkStoreOpts{})
if err != nil {
return nil, fmt.Errorf("error performing bulk set: %s", err)
}
return new(compv1pb.BulkSetResponse), nil
}
func (c *component) Delete(ctx context.Context, req *compv1pb.DeleteRequest) (*compv1pb.DeleteResponse, error) {
var etag *string
if req.GetEtag() != nil && len(req.GetEtag().GetValue()) > 0 {
etag = &req.GetEtag().Value
}
err := c.impl.Delete(ctx, &state.DeleteRequest{
Key: req.GetKey(),
ETag: etag,
Metadata: req.GetMetadata(),
Options: state.DeleteStateOption{
Concurrency: concurrencyOf(req.GetOptions().GetConcurrency()),
Consistency: consistencyOf(req.GetOptions().GetConsistency()),
},
})
if err != nil {
return nil, err
}
return new(compv1pb.DeleteResponse), nil
}
func (c *component) Features(context.Context, *compv1pb.FeaturesRequest) (*compv1pb.FeaturesResponse, error) {
implF := c.impl.Features()
features := make([]string, len(implF))
for i, f := range implF {
features[i] = string(f)
}
return &compv1pb.FeaturesResponse{
Features: features,
}, nil
}
func (c *component) Get(ctx context.Context, req *compv1pb.GetRequest) (*compv1pb.GetResponse, error) {
resp, err := c.impl.Get(ctx, &state.GetRequest{
Key: req.GetKey(),
Metadata: req.GetMetadata(),
Options: state.GetStateOption{
Consistency: consistencyOf(req.GetConsistency()),
},
})
if err != nil {
return nil, err
}
gresp := compv1pb.GetResponse{
Data: resp.Data,
Metadata: resp.Metadata,
}
if resp.ETag != nil && len(*resp.ETag) > 0 {
gresp.Etag = &compv1pb.Etag{
Value: *resp.ETag,
}
}
return &gresp, nil
}
func (c *component) Init(ctx context.Context, req *compv1pb.InitRequest) (*compv1pb.InitResponse, error) {
return new(compv1pb.InitResponse), c.impl.Init(ctx, state.Metadata{
Base: metadata.Base{
Name: "state.wrapped-in-memory",
Properties: req.GetMetadata().GetProperties(),
},
})
}
func (c *component) Close() error {
return c.impl.(io.Closer).Close()
}
func (c *component) Ping(ctx context.Context, req *compv1pb.PingRequest) (*compv1pb.PingResponse, error) {
return new(compv1pb.PingResponse), nil
}
func (c *component) Set(ctx context.Context, req *compv1pb.SetRequest) (*compv1pb.SetResponse, error) {
var etag *string
if req.GetEtag() != nil && len(req.GetEtag().GetValue()) > 0 {
etag = &req.GetEtag().Value
}
err := c.impl.Set(ctx, &state.SetRequest{
Key: req.GetKey(),
Value: req.GetValue(),
Metadata: req.GetMetadata(),
ETag: etag,
Options: state.SetStateOption{
Concurrency: concurrencyOf(req.GetOptions().GetConcurrency()),
Consistency: consistencyOf(req.GetOptions().GetConsistency()),
},
})
if err != nil {
return nil, fmt.Errorf("error performing set: %s", err)
}
return new(compv1pb.SetResponse), nil
}
func (c *component) Transact(ctx context.Context, req *compv1pb.TransactionalStateRequest) (*compv1pb.TransactionalStateResponse, error) {
var operations []state.TransactionalStateOperation
for _, op := range req.GetOperations() {
switch v := op.GetRequest().(type) {
case *compv1pb.TransactionalStateOperation_Delete:
delReq := state.DeleteRequest{
Key: v.Delete.GetKey(),
Metadata: v.Delete.GetMetadata(),
Options: state.DeleteStateOption{
Concurrency: concurrencyOf(v.Delete.GetOptions().GetConcurrency()),
Consistency: consistencyOf(v.Delete.GetOptions().GetConsistency()),
},
}
if v.Delete.GetEtag() != nil {
delReq.ETag = &v.Delete.GetEtag().Value
}
operations = append(operations, delReq)
case *compv1pb.TransactionalStateOperation_Set:
setReq := state.SetRequest{
Key: v.Set.GetKey(),
Value: v.Set.GetValue(),
Metadata: v.Set.GetMetadata(),
Options: state.SetStateOption{
Concurrency: concurrencyOf(v.Set.GetOptions().GetConcurrency()),
Consistency: consistencyOf(v.Set.GetOptions().GetConsistency()),
},
}
if v.Set.GetEtag() != nil && v.Set.GetEtag().GetValue() != "" {
setReq.ETag = &v.Set.GetEtag().Value
}
default:
return nil, fmt.Errorf("unknown operation type %T", v)
}
}
err := c.impl.(state.TransactionalStore).Multi(ctx, &state.TransactionalStateRequest{
Operations: operations,
Metadata: req.GetMetadata(),
})
if err != nil {
return nil, fmt.Errorf("error performing transactional state operation: %s", err)
}
return new(compv1pb.TransactionalStateResponse), nil
}
var consistencyModels = map[compv1pb.StateOptions_StateConsistency]string{
compv1pb.StateOptions_CONSISTENCY_EVENTUAL: state.Eventual,
compv1pb.StateOptions_CONSISTENCY_STRONG: state.Strong,
}
func consistencyOf(value compv1pb.StateOptions_StateConsistency) string {
consistency, ok := consistencyModels[value]
if !ok {
return ""
}
return consistency
}
var concurrencyModels = map[compv1pb.StateOptions_StateConcurrency]string{
compv1pb.StateOptions_CONCURRENCY_FIRST_WRITE: state.FirstWrite,
compv1pb.StateOptions_CONCURRENCY_LAST_WRITE: state.LastWrite,
}
func concurrencyOf(value compv1pb.StateOptions_StateConcurrency) string {
concurrency, ok := concurrencyModels[value]
if !ok {
return ""
}
return concurrency
}
|
mikeee/dapr
|
tests/integration/framework/process/statestore/component.go
|
GO
|
mit
| 9,022 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.