code
stringlengths 0
56.1M
| repo_name
stringclasses 515
values | path
stringlengths 2
147
| language
stringclasses 447
values | license
stringclasses 7
values | size
int64 0
56.8M
|
---|---|---|---|---|---|
/*
Copyright 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/state"
inmemory "github.com/dapr/components-contrib/state/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 state store to ensure that Init
// and Close are called only once.
type Wrapped struct {
state.Store
features []state.Feature
lock sync.Mutex
hasInit bool
hasClosed bool
}
type WrappedTransactionalMultiMaxSize struct {
*Wrapped
state.TransactionalStore
transactionalStoreMultiMaxSizeFn func() int
}
type WrappedQuerier struct {
*Wrapped
queryFunc func(context.Context, *state.QueryRequest) (*state.QueryResponse, error)
}
func New(t *testing.T, fopts ...Option) state.Store {
opts := options{
features: []state.Feature{state.FeatureETag, state.FeatureTransactional, state.FeatureTTL},
}
for _, fopt := range fopts {
fopt(&opts)
}
impl := inmemory.NewInMemoryStateStore(logger.NewLogger(t.Name() + "_state_store"))
return &Wrapped{
Store: impl,
features: opts.features,
}
}
func NewQuerier(t *testing.T, fopts ...Option) state.Store {
opts := options{
features: []state.Feature{state.FeatureETag, state.FeatureTransactional, state.FeatureTTL, state.FeatureQueryAPI},
}
for _, fopt := range fopts {
fopt(&opts)
}
impl := inmemory.NewInMemoryStateStore(logger.NewLogger(t.Name() + "_state_store"))
return &WrappedQuerier{
Wrapped: &Wrapped{Store: impl, features: opts.features},
queryFunc: opts.queryFunc,
}
}
func NewTransactionalMultiMaxSize(t *testing.T, fopts ...Option) state.Store {
opts := options{
features: []state.Feature{state.FeatureETag, state.FeatureTransactional, state.FeatureTTL},
}
for _, fopt := range fopts {
fopt(&opts)
}
impl := inmemory.NewInMemoryStateStore(logger.NewLogger(t.Name() + "_state_store"))
return &WrappedTransactionalMultiMaxSize{
Wrapped: &Wrapped{Store: impl, features: opts.features},
TransactionalStore: impl.(state.TransactionalStore),
transactionalStoreMultiMaxSizeFn: opts.transactionalStoreMultiMaxSizeFn,
}
}
func (w *Wrapped) Init(ctx context.Context, metadata state.Metadata) error {
w.lock.Lock()
defer w.lock.Unlock()
if !w.hasInit {
w.hasInit = true
return w.Store.Init(ctx, metadata)
}
return nil
}
func (w *WrappedQuerier) Query(ctx context.Context, req *state.QueryRequest) (*state.QueryResponse, error) {
w.lock.Lock()
defer w.lock.Unlock()
if w.queryFunc != nil {
return w.queryFunc(ctx, req)
}
return nil, nil
}
func (w *WrappedTransactionalMultiMaxSize) MultiMaxSize() int {
w.lock.Lock()
defer w.lock.Unlock()
if w.transactionalStoreMultiMaxSizeFn != nil {
return w.transactionalStoreMultiMaxSizeFn()
}
return -1
}
func (w *Wrapped) Close() error {
w.lock.Lock()
defer w.lock.Unlock()
if !w.hasClosed {
w.hasClosed = true
return w.Store.(io.Closer).Close()
}
return nil
}
func (w *Wrapped) Features() []state.Feature {
return w.features
}
|
mikeee/dapr
|
tests/integration/framework/process/statestore/inmemory/inmemory.go
|
GO
|
mit
| 3,637 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package inmemory
import (
"context"
"github.com/dapr/components-contrib/state"
)
// options contains the options for running an in-memory state store.
type options struct {
queryFunc func(context.Context, *state.QueryRequest) (*state.QueryResponse, error)
transactionalStoreMultiMaxSizeFn func() int
features []state.Feature
}
func WithQueryFn(fn func(context.Context, *state.QueryRequest) (*state.QueryResponse, error)) Option {
return func(o *options) {
o.queryFunc = fn
}
}
func WithTransactionalStoreMultiMaxSizeFn(fn func() int) Option {
return func(o *options) {
o.transactionalStoreMultiMaxSizeFn = fn
}
}
func WithFeatures(features ...state.Feature) Option {
return func(o *options) {
o.features = features
}
}
|
mikeee/dapr
|
tests/integration/framework/process/statestore/inmemory/options.go
|
GO
|
mit
| 1,350 |
/*
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 (
"github.com/dapr/components-contrib/state"
"github.com/dapr/dapr/tests/integration/framework/socket"
)
// options contains the options for running a pluggable state store in integration tests.
type options struct {
socket *socket.Socket
statestore state.Store
}
func WithSocket(socket *socket.Socket) Option {
return func(o *options) {
o.socket = socket
}
}
func WithStateStore(store state.Store) Option {
return func(o *options) {
o.statestore = store
}
}
|
mikeee/dapr
|
tests/integration/framework/process/statestore/options.go
|
GO
|
mit
| 1,066 |
/*
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"
"io"
"net"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/reflection"
"github.com/dapr/components-contrib/state"
compv1pb "github.com/dapr/dapr/pkg/proto/components/v1"
)
// Option is a function that configures the process.
type Option func(*options)
// StateStore is a pluggable state store component for Dapr.
type StateStore struct {
listener net.Listener
socketName string
component *component
server *grpc.Server
srvErrCh chan error
}
func New(t *testing.T, fopts ...Option) *StateStore {
t.Helper()
var opts options
for _, fopt := range fopts {
fopt(&opts)
}
require.NotNil(t, opts.socket)
require.NotNil(t, opts.statestore)
// Start the listener in New so we can squat 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)
component := newComponent(t, opts)
server := grpc.NewServer()
compv1pb.RegisterStateStoreServer(server, component)
compv1pb.RegisterTransactionalStateStoreServer(server, component)
compv1pb.RegisterQueriableStateStoreServer(server, component)
compv1pb.RegisterTransactionalStoreMultiMaxSizeServer(server, component)
reflection.Register(server)
return &StateStore{
listener: listener,
component: component,
socketName: socketFile.Name(),
server: server,
srvErrCh: make(chan error),
}
}
func (s *StateStore) SocketName() string {
return s.socketName
}
func (s *StateStore) Run(t *testing.T, ctx context.Context) {
s.component.impl.Init(ctx, state.Metadata{})
go func() {
s.srvErrCh <- s.server.Serve(s.listener)
}()
conn, err := grpc.DialContext(ctx, "unix://"+s.listener.Addr().String(),
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithBlock(),
)
require.NoError(t, err)
client := compv1pb.NewStateStoreClient(conn)
assert.EventuallyWithT(t, func(c *assert.CollectT) {
_, err = client.Ping(ctx, new(compv1pb.PingRequest))
//nolint:testifylint
assert.NoError(c, err)
}, 10*time.Second, 10*time.Millisecond)
require.NoError(t, conn.Close())
}
func (s *StateStore) Cleanup(t *testing.T) {
s.server.GracefulStop()
require.NoError(t, <-s.srvErrCh)
require.NoError(t, s.component.impl.(io.Closer).Close())
}
|
mikeee/dapr
|
tests/integration/framework/process/statestore/statestore.go
|
GO
|
mit
| 3,028 |
/*
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 socket
import (
"os"
"path/filepath"
"runtime"
"testing"
"github.com/stretchr/testify/require"
"golang.org/x/net/nettest"
"github.com/dapr/dapr/tests/integration/framework/util"
)
// Socket is a helper to create a temporary directory hosting unix socket files
// for Dapr pluggable components.
type Socket struct {
dir string
}
type File struct {
name string
filename string
}
func New(t *testing.T) *Socket {
if runtime.GOOS == "windows" {
t.Skip("Unix sockets are not supported on Windows")
}
// Darwin enforces a maximum 104 byte socket name limit, so we need to be a
// bit fancy on how we generate the name.
tmp, err := nettest.LocalPath()
require.NoError(t, err)
socketDir := filepath.Join(tmp, util.RandomString(t, 4))
require.NoError(t, os.MkdirAll(socketDir, 0o700))
t.Cleanup(func() { require.NoError(t, os.RemoveAll(tmp)) })
return &Socket{
dir: socketDir,
}
}
func (s *Socket) Directory() string {
return s.dir
}
func (s *Socket) File(t *testing.T) *File {
socketFile := util.RandomString(t, 8)
return &File{
name: socketFile,
filename: filepath.Join(s.dir, socketFile+".sock"),
}
}
func (f *File) Name() string {
return f.name
}
func (f *File) Filename() string {
return f.filename
}
|
mikeee/dapr
|
tests/integration/framework/socket/socket.go
|
GO
|
mit
| 1,822 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package util
import (
"path/filepath"
"strings"
"testing"
fuzz "github.com/google/gofuzz"
"k8s.io/apimachinery/pkg/api/validation/path"
)
func FileNames(t *testing.T, num int) []string {
if num < 0 {
t.Fatalf("file name count must be >= 0, got %d", num)
}
fz := fuzz.New()
names := make([]string, num)
taken := make(map[string]bool)
forbiddenChars := func(s string) bool {
for _, c := range forbiddenFileChars {
if strings.Contains(s, c) {
return true
}
}
return false
}
dir := t.TempDir()
for i := 0; i < num; i++ {
var fileName string
for len(fileName) == 0 ||
strings.HasPrefix(fileName, "..") ||
strings.HasPrefix(fileName, " ") ||
fileName == "." ||
forbiddenChars(fileName) ||
len(path.IsValidPathSegmentName(fileName)) > 0 ||
taken[fileName] {
fileName = ""
fz.Fuzz(&fileName)
}
taken[fileName] = true
names[i] = filepath.Join(dir, fileName)
}
return names
}
|
mikeee/dapr
|
tests/integration/framework/util/file.go
|
GO
|
mit
| 1,504 |
//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 util
var forbiddenFileChars = []string{"/"}
|
mikeee/dapr
|
tests/integration/framework/util/file_posix.go
|
GO
|
mit
| 654 |
//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 util
var forbiddenFileChars = []string{"<", ">", ":", "\"", "/", "\\", "|", "?", "*"}
|
mikeee/dapr
|
tests/integration/framework/util/file_windows.go
|
GO
|
mit
| 694 |
/*
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 util
import (
"context"
"strconv"
"testing"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
)
// DaprGRPCClient returns an unauthenticated gRPC client for Dapr whose
// connection will be closed on test cleanup.
func DaprGRPCClient(t *testing.T, ctx context.Context, port int) rtv1.DaprClient {
t.Helper()
conn, err := grpc.DialContext(ctx, "localhost:"+strconv.Itoa(port),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
require.NoError(t, err)
t.Cleanup(func() {
require.NoError(t, conn.Close())
})
return rtv1.NewDaprClient(conn)
}
|
mikeee/dapr
|
tests/integration/framework/util/grpc.go
|
GO
|
mit
| 1,250 |
/*
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 util
import (
"net/http"
"testing"
"time"
)
// HTTPClient returns a Go http.Client which has a default timeout of 10
// seconds, and separate connection pool to the default allowing tests to be
// properly isolated when running in parallel.
// The returned client will call CloseIdleConnections on test cleanup.
func HTTPClient(t *testing.T) *http.Client {
client := &http.Client{
Timeout: time.Second * 10,
Transport: http.DefaultTransport.(*http.Transport).Clone(),
}
t.Cleanup(client.CloseIdleConnections)
return client
}
|
mikeee/dapr
|
tests/integration/framework/util/http.go
|
GO
|
mit
| 1,110 |
/*
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 util
import (
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
rtpbv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
)
type metaResponse struct {
Components []*rtpbv1.RegisteredComponents `json:"components,omitempty"`
}
func GetMetaComponents(t require.TestingT, ctx context.Context, client *http.Client, port int) []*rtpbv1.RegisteredComponents {
return getMeta(t, ctx, client, port).Components
}
func getMeta(t require.TestingT, ctx context.Context, client *http.Client, port int) metaResponse {
metaURL := fmt.Sprintf("http://localhost:%d/v1.0/metadata", port)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, metaURL, nil)
require.NoError(t, err)
var meta metaResponse
resp, err := client.Do(req)
//nolint:testifylint
if assert.NoError(t, err) {
defer resp.Body.Close()
//nolint:testifylint
assert.NoError(t, json.NewDecoder(resp.Body).Decode(&meta))
}
return meta
}
|
mikeee/dapr
|
tests/integration/framework/util/meta.go
|
GO
|
mit
| 1,550 |
/*
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 util
import (
"os"
"strconv"
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// ParallelTest is a helper for running tests in parallel without having to
// create new Go test functions.
type ParallelTest struct {
lock sync.Mutex
fns []func(*assert.CollectT)
}
// NewParallel creates a new ParallelTest.
// Tests are executed during given test's cleanup.
func NewParallel(t *testing.T, fns ...func(*assert.CollectT)) *ParallelTest {
p := &ParallelTest{
fns: fns,
}
t.Cleanup(func() {
p.lock.Lock()
defer p.lock.Unlock()
t.Helper()
jobs := make(chan func(), len(p.fns))
workers := 5
wrokersStr, ok := os.LookupEnv("DAPR_INTEGRATION_PARALLEL_WORKERS")
if ok {
var err error
workers, err = strconv.Atoi(wrokersStr)
require.NoError(t, err)
}
for i := 0; i < workers; i++ {
go p.worker(jobs)
}
collects := make([]*assert.CollectT, len(p.fns))
var wg sync.WaitGroup
wg.Add(len(p.fns))
for i := range p.fns {
i := i
collects[i] = new(assert.CollectT)
jobs <- func() {
defer wg.Done()
defer recover()
p.fns[i](collects[i])
}
}
wg.Wait()
close(jobs)
})
return p
}
func (p *ParallelTest) worker(jobs <-chan func()) {
for j := range jobs {
j()
}
}
// Add adds a test function to be executed in parallel.
func (p *ParallelTest) Add(fn func(*assert.CollectT)) {
p.lock.Lock()
defer p.lock.Unlock()
p.fns = append(p.fns, fn)
}
|
mikeee/dapr
|
tests/integration/framework/util/parallel.go
|
GO
|
mit
| 2,034 |
/*
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 util
import (
"crypto/rand"
"math/big"
"testing"
"github.com/stretchr/testify/require"
)
// RandomString generates a random string of length n.
func RandomString(t *testing.T, n int) string {
t.Helper()
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
bytes := make([]byte, n)
_, err := rand.Read(bytes)
require.NoError(t, err)
for i := range bytes {
j, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters))))
require.NoError(t, err)
bytes[i] = letters[j.Int64()]
}
return string(bytes)
}
|
mikeee/dapr
|
tests/integration/framework/util/rand.go
|
GO
|
mit
| 1,120 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package integration
import (
_ "github.com/dapr/dapr/tests/integration/suite/actors"
_ "github.com/dapr/dapr/tests/integration/suite/daprd"
_ "github.com/dapr/dapr/tests/integration/suite/healthz"
_ "github.com/dapr/dapr/tests/integration/suite/operator"
_ "github.com/dapr/dapr/tests/integration/suite/placement"
_ "github.com/dapr/dapr/tests/integration/suite/ports"
_ "github.com/dapr/dapr/tests/integration/suite/sentry"
)
|
mikeee/dapr
|
tests/integration/import.go
|
GO
|
mit
| 996 |
/*
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 integration
import (
"context"
"flag"
"regexp"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/binary"
"github.com/dapr/dapr/tests/integration/suite"
)
var (
focusF = flag.String("focus", ".*", "Focus on specific test cases. Accepts regex.")
parallelFlag = flag.Bool("integration-parallel", true, "Disable running integration tests in parallel")
)
func RunIntegrationTests(t *testing.T) {
flag.Parse()
focus, err := regexp.Compile(*focusF)
require.NoError(t, err, "Invalid parameter focus")
t.Logf("running test suite with focus: %s", *focusF)
var binFailed bool
t.Run("build binaries", func(t *testing.T) {
t.Cleanup(func() {
binFailed = t.Failed()
})
binary.BuildAll(t)
})
require.False(t, binFailed, "building binaries must succeed")
focusedTests := make([]suite.NamedCase, 0)
for _, tcase := range suite.All(t) {
// Continue rather than using `t.Skip` to reduce the noise in the test
// output.
if !focus.MatchString(tcase.Name()) {
t.Logf("skipping test case due to focus %s", tcase.Name())
continue
}
focusedTests = append(focusedTests, tcase)
}
startTime := time.Now()
t.Cleanup(func() {
t.Logf("Total integration test execution time: [%d] %s", len(focusedTests), time.Since(startTime).Truncate(time.Millisecond*100))
})
for _, tcase := range focusedTests {
tcase := tcase
t.Run(tcase.Name(), func(t *testing.T) {
if *parallelFlag {
t.Parallel()
}
options := tcase.Setup(t)
t.Logf("setting up test case")
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
t.Cleanup(cancel)
framework.Run(t, ctx, options...)
t.Run("run", func(t *testing.T) {
t.Log("running test case")
tcase.Run(t, ctx)
})
})
}
}
|
mikeee/dapr
|
tests/integration/integration.go
|
GO
|
mit
| 2,422 |
//go:build integration
// +build integration
/*
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 integration
import (
"testing"
)
func Test_Integration(t *testing.T) {
RunIntegrationTests(t)
}
|
mikeee/dapr
|
tests/integration/integration_test.go
|
GO
|
mit
| 715 |
/*
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 actors
import (
_ "github.com/dapr/dapr/tests/integration/suite/actors/grpc"
_ "github.com/dapr/dapr/tests/integration/suite/actors/healthz"
_ "github.com/dapr/dapr/tests/integration/suite/actors/http"
_ "github.com/dapr/dapr/tests/integration/suite/actors/metadata"
_ "github.com/dapr/dapr/tests/integration/suite/actors/reminders"
_ "github.com/dapr/dapr/tests/integration/suite/actors/reminders/serialization"
)
|
mikeee/dapr
|
tests/integration/suite/actors/actors.go
|
GO
|
mit
| 991 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package grpc
import (
"context"
"net/http"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/protobuf/types/known/anypb"
"github.com/dapr/components-contrib/state"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/placement"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(ttl))
}
type ttl struct {
daprd *daprd.Daprd
place *placement.Placement
}
func (l *ttl) Setup(t *testing.T) []framework.Option {
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: actorstatettl
spec:
features:
- name: ActorStateTTL
enabled: true
`), 0o600))
handler := http.NewServeMux()
handler.HandleFunc("/dapr/config", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"entities": ["myactortype"]}`))
})
handler.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`OK`))
})
srv := prochttp.New(t, prochttp.WithHandler(handler))
l.place = placement.New(t)
l.daprd = daprd.New(t,
daprd.WithInMemoryActorStateStore("mystore"),
daprd.WithConfigs(configFile),
daprd.WithPlacementAddresses(l.place.Address()),
daprd.WithAppPort(srv.Port()),
)
return []framework.Option{
framework.WithProcesses(l.place, srv, l.daprd),
}
}
func (l *ttl) Run(t *testing.T, ctx context.Context) {
l.place.WaitUntilRunning(t, ctx)
l.daprd.WaitUntilRunning(t, ctx)
conn, err := grpc.DialContext(ctx, l.daprd.GRPCAddress(), grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock())
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, conn.Close()) })
client := rtv1.NewDaprClient(conn)
assert.EventuallyWithT(t, func(c *assert.CollectT) {
_, err = client.InvokeActor(ctx, &rtv1.InvokeActorRequest{
ActorType: "myactortype",
ActorId: "myactorid",
Method: "foo",
})
//nolint:testifylint
assert.NoError(c, err)
}, time.Second*20, time.Millisecond*10, "actor not ready")
now := time.Now()
_, err = client.ExecuteActorStateTransaction(ctx, &rtv1.ExecuteActorStateTransactionRequest{
ActorType: "myactortype",
ActorId: "myactorid",
Operations: []*rtv1.TransactionalActorStateOperation{
{
OperationType: string(state.OperationUpsert),
Key: "mykey",
Value: &anypb.Any{Value: []byte("myvalue")},
Metadata: map[string]string{
"ttlInSeconds": "2",
},
},
},
})
require.NoError(t, err)
t.Run("ensure the state key returns a ttlExpireTime", func(t *testing.T) {
var resp *rtv1.GetActorStateResponse
resp, err = client.GetActorState(ctx, &rtv1.GetActorStateRequest{
ActorType: "myactortype", ActorId: "myactorid", Key: "mykey",
})
require.NoError(t, err)
assert.Equal(t, "myvalue", string(resp.GetData()))
ttlExpireTimeStr, ok := resp.GetMetadata()["ttlExpireTime"]
require.True(t, ok)
var ttlExpireTime time.Time
ttlExpireTime, err = time.Parse(time.RFC3339, ttlExpireTimeStr)
require.NoError(t, err)
assert.InDelta(t, now.Add(2*time.Second).Unix(), ttlExpireTime.Unix(), 1)
})
t.Run("can update ttl with new value", func(t *testing.T) {
_, err = client.ExecuteActorStateTransaction(ctx, &rtv1.ExecuteActorStateTransactionRequest{
ActorType: "myactortype",
ActorId: "myactorid",
Operations: []*rtv1.TransactionalActorStateOperation{
{
OperationType: string(state.OperationUpsert),
Key: "mykey",
Value: &anypb.Any{Value: []byte("myvalue")},
Metadata: map[string]string{
"ttlInSeconds": "3",
},
},
},
})
require.NoError(t, err)
time.Sleep(time.Second * 1)
var resp *rtv1.GetActorStateResponse
resp, err = client.GetActorState(ctx, &rtv1.GetActorStateRequest{
ActorType: "myactortype", ActorId: "myactorid", Key: "mykey",
})
require.NoError(t, err)
assert.Equal(t, "myvalue", string(resp.GetData()))
})
t.Run("ensure the state key is deleted after the ttl", func(t *testing.T) {
assert.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetActorState(ctx, &rtv1.GetActorStateRequest{
ActorType: "myactortype",
ActorId: "myactorid",
Key: "mykey",
})
require.NoError(c, err)
assert.Empty(c, resp.GetData())
assert.Empty(c, resp.GetMetadata())
}, 5*time.Second, 10*time.Millisecond)
})
}
|
mikeee/dapr
|
tests/integration/suite/actors/grpc/ttl.go
|
GO
|
mit
| 5,461 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package healthz
import (
"context"
"fmt"
"io"
"log"
"net/http"
"strconv"
"testing"
"time"
chi "github.com/go-chi/chi/v5"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/placement"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(deactivateOnPlacementFail))
}
// deactivateOnPlacementFail ensures that all active actors are deactivated if the connection with Placement fails.
type deactivateOnPlacementFail struct {
daprd *daprd.Daprd
place *placement.Placement
invokedActorsCh chan string
deactivatedActorsCh chan string
}
func (h *deactivateOnPlacementFail) Setup(t *testing.T) []framework.Option {
h.invokedActorsCh = make(chan string, 2)
h.deactivatedActorsCh = make(chan string, 2)
r := chi.NewRouter()
r.Get("/dapr/config", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"entities": ["myactortype"]}`))
})
r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
r.Delete("/actors/{actorType}/{actorId}", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
act := fmt.Sprintf("%s/%s", chi.URLParam(r, "actorType"), chi.URLParam(r, "actorId"))
log.Printf("Received deactivation for actor %s", act)
h.deactivatedActorsCh <- act
})
r.Put("/actors/{actorType}/{actorId}/method/foo", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`bar`))
act := fmt.Sprintf("%s/%s", chi.URLParam(r, "actorType"), chi.URLParam(r, "actorId"))
log.Printf("Received invocation for actor %s", act)
h.invokedActorsCh <- act
})
srv := prochttp.New(t, prochttp.WithHandler(r))
h.place = placement.New(t)
h.daprd = daprd.New(t, daprd.WithResourceFiles(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: mystore
spec:
type: state.in-memory
version: v1
metadata:
- name: actorStateStore
value: true
`),
daprd.WithPlacementAddresses("127.0.0.1:"+strconv.Itoa(h.place.Port())),
daprd.WithAppProtocol("http"),
daprd.WithAppPort(srv.Port()),
)
return []framework.Option{
framework.WithProcesses(h.place, srv, h.daprd),
}
}
func (h *deactivateOnPlacementFail) Run(t *testing.T, ctx context.Context) {
h.place.WaitUntilRunning(t, ctx)
h.daprd.WaitUntilRunning(t, ctx)
client := util.HTTPClient(t)
// Activate 2 actors
for i := 0; i < 2; i++ {
assert.EventuallyWithT(t, func(t *assert.CollectT) {
daprdURL := fmt.Sprintf("http://localhost:%d/v1.0/actors/myactortype/myactor%d/method/foo", h.daprd.HTTPPort(), i)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, daprdURL, nil)
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equalf(t, http.StatusOK, resp.StatusCode, "Response body: %v", string(body))
}, 10*time.Second, 10*time.Millisecond, "actor not ready")
}
// Validate invocations
invoked := make([]string, 2)
for i := 0; i < 2; i++ {
select {
case invoked[i] = <-h.invokedActorsCh:
case <-time.After(time.Second * 5):
assert.Fail(t, "failed to invoke actor in time")
}
}
assert.ElementsMatch(t, []string{"myactortype/myactor0", "myactortype/myactor1"}, invoked)
// Terminate the placement process to simulate a failure
h.place.Cleanup(t)
// Ensure actors get deactivated
deactivated := make([]string, 2)
for i := range deactivated {
select {
case deactivated[i] = <-h.deactivatedActorsCh:
case <-time.After(5 * time.Second):
assert.Fail(t, "Did not receive deactivation signal in time")
}
}
assert.ElementsMatch(t, []string{"myactortype/myactor0", "myactortype/myactor1"}, deactivated)
}
|
mikeee/dapr
|
tests/integration/suite/actors/healthz/deactivate-on-placement-fail.go
|
GO
|
mit
| 4,621 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or impliea.
See the License for the specific language governing permissions and
limitations under the License.
*/
package endpoint
import (
"context"
"net/http"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/placement"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
const (
pathMethodFoo = "/actors/myactortype/myactorid/method/foo"
)
func init() {
suite.Register(new(allenabled))
}
// allenabled ensures that the daprd `/healthz` endpoint is called and actors
// will respond successfully when invoked when both app health check and
// entities are enabled.
type allenabled struct {
daprd *daprd.Daprd
place *placement.Placement
healthzCalled chan struct{}
rootCalled atomic.Bool
}
func (a *allenabled) Setup(t *testing.T) []framework.Option {
a.healthzCalled = make(chan struct{})
var once sync.Once
srv := prochttp.New(t,
prochttp.WithHandlerFunc("/dapr/config", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"entities": ["myactortype"]}`))
}),
prochttp.WithHandlerFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
once.Do(func() {
close(a.healthzCalled)
})
}),
prochttp.WithHandlerFunc(pathMethodFoo, func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`OK`))
}),
prochttp.WithHandlerFunc("/", func(w http.ResponseWriter, r *http.Request) {
a.rootCalled.Store(true)
w.WriteHeader(http.StatusInternalServerError)
}),
)
a.place = placement.New(t)
a.daprd = daprd.New(t,
daprd.WithInMemoryActorStateStore("mystore"),
daprd.WithPlacementAddresses(a.place.Address()),
daprd.WithAppProtocol("http"),
daprd.WithAppPort(srv.Port()),
daprd.WithAppHealthCheck(true),
)
return []framework.Option{
framework.WithProcesses(a.place, srv, a.daprd),
}
}
func (a *allenabled) Run(t *testing.T, ctx context.Context) {
a.place.WaitUntilRunning(t, ctx)
a.daprd.WaitUntilRunning(t, ctx)
gclient := a.daprd.GRPCClient(t, ctx)
assert.EventuallyWithT(t, func(c *assert.CollectT) {
meta, err := gclient.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
//nolint:testifylint
assert.NoError(c, err)
assert.True(c, meta.GetActorRuntime().GetHostReady())
assert.Len(c, meta.GetActorRuntime().GetActiveActors(), 1)
assert.Equal(c, rtv1.ActorRuntime_RUNNING, meta.GetActorRuntime().GetRuntimeStatus())
assert.Equal(c, "placement: connected", meta.GetActorRuntime().GetPlacement())
}, time.Second*30, time.Millisecond*10)
select {
case <-a.healthzCalled:
case <-time.After(time.Second * 15):
t.Fatal("timed out waiting for healthz call")
}
client := util.HTTPClient(t)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, fooActorURL(a.daprd), nil)
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
require.NoError(t, resp.Body.Close())
}
func fooActorURL(daprd *daprd.Daprd) string {
return "http://127.0.0.1:" + strconv.Itoa(daprd.HTTPPort()) + "/v1.0" + pathMethodFoo
}
|
mikeee/dapr
|
tests/integration/suite/actors/healthz/endpoint/allenabled.go
|
GO
|
mit
| 3,925 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implien.
See the License for the specific language governing permissions and
limitations under the License.
*/
package endpoint
import (
"context"
"net/http"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/placement"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(noapp))
}
// noapp ensures that the daprd `/healthz` endpoint is called and actors
// will respond successfully when invoked, even when the app health checks is
// disabled but entities have been defined.
type noapp struct {
daprd *daprd.Daprd
place *placement.Placement
healthzCalled chan struct{}
rootCalled atomic.Bool
}
func (n *noapp) Setup(t *testing.T) []framework.Option {
n.healthzCalled = make(chan struct{})
var once sync.Once
srv := prochttp.New(t,
prochttp.WithHandlerFunc("/dapr/config", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"entities": ["myactortype"]}`))
}),
prochttp.WithHandlerFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
once.Do(func() {
close(n.healthzCalled)
})
}),
prochttp.WithHandlerFunc(pathMethodFoo, func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`OK`))
}),
prochttp.WithHandlerFunc("/", func(w http.ResponseWriter, r *http.Request) {
n.rootCalled.Store(true)
w.WriteHeader(http.StatusInternalServerError)
}),
)
n.place = placement.New(t)
n.daprd = daprd.New(t,
daprd.WithInMemoryActorStateStore("mystore"),
daprd.WithPlacementAddresses(n.place.Address()),
daprd.WithAppProtocol("http"),
daprd.WithAppPort(srv.Port()),
daprd.WithAppHealthCheck(false),
)
return []framework.Option{
framework.WithProcesses(n.place, srv, n.daprd),
}
}
func (n *noapp) Run(t *testing.T, ctx context.Context) {
n.place.WaitUntilRunning(t, ctx)
n.daprd.WaitUntilTCPReady(t, ctx)
gclient := n.daprd.GRPCClient(t, ctx)
assert.EventuallyWithT(t, func(c *assert.CollectT) {
meta, err := gclient.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
//nolint:testifylint
assert.NoError(c, err)
assert.True(c, meta.GetActorRuntime().GetHostReady())
assert.Len(c, meta.GetActorRuntime().GetActiveActors(), 1)
assert.Equal(c, rtv1.ActorRuntime_RUNNING, meta.GetActorRuntime().GetRuntimeStatus())
assert.Equal(c, "placement: connected", meta.GetActorRuntime().GetPlacement())
}, time.Second*30, time.Millisecond*10)
select {
case <-n.healthzCalled:
case <-time.After(time.Second * 15):
t.Fatal("timed out waiting for healthz call")
}
client := util.HTTPClient(t)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, fooActorURL(n.daprd), nil)
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
require.NoError(t, resp.Body.Close())
assert.False(t, n.rootCalled.Load())
}
|
mikeee/dapr
|
tests/integration/suite/actors/healthz/endpoint/noapp.go
|
GO
|
mit
| 3,747 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implien.
See the License for the specific language governing permissions and
limitations under the License.
*/
package endpoint
import (
"context"
"net/http"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/placement"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(noappentities))
}
// noappentities ensures that actors work even though no entities have been
// defined and the app healthchecks is disabled.
type noappentities struct {
daprdNoHealthz *daprd.Daprd
daprd *daprd.Daprd
place *placement.Placement
healthzCalled chan struct{}
noHealthzCalled chan struct{}
}
func (n *noappentities) Setup(t *testing.T) []framework.Option {
n.healthzCalled = make(chan struct{})
n.noHealthzCalled = make(chan struct{})
n.place = placement.New(t)
var onceHealthz, onceNoHealthz sync.Once
srvHealthz := prochttp.New(t,
prochttp.WithHandlerFunc("/dapr/config", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"entities": ["myactortype"]}`))
}),
prochttp.WithHandlerFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
onceHealthz.Do(func() {
close(n.healthzCalled)
})
}),
prochttp.WithHandlerFunc(pathMethodFoo, func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`OK`))
}),
)
srvNoHealthz := prochttp.New(t,
prochttp.WithHandlerFunc("/dapr/config", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{}`))
}),
prochttp.WithHandlerFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
onceNoHealthz.Do(func() {
close(n.noHealthzCalled)
})
}),
)
n.daprd = daprd.New(t,
daprd.WithInMemoryActorStateStore("mystore"),
daprd.WithPlacementAddresses(n.place.Address()),
daprd.WithAppProtocol("http"),
daprd.WithAppPort(srvHealthz.Port()),
daprd.WithAppHealthCheck(true),
)
n.daprdNoHealthz = daprd.New(t,
daprd.WithInMemoryActorStateStore("mystore"),
daprd.WithPlacementAddresses(n.place.Address()),
daprd.WithAppProtocol("http"),
daprd.WithAppPort(srvNoHealthz.Port()),
daprd.WithAppHealthCheck(false),
)
return []framework.Option{
framework.WithProcesses(n.place, srvHealthz, srvNoHealthz, n.daprd, n.daprdNoHealthz),
}
}
func (n *noappentities) Run(t *testing.T, ctx context.Context) {
n.place.WaitUntilRunning(t, ctx)
n.daprd.WaitUntilAppHealth(t, ctx)
n.daprdNoHealthz.WaitUntilAppHealth(t, ctx)
for _, tv := range []struct {
cl rtv1.DaprClient
activeActors []*rtv1.ActiveActorsCount
}{
{cl: n.daprd.GRPCClient(t, ctx), activeActors: []*rtv1.ActiveActorsCount{{Type: "myactortype"}}},
{cl: n.daprdNoHealthz.GRPCClient(t, ctx), activeActors: nil},
} {
assert.EventuallyWithT(t, func(c *assert.CollectT) {
meta, err := tv.cl.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
//nolint:testifylint
assert.NoError(c, err)
assert.True(c, meta.GetActorRuntime().GetHostReady())
assert.Equal(c, tv.activeActors, meta.GetActorRuntime().GetActiveActors())
assert.Equal(c, rtv1.ActorRuntime_RUNNING, meta.GetActorRuntime().GetRuntimeStatus())
assert.Equal(c, "placement: connected", meta.GetActorRuntime().GetPlacement())
}, time.Second*30, time.Millisecond*10)
}
select {
case <-n.healthzCalled:
case <-time.After(time.Second * 15):
assert.Fail(t, "timed out waiting for healthz call")
}
client := util.HTTPClient(t)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, fooActorURL(n.daprd), nil)
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
require.NoError(t, resp.Body.Close())
select {
case <-n.noHealthzCalled:
assert.Fail(t, "healthz on health disabled and empty entities should not be called")
default:
}
meta, err := n.daprd.GRPCClient(t, ctx).GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.True(t, meta.GetActorRuntime().GetHostReady())
assert.Len(t, meta.GetActorRuntime().GetActiveActors(), 1)
assert.Equal(t, rtv1.ActorRuntime_RUNNING, meta.GetActorRuntime().GetRuntimeStatus())
assert.Equal(t, "placement: connected", meta.GetActorRuntime().GetPlacement())
}
|
mikeee/dapr
|
tests/integration/suite/actors/healthz/endpoint/noappentities.go
|
GO
|
mit
| 5,096 |
/*
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 implien.
See the License for the specific language governing permissions and
limitations under the License.
*/
package endpoint
import (
"context"
"net/http"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/placement"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(noentities))
}
// noentities ensures that the daprd `/healthz` endpoint is called and actors
// will respond successfully when invoked, even when the app healthz endpoint
// is enabled but no entities have been defined.
type noentities struct {
daprd *daprd.Daprd
daprdWithEntities *daprd.Daprd
place *placement.Placement
healthzCalled chan struct{}
}
func (n *noentities) Setup(t *testing.T) []framework.Option {
n.healthzCalled = make(chan struct{})
var once sync.Once
srvNoEntities := prochttp.New(t,
prochttp.WithHandlerFunc("/dapr/config", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{}`))
}),
prochttp.WithHandlerFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
once.Do(func() {
close(n.healthzCalled)
})
}),
)
srvWithEntities := prochttp.New(t,
prochttp.WithHandlerFunc("/dapr/config", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"entities": ["myactortype"]}`))
}),
prochttp.WithHandlerFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}),
prochttp.WithHandlerFunc(pathMethodFoo, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}),
)
n.place = placement.New(t)
n.daprd = daprd.New(t,
daprd.WithInMemoryActorStateStore("mystore"),
daprd.WithPlacementAddresses(n.place.Address()),
daprd.WithAppProtocol("http"),
daprd.WithAppPort(srvNoEntities.Port()),
daprd.WithAppHealthCheck(true),
)
n.daprdWithEntities = daprd.New(t,
daprd.WithInMemoryActorStateStore("mystore"),
daprd.WithPlacementAddresses(n.place.Address()),
daprd.WithAppProtocol("http"),
daprd.WithAppPort(srvWithEntities.Port()),
daprd.WithAppHealthCheck(true),
)
return []framework.Option{
framework.WithProcesses(n.place, srvNoEntities, srvWithEntities, n.daprd, n.daprdWithEntities),
}
}
func (n *noentities) Run(t *testing.T, ctx context.Context) {
n.place.WaitUntilRunning(t, ctx)
n.daprd.WaitUntilRunning(t, ctx)
n.daprdWithEntities.WaitUntilRunning(t, ctx)
for _, tv := range []struct {
cl rtv1.DaprClient
activeActors []*rtv1.ActiveActorsCount
}{
{cl: n.daprdWithEntities.GRPCClient(t, ctx), activeActors: []*rtv1.ActiveActorsCount{{Type: "myactortype"}}},
{cl: n.daprd.GRPCClient(t, ctx), activeActors: nil},
} {
assert.EventuallyWithT(t, func(c *assert.CollectT) {
meta, err := tv.cl.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
//nolint:testifylint
assert.NoError(c, err)
assert.True(c, meta.GetActorRuntime().GetHostReady())
assert.Equal(c, tv.activeActors, meta.GetActorRuntime().GetActiveActors())
assert.Equal(c, rtv1.ActorRuntime_RUNNING, meta.GetActorRuntime().GetRuntimeStatus())
assert.Equal(c, "placement: connected", meta.GetActorRuntime().GetPlacement())
}, time.Second*30, time.Millisecond*10)
}
select {
case <-n.healthzCalled:
case <-time.After(time.Second * 15):
t.Fatal("timed out waiting for healthz call")
}
client := util.HTTPClient(t)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, fooActorURL(n.daprd), nil)
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
require.NoError(t, resp.Body.Close())
}
|
mikeee/dapr
|
tests/integration/suite/actors/healthz/endpoint/noentities.go
|
GO
|
mit
| 4,496 |
/*
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 impliep.
See the License for the specific language governing permissions and
limitations under the License.
*/
package endpoint
import (
"context"
"net/http"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/placement"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(path))
}
// path tests that the healthz endpoint is called when the path is changed.
type path struct {
daprd *daprd.Daprd
place *placement.Placement
healthzCalled chan struct{}
customHealthz chan struct{}
rootCalled atomic.Bool
}
func (p *path) Setup(t *testing.T) []framework.Option {
p.healthzCalled = make(chan struct{})
p.customHealthz = make(chan struct{})
var honce, conce sync.Once
srv := prochttp.New(t,
prochttp.WithHandlerFunc("/dapr/config", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"entities": ["myactortype"]}`))
}),
prochttp.WithHandlerFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
honce.Do(func() {
close(p.healthzCalled)
})
}),
prochttp.WithHandlerFunc("/customhealthz", func(w http.ResponseWriter, r *http.Request) {
conce.Do(func() {
close(p.customHealthz)
})
}),
prochttp.WithHandlerFunc(pathMethodFoo, func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`OK`))
}),
prochttp.WithHandlerFunc("/", func(w http.ResponseWriter, r *http.Request) {
p.rootCalled.Store(true)
w.WriteHeader(http.StatusInternalServerError)
}),
)
p.place = placement.New(t)
p.daprd = daprd.New(t,
daprd.WithInMemoryActorStateStore("mystore"),
daprd.WithPlacementAddresses(p.place.Address()),
daprd.WithAppPort(srv.Port()),
daprd.WithAppHealthCheckPath("/customhealthz"),
daprd.WithAppHealthCheck(true),
daprd.WithAppHealthProbeInterval(1),
daprd.WithAppHealthProbeThreshold(1),
)
return []framework.Option{
framework.WithProcesses(p.place, srv, p.daprd),
}
}
func (p *path) Run(t *testing.T, ctx context.Context) {
p.place.WaitUntilRunning(t, ctx)
p.daprd.WaitUntilRunning(t, ctx)
gclient := p.daprd.GRPCClient(t, ctx)
assert.EventuallyWithT(t, func(c *assert.CollectT) {
meta, err := gclient.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
//nolint:testifylint
assert.NoError(c, err)
assert.True(c, meta.GetActorRuntime().GetHostReady())
assert.Len(c, meta.GetActorRuntime().GetActiveActors(), 1)
assert.Equal(c, rtv1.ActorRuntime_RUNNING, meta.GetActorRuntime().GetRuntimeStatus())
assert.Equal(c, "placement: connected", meta.GetActorRuntime().GetPlacement())
}, time.Second*30, time.Millisecond*10)
select {
case <-p.customHealthz:
case <-time.After(time.Second * 15):
assert.Fail(t, "timed out waiting for healthz call")
}
select {
case <-p.healthzCalled:
case <-time.After(time.Second * 15):
assert.Fail(t, "/healthz endpoint should still have been called for actor health check")
}
client := util.HTTPClient(t)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, fooActorURL(p.daprd), nil)
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
require.NoError(t, resp.Body.Close())
assert.False(t, p.rootCalled.Load())
}
|
mikeee/dapr
|
tests/integration/suite/actors/healthz/endpoint/path.go
|
GO
|
mit
| 4,089 |
/*
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 impliei.
See the License for the specific language governing permissions and
limitations under the License.
*/
package healthz
import (
_ "github.com/dapr/dapr/tests/integration/suite/actors/healthz/endpoint"
)
|
mikeee/dapr
|
tests/integration/suite/actors/healthz/healthz.go
|
GO
|
mit
| 663 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or impliei.
See the License for the specific language governing permissions and
limitations under the License.
*/
package healthz
import (
"context"
"net/http"
"strconv"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/placement"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(initerror))
}
// initerror tests that Daprd will block actor calls until actors have been
// initialized.
type initerror struct {
daprd *daprd.Daprd
place *placement.Placement
configCalled chan struct{}
blockConfig chan struct{}
healthzCalled chan struct{}
}
func (i *initerror) Setup(t *testing.T) []framework.Option {
i.configCalled = make(chan struct{})
i.blockConfig = make(chan struct{})
i.healthzCalled = make(chan struct{})
var once sync.Once
handler := http.NewServeMux()
handler.HandleFunc("/dapr/config", func(w http.ResponseWriter, r *http.Request) {
close(i.configCalled)
<-i.blockConfig
w.Write([]byte(`{"entities": ["myactortype"]}`))
})
handler.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
once.Do(func() {
close(i.healthzCalled)
})
})
handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`OK`))
})
srv := prochttp.New(t, prochttp.WithHandler(handler))
i.place = placement.New(t)
i.daprd = daprd.New(t,
daprd.WithInMemoryActorStateStore("mystore"),
daprd.WithPlacementAddresses(i.place.Address()),
daprd.WithAppPort(srv.Port()),
)
return []framework.Option{
framework.WithProcesses(i.place, srv, i.daprd),
}
}
func (i *initerror) Run(t *testing.T, ctx context.Context) {
i.place.WaitUntilRunning(t, ctx)
i.daprd.WaitUntilTCPReady(t, ctx)
client := util.HTTPClient(t)
select {
case <-i.configCalled:
case <-time.After(time.Second * 5):
t.Fatal("timed out waiting for config call")
}
rctx, cancel := context.WithTimeout(ctx, time.Second*2)
t.Cleanup(cancel)
daprdURL := "http://127.0.0.1:" + strconv.Itoa(i.daprd.HTTPPort()) + "/v1.0/actors/myactortype/myactorid/method/foo"
req, err := http.NewRequestWithContext(rctx, http.MethodPost, daprdURL, nil)
require.NoError(t, err)
resp, err := client.Do(req)
require.ErrorIs(t, err, context.DeadlineExceeded)
if resp != nil && resp.Body != nil {
require.NoError(t, resp.Body.Close())
}
meta, err := i.daprd.GRPCClient(t, ctx).GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Empty(t, meta.GetActorRuntime().GetActiveActors())
assert.Equal(t, rtv1.ActorRuntime_INITIALIZING, meta.GetActorRuntime().GetRuntimeStatus())
close(i.blockConfig)
select {
case <-i.healthzCalled:
case <-time.After(time.Second * 15):
assert.Fail(t, "timed out waiting for healthz call")
}
req, err = http.NewRequestWithContext(ctx, http.MethodPost, daprdURL, nil)
require.NoError(t, err)
resp, err = client.Do(req)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
require.NoError(t, resp.Body.Close())
meta, err = i.daprd.GRPCClient(t, ctx).GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
if assert.Len(t, meta.GetActorRuntime().GetActiveActors(), 1) {
assert.Equal(t, "myactortype", meta.GetActorRuntime().GetActiveActors()[0].GetType())
}
assert.Equal(t, rtv1.ActorRuntime_RUNNING, meta.GetActorRuntime().GetRuntimeStatus())
}
|
mikeee/dapr
|
tests/integration/suite/actors/healthz/initerror.go
|
GO
|
mit
| 4,231 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package http
import (
"context"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/placement"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(ttl))
}
type ttl struct {
daprd *daprd.Daprd
place *placement.Placement
healthzCalled chan struct{}
}
func (l *ttl) Setup(t *testing.T) []framework.Option {
l.healthzCalled = make(chan struct{})
var once sync.Once
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: actorstatettl
spec:
features:
- name: ActorStateTTL
enabled: true
`), 0o600))
handler := http.NewServeMux()
handler.HandleFunc("/dapr/config", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"entities": ["myactortype"]}`))
})
handler.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
once.Do(func() {
close(l.healthzCalled)
})
w.WriteHeader(http.StatusOK)
})
handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`OK`))
})
srv := prochttp.New(t, prochttp.WithHandler(handler))
l.place = placement.New(t)
l.daprd = daprd.New(t,
daprd.WithInMemoryActorStateStore("mystore"),
daprd.WithConfigs(configFile),
daprd.WithPlacementAddresses(l.place.Address()),
daprd.WithAppPort(srv.Port()),
)
return []framework.Option{
framework.WithProcesses(l.place, srv, l.daprd),
}
}
func (l *ttl) Run(t *testing.T, ctx context.Context) {
l.place.WaitUntilRunning(t, ctx)
l.daprd.WaitUntilRunning(t, ctx)
select {
case <-l.healthzCalled:
case <-time.After(time.Second * 15):
t.Fatal("timed out waiting for healthz call")
}
client := util.HTTPClient(t)
daprdURL := "http://localhost:" + strconv.Itoa(l.daprd.HTTPPort())
req, err := http.NewRequest(http.MethodPost, daprdURL+"/v1.0/actors/myactortype/myactorid/method/foo", nil)
require.NoError(t, err)
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, rErr := client.Do(req)
//nolint:testifylint
if assert.NoError(c, rErr) {
require.NoError(c, resp.Body.Close())
assert.Equal(c, http.StatusOK, resp.StatusCode)
}
}, time.Second*20, time.Millisecond*10, "actor not ready")
now := time.Now()
reqBody := `[{"operation":"upsert","request":{"key":"key1","value":"value1","metadata":{"ttlInSeconds":"2"}}}]`
req, err = http.NewRequest(http.MethodPost, daprdURL+"/v1.0/actors/myactortype/myactorid/state", strings.NewReader(reqBody))
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
t.Run("ensure the state key returns a ttlExpireTime header", func(t *testing.T) {
req, err = http.NewRequest(http.MethodGet, daprdURL+"/v1.0/actors/myactortype/myactorid/state/key1", nil)
require.NoError(t, err)
//nolint:bodyclose
resp, err = client.Do(req)
require.NoError(t, err)
var body []byte
body, err = io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, `"value1"`, string(body))
ttlExpireTimeStr := resp.Header.Get("metadata.ttlExpireTime")
var ttlExpireTime time.Time
ttlExpireTime, err = time.Parse(time.RFC3339, ttlExpireTimeStr)
require.NoError(t, err)
assert.InDelta(t, now.Add(2*time.Second).Unix(), ttlExpireTime.Unix(), 1)
})
t.Run("can update ttl with new value", func(t *testing.T) {
reqBody = `[{"operation":"upsert","request":{"key":"key1","value":"value1","metadata":{"ttlInSeconds":"3"}}}]`
req, err = http.NewRequest(http.MethodPost, daprdURL+"/v1.0/actors/myactortype/myactorid/state", strings.NewReader(reqBody))
require.NoError(t, err)
//nolint:bodyclose
resp, err = client.Do(req)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
time.Sleep(time.Second * 2)
req, err = http.NewRequest(http.MethodGet, daprdURL+"/v1.0/actors/myactortype/myactorid/state/key1", nil)
require.NoError(t, err)
//nolint:bodyclose
resp, err = client.Do(req)
require.NoError(t, err)
var body []byte
body, err = io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, `"value1"`, string(body))
})
t.Run("ensure the state key is deleted after the ttl", func(t *testing.T) {
assert.EventuallyWithT(t, func(c *assert.CollectT) {
req, err = http.NewRequest(http.MethodGet, daprdURL+"/v1.0/actors/myactortype/myactorid/state/key1", nil)
require.NoError(c, err)
//nolint:bodyclose
resp, err = client.Do(req)
require.NoError(c, err)
var body []byte
body, err = io.ReadAll(resp.Body)
require.NoError(c, err)
require.NoError(c, resp.Body.Close())
assert.Empty(c, string(body))
assert.Equal(c, http.StatusNoContent, resp.StatusCode)
}, 5*time.Second, 10*time.Millisecond)
})
}
|
mikeee/dapr
|
tests/integration/suite/actors/http/ttl.go
|
GO
|
mit
| 5,908 |
/*
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 metadata
import (
"context"
"net/http"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/placement"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(client))
}
// client tests the response of the metadata API for a healthy actor client.
type client struct {
daprd *daprd.Daprd
place *placement.Placement
blockConfig chan struct{}
}
func (m *client) Setup(t *testing.T) []framework.Option {
m.blockConfig = make(chan struct{})
handler := http.NewServeMux()
handler.HandleFunc("/dapr/config", func(w http.ResponseWriter, r *http.Request) {
<-m.blockConfig
w.Write([]byte(`{"entities": []}`))
})
handler.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
srv := prochttp.New(t, prochttp.WithHandler(handler))
m.place = placement.New(t)
m.daprd = daprd.New(t,
daprd.WithPlacementAddresses(m.place.Address()),
daprd.WithAppProtocol("http"),
daprd.WithAppPort(srv.Port()),
daprd.WithLogLevel("info"), // Daprd is super noisy in debug mode when connecting to placement.
)
return []framework.Option{
framework.WithProcesses(m.place, srv, m.daprd),
}
}
func (m *client) Run(t *testing.T, ctx context.Context) {
// Test an app that is an actor client (no actor state store configured)
// 1. Assert that status is "INITIALIZING" before /dapr/config is called
// 2. After init is done, status is "RUNNING", hostReady is "false", placement reports a connection, and hosted actors are empty
m.place.WaitUntilRunning(t, ctx)
m.daprd.WaitUntilTCPReady(t, ctx)
client := util.HTTPClient(t)
// Before initialization
res := getMetadata(t, ctx, client, m.daprd.HTTPPort())
require.False(t, t.Failed())
assert.Equal(t, "INITIALIZING", res.ActorRuntime.RuntimeStatus)
assert.False(t, res.ActorRuntime.HostReady)
assert.Empty(t, res.ActorRuntime.Placement)
assert.Empty(t, res.ActorRuntime.ActiveActors)
// Complete init
close(m.blockConfig)
assert.EventuallyWithT(t, func(t *assert.CollectT) {
res := getMetadata(t, ctx, client, m.daprd.HTTPPort())
assert.Equal(t, "RUNNING", res.ActorRuntime.RuntimeStatus)
assert.False(t, res.ActorRuntime.HostReady)
assert.Equal(t, "placement: connected", res.ActorRuntime.Placement)
assert.Empty(t, res.ActorRuntime.ActiveActors, 0)
}, 10*time.Second, 10*time.Millisecond)
}
|
mikeee/dapr
|
tests/integration/suite/actors/metadata/client.go
|
GO
|
mit
| 3,285 |
/*
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 metadata
import (
"context"
"net/http"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(disabled))
}
// disabled tests the response of the metadata API when the actor runtime is disabled
type disabled struct {
daprd *daprd.Daprd
}
func (m *disabled) Setup(t *testing.T) []framework.Option {
handler := http.NewServeMux()
handler.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
srv := prochttp.New(t, prochttp.WithHandler(handler))
m.daprd = daprd.New(t, // "WithPlacementAddress" is missing on purpose, to disable the actor runtime
daprd.WithInMemoryActorStateStore("mystore"),
daprd.WithAppProtocol("http"),
daprd.WithAppPort(srv.Port()),
daprd.WithLogLevel("info"), // Daprd is super noisy in debug mode when connecting to placement.
)
return []framework.Option{
framework.WithProcesses(srv, m.daprd),
}
}
func (m *disabled) Run(t *testing.T, ctx context.Context) {
// Test an app that has the actor runtime disabled (when there's no placement address)
m.daprd.WaitUntilTCPReady(t, ctx)
client := util.HTTPClient(t)
assert.EventuallyWithT(t, func(t *assert.CollectT) {
res := getMetadata(t, ctx, client, m.daprd.HTTPPort())
assert.Equal(t, "DISABLED", res.ActorRuntime.RuntimeStatus)
assert.False(t, res.ActorRuntime.HostReady)
assert.Empty(t, res.ActorRuntime.Placement)
assert.Empty(t, res.ActorRuntime.ActiveActors)
}, 10*time.Second, 10*time.Millisecond)
}
|
mikeee/dapr
|
tests/integration/suite/actors/metadata/disabled.go
|
GO
|
mit
| 2,377 |
/*
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 metadata
import (
"context"
"net/http"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/placement"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(host))
}
// host tests the response of the metadata API for a healthy actor host.
type host struct {
daprd *daprd.Daprd
place *placement.Placement
blockConfig chan struct{}
}
func (m *host) Setup(t *testing.T) []framework.Option {
m.blockConfig = make(chan struct{})
handler := http.NewServeMux()
handler.HandleFunc("/dapr/config", func(w http.ResponseWriter, r *http.Request) {
<-m.blockConfig
w.Write([]byte(`{"entities": ["myactortype"]}`))
})
handler.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`OK`))
})
srv := prochttp.New(t, prochttp.WithHandler(handler))
m.place = placement.New(t)
m.daprd = daprd.New(t,
daprd.WithInMemoryActorStateStore("mystore"),
daprd.WithPlacementAddresses(m.place.Address()),
daprd.WithAppProtocol("http"),
daprd.WithAppPort(srv.Port()),
daprd.WithLogLevel("info"), // Daprd is super noisy in debug mode when connecting to placement.
)
return []framework.Option{
framework.WithProcesses(m.place, srv, m.daprd),
}
}
func (m *host) Run(t *testing.T, ctx context.Context) {
// Test an app that is an actor host
// 1. Assert that status is "INITIALIZING" before /dapr/config is called
// 2. After init is done, status is "RUNNING", hostReady is "true", placement reports a connection, and hosted actors are listed
m.place.WaitUntilRunning(t, ctx)
m.daprd.WaitUntilTCPReady(t, ctx)
client := util.HTTPClient(t)
// Before initialization
res := getMetadata(t, ctx, client, m.daprd.HTTPPort())
require.False(t, t.Failed())
assert.Equal(t, "INITIALIZING", res.ActorRuntime.RuntimeStatus)
assert.False(t, res.ActorRuntime.HostReady)
assert.Empty(t, res.ActorRuntime.Placement)
assert.Empty(t, res.ActorRuntime.ActiveActors)
// Complete init
close(m.blockConfig)
assert.EventuallyWithT(t, func(t *assert.CollectT) {
res := getMetadata(t, ctx, client, m.daprd.HTTPPort())
assert.Equal(t, "RUNNING", res.ActorRuntime.RuntimeStatus)
assert.True(t, res.ActorRuntime.HostReady)
assert.Equal(t, "placement: connected", res.ActorRuntime.Placement)
if assert.Len(t, res.ActorRuntime.ActiveActors, 1) {
assert.Equal(t, "myactortype", res.ActorRuntime.ActiveActors[0].Type)
assert.Equal(t, 0, res.ActorRuntime.ActiveActors[0].Count)
}
}, 10*time.Second, 10*time.Millisecond)
}
|
mikeee/dapr
|
tests/integration/suite/actors/metadata/host.go
|
GO
|
mit
| 3,539 |
/*
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 metadata
import (
"context"
"net/http"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(hostNoPlacement))
}
// hostNoPlacement tests the response of the metadata API for an actor host that isn't connected to Placement.
type hostNoPlacement struct {
daprd *daprd.Daprd
blockConfig chan struct{}
}
func (m *hostNoPlacement) Setup(t *testing.T) []framework.Option {
m.blockConfig = make(chan struct{})
handler := http.NewServeMux()
handler.HandleFunc("/dapr/config", func(w http.ResponseWriter, r *http.Request) {
<-m.blockConfig
w.Write([]byte(`{"entities": ["myactortype"]}`))
})
handler.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
srv := prochttp.New(t, prochttp.WithHandler(handler))
m.daprd = daprd.New(t,
daprd.WithPlacementAddresses("localhost:65500"), // Placement isn't listening on that port
daprd.WithInMemoryActorStateStore("mystore"),
daprd.WithAppProtocol("http"),
daprd.WithAppPort(srv.Port()),
daprd.WithLogLevel("info"), // Daprd is super noisy in debug mode when connecting to placement.
)
return []framework.Option{
framework.WithProcesses(srv, m.daprd),
}
}
func (m *hostNoPlacement) Run(t *testing.T, ctx context.Context) {
// Test an app that is an actor host, but the placement service is not connected
// 1. Assert that status is "INITIALIZING" before /dapr/config is called
// 2. After init is done, status is "RUNNING", hostReady is "false", placement reports no connection, and hosted actors are listed
m.daprd.WaitUntilTCPReady(t, ctx)
client := util.HTTPClient(t)
// Before initialization
res := getMetadata(t, ctx, client, m.daprd.HTTPPort())
require.False(t, t.Failed())
assert.Equal(t, "INITIALIZING", res.ActorRuntime.RuntimeStatus)
assert.False(t, res.ActorRuntime.HostReady)
assert.Empty(t, res.ActorRuntime.Placement)
assert.Empty(t, res.ActorRuntime.ActiveActors)
// Complete init
close(m.blockConfig)
assert.EventuallyWithT(t, func(t *assert.CollectT) {
res := getMetadata(t, ctx, client, m.daprd.HTTPPort())
assert.Equal(t, "RUNNING", res.ActorRuntime.RuntimeStatus)
assert.False(t, res.ActorRuntime.HostReady)
assert.Equal(t, "placement: disconnected", res.ActorRuntime.Placement)
if assert.Len(t, res.ActorRuntime.ActiveActors, 1) {
assert.Equal(t, "myactortype", res.ActorRuntime.ActiveActors[0].Type)
assert.Equal(t, 0, res.ActorRuntime.ActiveActors[0].Count)
}
}, 10*time.Second, 10*time.Millisecond)
}
|
mikeee/dapr
|
tests/integration/suite/actors/metadata/host_noplacement.go
|
GO
|
mit
| 3,438 |
/*
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 metadata
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/stretchr/testify/require"
)
// Subset of data returned by the metadata endpoint.
type metadataRes struct {
ActorRuntime struct {
RuntimeStatus string `json:"runtimeStatus"`
ActiveActors []struct {
Type string `json:"type"`
Count int `json:"count"`
} `json:"activeActors"`
HostReady bool `json:"hostReady"`
Placement string `json:"placement"`
} `json:"actorRuntime"`
}
func getMetadata(t require.TestingT, ctx context.Context, client *http.Client, port int) (res metadataRes) {
ctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://localhost:%d/v1.0/metadata", port), nil)
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(&res)
require.NoError(t, err)
return res
}
|
mikeee/dapr
|
tests/integration/suite/actors/metadata/shared.go
|
GO
|
mit
| 1,547 |
/*
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 impliei.
See the License for the specific language governing permissions and
limitations under the License.
*/
package reminders
import (
"context"
"net/http"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/placement"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(basic))
}
// basic tests the basic functionality of actor reminders.
type basic struct {
daprd *daprd.Daprd
place *placement.Placement
reminderCalled atomic.Int64
stopReminderCalled atomic.Int64
}
func (b *basic) Setup(t *testing.T) []framework.Option {
handler := http.NewServeMux()
handler.HandleFunc("/dapr/config", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"entities": ["myactortype"]}`))
})
handler.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
handler.HandleFunc("/actors/myactortype/myactorid/method/remind/remindermethod", func(w http.ResponseWriter, r *http.Request) {
b.reminderCalled.Add(1)
})
handler.HandleFunc("/actors/myactortype/myactorid/method/remind/stopreminder", func(w http.ResponseWriter, r *http.Request) {
b.stopReminderCalled.Add(1)
w.Header().Set("X-DaprReminderCancel", "true")
w.WriteHeader(http.StatusOK)
})
handler.HandleFunc("/actors/myactortype/myactorid/method/foo", func(w http.ResponseWriter, r *http.Request) {})
srv := prochttp.New(t, prochttp.WithHandler(handler))
b.place = placement.New(t)
b.daprd = daprd.New(t,
daprd.WithInMemoryActorStateStore("mystore"),
daprd.WithPlacementAddresses(b.place.Address()),
daprd.WithAppPort(srv.Port()),
)
return []framework.Option{
framework.WithProcesses(b.place, srv, b.daprd),
}
}
func (b *basic) Run(t *testing.T, ctx context.Context) {
b.place.WaitUntilRunning(t, ctx)
b.daprd.WaitUntilRunning(t, ctx)
client := util.HTTPClient(t)
daprdURL := "http://localhost:" + strconv.Itoa(b.daprd.HTTPPort()) + "/v1.0/actors/myactortype/myactorid"
t.Run("actor ready", func(t *testing.T) {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, daprdURL+"/method/foo", nil)
require.NoError(t, err)
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, rErr := client.Do(req)
//nolint:testifylint
if assert.NoError(c, rErr) {
assert.NoError(c, resp.Body.Close())
assert.Equal(c, http.StatusOK, resp.StatusCode)
}
}, 10*time.Second, 10*time.Millisecond, "actor not ready in time")
})
conn, err := grpc.DialContext(ctx, b.daprd.GRPCAddress(),
grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock(),
)
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, conn.Close()) })
gclient := rtv1.NewDaprClient(conn)
t.Run("schedule reminder via HTTP", func(t *testing.T) {
const body = `{"dueTime": "0ms"}`
var (
req *http.Request
resp *http.Response
)
req, err = http.NewRequestWithContext(ctx, http.MethodPost, daprdURL+"/reminders/remindermethod", strings.NewReader(body))
require.NoError(t, err)
resp, err = client.Do(req)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
assert.Equal(t, http.StatusNoContent, resp.StatusCode)
assert.Eventually(t, func() bool {
return b.reminderCalled.Load() == 1
}, 3*time.Second, 10*time.Millisecond)
})
t.Run("schedule reminder via gRPC", func(t *testing.T) {
_, err = gclient.RegisterActorReminder(ctx, &rtv1.RegisterActorReminderRequest{
ActorType: "myactortype",
ActorId: "myactorid",
Name: "remindermethod",
DueTime: "0ms",
})
require.NoError(t, err)
assert.Eventually(t, func() bool {
return b.reminderCalled.Load() == 2
}, 3*time.Second, 10*time.Millisecond)
})
t.Run("cancel recurring reminder", func(t *testing.T) {
// Register a reminder that repeats every second
_, err = gclient.RegisterActorReminder(ctx, &rtv1.RegisterActorReminderRequest{
ActorType: "myactortype",
ActorId: "myactorid",
Name: "stopreminder",
DueTime: "0s",
Period: "1s",
})
require.NoError(t, err)
// Should be invoked once
assert.Eventually(t, func() bool {
return b.stopReminderCalled.Load() == 1
}, 3*time.Second, 10*time.Millisecond)
// After 2s, should not have been invoked more
time.Sleep(2 * time.Second)
assert.Equal(t, int64(1), b.stopReminderCalled.Load())
})
}
|
mikeee/dapr
|
tests/integration/suite/actors/reminders/basic.go
|
GO
|
mit
| 5,286 |
/*
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 impliei.
See the License for the specific language governing permissions and
limitations under the License.
*/
package reminders
import (
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
chi "github.com/go-chi/chi/v5"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
grpcinsecure "google.golang.org/grpc/credentials/insecure"
placementv1pb "github.com/dapr/dapr/pkg/proto/placement/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/placement"
"github.com/dapr/dapr/tests/integration/framework/process/sqlite"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(rebalancing))
}
// Number of iterations for the test
const iterations = 30
// rebalancing tests that during rebalancing, reminders do not cause actors to be activated on 2 separate hosts.
type rebalancing struct {
daprd [2]*daprd.Daprd
srv [2]*prochttp.HTTP
handler [2]*httpServer
db *sqlite.SQLite
place *placement.Placement
activeActors []atomic.Bool
doubleActivationCh chan string
}
func (i *rebalancing) Setup(t *testing.T) []framework.Option {
i.activeActors = make([]atomic.Bool, iterations)
i.doubleActivationCh = make(chan string)
// Create the SQLite database
i.db = sqlite.New(t,
sqlite.WithActorStateStore(true),
sqlite.WithMetadata("busyTimeout", "10s"),
sqlite.WithMetadata("disableWAL", "true"),
)
// Init placement
i.place = placement.New(t)
// Init two instances of daprd, each with its own server
for j := 0; j < 2; j++ {
i.handler[j] = &httpServer{
activeActors: i.activeActors,
doubleActivationCh: i.doubleActivationCh,
}
i.srv[j] = prochttp.New(t, prochttp.WithHandler(i.handler[j].NewHandler(j)))
i.daprd[j] = daprd.New(t,
daprd.WithResourceFiles(i.db.GetComponent(t)),
daprd.WithPlacementAddresses(i.place.Address()),
daprd.WithAppPort(i.srv[j].Port()),
// Daprd is super noisy in debug mode when connecting to placement.
daprd.WithLogLevel("info"),
)
}
return []framework.Option{
framework.WithProcesses(i.db, i.place, i.srv[0], i.srv[1], i.daprd[0], i.daprd[1]),
}
}
func (i *rebalancing) Run(t *testing.T, ctx context.Context) {
i.place.WaitUntilRunning(t, ctx)
// Wait for daprd to be ready
for j := 0; j < 2; j++ {
i.daprd[j].WaitUntilRunning(t, ctx)
}
// Wait for actors to be ready
for j := 0; j < 2; j++ {
err := i.handler[j].WaitForActorsReady(ctx)
require.NoErrorf(t, err, "Actor instance %d not ready", j)
}
// Establish a connection to the placement service
stream := i.getPlacementStream(t, ctx)
client := util.HTTPClient(t)
// Try to invoke an actor to ensure the actor subsystem is ready
require.EventuallyWithT(t, func(c *assert.CollectT) {
req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:%d/v1.0/actors/myactortype/pinger/method/ping", i.daprd[0].HTTPPort()), nil)
//nolint:testifylint
if assert.NoError(c, err) {
resp, rErr := client.Do(req)
//nolint:testifylint
if assert.NoError(c, rErr) {
//nolint:testifylint
assert.NoError(c, resp.Body.Close())
assert.Equal(c, http.StatusOK, resp.StatusCode)
}
}
}, 15*time.Second, 10*time.Millisecond, "actors not ready")
// Do a bunch of things in parallel
errCh := make(chan error)
// To start, monitor for double activations
go func() {
errs := make([]error, 0)
for doubleAct := range i.doubleActivationCh {
// An empty message is a signal to stop
if doubleAct == "" {
break
}
errs = append(errs, fmt.Errorf("double activation of actor %s", doubleAct))
}
if len(errs) > 0 {
errCh <- errors.Join(errs...)
} else {
errCh <- nil
}
}()
// Schedule reminders to be executed in 0s
for j := 0; j < iterations; j++ {
go func(j int) {
rctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
body := `{"dueTime": "0s"}`
daprdURL := fmt.Sprintf("http://localhost:%d/v1.0/actors/myactortype/myactorid-%d/reminders/reminder%d", i.daprd[0].HTTPPort(), j, j)
req, rErr := http.NewRequestWithContext(rctx, http.MethodPost, daprdURL, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
if rErr != nil {
errCh <- fmt.Errorf("failed scheduling reminder %d: %w", j, rErr)
return
}
resp, rErr := client.Do(req)
if rErr != nil {
errCh <- fmt.Errorf("failed scheduling reminder %d: %w", j, rErr)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
rb, _ := io.ReadAll(resp.Body)
errCh <- fmt.Errorf("failed scheduling reminder %d: status code is %d. Body: %s", j, resp.StatusCode, string(rb))
return
}
errCh <- nil
}(j)
}
// In parallel, add another node to the placement which will trigger a rebalancing
go func() {
rErr := i.reportStatusToPlacement(ctx, stream, []string{"myactortype"})
if rErr != nil {
errCh <- fmt.Errorf("failed to trigger rebalancing: %w", rErr)
} else {
errCh <- nil
}
}()
// Also invoke the same actors using actor invocation
for j := 0; j < iterations; j++ {
go func(j int) {
rctx, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
daprdURL := fmt.Sprintf("http://localhost:%d/v1.0/actors/myactortype/myactorid-%d/method/foo", i.daprd[0].HTTPPort(), j)
req, rErr := http.NewRequestWithContext(rctx, http.MethodPost, daprdURL, nil)
if rErr != nil {
errCh <- fmt.Errorf("failed invoking actor %d: %w", j, rErr)
return
}
assert.Eventually(t,
func() bool {
resp, respErr := client.Do(req)
if respErr != nil {
rErr = fmt.Errorf("failed invoking actor %d: %w", j, rErr)
return false
}
defer resp.Body.Close()
// We don't check the status code here as it could be 500 if we tried invoking the fake app
if resp.StatusCode != http.StatusOK {
log.Printf("MYLOG Invoking actor %d on non-existent host", j)
}
rErr = nil
return true
}, 20*time.Second, 1*time.Second)
errCh <- rErr
}(j)
}
// After 2s, stop doubleActivationCh by sending an empty message
go func() {
<-time.After(2 * time.Second)
i.doubleActivationCh <- ""
}()
// Wait for all operations to complete
for j := 0; j < (iterations*2)+2; j++ {
require.NoError(t, <-errCh)
}
}
type httpServer struct {
num int
actorsReady atomic.Bool
actorsReadyCh chan struct{}
activeActors []atomic.Bool
doubleActivationCh chan string
}
func (h *httpServer) NewHandler(num int) http.Handler {
h.actorsReadyCh = make(chan struct{})
h.num = num
r := chi.NewRouter()
r.Get("/dapr/config", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"entities": ["myactortype"]}`))
})
r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) {
if h.actorsReady.CompareAndSwap(false, true) {
close(h.actorsReadyCh)
}
w.WriteHeader(http.StatusOK)
})
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`OK`))
})
r.Put("/actors/{actorType}/{actorId}/method/{methodName}", func(w http.ResponseWriter, r *http.Request) {
// Invoke method
actorType := chi.URLParam(r, "actorType")
actorID := chi.URLParam(r, "actorId")
methodName := chi.URLParam(r, "methodName")
// Check if this is just a ping and return quickly
if methodName == "ping" {
w.WriteHeader(http.StatusOK)
return
}
parts := strings.Split(actorID, "-")
if len(parts) != 2 {
w.WriteHeader(http.StatusInternalServerError)
return
}
actorIDNum, err := strconv.Atoi(parts[1])
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
if actorIDNum > len(h.activeActors) {
w.WriteHeader(http.StatusInternalServerError)
return
}
if !h.activeActors[actorIDNum].CompareAndSwap(false, true) {
log.Printf("BUG!!! ACTOR %s/%s IS ALREADY ACTIVE ON ANOTHER HOST", actorType, actorID)
h.doubleActivationCh <- fmt.Sprintf("%s/%s", actorType, actorID)
}
log.Printf("MYLOG [%d] Invoked actor %s/%s: method %s", h.num, actorType, actorID, methodName)
// Simulate the actor doing some work
time.Sleep(2 * time.Second)
h.activeActors[actorIDNum].Store(false)
w.WriteHeader(http.StatusOK)
})
r.Put("/actors/{actorType}/{actorId}/method/remind/{reminderName}", func(w http.ResponseWriter, r *http.Request) {
// Invoke reminder
actorType := chi.URLParam(r, "actorType")
actorID := chi.URLParam(r, "actorId")
reminderName := chi.URLParam(r, "reminderName")
parts := strings.Split(actorID, "-")
if len(parts) != 2 {
w.WriteHeader(http.StatusInternalServerError)
return
}
actorIDNum, err := strconv.Atoi(parts[1])
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
if actorIDNum > len(h.activeActors) {
w.WriteHeader(http.StatusInternalServerError)
return
}
if !h.activeActors[actorIDNum].CompareAndSwap(false, true) {
log.Printf("BUG!!! ACTOR %s/%s IS ALREADY ACTIVE ON ANOTHER HOST", actorType, actorID)
h.doubleActivationCh <- fmt.Sprintf("%s/%s", actorType, actorID)
}
log.Printf("MYLOG [%d] Invoked actor %s/%s: reminder %s", h.num, actorType, actorID, reminderName)
// Simulate the actor doing some work
time.Sleep(2 * time.Second)
h.activeActors[actorIDNum].Store(false)
w.WriteHeader(http.StatusOK)
})
r.Delete("/actors/{actorType}/{actorId}", func(w http.ResponseWriter, r *http.Request) {
// Deactivate actor
actorType := chi.URLParam(r, "actorType")
actorID := chi.URLParam(r, "actorId")
log.Printf("MYLOG [%d] Deactivated actor %s/%s", h.num, actorType, actorID)
w.WriteHeader(http.StatusOK)
})
return r
}
func (h *httpServer) WaitForActorsReady(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-h.actorsReadyCh:
return nil
}
}
func (i *rebalancing) getPlacementStream(t *testing.T, ctx context.Context) placementv1pb.Placement_ReportDaprStatusClient {
// Establish a connection with placement
conn, err := grpc.DialContext(ctx, "localhost:"+strconv.Itoa(i.place.Port()),
grpc.WithBlock(),
grpc.WithTransportCredentials(grpcinsecure.NewCredentials()),
)
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, conn.Close()) })
client := placementv1pb.NewPlacementClient(conn)
// Establish a stream and send the initial heartbeat, with no actors
// We need to retry here because this will fail until the instance of
// placement (the only one) acquires leadership.
var stream placementv1pb.Placement_ReportDaprStatusClient
require.EventuallyWithT(t, func(c *assert.CollectT) {
stream, err = client.ReportDaprStatus(ctx)
require.NoError(c, err)
pctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
err = i.reportStatusToPlacement(pctx, stream, []string{})
//nolint:testifylint
if !assert.NoError(c, err) {
stream.CloseSend()
stream = nil
}
}, time.Second*20, time.Millisecond*10)
return stream
}
func (i *rebalancing) reportStatusToPlacement(ctx context.Context, stream placementv1pb.Placement_ReportDaprStatusClient, entities []string) error {
err := stream.Send(&placementv1pb.Host{
Name: "invalidapp",
Port: 1234,
Entities: entities,
Id: "invalidapp",
ApiLevel: 20,
})
if err != nil {
return fmt.Errorf("failed to send message: %w", err)
}
errCh := make(chan error, 1)
go func() {
for {
// When the stream ends (which happens when the context is canceled) this returns an error and we can return
o, rerr := stream.Recv()
if rerr != nil {
errCh <- fmt.Errorf("error from placement: %w", rerr)
return
}
if o.GetOperation() == "update" {
errCh <- nil
return
}
}
}()
select {
case <-ctx.Done():
return ctx.Err()
case err = <-errCh:
return err
}
}
|
mikeee/dapr
|
tests/integration/suite/actors/reminders/rebalancing.go
|
GO
|
mit
| 12,577 |
/*
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 impliei.
See the License for the specific language governing permissions and
limitations under the License.
*/
package serialization
import (
"context"
"database/sql"
"net/http"
"strings"
"sync/atomic"
"testing"
"time"
chi "github.com/go-chi/chi/v5"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func invokeActor(t *testing.T, ctx context.Context, baseURL string, client *http.Client) {
require.EventuallyWithT(t, func(c *assert.CollectT) {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, baseURL+"/method/foo", nil)
require.NoError(c, err)
resp, rErr := client.Do(req)
//nolint:testifylint
if assert.NoError(c, rErr) {
assert.NoError(c, resp.Body.Close())
assert.Equal(c, http.StatusOK, resp.StatusCode)
}
}, time.Second*20, time.Millisecond*10, "actor not ready in time")
}
func storeReminder(t *testing.T, ctx context.Context, baseURL string, client *http.Client) {
reqCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, baseURL+"/reminders/newreminder", strings.NewReader(`{"dueTime": "0","period": "2m"}`))
require.NoError(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.Equal(t, http.StatusNoContent, resp.StatusCode)
}
func loadRemindersFromDB(t *testing.T, ctx context.Context, db *sql.DB) (storedVal string) {
queryCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
err := db.QueryRowContext(queryCtx, "SELECT value FROM state WHERE key = 'actors||myactortype'").Scan(&storedVal)
require.NoError(t, err)
return storedVal
}
type httpServer struct {
actorsReady atomic.Bool
actorsReadyCh chan struct{}
remindersInvokeCount atomic.Uint32
}
func (h *httpServer) NewHandler() http.Handler {
h.actorsReadyCh = make(chan struct{})
r := chi.NewRouter()
r.Get("/dapr/config", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"entities": ["myactortype"]}`))
})
r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) {
if h.actorsReady.CompareAndSwap(false, true) {
close(h.actorsReadyCh)
}
w.WriteHeader(http.StatusOK)
})
r.HandleFunc("/actors/myactortype/myactorid/method/foo", func(w http.ResponseWriter, r *http.Request) {})
r.HandleFunc("/actors/myactortype/myactorid/method/remind/newreminder", func(w http.ResponseWriter, r *http.Request) {
h.remindersInvokeCount.Add(1)
})
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`OK`))
})
return r
}
func (h *httpServer) WaitForActorsReady(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-h.actorsReadyCh:
return nil
}
}
|
mikeee/dapr
|
tests/integration/suite/actors/reminders/serialization/common.go
|
GO
|
mit
| 3,261 |
/*
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 serialization
import (
"context"
"fmt"
"runtime"
"strconv"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/placement"
"github.com/dapr/dapr/tests/integration/framework/process/sqlite"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(defaultS))
}
// defaultS ensures that reminders are stored as JSON by default.
type defaultS struct {
daprd *daprd.Daprd
srv *prochttp.HTTP
handler *httpServer
place *placement.Placement
db *sqlite.SQLite
}
func (d *defaultS) Setup(t *testing.T) []framework.Option {
if runtime.GOOS == "windows" {
t.Skip("Skipping test on Windows due to SQLite limitations")
}
d.place = placement.New(t)
d.db = sqlite.New(t, sqlite.WithActorStateStore(true))
d.handler = new(httpServer)
d.srv = prochttp.New(t, prochttp.WithHandler(d.handler.NewHandler()))
d.daprd = daprd.New(t,
daprd.WithResourceFiles(d.db.GetComponent(t)),
daprd.WithPlacementAddresses("127.0.0.1:"+strconv.Itoa(d.place.Port())),
daprd.WithAppPort(d.srv.Port()),
)
return []framework.Option{
framework.WithProcesses(d.db, d.place, d.srv, d.daprd),
}
}
func (d *defaultS) Run(t *testing.T, ctx context.Context) {
d.place.WaitUntilRunning(t, ctx)
d.daprd.WaitUntilRunning(t, ctx)
require.NoError(t, d.handler.WaitForActorsReady(ctx))
client := util.HTTPClient(t)
baseURL := fmt.Sprintf("http://localhost:%d/v1.0/actors/myactortype/myactorid", d.daprd.HTTPPort())
invokeActor(t, ctx, baseURL, client)
storeReminder(t, ctx, baseURL, client)
// Check the data in the SQLite database
// The value must begin with `[{`, which indicates it was serialized as JSON
storedVal := loadRemindersFromDB(t, ctx, d.db.GetConnection(t))
assert.Truef(t, strings.HasPrefix(storedVal, "[{"), "Prefix not found in value: '%v'", storedVal)
assert.Eventually(t, func() bool {
return d.handler.remindersInvokeCount.Load() > 0
}, 5*time.Second, 10*time.Millisecond, "Reminder was not invoked at least once")
}
|
mikeee/dapr
|
tests/integration/suite/actors/reminders/serialization/default.go
|
GO
|
mit
| 2,916 |
/*
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 serialization
import (
"context"
"fmt"
"runtime"
"strconv"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/placement"
"github.com/dapr/dapr/tests/integration/framework/process/sqlite"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(jsonFormat))
}
// jsonFormat tests:
// - That reminders are serialized to JSON when the Actors API level in the cluster is < 20
type jsonFormat struct {
daprd *daprd.Daprd
srv *prochttp.HTTP
handler *httpServer
place *placement.Placement
db *sqlite.SQLite
}
func (j *jsonFormat) Setup(t *testing.T) []framework.Option {
if runtime.GOOS == "windows" {
t.Skip("Skipping test on Windows due to SQLite limitations")
}
// Init placement with a maximum API level of 10
// We need to set the max API level to 10, because levels 20 and up with serialise as protobuf
j.place = placement.New(t,
placement.WithMaxAPILevel(10),
)
// Create a SQLite database
j.db = sqlite.New(t, sqlite.WithActorStateStore(true))
// Init daprd and the HTTP server
j.handler = &httpServer{}
j.srv = prochttp.New(t, prochttp.WithHandler(j.handler.NewHandler()))
j.daprd = daprd.New(t,
daprd.WithResourceFiles(j.db.GetComponent(t)),
daprd.WithPlacementAddresses("127.0.0.1:"+strconv.Itoa(j.place.Port())),
daprd.WithAppPort(j.srv.Port()),
)
return []framework.Option{
framework.WithProcesses(j.db, j.place, j.srv, j.daprd),
}
}
func (j *jsonFormat) Run(t *testing.T, ctx context.Context) {
// Wait for placement to be ready
j.place.WaitUntilRunning(t, ctx)
// Wait for daprd to be ready
j.daprd.WaitUntilRunning(t, ctx)
// Wait for actors to be ready
err := j.handler.WaitForActorsReady(ctx)
require.NoError(t, err)
client := util.HTTPClient(t)
baseURL := fmt.Sprintf("http://localhost:%d/v1.0/actors/myactortype/myactorid", j.daprd.HTTPPort())
// Invoke an actor to confirm everything is ready to go
invokeActor(t, ctx, baseURL, client)
// Store a reminder
// This causes the data in the state store to be updated
storeReminder(t, ctx, baseURL, client)
// Check the data in the SQLite database
// The value must begin with `[{`, which indicates it was serialized as JSON
storedVal := loadRemindersFromDB(t, ctx, j.db.GetConnection(t))
assert.Truef(t, strings.HasPrefix(storedVal, "[{"), "Prefix not found in value: '%v'", storedVal)
// Ensure the reminder was invoked at least once
assert.Eventually(t, func() bool {
return j.handler.remindersInvokeCount.Load() > 0
}, 5*time.Second, 10*time.Millisecond, "Reminder was not invoked at least once")
}
|
mikeee/dapr
|
tests/integration/suite/actors/reminders/serialization/json.go
|
GO
|
mit
| 3,513 |
/*
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 serialization
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"runtime"
"strconv"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/placement"
"github.com/dapr/dapr/tests/integration/framework/process/sqlite"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(protobufFormat))
}
// protobufFormat tests:
// - The ability for daprd to read reminders serialized as JSON and protobuf
// - That reminders are serialized to protobuf when the Actors API level in the cluster is >= 20
type protobufFormat struct {
daprd *daprd.Daprd
srv *prochttp.HTTP
handler *httpServer
place *placement.Placement
db *sqlite.SQLite
}
func (p *protobufFormat) Setup(t *testing.T) []framework.Option {
if runtime.GOOS == "windows" {
t.Skip("Skipping test on Windows due to SQLite limitations")
}
// Init placement with minimum API level of 20
p.place = placement.New(t, placement.WithMaxAPILevel(-1), placement.WithMinAPILevel(20))
// Create a SQLite database and ensure state tables exist
now := time.Now().UTC().Format(time.RFC3339)
p.db = sqlite.New(t,
sqlite.WithActorStateStore(true),
sqlite.WithCreateStateTables(),
sqlite.WithExecs(fmt.Sprintf(`
INSERT INTO state VALUES
('actors||myactortype','[{"registeredTime":"%[1]s","period":"2m","actorID":"myactorid","actorType":"myactortype","name":"oldreminder","dueTime":"0"}]',0,'e467f810-4e93-45ed-85d9-e68d9fc7af4a',NULL,'%[1]s'),
('actors||myactortype||metadata','{"id":"00000000-0000-0000-0000-000000000000","actorRemindersMetadata":{"partitionCount":0}}',0,'e82c5496-ae32-40a6-9578-6a7bd84ff331',NULL,'%[1]s');
`, now)),
)
// Init daprd and the HTTP server
p.handler = &httpServer{}
p.srv = prochttp.New(t, prochttp.WithHandler(p.handler.NewHandler()))
p.daprd = daprd.New(t,
daprd.WithResourceFiles(p.db.GetComponent(t)),
daprd.WithPlacementAddresses("127.0.0.1:"+strconv.Itoa(p.place.Port())),
daprd.WithAppPort(p.srv.Port()),
)
return []framework.Option{
framework.WithProcesses(p.db, p.place, p.srv, p.daprd),
}
}
func (p *protobufFormat) Run(t *testing.T, ctx context.Context) {
// Wait for placement to be ready
p.place.WaitUntilRunning(t, ctx)
// Wait for daprd to be ready
p.daprd.WaitUntilRunning(t, ctx)
// Wait for actors to be ready
err := p.handler.WaitForActorsReady(ctx)
require.NoError(t, err)
client := util.HTTPClient(t)
baseURL := fmt.Sprintf("http://localhost:%d/v1.0/actors/myactortype/myactorid", p.daprd.HTTPPort())
// Invoke an actor to confirm everything is ready to go
invokeActor(t, ctx, baseURL, client)
// Store a reminder (which has the same name as the one already in the state store)
// This causes the data in the state store to be updated
storeReminder(t, ctx, baseURL, client)
// Check the data in the SQLite database
// The value must be base64-encoded, and after being decoded it should begin with `\0pb`, which indicates it was serialized as protobuf
storedVal := loadRemindersFromDB(t, ctx, p.db.GetConnection(t))
storedValBytes, err := base64.StdEncoding.DecodeString(storedVal)
require.NoErrorf(t, err, "Failed to decode value from base64: '%v'", storedVal)
assert.Truef(t, bytes.HasPrefix(storedValBytes, []byte{0, 'p', 'b'}), "Prefix not found in value: '%v'", storedVal)
}
|
mikeee/dapr
|
tests/integration/suite/actors/reminders/serialization/protobuf.go
|
GO
|
mit
| 4,206 |
/*
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 binding
import (
_ "github.com/dapr/dapr/tests/integration/suite/daprd/binding/input"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/binding/output"
)
|
mikeee/dapr
|
tests/integration/suite/daprd/binding/binding.go
|
GO
|
mit
| 730 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package input
import (
"context"
"errors"
"fmt"
"net/http"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/emptypb"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/app"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(appready))
}
type appready struct {
daprd *daprd.Daprd
appHealthy atomic.Bool
healthCalled atomic.Int64
bindingCalled atomic.Int64
}
func (a *appready) Setup(t *testing.T) []framework.Option {
srv := app.New(t,
app.WithHealthCheckFn(func(context.Context, *emptypb.Empty) (*rtv1.HealthCheckResponse, error) {
defer a.healthCalled.Add(1)
if a.appHealthy.Load() {
return &rtv1.HealthCheckResponse{}, nil
}
return nil, errors.New("app not healthy")
}),
app.WithOnBindingEventFn(func(ctx context.Context, in *rtv1.BindingEventRequest) (*rtv1.BindingEventResponse, error) {
switch in.GetName() {
case "mybinding":
a.bindingCalled.Add(1)
default:
assert.Failf(t, "unexpected binding name", "binding name: %s", in.GetName())
}
return new(rtv1.BindingEventResponse), nil
}),
app.WithListInputBindings(func(context.Context, *emptypb.Empty) (*rtv1.ListInputBindingsResponse, error) {
return &rtv1.ListInputBindingsResponse{
Bindings: []string{"mybinding"},
}, nil
}),
)
a.daprd = daprd.New(t,
daprd.WithAppPort(srv.Port(t)),
daprd.WithAppProtocol("grpc"),
daprd.WithAppHealthCheck(true),
daprd.WithAppHealthProbeInterval(1),
daprd.WithAppHealthProbeThreshold(1),
daprd.WithResourceFiles(`apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'mybinding'
spec:
type: bindings.cron
version: v1
metadata:
- name: schedule
value: "@every 1s"
- name: direction
value: "input"
`))
return []framework.Option{
framework.WithProcesses(srv, a.daprd),
}
}
func (a *appready) Run(t *testing.T, ctx context.Context) {
a.daprd.WaitUntilRunning(t, ctx)
client := a.daprd.GRPCClient(t, ctx)
httpClient := util.HTTPClient(t)
reqURL := fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/foo", a.daprd.HTTPPort(), a.daprd.AppID())
req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil)
require.NoError(t, err)
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 1)
}, time.Second*5, time.Millisecond*10)
called := a.healthCalled.Load()
require.Eventually(t, func() bool { return a.healthCalled.Load() > called }, time.Second*5, time.Millisecond*10)
assert.Eventually(t, func() bool {
resp, err := httpClient.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
return resp.StatusCode == http.StatusInternalServerError
}, time.Second*5, 10*time.Millisecond)
time.Sleep(time.Second * 2)
assert.Equal(t, int64(0), a.bindingCalled.Load())
a.appHealthy.Store(true)
assert.Eventually(t, func() bool {
resp, err := util.HTTPClient(t).Do(req)
require.NoError(t, err)
defer resp.Body.Close()
return resp.StatusCode == http.StatusOK
}, time.Second*5, 10*time.Millisecond)
assert.Eventually(t, func() bool {
return a.bindingCalled.Load() > 0
}, time.Second*5, 10*time.Millisecond)
// Should stop calling binding when app becomes unhealthy
a.appHealthy.Store(false)
assert.Eventually(t, func() bool {
resp, err := httpClient.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
return resp.StatusCode == http.StatusInternalServerError
}, time.Second*5, 10*time.Millisecond)
called = a.bindingCalled.Load()
time.Sleep(time.Second * 2)
assert.Equal(t, called, a.bindingCalled.Load())
}
|
mikeee/dapr
|
tests/integration/suite/daprd/binding/input/appready.go
|
GO
|
mit
| 4,570 |
/*
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 output
import (
"context"
"fmt"
"net/http"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
grpcMetadata "google.golang.org/grpc/metadata"
"github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(bindingerrors))
}
type bindingerrors struct {
srv *prochttp.HTTP
daprd *daprd.Daprd
}
func (b *bindingerrors) Setup(t *testing.T) []framework.Option {
mux := http.NewServeMux()
mux.HandleFunc("/error_404", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
})
b.srv = prochttp.New(t, prochttp.WithHandler(mux))
b.daprd = daprd.New(t,
daprd.WithResourceFiles(fmt.Sprintf(`apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: github-http-binding-404
spec:
type: bindings.http
version: v1
metadata:
- name: url
value: http://127.0.0.1:%d/error_404
`, b.srv.Port())))
return []framework.Option{
framework.WithProcesses(b.srv, b.daprd),
}
}
func (b *bindingerrors) Run(t *testing.T, ctx context.Context) {
b.daprd.WaitUntilRunning(t, ctx)
client := b.daprd.GRPCClient(t, ctx)
httpClient := util.HTTPClient(t)
assert.Eventually(t, func() bool {
reqURL := fmt.Sprintf("http://localhost:%d/v1.0/bindings/github-http-binding-404", b.daprd.HTTPPort())
req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, strings.NewReader("{\"operation\":\"get\"}"))
require.NoError(t, err)
resp, err := httpClient.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
return (resp.StatusCode == http.StatusInternalServerError) && (resp.Header.Get("Metadata.statuscode") == "404")
}, time.Second*5, 10*time.Millisecond)
assert.Eventually(t, func() bool {
req := runtime.InvokeBindingRequest{
Name: "github-http-binding-404",
Operation: "get",
}
var header grpcMetadata.MD
resp, err := client.InvokeBinding(ctx, &req, grpc.Header(&header))
require.Error(t, err)
require.Nil(t, resp)
statusCodeArr := header.Get("metadata.statuscode")
require.Len(t, statusCodeArr, 1)
return statusCodeArr[0] == "404"
}, time.Second*5, 10*time.Millisecond)
}
|
mikeee/dapr
|
tests/integration/suite/daprd/binding/output/errors.go
|
GO
|
mit
| 3,038 |
/*
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 daprd
import (
_ "github.com/dapr/dapr/tests/integration/suite/daprd/binding"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/httpserver"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/metadata"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/metrics"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/middleware"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/mtls"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/multipleconfigs"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/outbox"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/pluggable"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/pubsub"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/resiliency"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/resources"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/secret"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/serviceinvocation"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/shutdown"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/state"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/subscriptions"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/workflow"
)
|
mikeee/dapr
|
tests/integration/suite/daprd/daprd.go
|
GO
|
mit
| 1,837 |
/*
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 hotreload
import (
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/operator"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/selfhosted"
)
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/hotreload.go
|
GO
|
mit
| 743 |
/*
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://wwa.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to 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"
"testing"
"github.com/stretchr/testify/require"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/dapr/dapr/pkg/apis/common"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
"github.com/dapr/dapr/pkg/operator/api"
operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/operator"
"github.com/dapr/dapr/tests/integration/framework/process/logline"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(actorstate))
}
type actorstate struct {
daprdCreate *daprd.Daprd
daprdUpdate *daprd.Daprd
daprdDelete *daprd.Daprd
operatorCreate *operator.Operator
operatorUpdate *operator.Operator
operatorDelete *operator.Operator
loglineCreate *logline.LogLine
loglineUpdate *logline.LogLine
loglineDelete *logline.LogLine
}
func (a *actorstate) Setup(t *testing.T) []framework.Option {
sentry := sentry.New(t)
a.loglineCreate = logline.New(t, logline.WithStdoutLineContains(
"Aborting to hot-reload a state store component that is used as an actor state store: mystore (state.in-memory/v1)",
))
a.loglineUpdate = logline.New(t, logline.WithStdoutLineContains(
"Aborting to hot-reload a state store component that is used as an actor state store: mystore (state.in-memory/v1)",
))
a.loglineDelete = logline.New(t, logline.WithStdoutLineContains(
"Aborting to hot-reload a state store component that is used as an actor state store: mystore (state.in-memory/v1)",
))
a.operatorCreate = operator.New(t,
operator.WithSentry(sentry),
operator.WithGetConfigurationFn(func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error) {
return &operatorv1.GetConfigurationResponse{
Configuration: []byte(
`{"kind":"Configuration","apiVersion":"dapr.io/v1alpha1","metadata":{"name":"hotreloading"},"spec":{"features":[{"name":"HotReload","enabled":true}]}}`,
),
}, nil
}),
)
a.operatorUpdate = operator.New(t,
operator.WithSentry(sentry),
operator.WithGetConfigurationFn(func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error) {
return &operatorv1.GetConfigurationResponse{
Configuration: []byte(
`{"kind":"Configuration","apiVersion":"dapr.io/v1alpha1","metadata":{"name":"hotreloading"},"spec":{"features":[{"name":"HotReload","enabled":true}]}}`,
),
}, nil
}),
)
a.operatorDelete = operator.New(t,
operator.WithSentry(sentry),
operator.WithGetConfigurationFn(func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error) {
return &operatorv1.GetConfigurationResponse{
Configuration: []byte(
`{"kind":"Configuration","apiVersion":"dapr.io/v1alpha1","metadata":{"name":"hotreloading"},"spec":{"features":[{"name":"HotReload","enabled":true}]}}`,
),
}, nil
}),
)
inmemStore := compapi.Component{
TypeMeta: metav1.TypeMeta{Kind: "Component", APIVersion: "dapr.io/v1alpha1"},
ObjectMeta: metav1.ObjectMeta{Name: "mystore", Namespace: "default"},
Spec: compapi.ComponentSpec{
Type: "state.in-memory", Version: "v1",
Metadata: []common.NameValuePair{{Name: "actorStateStore", Value: common.DynamicValue{JSON: apiextv1.JSON{Raw: []byte(`"true"`)}}}},
},
}
a.operatorCreate.SetComponents()
a.operatorUpdate.SetComponents(inmemStore)
a.operatorDelete.SetComponents(inmemStore)
a.daprdCreate = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(
exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors)),
exec.WithStdout(a.loglineCreate.Stdout()),
),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(a.operatorCreate.Address(t)),
daprd.WithDisableK8sSecretStore(true),
)
a.daprdUpdate = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(
exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors)),
exec.WithStdout(a.loglineUpdate.Stdout()),
),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(a.operatorUpdate.Address(t)),
daprd.WithDisableK8sSecretStore(true),
)
a.daprdDelete = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(
exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors)),
exec.WithStdout(a.loglineDelete.Stdout()),
),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(a.operatorDelete.Address(t)),
daprd.WithDisableK8sSecretStore(true),
)
return []framework.Option{
framework.WithProcesses(sentry,
a.operatorCreate, a.operatorUpdate, a.operatorDelete,
a.loglineCreate, a.loglineUpdate, a.loglineDelete,
a.daprdCreate, a.daprdUpdate, a.daprdDelete,
),
}
}
func (a *actorstate) Run(t *testing.T, ctx context.Context) {
a.daprdCreate.WaitUntilRunning(t, ctx)
a.daprdUpdate.WaitUntilRunning(t, ctx)
a.daprdDelete.WaitUntilRunning(t, ctx)
httpClient := util.HTTPClient(t)
comps := util.GetMetaComponents(t, ctx, httpClient, a.daprdCreate.HTTPPort())
require.ElementsMatch(t, []*rtv1.RegisteredComponents{}, comps)
inmemStore := compapi.Component{
TypeMeta: metav1.TypeMeta{Kind: "Component", APIVersion: "dapr.io/v1alpha1"},
ObjectMeta: metav1.ObjectMeta{Name: "mystore", Namespace: "default"},
Spec: compapi.ComponentSpec{
Type: "state.in-memory", Version: "v1",
Metadata: []common.NameValuePair{{Name: "actorStateStore", Value: common.DynamicValue{JSON: apiextv1.JSON{Raw: []byte(`"true"`)}}}},
},
}
a.operatorCreate.AddComponents(inmemStore)
a.operatorCreate.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &inmemStore, EventType: operatorv1.ResourceEventType_CREATED})
a.loglineCreate.EventuallyFoundAll(t)
comps = util.GetMetaComponents(t, ctx, httpClient, a.daprdUpdate.HTTPPort())
require.ElementsMatch(t, []*rtv1.RegisteredComponents{
{
Name: "mystore", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, comps)
inmemStore.Spec.Metadata = []common.NameValuePair{}
a.operatorUpdate.SetComponents(inmemStore)
a.operatorUpdate.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &inmemStore, EventType: operatorv1.ResourceEventType_UPDATED})
a.loglineUpdate.EventuallyFoundAll(t)
comps = util.GetMetaComponents(t, ctx, httpClient, a.daprdDelete.HTTPPort())
require.ElementsMatch(t, []*rtv1.RegisteredComponents{
{
Name: "mystore", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, comps)
a.operatorDelete.SetComponents()
a.operatorDelete.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &inmemStore, EventType: operatorv1.ResourceEventType_DELETED})
a.loglineDelete.EventuallyFoundAll(t)
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/actorstate.go
|
GO
|
mit
| 8,045 |
/*
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 binding
import (
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/operator/binding/input"
)
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/binding/binding.go
|
GO
|
mit
| 678 |
/*
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 input
import (
"context"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/emptypb"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/dapr/dapr/pkg/apis/common"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
"github.com/dapr/dapr/pkg/operator/api"
operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/app"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/operator"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(grpc))
}
type grpc struct {
daprd *daprd.Daprd
operator *operator.Operator
listening [3]atomic.Bool
registered [3]atomic.Bool
bindingChan [3]chan string
}
func (g *grpc) Setup(t *testing.T) []framework.Option {
g.bindingChan = [3]chan string{
make(chan string, 1), make(chan string, 1), make(chan string, 1),
}
g.registered[0].Store(true)
srv := app.New(t,
app.WithOnBindingEventFn(func(ctx context.Context, in *rtv1.BindingEventRequest) (*rtv1.BindingEventResponse, error) {
switch in.GetName() {
case "binding1":
assert.True(t, g.registered[0].Load())
if g.listening[0].Load() {
g.listening[0].Store(false)
g.bindingChan[0] <- in.GetName()
}
case "binding2":
assert.True(t, g.registered[1].Load())
if g.listening[1].Load() {
g.listening[1].Store(false)
g.bindingChan[1] <- in.GetName()
}
case "binding3":
assert.True(t, g.registered[2].Load())
if g.listening[2].Load() {
g.listening[2].Store(false)
g.bindingChan[2] <- in.GetName()
}
default:
assert.Failf(t, "unexpected binding name", "binding name: %s", in.GetName())
}
return new(rtv1.BindingEventResponse), nil
}),
app.WithListInputBindings(func(context.Context, *emptypb.Empty) (*rtv1.ListInputBindingsResponse, error) {
return &rtv1.ListInputBindingsResponse{
Bindings: []string{"binding1", "binding2", "binding3"},
}, nil
}),
)
sentry := sentry.New(t)
g.operator = operator.New(t,
operator.WithSentry(sentry),
operator.WithGetConfigurationFn(func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error) {
return &operatorv1.GetConfigurationResponse{
Configuration: []byte(
`{"kind":"Configuration","apiVersion":"dapr.io/v1alpha1","metadata":{"name":"hotreloading"},"spec":{"features":[{"name":"HotReload","enabled":true}]}}`,
),
}, nil
}),
)
g.operator.AddComponents(compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "binding1",
Namespace: "default",
},
Spec: compapi.ComponentSpec{
Type: "bindings.cron",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "schedule", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`"@every 300ms"`)},
}},
{Name: "direction", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`"input"`)},
}},
},
},
})
g.daprd = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors))),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(g.operator.Address(t)),
daprd.WithDisableK8sSecretStore(true),
daprd.WithAppPort(srv.Port(t)),
daprd.WithAppProtocol("grpc"),
)
return []framework.Option{
framework.WithProcesses(sentry, srv, g.operator, g.daprd),
}
}
func (g *grpc) Run(t *testing.T, ctx context.Context) {
g.daprd.WaitUntilRunning(t, ctx)
client := g.daprd.GRPCClient(t, ctx)
t.Run("expect 1 component to be loaded", func(t *testing.T) {
assert.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
//nolint:testifylint
assert.NoError(c, err)
assert.Len(c, resp.GetRegisteredComponents(), 1)
}, time.Second*20, time.Millisecond*10)
g.expectBinding(t, 0, "binding1")
})
t.Run("create a component", func(t *testing.T) {
g.registered[1].Store(true)
comp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "binding2",
Namespace: "default",
},
Spec: compapi.ComponentSpec{
Type: "bindings.cron",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "schedule", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`"@every 300ms"`)},
}},
{Name: "direction", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`"input"`)},
}},
},
},
}
g.operator.AddComponents(comp)
g.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 2)
}, time.Second*5, time.Millisecond*10)
g.expectBindings(t, []bindingPair{
{0, "binding1"},
{1, "binding2"},
})
})
t.Run("create a third component", func(t *testing.T) {
g.registered[2].Store(true)
comp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "binding3",
Namespace: "default",
},
Spec: compapi.ComponentSpec{
Type: "bindings.cron",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "schedule", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`"@every 300ms"`)},
}},
{Name: "direction", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`"input"`)},
}},
},
},
}
g.operator.AddComponents(comp)
g.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 3)
}, time.Second*5, time.Millisecond*10)
g.expectBindings(t, []bindingPair{
{0, "binding1"},
{1, "binding2"},
{2, "binding3"},
})
})
t.Run("deleting a component should no longer be available", func(t *testing.T) {
comp := g.operator.Components()[0]
g.operator.SetComponents(g.operator.Components()[1:]...)
g.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_DELETED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 2)
}, time.Second*5, time.Millisecond*10)
g.registered[0].Store(false)
g.expectBindings(t, []bindingPair{
{1, "binding2"},
{2, "binding3"},
})
})
t.Run("deleting all components should no longer be available", func(t *testing.T) {
comp1 := g.operator.Components()[0]
comp2 := g.operator.Components()[1]
g.operator.SetComponents()
g.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp1, EventType: operatorv1.ResourceEventType_DELETED})
g.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp2, EventType: operatorv1.ResourceEventType_DELETED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(c, err)
assert.Empty(c, resp.GetRegisteredComponents())
}, time.Second*5, time.Millisecond*10)
g.registered[1].Store(false)
g.registered[2].Store(false)
// Sleep to ensure binding is not triggered.
time.Sleep(time.Millisecond * 500)
})
t.Run("recreating binding should start again", func(t *testing.T) {
g.registered[0].Store(true)
comp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "binding1",
Namespace: "default",
},
Spec: compapi.ComponentSpec{
Type: "bindings.cron",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "schedule", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`"@every 300ms"`)},
}},
{Name: "direction", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`"input"`)},
}},
},
},
}
g.operator.AddComponents(comp)
g.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 1)
}, time.Second*5, time.Millisecond*10)
g.expectBinding(t, 0, "binding1")
})
}
type bindingPair struct {
i int
b string
}
func (g *grpc) expectBindings(t *testing.T, expected []bindingPair) {
t.Helper()
var wg sync.WaitGroup
defer wg.Wait()
wg.Add(len(expected))
for _, e := range expected {
go func(e bindingPair) {
g.expectBinding(t, e.i, e.b)
wg.Done()
}(e)
}
}
func (g *grpc) expectBinding(t *testing.T, i int, binding string) {
t.Helper()
g.listening[i].Store(true)
select {
case got := <-g.bindingChan[i]:
assert.Equal(t, binding, got)
case <-time.After(time.Second * 5):
assert.Fail(t, "timed out waiting for binding event")
}
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/binding/input/grpc.go
|
GO
|
mit
| 10,369 |
/*
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 input
import (
"context"
nethttp "net/http"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/dapr/dapr/pkg/apis/common"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
"github.com/dapr/dapr/pkg/operator/api"
operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/operator"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(http))
}
type http struct {
daprd *daprd.Daprd
operator *operator.Operator
listening [3]atomic.Bool
registered [3]atomic.Bool
bindingChan [3]chan string
}
func (h *http) Setup(t *testing.T) []framework.Option {
h.bindingChan = [3]chan string{
make(chan string, 1), make(chan string, 1), make(chan string, 1),
}
h.registered[0].Store(true)
handler := nethttp.NewServeMux()
handler.HandleFunc("/", func(w nethttp.ResponseWriter, r *nethttp.Request) {
w.WriteHeader(nethttp.StatusOK)
if strings.HasPrefix(r.URL.Path, "/binding") {
switch path := r.URL.Path; path {
case "/binding1":
assert.True(t, h.registered[0].Load())
if h.listening[0].Load() {
h.listening[0].Store(false)
h.bindingChan[0] <- path
}
case "/binding2":
assert.True(t, h.registered[1].Load())
if h.listening[1].Load() {
h.listening[1].Store(false)
h.bindingChan[1] <- path
}
case "/binding3":
assert.True(t, h.registered[2].Load())
if h.listening[2].Load() {
h.listening[2].Store(false)
h.bindingChan[2] <- path
}
default:
assert.Failf(t, "unexpected binding name", "binding name: %s", path)
}
}
})
srv := prochttp.New(t, prochttp.WithHandler(handler))
sentry := sentry.New(t)
h.operator = operator.New(t,
operator.WithSentry(sentry),
operator.WithGetConfigurationFn(func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error) {
return &operatorv1.GetConfigurationResponse{
Configuration: []byte(
`{"kind":"Configuration","apiVersion":"dapr.io/v1alpha1","metadata":{"name":"hotreloading"},"spec":{"features":[{"name":"HotReload","enabled":true}]}}`,
),
}, nil
}),
)
h.operator.AddComponents(compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "binding1",
Namespace: "default",
},
Spec: compapi.ComponentSpec{
Type: "bindings.cron",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "schedule", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`"@every 300ms"`)},
}},
{Name: "direction", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`"input"`)},
}},
},
},
})
h.daprd = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors))),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(h.operator.Address(t)),
daprd.WithDisableK8sSecretStore(true),
daprd.WithAppPort(srv.Port()),
)
return []framework.Option{
framework.WithProcesses(sentry, srv, h.operator, h.daprd),
}
}
func (h *http) Run(t *testing.T, ctx context.Context) {
h.daprd.WaitUntilRunning(t, ctx)
client := util.HTTPClient(t)
t.Run("expect 1 component to be loaded", func(t *testing.T) {
assert.Len(t, util.GetMetaComponents(t, ctx, client, h.daprd.HTTPPort()), 1)
h.expectBinding(t, 0, "binding1")
})
t.Run("create a component", func(t *testing.T) {
h.registered[1].Store(true)
comp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "binding2",
Namespace: "default",
},
Spec: compapi.ComponentSpec{
Type: "bindings.cron",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "schedule", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`"@every 300ms"`)},
}},
{Name: "direction", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`"input"`)},
}},
},
},
}
h.operator.AddComponents(comp)
h.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, h.daprd.HTTPPort()), 2)
}, time.Second*5, time.Millisecond*10)
h.expectBindings(t, []bindingPair{
{0, "binding1"},
{1, "binding2"},
})
})
t.Run("create a third component", func(t *testing.T) {
h.registered[2].Store(true)
comp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "binding3",
Namespace: "default",
},
Spec: compapi.ComponentSpec{
Type: "bindings.cron",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "schedule", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`"@every 300ms"`)},
}},
{Name: "direction", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`"input"`)},
}},
},
},
}
h.operator.AddComponents(comp)
h.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, h.daprd.HTTPPort()), 3)
}, time.Second*5, time.Millisecond*10)
h.expectBindings(t, []bindingPair{
{0, "binding1"},
{1, "binding2"},
{2, "binding3"},
})
})
t.Run("deleting a component should no longer be available", func(t *testing.T) {
comp := h.operator.Components()[0]
h.operator.SetComponents(h.operator.Components()[1:]...)
h.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_DELETED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, h.daprd.HTTPPort()), 2)
}, time.Second*5, time.Millisecond*10)
h.registered[0].Store(false)
h.expectBindings(t, []bindingPair{
{1, "binding2"},
{2, "binding3"},
})
})
t.Run("deleting all components should no longer be available", func(t *testing.T) {
comp1 := h.operator.Components()[0]
comp2 := h.operator.Components()[1]
h.operator.SetComponents()
h.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp1, EventType: operatorv1.ResourceEventType_DELETED})
h.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp2, EventType: operatorv1.ResourceEventType_DELETED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Empty(c, util.GetMetaComponents(c, ctx, client, h.daprd.HTTPPort()))
}, time.Second*5, time.Millisecond*10)
h.registered[1].Store(false)
h.registered[2].Store(false)
// Sleep to ensure binding is not triggered.
time.Sleep(time.Millisecond * 500)
})
t.Run("recreating binding should start again", func(t *testing.T) {
h.registered[0].Store(true)
comp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "binding1",
Namespace: "default",
},
Spec: compapi.ComponentSpec{
Type: "bindings.cron",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "schedule", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`"@every 300ms"`)},
}},
{Name: "direction", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`"input"`)},
}},
},
},
}
h.operator.AddComponents(comp)
h.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, h.daprd.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10)
h.expectBinding(t, 0, "binding1")
})
}
func (h *http) expectBindings(t *testing.T, expected []bindingPair) {
t.Helper()
var wg sync.WaitGroup
defer wg.Wait()
wg.Add(len(expected))
for _, e := range expected {
go func(e bindingPair) {
h.expectBinding(t, e.i, e.b)
wg.Done()
}(e)
}
}
func (h *http) expectBinding(t *testing.T, i int, binding string) {
t.Helper()
h.listening[i].Store(true)
select {
case got := <-h.bindingChan[i]:
assert.Equal(t, "/"+binding, got)
case <-time.After(time.Second * 5):
assert.Fail(t, "timed out waiting for binding event")
}
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/binding/input/http.go
|
GO
|
mit
| 9,562 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package binding
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/dapr/dapr/pkg/apis/common"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
"github.com/dapr/dapr/pkg/operator/api"
operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/operator"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(output))
}
type output struct {
daprd *daprd.Daprd
operator *operator.Operator
bindingDir1 string
bindingDir2 string
bindingDir3 string
bindingDir1JSON common.DynamicValue
bindingDir2JSON common.DynamicValue
bindingDir3JSON common.DynamicValue
}
func (o *output) Setup(t *testing.T) []framework.Option {
sentry := sentry.New(t)
o.operator = operator.New(t,
operator.WithSentry(sentry),
operator.WithGetConfigurationFn(func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error) {
return &operatorv1.GetConfigurationResponse{
Configuration: []byte(
`{"kind":"Configuration","apiVersion":"dapr.io/v1alpha1","metadata":{"name":"hotreloading"},"spec":{"features":[{"name":"HotReload","enabled":true}]}}`,
),
}, nil
}),
)
o.bindingDir1, o.bindingDir2, o.bindingDir3 = t.TempDir(), t.TempDir(), t.TempDir()
dir1J, err := json.Marshal(o.bindingDir1)
require.NoError(t, err)
dir2J, err := json.Marshal(o.bindingDir2)
require.NoError(t, err)
dir3J, err := json.Marshal(o.bindingDir3)
require.NoError(t, err)
o.bindingDir1JSON = common.DynamicValue{JSON: apiextv1.JSON{Raw: dir1J}}
o.bindingDir2JSON = common.DynamicValue{JSON: apiextv1.JSON{Raw: dir2J}}
o.bindingDir3JSON = common.DynamicValue{JSON: apiextv1.JSON{Raw: dir3J}}
o.daprd = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors))),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(o.operator.Address(t)),
daprd.WithDisableK8sSecretStore(true),
)
return []framework.Option{
framework.WithProcesses(sentry, o.operator, o.daprd),
}
}
func (o *output) Run(t *testing.T, ctx context.Context) {
o.daprd.WaitUntilRunning(t, ctx)
client := util.HTTPClient(t)
t.Run("expect no components to be loaded yet", func(t *testing.T) {
assert.Empty(t, util.GetMetaComponents(t, ctx, client, o.daprd.HTTPPort()))
})
t.Run("adding a component should become available", func(t *testing.T) {
comp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "binding1",
Namespace: "default",
},
Spec: compapi.ComponentSpec{
Type: "bindings.localstorage",
Version: "v1",
Metadata: []common.NameValuePair{{
Name: "rootPath", Value: o.bindingDir1JSON,
}},
},
}
o.operator.SetComponents(comp)
o.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, o.daprd.HTTPPort()), 1)
}, time.Second*10, time.Millisecond*10)
o.postBinding(t, ctx, client, "binding1", "file1", "data1")
o.postBindingFail(t, ctx, client, "binding2")
o.postBindingFail(t, ctx, client, "binding3")
o.assertFile(t, o.bindingDir1, "file1", "data1")
})
t.Run("adding another component should become available", func(t *testing.T) {
comp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "binding2",
Namespace: "default",
},
Spec: compapi.ComponentSpec{
Type: "bindings.localstorage",
Version: "v1",
Metadata: []common.NameValuePair{{
Name: "rootPath", Value: o.bindingDir2JSON,
}},
},
}
o.operator.AddComponents(comp)
o.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, o.daprd.HTTPPort()), 2)
}, time.Second*10, time.Millisecond*10)
o.postBinding(t, ctx, client, "binding1", "file2", "data2")
o.postBinding(t, ctx, client, "binding2", "file1", "data1")
o.postBindingFail(t, ctx, client, "binding3")
o.assertFile(t, o.bindingDir1, "file2", "data2")
o.assertFile(t, o.bindingDir2, "file1", "data1")
})
t.Run("adding 3rd component should become available", func(t *testing.T) {
comp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "binding3",
Namespace: "default",
},
Spec: compapi.ComponentSpec{
Type: "bindings.localstorage",
Version: "v1",
Metadata: []common.NameValuePair{{
Name: "rootPath", Value: o.bindingDir3JSON,
}},
},
}
o.operator.AddComponents(comp)
o.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, o.daprd.HTTPPort()), 3)
}, time.Second*10, time.Millisecond*10)
o.postBinding(t, ctx, client, "binding1", "file3", "data3")
o.postBinding(t, ctx, client, "binding2", "file2", "data2")
o.postBinding(t, ctx, client, "binding3", "file1", "data1")
o.assertFile(t, o.bindingDir1, "file3", "data3")
o.assertFile(t, o.bindingDir2, "file2", "data2")
o.assertFile(t, o.bindingDir3, "file1", "data1")
})
t.Run("deleting component makes it no longer available", func(t *testing.T) {
comp := o.operator.Components()[0]
o.operator.SetComponents(o.operator.Components()[1:]...)
o.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_DELETED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, o.daprd.HTTPPort()), 2)
}, time.Second*10, time.Millisecond*10)
o.postBindingFail(t, ctx, client, "binding1")
assert.NoFileExists(t, filepath.Join(o.bindingDir1, "file4"))
o.postBinding(t, ctx, client, "binding2", "file3", "data3")
o.postBinding(t, ctx, client, "binding3", "file2", "data2")
o.assertFile(t, o.bindingDir2, "file3", "data3")
o.assertFile(t, o.bindingDir3, "file2", "data2")
})
t.Run("deleting component files are no longer available", func(t *testing.T) {
comp1 := o.operator.Components()[0]
comp2 := o.operator.Components()[1]
o.operator.SetComponents()
o.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp1, EventType: operatorv1.ResourceEventType_DELETED})
o.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp2, EventType: operatorv1.ResourceEventType_DELETED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Empty(c, util.GetMetaComponents(c, ctx, client, o.daprd.HTTPPort()))
}, time.Second*10, time.Millisecond*10)
o.postBindingFail(t, ctx, client, "binding1")
o.postBindingFail(t, ctx, client, "binding2")
o.postBindingFail(t, ctx, client, "binding3")
})
t.Run("recreating binding component should make it available again", func(t *testing.T) {
comp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "binding2",
Namespace: "default",
},
Spec: compapi.ComponentSpec{
Type: "bindings.localstorage",
Version: "v1",
Metadata: []common.NameValuePair{{
Name: "rootPath", Value: o.bindingDir2JSON,
}},
},
}
o.operator.AddComponents(comp)
o.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, o.daprd.HTTPPort()), 1)
}, time.Second*10, time.Millisecond*10)
o.postBinding(t, ctx, client, "binding2", "file5", "data5")
o.postBindingFail(t, ctx, client, "binding1")
o.postBindingFail(t, ctx, client, "binding3")
o.assertFile(t, o.bindingDir2, "file5", "data5")
})
}
func (o *output) postBinding(t *testing.T, ctx context.Context, client *http.Client, binding, file, data string) {
t.Helper()
url := fmt.Sprintf("http://localhost:%d/v1.0/bindings/%s", o.daprd.HTTPPort(), binding)
body := fmt.Sprintf(`{"operation":"create","data":"%s","metadata":{"fileName":"%s"}}`, data, file)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader(body))
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
respbody, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode, string(respbody))
}
func (o *output) postBindingFail(t *testing.T, ctx context.Context, client *http.Client, binding string) {
t.Helper()
url := fmt.Sprintf("http://localhost:%d/v1.0/bindings/%s", o.daprd.HTTPPort(), binding)
body := `{"operation":"create","data":"foo","metadata":{"fileName":"foo"}}`
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader(body))
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
respbody, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, http.StatusInternalServerError, resp.StatusCode, string(respbody))
}
func (o *output) assertFile(t *testing.T, dir, file, expData string) {
t.Helper()
fdata, err := os.ReadFile(filepath.Join(dir, file))
require.NoError(t, err)
assert.Equal(t, expData, string(fdata), fdata)
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/binding/output.go
|
GO
|
mit
| 10,738 |
/*
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"
"encoding/json"
"errors"
"io"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/dapr/dapr/pkg/apis/common"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
"github.com/dapr/dapr/pkg/operator/api"
commonv1 "github.com/dapr/dapr/pkg/proto/common/v1"
operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/operator"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(crypto))
}
type crypto struct {
daprd *daprd.Daprd
operator *operator.Operator
cryptoDir1 string
cryptoDir2 string
cryptoDir1JSON common.DynamicValue
cryptoDir2JSON common.DynamicValue
}
func (c *crypto) Setup(t *testing.T) []framework.Option {
sentry := sentry.New(t)
c.operator = operator.New(t,
operator.WithSentry(sentry),
operator.WithGetConfigurationFn(func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error) {
return &operatorv1.GetConfigurationResponse{
Configuration: []byte(
`{"kind":"Configuration","apiVersion":"dapr.io/v1alpha1","metadata":{"name":"hotreloading"},"spec":{"features":[{"name":"HotReload","enabled":true}]}}`,
),
}, nil
}),
)
c.cryptoDir1, c.cryptoDir2 = t.TempDir(), t.TempDir()
dir1J, err := json.Marshal(c.cryptoDir1)
require.NoError(t, err)
dir2J, err := json.Marshal(c.cryptoDir2)
require.NoError(t, err)
c.cryptoDir1JSON = common.DynamicValue{JSON: apiextv1.JSON{Raw: dir1J}}
c.cryptoDir2JSON = common.DynamicValue{JSON: apiextv1.JSON{Raw: dir2J}}
c.daprd = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors))),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(c.operator.Address(t)),
daprd.WithDisableK8sSecretStore(true),
)
return []framework.Option{
framework.WithProcesses(sentry, c.operator, c.daprd),
}
}
func (c *crypto) Run(t *testing.T, ctx context.Context) {
c.daprd.WaitUntilRunning(t, ctx)
client := c.daprd.GRPCClient(t, ctx)
t.Run("expect no components to be loaded yet", func(t *testing.T) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Empty(t, resp.GetRegisteredComponents())
c.encryptDecryptFail(t, ctx, client, "crypto1")
c.encryptDecryptFail(t, ctx, client, "crypto2")
})
t.Run("creating crypto component should make it available", func(t *testing.T) {
pk := make([]byte, 32)
for i := range pk {
pk[i] = byte(i)
}
require.NoError(t, os.WriteFile(filepath.Join(c.cryptoDir1, "crypto1"), pk, 0o600))
newComp := compapi.Component{
TypeMeta: metav1.TypeMeta{Kind: "Component", APIVersion: "dapr.io/v1alpha1"},
ObjectMeta: metav1.ObjectMeta{Name: "crypto1"},
Spec: compapi.ComponentSpec{
Type: "crypto.dapr.localstorage",
Version: "v1",
Metadata: []common.NameValuePair{{Name: "path", Value: c.cryptoDir1JSON}},
},
}
c.operator.SetComponents(newComp)
c.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &newComp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
//nolint:testifylint
assert.NoError(c, err)
assert.Len(c, resp.GetRegisteredComponents(), 1)
}, time.Second*10, time.Millisecond*10)
c.encryptDecrypt(t, ctx, client, "crypto1")
c.encryptDecryptFail(t, ctx, client, "crypto2")
c.encryptDecryptFail(t, ctx, client, "crypto3")
})
t.Run("creating another crypto component should make it available", func(t *testing.T) {
pk := make([]byte, 32)
for i := range pk {
pk[i] = byte(i + 32)
}
require.NoError(t, os.WriteFile(filepath.Join(c.cryptoDir2, "crypto2"), pk, 0o600))
newComp := compapi.Component{
TypeMeta: metav1.TypeMeta{Kind: "Component", APIVersion: "dapr.io/v1alpha1"},
ObjectMeta: metav1.ObjectMeta{Name: "crypto2"},
Spec: compapi.ComponentSpec{
Type: "crypto.dapr.localstorage",
Version: "v1",
Metadata: []common.NameValuePair{{Name: "path", Value: c.cryptoDir2JSON}},
},
}
c.operator.AddComponents(newComp)
c.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &newComp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
//nolint:testifylint
assert.NoError(c, err)
assert.Len(c, resp.GetRegisteredComponents(), 2)
}, time.Second*10, time.Millisecond*10)
c.encryptDecrypt(t, ctx, client, "crypto1")
c.encryptDecrypt(t, ctx, client, "crypto2")
c.encryptDecryptFail(t, ctx, client, "crypto3")
})
t.Run("creating third crypto component should make it available", func(t *testing.T) {
pk := make([]byte, 32)
for i := range pk {
pk[i] = byte(i + 32)
}
require.NoError(t, os.WriteFile(filepath.Join(c.cryptoDir2, "crypto3"), pk, 0o600))
newComp := compapi.Component{
TypeMeta: metav1.TypeMeta{Kind: "Component", APIVersion: "dapr.io/v1alpha1"},
ObjectMeta: metav1.ObjectMeta{Name: "crypto3"},
Spec: compapi.ComponentSpec{
Type: "crypto.dapr.localstorage",
Version: "v1",
Metadata: []common.NameValuePair{{Name: "path", Value: c.cryptoDir2JSON}},
},
}
c.operator.AddComponents(newComp)
c.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &newComp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
//nolint:testifylint
assert.NoError(c, err)
assert.Len(c, resp.GetRegisteredComponents(), 3)
}, time.Second*10, time.Millisecond*10)
c.encryptDecrypt(t, ctx, client, "crypto1")
c.encryptDecrypt(t, ctx, client, "crypto2")
c.encryptDecrypt(t, ctx, client, "crypto3")
})
t.Run("deleting crypto component (through type update) should make it no longer available", func(t *testing.T) {
updateComp := compapi.Component{
TypeMeta: metav1.TypeMeta{Kind: "Component", APIVersion: "dapr.io/v1alpha1"},
ObjectMeta: metav1.ObjectMeta{Name: "crypto2"},
Spec: compapi.ComponentSpec{
Type: "state.in-memory",
Version: "v1",
},
}
c.operator.SetComponents(c.operator.Components()[0], updateComp, c.operator.Components()[2])
c.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &updateComp, EventType: operatorv1.ResourceEventType_UPDATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
//nolint:testifylint
assert.NoError(c, err)
assert.ElementsMatch(c, []*rtv1.RegisteredComponents{
{Name: "crypto1", Type: "crypto.dapr.localstorage", Version: "v1"},
{Name: "crypto3", Type: "crypto.dapr.localstorage", Version: "v1"},
{
Name: "crypto2", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, resp.GetRegisteredComponents())
}, time.Second*10, time.Millisecond*10)
c.encryptDecrypt(t, ctx, client, "crypto1")
c.encryptDecryptFail(t, ctx, client, "crypto2")
c.encryptDecrypt(t, ctx, client, "crypto3")
})
t.Run("deleting all crypto components should make them no longer available", func(t *testing.T) {
delComp := c.operator.Components()[0]
c.operator.SetComponents(c.operator.Components()[1], c.operator.Components()[2])
c.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &delComp, EventType: operatorv1.ResourceEventType_DELETED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
//nolint:testifylint
assert.NoError(c, err)
assert.Len(c, resp.GetRegisteredComponents(), 2)
}, time.Second*10, time.Millisecond*10)
delComp = c.operator.Components()[0]
c.operator.SetComponents(c.operator.Components()[1])
c.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &delComp, EventType: operatorv1.ResourceEventType_DELETED})
updateComp := c.operator.Components()[0]
updateComp.Spec.Type = "state.in-memory"
updateComp.Spec.Metadata = nil
c.operator.SetComponents(updateComp)
assert.Equal(t, "crypto3", c.operator.Components()[0].Name)
c.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &updateComp, EventType: operatorv1.ResourceEventType_UPDATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
//nolint:testifylint
assert.NoError(c, err)
assert.ElementsMatch(c, []*rtv1.RegisteredComponents{
{
Name: "crypto3", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, resp.GetRegisteredComponents())
}, time.Second*10, time.Millisecond*10)
c.encryptDecryptFail(t, ctx, client, "crypto1")
c.encryptDecryptFail(t, ctx, client, "crypto2")
c.encryptDecryptFail(t, ctx, client, "crypto3")
})
t.Run("recreating crypto component should make it available again", func(t *testing.T) {
newComp := compapi.Component{
TypeMeta: metav1.TypeMeta{Kind: "Component", APIVersion: "dapr.io/v1alpha1"},
ObjectMeta: metav1.ObjectMeta{Name: "crypto2"},
Spec: compapi.ComponentSpec{
Type: "crypto.dapr.localstorage",
Version: "v1",
Metadata: []common.NameValuePair{{Name: "path", Value: c.cryptoDir2JSON}},
},
}
c.operator.AddComponents(newComp)
c.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &newComp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
//nolint:testifylint
assert.NoError(c, err)
assert.Len(c, resp.GetRegisteredComponents(), 2)
}, time.Second*10, time.Millisecond*10)
c.encryptDecryptFail(t, ctx, client, "crypto1")
c.encryptDecrypt(t, ctx, client, "crypto2")
c.encryptDecryptFail(t, ctx, client, "crypto3")
})
}
func (c *crypto) encryptDecryptFail(t *testing.T, ctx context.Context, client rtv1.DaprClient, name string) {
t.Helper()
encclient, err := client.EncryptAlpha1(ctx)
require.NoError(t, err)
require.NoError(t, encclient.Send(&rtv1.EncryptRequest{
Options: &rtv1.EncryptRequestOptions{
ComponentName: name,
KeyName: name,
KeyWrapAlgorithm: "AES",
},
Payload: &commonv1.StreamPayload{Data: []byte("hello"), Seq: 0},
}))
resp, err := encclient.Recv()
require.Error(t, err)
require.True(t,
strings.Contains(err.Error(), "not found") ||
strings.Contains(err.Error(), "crypto providers not configured"),
)
require.Nil(t, resp)
decclient, err := client.DecryptAlpha1(ctx)
require.NoError(t, err)
require.NoError(t, decclient.Send(&rtv1.DecryptRequest{
Options: &rtv1.DecryptRequestOptions{
ComponentName: name,
KeyName: name,
},
Payload: &commonv1.StreamPayload{Seq: 0, Data: []byte("hello")},
}))
respd, err := decclient.Recv()
require.Error(t, err)
require.True(t,
strings.Contains(err.Error(), "not found") ||
strings.Contains(err.Error(), "crypto providers not configured"),
)
require.Nil(t, respd)
}
func (c *crypto) encryptDecrypt(t *testing.T, ctx context.Context, client rtv1.DaprClient, name string) {
t.Helper()
encclient, err := client.EncryptAlpha1(ctx)
require.NoError(t, err)
require.NoError(t, encclient.Send(&rtv1.EncryptRequest{
Options: &rtv1.EncryptRequestOptions{
ComponentName: name,
KeyName: name,
KeyWrapAlgorithm: "AES",
},
Payload: &commonv1.StreamPayload{Data: []byte("hello"), Seq: 0},
}))
require.NoError(t, encclient.CloseSend())
var encdata []byte
for {
var resp *rtv1.EncryptResponse
resp, err = encclient.Recv()
if resp != nil {
encdata = append(encdata, resp.GetPayload().GetData()...)
}
if errors.Is(err, io.EOF) {
break
}
require.NoError(t, err)
}
decclient, err := client.DecryptAlpha1(ctx)
require.NoError(t, err)
require.NoError(t, decclient.Send(&rtv1.DecryptRequest{
Options: &rtv1.DecryptRequestOptions{
ComponentName: name,
KeyName: name,
},
Payload: &commonv1.StreamPayload{Seq: 0, Data: encdata},
}))
require.NoError(t, decclient.CloseSend())
var resp []byte
for {
respd, err := decclient.Recv()
if respd != nil {
resp = append(resp, respd.GetPayload().GetData()...)
}
if errors.Is(err, io.EOF) {
break
}
require.NoError(t, err)
}
assert.Equal(t, "hello", string(resp))
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/crypto.go
|
GO
|
mit
| 13,918 |
/*
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 informer
import (
"context"
"encoding/json"
"path/filepath"
"testing"
"time"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/dapr/dapr/pkg/apis/common"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
configapi "github.com/dapr/dapr/pkg/apis/configuration/v1alpha1"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/kubernetes"
"github.com/dapr/dapr/tests/integration/framework/process/kubernetes/store"
"github.com/dapr/dapr/tests/integration/framework/process/operator"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
"github.com/dapr/kit/ptr"
)
func init() {
suite.Register(new(components))
}
// components tests operator hot reloading with a live operator and daprd,
// using the process kubernetes informer.
type components struct {
daprd1 *daprd.Daprd
daprd2 *daprd.Daprd
store *store.Store
kubeapi *kubernetes.Kubernetes
operator *operator.Operator
}
func (c *components) Setup(t *testing.T) []framework.Option {
sentry := sentry.New(t, sentry.WithTrustDomain("integration.test.dapr.io"))
c.store = store.New(metav1.GroupVersionKind{
Group: "dapr.io",
Version: "v1alpha1",
Kind: "Component",
})
c.kubeapi = kubernetes.New(t,
kubernetes.WithBaseOperatorAPI(t,
spiffeid.RequireTrustDomainFromString("integration.test.dapr.io"),
"default",
sentry.Port(),
),
kubernetes.WithClusterDaprConfigurationList(t, &configapi.ConfigurationList{
Items: []configapi.Configuration{{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Configuration"},
ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "daprsystem"},
Spec: configapi.ConfigurationSpec{
MTLSSpec: &configapi.MTLSSpec{
ControlPlaneTrustDomain: "integration.test.dapr.io",
SentryAddress: sentry.Address(),
},
Features: []configapi.FeatureSpec{{
Name: "HotReload",
Enabled: ptr.Of(true),
}},
},
}},
}),
kubernetes.WithClusterDaprComponentListFromStore(t, c.store),
)
c.operator = operator.New(t,
operator.WithNamespace("default"),
operator.WithKubeconfigPath(c.kubeapi.KubeconfigPath(t)),
operator.WithTrustAnchorsFile(sentry.TrustAnchorsFile(t)),
)
opts := []daprd.Option{
daprd.WithMode("kubernetes"),
daprd.WithConfigs("daprsystem"),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(c.operator.Address()),
daprd.WithDisableK8sSecretStore(true),
daprd.WithEnableMTLS(true),
daprd.WithNamespace("default"),
daprd.WithExecOptions(exec.WithEnvVars(t,
"DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors),
)),
daprd.WithControlPlaneTrustDomain("integration.test.dapr.io"),
}
c.daprd1 = daprd.New(t, opts...)
c.daprd2 = daprd.New(t, opts...)
return []framework.Option{
framework.WithProcesses(sentry, c.kubeapi, c.operator, c.daprd1, c.daprd2),
}
}
func (c *components) Run(t *testing.T, ctx context.Context) {
c.operator.WaitUntilRunning(t, ctx)
c.daprd1.WaitUntilRunning(t, ctx)
c.daprd2.WaitUntilRunning(t, ctx)
client := util.HTTPClient(t)
t.Run("expect no components to be loaded yet", func(t *testing.T) {
assert.Empty(t, util.GetMetaComponents(t, ctx, client, c.daprd1.HTTPPort()))
assert.Empty(t, util.GetMetaComponents(t, ctx, client, c.daprd2.HTTPPort()))
})
t.Run("adding a component should become available", func(t *testing.T) {
comp := compapi.Component{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Component"},
ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "default"},
Spec: compapi.ComponentSpec{
Type: "state.in-memory",
Version: "v1",
},
}
c.store.Add(&comp)
c.kubeapi.Informer().Add(t, &comp)
require.EventuallyWithT(t, func(ct *assert.CollectT) {
assert.Len(ct, util.GetMetaComponents(ct, ctx, client, c.daprd1.HTTPPort()), 1)
assert.Len(ct, util.GetMetaComponents(ct, ctx, client, c.daprd2.HTTPPort()), 1)
}, time.Second*10, time.Millisecond*10)
exp := []*rtv1.RegisteredComponents{
{
Name: "123", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}
assert.ElementsMatch(t, exp, util.GetMetaComponents(t, ctx, client, c.daprd1.HTTPPort()))
assert.ElementsMatch(t, exp, util.GetMetaComponents(t, ctx, client, c.daprd2.HTTPPort()))
})
dir := filepath.Join(t.TempDir(), "db.sqlite")
dirJSON, err := json.Marshal(dir)
require.NoError(t, err)
comp := compapi.Component{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Component"},
ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "default"},
Spec: compapi.ComponentSpec{
Type: "state.sqlite",
Version: "v1",
IgnoreErrors: true,
Metadata: []common.NameValuePair{
{Name: "connectionString", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: dirJSON},
}},
{Name: "busyTimeout", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`"10s"`)},
}},
},
},
}
t.Run("updating component should be updated", func(t *testing.T) {
c.store.Set(&comp)
c.kubeapi.Informer().Modify(t, &comp)
require.EventuallyWithT(t, func(ct *assert.CollectT) {
exp := []*rtv1.RegisteredComponents{
{
Name: "123", Type: "state.sqlite", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "ACTOR"},
},
}
assert.ElementsMatch(ct, exp, util.GetMetaComponents(ct, ctx, client, c.daprd1.HTTPPort()))
assert.ElementsMatch(ct, exp, util.GetMetaComponents(ct, ctx, client, c.daprd2.HTTPPort()))
}, time.Second*20, time.Millisecond*10)
})
t.Run("deleting a component should delete the component", func(t *testing.T) {
c.store.Set()
c.kubeapi.Informer().Delete(t, &comp)
require.EventuallyWithT(t, func(ct *assert.CollectT) {
assert.Empty(ct, util.GetMetaComponents(ct, ctx, client, c.daprd1.HTTPPort()))
assert.Empty(ct, util.GetMetaComponents(ct, ctx, client, c.daprd2.HTTPPort()))
}, time.Second*20, time.Millisecond*10)
})
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/informer/components.go
|
GO
|
mit
| 7,165 |
/*
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 informer
import (
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/operator/informer/reconnect"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/operator/informer/scopes"
)
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/informer/informer.go
|
GO
|
mit
| 775 |
/*
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 reconnect
import (
"context"
"testing"
"time"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
configapi "github.com/dapr/dapr/pkg/apis/configuration/v1alpha1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/kubernetes"
"github.com/dapr/dapr/tests/integration/framework/process/kubernetes/store"
"github.com/dapr/dapr/tests/integration/framework/process/operator"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
"github.com/dapr/kit/ptr"
)
func init() {
suite.Register(new(components))
}
type components struct {
daprd1 *daprd.Daprd
daprd2 *daprd.Daprd
store *store.Store
kubeapi *kubernetes.Kubernetes
operator1 *operator.Operator
operator2 *operator.Operator
operator3 *operator.Operator
}
func (c *components) Setup(t *testing.T) []framework.Option {
sentry := sentry.New(t, sentry.WithTrustDomain("integration.test.dapr.io"))
c.store = store.New(metav1.GroupVersionKind{
Group: "dapr.io",
Version: "v1alpha1",
Kind: "Component",
})
c.kubeapi = kubernetes.New(t,
kubernetes.WithBaseOperatorAPI(t,
spiffeid.RequireTrustDomainFromString("integration.test.dapr.io"),
"default",
sentry.Port(),
),
kubernetes.WithClusterDaprConfigurationList(t, &configapi.ConfigurationList{
Items: []configapi.Configuration{{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Configuration"},
ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "daprsystem"},
Spec: configapi.ConfigurationSpec{
MTLSSpec: &configapi.MTLSSpec{
ControlPlaneTrustDomain: "integration.test.dapr.io",
SentryAddress: sentry.Address(),
},
Features: []configapi.FeatureSpec{{
Name: "HotReload",
Enabled: ptr.Of(true),
}},
},
}},
}),
kubernetes.WithClusterDaprComponentListFromStore(t, c.store),
)
oopts := []operator.Option{
operator.WithNamespace("default"),
operator.WithKubeconfigPath(c.kubeapi.KubeconfigPath(t)),
operator.WithTrustAnchorsFile(sentry.TrustAnchorsFile(t)),
}
c.operator1 = operator.New(t, oopts...)
c.operator2 = operator.New(t, append(oopts,
operator.WithAPIPort(c.operator1.Port()),
)...)
c.operator3 = operator.New(t, append(oopts,
operator.WithAPIPort(c.operator1.Port()),
)...)
dopts := []daprd.Option{
daprd.WithMode("kubernetes"),
daprd.WithConfigs("daprsystem"),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(c.operator1.Address()),
daprd.WithControlPlaneTrustDomain("integration.test.dapr.io"),
daprd.WithDisableK8sSecretStore(true),
daprd.WithEnableMTLS(true),
daprd.WithNamespace("default"),
daprd.WithExecOptions(exec.WithEnvVars(t,
"DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors),
)),
}
c.daprd1 = daprd.New(t, dopts...)
c.daprd2 = daprd.New(t, dopts...)
return []framework.Option{
framework.WithProcesses(sentry, c.kubeapi, c.daprd1, c.daprd2),
}
}
func (c *components) Run(t *testing.T, ctx context.Context) {
c.operator1.Run(t, ctx)
c.operator1.WaitUntilRunning(t, ctx)
c.daprd1.WaitUntilRunning(t, ctx)
c.daprd2.WaitUntilRunning(t, ctx)
client := util.HTTPClient(t)
comp := compapi.Component{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Component"},
ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "default"},
Spec: compapi.ComponentSpec{Type: "state.in-memory", Version: "v1"},
}
c.store.Add(&comp)
c.kubeapi.Informer().Add(t, &comp)
require.EventuallyWithT(t, func(t *assert.CollectT) {
assert.Len(t, c.daprd1.GetMetaRegistedComponents(t, ctx), 1)
assert.Len(t, c.daprd2.GetMetaRegistedComponents(t, ctx), 1)
}, time.Second*10, time.Millisecond*10)
c.operator1.Cleanup(t)
c.store.Set()
c.kubeapi.Informer().Delete(t, &comp)
c.operator2.Run(t, ctx)
c.operator2.WaitUntilRunning(t, ctx)
require.EventuallyWithT(t, func(t *assert.CollectT) {
assert.Empty(t, util.GetMetaComponents(t, ctx, client, c.daprd1.HTTPPort()))
assert.Empty(t, util.GetMetaComponents(t, ctx, client, c.daprd2.HTTPPort()))
}, time.Second*10, time.Millisecond*10)
c.operator2.Cleanup(t)
c.store.Add(&comp)
c.kubeapi.Informer().Add(t, &comp)
c.operator3.Run(t, ctx)
c.operator3.WaitUntilRunning(t, ctx)
require.EventuallyWithT(t, func(t *assert.CollectT) {
assert.Len(t, util.GetMetaComponents(t, ctx, client, c.daprd1.HTTPPort()), 1)
assert.Len(t, util.GetMetaComponents(t, ctx, client, c.daprd2.HTTPPort()), 1)
}, time.Second*10, time.Millisecond*10)
c.operator3.Cleanup(t)
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/informer/reconnect/components.go
|
GO
|
mit
| 5,557 |
/*
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 reconnect
import (
"context"
"testing"
"time"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
configapi "github.com/dapr/dapr/pkg/apis/configuration/v1alpha1"
subapi "github.com/dapr/dapr/pkg/apis/subscriptions/v2alpha1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/kubernetes"
"github.com/dapr/dapr/tests/integration/framework/process/kubernetes/store"
"github.com/dapr/dapr/tests/integration/framework/process/operator"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/suite"
"github.com/dapr/kit/ptr"
)
func init() {
suite.Register(new(subscriptions))
}
type subscriptions struct {
daprd *daprd.Daprd
compStore *store.Store
subStore *store.Store
kubeapi *kubernetes.Kubernetes
operator1 *operator.Operator
operator2 *operator.Operator
operator3 *operator.Operator
}
func (s *subscriptions) Setup(t *testing.T) []framework.Option {
sentry := sentry.New(t, sentry.WithTrustDomain("integration.test.dapr.io"))
s.compStore = store.New(metav1.GroupVersionKind{
Group: "dapr.io",
Version: "v1alpha1",
Kind: "Component",
})
s.subStore = store.New(metav1.GroupVersionKind{
Group: "dapr.io",
Version: "v2alpha1",
Kind: "Subscription",
})
s.kubeapi = kubernetes.New(t,
kubernetes.WithBaseOperatorAPI(t,
spiffeid.RequireTrustDomainFromString("integration.test.dapr.io"),
"default",
sentry.Port(),
),
kubernetes.WithClusterDaprConfigurationList(t, &configapi.ConfigurationList{
Items: []configapi.Configuration{{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Configuration"},
ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "daprsystem"},
Spec: configapi.ConfigurationSpec{
MTLSSpec: &configapi.MTLSSpec{
ControlPlaneTrustDomain: "integration.test.dapr.io",
SentryAddress: sentry.Address(),
},
Features: []configapi.FeatureSpec{{
Name: "HotReload",
Enabled: ptr.Of(true),
}},
},
}},
}),
kubernetes.WithClusterDaprComponentListFromStore(t, s.compStore),
kubernetes.WithClusterDaprSubscriptionV2ListFromStore(t, s.subStore),
)
opts := []operator.Option{
operator.WithNamespace("default"),
operator.WithKubeconfigPath(s.kubeapi.KubeconfigPath(t)),
operator.WithTrustAnchorsFile(sentry.TrustAnchorsFile(t)),
}
s.operator1 = operator.New(t, opts...)
s.operator2 = operator.New(t, append(opts,
operator.WithAPIPort(s.operator1.Port()),
)...)
s.operator3 = operator.New(t, append(opts,
operator.WithAPIPort(s.operator1.Port()),
)...)
s.daprd = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("daprsystem"),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(s.operator1.Address()),
daprd.WithControlPlaneTrustDomain("integration.test.dapr.io"),
daprd.WithDisableK8sSecretStore(true),
daprd.WithEnableMTLS(true),
daprd.WithNamespace("default"),
daprd.WithExecOptions(exec.WithEnvVars(t,
"DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors),
)),
)
return []framework.Option{
framework.WithProcesses(sentry, s.kubeapi, s.daprd),
}
}
func (s *subscriptions) Run(t *testing.T, ctx context.Context) {
s.operator1.Run(t, ctx)
s.operator1.WaitUntilRunning(t, ctx)
s.daprd.WaitUntilRunning(t, ctx)
comp := compapi.Component{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Component"},
ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "default"},
Spec: compapi.ComponentSpec{Type: "pubsub.in-memory", Version: "v1"},
}
sub := subapi.Subscription{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v2alpha1", Kind: "Subscription"},
ObjectMeta: metav1.ObjectMeta{Name: "sub0", Namespace: "default"},
Spec: subapi.SubscriptionSpec{
Pubsubname: "123", Topic: "a",
Routes: subapi.Routes{Default: "/a"},
},
}
s.compStore.Add(&comp)
s.subStore.Add(&sub)
s.kubeapi.Informer().Add(t, &comp)
s.kubeapi.Informer().Add(t, &sub)
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, s.daprd.GetMetaRegistedComponents(c, ctx), 1)
assert.Len(c, s.daprd.GetMetaSubscriptions(c, ctx), 1)
}, time.Second*10, time.Millisecond*10)
s.operator1.Cleanup(t)
s.subStore.Set()
s.kubeapi.Informer().Delete(t, &sub)
s.operator2.Run(t, ctx)
s.operator2.WaitUntilRunning(t, ctx)
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, s.daprd.GetMetaRegistedComponents(c, ctx), 1)
assert.Empty(c, s.daprd.GetMetaSubscriptions(c, ctx))
}, time.Second*10, time.Millisecond*10)
s.operator2.Cleanup(t)
s.subStore.Add(&sub)
s.kubeapi.Informer().Add(t, &sub)
s.operator3.Run(t, ctx)
s.operator3.WaitUntilRunning(t, ctx)
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, s.daprd.GetMetaRegistedComponents(c, ctx), 1)
assert.Len(c, s.daprd.GetMetaSubscriptions(c, ctx), 1)
}, time.Second*10, time.Millisecond*10)
s.operator3.Cleanup(t)
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/informer/reconnect/subscriptions.go
|
GO
|
mit
| 5,902 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package scopes
import (
"context"
"testing"
"time"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
configapi "github.com/dapr/dapr/pkg/apis/configuration/v1alpha1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/kubernetes"
"github.com/dapr/dapr/tests/integration/framework/process/kubernetes/store"
"github.com/dapr/dapr/tests/integration/framework/process/operator"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
"github.com/dapr/kit/ptr"
)
func init() {
suite.Register(new(components))
}
type components struct {
daprd *daprd.Daprd
store *store.Store
kubeapi *kubernetes.Kubernetes
operator1 *operator.Operator
operator2 *operator.Operator
}
func (c *components) Setup(t *testing.T) []framework.Option {
sentry := sentry.New(t, sentry.WithTrustDomain("integration.test.dapr.io"))
c.store = store.New(metav1.GroupVersionKind{
Group: "dapr.io",
Version: "v1alpha1",
Kind: "Component",
})
c.kubeapi = kubernetes.New(t,
kubernetes.WithBaseOperatorAPI(t,
spiffeid.RequireTrustDomainFromString("integration.test.dapr.io"),
"default",
sentry.Port(),
),
kubernetes.WithClusterDaprConfigurationList(t, &configapi.ConfigurationList{
Items: []configapi.Configuration{{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Configuration"},
ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "daprsystem"},
Spec: configapi.ConfigurationSpec{
MTLSSpec: &configapi.MTLSSpec{
ControlPlaneTrustDomain: "integration.test.dapr.io",
SentryAddress: sentry.Address(),
},
Features: []configapi.FeatureSpec{{
Name: "HotReload",
Enabled: ptr.Of(true),
}},
},
}},
}),
kubernetes.WithClusterDaprComponentListFromStore(t, c.store),
)
opts := []operator.Option{
operator.WithNamespace("default"),
operator.WithKubeconfigPath(c.kubeapi.KubeconfigPath(t)),
operator.WithTrustAnchorsFile(sentry.TrustAnchorsFile(t)),
}
c.operator1 = operator.New(t, opts...)
c.operator2 = operator.New(t, append(opts,
operator.WithAPIPort(c.operator1.Port()),
)...)
c.daprd = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("daprsystem"),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(c.operator1.Address()),
daprd.WithDisableK8sSecretStore(true),
daprd.WithEnableMTLS(true),
daprd.WithNamespace("default"),
daprd.WithControlPlaneTrustDomain("integration.test.dapr.io"),
daprd.WithExecOptions(exec.WithEnvVars(t,
"DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors),
)),
)
return []framework.Option{
framework.WithProcesses(sentry, c.kubeapi, c.daprd),
}
}
func (c *components) Run(t *testing.T, ctx context.Context) {
c.operator1.Run(t, ctx)
c.operator1.WaitUntilRunning(t, ctx)
c.daprd.WaitUntilRunning(t, ctx)
client := util.HTTPClient(t)
comp := compapi.Component{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Component"},
ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "default"},
Spec: compapi.ComponentSpec{Type: "state.in-memory", Version: "v1"},
}
c.store.Add(&comp)
c.kubeapi.Informer().Add(t, &comp)
require.EventuallyWithT(t, func(t *assert.CollectT) {
assert.Len(t, util.GetMetaComponents(t, ctx, client, c.daprd.HTTPPort()), 1)
}, time.Second*10, time.Millisecond*10)
comp.Scopes = []string{"foo"}
c.store.Set(&comp)
c.kubeapi.Informer().Modify(t, &comp)
require.EventuallyWithT(t, func(t *assert.CollectT) {
assert.Empty(t, util.GetMetaComponents(t, ctx, client, c.daprd.HTTPPort()))
}, time.Second*10, time.Millisecond*10)
comp.Scopes = []string{"foo", c.daprd.AppID()}
c.store.Set(&comp)
c.kubeapi.Informer().Modify(t, &comp)
require.EventuallyWithT(t, func(t *assert.CollectT) {
assert.Len(t, util.GetMetaComponents(t, ctx, client, c.daprd.HTTPPort()), 1)
}, time.Second*10, time.Millisecond*10)
comp.Scopes = []string{"foo"}
c.operator1.Cleanup(t)
c.store.Set(&comp)
c.operator2.Run(t, ctx)
t.Cleanup(func() { c.operator2.Cleanup(t) })
c.operator2.WaitUntilRunning(t, ctx)
c.store.Set(&comp)
c.kubeapi.Informer().Modify(t, &comp)
require.EventuallyWithT(t, func(t *assert.CollectT) {
assert.Empty(t, util.GetMetaComponents(t, ctx, client, c.daprd.HTTPPort()))
}, time.Second*10, time.Millisecond*10)
comp.Scopes = []string{}
c.store.Set(&comp)
c.kubeapi.Informer().Modify(t, &comp)
require.EventuallyWithT(t, func(t *assert.CollectT) {
assert.Len(t, util.GetMetaComponents(t, ctx, client, c.daprd.HTTPPort()), 1)
}, time.Second*10, time.Millisecond*10)
comp2 := comp.DeepCopy()
comp2.Name = "456"
comp2.Scopes = []string{c.daprd.AppID()}
c.store.Set(&comp, comp2)
c.kubeapi.Informer().Modify(t, comp2)
require.EventuallyWithT(t, func(t *assert.CollectT) {
assert.Len(t, util.GetMetaComponents(t, ctx, client, c.daprd.HTTPPort()), 2)
}, time.Second*10, time.Millisecond*10)
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/informer/scopes/components.go
|
GO
|
mit
| 5,970 |
/*
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 informer
import (
"context"
"testing"
"time"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
configapi "github.com/dapr/dapr/pkg/apis/configuration/v1alpha1"
subapi "github.com/dapr/dapr/pkg/apis/subscriptions/v2alpha1"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/subscriber"
"github.com/dapr/dapr/tests/integration/framework/process/kubernetes"
"github.com/dapr/dapr/tests/integration/framework/process/kubernetes/store"
"github.com/dapr/dapr/tests/integration/framework/process/operator"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/suite"
"github.com/dapr/kit/ptr"
)
func init() {
suite.Register(new(subscriptions))
}
type subscriptions struct {
sub *subscriber.Subscriber
daprd *daprd.Daprd
compStore *store.Store
subStore *store.Store
kubeapi *kubernetes.Kubernetes
operator *operator.Operator
}
func (s *subscriptions) Setup(t *testing.T) []framework.Option {
s.sub = subscriber.New(t)
sentry := sentry.New(t, sentry.WithTrustDomain("integration.test.dapr.io"))
s.compStore = store.New(metav1.GroupVersionKind{
Group: "dapr.io",
Version: "v1alpha1",
Kind: "Component",
})
s.subStore = store.New(metav1.GroupVersionKind{
Group: "dapr.io",
Version: "v2alpha1",
Kind: "Subscription",
})
s.compStore.Add(&compapi.Component{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Component"},
ObjectMeta: metav1.ObjectMeta{Name: "pubsub0", Namespace: "default"},
Spec: compapi.ComponentSpec{Type: "pubsub.in-memory", Version: "v1"},
})
s.kubeapi = kubernetes.New(t,
kubernetes.WithBaseOperatorAPI(t,
spiffeid.RequireTrustDomainFromString("integration.test.dapr.io"),
"default",
sentry.Port(),
),
kubernetes.WithClusterDaprConfigurationList(t, &configapi.ConfigurationList{
Items: []configapi.Configuration{{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Configuration"},
ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "daprsystem"},
Spec: configapi.ConfigurationSpec{
MTLSSpec: &configapi.MTLSSpec{
ControlPlaneTrustDomain: "integration.test.dapr.io",
SentryAddress: sentry.Address(),
},
Features: []configapi.FeatureSpec{{
Name: "HotReload",
Enabled: ptr.Of(true),
}},
},
}},
}),
kubernetes.WithClusterDaprComponentListFromStore(t, s.compStore),
kubernetes.WithClusterDaprSubscriptionV2ListFromStore(t, s.subStore),
)
s.operator = operator.New(t,
operator.WithNamespace("default"),
operator.WithKubeconfigPath(s.kubeapi.KubeconfigPath(t)),
operator.WithTrustAnchorsFile(sentry.TrustAnchorsFile(t)),
)
s.daprd = daprd.New(t,
daprd.WithAppPort(s.sub.Port(t)),
daprd.WithAppProtocol("grpc"),
daprd.WithMode("kubernetes"),
daprd.WithConfigs("daprsystem"),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(s.operator.Address()),
daprd.WithDisableK8sSecretStore(true),
daprd.WithEnableMTLS(true),
daprd.WithNamespace("default"),
daprd.WithExecOptions(exec.WithEnvVars(t,
"DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors),
)),
daprd.WithControlPlaneTrustDomain("integration.test.dapr.io"),
)
return []framework.Option{
framework.WithProcesses(sentry, s.sub, s.kubeapi, s.operator, s.daprd),
}
}
func (s *subscriptions) Run(t *testing.T, ctx context.Context) {
s.operator.WaitUntilRunning(t, ctx)
s.daprd.WaitUntilRunning(t, ctx)
assert.Len(t, s.daprd.GetMetaRegistedComponents(t, ctx), 1)
newReq := func(pubsub, topic string) *rtv1.PublishEventRequest {
return &rtv1.PublishEventRequest{PubsubName: pubsub, Topic: topic, Data: []byte(`{"status": "completed"}`)}
}
s.sub.ExpectPublishNoReceive(t, ctx, s.daprd, newReq("pubsub0", "a"))
s.sub.ExpectPublishNoReceive(t, ctx, s.daprd, newReq("pubsub0", "b"))
sub1 := subapi.Subscription{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v2alpha1", Kind: "Subscription"},
ObjectMeta: metav1.ObjectMeta{Name: "sub0", Namespace: "default"},
Spec: subapi.SubscriptionSpec{
Pubsubname: "pubsub0", Topic: "a",
Routes: subapi.Routes{Default: "/a"},
},
}
s.subStore.Add(&sub1)
s.kubeapi.Informer().Add(t, &sub1)
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, s.daprd.GetMetaSubscriptions(c, ctx), 1)
}, time.Second*10, time.Millisecond*10)
s.sub.ExpectPublishReceive(t, ctx, s.daprd, newReq("pubsub0", "a"))
s.sub.ExpectPublishNoReceive(t, ctx, s.daprd, newReq("pubsub0", "b"))
sub2 := subapi.Subscription{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v2alpha1", Kind: "Subscription"},
ObjectMeta: metav1.ObjectMeta{Name: "sub1", Namespace: "default"},
Spec: subapi.SubscriptionSpec{
Pubsubname: "pubsub0", Topic: "b",
Routes: subapi.Routes{Default: "/b"},
},
}
s.subStore.Add(&sub2)
s.kubeapi.Informer().Add(t, &sub2)
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, s.daprd.GetMetaSubscriptions(c, ctx), 2)
}, time.Second*10, time.Millisecond*10)
s.sub.ExpectPublishReceive(t, ctx, s.daprd, newReq("pubsub0", "a"))
s.sub.ExpectPublishReceive(t, ctx, s.daprd, newReq("pubsub0", "b"))
sub2.Spec.Topic = "c"
s.subStore.Set(&sub1, &sub2)
s.kubeapi.Informer().Modify(t, &sub2)
assert.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := s.daprd.GRPCClient(t, ctx).GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
if assert.Len(c, resp.GetSubscriptions(), 2) {
assert.Equal(c, "a", resp.GetSubscriptions()[0].GetTopic())
assert.Equal(c, "c", resp.GetSubscriptions()[1].GetTopic())
}
}, time.Second*15, time.Millisecond*10)
s.sub.ExpectPublishReceive(t, ctx, s.daprd, newReq("pubsub0", "a"))
s.sub.ExpectPublishNoReceive(t, ctx, s.daprd, newReq("pubsub0", "b"))
s.sub.ExpectPublishReceive(t, ctx, s.daprd, newReq("pubsub0", "c"))
s.subStore.Set(&sub1)
s.kubeapi.Informer().Delete(t, &sub2)
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, s.daprd.GetMetaSubscriptions(c, ctx), 1)
}, time.Second*25, time.Millisecond*10)
s.sub.ExpectPublishNoReceive(t, ctx, s.daprd, newReq("pubsub0", "c"))
s.sub.ExpectPublishNoReceive(t, ctx, s.daprd, newReq("pubsub0", "b"))
s.sub.ExpectPublishReceive(t, ctx, s.daprd, newReq("pubsub0", "a"))
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/informer/subscriptions.go
|
GO
|
mit
| 7,313 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package app
import (
"context"
"fmt"
"io"
nethttp "net/http"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/dapr/dapr/pkg/apis/common"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
"github.com/dapr/dapr/pkg/operator/api"
operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/operator"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(routeralias))
}
type routeralias struct {
daprd1 *daprd.Daprd
daprd2 *daprd.Daprd
operator *operator.Operator
}
func (r *routeralias) Setup(t *testing.T) []framework.Option {
sentry := sentry.New(t)
r.operator = operator.New(t,
operator.WithSentry(sentry),
operator.WithGetConfigurationFn(func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error) {
return &operatorv1.GetConfigurationResponse{
Configuration: []byte(
`{"kind":"Configuration","apiVersion":"dapr.io/v1alpha1","metadata":{"name":"hotreloading"},"spec":{"nameResolution": {"component": "mdns"}, "features":[{"name":"HotReload","enabled":true}],
"appHttpPipeline":{"handlers":[{"name":"routeralias1","type":"middleware.http.routeralias"},{"name":"routeralias2","type":"middleware.http.routeralias"},{"name":"routeralias3","type":"middleware.http.routeralias"}]}}}`,
),
}, nil
}),
)
r.operator.SetComponents(compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "routeralias1",
Namespace: "ns1",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.routeralias",
Version: "v1",
Metadata: []common.NameValuePair{{Name: "routes", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`{"/helloworld":"/foobar","/xyz":"/abc"}`)},
}}},
},
}, compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "routeralias2",
Namespace: "ns1",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.routeralias",
Version: "v1",
Metadata: []common.NameValuePair{{Name: "routes", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`{"/helloworld":"/xyz","/foobar":"/abc"}`)},
}}},
},
})
srv := func(id string) *prochttp.HTTP {
handler := nethttp.NewServeMux()
handler.HandleFunc("/", func(w nethttp.ResponseWriter, r *nethttp.Request) {
fmt.Fprintf(w, "%s:%s", id, r.URL.Path)
})
return prochttp.New(t, prochttp.WithHandler(handler))
}
srv1 := srv("daprd1")
srv2 := srv("daprd2")
r.daprd1 = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors))),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(r.operator.Address(t)),
daprd.WithDisableK8sSecretStore(true),
daprd.WithNamespace("ns2"),
daprd.WithAppPort(srv1.Port()),
)
r.daprd2 = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors))),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(r.operator.Address(t)),
daprd.WithDisableK8sSecretStore(true),
daprd.WithNamespace("ns1"),
daprd.WithAppPort(srv2.Port()),
)
return []framework.Option{
framework.WithProcesses(sentry, srv1, srv2, r.operator, r.daprd1, r.daprd2),
}
}
func (r *routeralias) Run(t *testing.T, ctx context.Context) {
r.daprd1.WaitUntilAppHealth(t, ctx)
r.daprd2.WaitUntilAppHealth(t, ctx)
client := util.HTTPClient(t)
r.doReq(t, ctx, client, fmt.Sprintf("/v1.0/invoke/%s/method/helloworld", r.daprd2.AppID()), "daprd2:/abc")
comp1 := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "routeralias1",
Namespace: "ns1",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.routeralias",
Version: "v1",
Metadata: []common.NameValuePair{{Name: "routes", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`{"/abc":"/barfoo","/xyz":"/abc"}`)},
}}},
},
}
comp2 := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "routeralias2",
Namespace: "ns1",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.routeralias",
Version: "v1",
Metadata: []common.NameValuePair{{Name: "routes", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`{"/helloworld":"/xyz","/foobar":"/abc"}`)},
}}},
},
}
comp3 := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "routeralias3",
Namespace: "ns1",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.routeralias",
Version: "v1",
Metadata: []common.NameValuePair{{Name: "routes", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`{"/helloworld":"/eee","/foobar":"/fff","/xyz":"/aaa"}`)},
}}},
},
}
r.operator.SetComponents(comp1, comp2, comp3)
r.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp1, EventType: operatorv1.ResourceEventType_UPDATED})
r.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp2, EventType: operatorv1.ResourceEventType_UPDATED})
r.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp3, EventType: operatorv1.ResourceEventType_CREATED})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
r.doReq(c, ctx, client, fmt.Sprintf("/v1.0/invoke/%s/method/helloworld", r.daprd2.AppID()), "daprd2:/aaa")
}, time.Second*10, time.Millisecond*10)
}
func (r *routeralias) doReq(t require.TestingT, ctx context.Context, client *nethttp.Client, path, expect string) {
url := fmt.Sprintf("http://localhost:%d/%s", r.daprd1.HTTPPort(), path)
req, err := nethttp.NewRequestWithContext(ctx, nethttp.MethodPost, url, nil)
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, nethttp.StatusOK, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, expect, string(body))
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/middleware/http/app/routeralias.go
|
GO
|
mit
| 7,178 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package app
import (
"context"
"fmt"
"io"
nethttp "net/http"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/dapr/dapr/pkg/apis/common"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
"github.com/dapr/dapr/pkg/operator/api"
operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/operator"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(uppercase))
}
type uppercase struct {
daprd1 *daprd.Daprd
daprd2 *daprd.Daprd
daprd3 *daprd.Daprd
operator *operator.Operator
}
func (u *uppercase) Setup(t *testing.T) []framework.Option {
sentry := sentry.New(t)
u.operator = operator.New(t,
operator.WithSentry(sentry),
operator.WithGetConfigurationFn(func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error) {
return &operatorv1.GetConfigurationResponse{
Configuration: []byte(
`{"kind":"Configuration","apiVersion":"dapr.io/v1alpha1","metadata":{"name":"hotreloading"},"spec":{"nameResolution": {"component": "mdns"}, "features":[{"name":"HotReload","enabled":true}],
"appHttpPipeline":{"handlers":[{"name":"uppercase","type":"middleware.http.uppercase"},{"name":"uppercase2","type":"middleware.http.uppercase"}]}}}`,
),
}, nil
}),
)
handler := nethttp.NewServeMux()
handler.HandleFunc("/", func(nethttp.ResponseWriter, *nethttp.Request) {})
handler.HandleFunc("/foo", func(w nethttp.ResponseWriter, r *nethttp.Request) {
_, err := io.Copy(w, r.Body)
require.NoError(t, err)
})
srv := prochttp.New(t, prochttp.WithHandler(handler))
u.operator.SetComponents(compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "uppercase",
Namespace: "ns1",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.uppercase",
Version: "v1",
},
}, compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "uppercase2",
Namespace: "ns1",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.routeralias",
Version: "v1",
Metadata: []common.NameValuePair{{Name: "routes", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`{"/foo":"/v1.0/invoke/nowhere/method/bar"}`)},
}}},
},
})
u.daprd1 = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors))),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(u.operator.Address(t)),
daprd.WithDisableK8sSecretStore(true),
daprd.WithNamespace("ns1"),
daprd.WithAppPort(srv.Port()),
)
u.daprd2 = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors))),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(u.operator.Address(t)),
daprd.WithDisableK8sSecretStore(true),
daprd.WithNamespace("ns2"),
daprd.WithAppPort(srv.Port()),
)
u.daprd3 = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors))),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(u.operator.Address(t)),
daprd.WithDisableK8sSecretStore(true),
daprd.WithNamespace("ns3"),
daprd.WithAppPort(srv.Port()),
)
return []framework.Option{
framework.WithProcesses(srv, sentry, u.operator, u.daprd1, u.daprd2, u.daprd3),
}
}
func (u *uppercase) Run(t *testing.T, ctx context.Context) {
u.daprd1.WaitUntilAppHealth(t, ctx)
u.daprd2.WaitUntilAppHealth(t, ctx)
u.daprd3.WaitUntilAppHealth(t, ctx)
client := util.HTTPClient(t)
assert.Len(t, util.GetMetaComponents(t, ctx, client, u.daprd1.HTTPPort()), 2)
t.Run("existing middleware should be loaded", func(t *testing.T) {
u.doReq(t, ctx, client, u.daprd1, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, false)
})
t.Run("adding a new middleware should be loaded", func(t *testing.T) {
newComp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "uppercase",
Namespace: "ns2",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.uppercase",
Version: "v1",
},
}
u.operator.AddComponents(newComp)
u.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &newComp, EventType: operatorv1.ResourceEventType_CREATED})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(t, ctx, client, u.daprd2.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10, "expected component to be loaded")
u.doReq(t, ctx, client, u.daprd1, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, false)
})
t.Run("adding third middleware should be loaded", func(t *testing.T) {
newComp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "uppercase",
Namespace: "ns3",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.uppercase",
Version: "v1",
},
}
u.operator.AddComponents(newComp)
u.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &newComp, EventType: operatorv1.ResourceEventType_CREATED})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(t, ctx, client, u.daprd3.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10, "expected component to be loaded")
u.doReq(t, ctx, client, u.daprd1, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, true)
})
t.Run("changing the type of middleware should no longer make it available as type needs to match", func(t *testing.T) {
newComp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "uppercase",
Namespace: "ns1",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.routeralias",
Version: "v1",
Metadata: []common.NameValuePair{{Name: "routes", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`{"/foo":"/v1.0/invoke/nowhere/method/bar"}`)},
}}},
},
}
u.operator.AddComponents(newComp)
u.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &newComp, EventType: operatorv1.ResourceEventType_UPDATED})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, client, u.daprd1.HTTPPort())
assert.ElementsMatch(c, []*rtv1.RegisteredComponents{
{Name: "uppercase", Type: "middleware.http.routeralias", Version: "v1"},
{Name: "uppercase2", Type: "middleware.http.routeralias", Version: "v1"},
}, resp)
}, time.Second*5, time.Millisecond*10, "expected component to be loaded")
u.doReq(t, ctx, client, u.daprd1, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, true)
})
t.Run("changing the type of middleware should make it available as type needs to match", func(t *testing.T) {
newComp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "uppercase2",
Namespace: "ns1",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.uppercase",
Version: "v1",
},
}
u.operator.AddComponents(newComp)
u.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &newComp, EventType: operatorv1.ResourceEventType_UPDATED})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, client, u.daprd1.HTTPPort())
assert.ElementsMatch(c, []*rtv1.RegisteredComponents{
{Name: "uppercase", Type: "middleware.http.routeralias", Version: "v1"},
{Name: "uppercase2", Type: "middleware.http.uppercase", Version: "v1"},
}, resp)
}, time.Second*5, time.Millisecond*10, "expected component to be loaded")
u.doReq(t, ctx, client, u.daprd1, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, true)
})
t.Run("deleting components should no longer make them available", func(t *testing.T) {
comp1 := &compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "uppercase",
Namespace: "ns1",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.routeralias",
Version: "v1",
Metadata: []common.NameValuePair{{Name: "routes", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`{"/foo":"/v1.0/invoke/nowhere/method/bar"}`)},
}}},
},
}
comp2 := &compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "uppercase2",
Namespace: "ns1",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.uppercase",
Version: "v1",
},
}
comp3 := comp2.DeepCopy()
comp3.ObjectMeta.Name = "uppercase"
comp3.ObjectMeta.Namespace = "ns2"
comp4 := comp3.DeepCopy()
comp4.ObjectMeta.Namespace = "ns3"
u.operator.SetComponents()
u.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: comp1, EventType: operatorv1.ResourceEventType_DELETED})
u.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: comp2, EventType: operatorv1.ResourceEventType_DELETED})
u.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: comp3, EventType: operatorv1.ResourceEventType_DELETED})
u.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: comp4, EventType: operatorv1.ResourceEventType_DELETED})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Empty(c, util.GetMetaComponents(c, ctx, client, u.daprd1.HTTPPort()))
assert.Empty(c, util.GetMetaComponents(c, ctx, client, u.daprd2.HTTPPort()))
assert.Empty(c, util.GetMetaComponents(c, ctx, client, u.daprd3.HTTPPort()))
}, time.Second*5, time.Millisecond*10, "expected component to be loaded")
u.doReq(t, ctx, client, u.daprd1, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, false)
})
}
func (u *uppercase) doReq(t require.TestingT, ctx context.Context, client *nethttp.Client, source, target *daprd.Daprd, expectUpper bool) {
url := fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s.%s/method/foo", source.HTTPPort(), target.AppID(), target.Namespace())
req, err := nethttp.NewRequestWithContext(ctx, nethttp.MethodPost, url, strings.NewReader("hello"))
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, nethttp.StatusOK, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
if expectUpper {
assert.Equal(t, "HELLO", string(body))
} else {
assert.Equal(t, "hello", string(body))
}
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/middleware/http/app/uppercase.go
|
GO
|
mit
| 13,963 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package http
import (
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/operator/middleware/http/app"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/operator/middleware/http/server"
)
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/middleware/http/http.go
|
GO
|
mit
| 779 |
/*
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 server
import (
"context"
"fmt"
"io"
nethttp "net/http"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/dapr/dapr/pkg/apis/common"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
"github.com/dapr/dapr/pkg/operator/api"
operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/operator"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(routeralias))
}
type routeralias struct {
daprd1 *daprd.Daprd
daprd2 *daprd.Daprd
operator *operator.Operator
}
func (r *routeralias) Setup(t *testing.T) []framework.Option {
sentry := sentry.New(t)
r.operator = operator.New(t,
operator.WithSentry(sentry),
operator.WithGetConfigurationFn(func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error) {
return &operatorv1.GetConfigurationResponse{
Configuration: []byte(
`{"kind":"Configuration","apiVersion":"dapr.io/v1alpha1","metadata":{"name":"hotreloading"},"spec":{"nameResolution": {"component": "mdns"}, "features":[{"name":"HotReload","enabled":true}],
"httpPipeline":{"handlers":[{"name":"routeralias1","type":"middleware.http.routeralias"},{"name":"routeralias2","type":"middleware.http.routeralias"},{"name":"routeralias3","type":"middleware.http.routeralias"}]}}}`,
),
}, nil
}),
)
srv := func(id string) *prochttp.HTTP {
handler := nethttp.NewServeMux()
handler.HandleFunc("/", func(w nethttp.ResponseWriter, r *nethttp.Request) {
fmt.Fprintf(w, "%s:%s", id, r.URL.Path)
})
return prochttp.New(t, prochttp.WithHandler(handler))
}
srv1 := srv("daprd1")
srv2 := srv("daprd2")
r.daprd1 = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors))),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(r.operator.Address(t)),
daprd.WithDisableK8sSecretStore(true),
daprd.WithNamespace("ns2"),
daprd.WithAppPort(srv1.Port()),
)
r.daprd2 = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors))),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(r.operator.Address(t)),
daprd.WithDisableK8sSecretStore(true),
daprd.WithNamespace("ns1"),
daprd.WithAppPort(srv2.Port()),
)
r.operator.SetComponents(compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "routeralias1",
Namespace: "ns1",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.routeralias",
Version: "v1",
Metadata: []common.NameValuePair{{Name: "routes", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(fmt.Sprintf(
`{"/helloworld":"/v1.0/invoke/%[1]s/method/foobar"}`,
r.daprd1.AppID()))},
}}},
},
}, compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "routeralias2",
Namespace: "ns1",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.routeralias",
Version: "v1",
Metadata: []common.NameValuePair{{Name: "routes", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(fmt.Sprintf(
`{
"/helloworld":"/v1.0/invoke/%[1]s/method/barfoo",
"/v1.0/invoke/%[1]s/method/foobar": "/v1.0/invoke/%[1]s/method/abc"
}`,
r.daprd1.AppID()))},
}}},
},
})
return []framework.Option{
framework.WithProcesses(sentry, srv1, srv2, r.operator, r.daprd1, r.daprd2),
}
}
func (r *routeralias) Run(t *testing.T, ctx context.Context) {
r.daprd1.WaitUntilAppHealth(t, ctx)
r.daprd2.WaitUntilAppHealth(t, ctx)
client := util.HTTPClient(t)
r.doReq(t, ctx, client, "helloworld", "daprd1:/abc")
comp1 := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "routeralias1",
Namespace: "ns1",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.routeralias",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "routes", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(fmt.Sprintf(`{
"/v1.0/invoke/%[1]s/method/barfoo": "/v1.0/invoke/%[1]s/method/aaa"
}`, r.daprd1.AppID()),
)},
}},
},
},
}
comp2 := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "routeralias2",
Namespace: "ns1",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.routeralias",
Version: "v1",
Metadata: []common.NameValuePair{{Name: "routes", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(fmt.Sprintf(`{
"/helloworld": "/v1.0/invoke/%[1]s/method/barfoo",
"/v1.0/invoke/%[1]s/method/abc": "/v1.0/invoke/%[1]s/method/aaa"
}`, r.daprd1.AppID()),
)},
}}},
},
}
comp3 := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "routeralias3",
Namespace: "ns1",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.routeralias",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "routes", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(fmt.Sprintf(`{
"/v1.0/invoke/%[1]s/method/barfoo": "/v1.0/invoke/%[1]s/method/xyz"
}`, r.daprd1.AppID()),
)},
}},
},
},
}
r.operator.SetComponents(comp1, comp2, comp3)
r.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp1, EventType: operatorv1.ResourceEventType_UPDATED})
r.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp2, EventType: operatorv1.ResourceEventType_UPDATED})
r.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp3, EventType: operatorv1.ResourceEventType_CREATED})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
r.doReq(c, ctx, client, "helloworld", "daprd1:/xyz")
}, time.Second*10, time.Millisecond*10)
}
func (r *routeralias) doReq(t require.TestingT, ctx context.Context, client *nethttp.Client, path, expect string) {
url := fmt.Sprintf("http://localhost:%d/%s", r.daprd2.HTTPPort(), path)
req, err := nethttp.NewRequestWithContext(ctx, nethttp.MethodPost, url, nil)
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, nethttp.StatusOK, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, expect, string(body))
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/middleware/http/server/routeralias.go
|
GO
|
mit
| 7,596 |
/*
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 server
import (
"context"
"fmt"
"io"
nethttp "net/http"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/dapr/dapr/pkg/apis/common"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
"github.com/dapr/dapr/pkg/operator/api"
operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/operator"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(uppercase))
}
type uppercase struct {
daprd1 *daprd.Daprd
daprd2 *daprd.Daprd
daprd3 *daprd.Daprd
operator *operator.Operator
}
func (u *uppercase) Setup(t *testing.T) []framework.Option {
sentry := sentry.New(t)
u.operator = operator.New(t,
operator.WithSentry(sentry),
operator.WithGetConfigurationFn(func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error) {
return &operatorv1.GetConfigurationResponse{
Configuration: []byte(
`{"kind":"Configuration","apiVersion":"dapr.io/v1alpha1","metadata":{"name":"hotreloading"},"spec":{"nameResolution": {"component": "mdns"}, "features":[{"name":"HotReload","enabled":true}],
"httpPipeline":{"handlers":[{"name":"uppercase","type":"middleware.http.uppercase"},{"name":"uppercase2","type":"middleware.http.uppercase"}]}}}`,
),
}, nil
}),
)
handler := nethttp.NewServeMux()
handler.HandleFunc("/", func(nethttp.ResponseWriter, *nethttp.Request) {})
handler.HandleFunc("/foo", func(w nethttp.ResponseWriter, r *nethttp.Request) {
_, err := io.Copy(w, r.Body)
require.NoError(t, err)
})
srv := prochttp.New(t, prochttp.WithHandler(handler))
u.operator.SetComponents(compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "uppercase",
Namespace: "ns1",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.uppercase",
Version: "v1",
},
}, compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "uppercase2",
Namespace: "ns1",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.routeralias",
Version: "v1",
Metadata: []common.NameValuePair{{Name: "routes", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`{"/foo":"/v1.0/invoke/nowhere/method/bar"}`)},
}}},
},
})
u.daprd1 = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors))),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(u.operator.Address(t)),
daprd.WithDisableK8sSecretStore(true),
daprd.WithNamespace("ns1"),
daprd.WithAppPort(srv.Port()),
)
u.daprd2 = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors))),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(u.operator.Address(t)),
daprd.WithDisableK8sSecretStore(true),
daprd.WithNamespace("ns2"),
daprd.WithAppPort(srv.Port()),
)
u.daprd3 = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors))),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(u.operator.Address(t)),
daprd.WithDisableK8sSecretStore(true),
daprd.WithNamespace("ns3"),
daprd.WithAppPort(srv.Port()),
)
return []framework.Option{
framework.WithProcesses(srv, sentry, u.operator, u.daprd1, u.daprd2, u.daprd3),
}
}
func (u *uppercase) Run(t *testing.T, ctx context.Context) {
u.daprd1.WaitUntilAppHealth(t, ctx)
u.daprd2.WaitUntilAppHealth(t, ctx)
u.daprd3.WaitUntilAppHealth(t, ctx)
client := util.HTTPClient(t)
assert.Len(t, util.GetMetaComponents(t, ctx, client, u.daprd1.HTTPPort()), 2)
t.Run("existing middleware should be loaded", func(t *testing.T) {
u.doReq(t, ctx, client, u.daprd1, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, false)
})
t.Run("adding a new middleware should be loaded", func(t *testing.T) {
newComp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "uppercase",
Namespace: "ns2",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.uppercase",
Version: "v1",
},
}
u.operator.AddComponents(newComp)
u.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &newComp, EventType: operatorv1.ResourceEventType_CREATED})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(t, ctx, client, u.daprd2.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10, "expected component to be loaded")
u.doReq(t, ctx, client, u.daprd1, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, false)
})
t.Run("adding third middleware should be loaded", func(t *testing.T) {
newComp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "uppercase",
Namespace: "ns3",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.uppercase",
Version: "v1",
},
}
u.operator.AddComponents(newComp)
u.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &newComp, EventType: operatorv1.ResourceEventType_CREATED})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(t, ctx, client, u.daprd3.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10, "expected component to be loaded")
u.doReq(t, ctx, client, u.daprd1, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, true)
})
t.Run("changing the type of middleware should no longer make it available as type needs to match", func(t *testing.T) {
newComp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "uppercase",
Namespace: "ns1",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.routeralias",
Version: "v1",
Metadata: []common.NameValuePair{{Name: "routes", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`{"/foo":"/v1.0/invoke/nowhere/method/bar"}`)},
}}},
},
}
u.operator.AddComponents(newComp)
u.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &newComp, EventType: operatorv1.ResourceEventType_UPDATED})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, client, u.daprd1.HTTPPort())
assert.ElementsMatch(c, []*rtv1.RegisteredComponents{
{Name: "uppercase", Type: "middleware.http.routeralias", Version: "v1"},
{Name: "uppercase2", Type: "middleware.http.routeralias", Version: "v1"},
}, resp)
}, time.Second*5, time.Millisecond*10, "expected component to be loaded")
u.doReq(t, ctx, client, u.daprd1, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, true)
})
t.Run("changing the type of middleware should make it available as type needs to match", func(t *testing.T) {
newComp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "uppercase2",
Namespace: "ns1",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.uppercase",
Version: "v1",
},
}
u.operator.AddComponents(newComp)
u.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &newComp, EventType: operatorv1.ResourceEventType_UPDATED})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, client, u.daprd1.HTTPPort())
assert.ElementsMatch(c, []*rtv1.RegisteredComponents{
{Name: "uppercase", Type: "middleware.http.routeralias", Version: "v1"},
{Name: "uppercase2", Type: "middleware.http.uppercase", Version: "v1"},
}, resp)
}, time.Second*5, time.Millisecond*10, "expected component to be loaded")
u.doReq(t, ctx, client, u.daprd1, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, true)
})
t.Run("deleting components should no longer make them available", func(t *testing.T) {
comp1 := &compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "uppercase",
Namespace: "ns1",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.routeralias",
Version: "v1",
Metadata: []common.NameValuePair{{Name: "routes", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`{"/foo":"/v1.0/invoke/nowhere/method/bar"}`)},
}}},
},
}
comp2 := &compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "uppercase2",
Namespace: "ns1",
},
Spec: compapi.ComponentSpec{
Type: "middleware.http.uppercase",
Version: "v1",
},
}
comp3 := comp2.DeepCopy()
comp3.ObjectMeta.Name = "uppercase"
comp3.ObjectMeta.Namespace = "ns2"
comp4 := comp3.DeepCopy()
comp4.ObjectMeta.Namespace = "ns3"
u.operator.SetComponents()
u.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: comp1, EventType: operatorv1.ResourceEventType_DELETED})
u.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: comp2, EventType: operatorv1.ResourceEventType_DELETED})
u.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: comp3, EventType: operatorv1.ResourceEventType_DELETED})
u.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: comp4, EventType: operatorv1.ResourceEventType_DELETED})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Empty(c, util.GetMetaComponents(t, ctx, client, u.daprd1.HTTPPort()))
assert.Empty(c, util.GetMetaComponents(t, ctx, client, u.daprd2.HTTPPort()))
assert.Empty(c, util.GetMetaComponents(t, ctx, client, u.daprd3.HTTPPort()))
}, time.Second*5, time.Millisecond*10, "expected component to be loaded")
u.doReq(t, ctx, client, u.daprd1, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, false)
})
}
func (u *uppercase) doReq(t require.TestingT, ctx context.Context, client *nethttp.Client, source, target *daprd.Daprd, expectUpper bool) {
url := fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s.%s/method/foo", source.HTTPPort(), target.AppID(), target.Namespace())
req, err := nethttp.NewRequestWithContext(ctx, nethttp.MethodPost, url, strings.NewReader("hello"))
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, nethttp.StatusOK, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
if expectUpper {
assert.Equal(t, "HELLO", string(body))
} else {
assert.Equal(t, "hello", string(body))
}
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/middleware/http/server/uppercase.go
|
GO
|
mit
| 13,963 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package middleware
import (
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/operator/middleware/http"
)
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/middleware/middleware.go
|
GO
|
mit
| 683 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package operator
import (
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/operator/binding"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/operator/informer"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/operator/middleware"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/operator/pubsub"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/operator/subscriptions"
)
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/operator.go
|
GO
|
mit
| 1,014 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package pubsub
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/emptypb"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
"github.com/dapr/dapr/pkg/operator/api"
operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/app"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/operator"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(grpc))
}
type grpc struct {
daprd *daprd.Daprd
operator *operator.Operator
topicChan chan string
}
func (g *grpc) Setup(t *testing.T) []framework.Option {
g.topicChan = make(chan string, 1)
sentry := sentry.New(t)
g.operator = operator.New(t,
operator.WithSentry(sentry),
operator.WithGetConfigurationFn(func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error) {
return &operatorv1.GetConfigurationResponse{
Configuration: []byte(
`{"kind":"Configuration","apiVersion":"dapr.io/v1alpha1","metadata":{"name":"hotreloading"},"spec":{"features":[{"name":"HotReload","enabled":true}]}}`,
),
}, nil
}),
)
srv := app.New(t,
app.WithOnTopicEventFn(func(_ context.Context, in *rtv1.TopicEventRequest) (*rtv1.TopicEventResponse, error) {
g.topicChan <- in.GetPath()
return new(rtv1.TopicEventResponse), nil
}),
app.WithListTopicSubscriptions(func(context.Context, *emptypb.Empty) (*rtv1.ListTopicSubscriptionsResponse, error) {
return &rtv1.ListTopicSubscriptionsResponse{
Subscriptions: []*rtv1.TopicSubscription{
{PubsubName: "pubsub1", Topic: "topic1", Routes: &rtv1.TopicRoutes{Default: "/route1"}},
{PubsubName: "pubsub2", Topic: "topic2", Routes: &rtv1.TopicRoutes{Default: "/route2"}},
{PubsubName: "pubsub3", Topic: "topic3", Routes: &rtv1.TopicRoutes{Default: "/route3"}},
},
}, nil
}),
)
g.operator.AddComponents(compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "pubsub1",
Namespace: "default",
},
Spec: compapi.ComponentSpec{
Type: "pubsub.in-memory",
Version: "v1",
},
})
g.daprd = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors))),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(g.operator.Address(t)),
daprd.WithDisableK8sSecretStore(true),
daprd.WithAppPort(srv.Port(t)),
daprd.WithAppProtocol("grpc"),
)
return []framework.Option{
framework.WithProcesses(sentry, srv, g.operator, g.daprd),
}
}
func (g *grpc) Run(t *testing.T, ctx context.Context) {
g.daprd.WaitUntilRunning(t, ctx)
client := g.daprd.GRPCClient(t, ctx)
t.Run("expect 1 component to be loaded", func(t *testing.T) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(t, resp.GetRegisteredComponents(), 1)
g.publishMessage(t, ctx, client, "pubsub1", "topic1", "/route1")
g.publishMessageFails(t, ctx, client, "pubsub2", "topic2")
g.publishMessageFails(t, ctx, client, "pubsub3", "topic3")
})
t.Run("create a component", func(t *testing.T) {
comp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "pubsub2",
Namespace: "default",
},
Spec: compapi.ComponentSpec{
Type: "pubsub.in-memory",
Version: "v1",
},
}
g.operator.AddComponents(comp)
g.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 2)
}, time.Second*5, time.Millisecond*10)
g.publishMessage(t, ctx, client, "pubsub1", "topic1", "/route1")
g.publishMessage(t, ctx, client, "pubsub2", "topic2", "/route2")
})
t.Run("create a third component", func(t *testing.T) {
comp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "pubsub3",
Namespace: "default",
},
Spec: compapi.ComponentSpec{
Type: "pubsub.in-memory",
Version: "v1",
},
}
g.operator.AddComponents(comp)
g.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 3)
}, time.Second*5, time.Millisecond*10)
g.publishMessage(t, ctx, client, "pubsub1", "topic1", "/route1")
g.publishMessage(t, ctx, client, "pubsub2", "topic2", "/route2")
g.publishMessage(t, ctx, client, "pubsub3", "topic3", "/route3")
})
t.Run("delete a component", func(t *testing.T) {
comp := g.operator.Components()[1]
g.operator.SetComponents(g.operator.Components()[0], g.operator.Components()[2])
g.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_DELETED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 2)
}, time.Second*5, time.Millisecond*10)
g.publishMessage(t, ctx, client, "pubsub1", "topic1", "/route1")
g.publishMessageFails(t, ctx, client, "pubsub2", "topic2")
g.publishMessage(t, ctx, client, "pubsub3", "topic3", "/route3")
})
t.Run("delete another component", func(t *testing.T) {
comp := g.operator.Components()[0]
g.operator.SetComponents(g.operator.Components()[1])
g.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_DELETED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 1)
}, time.Second*5, time.Millisecond*10)
g.publishMessageFails(t, ctx, client, "pubsub1", "topic1")
g.publishMessageFails(t, ctx, client, "pubsub2", "topic2")
g.publishMessage(t, ctx, client, "pubsub3", "topic3", "/route3")
})
t.Run("delete last component", func(t *testing.T) {
comp := g.operator.Components()[0]
g.operator.SetComponents()
g.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_DELETED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Empty(c, resp.GetRegisteredComponents())
}, time.Second*5, time.Millisecond*10)
g.publishMessageFails(t, ctx, client, "pubsub1", "topic1")
g.publishMessageFails(t, ctx, client, "pubsub2", "topic2")
g.publishMessageFails(t, ctx, client, "pubsub3", "topic3")
})
t.Run("recreating pubsub should make it available again", func(t *testing.T) {
comp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "pubsub2",
Namespace: "default",
},
Spec: compapi.ComponentSpec{
Type: "pubsub.in-memory",
Version: "v1",
},
}
g.operator.AddComponents(comp)
g.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 1)
}, time.Second*5, time.Millisecond*10)
g.publishMessageFails(t, ctx, client, "pubsub1", "topic1")
g.publishMessage(t, ctx, client, "pubsub2", "topic2", "/route2")
g.publishMessageFails(t, ctx, client, "pubsub3", "topic3")
})
}
func (g *grpc) publishMessage(t *testing.T, ctx context.Context, client rtv1.DaprClient, pubsub, topic, route string) {
t.Helper()
_, err := client.PublishEvent(ctx, &rtv1.PublishEventRequest{
PubsubName: pubsub,
Topic: topic,
Data: []byte(`{"status": "completed"}`),
})
require.NoError(t, err)
select {
case topic := <-g.topicChan:
assert.Equal(t, route, topic)
case <-time.After(time.Second * 5):
assert.Fail(t, "timed out waiting for topic")
}
}
func (g *grpc) publishMessageFails(t *testing.T, ctx context.Context, client rtv1.DaprClient, pubsub, topic string) {
t.Helper()
_, err := client.PublishEvent(ctx, &rtv1.PublishEventRequest{
PubsubName: pubsub,
Topic: topic,
Data: []byte(`{"status": "completed"}`),
})
require.Error(t, err)
assert.Contains(t, err.Error(), "not found")
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/pubsub/grpc.go
|
GO
|
mit
| 9,798 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package pubsub
import (
"context"
"fmt"
"io"
nethttp "net/http"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
"github.com/dapr/dapr/pkg/operator/api"
operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/operator"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(http))
}
type http struct {
daprd *daprd.Daprd
operator *operator.Operator
topicChan chan string
}
func (h *http) Setup(t *testing.T) []framework.Option {
h.topicChan = make(chan string, 1)
handler := nethttp.NewServeMux()
handler.HandleFunc("/dapr/subscribe", func(w nethttp.ResponseWriter, r *nethttp.Request) {
w.WriteHeader(nethttp.StatusOK)
io.WriteString(w, `[
{
"pubsubname": "pubsub1",
"topic": "topic1",
"route": "route1"
},
{
"pubsubname": "pubsub2",
"topic": "topic2",
"route": "route2"
},
{
"pubsubname": "pubsub3",
"topic": "topic3",
"route": "route3"
}
]`)
})
handler.HandleFunc("/", func(w nethttp.ResponseWriter, r *nethttp.Request) {
if strings.HasPrefix(r.URL.Path, "/route") {
h.topicChan <- r.URL.Path
}
})
srv := prochttp.New(t, prochttp.WithHandler(handler))
sentry := sentry.New(t)
h.operator = operator.New(t,
operator.WithSentry(sentry),
operator.WithGetConfigurationFn(func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error) {
return &operatorv1.GetConfigurationResponse{
Configuration: []byte(
`{"kind":"Configuration","apiVersion":"dapr.io/v1alpha1","metadata":{"name":"hotreloading"},"spec":{"features":[{"name":"HotReload","enabled":true}]}}`,
),
}, nil
}),
)
h.operator.AddComponents(compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "pubsub1",
Namespace: "default",
},
Spec: compapi.ComponentSpec{
Type: "pubsub.in-memory",
Version: "v1",
},
})
h.daprd = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors))),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(h.operator.Address(t)),
daprd.WithDisableK8sSecretStore(true),
daprd.WithAppPort(srv.Port()),
)
return []framework.Option{
framework.WithProcesses(sentry, srv, h.operator, h.daprd),
}
}
func (h *http) Run(t *testing.T, ctx context.Context) {
h.daprd.WaitUntilRunning(t, ctx)
client := util.HTTPClient(t)
t.Run("expect 1 component to be loaded", func(t *testing.T) {
assert.Len(t, util.GetMetaComponents(t, ctx, client, h.daprd.HTTPPort()), 1)
h.publishMessage(t, ctx, client, "pubsub1", "topic1", "/route1")
})
t.Run("create a component", func(t *testing.T) {
comp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "pubsub2",
Namespace: "default",
},
Spec: compapi.ComponentSpec{
Type: "pubsub.in-memory",
Version: "v1",
},
}
h.operator.AddComponents(comp)
h.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, h.daprd.HTTPPort()), 2)
}, time.Second*5, time.Millisecond*10)
h.publishMessage(t, ctx, client, "pubsub1", "topic1", "/route1")
h.publishMessage(t, ctx, client, "pubsub2", "topic2", "/route2")
})
t.Run("create a third component", func(t *testing.T) {
comp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "pubsub3",
Namespace: "default",
},
Spec: compapi.ComponentSpec{
Type: "pubsub.in-memory",
Version: "v1",
},
}
h.operator.AddComponents(comp)
h.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, h.daprd.HTTPPort()), 3)
}, time.Second*5, time.Millisecond*10)
h.publishMessage(t, ctx, client, "pubsub1", "topic1", "/route1")
h.publishMessage(t, ctx, client, "pubsub2", "topic2", "/route2")
h.publishMessage(t, ctx, client, "pubsub3", "topic3", "/route3")
})
t.Run("delete a component", func(t *testing.T) {
comp := h.operator.Components()[1]
h.operator.SetComponents(h.operator.Components()[0], h.operator.Components()[2])
h.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_DELETED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, h.daprd.HTTPPort()), 2)
}, time.Second*5, time.Millisecond*10)
h.publishMessage(t, ctx, client, "pubsub1", "topic1", "/route1")
h.publishMessageFails(t, ctx, client, "pubsub2", "topic2")
h.publishMessage(t, ctx, client, "pubsub3", "topic3", "/route3")
})
t.Run("delete another component", func(t *testing.T) {
comp := h.operator.Components()[0]
h.operator.SetComponents(h.operator.Components()[1])
h.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_DELETED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, h.daprd.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10)
h.publishMessageFails(t, ctx, client, "pubsub1", "topic1")
h.publishMessageFails(t, ctx, client, "pubsub2", "topic2")
h.publishMessage(t, ctx, client, "pubsub3", "topic3", "/route3")
})
t.Run("delete last component", func(t *testing.T) {
comp := h.operator.Components()[0]
h.operator.SetComponents()
h.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_DELETED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Empty(c, util.GetMetaComponents(c, ctx, client, h.daprd.HTTPPort()))
}, time.Second*5, time.Millisecond*10)
h.publishMessageFails(t, ctx, client, "pubsub1", "topic1")
h.publishMessageFails(t, ctx, client, "pubsub2", "topic2")
h.publishMessageFails(t, ctx, client, "pubsub3", "topic3")
})
t.Run("recreating pubsub should make it available again", func(t *testing.T) {
comp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{
Name: "pubsub2",
Namespace: "default",
},
Spec: compapi.ComponentSpec{
Type: "pubsub.in-memory",
Version: "v1",
},
}
h.operator.AddComponents(comp)
h.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, h.daprd.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10)
h.publishMessageFails(t, ctx, client, "pubsub1", "topic1")
h.publishMessage(t, ctx, client, "pubsub2", "topic2", "/route2")
h.publishMessageFails(t, ctx, client, "pubsub3", "topic3")
})
}
func (h *http) publishMessage(t *testing.T, ctx context.Context, client *nethttp.Client, pubsub, topic, route string) {
t.Helper()
reqURL := fmt.Sprintf("http://localhost:%d/v1.0/publish/%s/%s", h.daprd.HTTPPort(), pubsub, topic)
req, err := nethttp.NewRequestWithContext(ctx, nethttp.MethodPost, reqURL, strings.NewReader(`{"status": "completed"}`))
require.NoError(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
require.NoError(t, err)
assert.Equal(t, nethttp.StatusNoContent, resp.StatusCode, reqURL)
respBody, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
assert.Empty(t, string(respBody))
select {
case topic := <-h.topicChan:
assert.Equal(t, route, topic)
case <-time.After(time.Second * 5):
assert.Fail(t, "timed out waiting for topic")
}
}
func (h *http) publishMessageFails(t *testing.T, ctx context.Context, client *nethttp.Client, pubsub, topic string) {
t.Helper()
reqURL := fmt.Sprintf("http://localhost:%d/v1.0/publish/%s/%s", h.daprd.HTTPPort(), pubsub, topic)
req, err := nethttp.NewRequestWithContext(ctx, nethttp.MethodPost, reqURL, strings.NewReader(`{"status": "completed"}`))
require.NoError(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, nethttp.StatusNotFound, resp.StatusCode, reqURL)
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/pubsub/http.go
|
GO
|
mit
| 9,639 |
/*
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"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/dapr/dapr/pkg/apis/common"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
"github.com/dapr/dapr/pkg/operator/api"
operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1"
rtpbv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/operator"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(secret))
}
type secret struct {
daprd *daprd.Daprd
operator *operator.Operator
client *http.Client
resDir1 string
resDir2 string
resDir3 string
}
func (s *secret) Setup(t *testing.T) []framework.Option {
sentry := sentry.New(t)
s.operator = operator.New(t,
operator.WithSentry(sentry),
operator.WithGetConfigurationFn(func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error) {
return &operatorv1.GetConfigurationResponse{
Configuration: []byte(
`{"kind":"Configuration","apiVersion":"dapr.io/v1alpha1","metadata":{"name":"hotreloading"},"spec":{"features":[{"name":"HotReload","enabled":true}]}}`,
),
}, nil
}),
)
s.client = util.HTTPClient(t)
s.daprd = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(s.operator.Address(t)),
daprd.WithDisableK8sSecretStore(true),
daprd.WithExecOptions(exec.WithEnvVars(t,
"DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors),
"FOO_SEC_1", "bar1",
"FOO_SEC_2", "bar2",
"FOO_SEC_3", "bar3",
"BAR_SEC_1", "baz1",
"BAR_SEC_2", "baz2",
"BAR_SEC_3", "baz3",
"BAZ_SEC_1", "foo1",
"BAZ_SEC_2", "foo2",
"BAZ_SEC_3", "foo3",
)),
)
s.resDir1, s.resDir2, s.resDir3 = t.TempDir(), t.TempDir(), t.TempDir()
return []framework.Option{
framework.WithProcesses(sentry, s.operator, s.daprd),
}
}
func (s *secret) Run(t *testing.T, ctx context.Context) {
s.daprd.WaitUntilRunning(t, ctx)
t.Run("expect no components to be loaded yet", func(t *testing.T) {
assert.Empty(t, util.GetMetaComponents(t, ctx, s.client, s.daprd.HTTPPort()))
s.readExpectError(t, ctx, "123", "SEC_1", http.StatusInternalServerError)
})
t.Run("adding a component should become available", func(t *testing.T) {
newComp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "123"},
Spec: compapi.ComponentSpec{
Type: "secretstores.local.env",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "PREFIX", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`"FOO_"`)},
}},
},
},
}
s.operator.SetComponents(newComp)
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &newComp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(t, ctx, s.client, s.daprd.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10)
resp := util.GetMetaComponents(t, ctx, s.client, s.daprd.HTTPPort())
require.Len(t, resp, 1)
assert.ElementsMatch(t, resp, []*rtpbv1.RegisteredComponents{
{Name: "123", Type: "secretstores.local.env", Version: "v1"},
})
s.read(t, ctx, "123", "SEC_1", "bar1")
s.read(t, ctx, "123", "SEC_2", "bar2")
s.read(t, ctx, "123", "SEC_3", "bar3")
})
t.Run("adding a second and third component should also become available", func(t *testing.T) {
// After a single secret store exists, Dapr returns a Unauthorized response
// rather than an Internal Server Error when writing to a non-existent
// secret store.
s.readExpectError(t, ctx, "abc", "2-sec-1", http.StatusUnauthorized)
s.readExpectError(t, ctx, "xyz", "SEC_1", http.StatusUnauthorized)
require.NoError(t, os.WriteFile(filepath.Join(s.resDir2, "2-sec.json"), []byte(`
{
"2-sec-1": "foo",
"2-sec-2": "bar",
"2-sec-3": "xxx"
}
`), 0o600))
dir := filepath.Join(s.resDir2, "2-sec.json")
dirJSON, err := json.Marshal(dir)
require.NoError(t, err)
newComp1 := compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "abc"},
Spec: compapi.ComponentSpec{
Type: "secretstores.local.file",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "secretsFile", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: dirJSON},
}},
},
},
}
newComp2 := compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "xyz"},
Spec: compapi.ComponentSpec{
Type: "secretstores.local.env",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "PREFIX", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`"BAR_"`)},
}},
},
},
}
s.operator.AddComponents(newComp1, newComp2)
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &newComp1, EventType: operatorv1.ResourceEventType_CREATED})
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &newComp2, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(t, ctx, s.client, s.daprd.HTTPPort()), 3)
}, time.Second*5, time.Millisecond*10)
resp := util.GetMetaComponents(t, ctx, s.client, s.daprd.HTTPPort())
require.Len(t, resp, 3)
assert.ElementsMatch(t, []*rtpbv1.RegisteredComponents{
{Name: "123", Type: "secretstores.local.env", Version: "v1"},
{Name: "abc", Type: "secretstores.local.file", Version: "v1"},
{Name: "xyz", Type: "secretstores.local.env", Version: "v1"},
}, resp)
s.read(t, ctx, "123", "SEC_1", "bar1")
s.read(t, ctx, "123", "SEC_2", "bar2")
s.read(t, ctx, "123", "SEC_3", "bar3")
s.read(t, ctx, "abc", "2-sec-1", "foo")
s.read(t, ctx, "abc", "2-sec-2", "bar")
s.read(t, ctx, "abc", "2-sec-3", "xxx")
s.read(t, ctx, "xyz", "SEC_1", "baz1")
s.read(t, ctx, "xyz", "SEC_2", "baz2")
s.read(t, ctx, "xyz", "SEC_3", "baz3")
})
t.Run("changing the type of a secret store should update the component and still be available", func(t *testing.T) {
comp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "abc"},
Spec: compapi.ComponentSpec{
Type: "secretstores.local.env",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "PREFIX", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`"BAZ_"`)},
}},
},
},
}
s.operator.SetComponents(s.operator.Components()[0], comp, s.operator.Components()[2])
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_UPDATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, s.client, s.daprd.HTTPPort())
assert.ElementsMatch(c, []*rtpbv1.RegisteredComponents{
{Name: "123", Type: "secretstores.local.env", Version: "v1"},
{Name: "abc", Type: "secretstores.local.env", Version: "v1"},
{Name: "xyz", Type: "secretstores.local.env", Version: "v1"},
}, resp)
}, time.Second*5, time.Millisecond*10)
s.read(t, ctx, "123", "SEC_1", "bar1")
s.read(t, ctx, "123", "SEC_2", "bar2")
s.read(t, ctx, "123", "SEC_3", "bar3")
s.read(t, ctx, "abc", "SEC_1", "foo1")
s.read(t, ctx, "abc", "SEC_2", "foo2")
s.read(t, ctx, "abc", "SEC_3", "foo3")
s.read(t, ctx, "xyz", "SEC_1", "baz1")
s.read(t, ctx, "xyz", "SEC_2", "baz2")
s.read(t, ctx, "xyz", "SEC_3", "baz3")
})
t.Run("updating multiple secret stores should be updated, and multiple components in a single file", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(s.resDir1, "1-sec.json"), []byte(`
{
"1-sec-1": "foo",
"1-sec-2": "bar",
"1-sec-3": "xxx"
}
`), 0o600))
dir := filepath.Join(s.resDir1, "1-sec.json")
dirJSON, err := json.Marshal(dir)
require.NoError(t, err)
comp1 := compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "123"},
Spec: compapi.ComponentSpec{
Type: "secretstores.local.file",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "secretsFile", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: dirJSON},
}},
},
},
}
comp2 := compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo"},
Spec: compapi.ComponentSpec{
Type: "secretstores.local.env",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "PREFIX", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`"BAZ_"`)},
}},
},
},
}
dir = filepath.Join(s.resDir2, "2-sec.json")
dirJSON, err = json.Marshal(dir)
require.NoError(t, err)
comp3 := compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "abc"},
Spec: compapi.ComponentSpec{
Type: "secretstores.local.file",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "secretsFile", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: dirJSON},
}},
},
},
}
s.operator.SetComponents(comp1, comp2, s.operator.Components()[2], comp3)
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp1, EventType: operatorv1.ResourceEventType_UPDATED})
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp2, EventType: operatorv1.ResourceEventType_UPDATED})
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp3, EventType: operatorv1.ResourceEventType_UPDATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, s.client, s.daprd.HTTPPort())
assert.ElementsMatch(c, []*rtpbv1.RegisteredComponents{
{Name: "123", Type: "secretstores.local.file", Version: "v1"},
{Name: "abc", Type: "secretstores.local.file", Version: "v1"},
{Name: "xyz", Type: "secretstores.local.env", Version: "v1"},
{Name: "foo", Type: "secretstores.local.env", Version: "v1"},
}, resp)
}, time.Second*5, time.Millisecond*10)
s.read(t, ctx, "123", "1-sec-1", "foo")
s.read(t, ctx, "123", "1-sec-2", "bar")
s.read(t, ctx, "123", "1-sec-3", "xxx")
s.read(t, ctx, "abc", "2-sec-1", "foo")
s.read(t, ctx, "abc", "2-sec-2", "bar")
s.read(t, ctx, "abc", "2-sec-3", "xxx")
s.read(t, ctx, "xyz", "SEC_1", "baz1")
s.read(t, ctx, "xyz", "SEC_2", "baz2")
s.read(t, ctx, "xyz", "SEC_3", "baz3")
s.read(t, ctx, "foo", "SEC_1", "foo1")
s.read(t, ctx, "foo", "SEC_2", "foo2")
s.read(t, ctx, "foo", "SEC_3", "foo3")
})
t.Run("renaming a component should close the old name, and open the new one", func(t *testing.T) {
dir := filepath.Join(s.resDir2, "2-sec.json")
dirJSON, err := json.Marshal(dir)
require.NoError(t, err)
comp1 := s.operator.Components()[3]
comp2 := compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "bar"},
Spec: compapi.ComponentSpec{
Type: "secretstores.local.file",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "secretsFile", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: dirJSON},
}},
},
},
}
s.operator.SetComponents(s.operator.Components()[0], s.operator.Components()[1], s.operator.Components()[2], comp2)
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp1, EventType: operatorv1.ResourceEventType_DELETED})
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp2, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, s.client, s.daprd.HTTPPort())
assert.ElementsMatch(c, []*rtpbv1.RegisteredComponents{
{Name: "123", Type: "secretstores.local.file", Version: "v1"},
{Name: "bar", Type: "secretstores.local.file", Version: "v1"},
{Name: "xyz", Type: "secretstores.local.env", Version: "v1"},
{Name: "foo", Type: "secretstores.local.env", Version: "v1"},
}, resp)
}, time.Second*5, time.Millisecond*10)
s.read(t, ctx, "123", "1-sec-1", "foo")
s.read(t, ctx, "123", "1-sec-2", "bar")
s.read(t, ctx, "123", "1-sec-3", "xxx")
s.read(t, ctx, "bar", "2-sec-1", "foo")
s.read(t, ctx, "bar", "2-sec-2", "bar")
s.read(t, ctx, "bar", "2-sec-3", "xxx")
s.read(t, ctx, "xyz", "SEC_1", "baz1")
s.read(t, ctx, "xyz", "SEC_2", "baz2")
s.read(t, ctx, "xyz", "SEC_3", "baz3")
s.read(t, ctx, "foo", "SEC_1", "foo1")
s.read(t, ctx, "foo", "SEC_2", "foo2")
s.read(t, ctx, "foo", "SEC_3", "foo3")
})
t.Run("deleting a component (through type update) should delete the components", func(t *testing.T) {
comp1 := s.operator.Components()[3]
comp2 := compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "bar"},
Spec: compapi.ComponentSpec{
Type: "state.in-memory",
Version: "v1",
},
}
s.operator.SetComponents(s.operator.Components()[0], s.operator.Components()[1], s.operator.Components()[2], comp2)
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp1, EventType: operatorv1.ResourceEventType_DELETED})
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp2, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, s.client, s.daprd.HTTPPort())
assert.ElementsMatch(c,
[]*rtpbv1.RegisteredComponents{
{Name: "123", Type: "secretstores.local.file", Version: "v1"},
{Name: "xyz", Type: "secretstores.local.env", Version: "v1"},
{Name: "foo", Type: "secretstores.local.env", Version: "v1"},
{
Name: "bar", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, resp)
}, time.Second*5, time.Millisecond*10)
s.read(t, ctx, "123", "1-sec-1", "foo")
s.read(t, ctx, "123", "1-sec-2", "bar")
s.read(t, ctx, "123", "1-sec-3", "xxx")
s.read(t, ctx, "xyz", "SEC_1", "baz1")
s.read(t, ctx, "xyz", "SEC_2", "baz2")
s.read(t, ctx, "xyz", "SEC_3", "baz3")
s.read(t, ctx, "foo", "SEC_1", "foo1")
s.read(t, ctx, "foo", "SEC_2", "foo2")
s.read(t, ctx, "foo", "SEC_3", "foo3")
s.readExpectError(t, ctx, "bar", "2-sec-1", http.StatusUnauthorized)
s.readExpectError(t, ctx, "bar", "2-sec-2", http.StatusUnauthorized)
s.readExpectError(t, ctx, "bar", "2-sec-3", http.StatusUnauthorized)
})
t.Run("deleting all components should result in no components remaining", func(t *testing.T) {
comp1 := s.operator.Components()[0]
comp2 := s.operator.Components()[1]
comp3 := s.operator.Components()[2]
comp4 := s.operator.Components()[3]
s.operator.SetComponents(comp4)
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp1, EventType: operatorv1.ResourceEventType_DELETED})
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp2, EventType: operatorv1.ResourceEventType_DELETED})
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp3, EventType: operatorv1.ResourceEventType_DELETED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, s.client, s.daprd.HTTPPort())
assert.Len(c, resp, 1)
assert.ElementsMatch(c, resp, []*rtpbv1.RegisteredComponents{
{
Name: "bar", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
})
}, time.Second*5, time.Millisecond*10)
s.readExpectError(t, ctx, "123", "1-sec-1", http.StatusInternalServerError)
s.readExpectError(t, ctx, "xyz", "SEC_1", http.StatusInternalServerError)
s.readExpectError(t, ctx, "bar", "2-sec-1", http.StatusInternalServerError)
s.readExpectError(t, ctx, "foo", "SEC_1", http.StatusInternalServerError)
})
t.Run("recreating secret component should make it available again", func(t *testing.T) {
comp1 := compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "123"},
Spec: compapi.ComponentSpec{
Type: "secretstores.local.env",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "PREFIX", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: []byte(`"FOO_"`)},
}},
},
},
}
s.operator.SetComponents(comp1, s.operator.Components()[0])
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp1, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(t, ctx, s.client, s.daprd.HTTPPort()), 2)
}, time.Second*5, time.Millisecond*10)
s.read(t, ctx, "123", "SEC_1", "bar1")
s.read(t, ctx, "123", "SEC_2", "bar2")
s.read(t, ctx, "123", "SEC_3", "bar3")
})
}
func (s *secret) readExpectError(t *testing.T, ctx context.Context, compName, key string, expCode int) {
t.Helper()
getURL := fmt.Sprintf("http://localhost:%d/v1.0/secrets/%s/%s",
s.daprd.HTTPPort(), url.QueryEscape(compName), url.QueryEscape(key))
req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil)
require.NoError(t, err)
s.doReq(t, req, expCode, fmt.Sprintf(
`\{"errorCode":"(ERR_SECRET_STORES_NOT_CONFIGURED|ERR_SECRET_STORE_NOT_FOUND)","message":"(secret store is not configured|failed finding secret store with key %s)"\}`,
compName))
}
func (s *secret) read(t *testing.T, ctx context.Context, compName, key, expValue string) {
t.Helper()
getURL := fmt.Sprintf("http://localhost:%d/v1.0/secrets/%s/%s", s.daprd.HTTPPort(), url.QueryEscape(compName), url.QueryEscape(key))
req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil)
require.NoError(t, err)
s.doReq(t, req, http.StatusOK, expValue)
}
func (s *secret) doReq(t *testing.T, req *http.Request, expCode int, expBody string) {
t.Helper()
resp, err := s.client.Do(req)
require.NoError(t, err)
assert.Equal(t, expCode, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
assert.Regexp(t, expBody, string(body))
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/secret.go
|
GO
|
mit
| 19,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 implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package operator
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/dapr/dapr/pkg/apis/common"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
"github.com/dapr/dapr/pkg/operator/api"
operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/operator"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(state))
}
type state struct {
daprd *daprd.Daprd
operator *operator.Operator
}
func (s *state) Setup(t *testing.T) []framework.Option {
sentry := sentry.New(t)
s.operator = operator.New(t,
operator.WithSentry(sentry),
operator.WithGetConfigurationFn(func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error) {
return &operatorv1.GetConfigurationResponse{
Configuration: []byte(
`{"kind":"Configuration","apiVersion":"dapr.io/v1alpha1","metadata":{"name":"hotreloading"},"spec":{"features":[{"name":"HotReload","enabled":true}]}}`,
),
}, nil
}),
)
s.daprd = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors))),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(s.operator.Address(t)),
daprd.WithDisableK8sSecretStore(true),
)
return []framework.Option{
framework.WithProcesses(sentry, s.operator, s.daprd),
}
}
func (s *state) Run(t *testing.T, ctx context.Context) {
s.daprd.WaitUntilRunning(t, ctx)
client := util.HTTPClient(t)
t.Run("expect no components to be loaded yet", func(t *testing.T) {
assert.Empty(t, util.GetMetaComponents(t, ctx, client, s.daprd.HTTPPort()))
s.writeExpectError(t, ctx, client, "123", http.StatusInternalServerError)
})
t.Run("adding a component should become available", func(t *testing.T) {
newComp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "123"},
Spec: compapi.ComponentSpec{
Type: "state.in-memory",
Version: "v1",
},
}
s.operator.SetComponents(newComp)
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &newComp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(t, ctx, client, s.daprd.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10)
resp := util.GetMetaComponents(t, ctx, client, s.daprd.HTTPPort())
require.Len(t, resp, 1)
assert.ElementsMatch(t, resp, []*rtv1.RegisteredComponents{
{
Name: "123",
Type: "state.in-memory",
Version: "v1",
Capabilities: []string{
"ETAG",
"TRANSACTIONAL",
"TTL",
"DELETE_WITH_PREFIX",
"ACTOR",
},
},
})
s.writeRead(t, ctx, client, "123")
})
t.Run("adding a second and third component should also become available", func(t *testing.T) {
// After a single state store exists, Dapr returns a Bad Request response
// rather than an Internal Server Error when writing to a non-existent
// state store.
s.writeExpectError(t, ctx, client, "abc", http.StatusBadRequest)
s.writeExpectError(t, ctx, client, "xyz", http.StatusBadRequest)
newComp1 := compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "abc"},
Spec: compapi.ComponentSpec{
Type: "state.in-memory",
Version: "v1",
},
}
newComp2 := compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "xyz"},
Spec: compapi.ComponentSpec{
Type: "state.in-memory",
Version: "v1",
},
}
s.operator.AddComponents(newComp1, newComp2)
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &newComp1, EventType: operatorv1.ResourceEventType_CREATED})
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &newComp2, EventType: operatorv1.ResourceEventType_CREATED})
var resp []*rtv1.RegisteredComponents
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp = util.GetMetaComponents(t, ctx, client, s.daprd.HTTPPort())
assert.Len(c, resp, 3)
}, time.Second*5, time.Millisecond*10)
assert.ElementsMatch(t, []*rtv1.RegisteredComponents{
{
Name: "123", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
{
Name: "abc", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
{
Name: "xyz", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, resp)
s.writeRead(t, ctx, client, "123")
s.writeRead(t, ctx, client, "abc")
s.writeRead(t, ctx, client, "xyz")
})
tmpDir := t.TempDir()
t.Run("changing the type of a state store should update the component and still be available", func(t *testing.T) {
s.writeRead(t, ctx, client, "123")
s.writeRead(t, ctx, client, "abc")
s.writeRead(t, ctx, client, "xyz")
dbPath := filepath.Join(tmpDir, "db.sqlite")
dbPathJSON, err := json.Marshal(dbPath)
require.NoError(t, err)
newComp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "abc"},
Spec: compapi.ComponentSpec{
Type: "state.sqlite",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "connectionString", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: dbPathJSON},
}},
},
},
}
s.operator.SetComponents(s.operator.Components()[0], newComp, s.operator.Components()[2])
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &newComp, EventType: operatorv1.ResourceEventType_UPDATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, client, s.daprd.HTTPPort())
assert.ElementsMatch(c, []*rtv1.RegisteredComponents{
{
Name: "123", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
{
Name: "abc", Type: "state.sqlite", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "ACTOR"},
},
{
Name: "xyz", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, resp)
}, time.Second*5, time.Millisecond*10)
s.writeRead(t, ctx, client, "123")
s.writeRead(t, ctx, client, "abc")
s.writeRead(t, ctx, client, "xyz")
})
t.Run("updating multiple state stores should be updated", func(t *testing.T) {
s.writeRead(t, ctx, client, "123")
s.writeRead(t, ctx, client, "abc")
s.writeRead(t, ctx, client, "xyz")
s.writeExpectError(t, ctx, client, "foo", http.StatusBadRequest)
dbPath := filepath.Join(tmpDir, "db.sqlite")
dbPathJSON, err := json.Marshal(dbPath)
require.NoError(t, err)
comp1 := compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "123"},
Spec: compapi.ComponentSpec{
Type: "state.sqlite",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "connectionString", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: dbPathJSON},
}},
},
},
}
comp2 := compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "abc"},
Spec: compapi.ComponentSpec{
Type: "state.in-memory",
Version: "v1",
},
}
comp3 := compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "xyz"},
Spec: compapi.ComponentSpec{
Type: "state.in-memory",
Version: "v1",
},
}
comp4 := compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo"},
Spec: compapi.ComponentSpec{
Type: "state.in-memory",
Version: "v1",
},
}
s.operator.SetComponents(comp1, comp2, comp3, comp4)
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp1, EventType: operatorv1.ResourceEventType_UPDATED})
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp2, EventType: operatorv1.ResourceEventType_UPDATED})
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp3, EventType: operatorv1.ResourceEventType_UPDATED})
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp4, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, client, s.daprd.HTTPPort())
assert.ElementsMatch(c, []*rtv1.RegisteredComponents{
{
Name: "123", Type: "state.sqlite", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "ACTOR"},
},
{
Name: "abc", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
{
Name: "xyz", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
{
Name: "foo", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, resp)
}, time.Second*5, time.Millisecond*10)
s.writeRead(t, ctx, client, "123")
s.writeRead(t, ctx, client, "abc")
s.writeRead(t, ctx, client, "xyz")
s.writeRead(t, ctx, client, "foo")
})
t.Run("renaming a component should close the old name, and open the new one", func(t *testing.T) {
s.writeRead(t, ctx, client, "123")
s.writeRead(t, ctx, client, "abc")
s.writeRead(t, ctx, client, "xyz")
s.writeRead(t, ctx, client, "foo")
dbPath := filepath.Join(tmpDir, "db.sqlite")
dbPathJSON, err := json.Marshal(dbPath)
require.NoError(t, err)
comp1 := compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "abc"},
Spec: compapi.ComponentSpec{
Type: "state.sqlite",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "connectionString", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: dbPathJSON},
}},
},
},
}
comp2 := compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "bar"},
Spec: compapi.ComponentSpec{
Type: "state.in-memory",
Version: "v1",
},
}
s.operator.SetComponents(s.operator.Components()[0], comp2, s.operator.Components()[2], s.operator.Components()[3])
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp1, EventType: operatorv1.ResourceEventType_DELETED})
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp2, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, client, s.daprd.HTTPPort())
assert.ElementsMatch(c, []*rtv1.RegisteredComponents{
{
Name: "123", Type: "state.sqlite", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "ACTOR"},
},
{
Name: "bar", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
{
Name: "xyz", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
{
Name: "foo", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, resp)
}, time.Second*5, time.Millisecond*10)
s.writeRead(t, ctx, client, "123")
s.writeRead(t, ctx, client, "bar")
s.writeRead(t, ctx, client, "xyz")
s.writeRead(t, ctx, client, "foo")
})
tmpDir = t.TempDir()
t.Run("deleting a component (through type update) should delete the components", func(t *testing.T) {
s.writeRead(t, ctx, client, "123")
s.writeRead(t, ctx, client, "bar")
s.writeRead(t, ctx, client, "xyz")
s.writeRead(t, ctx, client, "foo")
secPath := filepath.Join(tmpDir, "foo")
require.NoError(t, os.WriteFile(secPath, []byte(`{}`), 0o600))
secPathJSON, err := json.Marshal(secPath)
require.NoError(t, err)
component := compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "bar"},
Spec: compapi.ComponentSpec{
Type: "secretstores.local.file",
Version: "v1",
Metadata: []common.NameValuePair{
{Name: "secretsFile", Value: common.DynamicValue{
JSON: apiextv1.JSON{Raw: secPathJSON},
}},
},
},
}
s.operator.SetComponents(s.operator.Components()[0], component, s.operator.Components()[2], s.operator.Components()[3])
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &component, EventType: operatorv1.ResourceEventType_UPDATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, client, s.daprd.HTTPPort())
assert.ElementsMatch(c, []*rtv1.RegisteredComponents{
{Name: "bar", Type: "secretstores.local.file", Version: "v1"},
{
Name: "123", Type: "state.sqlite", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "ACTOR"},
},
{
Name: "xyz", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
{
Name: "foo", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, resp)
}, time.Second*5, time.Millisecond*10)
s.writeRead(t, ctx, client, "123")
s.writeExpectError(t, ctx, client, "bar", http.StatusBadRequest)
s.writeRead(t, ctx, client, "xyz")
s.writeRead(t, ctx, client, "foo")
})
t.Run("deleting all components should result in no components remaining", func(t *testing.T) {
s.writeRead(t, ctx, client, "123")
s.writeExpectError(t, ctx, client, "bar", http.StatusBadRequest)
s.writeRead(t, ctx, client, "xyz")
s.writeRead(t, ctx, client, "foo")
comp1 := s.operator.Components()[0]
comp2 := s.operator.Components()[2]
comp3 := s.operator.Components()[3]
s.operator.SetComponents(s.operator.Components()[1])
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp1, EventType: operatorv1.ResourceEventType_DELETED})
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp2, EventType: operatorv1.ResourceEventType_DELETED})
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp3, EventType: operatorv1.ResourceEventType_DELETED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, client, s.daprd.HTTPPort())
assert.ElementsMatch(c, []*rtv1.RegisteredComponents{
{Name: "bar", Type: "secretstores.local.file", Version: "v1"},
}, resp)
}, time.Second*10, time.Millisecond*10)
s.writeExpectError(t, ctx, client, "123", http.StatusInternalServerError)
s.writeExpectError(t, ctx, client, "bar", http.StatusInternalServerError)
s.writeExpectError(t, ctx, client, "xyz", http.StatusInternalServerError)
s.writeExpectError(t, ctx, client, "foo", http.StatusInternalServerError)
})
t.Run("recreate state component should make it available again", func(t *testing.T) {
comp := compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "123"},
Spec: compapi.ComponentSpec{
Type: "state.in-memory",
Version: "v1",
},
}
s.operator.AddComponents(comp)
s.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &comp, EventType: operatorv1.ResourceEventType_CREATED})
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(t, ctx, client, s.daprd.HTTPPort()), 2)
}, time.Second*5, time.Millisecond*10)
s.writeRead(t, ctx, client, "123")
})
}
func (s *state) writeExpectError(t *testing.T, ctx context.Context, client *http.Client, compName string, expCode int) {
t.Helper()
postURL := fmt.Sprintf("http://localhost:%d/v1.0/state/%s", s.daprd.HTTPPort(), compName)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, postURL, nil)
require.NoError(t, err)
s.doReq(t, client, req, expCode, fmt.Sprintf(
`\{"errorCode":"(ERR_STATE_STORE_NOT_CONFIGURED|ERR_STATE_STORE_NOT_FOUND)","message":"state store %s (is not configured|is not found)","details":\[.*\]\}`,
compName))
}
func (s *state) writeRead(t *testing.T, ctx context.Context, client *http.Client, compName string) {
t.Helper()
postURL := fmt.Sprintf("http://localhost:%d/v1.0/state/%s", s.daprd.HTTPPort(), url.QueryEscape(compName))
getURL := fmt.Sprintf("%s/foo", postURL)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, postURL,
strings.NewReader(`[{"key": "foo", "value": "bar"}]`))
require.NoError(t, err)
s.doReq(t, client, req, http.StatusNoContent, "")
req, err = http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil)
require.NoError(t, err)
s.doReq(t, client, req, http.StatusOK, `"bar"`)
}
func (s *state) doReq(t *testing.T, client *http.Client, req *http.Request, expCode int, expBody string) {
t.Helper()
resp, err := client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, expCode, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
assert.Regexp(t, expBody, string(body))
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/state.go
|
GO
|
mit
| 18,530 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package subscriptions
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
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"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/operator"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/subscriber"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(grpc))
}
type grpc struct {
sub *subscriber.Subscriber
daprd *daprd.Daprd
operator *operator.Operator
pubsub1, pubsub2 compapi.Component
}
func (g *grpc) Setup(t *testing.T) []framework.Option {
g.sub = subscriber.New(t)
sentry := sentry.New(t)
g.operator = operator.New(t,
operator.WithSentry(sentry),
operator.WithGetConfigurationFn(func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error) {
return &operatorv1.GetConfigurationResponse{
Configuration: []byte(
`{"kind":"Configuration","apiVersion":"dapr.io/v1alpha1","metadata":{"name":"hotreloading"},"spec":{"features":[{"name":"HotReload","enabled":true}]}}`,
),
}, nil
}),
)
g.daprd = daprd.New(t,
daprd.WithAppPort(g.sub.Port(t)),
daprd.WithAppProtocol("grpc"),
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors))),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(g.operator.Address(t)),
daprd.WithDisableK8sSecretStore(true),
)
g.pubsub1 = compapi.Component{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Component"},
ObjectMeta: metav1.ObjectMeta{Name: "pubsub0", Namespace: "default"},
Spec: compapi.ComponentSpec{Type: "pubsub.in-memory", Version: "v1"},
}
g.pubsub2 = compapi.Component{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Component"},
ObjectMeta: metav1.ObjectMeta{Name: "pubsub1", Namespace: "default"},
Spec: compapi.ComponentSpec{Type: "pubsub.in-memory", Version: "v1"},
}
g.operator.AddComponents(g.pubsub1, g.pubsub2)
return []framework.Option{
framework.WithProcesses(g.sub, sentry, g.operator, g.daprd),
}
}
func (g *grpc) Run(t *testing.T, ctx context.Context) {
g.daprd.WaitUntilRunning(t, ctx)
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, g.daprd.GetMetaRegistedComponents(t, ctx), 2)
assert.Empty(c, g.daprd.GetMetaSubscriptions(t, ctx))
}, time.Second*5, time.Millisecond*10)
newReq := func(pubsub, topic string) *rtv1.PublishEventRequest {
return &rtv1.PublishEventRequest{PubsubName: pubsub, Topic: topic, Data: []byte(`{"status": "completed"}`)}
}
g.sub.ExpectPublishNoReceive(t, ctx, g.daprd, newReq("pubsub0", "a"))
sub1 := subapi.Subscription{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v2alpha1", Kind: "Subscription"},
ObjectMeta: metav1.ObjectMeta{Name: "sub0", Namespace: "default"},
Spec: subapi.SubscriptionSpec{
Pubsubname: "pubsub0", Topic: "a",
Routes: subapi.Routes{Default: "/a"},
},
}
g.operator.AddSubscriptions(sub1)
g.operator.SubscriptionUpdateEvent(t, ctx, &api.SubscriptionUpdateEvent{
Subscription: &sub1,
EventType: operatorv1.ResourceEventType_CREATED,
})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, g.daprd.GetMetaSubscriptions(t, ctx), 1)
}, time.Second*5, time.Millisecond*10)
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub0", "a"))
g.sub.ExpectPublishNoReceive(t, ctx, g.daprd, newReq("pubsub0", "b"))
sub2 := subapi.Subscription{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v2alpha1", Kind: "Subscription"},
ObjectMeta: metav1.ObjectMeta{Name: "sub1", Namespace: "default"},
Spec: subapi.SubscriptionSpec{
Pubsubname: "pubsub0", Topic: "b",
Routes: subapi.Routes{Default: "/b"},
},
}
g.operator.AddSubscriptions(sub2)
g.operator.SubscriptionUpdateEvent(t, ctx, &api.SubscriptionUpdateEvent{
Subscription: &sub2,
EventType: operatorv1.ResourceEventType_CREATED,
})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, g.daprd.GetMetaSubscriptions(t, ctx), 2)
}, time.Second*5, time.Millisecond*10)
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub0", "a"))
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub0", "b"))
g.operator.SetSubscriptions(sub2)
g.operator.SubscriptionUpdateEvent(t, ctx, &api.SubscriptionUpdateEvent{
Subscription: &sub1,
EventType: operatorv1.ResourceEventType_DELETED,
})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, g.daprd.GetMetaSubscriptions(t, ctx), 1)
}, time.Second*5, time.Millisecond*10)
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub0", "b"))
g.sub.ExpectPublishNoReceive(t, ctx, g.daprd, newReq("pubsub0", "a"))
sub3 := subapi.Subscription{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v2alpha1", Kind: "Subscription"},
ObjectMeta: metav1.ObjectMeta{Name: "sub2", Namespace: "default"},
Spec: subapi.SubscriptionSpec{
Pubsubname: "pubsub1", Topic: "c",
Routes: subapi.Routes{Default: "/c"},
},
}
g.operator.AddSubscriptions(sub3)
g.operator.SubscriptionUpdateEvent(t, ctx, &api.SubscriptionUpdateEvent{
Subscription: &sub3,
EventType: operatorv1.ResourceEventType_CREATED,
})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, g.daprd.GetMetaSubscriptions(t, ctx), 2)
}, time.Second*5, time.Millisecond*10)
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub0", "b"))
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub1", "c"))
sub2.Spec.Topic = "d"
sub2.Spec.Routes.Default = "/d"
g.operator.SetSubscriptions(sub2, sub3)
g.operator.SubscriptionUpdateEvent(t, ctx, &api.SubscriptionUpdateEvent{
Subscription: &sub2,
EventType: operatorv1.ResourceEventType_UPDATED,
})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := g.daprd.GRPCClient(t, ctx).GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
if assert.Len(c, resp.GetSubscriptions(), 2) {
assert.Equal(c, "c", resp.GetSubscriptions()[0].GetTopic())
assert.Equal(c, "d", resp.GetSubscriptions()[1].GetTopic())
}
}, time.Second*5, time.Millisecond*10)
g.sub.ExpectPublishNoReceive(t, ctx, g.daprd, newReq("pubsub0", "b"))
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub0", "d"))
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub1", "c"))
g.operator.SetComponents()
g.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{
Component: &g.pubsub1,
EventType: operatorv1.ResourceEventType_DELETED,
})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, g.daprd.GetMetaRegistedComponents(t, ctx), 1)
}, time.Second*5, time.Millisecond*10)
g.sub.ExpectPublishError(t, ctx, g.daprd, newReq("pubsub0", "d"))
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub1", "c"))
g.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{
Component: &g.pubsub2,
EventType: operatorv1.ResourceEventType_DELETED,
})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Empty(c, g.daprd.GetMetaRegistedComponents(t, ctx))
}, time.Second*5, time.Millisecond*10)
g.sub.ExpectPublishError(t, ctx, g.daprd, newReq("pubsub0", "d"))
g.sub.ExpectPublishError(t, ctx, g.daprd, newReq("pubsub1", "c"))
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/subscriptions/grpc.go
|
GO
|
mit
| 8,499 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package subscriptions
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
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"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/operator"
"github.com/dapr/dapr/tests/integration/framework/process/http/subscriber"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(http))
}
type http struct {
sub *subscriber.Subscriber
daprd *daprd.Daprd
operator *operator.Operator
pubsub1, pubsub2 compapi.Component
}
func (h *http) Setup(t *testing.T) []framework.Option {
h.sub = subscriber.New(t,
subscriber.WithRoutes("/a", "/b", "/c", "/d"),
)
sentry := sentry.New(t)
h.operator = operator.New(t,
operator.WithSentry(sentry),
operator.WithGetConfigurationFn(func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error) {
return &operatorv1.GetConfigurationResponse{
Configuration: []byte(
`{"kind":"Configuration","apiVersion":"dapr.io/v1alpha1","metadata":{"name":"hotreloading"},"spec":{"features":[{"name":"HotReload","enabled":true}]}}`,
),
}, nil
}),
)
h.daprd = daprd.New(t,
daprd.WithAppPort(h.sub.Port()),
daprd.WithAppProtocol("http"),
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors))),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(h.operator.Address(t)),
daprd.WithDisableK8sSecretStore(true),
)
h.pubsub1 = compapi.Component{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Component"},
ObjectMeta: metav1.ObjectMeta{Name: "pubsub0", Namespace: "default"},
Spec: compapi.ComponentSpec{Type: "pubsub.in-memory", Version: "v1"},
}
h.pubsub2 = compapi.Component{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Component"},
ObjectMeta: metav1.ObjectMeta{Name: "pubsub1", Namespace: "default"},
Spec: compapi.ComponentSpec{Type: "pubsub.in-memory", Version: "v1"},
}
h.operator.AddComponents(h.pubsub1, h.pubsub2)
return []framework.Option{
framework.WithProcesses(h.sub, sentry, h.operator, h.daprd),
}
}
func (h *http) Run(t *testing.T, ctx context.Context) {
h.daprd.WaitUntilRunning(t, ctx)
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, h.daprd.GetMetaRegistedComponents(t, ctx), 2)
assert.Empty(c, h.daprd.GetMetaSubscriptions(t, ctx))
}, time.Second*5, time.Millisecond*10)
newReq := func(daprd *daprd.Daprd, pubsubName, topic string) subscriber.PublishRequest {
return subscriber.PublishRequest{
Daprd: daprd,
PubSubName: pubsubName,
Topic: topic,
Data: `{"status": "completed"}`,
}
}
h.sub.ExpectPublishNoReceive(t, ctx, newReq(h.daprd, "pubsub0", "a"))
sub1 := subapi.Subscription{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v2alpha1", Kind: "Subscription"},
ObjectMeta: metav1.ObjectMeta{Name: "sub0", Namespace: "default"},
Spec: subapi.SubscriptionSpec{
Pubsubname: "pubsub0", Topic: "a",
Routes: subapi.Routes{Default: "/a"},
},
}
h.operator.AddSubscriptions(sub1)
h.operator.SubscriptionUpdateEvent(t, ctx, &api.SubscriptionUpdateEvent{
Subscription: &sub1,
EventType: operatorv1.ResourceEventType_CREATED,
})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, h.daprd.GetMetaSubscriptions(t, ctx), 1)
}, time.Second*5, time.Millisecond*10)
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub0", "a"))
h.sub.ExpectPublishNoReceive(t, ctx, newReq(h.daprd, "pubsub0", "b"))
sub2 := subapi.Subscription{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v2alpha1", Kind: "Subscription"},
ObjectMeta: metav1.ObjectMeta{Name: "sub1", Namespace: "default"},
Spec: subapi.SubscriptionSpec{
Pubsubname: "pubsub0", Topic: "b",
Routes: subapi.Routes{Default: "/b"},
},
}
h.operator.AddSubscriptions(sub2)
h.operator.SubscriptionUpdateEvent(t, ctx, &api.SubscriptionUpdateEvent{
Subscription: &sub2,
EventType: operatorv1.ResourceEventType_CREATED,
})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, h.daprd.GetMetaSubscriptions(t, ctx), 2)
}, time.Second*5, time.Millisecond*10)
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub0", "a"))
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub0", "b"))
h.operator.SetSubscriptions(sub2)
h.operator.SubscriptionUpdateEvent(t, ctx, &api.SubscriptionUpdateEvent{
Subscription: &sub1,
EventType: operatorv1.ResourceEventType_DELETED,
})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, h.daprd.GetMetaSubscriptions(t, ctx), 1)
}, time.Second*5, time.Millisecond*10)
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub0", "b"))
h.sub.ExpectPublishNoReceive(t, ctx, newReq(h.daprd, "pubsub0", "a"))
sub3 := subapi.Subscription{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v2alpha1", Kind: "Subscription"},
ObjectMeta: metav1.ObjectMeta{Name: "sub2", Namespace: "default"},
Spec: subapi.SubscriptionSpec{
Pubsubname: "pubsub1", Topic: "c",
Routes: subapi.Routes{Default: "/c"},
},
}
h.operator.AddSubscriptions(sub3)
h.operator.SubscriptionUpdateEvent(t, ctx, &api.SubscriptionUpdateEvent{
Subscription: &sub3,
EventType: operatorv1.ResourceEventType_CREATED,
})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, h.daprd.GetMetaSubscriptions(t, ctx), 2)
}, time.Second*5, time.Millisecond*10)
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub0", "b"))
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub1", "c"))
sub2.Spec.Topic = "d"
sub2.Spec.Routes.Default = "/d"
h.operator.SetSubscriptions(sub2, sub3)
h.operator.SubscriptionUpdateEvent(t, ctx, &api.SubscriptionUpdateEvent{
Subscription: &sub2,
EventType: operatorv1.ResourceEventType_UPDATED,
})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := h.daprd.GRPCClient(t, ctx).GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
if assert.Len(c, resp.GetSubscriptions(), 2) {
assert.Equal(c, "c", resp.GetSubscriptions()[0].GetTopic())
assert.Equal(c, "d", resp.GetSubscriptions()[1].GetTopic())
}
}, time.Second*5, time.Millisecond*10)
h.sub.ExpectPublishNoReceive(t, ctx, newReq(h.daprd, "pubsub0", "b"))
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub0", "d"))
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub1", "c"))
h.operator.SetComponents()
h.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{
Component: &h.pubsub1,
EventType: operatorv1.ResourceEventType_DELETED,
})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, h.daprd.GetMetaRegistedComponents(t, ctx), 1)
}, time.Second*5, time.Millisecond*10)
h.sub.ExpectPublishError(t, ctx, newReq(h.daprd, "pubsub0", "d"))
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub1", "c"))
h.operator.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{
Component: &h.pubsub2,
EventType: operatorv1.ResourceEventType_DELETED,
})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Empty(c, h.daprd.GetMetaRegistedComponents(t, ctx))
}, time.Second*5, time.Millisecond*10)
h.sub.ExpectPublishError(t, ctx, newReq(h.daprd, "pubsub0", "d"))
h.sub.ExpectPublishError(t, ctx, newReq(h.daprd, "pubsub1", "c"))
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/subscriptions/http.go
|
GO
|
mit
| 8,617 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package subscriptions
import (
"context"
"fmt"
nethttp "net/http"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
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"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/operator"
"github.com/dapr/dapr/tests/integration/framework/process/http/subscriber"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(inflight))
}
// inflight ensures in-flight messages are not lost when subscriptions
// are hot-reloaded.
type inflight struct {
daprd *daprd.Daprd
sub *subscriber.Subscriber
operator *operator.Operator
inPublish chan struct{}
returnPublish chan struct{}
}
func (i *inflight) Setup(t *testing.T) []framework.Option {
i.inPublish = make(chan struct{})
i.returnPublish = make(chan struct{})
i.sub = subscriber.New(t,
subscriber.WithHandlerFunc("/a", func(w nethttp.ResponseWriter, r *nethttp.Request) {
close(i.inPublish)
<-i.returnPublish
}),
)
sentry := sentry.New(t)
i.operator = operator.New(t,
operator.WithSentry(sentry),
operator.WithGetConfigurationFn(func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error) {
return &operatorv1.GetConfigurationResponse{
Configuration: []byte(
`{"kind":"Configuration","apiVersion":"dapr.io/v1alpha1","metadata":{"name":"hotreloading"},"spec":{"features":[{"name":"HotReload","enabled":true}]}}`,
),
}, nil
}),
)
i.daprd = daprd.New(t,
daprd.WithAppPort(i.sub.Port()),
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(exec.WithEnvVars(t, "DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors))),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(i.operator.Address(t)),
daprd.WithDisableK8sSecretStore(true),
)
i.operator.AddComponents(compapi.Component{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Component"},
ObjectMeta: metav1.ObjectMeta{Name: "pubsub", Namespace: "default"},
Spec: compapi.ComponentSpec{Type: "pubsub.in-memory", Version: "v1"},
})
return []framework.Option{
framework.WithProcesses(i.sub, sentry, i.operator, i.daprd),
}
}
func (i *inflight) Run(t *testing.T, ctx context.Context) {
i.daprd.WaitUntilRunning(t, ctx)
assert.Len(t, i.daprd.GetMetaRegistedComponents(t, ctx), 1)
assert.Empty(t, i.daprd.GetMetaSubscriptions(t, ctx))
sub := subapi.Subscription{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v2alpha1", Kind: "Subscription"},
ObjectMeta: metav1.ObjectMeta{Name: "sub", Namespace: "default"},
Spec: subapi.SubscriptionSpec{
Pubsubname: "pubsub", Topic: "a",
Routes: subapi.Routes{Default: "/a"},
},
}
i.operator.AddSubscriptions(sub)
i.operator.SubscriptionUpdateEvent(t, ctx, &api.SubscriptionUpdateEvent{
Subscription: &sub,
EventType: operatorv1.ResourceEventType_CREATED,
})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, i.daprd.GetMetaSubscriptions(t, ctx), 1)
}, time.Second*5, time.Millisecond*10)
client := i.daprd.GRPCClient(t, ctx)
_, err := client.PublishEvent(ctx, &rtv1.PublishEventRequest{
PubsubName: "pubsub",
Topic: "a",
Data: []byte(`{"status":"completed"}`),
})
require.NoError(t, err)
select {
case <-i.inPublish:
case <-time.After(time.Second * 5):
assert.Fail(t, "did not receive publish event")
}
i.operator.SetSubscriptions()
i.operator.SubscriptionUpdateEvent(t, ctx, &api.SubscriptionUpdateEvent{
Subscription: &sub,
EventType: operatorv1.ResourceEventType_DELETED,
})
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Empty(c, i.daprd.GetMetaSubscriptions(t, ctx))
}, time.Second*5, time.Millisecond*10)
egressMetric := fmt.Sprintf("dapr_component_pubsub_egress_count|app_id:%s|component:pubsub|namespace:|success:true|topic:a", i.daprd.AppID())
ingressMetric := fmt.Sprintf("dapr_component_pubsub_ingress_count|app_id:%s|component:pubsub|namespace:|process_status:success|status:success|topic:a", i.daprd.AppID())
metrics := i.daprd.Metrics(t, ctx)
assert.Equal(t, 1, int(metrics[egressMetric]))
assert.Equal(t, 0, int(metrics[ingressMetric]))
close(i.returnPublish)
assert.EventuallyWithT(t, func(c *assert.CollectT) {
metrics := i.daprd.Metrics(t, ctx)
assert.Equal(c, 1, int(metrics[egressMetric]))
assert.Equal(c, 1, int(metrics[ingressMetric]))
}, time.Second*5, time.Millisecond*10)
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/subscriptions/inflight.go
|
GO
|
mit
| 5,610 |
/*
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"
"testing"
"github.com/stretchr/testify/require"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/dapr/dapr/pkg/apis/common"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
"github.com/dapr/dapr/pkg/operator/api"
operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/operator"
"github.com/dapr/dapr/tests/integration/framework/process/logline"
"github.com/dapr/dapr/tests/integration/framework/process/sentry"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(workflowbackend))
}
type workflowbackend struct {
daprdCreate *daprd.Daprd
daprdUpdate *daprd.Daprd
daprdDelete *daprd.Daprd
operatorCreate *operator.Operator
operatorUpdate *operator.Operator
operatorDelete *operator.Operator
loglineCreate *logline.LogLine
loglineUpdate *logline.LogLine
loglineDelete *logline.LogLine
}
func (w *workflowbackend) Setup(t *testing.T) []framework.Option {
sentry := sentry.New(t)
w.loglineCreate = logline.New(t, logline.WithStdoutLineContains(
"Aborting to hot-reload a workflowbackend component which is not supported: wfbackend (workflowbackend.actors/v1)",
))
w.loglineUpdate = logline.New(t, logline.WithStdoutLineContains(
"Aborting to hot-reload a workflowbackend component which is not supported: wfbackend (workflowbackend.sqlite/v1)",
))
w.loglineDelete = logline.New(t, logline.WithStdoutLineContains(
"Aborting to hot-reload a workflowbackend component which is not supported: wfbackend (workflowbackend.actors/v1)",
))
w.operatorCreate = operator.New(t,
operator.WithSentry(sentry),
operator.WithGetConfigurationFn(func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error) {
return &operatorv1.GetConfigurationResponse{
Configuration: []byte(
`{"kind":"Configuration","apiVersion":"dapr.io/v1alpha1","metadata":{"name":"hotreloading"},"spec":{"features":[{"name":"HotReload","enabled":true}]}}`,
),
}, nil
}),
)
w.operatorUpdate = operator.New(t,
operator.WithSentry(sentry),
operator.WithGetConfigurationFn(func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error) {
return &operatorv1.GetConfigurationResponse{
Configuration: []byte(
`{"kind":"Configuration","apiVersion":"dapr.io/v1alpha1","metadata":{"name":"hotreloading"},"spec":{"features":[{"name":"HotReload","enabled":true}]}}`,
),
}, nil
}),
)
w.operatorDelete = operator.New(t,
operator.WithSentry(sentry),
operator.WithGetConfigurationFn(func(context.Context, *operatorv1.GetConfigurationRequest) (*operatorv1.GetConfigurationResponse, error) {
return &operatorv1.GetConfigurationResponse{
Configuration: []byte(
`{"kind":"Configuration","apiVersion":"dapr.io/v1alpha1","metadata":{"name":"hotreloading"},"spec":{"features":[{"name":"HotReload","enabled":true}]}}`,
),
}, nil
}),
)
inmemStore := compapi.Component{
TypeMeta: metav1.TypeMeta{Kind: "Component", APIVersion: "dapr.io/v1alpha1"},
ObjectMeta: metav1.ObjectMeta{Name: "mystore", Namespace: "default"},
Spec: compapi.ComponentSpec{
Type: "state.in-memory", Version: "v1",
Metadata: []common.NameValuePair{{Name: "actorStateStore", Value: common.DynamicValue{JSON: apiextv1.JSON{Raw: []byte(`"true"`)}}}},
},
}
w.operatorCreate.SetComponents(inmemStore)
w.operatorUpdate.SetComponents(inmemStore, compapi.Component{
TypeMeta: metav1.TypeMeta{Kind: "Component", APIVersion: "dapr.io/v1alpha1"},
ObjectMeta: metav1.ObjectMeta{Name: "wfbackend", Namespace: "default"},
Spec: compapi.ComponentSpec{Type: "workflowbackend.actors", Version: "v1"},
})
w.operatorDelete.SetComponents(inmemStore, compapi.Component{
TypeMeta: metav1.TypeMeta{Kind: "Component", APIVersion: "dapr.io/v1alpha1"},
ObjectMeta: metav1.ObjectMeta{Name: "wfbackend", Namespace: "default"},
Spec: compapi.ComponentSpec{Type: "workflowbackend.actors", Version: "v1"},
})
w.daprdCreate = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(
exec.WithEnvVars(t,
"DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors),
),
exec.WithStdout(w.loglineCreate.Stdout()),
),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(w.operatorCreate.Address(t)),
daprd.WithDisableK8sSecretStore(true),
)
w.daprdUpdate = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(
exec.WithEnvVars(t,
"DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors),
),
exec.WithStdout(w.loglineUpdate.Stdout()),
),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(w.operatorUpdate.Address(t)),
daprd.WithDisableK8sSecretStore(true),
)
w.daprdDelete = daprd.New(t,
daprd.WithMode("kubernetes"),
daprd.WithConfigs("hotreloading"),
daprd.WithExecOptions(
exec.WithEnvVars(t,
"DAPR_TRUST_ANCHORS", string(sentry.CABundle().TrustAnchors),
),
exec.WithStdout(w.loglineDelete.Stdout()),
),
daprd.WithSentryAddress(sentry.Address()),
daprd.WithControlPlaneAddress(w.operatorDelete.Address(t)),
daprd.WithDisableK8sSecretStore(true),
)
return []framework.Option{
framework.WithProcesses(sentry,
w.operatorCreate, w.operatorUpdate, w.operatorDelete,
w.loglineCreate, w.loglineUpdate, w.loglineDelete,
w.daprdCreate, w.daprdUpdate, w.daprdDelete,
),
}
}
func (w *workflowbackend) Run(t *testing.T, ctx context.Context) {
w.daprdCreate.WaitUntilRunning(t, ctx)
w.daprdUpdate.WaitUntilRunning(t, ctx)
w.daprdDelete.WaitUntilRunning(t, ctx)
httpClient := util.HTTPClient(t)
comps := util.GetMetaComponents(t, ctx, httpClient, w.daprdCreate.HTTPPort())
require.ElementsMatch(t, []*rtv1.RegisteredComponents{
{
Name: "mystore", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, comps)
actorsComp := compapi.Component{
TypeMeta: metav1.TypeMeta{Kind: "Component", APIVersion: "dapr.io/v1alpha1"},
ObjectMeta: metav1.ObjectMeta{Name: "wfbackend", Namespace: "default"},
Spec: compapi.ComponentSpec{Type: "workflowbackend.actors", Version: "v1"},
}
w.operatorCreate.AddComponents(actorsComp)
w.operatorCreate.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &actorsComp, EventType: operatorv1.ResourceEventType_CREATED})
w.loglineCreate.EventuallyFoundAll(t)
comps = util.GetMetaComponents(t, ctx, httpClient, w.daprdUpdate.HTTPPort())
require.ElementsMatch(t, []*rtv1.RegisteredComponents{
{Name: "wfbackend", Type: "workflowbackend.actors", Version: "v1"},
{
Name: "mystore", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, comps)
sqliteComp := compapi.Component{
TypeMeta: metav1.TypeMeta{Kind: "Component", APIVersion: "dapr.io/v1alpha1"},
ObjectMeta: metav1.ObjectMeta{Name: "wfbackend", Namespace: "default"},
Spec: compapi.ComponentSpec{Type: "workflowbackend.sqlite", Version: "v1"},
}
w.operatorUpdate.SetComponents(sqliteComp)
w.operatorUpdate.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &sqliteComp, EventType: operatorv1.ResourceEventType_UPDATED})
w.loglineUpdate.EventuallyFoundAll(t)
comps = util.GetMetaComponents(t, ctx, httpClient, w.daprdDelete.HTTPPort())
require.ElementsMatch(t, []*rtv1.RegisteredComponents{
{Name: "wfbackend", Type: "workflowbackend.actors", Version: "v1"},
{
Name: "mystore", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, comps)
w.operatorDelete.SetComponents()
w.operatorDelete.ComponentUpdateEvent(t, ctx, &api.ComponentUpdateEvent{Component: &actorsComp, EventType: operatorv1.ResourceEventType_DELETED})
w.loglineDelete.EventuallyFoundAll(t)
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/operator/workflowbackend.go
|
GO
|
mit
| 9,021 |
/*
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 selfhosted
import (
"context"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/logline"
"github.com/dapr/dapr/tests/integration/framework/process/placement"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(actorstate))
}
type actorstate struct {
daprdCreate *daprd.Daprd
daprdUpdate *daprd.Daprd
daprdDelete *daprd.Daprd
resDirCreate string
resDirUpdate string
resDirDelete string
loglineCreate *logline.LogLine
loglineUpdate *logline.LogLine
loglineDelete *logline.LogLine
}
func (a *actorstate) Setup(t *testing.T) []framework.Option {
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: hotreloading
spec:
features:
- name: HotReload
enabled: true`), 0o600))
a.loglineCreate = logline.New(t, logline.WithStdoutLineContains(
"Aborting to hot-reload a state store component that is used as an actor state store: mystore (state.in-memory/v1)",
))
a.loglineUpdate = logline.New(t, logline.WithStdoutLineContains(
"Aborting to hot-reload a state store component that is used as an actor state store: mystore (pubsub.in-memory/v1)",
))
a.loglineDelete = logline.New(t, logline.WithStdoutLineContains(
"Aborting to hot-reload a state store component that is used as an actor state store: mystore (state.in-memory/v1)",
))
a.resDirCreate = t.TempDir()
a.resDirUpdate = t.TempDir()
a.resDirDelete = t.TempDir()
place := placement.New(t)
a.daprdCreate = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(a.resDirCreate),
daprd.WithPlacementAddresses(place.Address()),
daprd.WithExecOptions(
exec.WithStdout(a.loglineCreate.Stdout()),
),
)
a.daprdUpdate = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(a.resDirUpdate),
daprd.WithPlacementAddresses(place.Address()),
daprd.WithExecOptions(
exec.WithStdout(a.loglineUpdate.Stdout()),
),
)
require.NoError(t, os.WriteFile(filepath.Join(a.resDirUpdate, "state.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: mystore
spec:
type: state.in-memory
version: v1
metadata:
- name: actorstatestore
value: "true"
`), 0o600))
a.daprdDelete = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(a.resDirDelete),
daprd.WithPlacementAddresses(place.Address()),
daprd.WithExecOptions(
exec.WithStdout(a.loglineDelete.Stdout()),
),
)
require.NoError(t, os.WriteFile(filepath.Join(a.resDirDelete, "state.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: mystore
spec:
type: state.in-memory
version: v1
metadata:
- name: actorstatestore
value: "true"
`), 0o600))
return []framework.Option{
framework.WithProcesses(place,
a.loglineCreate, a.loglineUpdate, a.loglineDelete,
a.daprdCreate, a.daprdUpdate, a.daprdDelete,
),
}
}
func (a *actorstate) Run(t *testing.T, ctx context.Context) {
a.daprdCreate.WaitUntilRunning(t, ctx)
a.daprdUpdate.WaitUntilRunning(t, ctx)
a.daprdDelete.WaitUntilRunning(t, ctx)
httpClient := util.HTTPClient(t)
require.Empty(t, util.GetMetaComponents(t, ctx, httpClient, a.daprdCreate.HTTPPort()))
require.NoError(t, os.WriteFile(filepath.Join(a.resDirCreate, "state.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: mystore
spec:
type: state.in-memory
version: v1
metadata:
- name: actorstatestore
value: "true"
`), 0o600))
a.loglineCreate.EventuallyFoundAll(t)
comps := util.GetMetaComponents(t, ctx, httpClient, a.daprdUpdate.HTTPPort())
require.ElementsMatch(t, []*rtv1.RegisteredComponents{
{
Name: "mystore", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, comps)
require.NoError(t, os.WriteFile(filepath.Join(a.resDirUpdate, "state.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: mystore
spec:
type: pubsub.in-memory
version: v1
metadata:
- name: actorstatestore
value: "true"
`), 0o600))
a.loglineUpdate.EventuallyFoundAll(t)
comps = util.GetMetaComponents(t, ctx, httpClient, a.daprdDelete.HTTPPort())
require.ElementsMatch(t, []*rtv1.RegisteredComponents{
{
Name: "mystore", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, comps)
require.NoError(t, os.Remove(filepath.Join(a.resDirDelete, "state.yaml")))
a.loglineDelete.EventuallyFoundAll(t)
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/actorstate.go
|
GO
|
mit
| 5,530 |
/*
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 binding
import (
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/selfhosted/binding/input"
)
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/binding/binding.go
|
GO
|
mit
| 680 |
/*
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 input
import (
"context"
"os"
"path/filepath"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/emptypb"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/app"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(grpc))
}
type grpc struct {
daprd *daprd.Daprd
resDir string
listening [3]atomic.Bool
registered [3]atomic.Bool
bindingChan [3]chan string
}
func (g *grpc) Setup(t *testing.T) []framework.Option {
g.bindingChan = [3]chan string{
make(chan string, 1), make(chan string, 1), make(chan string, 1),
}
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: hotreloading
spec:
features:
- name: HotReload
enabled: true`), 0o600))
g.resDir = t.TempDir()
g.registered[0].Store(true)
srv := app.New(t,
app.WithOnBindingEventFn(func(ctx context.Context, in *rtv1.BindingEventRequest) (*rtv1.BindingEventResponse, error) {
switch in.GetName() {
case "binding1":
assert.True(t, g.registered[0].Load())
if g.listening[0].Load() {
g.listening[0].Store(false)
g.bindingChan[0] <- in.GetName()
}
case "binding2":
assert.True(t, g.registered[1].Load())
if g.listening[1].Load() {
g.listening[1].Store(false)
g.bindingChan[1] <- in.GetName()
}
case "binding3":
assert.True(t, g.registered[2].Load())
if g.listening[2].Load() {
g.listening[2].Store(false)
g.bindingChan[2] <- in.GetName()
}
default:
assert.Failf(t, "unexpected binding name", "binding name: %s", in.GetName())
}
return new(rtv1.BindingEventResponse), nil
}),
app.WithListInputBindings(func(context.Context, *emptypb.Empty) (*rtv1.ListInputBindingsResponse, error) {
return &rtv1.ListInputBindingsResponse{
Bindings: []string{"binding1", "binding2", "binding3"},
}, nil
}),
)
require.NoError(t, os.WriteFile(filepath.Join(g.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'binding1'
spec:
type: bindings.cron
version: v1
metadata:
- name: schedule
value: "@every 300ms"
- name: direction
value: "input"
`), 0o600))
g.daprd = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(g.resDir),
daprd.WithAppProtocol("grpc"),
daprd.WithAppPort(srv.Port(t)),
)
return []framework.Option{
framework.WithProcesses(srv, g.daprd),
}
}
func (g *grpc) Run(t *testing.T, ctx context.Context) {
g.daprd.WaitUntilRunning(t, ctx)
client := g.daprd.GRPCClient(t, ctx)
t.Run("expect 1 component to be loaded", func(t *testing.T) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(t, resp.GetRegisteredComponents(), 1)
g.expectBinding(t, 0, "binding1")
})
t.Run("create a component", func(t *testing.T) {
g.registered[1].Store(true)
require.NoError(t, os.WriteFile(filepath.Join(g.resDir, "2.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'binding2'
spec:
type: bindings.cron
version: v1
metadata:
- name: schedule
value: "@every 300ms"
- name: direction
value: "input"
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 2)
}, time.Second*5, time.Millisecond*10)
g.expectBindings(t, []bindingPair{
{0, "binding1"},
{1, "binding2"},
})
})
t.Run("create a third component", func(t *testing.T) {
g.registered[2].Store(true)
require.NoError(t, os.WriteFile(filepath.Join(g.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'binding1'
spec:
type: bindings.cron
version: v1
metadata:
- name: schedule
value: "@every 300ms"
- name: direction
value: "input"
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'binding3'
spec:
type: bindings.cron
version: v1
metadata:
- name: schedule
value: "@every 300ms"
- name: direction
value: "input"
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 3)
}, time.Second*5, time.Millisecond*10)
g.expectBindings(t, []bindingPair{
{0, "binding1"},
{1, "binding2"},
{2, "binding3"},
})
})
t.Run("deleting a component should no longer be available", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(g.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'binding3'
spec:
type: bindings.cron
version: v1
metadata:
- name: schedule
value: "@every 300ms"
- name: direction
value: "input"
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 2)
}, time.Second*5, time.Millisecond*10)
g.registered[0].Store(false)
g.expectBindings(t, []bindingPair{
{1, "binding2"},
{2, "binding3"},
})
})
t.Run("deleting all components should no longer be available", func(t *testing.T) {
require.NoError(t, os.Remove(filepath.Join(g.resDir, "1.yaml")))
require.NoError(t, os.Remove(filepath.Join(g.resDir, "2.yaml")))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Empty(c, resp.GetRegisteredComponents())
}, time.Second*5, time.Millisecond*10)
g.registered[1].Store(false)
g.registered[2].Store(false)
// Sleep to ensure binding is not triggered.
time.Sleep(time.Millisecond * 500)
})
t.Run("recreating binding should start again", func(t *testing.T) {
g.registered[0].Store(true)
require.NoError(t, os.WriteFile(filepath.Join(g.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'binding1'
spec:
type: bindings.cron
version: v1
metadata:
- name: schedule
value: "@every 300ms"
- name: direction
value: "input"
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 1)
}, time.Second*5, time.Millisecond*10)
g.expectBinding(t, 0, "binding1")
})
}
type bindingPair struct {
i int
b string
}
func (g *grpc) expectBindings(t *testing.T, expected []bindingPair) {
t.Helper()
var wg sync.WaitGroup
defer wg.Wait()
wg.Add(len(expected))
for _, e := range expected {
go func(e bindingPair) {
g.expectBinding(t, e.i, e.b)
wg.Done()
}(e)
}
}
func (g *grpc) expectBinding(t *testing.T, i int, binding string) {
t.Helper()
g.listening[i].Store(true)
select {
case got := <-g.bindingChan[i]:
assert.Equal(t, binding, got)
case <-time.After(time.Second * 5):
assert.Fail(t, "timed out waiting for binding event")
}
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/binding/input/grpc.go
|
GO
|
mit
| 8,039 |
/*
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 input
import (
"context"
nethttp "net/http"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(http))
}
type http struct {
daprd *daprd.Daprd
resDir string
listening [3]atomic.Bool
registered [3]atomic.Bool
bindingChan [3]chan string
}
func (h *http) Setup(t *testing.T) []framework.Option {
h.bindingChan = [3]chan string{
make(chan string, 1), make(chan string, 1), make(chan string, 1),
}
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: hotreloading
spec:
features:
- name: HotReload
enabled: true`), 0o600))
h.resDir = t.TempDir()
h.registered[0].Store(true)
handler := nethttp.NewServeMux()
handler.HandleFunc("/", func(w nethttp.ResponseWriter, r *nethttp.Request) {
w.WriteHeader(nethttp.StatusOK)
if strings.HasPrefix(r.URL.Path, "/binding") {
switch path := r.URL.Path; path {
case "/binding1":
assert.True(t, h.registered[0].Load())
if h.listening[0].Load() {
h.listening[0].Store(false)
h.bindingChan[0] <- path
}
case "/binding2":
assert.True(t, h.registered[1].Load())
if h.listening[1].Load() {
h.listening[1].Store(false)
h.bindingChan[1] <- path
}
case "/binding3":
assert.True(t, h.registered[2].Load())
if h.listening[2].Load() {
h.listening[2].Store(false)
h.bindingChan[2] <- path
}
default:
assert.Failf(t, "unexpected binding name", "binding name: %s", path)
}
}
})
srv := prochttp.New(t, prochttp.WithHandler(handler))
require.NoError(t, os.WriteFile(filepath.Join(h.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'binding1'
spec:
type: bindings.cron
version: v1
metadata:
- name: schedule
value: "@every 300ms"
- name: direction
value: "input"
`), 0o600))
h.daprd = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(h.resDir),
daprd.WithAppPort(srv.Port()),
)
return []framework.Option{
framework.WithProcesses(srv, h.daprd),
}
}
func (h *http) Run(t *testing.T, ctx context.Context) {
h.daprd.WaitUntilRunning(t, ctx)
client := util.HTTPClient(t)
t.Run("expect 1 component to be loaded", func(t *testing.T) {
assert.Len(t, util.GetMetaComponents(t, ctx, client, h.daprd.HTTPPort()), 1)
h.expectBinding(t, 0, "binding1")
})
t.Run("create a component", func(t *testing.T) {
h.registered[1].Store(true)
require.NoError(t, os.WriteFile(filepath.Join(h.resDir, "2.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'binding2'
spec:
type: bindings.cron
version: v1
metadata:
- name: schedule
value: "@every 300ms"
- name: direction
value: "input"
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, h.daprd.HTTPPort()), 2)
}, time.Second*5, time.Millisecond*10)
h.expectBindings(t, []bindingPair{
{0, "binding1"},
{1, "binding2"},
})
})
t.Run("create a third component", func(t *testing.T) {
h.registered[2].Store(true)
require.NoError(t, os.WriteFile(filepath.Join(h.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'binding1'
spec:
type: bindings.cron
version: v1
metadata:
- name: schedule
value: "@every 300ms"
- name: direction
value: "input"
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'binding3'
spec:
type: bindings.cron
version: v1
metadata:
- name: schedule
value: "@every 300ms"
- name: direction
value: "input"
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, h.daprd.HTTPPort()), 3)
}, time.Second*5, time.Millisecond*10)
h.expectBindings(t, []bindingPair{
{0, "binding1"},
{1, "binding2"},
{2, "binding3"},
})
})
t.Run("deleting a component should no longer be available", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(h.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'binding3'
spec:
type: bindings.cron
version: v1
metadata:
- name: schedule
value: "@every 1ms"
- name: direction
value: "input"
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, h.daprd.HTTPPort()), 2)
}, time.Second*5, time.Millisecond*10)
h.registered[0].Store(false)
h.expectBindings(t, []bindingPair{
{1, "binding2"},
{2, "binding3"},
})
})
t.Run("deleting all components should no longer be available", func(t *testing.T) {
require.NoError(t, os.Remove(filepath.Join(h.resDir, "1.yaml")))
require.NoError(t, os.Remove(filepath.Join(h.resDir, "2.yaml")))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Empty(c, util.GetMetaComponents(c, ctx, client, h.daprd.HTTPPort()))
}, time.Second*5, time.Millisecond*10)
h.registered[1].Store(false)
h.registered[2].Store(false)
// Sleep to ensure binding is not triggered.
time.Sleep(time.Millisecond * 500)
})
t.Run("recreating binding should start again", func(t *testing.T) {
h.registered[0].Store(true)
require.NoError(t, os.WriteFile(filepath.Join(h.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'binding1'
spec:
type: bindings.cron
version: v1
metadata:
- name: schedule
value: "@every 300ms"
- name: direction
value: "input"
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, h.daprd.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10)
h.expectBinding(t, 0, "binding1")
})
}
func (h *http) expectBindings(t *testing.T, expected []bindingPair) {
t.Helper()
var wg sync.WaitGroup
defer wg.Wait()
wg.Add(len(expected))
for _, e := range expected {
go func(e bindingPair) {
h.expectBinding(t, e.i, e.b)
wg.Done()
}(e)
}
}
func (h *http) expectBinding(t *testing.T, i int, binding string) {
t.Helper()
h.listening[i].Store(true)
select {
case got := <-h.bindingChan[i]:
assert.Equal(t, "/"+binding, got)
case <-time.After(time.Second * 5):
assert.Fail(t, "timed out waiting for binding event")
}
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/binding/input/http.go
|
GO
|
mit
| 7,352 |
/*
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 binding
import (
"context"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(output))
}
type output struct {
daprd *daprd.Daprd
resDir string
bindingDir1 string
bindingDir2 string
bindingDir3 string
}
func (o *output) Setup(t *testing.T) []framework.Option {
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: hotreloading
spec:
features:
- name: HotReload
enabled: true`), 0o600))
o.resDir = t.TempDir()
o.bindingDir1, o.bindingDir2, o.bindingDir3 = t.TempDir(), t.TempDir(), t.TempDir()
o.daprd = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(o.resDir),
)
return []framework.Option{
framework.WithProcesses(o.daprd),
}
}
func (o *output) Run(t *testing.T, ctx context.Context) {
o.daprd.WaitUntilRunning(t, ctx)
client := util.HTTPClient(t)
t.Run("expect no components to be loaded yet", func(t *testing.T) {
assert.Empty(t, util.GetMetaComponents(t, ctx, client, o.daprd.HTTPPort()))
})
t.Run("adding a component should become available", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(o.resDir, "1.yaml"), []byte(
fmt.Sprintf(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'binding1'
spec:
type: bindings.localstorage
version: v1
metadata:
- name: rootPath
value: '%s'
`, o.bindingDir1)), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, o.daprd.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10)
o.postBinding(t, ctx, client, "binding1", "file1", "data1")
o.postBindingFail(t, ctx, client, "binding2")
o.postBindingFail(t, ctx, client, "binding3")
o.assertFile(t, o.bindingDir1, "file1", "data1")
})
t.Run("adding another component should become available", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(o.resDir, "1.yaml"), []byte(
fmt.Sprintf(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'binding1'
spec:
type: bindings.localstorage
version: v1
metadata:
- name: rootPath
value: '%s'
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'binding2'
spec:
type: bindings.localstorage
version: v1
metadata:
- name: rootPath
value: '%s'
`, o.bindingDir1, o.bindingDir2)), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, o.daprd.HTTPPort()), 2)
}, time.Second*5, time.Millisecond*10)
o.postBinding(t, ctx, client, "binding1", "file2", "data2")
o.postBinding(t, ctx, client, "binding2", "file1", "data1")
o.postBindingFail(t, ctx, client, "binding3")
o.assertFile(t, o.bindingDir1, "file2", "data2")
o.assertFile(t, o.bindingDir2, "file1", "data1")
})
t.Run("adding 3rd component should become available", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(o.resDir, "2.yaml"), []byte(
fmt.Sprintf(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'binding3'
spec:
type: bindings.localstorage
version: v1
metadata:
- name: rootPath
value: '%s'
`, o.bindingDir3)), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, o.daprd.HTTPPort()), 3)
}, time.Second*5, time.Millisecond*10)
o.postBinding(t, ctx, client, "binding1", "file3", "data3")
o.postBinding(t, ctx, client, "binding2", "file2", "data2")
o.postBinding(t, ctx, client, "binding3", "file1", "data1")
o.assertFile(t, o.bindingDir1, "file3", "data3")
o.assertFile(t, o.bindingDir2, "file2", "data2")
o.assertFile(t, o.bindingDir3, "file1", "data1")
})
t.Run("deleting component makes it no longer available", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(o.resDir, "1.yaml"), []byte(
fmt.Sprintf(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'binding2'
spec:
type: bindings.localstorage
version: v1
metadata:
- name: rootPath
value: '%s'
`, o.bindingDir2)), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, o.daprd.HTTPPort()), 2)
}, time.Second*5, time.Millisecond*10)
o.postBindingFail(t, ctx, client, "binding1")
assert.NoFileExists(t, filepath.Join(o.bindingDir1, "file4"))
o.postBinding(t, ctx, client, "binding2", "file3", "data3")
o.postBinding(t, ctx, client, "binding3", "file2", "data2")
o.assertFile(t, o.bindingDir2, "file3", "data3")
o.assertFile(t, o.bindingDir3, "file2", "data2")
})
t.Run("deleting component files are no longer available", func(t *testing.T) {
require.NoError(t, os.Remove(filepath.Join(o.resDir, "1.yaml")))
require.NoError(t, os.Remove(filepath.Join(o.resDir, "2.yaml")))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Empty(c, util.GetMetaComponents(c, ctx, client, o.daprd.HTTPPort()))
}, time.Second*5, time.Millisecond*10)
o.postBindingFail(t, ctx, client, "binding1")
o.postBindingFail(t, ctx, client, "binding2")
o.postBindingFail(t, ctx, client, "binding3")
})
t.Run("recreating binding component should make it available again", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(o.resDir, "2.yaml"), []byte(
fmt.Sprintf(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'binding2'
spec:
type: bindings.localstorage
version: v1
metadata:
- name: rootPath
value: '%s'
`, o.bindingDir2)), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, o.daprd.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10)
o.postBinding(t, ctx, client, "binding2", "file5", "data5")
o.postBindingFail(t, ctx, client, "binding1")
o.postBindingFail(t, ctx, client, "binding3")
o.assertFile(t, o.bindingDir2, "file5", "data5")
})
}
func (o *output) postBinding(t *testing.T, ctx context.Context, client *http.Client, binding, file, data string) {
t.Helper()
url := fmt.Sprintf("http://localhost:%d/v1.0/bindings/%s", o.daprd.HTTPPort(), binding)
body := fmt.Sprintf(`{"operation":"create","data":"%s","metadata":{"fileName":"%s"}}`, data, file)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader(body))
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
respbody, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode, string(respbody))
}
func (o *output) postBindingFail(t *testing.T, ctx context.Context, client *http.Client, binding string) {
t.Helper()
url := fmt.Sprintf("http://localhost:%d/v1.0/bindings/%s", o.daprd.HTTPPort(), binding)
body := `{"operation":"create","data":"foo","metadata":{"fileName":"foo"}}`
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader(body))
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
respbody, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, http.StatusInternalServerError, resp.StatusCode, string(respbody))
}
func (o *output) assertFile(t *testing.T, dir, file, expData string) {
t.Helper()
fdata, err := os.ReadFile(filepath.Join(dir, file))
require.NoError(t, err)
assert.Equal(t, expData, string(fdata), fdata)
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/binding/output.go
|
GO
|
mit
| 8,365 |
/*
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 selfhosted
import (
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
commonv1 "github.com/dapr/dapr/pkg/proto/common/v1"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(crypto))
}
type crypto struct {
daprd *daprd.Daprd
resDir string
cryptoDir1 string
cryptoDir2 string
}
func (c *crypto) Setup(t *testing.T) []framework.Option {
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: hotreloading
spec:
features:
- name: HotReload
enabled: true`), 0o600))
c.resDir = t.TempDir()
c.cryptoDir1, c.cryptoDir2 = t.TempDir(), t.TempDir()
c.daprd = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(c.resDir),
)
return []framework.Option{
framework.WithProcesses(c.daprd),
}
}
func (c *crypto) Run(t *testing.T, ctx context.Context) {
c.daprd.WaitUntilRunning(t, ctx)
client := c.daprd.GRPCClient(t, ctx)
t.Run("expect no components to be loaded yet", func(t *testing.T) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Empty(t, resp.GetRegisteredComponents())
c.encryptDecryptFail(t, ctx, client, "crypto1")
c.encryptDecryptFail(t, ctx, client, "crypto2")
})
t.Run("creating crypto component should make it available", func(t *testing.T) {
pk := make([]byte, 32)
for i := range pk {
pk[i] = byte(i)
}
require.NoError(t, os.WriteFile(filepath.Join(c.cryptoDir1, "crypto1"), pk, 0o600))
require.NoError(t, os.WriteFile(filepath.Join(c.resDir, "1.yaml"),
[]byte(fmt.Sprintf(`apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: crypto1
spec:
type: crypto.dapr.localstorage
version: v1
metadata:
- name: path
value: '%s'
`, c.cryptoDir1)), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 1)
}, time.Second*5, time.Millisecond*10)
c.encryptDecrypt(t, ctx, client, "crypto1")
c.encryptDecryptFail(t, ctx, client, "crypto2")
c.encryptDecryptFail(t, ctx, client, "crypto3")
})
t.Run("creating another crypto component should make it available", func(t *testing.T) {
pk := make([]byte, 32)
for i := range pk {
pk[i] = byte(i + 32)
}
require.NoError(t, os.WriteFile(filepath.Join(c.cryptoDir2, "crypto2"), pk, 0o600))
require.NoError(t, os.WriteFile(filepath.Join(c.resDir, "2.yaml"),
[]byte(fmt.Sprintf(`apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: crypto2
spec:
type: crypto.dapr.localstorage
version: v1
metadata:
- name: path
value: '%s'
`, c.cryptoDir2)), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 2)
}, time.Second*5, time.Millisecond*10)
c.encryptDecrypt(t, ctx, client, "crypto1")
c.encryptDecrypt(t, ctx, client, "crypto2")
c.encryptDecryptFail(t, ctx, client, "crypto3")
})
t.Run("creating third crypto component should make it available", func(t *testing.T) {
pk := make([]byte, 32)
for i := range pk {
pk[i] = byte(i + 32)
}
require.NoError(t, os.WriteFile(filepath.Join(c.cryptoDir2, "crypto3"), pk, 0o600))
require.NoError(t, os.WriteFile(filepath.Join(c.resDir, "2.yaml"),
[]byte(fmt.Sprintf(`apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: crypto3
spec:
type: crypto.dapr.localstorage
version: v1
metadata:
- name: path
value: '%[1]s'
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: crypto2
spec:
type: crypto.dapr.localstorage
version: v1
metadata:
- name: path
value: '%[1]s'
`, c.cryptoDir2)), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 3)
}, time.Second*5, time.Millisecond*10)
c.encryptDecrypt(t, ctx, client, "crypto1")
c.encryptDecrypt(t, ctx, client, "crypto2")
c.encryptDecrypt(t, ctx, client, "crypto3")
})
t.Run("deleting crypto component (through type update) should make it no longer available", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(c.resDir, "2.yaml"), []byte(fmt.Sprintf(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: crypto2
spec:
type: state.in-memory
version: v1
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: crypto3
spec:
type: crypto.dapr.localstorage
version: v1
metadata:
- name: path
value: '%s'
`, c.cryptoDir2)), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.ElementsMatch(c, []*rtv1.RegisteredComponents{
{Name: "crypto1", Type: "crypto.dapr.localstorage", Version: "v1"},
{Name: "crypto3", Type: "crypto.dapr.localstorage", Version: "v1"},
{
Name: "crypto2", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, resp.GetRegisteredComponents())
}, time.Second*5, time.Millisecond*10)
c.encryptDecrypt(t, ctx, client, "crypto1")
c.encryptDecryptFail(t, ctx, client, "crypto2")
c.encryptDecrypt(t, ctx, client, "crypto3")
})
t.Run("deleting all crypto components should make them no longer available", func(t *testing.T) {
require.NoError(t, os.Remove(filepath.Join(c.resDir, "1.yaml")))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 2)
}, time.Second*5, time.Millisecond*10)
require.NoError(t, os.WriteFile(filepath.Join(c.resDir, "2.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: crypto1
spec:
type: state.in-memory
version: v1
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.ElementsMatch(c, []*rtv1.RegisteredComponents{
{
Name: "crypto1", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, resp.GetRegisteredComponents())
}, time.Second*5, time.Millisecond*10)
c.encryptDecryptFail(t, ctx, client, "crypto1")
c.encryptDecryptFail(t, ctx, client, "crypto2")
c.encryptDecryptFail(t, ctx, client, "crypto3")
})
t.Run("recreating crypto component should make it available again", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(c.resDir, "1.yaml"), []byte(fmt.Sprintf(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: crypto2
spec:
type: crypto.dapr.localstorage
version: v1
metadata:
- name: path
value: '%s'
`, c.cryptoDir2)), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 2)
}, time.Second*5, time.Millisecond*10)
c.encryptDecryptFail(t, ctx, client, "crypto1")
c.encryptDecrypt(t, ctx, client, "crypto2")
c.encryptDecryptFail(t, ctx, client, "crypto3")
})
}
func (c *crypto) encryptDecryptFail(t *testing.T, ctx context.Context, client rtv1.DaprClient, name string) {
t.Helper()
encclient, err := client.EncryptAlpha1(ctx)
require.NoError(t, err)
require.NoError(t, encclient.Send(&rtv1.EncryptRequest{
Options: &rtv1.EncryptRequestOptions{
ComponentName: name,
KeyName: name,
KeyWrapAlgorithm: "AES",
},
Payload: &commonv1.StreamPayload{Data: []byte("hello"), Seq: 0},
}))
resp, err := encclient.Recv()
require.Error(t, err)
require.True(t,
strings.Contains(err.Error(), "not found") ||
strings.Contains(err.Error(), "crypto providers not configured"),
)
require.Nil(t, resp)
decclient, err := client.DecryptAlpha1(ctx)
require.NoError(t, err)
require.NoError(t, decclient.Send(&rtv1.DecryptRequest{
Options: &rtv1.DecryptRequestOptions{
ComponentName: name,
KeyName: name,
},
Payload: &commonv1.StreamPayload{Seq: 0, Data: []byte("hello")},
}))
respd, err := decclient.Recv()
require.Error(t, err)
require.True(t,
strings.Contains(err.Error(), "not found") ||
strings.Contains(err.Error(), "crypto providers not configured"),
)
require.Nil(t, respd)
}
func (c *crypto) encryptDecrypt(t *testing.T, ctx context.Context, client rtv1.DaprClient, name string) {
t.Helper()
encclient, err := client.EncryptAlpha1(ctx)
require.NoError(t, err)
require.NoError(t, encclient.Send(&rtv1.EncryptRequest{
Options: &rtv1.EncryptRequestOptions{
ComponentName: name,
KeyName: name,
KeyWrapAlgorithm: "AES",
},
Payload: &commonv1.StreamPayload{Data: []byte("hello"), Seq: 0},
}))
require.NoError(t, encclient.CloseSend())
var encdata []byte
for {
var resp *rtv1.EncryptResponse
resp, err = encclient.Recv()
if resp != nil {
encdata = append(encdata, resp.GetPayload().GetData()...)
}
if errors.Is(err, io.EOF) {
break
}
require.NoError(t, err)
}
decclient, err := client.DecryptAlpha1(ctx)
require.NoError(t, err)
require.NoError(t, decclient.Send(&rtv1.DecryptRequest{
Options: &rtv1.DecryptRequestOptions{
ComponentName: name,
KeyName: name,
},
Payload: &commonv1.StreamPayload{Seq: 0, Data: encdata},
}))
require.NoError(t, decclient.CloseSend())
var resp []byte
for {
respd, err := decclient.Recv()
if respd != nil {
resp = append(resp, respd.GetPayload().GetData()...)
}
if errors.Is(err, io.EOF) {
break
}
require.NoError(t, err)
}
assert.Equal(t, "hello", string(resp))
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/crypto.go
|
GO
|
mit
| 10,929 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package app
import (
"context"
"fmt"
"io"
nethttp "net/http"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(routeralias))
}
type routeralias struct {
daprd1 *daprd.Daprd
daprd2 *daprd.Daprd
resDir string
}
func (r *routeralias) Setup(t *testing.T) []framework.Option {
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: hotreloading
spec:
features:
- name: HotReload
enabled: true
appHttpPipeline:
handlers:
- name: routeralias1
type: middleware.http.routeralias
- name: routeralias2
type: middleware.http.routeralias
- name: routeralias3
type: middleware.http.routeralias
`), 0o600))
r.resDir = t.TempDir()
srv := func(id string) *prochttp.HTTP {
handler := nethttp.NewServeMux()
handler.HandleFunc("/", func(w nethttp.ResponseWriter, r *nethttp.Request) {
fmt.Fprintf(w, "%s:%s", id, r.URL.Path)
})
return prochttp.New(t, prochttp.WithHandler(handler))
}
srv1 := srv("daprd1")
srv2 := srv("daprd2")
r.daprd1 = daprd.New(t,
daprd.WithAppPort(srv1.Port()),
)
r.daprd2 = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(r.resDir),
daprd.WithAppPort(srv2.Port()),
)
require.NoError(t, os.WriteFile(filepath.Join(r.resDir, "res.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: routeralias1
spec:
type: middleware.http.routeralias
version: v1
metadata:
- name: routes
value: '{
"/helloworld": "/foobar",
"/xyz": "/abc"
}'
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: routeralias2
spec:
type: middleware.http.routeralias
version: v1
metadata:
- name: routes
value: '{
"/helloworld": "/xyz",
"/foobar": "/abc"
}'
`), 0o600))
return []framework.Option{
framework.WithProcesses(srv1, srv2, r.daprd1, r.daprd2),
}
}
func (r *routeralias) Run(t *testing.T, ctx context.Context) {
r.daprd1.WaitUntilAppHealth(t, ctx)
r.daprd2.WaitUntilAppHealth(t, ctx)
client := util.HTTPClient(t)
r.doReq(t, ctx, client, fmt.Sprintf("/v1.0/invoke/%s/method/helloworld", r.daprd2.AppID()), "daprd2:/abc")
require.NoError(t, os.WriteFile(filepath.Join(r.resDir, "res.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: routeralias1
spec:
type: middleware.http.routeralias
version: v1
metadata:
- name: routes
value: '{
"/abc": "/barfoo",
"/xyz": "/abc"
}'
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: routeralias2
spec:
type: middleware.http.routeralias
version: v1
metadata:
- name: routes
value: '{
"/helloworld": "/xyz",
"/foobar": "/abc"
}'
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: routeralias3
spec:
type: middleware.http.routeralias
version: v1
metadata:
- name: routes
value: '{
"/helloworld": "/eee",
"/foobar": "/fff",
"/xyz": "/aaa"
}'
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
r.doReq(c, ctx, client, fmt.Sprintf("/v1.0/invoke/%s/method/helloworld", r.daprd2.AppID()), "daprd2:/aaa")
}, time.Second*10, time.Millisecond*10)
}
func (r *routeralias) doReq(t require.TestingT, ctx context.Context, client *nethttp.Client, path, expect string) {
url := fmt.Sprintf("http://localhost:%d/%s", r.daprd1.HTTPPort(), path)
req, err := nethttp.NewRequestWithContext(ctx, nethttp.MethodPost, url, nil)
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, nethttp.StatusOK, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, expect, string(body))
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/middleware/http/app/routeralias.go
|
GO
|
mit
| 4,693 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package app
import (
"context"
"fmt"
"io"
nethttp "net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(uppercase))
}
type uppercase struct {
daprd1 *daprd.Daprd
daprd2 *daprd.Daprd
daprd3 *daprd.Daprd
resDir1 string
resDir2 string
resDir3 string
}
func (u *uppercase) Setup(t *testing.T) []framework.Option {
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: hotreloading
spec:
features:
- name: HotReload
enabled: true
appHttpPipeline:
handlers:
- name: uppercase
type: middleware.http.uppercase
- name: uppercase2
type: middleware.http.uppercase
`), 0o600))
u.resDir1, u.resDir2, u.resDir3 = t.TempDir(), t.TempDir(), t.TempDir()
handler := nethttp.NewServeMux()
handler.HandleFunc("/", func(nethttp.ResponseWriter, *nethttp.Request) {})
handler.HandleFunc("/foo", func(w nethttp.ResponseWriter, r *nethttp.Request) {
_, err := io.Copy(w, r.Body)
require.NoError(t, err)
})
srv := prochttp.New(t, prochttp.WithHandler(handler))
require.NoError(t, os.WriteFile(filepath.Join(u.resDir1, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'uppercase'
spec:
type: middleware.http.uppercase
version: v1
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'uppercase2'
spec:
type: middleware.http.routeralias
version: v1
metadata:
- name: "routes"
value: '{"/foo":"/v1.0/invoke/nowhere/method/bar"}'
`), 0o600))
u.daprd1 = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(u.resDir1),
daprd.WithAppPort(srv.Port()),
)
u.daprd2 = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(u.resDir2),
daprd.WithAppPort(srv.Port()),
)
u.daprd3 = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(u.resDir3),
daprd.WithAppPort(srv.Port()),
)
return []framework.Option{
framework.WithProcesses(srv, u.daprd1, u.daprd2, u.daprd3),
}
}
func (u *uppercase) Run(t *testing.T, ctx context.Context) {
u.daprd1.WaitUntilAppHealth(t, ctx)
u.daprd2.WaitUntilAppHealth(t, ctx)
u.daprd3.WaitUntilAppHealth(t, ctx)
client := util.HTTPClient(t)
assert.Len(t, util.GetMetaComponents(t, ctx, client, u.daprd1.HTTPPort()), 2)
t.Run("existing middleware should be loaded", func(t *testing.T) {
u.doReq(t, ctx, client, u.daprd1, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, false)
})
t.Run("adding a new middleware should be loaded", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(u.resDir2, "2.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'uppercase'
spec:
type: middleware.http.uppercase
version: v1
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(t, ctx, client, u.daprd2.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10, "expected component to be loaded")
u.doReq(t, ctx, client, u.daprd1, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, false)
})
t.Run("adding third middleware should be loaded", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(u.resDir3, "3.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'uppercase'
spec:
type: middleware.http.uppercase
version: v1
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(t, ctx, client, u.daprd3.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10, "expected component to be loaded")
u.doReq(t, ctx, client, u.daprd1, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, true)
})
t.Run("changing the type of middleware should no longer make it available as type needs to match", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(u.resDir1, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'uppercase'
spec:
type: middleware.http.routeralias
version: v1
metadata:
- name: "routes"
value: '{"/foo":"/v1.0/invoke/nowhere/method/bar"}'
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'uppercase2'
spec:
type: middleware.http.routeralias
version: v1
metadata:
- name: "routes"
value: '{"/foo":"/v1.0/invoke/nowhere/method/bar"}'
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, client, u.daprd1.HTTPPort())
assert.ElementsMatch(c, []*rtv1.RegisteredComponents{
{Name: "uppercase", Type: "middleware.http.routeralias", Version: "v1"},
{Name: "uppercase2", Type: "middleware.http.routeralias", Version: "v1"},
}, resp)
}, time.Second*5, time.Millisecond*10, "expected component to be loaded")
u.doReq(t, ctx, client, u.daprd1, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, true)
})
t.Run("changing the type of middleware should make it available as type needs to match", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(u.resDir1, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'uppercase'
spec:
type: middleware.http.routeralias
version: v1
metadata:
- name: "routes"
value: '{"/foo":"/v1.0/invoke/nowhere/method/bar"}'
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'uppercase2'
spec:
type: middleware.http.uppercase
version: v1
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, client, u.daprd1.HTTPPort())
assert.ElementsMatch(c, []*rtv1.RegisteredComponents{
{Name: "uppercase", Type: "middleware.http.routeralias", Version: "v1"},
{Name: "uppercase2", Type: "middleware.http.uppercase", Version: "v1"},
}, resp)
}, time.Second*5, time.Millisecond*10, "expected component to be loaded")
u.doReq(t, ctx, client, u.daprd1, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, true)
})
t.Run("deleting components should no longer make them available", func(t *testing.T) {
require.NoError(t, os.Remove(filepath.Join(u.resDir1, "1.yaml")))
require.NoError(t, os.Remove(filepath.Join(u.resDir2, "2.yaml")))
require.NoError(t, os.Remove(filepath.Join(u.resDir3, "3.yaml")))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Empty(c, util.GetMetaComponents(c, ctx, client, u.daprd1.HTTPPort()))
assert.Empty(c, util.GetMetaComponents(c, ctx, client, u.daprd2.HTTPPort()))
assert.Empty(c, util.GetMetaComponents(c, ctx, client, u.daprd3.HTTPPort()))
}, time.Second*5, time.Millisecond*10, "expected component to be loaded")
u.doReq(t, ctx, client, u.daprd1, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, false)
})
}
func (u *uppercase) doReq(t require.TestingT, ctx context.Context, client *nethttp.Client, source, target *daprd.Daprd, expectUpper bool) {
url := fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/foo", source.HTTPPort(), target.AppID())
req, err := nethttp.NewRequestWithContext(ctx, nethttp.MethodPost, url, strings.NewReader("hello"))
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, nethttp.StatusOK, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
if expectUpper {
assert.Equal(t, "HELLO", string(body))
} else {
assert.Equal(t, "hello", string(body))
}
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/middleware/http/app/uppercase.go
|
GO
|
mit
| 10,683 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package http
import (
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/selfhosted/middleware/http/app"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/selfhosted/middleware/http/server"
)
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/middleware/http/http.go
|
GO
|
mit
| 783 |
/*
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 server
import (
"context"
"fmt"
"io"
nethttp "net/http"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(routeralias))
}
type routeralias struct {
daprd1 *daprd.Daprd
daprd2 *daprd.Daprd
resDir string
}
func (r *routeralias) Setup(t *testing.T) []framework.Option {
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: hotreloading
spec:
features:
- name: HotReload
enabled: true
httpPipeline:
handlers:
- name: routeralias1
type: middleware.http.routeralias
- name: routeralias2
type: middleware.http.routeralias
- name: routeralias3
type: middleware.http.routeralias
`), 0o600))
r.resDir = t.TempDir()
srv := func(id string) *prochttp.HTTP {
handler := nethttp.NewServeMux()
handler.HandleFunc("/", func(w nethttp.ResponseWriter, r *nethttp.Request) {
fmt.Fprintf(w, "%s:%s", id, r.URL.Path)
})
return prochttp.New(t, prochttp.WithHandler(handler))
}
srv1 := srv("daprd1")
srv2 := srv("daprd2")
r.daprd1 = daprd.New(t,
daprd.WithAppPort(srv1.Port()),
)
r.daprd2 = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(r.resDir),
daprd.WithAppPort(srv2.Port()),
)
require.NoError(t, os.WriteFile(filepath.Join(r.resDir, "res.yaml"), []byte(
fmt.Sprintf(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: routeralias1
spec:
type: middleware.http.routeralias
version: v1
metadata:
- name: routes
value: '{ "/helloworld": "/v1.0/invoke/%[1]s/method/foobar" }'
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: routeralias2
spec:
type: middleware.http.routeralias
version: v1
metadata:
- name: routes
value: '{
"/helloworld": "/v1.0/invoke/%[1]s/method/barfoo",
"/v1.0/invoke/%[1]s/method/foobar": "/v1.0/invoke/%[1]s/method/abc"
}'
`, r.daprd1.AppID()),
), 0o600))
return []framework.Option{
framework.WithProcesses(srv1, srv2, r.daprd1, r.daprd2),
}
}
func (r *routeralias) Run(t *testing.T, ctx context.Context) {
r.daprd1.WaitUntilAppHealth(t, ctx)
r.daprd2.WaitUntilAppHealth(t, ctx)
client := util.HTTPClient(t)
r.doReq(t, ctx, client, "helloworld", "daprd1:/abc")
require.NoError(t, os.WriteFile(filepath.Join(r.resDir, "res.yaml"), []byte(
fmt.Sprintf(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: routeralias1
spec:
type: middleware.http.routeralias
version: v1
metadata:
- name: routes
value: '{
"/v1.0/invoke/%[1]s/method/barfoo": "/v1.0/invoke/%[1]s/method/aaa"
}'
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: routeralias2
spec:
type: middleware.http.routeralias
version: v1
metadata:
- name: routes
value: '{
"/helloworld": "/v1.0/invoke/%[1]s/method/barfoo",
"/v1.0/invoke/%[1]s/method/abc": "/v1.0/invoke/%[1]s/method/aaa"
}'
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: routeralias3
spec:
type: middleware.http.routeralias
version: v1
metadata:
- name: routes
value: '{
"/v1.0/invoke/%[1]s/method/barfoo": "/v1.0/invoke/%[1]s/method/xyz"
}'
`, r.daprd1.AppID()),
), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
r.doReq(c, ctx, client, "helloworld", "daprd1:/xyz")
}, time.Second*10, time.Millisecond*10)
}
func (r *routeralias) doReq(t require.TestingT, ctx context.Context, client *nethttp.Client, path, expect string) {
url := fmt.Sprintf("http://localhost:%d/%s", r.daprd2.HTTPPort(), path)
req, err := nethttp.NewRequestWithContext(ctx, nethttp.MethodPost, url, nil)
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, nethttp.StatusOK, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, expect, string(body))
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/middleware/http/server/routeralias.go
|
GO
|
mit
| 4,828 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package server
import (
"context"
"fmt"
"io"
nethttp "net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(uppercase))
}
type uppercase struct {
daprd1 *daprd.Daprd
daprd2 *daprd.Daprd
daprd3 *daprd.Daprd
resDir1 string
resDir2 string
resDir3 string
}
func (u *uppercase) Setup(t *testing.T) []framework.Option {
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: hotreloading
spec:
features:
- name: HotReload
enabled: true
httpPipeline:
handlers:
- name: uppercase
type: middleware.http.uppercase
- name: uppercase2
type: middleware.http.uppercase
`), 0o600))
u.resDir1, u.resDir2, u.resDir3 = t.TempDir(), t.TempDir(), t.TempDir()
handler := nethttp.NewServeMux()
handler.HandleFunc("/", func(nethttp.ResponseWriter, *nethttp.Request) {})
handler.HandleFunc("/foo", func(w nethttp.ResponseWriter, r *nethttp.Request) {
_, err := io.Copy(w, r.Body)
require.NoError(t, err)
})
srv := prochttp.New(t, prochttp.WithHandler(handler))
require.NoError(t, os.WriteFile(filepath.Join(u.resDir1, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'uppercase'
spec:
type: middleware.http.uppercase
version: v1
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'uppercase2'
spec:
type: middleware.http.routeralias
version: v1
metadata:
- name: "routes"
value: '{"/foo":"/v1.0/invoke/nowhere/method/bar"}'
`), 0o600))
u.daprd1 = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(u.resDir1),
daprd.WithAppPort(srv.Port()),
)
u.daprd2 = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(u.resDir2),
daprd.WithAppPort(srv.Port()),
)
u.daprd3 = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(u.resDir3),
daprd.WithAppPort(srv.Port()),
)
return []framework.Option{
framework.WithProcesses(srv, u.daprd1, u.daprd2, u.daprd3),
}
}
func (u *uppercase) Run(t *testing.T, ctx context.Context) {
u.daprd1.WaitUntilAppHealth(t, ctx)
u.daprd2.WaitUntilAppHealth(t, ctx)
u.daprd3.WaitUntilAppHealth(t, ctx)
client := util.HTTPClient(t)
assert.Len(t, util.GetMetaComponents(t, ctx, client, u.daprd1.HTTPPort()), 2)
t.Run("existing middleware should be loaded", func(t *testing.T) {
u.doReq(t, ctx, client, u.daprd1, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, false)
})
t.Run("adding a new middleware should be loaded", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(u.resDir2, "2.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'uppercase'
spec:
type: middleware.http.uppercase
version: v1
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(t, ctx, client, u.daprd2.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10, "expected component to be loaded")
u.doReq(t, ctx, client, u.daprd1, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, false)
})
t.Run("adding third middleware should be loaded", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(u.resDir3, "3.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'uppercase'
spec:
type: middleware.http.uppercase
version: v1
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(t, ctx, client, u.daprd3.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10, "expected component to be loaded")
u.doReq(t, ctx, client, u.daprd1, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, true)
})
t.Run("changing the type of middleware should no longer make it available as type needs to match", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(u.resDir1, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'uppercase'
spec:
type: middleware.http.routeralias
version: v1
metadata:
- name: "routes"
value: '{"/foo":"/v1.0/invoke/nowhere/method/bar"}'
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'uppercase2'
spec:
type: middleware.http.routeralias
version: v1
metadata:
- name: "routes"
value: '{"/foo":"/v1.0/invoke/nowhere/method/bar"}'
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, client, u.daprd1.HTTPPort())
assert.ElementsMatch(c, []*rtv1.RegisteredComponents{
{Name: "uppercase", Type: "middleware.http.routeralias", Version: "v1"},
{Name: "uppercase2", Type: "middleware.http.routeralias", Version: "v1"},
}, resp)
}, time.Second*5, time.Millisecond*10, "expected component to be loaded")
u.doReq(t, ctx, client, u.daprd1, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, true)
})
t.Run("changing the type of middleware should make it available as type needs to match", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(u.resDir1, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'uppercase'
spec:
type: middleware.http.routeralias
version: v1
metadata:
- name: "routes"
value: '{"/foo":"/v1.0/invoke/nowhere/method/bar"}'
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'uppercase2'
spec:
type: middleware.http.uppercase
version: v1
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, client, u.daprd1.HTTPPort())
assert.ElementsMatch(c, []*rtv1.RegisteredComponents{
{Name: "uppercase", Type: "middleware.http.routeralias", Version: "v1"},
{Name: "uppercase2", Type: "middleware.http.uppercase", Version: "v1"},
}, resp)
}, time.Second*5, time.Millisecond*10, "expected component to be loaded")
u.doReq(t, ctx, client, u.daprd1, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, true)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, true)
})
t.Run("deleting components should no longer make them available", func(t *testing.T) {
require.NoError(t, os.Remove(filepath.Join(u.resDir1, "1.yaml")))
require.NoError(t, os.Remove(filepath.Join(u.resDir2, "2.yaml")))
require.NoError(t, os.Remove(filepath.Join(u.resDir3, "3.yaml")))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Empty(c, util.GetMetaComponents(c, ctx, client, u.daprd1.HTTPPort()))
assert.Empty(c, util.GetMetaComponents(c, ctx, client, u.daprd2.HTTPPort()))
assert.Empty(c, util.GetMetaComponents(c, ctx, client, u.daprd3.HTTPPort()))
}, time.Second*5, time.Millisecond*10, "expected component to be loaded")
u.doReq(t, ctx, client, u.daprd1, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd1, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd1, u.daprd3, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd2, u.daprd3, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd1, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd2, false)
u.doReq(t, ctx, client, u.daprd3, u.daprd3, false)
})
}
func (u *uppercase) doReq(t require.TestingT, ctx context.Context, client *nethttp.Client, source, target *daprd.Daprd, expectUpper bool) {
url := fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/foo", source.HTTPPort(), target.AppID())
req, err := nethttp.NewRequestWithContext(ctx, nethttp.MethodPost, url, strings.NewReader("hello"))
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, nethttp.StatusOK, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
if expectUpper {
assert.Equal(t, "HELLO", string(body))
} else {
assert.Equal(t, "hello", string(body))
}
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/middleware/http/server/uppercase.go
|
GO
|
mit
| 10,683 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package middleware
import (
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/selfhosted/middleware/http"
)
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/middleware/middleware.go
|
GO
|
mit
| 685 |
/*
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://wwn.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to 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 namespace
import (
"context"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/logline"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(set))
}
// set ensures that component manifest files are hot-reloaded, but ignore
// components which are not in the same namespace when NAMESPACE env var set.
type set struct {
daprd *daprd.Daprd
logline *logline.LogLine
resDir string
}
func (s *set) Setup(t *testing.T) []framework.Option {
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: hotreloading
spec:
features:
- name: HotReload
enabled: true`), 0o600))
s.resDir = t.TempDir()
s.logline = logline.New(t, logline.WithStdoutLineContains(
`"Fatal error from runtime: failed to load resources from disk: duplicate definition of Component name foo (state.in-memory/v1) with existing foo (pubsub.in-memory/v1)"`,
))
s.daprd = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(s.resDir),
daprd.WithExit1(),
daprd.WithLogLineStdout(s.logline),
daprd.WithNamespace("mynamespace"),
)
require.NoError(t, os.WriteFile(filepath.Join(s.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 123
spec:
type: state.in-memory
version: v1
`), 0o600))
return []framework.Option{
framework.WithProcesses(s.logline, s.daprd),
}
}
func (s *set) Run(t *testing.T, ctx context.Context) {
s.daprd.WaitUntilRunning(t, ctx)
assert.EventuallyWithT(t, func(t *assert.CollectT) {
assert.ElementsMatch(t, []*rtv1.RegisteredComponents{
{
Name: "123", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, s.daprd.GetMetaRegistedComponents(t, ctx))
}, 5*time.Second, 10*time.Millisecond)
require.NoError(t, os.WriteFile(filepath.Join(s.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 123
namespace: default
spec:
type: pubsub.in-memory
version: v1
`), 0o600))
assert.EventuallyWithT(t, func(t *assert.CollectT) {
assert.Empty(t, s.daprd.GetMetaRegistedComponents(t, ctx))
}, 5*time.Second, 10*time.Millisecond)
require.NoError(t, os.WriteFile(filepath.Join(s.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 123
spec:
type: pubsub.in-memory
version: v1
`), 0o600))
assert.EventuallyWithT(t, func(t *assert.CollectT) {
assert.ElementsMatch(t, []*rtv1.RegisteredComponents{
{
Name: "123", Type: "pubsub.in-memory", Version: "v1",
Capabilities: []string{"SUBSCRIBE_WILDCARDS"},
},
}, s.daprd.GetMetaRegistedComponents(t, ctx))
}, 5*time.Second, 10*time.Millisecond)
require.NoError(t, os.WriteFile(filepath.Join(s.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 123
namespace: mynamespace
spec:
type: state.in-memory
version: v1
`), 0o600))
assert.EventuallyWithT(t, func(t *assert.CollectT) {
assert.ElementsMatch(t, []*rtv1.RegisteredComponents{
{
Name: "123", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, s.daprd.GetMetaRegistedComponents(t, ctx))
}, 5*time.Second, 10*time.Millisecond)
require.NoError(t, os.WriteFile(filepath.Join(s.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: foo
namespace: foobar
spec:
type: state.in-memory
version: v1
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 123
namespace: mynamespace
spec:
type: pubsub.in-memory
version: v1
`), 0o600))
assert.EventuallyWithT(t, func(t *assert.CollectT) {
assert.ElementsMatch(t, []*rtv1.RegisteredComponents{
{
Name: "123", Type: "pubsub.in-memory", Version: "v1",
Capabilities: []string{"SUBSCRIBE_WILDCARDS"},
},
}, s.daprd.GetMetaRegistedComponents(t, ctx))
}, 5*time.Second, 10*time.Millisecond)
require.NoError(t, os.WriteFile(filepath.Join(s.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 123
namespace: mynamespace
spec:
type: state.in-memory
version: v1
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: foo
namespace: foobar
spec:
type: state.in-memory
version: v1
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: foo
namespace: mynamespace
spec:
type: pubsub.in-memory
version: v1
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: foo
spec:
type: state.in-memory
version: v1
`), 0o600))
s.logline.EventuallyFoundAll(t)
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/namespace/set.go
|
GO
|
mit
| 5,565 |
/*
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://wwn.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to 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 namespace
import (
"context"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/logline"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(unset))
}
// unset ensures that component manifest files are hot-reloaded, regardless
// of the namespace set on them when NAMESPACE env var isn't set.
type unset struct {
daprd *daprd.Daprd
logline *logline.LogLine
resDir string
}
func (u *unset) Setup(t *testing.T) []framework.Option {
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: hotreloading
spec:
features:
- name: HotReload
enabled: true`), 0o600))
u.resDir = t.TempDir()
u.logline = logline.New(t, logline.WithStdoutLineContains(
`Fatal error from runtime: failed to load resources from disk: duplicate definition of Component name foo (pubsub.in-memory/v1) with existing foo (state.in-memory/v1)\nduplicate definition of Component name foo (state.in-memory/v1) with existing foo (state.in-memory/v1)`,
))
u.daprd = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(u.resDir),
daprd.WithExit1(),
daprd.WithLogLineStdout(u.logline),
)
require.NoError(t, os.WriteFile(filepath.Join(u.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 123
spec:
type: state.in-memory
version: v1
`), 0o600))
return []framework.Option{
framework.WithProcesses(u.logline, u.daprd),
}
}
func (u *unset) Run(t *testing.T, ctx context.Context) {
u.daprd.WaitUntilRunning(t, ctx)
assert.EventuallyWithT(t, func(t *assert.CollectT) {
assert.ElementsMatch(t, []*rtv1.RegisteredComponents{
{
Name: "123", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, u.daprd.GetMetaRegistedComponents(t, ctx))
}, 5*time.Second, 10*time.Millisecond)
require.NoError(t, os.WriteFile(filepath.Join(u.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 123
namespace: default
spec:
type: pubsub.in-memory
version: v1
`), 0o600))
assert.EventuallyWithT(t, func(t *assert.CollectT) {
assert.ElementsMatch(t, []*rtv1.RegisteredComponents{
{
Name: "123", Type: "pubsub.in-memory", Version: "v1",
Capabilities: []string{"SUBSCRIBE_WILDCARDS"},
},
}, u.daprd.GetMetaRegistedComponents(t, ctx))
}, 5*time.Second, 10*time.Millisecond)
require.NoError(t, os.WriteFile(filepath.Join(u.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 123
namespace: mynamespace
spec:
type: state.in-memory
version: v1
`), 0o600))
assert.EventuallyWithT(t, func(t *assert.CollectT) {
assert.ElementsMatch(t, []*rtv1.RegisteredComponents{
{
Name: "123", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, u.daprd.GetMetaRegistedComponents(t, ctx))
}, 5*time.Second, 10*time.Millisecond)
require.NoError(t, os.WriteFile(filepath.Join(u.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 123
namespace: mynamespace
spec:
type: state.in-memory
version: v1
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: foo
namespace: foobar
spec:
type: state.in-memory
version: v1
`), 0o600))
assert.EventuallyWithT(t, func(t *assert.CollectT) {
assert.ElementsMatch(t, []*rtv1.RegisteredComponents{
{
Name: "123", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
{
Name: "foo", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, u.daprd.GetMetaRegistedComponents(t, ctx))
}, 5*time.Second, 10*time.Millisecond)
require.NoError(t, os.WriteFile(filepath.Join(u.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 123
namespace: mynamespace
spec:
type: state.in-memory
version: v1
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: foo
namespace: foobar
spec:
type: state.in-memory
version: v1
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: foo
namespace: mynamespace
spec:
type: pubsub.in-memory
version: v1
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: foo
spec:
type: state.in-memory
version: v1
`), 0o600))
u.logline.EventuallyFoundAll(t)
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/namespace/unset.go
|
GO
|
mit
| 5,473 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package pubsub
import (
"context"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/emptypb"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/app"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(grpc))
}
type grpc struct {
daprd *daprd.Daprd
resDir string
topicChan chan string
}
func (g *grpc) Setup(t *testing.T) []framework.Option {
g.topicChan = make(chan string, 1)
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: hotreloading
spec:
features:
- name: HotReload
enabled: true`), 0o600))
srv := app.New(t,
app.WithOnTopicEventFn(func(_ context.Context, in *rtv1.TopicEventRequest) (*rtv1.TopicEventResponse, error) {
g.topicChan <- in.GetPath()
return new(rtv1.TopicEventResponse), nil
}),
app.WithListTopicSubscriptions(func(context.Context, *emptypb.Empty) (*rtv1.ListTopicSubscriptionsResponse, error) {
return &rtv1.ListTopicSubscriptionsResponse{
Subscriptions: []*rtv1.TopicSubscription{
{PubsubName: "pubsub1", Topic: "topic1", Routes: &rtv1.TopicRoutes{Default: "/route1"}},
{PubsubName: "pubsub2", Topic: "topic2", Routes: &rtv1.TopicRoutes{Default: "/route2"}},
{PubsubName: "pubsub3", Topic: "topic3", Routes: &rtv1.TopicRoutes{Default: "/route3"}},
},
}, nil
}),
)
g.resDir = t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(g.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'pubsub1'
spec:
type: pubsub.in-memory
version: v1
`), 0o600))
g.daprd = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(g.resDir),
daprd.WithAppPort(srv.Port(t)),
daprd.WithAppProtocol("grpc"),
)
return []framework.Option{
framework.WithProcesses(srv, g.daprd),
}
}
func (g *grpc) Run(t *testing.T, ctx context.Context) {
g.daprd.WaitUntilRunning(t, ctx)
client := g.daprd.GRPCClient(t, ctx)
t.Run("expect 1 component to be loaded", func(t *testing.T) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(t, resp.GetRegisteredComponents(), 1)
g.publishMessage(t, ctx, client, "pubsub1", "topic1", "/route1")
g.publishMessageFails(t, ctx, client, "pubsub2", "topic2")
g.publishMessageFails(t, ctx, client, "pubsub3", "topic3")
})
t.Run("create a component", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(g.resDir, "2.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'pubsub2'
spec:
type: pubsub.in-memory
version: v1
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 2)
}, time.Second*5, time.Millisecond*10)
g.publishMessage(t, ctx, client, "pubsub1", "topic1", "/route1")
g.publishMessage(t, ctx, client, "pubsub2", "topic2", "/route2")
})
t.Run("create a third component", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(g.resDir, "2.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'pubsub2'
spec:
type: pubsub.in-memory
version: v1
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'pubsub3'
spec:
type: pubsub.in-memory
version: v1
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 3)
}, time.Second*5, time.Millisecond*10)
g.publishMessage(t, ctx, client, "pubsub1", "topic1", "/route1")
g.publishMessage(t, ctx, client, "pubsub2", "topic2", "/route2")
g.publishMessage(t, ctx, client, "pubsub3", "topic3", "/route3")
})
t.Run("delete a component", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(g.resDir, "2.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'pubsub3'
spec:
type: pubsub.in-memory
version: v1
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 2)
}, time.Second*5, time.Millisecond*10)
g.publishMessage(t, ctx, client, "pubsub1", "topic1", "/route1")
g.publishMessageFails(t, ctx, client, "pubsub2", "topic2")
g.publishMessage(t, ctx, client, "pubsub3", "topic3", "/route3")
})
t.Run("delete another component", func(t *testing.T) {
require.NoError(t, os.Remove(filepath.Join(g.resDir, "1.yaml")))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 1)
}, time.Second*5, time.Millisecond*10)
g.publishMessageFails(t, ctx, client, "pubsub1", "topic1")
g.publishMessageFails(t, ctx, client, "pubsub2", "topic2")
g.publishMessage(t, ctx, client, "pubsub3", "topic3", "/route3")
})
t.Run("delete last component", func(t *testing.T) {
require.NoError(t, os.Remove(filepath.Join(g.resDir, "2.yaml")))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Empty(c, resp.GetRegisteredComponents())
}, time.Second*5, time.Millisecond*10)
g.publishMessageFails(t, ctx, client, "pubsub1", "topic1")
g.publishMessageFails(t, ctx, client, "pubsub2", "topic2")
g.publishMessageFails(t, ctx, client, "pubsub3", "topic3")
})
t.Run("recreating pubsub should make it available again", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(g.resDir, "2.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'pubsub2'
spec:
type: pubsub.in-memory
version: v1
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := client.GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
assert.Len(c, resp.GetRegisteredComponents(), 1)
}, time.Second*5, time.Millisecond*10)
g.publishMessageFails(t, ctx, client, "pubsub1", "topic1")
g.publishMessage(t, ctx, client, "pubsub2", "topic2", "/route2")
g.publishMessageFails(t, ctx, client, "pubsub3", "topic3")
})
}
func (g *grpc) publishMessage(t *testing.T, ctx context.Context, client rtv1.DaprClient, pubsub, topic, route string) {
t.Helper()
_, err := client.PublishEvent(ctx, &rtv1.PublishEventRequest{
PubsubName: pubsub,
Topic: topic,
Data: []byte(`{"status": "completed"}`),
})
require.NoError(t, err)
select {
case topic := <-g.topicChan:
assert.Equal(t, route, topic)
case <-time.After(time.Second * 5):
assert.Fail(t, "timed out waiting for topic")
}
}
func (g *grpc) publishMessageFails(t *testing.T, ctx context.Context, client rtv1.DaprClient, pubsub, topic string) {
t.Helper()
_, err := client.PublishEvent(ctx, &rtv1.PublishEventRequest{
PubsubName: pubsub,
Topic: topic,
Data: []byte(`{"status": "completed"}`),
})
require.Error(t, err)
assert.Contains(t, err.Error(), "not found")
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/pubsub/grpc.go
|
GO
|
mit
| 8,142 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package pubsub
import (
"context"
"fmt"
"io"
nethttp "net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(http))
}
type http struct {
daprd *daprd.Daprd
resDir string
topicChan chan string
}
func (h *http) Setup(t *testing.T) []framework.Option {
h.topicChan = make(chan string, 1)
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: hotreloading
spec:
features:
- name: HotReload
enabled: true`), 0o600))
handler := nethttp.NewServeMux()
handler.HandleFunc("/dapr/subscribe", func(w nethttp.ResponseWriter, r *nethttp.Request) {
w.WriteHeader(nethttp.StatusOK)
io.WriteString(w, `[
{
"pubsubname": "pubsub1",
"topic": "topic1",
"route": "route1"
},
{
"pubsubname": "pubsub2",
"topic": "topic2",
"route": "route2"
},
{
"pubsubname": "pubsub3",
"topic": "topic3",
"route": "route3"
}
]`)
})
handler.HandleFunc("/", func(w nethttp.ResponseWriter, r *nethttp.Request) {
if strings.HasPrefix(r.URL.Path, "/route") {
h.topicChan <- r.URL.Path
}
})
srv := prochttp.New(t, prochttp.WithHandler(handler))
h.resDir = t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(h.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'pubsub1'
spec:
type: pubsub.in-memory
version: v1
`), 0o600))
h.daprd = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(h.resDir),
daprd.WithAppPort(srv.Port()),
)
return []framework.Option{
framework.WithProcesses(srv, h.daprd),
}
}
func (h *http) Run(t *testing.T, ctx context.Context) {
h.daprd.WaitUntilRunning(t, ctx)
client := util.HTTPClient(t)
t.Run("expect 1 component to be loaded", func(t *testing.T) {
assert.Len(t, util.GetMetaComponents(t, ctx, client, h.daprd.HTTPPort()), 1)
h.publishMessage(t, ctx, client, "pubsub1", "topic1", "/route1")
})
t.Run("create a component", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(h.resDir, "2.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'pubsub2'
spec:
type: pubsub.in-memory
version: v1
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, h.daprd.HTTPPort()), 2)
}, time.Second*5, time.Millisecond*10)
h.publishMessage(t, ctx, client, "pubsub1", "topic1", "/route1")
h.publishMessage(t, ctx, client, "pubsub2", "topic2", "/route2")
})
t.Run("create a third component", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(h.resDir, "2.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'pubsub2'
spec:
type: pubsub.in-memory
version: v1
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'pubsub3'
spec:
type: pubsub.in-memory
version: v1
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, h.daprd.HTTPPort()), 3)
}, time.Second*5, time.Millisecond*10)
h.publishMessage(t, ctx, client, "pubsub1", "topic1", "/route1")
h.publishMessage(t, ctx, client, "pubsub2", "topic2", "/route2")
h.publishMessage(t, ctx, client, "pubsub3", "topic3", "/route3")
})
t.Run("delete a component", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(h.resDir, "2.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'pubsub3'
spec:
type: pubsub.in-memory
version: v1
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, h.daprd.HTTPPort()), 2)
}, time.Second*5, time.Millisecond*10)
h.publishMessage(t, ctx, client, "pubsub1", "topic1", "/route1")
h.publishMessageFails(t, ctx, client, "pubsub2", "topic2")
h.publishMessage(t, ctx, client, "pubsub3", "topic3", "/route3")
})
t.Run("delete another component", func(t *testing.T) {
require.NoError(t, os.Remove(filepath.Join(h.resDir, "1.yaml")))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, h.daprd.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10)
h.publishMessageFails(t, ctx, client, "pubsub1", "topic1")
h.publishMessageFails(t, ctx, client, "pubsub2", "topic2")
h.publishMessage(t, ctx, client, "pubsub3", "topic3", "/route3")
})
t.Run("delete last component", func(t *testing.T) {
require.NoError(t, os.Remove(filepath.Join(h.resDir, "2.yaml")))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Empty(c, util.GetMetaComponents(c, ctx, client, h.daprd.HTTPPort()))
}, time.Second*5, time.Millisecond*10)
h.publishMessageFails(t, ctx, client, "pubsub1", "topic1")
h.publishMessageFails(t, ctx, client, "pubsub2", "topic2")
h.publishMessageFails(t, ctx, client, "pubsub3", "topic3")
})
t.Run("recreating pubsub should make it available again", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(h.resDir, "2.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'pubsub2'
spec:
type: pubsub.in-memory
version: v1
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, h.daprd.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10)
h.publishMessageFails(t, ctx, client, "pubsub1", "topic1")
h.publishMessage(t, ctx, client, "pubsub2", "topic2", "/route2")
h.publishMessageFails(t, ctx, client, "pubsub3", "topic3")
})
}
func (h *http) publishMessage(t *testing.T, ctx context.Context, client *nethttp.Client, pubsub, topic, route string) {
t.Helper()
reqURL := fmt.Sprintf("http://localhost:%d/v1.0/publish/%s/%s", h.daprd.HTTPPort(), pubsub, topic)
req, err := nethttp.NewRequestWithContext(ctx, nethttp.MethodPost, reqURL, strings.NewReader(`{"status": "completed"}`))
require.NoError(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
require.NoError(t, err)
assert.Equal(t, nethttp.StatusNoContent, resp.StatusCode, reqURL)
respBody, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
assert.Empty(t, string(respBody))
select {
case topic := <-h.topicChan:
assert.Equal(t, route, topic)
case <-time.After(time.Second * 5):
assert.Fail(t, "timed out waiting for topic")
}
}
func (h *http) publishMessageFails(t *testing.T, ctx context.Context, client *nethttp.Client, pubsub, topic string) {
t.Helper()
reqURL := fmt.Sprintf("http://localhost:%d/v1.0/publish/%s/%s", h.daprd.HTTPPort(), pubsub, topic)
req, err := nethttp.NewRequestWithContext(ctx, nethttp.MethodPost, reqURL, strings.NewReader(`{"status": "completed"}`))
require.NoError(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, nethttp.StatusNotFound, resp.StatusCode, reqURL)
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/pubsub/http.go
|
GO
|
mit
| 7,997 |
/*
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 selfhosted
import (
"context"
"fmt"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(scopes))
}
type scopes struct {
daprd *daprd.Daprd
resDir string
}
func (s *scopes) Setup(t *testing.T) []framework.Option {
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: hotreloading
spec:
features:
- name: HotReload
enabled: true
`), 0o600))
s.resDir = t.TempDir()
s.daprd = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(s.resDir),
)
return []framework.Option{
framework.WithProcesses(s.daprd),
}
}
func (s *scopes) Run(t *testing.T, ctx context.Context) {
s.daprd.WaitUntilRunning(t, ctx)
client := util.HTTPClient(t)
assert.Empty(t, util.GetMetaComponents(t, ctx, client, s.daprd.HTTPPort()))
require.NoError(t, os.WriteFile(filepath.Join(s.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: '123'
spec:
type: state.in-memory
version: v1
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, s.daprd.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10)
require.NoError(t, os.WriteFile(filepath.Join(s.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: '123'
spec:
type: state.in-memory
version: v1
scopes:
- not-my-app-id
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Empty(c, util.GetMetaComponents(c, ctx, client, s.daprd.HTTPPort()))
}, time.Second*5, time.Millisecond*10)
require.NoError(t, os.WriteFile(filepath.Join(s.resDir, "1.yaml"), []byte(
fmt.Sprintf(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: '123'
spec:
type: state.in-memory
version: v1
scopes:
- not-my-app-id
- '%s'
`, s.daprd.AppID())), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, s.daprd.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10)
require.NoError(t, os.WriteFile(filepath.Join(s.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: '123'
spec:
type: state.in-memory
version: v1
scopes:
- not-my-app-id
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Empty(c, util.GetMetaComponents(c, ctx, client, s.daprd.HTTPPort()))
}, time.Second*5, time.Millisecond*10)
require.NoError(t, os.WriteFile(filepath.Join(s.resDir, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: '123'
spec:
type: state.in-memory
version: v1
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, s.daprd.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10)
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/scope.go
|
GO
|
mit
| 3,754 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/
package scopes
import (
"context"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(components))
}
type components struct {
daprd *daprd.Daprd
resDir string
}
func (c *components) Setup(t *testing.T) []framework.Option {
c.resDir = t.TempDir()
c.daprd = daprd.New(t,
daprd.WithConfigManifests(t, `
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: hotreloading
spec:
features:
- name: HotReload
enabled: true`),
daprd.WithResourcesDir(c.resDir),
daprd.WithNamespace("default"),
daprd.WithAppID("myappid"),
)
return []framework.Option{
framework.WithProcesses(c.daprd),
}
}
func (c *components) Run(t *testing.T, ctx context.Context) {
c.daprd.WaitUntilRunning(t, ctx)
client := util.HTTPClient(t)
file := filepath.Join(c.resDir, "res.yaml")
require.NoError(t, os.WriteFile(file, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 123
spec:
type: state.in-memory
version: v1
`), 0o600))
require.EventuallyWithT(t, func(t *assert.CollectT) {
assert.Len(t, util.GetMetaComponents(t, ctx, client, c.daprd.HTTPPort()), 1)
}, time.Second*10, time.Millisecond*10)
require.NoError(t, os.WriteFile(file, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 123
spec:
type: state.in-memory
version: v1
scopes:
- foo
`), 0o600))
require.EventuallyWithT(t, func(t *assert.CollectT) {
assert.Empty(t, util.GetMetaComponents(t, ctx, client, c.daprd.HTTPPort()))
}, time.Second*10, time.Millisecond*10)
require.NoError(t, os.WriteFile(file, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 123
spec:
type: state.in-memory
version: v1
scopes:
- foo
- myappid
`), 0o600))
require.EventuallyWithT(t, func(t *assert.CollectT) {
assert.Len(t, util.GetMetaComponents(t, ctx, client, c.daprd.HTTPPort()), 1)
}, time.Second*10, time.Millisecond*10)
require.NoError(t, os.WriteFile(file, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 123
spec:
type: state.in-memory
version: v1
scopes:
- foo
`), 0o600))
require.EventuallyWithT(t, func(t *assert.CollectT) {
assert.Empty(t, util.GetMetaComponents(t, ctx, client, c.daprd.HTTPPort()))
}, time.Second*10, time.Millisecond*10)
require.NoError(t, os.WriteFile(file, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 123
spec:
type: state.in-memory
version: v1
`), 0o600))
require.EventuallyWithT(t, func(t *assert.CollectT) {
assert.Len(t, util.GetMetaComponents(t, ctx, client, c.daprd.HTTPPort()), 1)
}, time.Second*10, time.Millisecond*10)
require.NoError(t, os.WriteFile(file, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 123
spec:
type: state.in-memory
version: v1
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 456
spec:
type: state.in-memory
version: v1
scopes:
- myappid
`), 0o600))
require.EventuallyWithT(t, func(t *assert.CollectT) {
assert.Len(t, util.GetMetaComponents(t, ctx, client, c.daprd.HTTPPort()), 2)
}, time.Second*10, time.Millisecond*10)
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/scopes/components.go
|
GO
|
mit
| 3,930 |
/*
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 selfhosted
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
rtpbv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(secret))
}
type secret struct {
daprd *daprd.Daprd
client *http.Client
resDir1 string
resDir2 string
resDir3 string
}
func (s *secret) Setup(t *testing.T) []framework.Option {
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: hotreloading
spec:
features:
- name: HotReload
enabled: true`), 0o600))
s.resDir1, s.resDir2, s.resDir3 = t.TempDir(), t.TempDir(), t.TempDir()
s.client = util.HTTPClient(t)
s.daprd = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(s.resDir1, s.resDir2, s.resDir3),
daprd.WithExecOptions(exec.WithEnvVars(t,
"FOO_SEC_1", "bar1",
"FOO_SEC_2", "bar2",
"FOO_SEC_3", "bar3",
"BAR_SEC_1", "baz1",
"BAR_SEC_2", "baz2",
"BAR_SEC_3", "baz3",
"BAZ_SEC_1", "foo1",
"BAZ_SEC_2", "foo2",
"BAZ_SEC_3", "foo3",
)),
)
return []framework.Option{
framework.WithProcesses(s.daprd),
}
}
func (s *secret) Run(t *testing.T, ctx context.Context) {
s.daprd.WaitUntilRunning(t, ctx)
t.Run("expect no components to be loaded yet", func(t *testing.T) {
assert.Empty(t, util.GetMetaComponents(t, ctx, s.client, s.daprd.HTTPPort()))
s.readExpectError(t, ctx, "123", "SEC_1", http.StatusInternalServerError)
})
t.Run("adding a component should become available", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(s.resDir1, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: '123'
spec:
type: secretstores.local.env
version: v1
metadata:
- name: prefix
value: FOO_
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, s.client, s.daprd.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10)
resp := util.GetMetaComponents(t, ctx, s.client, s.daprd.HTTPPort())
require.Len(t, resp, 1)
assert.ElementsMatch(t, resp, []*rtpbv1.RegisteredComponents{
{Name: "123", Type: "secretstores.local.env", Version: "v1"},
})
s.read(t, ctx, "123", "SEC_1", "bar1")
s.read(t, ctx, "123", "SEC_2", "bar2")
s.read(t, ctx, "123", "SEC_3", "bar3")
})
t.Run("adding a second and third component should also become available", func(t *testing.T) {
// After a single secret store exists, Dapr returns a Unauthorized response
// rather than an Internal Server Error when writing to a non-existent
// secret store.
s.readExpectError(t, ctx, "abc", "2-sec-1", http.StatusUnauthorized)
s.readExpectError(t, ctx, "xyz", "SEC_1", http.StatusUnauthorized)
require.NoError(t, os.WriteFile(filepath.Join(s.resDir2, "2-sec.json"), []byte(`
{
"2-sec-1": "foo",
"2-sec-2": "bar",
"2-sec-3": "xxx"
}
`), 0o600))
require.NoError(t, os.WriteFile(filepath.Join(s.resDir2, "2.yaml"), []byte(fmt.Sprintf(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'abc'
spec:
type: secretstores.local.file
version: v1
metadata:
- name: secretsFile
value: '%s'
`, filepath.Join(s.resDir2, "2-sec.json"))), 0o600))
require.NoError(t, os.WriteFile(filepath.Join(s.resDir3, "3.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'xyz'
spec:
type: secretstores.local.env
version: v1
metadata:
- name: prefix
value: BAR_
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, s.client, s.daprd.HTTPPort()), 3)
}, time.Second*5, time.Millisecond*10)
resp := util.GetMetaComponents(t, ctx, s.client, s.daprd.HTTPPort())
require.Len(t, resp, 3)
assert.ElementsMatch(t, []*rtpbv1.RegisteredComponents{
{Name: "123", Type: "secretstores.local.env", Version: "v1"},
{Name: "abc", Type: "secretstores.local.file", Version: "v1"},
{Name: "xyz", Type: "secretstores.local.env", Version: "v1"},
}, resp)
s.read(t, ctx, "123", "SEC_1", "bar1")
s.read(t, ctx, "123", "SEC_2", "bar2")
s.read(t, ctx, "123", "SEC_3", "bar3")
s.read(t, ctx, "abc", "2-sec-1", "foo")
s.read(t, ctx, "abc", "2-sec-2", "bar")
s.read(t, ctx, "abc", "2-sec-3", "xxx")
s.read(t, ctx, "xyz", "SEC_1", "baz1")
s.read(t, ctx, "xyz", "SEC_2", "baz2")
s.read(t, ctx, "xyz", "SEC_3", "baz3")
})
t.Run("changing the type of a secret store should update the component and still be available", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(s.resDir2, "2.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'abc'
spec:
type: secretstores.local.env
version: v1
metadata:
- name: prefix
value: BAZ_
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, s.client, s.daprd.HTTPPort())
assert.ElementsMatch(c, []*rtpbv1.RegisteredComponents{
{Name: "123", Type: "secretstores.local.env", Version: "v1"},
{Name: "abc", Type: "secretstores.local.env", Version: "v1"},
{Name: "xyz", Type: "secretstores.local.env", Version: "v1"},
}, resp)
}, time.Second*5, time.Millisecond*10)
s.read(t, ctx, "123", "SEC_1", "bar1")
s.read(t, ctx, "123", "SEC_2", "bar2")
s.read(t, ctx, "123", "SEC_3", "bar3")
s.read(t, ctx, "abc", "SEC_1", "foo1")
s.read(t, ctx, "abc", "SEC_2", "foo2")
s.read(t, ctx, "abc", "SEC_3", "foo3")
s.read(t, ctx, "xyz", "SEC_1", "baz1")
s.read(t, ctx, "xyz", "SEC_2", "baz2")
s.read(t, ctx, "xyz", "SEC_3", "baz3")
})
t.Run("updating multiple secret stores should be updated, and multiple components in a single file", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(s.resDir1, "1-sec.json"), []byte(`
{
"1-sec-1": "foo",
"1-sec-2": "bar",
"1-sec-3": "xxx"
}
`), 0o600))
require.NoError(t, os.WriteFile(filepath.Join(s.resDir1, "1.yaml"), []byte(fmt.Sprintf(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: '123'
spec:
type: secretstores.local.file
version: v1
metadata:
- name: secretsFile
value: '%s'
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'foo'
spec:
type: secretstores.local.env
version: v1
metadata:
- name: prefix
value: BAZ_
`, filepath.Join(s.resDir1, "1-sec.json"))), 0o600))
require.NoError(t, os.WriteFile(filepath.Join(s.resDir2, "2.yaml"), []byte(fmt.Sprintf(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'abc'
spec:
type: secretstores.local.file
version: v1
metadata:
- name: secretsFile
value: '%s'
`, filepath.Join(s.resDir2, "2-sec.json"))), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, s.client, s.daprd.HTTPPort())
assert.ElementsMatch(c, []*rtpbv1.RegisteredComponents{
{Name: "123", Type: "secretstores.local.file", Version: "v1"},
{Name: "abc", Type: "secretstores.local.file", Version: "v1"},
{Name: "xyz", Type: "secretstores.local.env", Version: "v1"},
{Name: "foo", Type: "secretstores.local.env", Version: "v1"},
}, resp)
}, time.Second*5, time.Millisecond*10)
s.read(t, ctx, "123", "1-sec-1", "foo")
s.read(t, ctx, "123", "1-sec-2", "bar")
s.read(t, ctx, "123", "1-sec-3", "xxx")
s.read(t, ctx, "abc", "2-sec-1", "foo")
s.read(t, ctx, "abc", "2-sec-2", "bar")
s.read(t, ctx, "abc", "2-sec-3", "xxx")
s.read(t, ctx, "xyz", "SEC_1", "baz1")
s.read(t, ctx, "xyz", "SEC_2", "baz2")
s.read(t, ctx, "xyz", "SEC_3", "baz3")
s.read(t, ctx, "foo", "SEC_1", "foo1")
s.read(t, ctx, "foo", "SEC_2", "foo2")
s.read(t, ctx, "foo", "SEC_3", "foo3")
})
t.Run("renaming a component should close the old name, and open the new one", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(s.resDir2, "2.yaml"), []byte(fmt.Sprintf(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'bar'
spec:
type: secretstores.local.file
version: v1
metadata:
- name: secretsFile
value: '%s'
`, filepath.Join(s.resDir2, "2-sec.json"))), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, s.client, s.daprd.HTTPPort())
assert.ElementsMatch(c, []*rtpbv1.RegisteredComponents{
{Name: "123", Type: "secretstores.local.file", Version: "v1"},
{Name: "bar", Type: "secretstores.local.file", Version: "v1"},
{Name: "xyz", Type: "secretstores.local.env", Version: "v1"},
{Name: "foo", Type: "secretstores.local.env", Version: "v1"},
}, resp)
}, time.Second*5, time.Millisecond*10)
s.read(t, ctx, "123", "1-sec-1", "foo")
s.read(t, ctx, "123", "1-sec-2", "bar")
s.read(t, ctx, "123", "1-sec-3", "xxx")
s.read(t, ctx, "bar", "2-sec-1", "foo")
s.read(t, ctx, "bar", "2-sec-2", "bar")
s.read(t, ctx, "bar", "2-sec-3", "xxx")
s.read(t, ctx, "xyz", "SEC_1", "baz1")
s.read(t, ctx, "xyz", "SEC_2", "baz2")
s.read(t, ctx, "xyz", "SEC_3", "baz3")
s.read(t, ctx, "foo", "SEC_1", "foo1")
s.read(t, ctx, "foo", "SEC_2", "foo2")
s.read(t, ctx, "foo", "SEC_3", "foo3")
})
t.Run("deleting a component (through type update) should delete the components", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(s.resDir2, "2.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'bar'
spec:
type: state.in-memory
version: v1
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, s.client, s.daprd.HTTPPort())
assert.ElementsMatch(c,
[]*rtpbv1.RegisteredComponents{
{Name: "123", Type: "secretstores.local.file", Version: "v1"},
{Name: "xyz", Type: "secretstores.local.env", Version: "v1"},
{Name: "foo", Type: "secretstores.local.env", Version: "v1"},
{
Name: "bar", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, resp)
}, time.Second*5, time.Millisecond*10)
s.read(t, ctx, "123", "1-sec-1", "foo")
s.read(t, ctx, "123", "1-sec-2", "bar")
s.read(t, ctx, "123", "1-sec-3", "xxx")
s.read(t, ctx, "xyz", "SEC_1", "baz1")
s.read(t, ctx, "xyz", "SEC_2", "baz2")
s.read(t, ctx, "xyz", "SEC_3", "baz3")
s.read(t, ctx, "foo", "SEC_1", "foo1")
s.read(t, ctx, "foo", "SEC_2", "foo2")
s.read(t, ctx, "foo", "SEC_3", "foo3")
s.readExpectError(t, ctx, "bar", "2-sec-1", http.StatusUnauthorized)
s.readExpectError(t, ctx, "bar", "2-sec-2", http.StatusUnauthorized)
s.readExpectError(t, ctx, "bar", "2-sec-3", http.StatusUnauthorized)
})
t.Run("deleting all components should result in no components remaining", func(t *testing.T) {
require.NoError(t, os.Remove(filepath.Join(s.resDir1, "1.yaml")))
require.NoError(t, os.Remove(filepath.Join(s.resDir3, "3.yaml")))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, s.client, s.daprd.HTTPPort())
assert.ElementsMatch(c, []*rtpbv1.RegisteredComponents{
{
Name: "bar", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, resp)
}, time.Second*5, time.Millisecond*10)
s.readExpectError(t, ctx, "123", "1-sec-1", http.StatusInternalServerError)
s.readExpectError(t, ctx, "xyz", "SEC_1", http.StatusInternalServerError)
s.readExpectError(t, ctx, "bar", "2-sec-1", http.StatusInternalServerError)
s.readExpectError(t, ctx, "foo", "SEC_1", http.StatusInternalServerError)
})
t.Run("recreating secret component should make it available again", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(s.resDir1, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: '123'
spec:
type: secretstores.local.env
version: v1
metadata:
- name: prefix
value: FOO_
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, s.client, s.daprd.HTTPPort()), 2)
}, time.Second*5, time.Millisecond*10)
s.read(t, ctx, "123", "SEC_1", "bar1")
s.read(t, ctx, "123", "SEC_2", "bar2")
s.read(t, ctx, "123", "SEC_3", "bar3")
})
}
func (s *secret) readExpectError(t *testing.T, ctx context.Context, compName, key string, expCode int) {
t.Helper()
getURL := fmt.Sprintf("http://localhost:%d/v1.0/secrets/%s/%s",
s.daprd.HTTPPort(), url.QueryEscape(compName), url.QueryEscape(key))
req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil)
require.NoError(t, err)
s.doReq(t, req, expCode, fmt.Sprintf(
`\{"errorCode":"(ERR_SECRET_STORES_NOT_CONFIGURED|ERR_SECRET_STORE_NOT_FOUND)","message":"(secret store is not configured|failed finding secret store with key %s)"\}`,
compName))
}
func (s *secret) read(t *testing.T, ctx context.Context, compName, key, expValue string) {
t.Helper()
getURL := fmt.Sprintf("http://localhost:%d/v1.0/secrets/%s/%s", s.daprd.HTTPPort(), url.QueryEscape(compName), url.QueryEscape(key))
req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil)
require.NoError(t, err)
s.doReq(t, req, http.StatusOK, expValue)
}
func (s *secret) doReq(t *testing.T, req *http.Request, expCode int, expBody string) {
t.Helper()
resp, err := s.client.Do(req)
require.NoError(t, err)
assert.Equal(t, expCode, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
assert.Regexp(t, expBody, string(body))
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/secret.go
|
GO
|
mit
| 14,460 |
/*
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 selfhosted
import (
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/selfhosted/binding"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/selfhosted/middleware"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/selfhosted/namespace"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/selfhosted/pubsub"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/selfhosted/scopes"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/selfhosted/subscriptions"
)
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/selfhosted.go
|
GO
|
mit
| 1,111 |
/*
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 selfhosted
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
rtpbv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(state))
}
type state struct {
daprd *daprd.Daprd
resDir1 string
resDir2 string
resDir3 string
}
func (s *state) Setup(t *testing.T) []framework.Option {
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: hotreloading
spec:
features:
- name: HotReload
enabled: true`), 0o600))
s.resDir1, s.resDir2, s.resDir3 = t.TempDir(), t.TempDir(), t.TempDir()
s.daprd = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(s.resDir1, s.resDir2, s.resDir3),
)
return []framework.Option{
framework.WithProcesses(s.daprd),
}
}
func (s *state) Run(t *testing.T, ctx context.Context) {
s.daprd.WaitUntilRunning(t, ctx)
client := util.HTTPClient(t)
t.Run("expect no components to be loaded yet", func(t *testing.T) {
assert.Empty(t, util.GetMetaComponents(t, ctx, client, s.daprd.HTTPPort()))
s.writeExpectError(t, ctx, client, "123", http.StatusInternalServerError)
})
t.Run("adding a component should become available", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(s.resDir1, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: '123'
spec:
type: state.in-memory
version: v1
metadata: []
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, s.daprd.HTTPPort()), 1)
}, time.Second*5, time.Millisecond*10)
resp := util.GetMetaComponents(t, ctx, client, s.daprd.HTTPPort())
assert.ElementsMatch(t, []*rtpbv1.RegisteredComponents{
{
Name: "123", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, resp)
s.writeRead(t, ctx, client, "123")
})
t.Run("adding a second and third component should also become available", func(t *testing.T) {
// After a single state store exists, Dapr returns a Bad Request response
// rather than an Internal Server Error when writing to a non-existent
// state store.
s.writeExpectError(t, ctx, client, "abc", http.StatusBadRequest)
s.writeExpectError(t, ctx, client, "xyz", http.StatusBadRequest)
require.NoError(t, os.WriteFile(filepath.Join(s.resDir2, "2.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'abc'
spec:
type: state.in-memory
version: v1
metadata: []
`), 0o600))
require.NoError(t, os.WriteFile(filepath.Join(s.resDir3, "3.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'xyz'
spec:
type: state.in-memory
version: v1
metadata: []
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, s.daprd.HTTPPort()), 3)
}, time.Second*5, time.Millisecond*10)
resp := util.GetMetaComponents(t, ctx, client, s.daprd.HTTPPort())
assert.ElementsMatch(t, []*rtpbv1.RegisteredComponents{
{
Name: "123", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
{
Name: "abc", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
{
Name: "xyz", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, resp)
s.writeRead(t, ctx, client, "123")
s.writeRead(t, ctx, client, "abc")
s.writeRead(t, ctx, client, "xyz")
})
tmpDir := t.TempDir()
t.Run("changing the type of a state store should update the component and still be available", func(t *testing.T) {
s.writeRead(t, ctx, client, "123")
s.writeRead(t, ctx, client, "abc")
s.writeRead(t, ctx, client, "xyz")
require.NoError(t, os.WriteFile(filepath.Join(s.resDir2, "2.yaml"), []byte(fmt.Sprintf(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'abc'
spec:
type: state.sqlite
version: v1
metadata:
- name: connectionString
value: %s/db.sqlite
`, tmpDir)), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, client, s.daprd.HTTPPort())
assert.ElementsMatch(c, []*rtpbv1.RegisteredComponents{
{
Name: "123", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
{
Name: "abc", Type: "state.sqlite", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "ACTOR"},
},
{
Name: "xyz", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, resp)
}, time.Second*5, time.Millisecond*10)
s.writeRead(t, ctx, client, "123")
s.writeRead(t, ctx, client, "abc")
s.writeRead(t, ctx, client, "xyz")
})
t.Run("updating multiple state stores should be updated, and multiple components in a single file", func(t *testing.T) {
s.writeRead(t, ctx, client, "123")
s.writeRead(t, ctx, client, "abc")
s.writeRead(t, ctx, client, "xyz")
s.writeExpectError(t, ctx, client, "foo", http.StatusBadRequest)
require.NoError(t, os.WriteFile(filepath.Join(s.resDir1, "1.yaml"), []byte(fmt.Sprintf(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: '123'
spec:
type: state.sqlite
version: v1
metadata:
- name: connectionString
value: %s/db.sqlite
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'foo'
spec:
type: state.in-memory
version: v1
metadata: []
`, s.resDir1)), 0o600))
require.NoError(t, os.WriteFile(filepath.Join(s.resDir2, "2.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'abc'
spec:
type: state.in-memory
version: v1
metadata: []
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, client, s.daprd.HTTPPort())
assert.ElementsMatch(c, []*rtpbv1.RegisteredComponents{
{
Name: "123", Type: "state.sqlite", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "ACTOR"},
},
{
Name: "abc", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
{
Name: "xyz", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
{
Name: "foo", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, resp)
}, time.Second*5, time.Millisecond*10)
s.writeRead(t, ctx, client, "123")
s.writeRead(t, ctx, client, "abc")
s.writeRead(t, ctx, client, "xyz")
s.writeRead(t, ctx, client, "foo")
})
t.Run("renaming a component should close the old name, and open the new one", func(t *testing.T) {
s.writeRead(t, ctx, client, "123")
s.writeRead(t, ctx, client, "abc")
s.writeRead(t, ctx, client, "xyz")
s.writeRead(t, ctx, client, "foo")
require.NoError(t, os.WriteFile(filepath.Join(s.resDir2, "2.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'bar'
spec:
type: state.in-memory
version: v1
metadata: []
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, client, s.daprd.HTTPPort())
assert.ElementsMatch(c, []*rtpbv1.RegisteredComponents{
{
Name: "123", Type: "state.sqlite", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "ACTOR"},
},
{
Name: "bar", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
{
Name: "xyz", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
{
Name: "foo", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, resp)
}, time.Second*5, time.Millisecond*10)
s.writeRead(t, ctx, client, "123")
s.writeRead(t, ctx, client, "bar")
s.writeRead(t, ctx, client, "xyz")
s.writeRead(t, ctx, client, "foo")
})
tmpDir = t.TempDir()
t.Run("deleting a component (through type update) should delete the components", func(t *testing.T) {
s.writeRead(t, ctx, client, "123")
s.writeRead(t, ctx, client, "bar")
s.writeRead(t, ctx, client, "xyz")
s.writeRead(t, ctx, client, "foo")
secPath := filepath.Join(tmpDir, "foo")
require.NoError(t, os.WriteFile(secPath, []byte(`{}`), 0o600))
require.NoError(t, os.WriteFile(filepath.Join(s.resDir2, "2.yaml"), []byte(fmt.Sprintf(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'bar'
spec:
type: secretstores.local.file
version: v1
metadata:
- name: secretsFile
value: '%s'
`, secPath)), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, client, s.daprd.HTTPPort())
assert.ElementsMatch(c, []*rtpbv1.RegisteredComponents{
{Name: "bar", Type: "secretstores.local.file", Version: "v1"},
{
Name: "123", Type: "state.sqlite", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "ACTOR"},
},
{
Name: "xyz", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
{
Name: "foo", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, resp)
}, time.Second*5, time.Millisecond*10)
s.writeRead(t, ctx, client, "123")
s.writeExpectError(t, ctx, client, "bar", http.StatusBadRequest)
s.writeRead(t, ctx, client, "xyz")
s.writeRead(t, ctx, client, "foo")
})
t.Run("deleting all components should result in no components remaining", func(t *testing.T) {
s.writeRead(t, ctx, client, "123")
s.writeExpectError(t, ctx, client, "bar", http.StatusBadRequest)
s.writeRead(t, ctx, client, "xyz")
s.writeRead(t, ctx, client, "foo")
require.NoError(t, os.Remove(filepath.Join(s.resDir1, "1.yaml")))
require.NoError(t, os.Remove(filepath.Join(s.resDir3, "3.yaml")))
require.EventuallyWithT(t, func(c *assert.CollectT) {
resp := util.GetMetaComponents(c, ctx, client, s.daprd.HTTPPort())
assert.ElementsMatch(c, []*rtpbv1.RegisteredComponents{
{Name: "bar", Type: "secretstores.local.file", Version: "v1"},
}, resp)
}, time.Second*10, time.Millisecond*10)
s.writeExpectError(t, ctx, client, "123", http.StatusInternalServerError)
s.writeExpectError(t, ctx, client, "bar", http.StatusInternalServerError)
s.writeExpectError(t, ctx, client, "xyz", http.StatusInternalServerError)
s.writeExpectError(t, ctx, client, "foo", http.StatusInternalServerError)
})
t.Run("recreate state component should make it available again", func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(s.resDir1, "1.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: '123'
spec:
type: state.in-memory
version: v1
metadata: []
`), 0o600))
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, util.GetMetaComponents(c, ctx, client, s.daprd.HTTPPort()), 2)
}, time.Second*5, time.Millisecond*10)
s.writeRead(t, ctx, client, "123")
})
}
func (s *state) writeExpectError(t *testing.T, ctx context.Context, client *http.Client, compName string, expCode int) {
t.Helper()
postURL := fmt.Sprintf("http://localhost:%d/v1.0/state/%s", s.daprd.HTTPPort(), compName)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, postURL, nil)
require.NoError(t, err)
s.doReq(t, client, req, expCode, fmt.Sprintf(
`\{"errorCode":"(ERR_STATE_STORE_NOT_CONFIGURED|ERR_STATE_STORE_NOT_FOUND)","message":"state store %s (is not configured|is not found)","details":\[.*\]\}`,
compName))
}
func (s *state) writeRead(t *testing.T, ctx context.Context, client *http.Client, compName string) {
t.Helper()
postURL := fmt.Sprintf("http://localhost:%d/v1.0/state/%s", s.daprd.HTTPPort(), url.QueryEscape(compName))
getURL := fmt.Sprintf("%s/foo", postURL)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, postURL,
strings.NewReader(`[{"key": "foo", "value": "bar"}]`))
require.NoError(t, err)
s.doReq(t, client, req, http.StatusNoContent, "")
req, err = http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil)
require.NoError(t, err)
s.doReq(t, client, req, http.StatusOK, `"bar"`)
}
func (s *state) doReq(t *testing.T, client *http.Client, req *http.Request, expCode int, expBody string) {
t.Helper()
resp, err := client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, expCode, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
assert.Regexp(t, expBody, string(body))
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/state.go
|
GO
|
mit
| 14,178 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package subscriptions
import (
"context"
"fmt"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/subscriber"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(grpc))
}
type grpc struct {
daprd *daprd.Daprd
sub *subscriber.Subscriber
resDir1 string
resDir2 string
}
func (g *grpc) Setup(t *testing.T) []framework.Option {
g.sub = subscriber.New(t)
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: hotreloading
spec:
features:
- name: HotReload
enabled: true`), 0o600))
g.resDir1, g.resDir2 = t.TempDir(), t.TempDir()
for i, dir := range []string{g.resDir1, g.resDir2} {
require.NoError(t, os.WriteFile(filepath.Join(dir, "pubsub.yaml"), []byte(fmt.Sprintf(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'pubsub%d'
spec:
type: pubsub.in-memory
version: v1
`, i)), 0o600))
}
g.daprd = daprd.New(t,
daprd.WithAppPort(g.sub.Port(t)),
daprd.WithAppProtocol("grpc"),
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(g.resDir1, g.resDir2),
)
return []framework.Option{
framework.WithProcesses(g.sub, g.daprd),
}
}
func (g *grpc) Run(t *testing.T, ctx context.Context) {
g.daprd.WaitUntilRunning(t, ctx)
assert.Len(t, g.daprd.GetMetaRegistedComponents(t, ctx), 2)
assert.Empty(t, g.daprd.GetMetaSubscriptions(t, ctx))
newReq := func(pubsub, topic string) *rtv1.PublishEventRequest {
return &rtv1.PublishEventRequest{PubsubName: pubsub, Topic: topic, Data: []byte(`{"status": "completed"}`)}
}
g.sub.ExpectPublishNoReceive(t, ctx, g.daprd, newReq("pubsub0", "a"))
require.NoError(t, os.WriteFile(filepath.Join(g.resDir1, "sub.yaml"), []byte(`
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: 'sub1'
spec:
pubsubname: 'pubsub0'
topic: 'a'
routes:
default: '/a'
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, g.daprd.GetMetaSubscriptions(t, ctx), 1)
}, time.Second*5, time.Millisecond*10)
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub0", "a"))
g.sub.ExpectPublishNoReceive(t, ctx, g.daprd, newReq("pubsub0", "b"))
require.NoError(t, os.WriteFile(filepath.Join(g.resDir2, "sub.yaml"), []byte(`
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: 'sub2'
spec:
pubsubname: 'pubsub0'
topic: 'b'
routes:
default: '/b'
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, g.daprd.GetMetaSubscriptions(t, ctx), 2)
}, time.Second*5, time.Millisecond*10)
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub0", "b"))
require.NoError(t, os.Remove(filepath.Join(g.resDir1, "sub.yaml")))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, g.daprd.GetMetaSubscriptions(t, ctx), 1)
}, time.Second*5, time.Millisecond*10)
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub0", "b"))
g.sub.ExpectPublishNoReceive(t, ctx, g.daprd, newReq("pubsub0", "a"))
g.sub.ExpectPublishNoReceive(t, ctx, g.daprd, newReq("pubsub1", "c"))
require.NoError(t, os.WriteFile(filepath.Join(g.resDir2, "sub.yaml"), []byte(`
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: 'sub2'
spec:
pubsubname: 'pubsub0'
topic: 'b'
routes:
default: '/b'
---
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: 'sub3'
spec:
pubsubname: 'pubsub1'
topic: c
routes:
default: '/c'
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, g.daprd.GetMetaSubscriptions(t, ctx), 2)
}, time.Second*5, time.Millisecond*10)
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub0", "b"))
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub1", "c"))
require.NoError(t, os.WriteFile(filepath.Join(g.resDir2, "sub.yaml"), []byte(`
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: 'sub2'
spec:
pubsubname: 'pubsub0'
topic: 'd'
routes:
default: '/d'
---
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: 'sub3'
spec:
pubsubname: 'pubsub1'
topic: c
routes:
default: '/c'
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := g.daprd.GRPCClient(t, ctx).GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
if assert.Len(c, resp.GetSubscriptions(), 2) {
assert.Equal(c, "c", resp.GetSubscriptions()[0].GetTopic())
assert.Equal(c, "d", resp.GetSubscriptions()[1].GetTopic())
}
}, time.Second*5, time.Millisecond*10)
g.sub.ExpectPublishNoReceive(t, ctx, g.daprd, newReq("pubsub0", "b"))
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub0", "d"))
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub1", "c"))
require.NoError(t, os.WriteFile(filepath.Join(g.resDir2, "sub.yaml"), []byte(`
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: 'sub2'
spec:
pubsubname: 'pubsub0'
topic: 'd'
routes:
default: '/d'
---
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: 'sub3'
spec:
pubsubname: 'pubsub1'
topic: c
routes:
default: '/c'
---
apiVersion: dapr.io/v1alpha1
kind: Subscription
metadata:
name: 'sub4'
spec:
pubsubname: 'pubsub1'
topic: e
route: '/e'
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, g.daprd.GetMetaSubscriptions(t, ctx), 3)
}, time.Second*5, time.Millisecond*10)
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub0", "d"))
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub1", "c"))
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub1", "e"))
require.NoError(t, os.WriteFile(filepath.Join(g.resDir2, "sub.yaml"), []byte(`
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: 'sub2'
spec:
pubsubname: 'pubsub0'
topic: 'd'
routes:
default: '/d'
---
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: 'sub3'
spec:
pubsubname: 'pubsub1'
topic: c
routes:
default: '/c'
---
apiVersion: dapr.io/v1alpha1
kind: Subscription
metadata:
name: 'sub4'
spec:
pubsubname: 'pubsub1'
topic: f
route: '/f'
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := g.daprd.GRPCClient(t, ctx).GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
if assert.Len(c, resp.GetSubscriptions(), 3) {
assert.Equal(c, "f", resp.GetSubscriptions()[2].GetTopic())
}
}, time.Second*5, time.Millisecond*10)
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub0", "d"))
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub1", "c"))
g.sub.ExpectPublishNoReceive(t, ctx, g.daprd, newReq("pubsub1", "e"))
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub1", "f"))
require.NoError(t, os.Remove(filepath.Join(g.resDir2, "pubsub.yaml")))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, g.daprd.GetMetaRegistedComponents(t, ctx), 1)
}, time.Second*5, time.Millisecond*10)
g.sub.ExpectPublishReceive(t, ctx, g.daprd, newReq("pubsub0", "d"))
g.sub.ExpectPublishError(t, ctx, g.daprd, newReq("pubsub1", "c"))
g.sub.ExpectPublishError(t, ctx, g.daprd, newReq("pubsub1", "f"))
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/subscriptions/grpc.go
|
GO
|
mit
| 7,988 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package subscriptions
import (
"context"
"fmt"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/http/subscriber"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(http))
}
type http struct {
daprd *daprd.Daprd
sub *subscriber.Subscriber
resDir1 string
resDir2 string
}
func (h *http) Setup(t *testing.T) []framework.Option {
h.sub = subscriber.New(t,
subscriber.WithRoutes("/a", "/b", "/c", "/d", "/e", "/f"),
)
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: hotreloading
spec:
features:
- name: HotReload
enabled: true`), 0o600))
h.resDir1, h.resDir2 = t.TempDir(), t.TempDir()
for i, dir := range []string{h.resDir1, h.resDir2} {
require.NoError(t, os.WriteFile(filepath.Join(dir, "pubsub.yaml"), []byte(fmt.Sprintf(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: 'pubsub%d'
spec:
type: pubsub.in-memory
version: v1
`, i)), 0o600))
}
h.daprd = daprd.New(t,
daprd.WithAppPort(h.sub.Port()),
daprd.WithAppProtocol("http"),
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(h.resDir1, h.resDir2),
)
return []framework.Option{
framework.WithProcesses(h.sub, h.daprd),
}
}
func (h *http) Run(t *testing.T, ctx context.Context) {
h.daprd.WaitUntilRunning(t, ctx)
assert.Len(t, h.daprd.GetMetaRegistedComponents(t, ctx), 2)
assert.Empty(t, h.daprd.GetMetaSubscriptions(t, ctx))
newReq := func(daprd *daprd.Daprd, pubsubName, topic string) subscriber.PublishRequest {
return subscriber.PublishRequest{
Daprd: daprd,
PubSubName: pubsubName,
Topic: topic,
Data: `{"status": "completed"}`,
}
}
h.sub.ExpectPublishNoReceive(t, ctx, newReq(h.daprd, "pubsub0", "a"))
require.NoError(t, os.WriteFile(filepath.Join(h.resDir1, "sub.yaml"), []byte(`
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: 'sub1'
spec:
pubsubname: 'pubsub0'
topic: 'a'
routes:
default: '/a'
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, h.daprd.GetMetaSubscriptions(t, ctx), 1)
}, time.Second*5, time.Millisecond*10)
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub0", "a"))
h.sub.ExpectPublishNoReceive(t, ctx, newReq(h.daprd, "pubsub0", "b"))
require.NoError(t, os.WriteFile(filepath.Join(h.resDir2, "sub.yaml"), []byte(`
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: 'sub2'
spec:
pubsubname: 'pubsub0'
topic: 'b'
routes:
default: '/b'
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, h.daprd.GetMetaSubscriptions(t, ctx), 2)
}, time.Second*5, time.Millisecond*10)
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub0", "b"))
require.NoError(t, os.Remove(filepath.Join(h.resDir1, "sub.yaml")))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, h.daprd.GetMetaSubscriptions(t, ctx), 1)
}, time.Second*5, time.Millisecond*10)
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub0", "b"))
h.sub.ExpectPublishNoReceive(t, ctx, newReq(h.daprd, "pubsub0", "a"))
h.sub.ExpectPublishNoReceive(t, ctx, newReq(h.daprd, "pubsub1", "c"))
require.NoError(t, os.WriteFile(filepath.Join(h.resDir2, "sub.yaml"), []byte(`
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: 'sub2'
spec:
pubsubname: 'pubsub0'
topic: 'b'
routes:
default: '/b'
---
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: 'sub3'
spec:
pubsubname: 'pubsub1'
topic: c
routes:
default: '/c'
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, h.daprd.GetMetaSubscriptions(t, ctx), 2)
}, time.Second*5, time.Millisecond*10)
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub0", "b"))
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub1", "c"))
require.NoError(t, os.WriteFile(filepath.Join(h.resDir2, "sub.yaml"), []byte(`
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: 'sub2'
spec:
pubsubname: 'pubsub0'
topic: 'd'
routes:
default: '/d'
---
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: 'sub3'
spec:
pubsubname: 'pubsub1'
topic: c
routes:
default: '/c'
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := h.daprd.GRPCClient(t, ctx).GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
if assert.Len(c, resp.GetSubscriptions(), 2) {
assert.Equal(c, "c", resp.GetSubscriptions()[0].GetTopic())
assert.Equal(c, "d", resp.GetSubscriptions()[1].GetTopic())
}
}, time.Second*5, time.Millisecond*10)
h.sub.ExpectPublishNoReceive(t, ctx, newReq(h.daprd, "pubsub0", "b"))
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub0", "d"))
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub1", "c"))
require.NoError(t, os.WriteFile(filepath.Join(h.resDir2, "sub.yaml"), []byte(`
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: 'sub2'
spec:
pubsubname: 'pubsub0'
topic: 'd'
routes:
default: '/d'
---
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: 'sub3'
spec:
pubsubname: 'pubsub1'
topic: c
routes:
default: '/c'
---
apiVersion: dapr.io/v1alpha1
kind: Subscription
metadata:
name: 'sub4'
spec:
pubsubname: 'pubsub1'
topic: e
route: '/e'
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, h.daprd.GetMetaSubscriptions(t, ctx), 3)
}, time.Second*5, time.Millisecond*10)
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub0", "d"))
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub1", "c"))
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub1", "e"))
require.NoError(t, os.WriteFile(filepath.Join(h.resDir2, "sub.yaml"), []byte(`
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: 'sub2'
spec:
pubsubname: 'pubsub0'
topic: 'd'
routes:
default: '/d'
---
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: 'sub3'
spec:
pubsubname: 'pubsub1'
topic: c
routes:
default: '/c'
---
apiVersion: dapr.io/v1alpha1
kind: Subscription
metadata:
name: 'sub4'
spec:
pubsubname: 'pubsub1'
topic: f
route: '/f'
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
resp, err := h.daprd.GRPCClient(t, ctx).GetMetadata(ctx, new(rtv1.GetMetadataRequest))
require.NoError(t, err)
if assert.Len(c, resp.GetSubscriptions(), 3) {
assert.Equal(c, "f", resp.GetSubscriptions()[2].GetTopic())
}
}, time.Second*5, time.Millisecond*10)
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub0", "d"))
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub1", "c"))
h.sub.ExpectPublishNoReceive(t, ctx, newReq(h.daprd, "pubsub1", "e"))
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub1", "f"))
require.NoError(t, os.Remove(filepath.Join(h.resDir2, "pubsub.yaml")))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, h.daprd.GetMetaRegistedComponents(t, ctx), 1)
}, time.Second*5, time.Millisecond*10)
h.sub.ExpectPublishReceive(t, ctx, newReq(h.daprd, "pubsub0", "d"))
h.sub.ExpectPublishError(t, ctx, newReq(h.daprd, "pubsub1", "c"))
h.sub.ExpectPublishError(t, ctx, newReq(h.daprd, "pubsub1", "f"))
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/subscriptions/http.go
|
GO
|
mit
| 8,118 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package subscriptions
import (
"context"
"fmt"
nethttp "net/http"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/http/subscriber"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(inflight))
}
// inflight ensures in-flight messages are not lost when subscriptions
// are hot-reloaded.
type inflight struct {
daprd *daprd.Daprd
sub *subscriber.Subscriber
dir string
inPublish chan struct{}
returnPublish chan struct{}
}
func (i *inflight) Setup(t *testing.T) []framework.Option {
i.inPublish = make(chan struct{})
i.returnPublish = make(chan struct{})
i.sub = subscriber.New(t,
subscriber.WithHandlerFunc("/a", func(w nethttp.ResponseWriter, r *nethttp.Request) {
close(i.inPublish)
<-i.returnPublish
}),
)
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: hotreloading
spec:
features:
- name: HotReload
enabled: true`), 0o600))
i.dir = t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(i.dir, "pubsub.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: pubsub
spec:
type: pubsub.in-memory
version: v1
`), 0o600))
i.daprd = daprd.New(t,
daprd.WithAppPort(i.sub.Port()),
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(i.dir),
)
return []framework.Option{
framework.WithProcesses(i.sub, i.daprd),
}
}
func (i *inflight) Run(t *testing.T, ctx context.Context) {
i.daprd.WaitUntilRunning(t, ctx)
assert.Len(t, i.daprd.GetMetaRegistedComponents(t, ctx), 1)
assert.Empty(t, i.daprd.GetMetaSubscriptions(t, ctx))
require.NoError(t, os.WriteFile(filepath.Join(i.dir, "sub.yaml"), []byte(`
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: sub
spec:
pubsubname: pubsub
topic: a
routes:
default: /a
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, i.daprd.GetMetaSubscriptions(t, ctx), 1)
}, time.Second*5, time.Millisecond*10)
client := i.daprd.GRPCClient(t, ctx)
_, err := client.PublishEvent(ctx, &rtv1.PublishEventRequest{
PubsubName: "pubsub",
Topic: "a",
Data: []byte(`{"status":"completed"}`),
})
require.NoError(t, err)
select {
case <-i.inPublish:
case <-time.After(time.Second * 5):
assert.Fail(t, "did not receive publish event")
}
require.NoError(t, os.Remove(filepath.Join(i.dir, "sub.yaml")))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Empty(c, i.daprd.GetMetaSubscriptions(t, ctx))
}, time.Second*5, time.Millisecond*10)
egressMetric := fmt.Sprintf("dapr_component_pubsub_egress_count|app_id:%s|component:pubsub|namespace:|success:true|topic:a", i.daprd.AppID())
ingressMetric := fmt.Sprintf("dapr_component_pubsub_ingress_count|app_id:%s|component:pubsub|namespace:|process_status:success|status:success|topic:a", i.daprd.AppID())
metrics := i.daprd.Metrics(t, ctx)
assert.Equal(t, 1, int(metrics[egressMetric]))
assert.Equal(t, 0, int(metrics[ingressMetric]))
close(i.returnPublish)
assert.EventuallyWithT(t, func(c *assert.CollectT) {
metrics := i.daprd.Metrics(t, ctx)
assert.Equal(c, 1, int(metrics[egressMetric]))
assert.Equal(c, 1, int(metrics[ingressMetric]))
}, time.Second*5, time.Millisecond*10)
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/subscriptions/inflight.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 stream
import (
"context"
"fmt"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/grpc/subscriber"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(persist))
}
type persist struct {
daprd *daprd.Daprd
sub *subscriber.Subscriber
dir string
}
func (p *persist) Setup(t *testing.T) []framework.Option {
p.sub = subscriber.New(t)
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: hotreloading
spec:
features:
- name: HotReload
enabled: true`), 0o600))
p.dir = t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(p.dir, "pubsub.yaml"), []byte(fmt.Sprintf(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: mypub
spec:
type: pubsub.in-memory
version: v1
`)), 0o600))
p.daprd = daprd.New(t,
daprd.WithAppPort(p.sub.Port(t)),
daprd.WithAppProtocol("grpc"),
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(p.dir),
)
return []framework.Option{
framework.WithProcesses(p.sub, p.daprd),
}
}
func (p *persist) Run(t *testing.T, ctx context.Context) {
p.daprd.WaitUntilRunning(t, ctx)
assert.Len(t, p.daprd.GetMetaRegistedComponents(t, ctx), 1)
assert.Empty(t, p.daprd.GetMetaSubscriptions(t, ctx))
require.NoError(t, os.WriteFile(filepath.Join(p.dir, "sub.yaml"), []byte(`
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: sub
spec:
pubsubname: mypub
topic: a
routes:
default: /a
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, p.daprd.GetMetaSubscriptions(t, ctx), 1)
}, time.Second*5, time.Millisecond*10)
newReq := func(pubsub, topic string) *rtv1.PublishEventRequest {
return &rtv1.PublishEventRequest{PubsubName: pubsub, Topic: topic, Data: []byte(`{"status": "completed"}`)}
}
p.sub.ExpectPublishReceive(t, ctx, p.daprd, newReq("mypub", "a"))
client := p.daprd.GRPCClient(t, ctx)
stream, err := client.SubscribeTopicEventsAlpha1(ctx)
require.NoError(t, err)
require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{
SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_InitialRequest{
InitialRequest: &rtv1.SubscribeTopicEventsInitialRequestAlpha1{
PubsubName: "mypub", Topic: "b",
},
},
}))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, p.daprd.GetMetaSubscriptions(c, ctx), 2)
}, time.Second*10, time.Millisecond*10)
p.sub.ExpectPublishReceive(t, ctx, p.daprd, newReq("mypub", "a"))
_, err = client.PublishEvent(ctx, newReq("mypub", "b"))
require.NoError(t, err)
event, err := stream.Recv()
require.NoError(t, err)
assert.Equal(t, "b", event.GetTopic())
require.NoError(t, stream.Send(&rtv1.SubscribeTopicEventsRequestAlpha1{
SubscribeTopicEventsRequestType: &rtv1.SubscribeTopicEventsRequestAlpha1_EventResponse{
EventResponse: &rtv1.SubscribeTopicEventsResponseAlpha1{
Id: event.GetId(),
Status: &rtv1.TopicEventResponse{Status: rtv1.TopicEventResponse_SUCCESS},
},
},
}))
require.NoError(t, os.WriteFile(filepath.Join(p.dir, "sub.yaml"), []byte(`
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: sub
spec:
pubsubname: mypub
topic: a
routes:
default: /a
---
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: sub2
spec:
pubsubname: mypub
topic: c
routes:
default: /c
`), 0o600))
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, p.daprd.GetMetaSubscriptions(t, ctx), 2)
}, time.Second*5, time.Millisecond*10)
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/subscriptions/stream/persist.go
|
GO
|
mit
| 4,449 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package subscriptions
import (
_ "github.com/dapr/dapr/tests/integration/suite/daprd/hotreload/selfhosted/subscriptions/stream"
)
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/subscriptions/subscriptions.go
|
GO
|
mit
| 693 |
/*
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 selfhosted
import (
"context"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/exec"
"github.com/dapr/dapr/tests/integration/framework/process/logline"
"github.com/dapr/dapr/tests/integration/framework/process/placement"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(workflowbackend))
}
type workflowbackend struct {
daprdCreate *daprd.Daprd
daprdUpdate *daprd.Daprd
daprdDelete *daprd.Daprd
resDirCreate string
resDirUpdate string
resDirDelete string
loglineCreate *logline.LogLine
loglineUpdate *logline.LogLine
loglineDelete *logline.LogLine
}
func (w *workflowbackend) Setup(t *testing.T) []framework.Option {
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte(`
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: hotreloading
spec:
features:
- name: HotReload
enabled: true`), 0o600))
w.loglineCreate = logline.New(t, logline.WithStdoutLineContains(
"Aborting to hot-reload a workflowbackend component which is not supported: wfbackend (workflowbackend.actors/v1)",
))
w.loglineUpdate = logline.New(t, logline.WithStdoutLineContains(
"Aborting to hot-reload a workflowbackend component which is not supported: wfbackend (pubsub.in-memory/v1)",
))
w.loglineDelete = logline.New(t, logline.WithStdoutLineContains(
"Aborting to hot-reload a workflowbackend component which is not supported: wfbackend (workflowbackend.actors/v1)",
))
w.resDirCreate = t.TempDir()
w.resDirUpdate = t.TempDir()
w.resDirDelete = t.TempDir()
place := placement.New(t)
w.daprdCreate = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(w.resDirCreate),
daprd.WithPlacementAddresses(place.Address()),
daprd.WithInMemoryActorStateStore("mystore"),
daprd.WithExecOptions(
exec.WithStdout(w.loglineCreate.Stdout()),
),
)
w.daprdUpdate = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(w.resDirUpdate),
daprd.WithPlacementAddresses(place.Address()),
daprd.WithInMemoryActorStateStore("mystore"),
daprd.WithExecOptions(
exec.WithStdout(w.loglineUpdate.Stdout()),
),
)
require.NoError(t, os.WriteFile(filepath.Join(w.resDirUpdate, "wf.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: wfbackend
spec:
type: workflowbackend.actors
version: v1
`), 0o600))
w.daprdDelete = daprd.New(t,
daprd.WithConfigs(configFile),
daprd.WithResourcesDir(w.resDirDelete),
daprd.WithPlacementAddresses(place.Address()),
daprd.WithInMemoryActorStateStore("mystore"),
daprd.WithExecOptions(
exec.WithStdout(w.loglineDelete.Stdout()),
),
)
require.NoError(t, os.WriteFile(filepath.Join(w.resDirDelete, "wf.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: wfbackend
spec:
type: workflowbackend.actors
version: v1
`), 0o600))
return []framework.Option{
framework.WithProcesses(place,
w.loglineCreate, w.loglineUpdate, w.loglineDelete,
w.daprdCreate, w.daprdUpdate, w.daprdDelete,
),
}
}
func (w *workflowbackend) Run(t *testing.T, ctx context.Context) {
w.daprdCreate.WaitUntilRunning(t, ctx)
w.daprdUpdate.WaitUntilRunning(t, ctx)
w.daprdDelete.WaitUntilRunning(t, ctx)
httpClient := util.HTTPClient(t)
comps := util.GetMetaComponents(t, ctx, httpClient, w.daprdCreate.HTTPPort())
require.ElementsMatch(t, []*rtv1.RegisteredComponents{
{
Name: "mystore", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, comps)
require.NoError(t, os.WriteFile(filepath.Join(w.resDirCreate, "wf.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: wfbackend
spec:
type: workflowbackend.actors
version: v1
`), 0o600))
w.loglineCreate.EventuallyFoundAll(t)
comps = util.GetMetaComponents(t, ctx, httpClient, w.daprdUpdate.HTTPPort())
require.ElementsMatch(t, []*rtv1.RegisteredComponents{
{Name: "wfbackend", Type: "workflowbackend.actors", Version: "v1"},
{
Name: "mystore", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, comps)
require.NoError(t, os.WriteFile(filepath.Join(w.resDirUpdate, "wf.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: wfbackend
spec:
type: pubsub.in-memory
version: v1
`), 0o600))
w.loglineUpdate.EventuallyFoundAll(t)
comps = util.GetMetaComponents(t, ctx, httpClient, w.daprdDelete.HTTPPort())
require.ElementsMatch(t, []*rtv1.RegisteredComponents{
{Name: "wfbackend", Type: "workflowbackend.actors", Version: "v1"},
{
Name: "mystore", Type: "state.in-memory", Version: "v1",
Capabilities: []string{"ETAG", "TRANSACTIONAL", "TTL", "DELETE_WITH_PREFIX", "ACTOR"},
},
}, comps)
require.NoError(t, os.Remove(filepath.Join(w.resDirDelete, "wf.yaml")))
w.loglineDelete.EventuallyFoundAll(t)
}
|
mikeee/dapr
|
tests/integration/suite/daprd/hotreload/selfhosted/workflowbackend.go
|
GO
|
mit
| 5,842 |
/*
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 httpserver
import (
"context"
"crypto/tls"
"fmt"
"io"
"net"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/net/http2"
"github.com/dapr/dapr/tests/integration/framework"
procdaprd "github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(httpServer))
}
// httpServer tests Dapr's HTTP server features.
type httpServer struct {
proc *procdaprd.Daprd
}
func (h *httpServer) Setup(t *testing.T) []framework.Option {
h.proc = procdaprd.New(t)
return []framework.Option{
framework.WithProcesses(h.proc),
}
}
func (h *httpServer) Run(t *testing.T, ctx context.Context) {
h.proc.WaitUntilRunning(t, ctx)
h1Client := util.HTTPClient(t)
h2cClient := &http.Client{
Transport: &http2.Transport{
// Allow http2.Transport to use protocol "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)
},
},
}
t.Cleanup(h2cClient.CloseIdleConnections)
t.Run("test with HTTP1", func(t *testing.T) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://localhost:%d/v1.0/healthz", h.proc.HTTPPort()), nil)
require.NoError(t, err)
// Body is closed below but the linter isn't seeing that
//nolint:bodyclose
res, err := h1Client.Do(req)
require.NoError(t, err)
defer closeBody(res.Body)
require.Equal(t, http.StatusNoContent, res.StatusCode)
assert.Equal(t, 1, res.ProtoMajor)
})
t.Run("test with HTTP2 Cleartext with prior knowledge", func(t *testing.T) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://localhost:%d/v1.0/healthz", h.proc.HTTPPort()), nil)
require.NoError(t, err)
// Body is closed below but the linter isn't seeing that
//nolint:bodyclose
res, err := h2cClient.Do(req)
require.NoError(t, err)
defer closeBody(res.Body)
require.Equal(t, http.StatusNoContent, res.StatusCode)
assert.Equal(t, 2, res.ProtoMajor)
})
t.Run("server allows upgrading from HTTP1 to HTTP2 Cleartext", func(t *testing.T) {
// The Go HTTP client doesn't handle upgrades from HTTP/1 to HTTP/2
// The best we can do for now is to verify that the server responds with a 101 response when we signal that we are able to upgrade
// See: https://github.com/golang/go/issues/46249
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://localhost:%d/v1.0/healthz", h.proc.HTTPPort()), nil)
require.NoError(t, err)
req.Header.Set("Connection", "Upgrade, HTTP2-Settings")
req.Header.Set("Upgrade", "h2c")
req.Header.Set("HTTP2-Settings", "AAMAAABkAARAAAAAAAIAAAAA")
// Body is closed below but the linter isn't seeing that
res, err := h1Client.Do(req)
require.NoError(t, err)
t.Cleanup(func() {
require.NoError(t, res.Body.Close())
})
// This response should have arrived over HTTP/1
assert.Equal(t, 1, res.ProtoMajor)
assert.Equal(t, http.StatusSwitchingProtocols, res.StatusCode)
assert.NotEmpty(t, res.Header)
assert.Equal(t, "Upgrade", res.Header.Get("Connection"))
assert.Equal(t, "h2c", res.Header.Get("Upgrade"))
})
}
// Drain body before closing
func closeBody(body io.ReadCloser) error {
_, err := io.Copy(io.Discard, body)
if err != nil {
return err
}
return body.Close()
}
|
mikeee/dapr
|
tests/integration/suite/daprd/httpserver/httpserver.go
|
GO
|
mit
| 4,070 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package metadata
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/tests/integration/framework"
procdaprd "github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(metadata))
}
// metadata tests Dapr's response to metadata API requests.
type metadata struct {
proc *procdaprd.Daprd
}
func (m *metadata) Setup(t *testing.T) []framework.Option {
subComponentAndConfiguration := `
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: pubsub
spec:
type: pubsub.in-memory
version: v1
---
apiVersion: dapr.io/v1alpha1
kind: Subscription
metadata:
name: sub
spec:
topic: B
route: /B
pubsubname: pubsub
`
m.proc = procdaprd.New(t, procdaprd.WithResourceFiles(subComponentAndConfiguration))
return []framework.Option{
framework.WithProcesses(m.proc),
}
}
func (m *metadata) Run(t *testing.T, parentCtx context.Context) {
m.proc.WaitUntilRunning(t, parentCtx)
httpClient := util.HTTPClient(t)
t.Run("test HTTP", func(t *testing.T) {
tests := map[string]string{
"public endpoint": fmt.Sprintf("http://localhost:%d/v1.0/metadata", m.proc.PublicPort()),
"API endpoint": fmt.Sprintf("http://localhost:%d/v1.0/metadata", m.proc.HTTPPort()),
}
for testName, reqURL := range tests {
t.Run(testName, func(t *testing.T) {
ctx, cancel := context.WithTimeout(parentCtx, time.Second*5)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil)
require.NoError(t, err)
resp, err := httpClient.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
validateResponse(t, m.proc.AppID(), m.proc.AppPort(), resp.Body)
})
}
})
}
// validateResponse asserts that the response body is valid JSON
// and contains the expected fields.
func validateResponse(t *testing.T, appID string, appPort int, body io.Reader) {
bodyMap := map[string]interface{}{}
err := json.NewDecoder(body).Decode(&bodyMap)
require.NoError(t, err)
require.Equal(t, appID, bodyMap["id"])
require.Equal(t, "edge", bodyMap["runtimeVersion"])
extended, ok := bodyMap["extended"].(map[string]interface{})
require.True(t, ok)
require.Equal(t, "edge", extended["daprRuntimeVersion"])
appConnectionProperties, ok := bodyMap["appConnectionProperties"].(map[string]interface{})
require.True(t, ok)
port, ok := appConnectionProperties["port"].(float64)
require.True(t, ok)
require.Equal(t, appPort, int(port))
require.Equal(t, "http", appConnectionProperties["protocol"])
require.Equal(t, "127.0.0.1", appConnectionProperties["channelAddress"])
// validate that the metadata contains correct format of subscription.
// The http response struct is private, so we use assert here.
subscriptions, ok := bodyMap["subscriptions"].([]interface{})
require.True(t, ok)
subscription, ok := subscriptions[0].(map[string]interface{})
require.True(t, ok)
rules, ok := subscription["rules"].([]interface{})
require.True(t, ok)
rule, ok := rules[0].(map[string]interface{})
require.True(t, ok)
require.Empty(t, rule["match"])
require.Equal(t, "/B", rule["path"])
}
|
mikeee/dapr
|
tests/integration/suite/daprd/metadata/metadata.go
|
GO
|
mit
| 3,847 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package grpc
import (
"context"
"fmt"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
commonv1 "github.com/dapr/dapr/pkg/proto/common/v1"
rtv1 "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
"github.com/dapr/dapr/tests/integration/framework/process/http/app"
"github.com/dapr/dapr/tests/integration/suite"
)
func init() {
suite.Register(new(basic))
}
// basic tests daprd metrics for the gRPC server
type basic struct {
daprd *daprd.Daprd
}
func (b *basic) Setup(t *testing.T) []framework.Option {
app := app.New(t,
app.WithHandlerFunc("/hi", func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, "OK")
}),
)
b.daprd = daprd.New(t,
daprd.WithAppPort(app.Port()),
daprd.WithAppProtocol("http"),
daprd.WithAppID("myapp"),
daprd.WithInMemoryStateStore("mystore"),
)
return []framework.Option{
framework.WithProcesses(app, b.daprd),
}
}
func (b *basic) Run(t *testing.T, ctx context.Context) {
b.daprd.WaitUntilRunning(t, ctx)
client := b.daprd.GRPCClient(t, ctx)
t.Run("service invocation", func(t *testing.T) {
// Invoke
_, err := client.InvokeService(ctx, &rtv1.InvokeServiceRequest{
Id: "myapp",
Message: &commonv1.InvokeRequest{
Method: "hi",
HttpExtension: &commonv1.HTTPExtension{
Verb: commonv1.HTTPExtension_GET,
},
},
})
require.NoError(t, err)
// Verify metrics
metrics := b.daprd.Metrics(t, ctx)
assert.Equal(t, 1, int(metrics["dapr_grpc_io_server_completed_rpcs|app_id:myapp|grpc_server_method:/dapr.proto.runtime.v1.Dapr/InvokeService|grpc_server_status:OK"]))
})
t.Run("state stores", func(t *testing.T) {
// Write state
_, err := client.SaveState(ctx, &rtv1.SaveStateRequest{
StoreName: "mystore",
States: []*commonv1.StateItem{
{Key: "myvalue", Value: []byte(`"hello world"`)},
},
})
require.NoError(t, err)
// Get state
_, err = client.GetState(ctx, &rtv1.GetStateRequest{
StoreName: "mystore",
Key: "myvalue",
})
require.NoError(t, err)
// Verify metrics
metrics := b.daprd.Metrics(t, ctx)
assert.Equal(t, 1, int(metrics["dapr_grpc_io_server_completed_rpcs|app_id:myapp|grpc_server_method:/dapr.proto.runtime.v1.Dapr/SaveState|grpc_server_status:OK"]))
assert.Equal(t, 1, int(metrics["dapr_grpc_io_server_completed_rpcs|app_id:myapp|grpc_server_method:/dapr.proto.runtime.v1.Dapr/GetState|grpc_server_status:OK"]))
})
}
|
mikeee/dapr
|
tests/integration/suite/daprd/metrics/grpc/basic.go
|
GO
|
mit
| 3,110 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.