Enabled linter for test files as well (#696)

* Enabled linter for test files as well

* Fixed unittest failure

* Fixed unit test
This commit is contained in:
sayboras 2019-10-29 09:50:13 +11:00 committed by Young Bu Park
parent eaa1e29f8e
commit b49e75e5e6
12 changed files with 374 additions and 365 deletions

View File

@ -10,7 +10,7 @@ run:
issues-exit-code: 1
# include test files or not, default is true
tests: false
tests: true
# list of build tags, all linters use it. Default is empty list.
#build-tags:
@ -116,7 +116,7 @@ linters-settings:
# minimal length of string constant, 3 by default
min-len: 3
# minimal occurrences count to trigger, 3 by default
min-occurrences: 3
min-occurrences: 5
depguard:
list-type: blacklist
include-go-root: false

View File

@ -24,7 +24,8 @@ import (
)
const (
TestDaprID = "fakeDaprID"
TestDaprID = "fakeDaprID"
TestKeyName = "key0"
)
type fakeStateStore struct {
@ -396,11 +397,10 @@ func TestReminderFiresOnceWitnEmptyPeriod(t *testing.T) {
func TestConstructActorStateKey(t *testing.T) {
testActorsRuntime := newTestActorsRuntime()
actorType, actorID := getTestActorTypeAndID()
keyName := "key0"
expected := fmt.Sprintf("%s-%s-%s-%s", TestDaprID, actorType, actorID, keyName)
expected := fmt.Sprintf("%s-%s-%s-%s", TestDaprID, actorType, actorID, TestKeyName)
// act
stateKey := testActorsRuntime.constructActorStateKey(actorType, actorID, keyName)
stateKey := testActorsRuntime.constructActorStateKey(actorType, actorID, TestKeyName)
// assert
assert.Equal(t, expected, stateKey)
@ -409,7 +409,6 @@ func TestConstructActorStateKey(t *testing.T) {
func TestSaveState(t *testing.T) {
testActorRuntime := newTestActorsRuntime()
actorType, actorID := getTestActorTypeAndID()
keyName := "key0"
fakeData := strconv.Quote("fakeData")
var val interface{}
@ -422,7 +421,7 @@ func TestSaveState(t *testing.T) {
err := testActorRuntime.SaveState(&SaveStateRequest{
ActorID: actorID,
ActorType: actorType,
Key: keyName,
Key: TestKeyName,
Value: val,
})
assert.NoError(t, err)
@ -431,7 +430,7 @@ func TestSaveState(t *testing.T) {
response, err := testActorRuntime.GetState(&GetStateRequest{
ActorID: actorID,
ActorType: actorType,
Key: keyName,
Key: TestKeyName,
})
assert.NoError(t, err)
@ -441,7 +440,6 @@ func TestSaveState(t *testing.T) {
func TestGetState(t *testing.T) {
testActorRuntime := newTestActorsRuntime()
actorType, actorID := getTestActorTypeAndID()
keyName := "key0"
fakeData := strconv.Quote("fakeData")
var val interface{}
@ -453,7 +451,7 @@ func TestGetState(t *testing.T) {
testActorRuntime.SaveState(&SaveStateRequest{
ActorID: actorID,
ActorType: actorType,
Key: keyName,
Key: TestKeyName,
Value: val,
})
@ -461,7 +459,7 @@ func TestGetState(t *testing.T) {
response, err := testActorRuntime.GetState(&GetStateRequest{
ActorID: actorID,
ActorType: actorType,
Key: keyName,
Key: TestKeyName,
})
// assert
@ -472,7 +470,6 @@ func TestGetState(t *testing.T) {
func TestDeleteState(t *testing.T) {
testActorRuntime := newTestActorsRuntime()
actorType, actorID := getTestActorTypeAndID()
keyName := "key0"
fakeData := strconv.Quote("fakeData")
var val interface{}
@ -485,7 +482,7 @@ func TestDeleteState(t *testing.T) {
testActorRuntime.SaveState(&SaveStateRequest{
ActorID: actorID,
ActorType: actorType,
Key: keyName,
Key: TestKeyName,
Value: val,
})
@ -493,7 +490,7 @@ func TestDeleteState(t *testing.T) {
response, err := testActorRuntime.GetState(&GetStateRequest{
ActorID: actorID,
ActorType: actorType,
Key: keyName,
Key: TestKeyName,
})
assert.NoError(t, err)
@ -503,7 +500,7 @@ func TestDeleteState(t *testing.T) {
err = testActorRuntime.DeleteState(&DeleteStateRequest{
ActorID: actorID,
ActorType: actorType,
Key: keyName,
Key: TestKeyName,
})
assert.NoError(t, err)
@ -511,7 +508,7 @@ func TestDeleteState(t *testing.T) {
response, err = testActorRuntime.GetState(&GetStateRequest{
ActorID: actorID,
ActorType: actorType,
Key: keyName,
Key: TestKeyName,
})
assert.NoError(t, err)
@ -530,7 +527,7 @@ func TestTransactionalState(t *testing.T) {
ActorType: actorType,
ActorID: actorID,
Operations: []TransactionalOperation{
TransactionalOperation{
{
Operation: Upsert,
Request: TransactionalUpsert{
Key: "key1",
@ -553,14 +550,14 @@ func TestTransactionalState(t *testing.T) {
ActorType: actorType,
ActorID: actorID,
Operations: []TransactionalOperation{
TransactionalOperation{
{
Operation: Upsert,
Request: TransactionalUpsert{
Key: "key1",
Value: "fakeData",
},
},
TransactionalOperation{
{
Operation: Delete,
Request: TransactionalDelete{
Key: "key1",
@ -582,7 +579,7 @@ func TestTransactionalState(t *testing.T) {
ActorType: actorType,
ActorID: actorID,
Operations: []TransactionalOperation{
TransactionalOperation{
{
Operation: Upsert,
Request: "wrongBody",
},
@ -602,7 +599,7 @@ func TestTransactionalState(t *testing.T) {
ActorType: actorType,
ActorID: actorID,
Operations: []TransactionalOperation{
TransactionalOperation{
{
Operation: "Wrong",
Request: "wrongBody",
},

View File

@ -7,6 +7,8 @@ package grpc
import (
"context"
"fmt"
"io"
"net"
"testing"
@ -42,7 +44,7 @@ func (m *mockServer) OnTopicEvent(ctx context.Context, in *pb.CloudEventEnvelope
}
func TestInvokeMethod(t *testing.T) {
lis, err := net.Listen("tcp", ":9998")
lis, err := net.Listen("tcp", "127.0.0.1:9998")
assert.NoError(t, err)
grpcServer := grpc.NewServer()
@ -54,7 +56,7 @@ func TestInvokeMethod(t *testing.T) {
var opts []grpc.DialOption
opts = append(opts, grpc.WithInsecure())
conn, err := grpc.Dial("localhost:9998", opts...)
defer conn.Close()
defer close(t, conn)
assert.NoError(t, err)
c := Channel{baseAddress: "localhost:9998", client: conn}
@ -65,6 +67,13 @@ func TestInvokeMethod(t *testing.T) {
grpcServer.Stop()
assert.NoError(t, err)
assert.True(t, "param1=val1&param2=val2&" == string(response.Data) ||
"param2=val2&param1=val1&" == string(response.Data))
assert.True(t, string(response.Data) == "param1=val1&param2=val2&" ||
string(response.Data) == "param2=val2&param1=val1&")
}
func close(t *testing.T, c io.Closer) {
err := c.Close()
if err != nil {
assert.Fail(t, fmt.Sprintf("unable to close %s", err))
}
}

View File

@ -1,26 +1,26 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// ------------------------------------------------------------
package exporters
import (
"github.com/dapr/components-contrib/exporters"
"github.com/dapr/components-contrib/exporters/native"
"github.com/dapr/components-contrib/exporters/stringexporter"
"github.com/dapr/components-contrib/exporters/zipkin"
)
// Load message buses
func Load() {
RegisterExporter("zipkin", func() exporters.Exporter {
return zipkin.NewZipkinExporter()
})
RegisterExporter("string", func() exporters.Exporter {
return stringexporter.NewStringExporter()
})
RegisterExporter("native", func() exporters.Exporter {
return native.NewNativeExporter()
})
}
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// ------------------------------------------------------------
package exporters
import (
"github.com/dapr/components-contrib/exporters"
"github.com/dapr/components-contrib/exporters/native"
"github.com/dapr/components-contrib/exporters/stringexporter"
"github.com/dapr/components-contrib/exporters/zipkin"
)
// Load message buses
func Load() {
RegisterExporter("zipkin", func() exporters.Exporter {
return zipkin.NewZipkinExporter()
})
RegisterExporter("string", func() exporters.Exporter {
return stringexporter.NewStringExporter()
})
RegisterExporter("native", func() exporters.Exporter {
return native.NewNativeExporter()
})
}

View File

@ -1,30 +1,29 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// ------------------------------------------------------------
package exporters
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestLoad(t *testing.T) {
testRegistry := NewRegistry()
Load()
t.Run("zipkin is registered", func(t *testing.T) {
p, e := testRegistry.CreateExporter("exporters.zipkin")
assert.NotNil(t, p)
assert.Nil(t, e)
})
t.Run("string is registered", func(t *testing.T) {
p, e := testRegistry.CreateExporter("exporters.string")
assert.NotNil(t, p)
assert.Nil(t, e)
})
}
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// ------------------------------------------------------------
package exporters
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestLoad(t *testing.T) {
testRegistry := NewRegistry()
Load()
t.Run("zipkin is registered", func(t *testing.T) {
p, e := testRegistry.CreateExporter("exporters.zipkin")
assert.NotNil(t, p)
assert.Nil(t, e)
})
t.Run("string is registered", func(t *testing.T) {
p, e := testRegistry.CreateExporter("exporters.string")
assert.NotNil(t, p)
assert.Nil(t, e)
})
}

View File

@ -1,51 +1,51 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// ------------------------------------------------------------
package exporters
import (
"fmt"
"sync"
"github.com/dapr/components-contrib/exporters"
)
// Registry is the interface for callers to get registered exporter components
type Registry interface {
CreateExporter(name string) (exporters.Exporter, error)
}
type exporterRegistry struct {
exporters map[string]func() exporters.Exporter
}
var instance *exporterRegistry
var once sync.Once
// NewRegistry returns a new exporter registry
func NewRegistry() Registry {
once.Do(func() {
instance = &exporterRegistry{
exporters: map[string]func() exporters.Exporter{},
}
})
return instance
}
// RegisterExporter registers a new exporter
func RegisterExporter(name string, factoryMethod func() exporters.Exporter) {
instance.exporters[createFullName(name)] = factoryMethod
}
func createFullName(name string) string {
return fmt.Sprintf("exporters.%s", name)
}
func (p *exporterRegistry) CreateExporter(name string) (exporters.Exporter, error) {
if method, ok := p.exporters[name]; ok {
return method(), nil
}
return nil, fmt.Errorf("couldn't find exporter %s", name)
}
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// ------------------------------------------------------------
package exporters
import (
"fmt"
"sync"
"github.com/dapr/components-contrib/exporters"
)
// Registry is the interface for callers to get registered exporter components
type Registry interface {
CreateExporter(name string) (exporters.Exporter, error)
}
type exporterRegistry struct {
exporters map[string]func() exporters.Exporter
}
var instance *exporterRegistry
var once sync.Once
// NewRegistry returns a new exporter registry
func NewRegistry() Registry {
once.Do(func() {
instance = &exporterRegistry{
exporters: map[string]func() exporters.Exporter{},
}
})
return instance
}
// RegisterExporter registers a new exporter
func RegisterExporter(name string, factoryMethod func() exporters.Exporter) {
instance.exporters[createFullName(name)] = factoryMethod
}
func createFullName(name string) string {
return fmt.Sprintf("exporters.%s", name)
}
func (p *exporterRegistry) CreateExporter(name string) (exporters.Exporter, error) {
if method, ok := p.exporters[name]; ok {
return method(), nil
}
return nil, fmt.Errorf("couldn't find exporter %s", name)
}

View File

@ -1,63 +1,63 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// ------------------------------------------------------------
package exporters
import (
"fmt"
"testing"
"github.com/dapr/components-contrib/exporters"
daprt "github.com/dapr/dapr/pkg/testing"
"github.com/stretchr/testify/assert"
)
func TestCreateFullName(t *testing.T) {
t.Run("create zipkin exporter key name", func(t *testing.T) {
assert.Equal(t, "exporters.zipkin", createFullName("zipkin"))
})
t.Run("create string key name", func(t *testing.T) {
assert.Equal(t, "exporters.string", createFullName("string"))
})
}
func TestNewExporterRegistry(t *testing.T) {
registry0 := NewRegistry()
registry1 := NewRegistry()
assert.Equal(t, registry0, registry1, "should be the same object")
}
func TestCreateExporter(t *testing.T) {
testRegistry := NewRegistry()
t.Run("exporter is registered", func(t *testing.T) {
const ExporterName = "mockExporter"
// Initiate mock object
mockExporter := new(daprt.MockExporter)
// act
RegisterExporter(ExporterName, func() exporters.Exporter {
return mockExporter
})
p, e := testRegistry.CreateExporter(createFullName(ExporterName))
// assert
assert.Equal(t, mockExporter, p)
assert.Nil(t, e)
})
t.Run("exporter is not registered", func(t *testing.T) {
const ExporterName = "fakeExporter"
// act
p, e := testRegistry.CreateExporter(createFullName(ExporterName))
// assert
assert.Nil(t, p)
assert.Equal(t, fmt.Errorf("couldn't find exporter %s", createFullName(ExporterName)), e)
})
}
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// ------------------------------------------------------------
package exporters
import (
"fmt"
"testing"
"github.com/dapr/components-contrib/exporters"
daprt "github.com/dapr/dapr/pkg/testing"
"github.com/stretchr/testify/assert"
)
func TestCreateFullName(t *testing.T) {
t.Run("create zipkin exporter key name", func(t *testing.T) {
assert.Equal(t, "exporters.zipkin", createFullName("zipkin"))
})
t.Run("create string key name", func(t *testing.T) {
assert.Equal(t, "exporters.string", createFullName("string"))
})
}
func TestNewExporterRegistry(t *testing.T) {
registry0 := NewRegistry()
registry1 := NewRegistry()
assert.Equal(t, registry0, registry1, "should be the same object")
}
func TestCreateExporter(t *testing.T) {
testRegistry := NewRegistry()
t.Run("exporter is registered", func(t *testing.T) {
const ExporterName = "mockExporter"
// Initiate mock object
mockExporter := new(daprt.MockExporter)
// act
RegisterExporter(ExporterName, func() exporters.Exporter {
return mockExporter
})
p, e := testRegistry.CreateExporter(createFullName(ExporterName))
// assert
assert.Equal(t, mockExporter, p)
assert.Nil(t, e)
})
t.Run("exporter is not registered", func(t *testing.T) {
const ExporterName = "fakeExporter"
// act
p, e := testRegistry.CreateExporter(createFullName(ExporterName))
// assert
assert.Nil(t, p)
assert.Equal(t, fmt.Errorf("couldn't find exporter %s", createFullName(ExporterName)), e)
})
}

View File

@ -8,6 +8,7 @@ package grpc
import (
"context"
"fmt"
"io"
"net"
"testing"
"time"
@ -101,7 +102,7 @@ func TestCallActorWithTracing(t *testing.T) {
var opts []grpc_go.DialOption
opts = append(opts, grpc_go.WithInsecure())
conn, err := grpc_go.Dial(fmt.Sprintf("localhost:%d", port), opts...)
defer conn.Close()
defer close(t, conn)
assert.NoError(t, err)
client := daprinternal_pb.NewDaprInternalClient(conn)
@ -148,7 +149,7 @@ func TestCallRemoteAppWithTracing(t *testing.T) {
var opts []grpc_go.DialOption
opts = append(opts, grpc_go.WithInsecure())
conn, err := grpc_go.Dial(fmt.Sprintf("localhost:%d", port), opts...)
defer conn.Close()
defer close(t, conn)
assert.NoError(t, err)
client := daprinternal_pb.NewDaprInternalClient(conn)
@ -178,13 +179,13 @@ func TestSaveState(t *testing.T) {
var opts []grpc_go.DialOption
opts = append(opts, grpc_go.WithInsecure())
conn, err := grpc_go.Dial(fmt.Sprintf("localhost:%d", port), opts...)
defer conn.Close()
defer close(t, conn)
assert.NoError(t, err)
client := dapr_pb.NewDaprClient(conn)
request := &dapr_pb.SaveStateEnvelope{
Requests: []*dapr_pb.StateRequest{
&dapr_pb.StateRequest{
{
Key: "1",
Value: &any.Any{Value: []byte("2")},
},
@ -212,7 +213,7 @@ func TestGetState(t *testing.T) {
var opts []grpc_go.DialOption
opts = append(opts, grpc_go.WithInsecure())
conn, err := grpc_go.Dial(fmt.Sprintf("localhost:%d", port), opts...)
defer conn.Close()
defer close(t, conn)
assert.NoError(t, err)
client := dapr_pb.NewDaprClient(conn)
@ -237,7 +238,7 @@ func TestDeleteState(t *testing.T) {
var opts []grpc_go.DialOption
opts = append(opts, grpc_go.WithInsecure())
conn, err := grpc_go.Dial(fmt.Sprintf("localhost:%d", port), opts...)
defer conn.Close()
defer close(t, conn)
assert.NoError(t, err)
client := dapr_pb.NewDaprClient(conn)
@ -262,7 +263,7 @@ func TestPublishTopic(t *testing.T) {
var opts []grpc_go.DialOption
opts = append(opts, grpc_go.WithInsecure())
conn, err := grpc_go.Dial(fmt.Sprintf("localhost:%d", port), opts...)
defer conn.Close()
defer close(t, conn)
assert.NoError(t, err)
client := dapr_pb.NewDaprClient(conn)
@ -287,7 +288,7 @@ func TestInvokeBinding(t *testing.T) {
var opts []grpc_go.DialOption
opts = append(opts, grpc_go.WithInsecure())
conn, err := grpc_go.Dial(fmt.Sprintf("localhost:%d", port), opts...)
defer conn.Close()
defer close(t, conn)
assert.NoError(t, err)
client := dapr_pb.NewDaprClient(conn)
@ -295,3 +296,10 @@ func TestInvokeBinding(t *testing.T) {
server.Stop()
assert.Nil(t, err)
}
func close(t *testing.T, c io.Closer) {
err := c.Close()
if err != nil {
assert.Fail(t, fmt.Sprintf("unable to close %s", err))
}
}

View File

@ -3,6 +3,7 @@
// Licensed under the MIT License.
// ------------------------------------------------------------
//nolint:goconst
package http
import (
@ -40,8 +41,7 @@ var retryCounter = 0
func TestSetHeaders(t *testing.T) {
testAPI := &api{}
c := &routing.Context{}
request := fasthttp.Request{}
c.RequestCtx = &fasthttp.RequestCtx{Request: request}
c.RequestCtx = &fasthttp.RequestCtx{Request: fasthttp.Request{}}
c.Request.Header.Set("H1", "v1")
c.Request.Header.Set("H2", "v2")
m := map[string]string{}
@ -320,7 +320,6 @@ func TestV1DirectMessagingEndpointsWithTracer(t *testing.T) {
mockDirectMessaging.AssertNumberOfCalls(t, "Invoke", 1)
assert.Equal(t, 200, resp.StatusCode)
assert.Equal(t, "0", buffer, "failed to generate proper traces with invoke")
})
fakeServer.Shutdown()
@ -428,12 +427,12 @@ func TestV1ActorEndpoints(t *testing.T) {
fakeBodyArray := []byte{0x01, 0x02, 0x03, 0x06, 0x10}
fakeBodyObject := map[string]interface{}{
fakeResp := map[string]interface{}{
"data": "fakeData",
"data2": fakeBodyArray,
}
serializedByteArray, _ := json.Marshal(fakeBodyObject)
serializedByteArray, _ := json.Marshal(fakeResp)
encodedLen := base64.StdEncoding.EncodedLen(len(fakeBodyArray))
base64Encoded := make([]byte, encodedLen)
@ -554,14 +553,14 @@ func TestV1ActorEndpoints(t *testing.T) {
apiPath := "v1.0/actors/fakeActorType/fakeActorID/state"
testTransactionalOperations := []actors.TransactionalOperation{
actors.TransactionalOperation{
{
Operation: actors.Upsert,
Request: map[string]interface{}{
"key": "fakeKey1",
"value": fakeBodyObject,
},
},
actors.TransactionalOperation{
{
Operation: actors.Delete,
Request: map[string]interface{}{
"key": "fakeKey1",
@ -722,12 +721,12 @@ func TestV1ActorEndpointsWithTracer(t *testing.T) {
fakeBodyArray := []byte{0x01, 0x02, 0x03, 0x06, 0x10}
fakeBodyObject := map[string]interface{}{
fakeObj := map[string]interface{}{
"data": "fakeData",
"data2": fakeBodyArray,
}
serializedByteArray, _ := json.Marshal(fakeBodyObject)
serializedByteArray, _ := json.Marshal(fakeObj)
encodedLen := base64.StdEncoding.EncodedLen(len(fakeBodyArray))
base64Encoded := make([]byte, encodedLen)
@ -857,14 +856,14 @@ func TestV1ActorEndpointsWithTracer(t *testing.T) {
apiPath := "v1.0/actors/fakeActorType/fakeActorID/state"
testTransactionalOperations := []actors.TransactionalOperation{
actors.TransactionalOperation{
{
Operation: actors.Upsert,
Request: map[string]interface{}{
"key": "fakeKey1",
"value": fakeBodyObject,
},
},
actors.TransactionalOperation{
{
Operation: actors.Delete,
Request: map[string]interface{}{
"key": "fakeKey1",
@ -993,6 +992,7 @@ func (f *fakeHTTPServer) DoRequest(method, path string, body []byte, params map[
}
bodyBytes, _ := ioutil.ReadAll(res.Body)
defer res.Body.Close()
response := fakeHTTPResponse{
StatusCode: res.StatusCode,
ContentType: res.Header.Get("Content-Type"),
@ -1037,7 +1037,7 @@ func TestV1StateEndpoints(t *testing.T) {
})
t.Run("Update state - No ETag", func(t *testing.T) {
apiPath := "v1.0/state"
request := []state.SetRequest{state.SetRequest{
request := []state.SetRequest{{
Key: "good-key",
ETag: "",
}}
@ -1049,7 +1049,7 @@ func TestV1StateEndpoints(t *testing.T) {
})
t.Run("Update state - Matching ETag", func(t *testing.T) {
apiPath := "v1.0/state"
request := []state.SetRequest{state.SetRequest{
request := []state.SetRequest{{
Key: "good-key",
ETag: etag,
}}
@ -1061,7 +1061,7 @@ func TestV1StateEndpoints(t *testing.T) {
})
t.Run("Update state - Wrong ETag", func(t *testing.T) {
apiPath := "v1.0/state"
request := []state.SetRequest{state.SetRequest{
request := []state.SetRequest{{
Key: "good-key",
ETag: "BAD ETAG",
}}
@ -1107,7 +1107,7 @@ func TestV1StateEndpoints(t *testing.T) {
t.Run("Set state - With Retries", func(t *testing.T) {
apiPath := "v1.0/state"
retryCounter = 0
request := []state.SetRequest{state.SetRequest{
request := []state.SetRequest{{
Key: "failed-key",
ETag: "BAD ETAG",
Options: state.SetStateOption{

View File

@ -1,113 +1,109 @@
package handlers
import (
"testing"
"github.com/stretchr/testify/assert"
testclient "github.com/dapr/dapr/pkg/client/clientset/versioned"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func TestGetDaprID(t *testing.T) {
t.Run("WithValidId", func(t *testing.T) {
// Arrange
expected := "test_id"
deployment := getDeployment(expected, "true")
testDaprHandler := NewDaprHandler(testclient.New(nil))
// Act
got := testDaprHandler.getDaprID(deployment)
// Assert
assert.Equal(t, expected, got)
})
t.Run("WithEmptyId", func(t *testing.T) {
// Arrange
expected := ""
deployment := getDeployment(expected, "true")
testDaprHandler := NewDaprHandler(testclient.New(nil))
// Act
got := testDaprHandler.getDaprID(deployment)
// Assert
assert.Equal(t, expected, got)
})
}
func TestIsAnnotatedForDapr(t *testing.T) {
t.Run("Enabled", func(t *testing.T) {
// Arrange
expected := "true"
deployment := getDeployment("test_id", expected)
testDaprHandler := NewDaprHandler(testclient.New(nil))
// Act
got := testDaprHandler.isAnnotatedForDapr(deployment)
// Assert
assert.True(t, got)
})
t.Run("Disabled", func(t *testing.T) {
// Arrange
expected := "false"
deployment := getDeployment("test_id", expected)
testDaprHandler := NewDaprHandler(testclient.New(nil))
// Act
got := testDaprHandler.isAnnotatedForDapr(deployment)
// Assert
assert.False(t, got)
})
t.Run("Invalid", func(t *testing.T) {
// Arrange
expected := "0"
deployment := getDeployment("test_id", expected)
testDaprHandler := NewDaprHandler(testclient.New(nil))
// Act
got := testDaprHandler.isAnnotatedForDapr(deployment)
// Assert
assert.False(t, got)
})
}
func getDeployment(daprId string, daprEnabled string) *appsv1.Deployment {
// Arrange
metadata := meta_v1.ObjectMeta{
Name: "app",
Labels: map[string]string{"app": "test_app"},
Annotations: map[string]string{
daprIDAnnotationKey: daprId,
daprEnabledAnnotationKey: daprEnabled,
},
}
podTemplateSpec := corev1.PodTemplateSpec{
ObjectMeta: metadata,
}
deployment := &appsv1.Deployment{
ObjectMeta: meta_v1.ObjectMeta{
Name: "app",
},
Spec: appsv1.DeploymentSpec{
Template: podTemplateSpec,
},
}
return deployment
}
package handlers
import (
"testing"
"github.com/stretchr/testify/assert"
testclient "github.com/dapr/dapr/pkg/client/clientset/versioned"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func TestGetDaprID(t *testing.T) {
t.Run("WithValidId", func(t *testing.T) {
// Arrange
expected := "test_id"
deployment := getDeployment(expected, "true")
testDaprHandler := NewDaprHandler(testclient.New(nil))
// Act
got := testDaprHandler.getDaprID(deployment)
// Assert
assert.Equal(t, expected, got)
})
t.Run("WithEmptyId", func(t *testing.T) {
// Arrange
expected := ""
deployment := getDeployment(expected, "true")
testDaprHandler := NewDaprHandler(testclient.New(nil))
// Act
got := testDaprHandler.getDaprID(deployment)
// Assert
assert.Equal(t, expected, got)
})
}
func TestIsAnnotatedForDapr(t *testing.T) {
t.Run("Enabled", func(t *testing.T) {
// Arrange
expected := "true"
deployment := getDeployment("test_id", expected)
testDaprHandler := NewDaprHandler(testclient.New(nil))
// Act
got := testDaprHandler.isAnnotatedForDapr(deployment)
// Assert
assert.True(t, got)
})
t.Run("Disabled", func(t *testing.T) {
// Arrange
expected := "false"
deployment := getDeployment("test_id", expected)
testDaprHandler := NewDaprHandler(testclient.New(nil))
// Act
got := testDaprHandler.isAnnotatedForDapr(deployment)
// Assert
assert.False(t, got)
})
t.Run("Invalid", func(t *testing.T) {
// Arrange
expected := "0"
deployment := getDeployment("test_id", expected)
testDaprHandler := NewDaprHandler(testclient.New(nil))
// Act
got := testDaprHandler.isAnnotatedForDapr(deployment)
// Assert
assert.False(t, got)
})
}
func getDeployment(daprID string, daprEnabled string) *appsv1.Deployment {
// Arrange
metadata := meta_v1.ObjectMeta{
Name: "app",
Labels: map[string]string{"app": "test_app"},
Annotations: map[string]string{
daprIDAnnotationKey: daprID,
daprEnabledAnnotationKey: daprEnabled,
},
}
podTemplateSpec := corev1.PodTemplateSpec{
ObjectMeta: metadata,
}
deployment := &appsv1.Deployment{
ObjectMeta: meta_v1.ObjectMeta{
Name: "app",
},
Spec: appsv1.DeploymentSpec{
Template: podTemplateSpec,
},
}
return deployment
}

View File

@ -92,7 +92,7 @@ func TestInitPubSub(t *testing.T) {
rt.appChannel = mockAppChannel
// User App subscribes 2 topics via http app channel
fakeHttpResponse := &channel.InvokeResponse{
fakeHTTPResponse := &channel.InvokeResponse{
Metadata: map[string]string{http_channel.HTTPStatusCode: "200"},
Data: []byte("[ \"topic0\", \"topic1\" ]"),
}
@ -102,7 +102,7 @@ func TestInitPubSub(t *testing.T) {
&channel.InvokeRequest{
Method: "dapr/subscribe",
Metadata: map[string]string{http_channel.HTTPVerb: http_channel.Get},
}).Return(fakeHttpResponse, nil)
}).Return(fakeHTTPResponse, nil)
// act
err := rt.initPubSub()
@ -120,7 +120,7 @@ func TestInitPubSub(t *testing.T) {
mockAppChannel := new(channelt.MockAppChannel)
rt.appChannel = mockAppChannel
fakeHttpResponse := &channel.InvokeResponse{
fakeHTTPResponse := &channel.InvokeResponse{
Metadata: map[string]string{http_channel.HTTPStatusCode: "404"},
Data: nil,
}
@ -130,7 +130,7 @@ func TestInitPubSub(t *testing.T) {
&channel.InvokeRequest{
Method: "dapr/subscribe",
Metadata: map[string]string{http_channel.HTTPVerb: http_channel.Get},
}).Return(fakeHttpResponse, nil)
}).Return(fakeHTTPResponse, nil)
// act
err := rt.initPubSub()
@ -215,7 +215,7 @@ func TestInitSecretStores(t *testing.T) {
func TestMetadataItemsToPropertiesConversion(t *testing.T) {
rt := NewTestDaprRuntime(modes.StandaloneMode)
items := []components_v1alpha1.MetadataItem{
components_v1alpha1.MetadataItem{
{
Name: "a",
Value: "b",
},
@ -233,14 +233,14 @@ func TestProcessComponentSecrets(t *testing.T) {
Spec: components_v1alpha1.ComponentSpec{
Type: "bindings.mock",
Metadata: []components_v1alpha1.MetadataItem{
components_v1alpha1.MetadataItem{
{
Name: "a",
SecretKeyRef: components_v1alpha1.SecretKeyRef{
Key: "key1",
Name: "name1",
},
},
components_v1alpha1.MetadataItem{
{
Name: "b",
Value: "value2",
},
@ -331,14 +331,14 @@ func TestInitSecretStoresInKubernetesMode(t *testing.T) {
Spec: components_v1alpha1.ComponentSpec{
Type: "secretstores.fake.secretstore",
Metadata: []components_v1alpha1.MetadataItem{
components_v1alpha1.MetadataItem{
{
Name: "a",
SecretKeyRef: components_v1alpha1.SecretKeyRef{
Key: "key1",
Name: "name1",
},
},
components_v1alpha1.MetadataItem{
{
Name: "b",
Value: "value2",
},
@ -380,12 +380,12 @@ func TestOnNewPublishedMessage(t *testing.T) {
mockAppChannel := new(channelt.MockAppChannel)
rt.appChannel = mockAppChannel
fakeHttpResponse := &channel.InvokeResponse{
fakeHTTPResponse := &channel.InvokeResponse{
Metadata: map[string]string{http_channel.HTTPStatusCode: "200"},
Data: []byte("OK"),
}
mockAppChannel.On("InvokeMethod", expectedRequest).Return(fakeHttpResponse, nil)
mockAppChannel.On("InvokeMethod", expectedRequest).Return(fakeHTTPResponse, nil)
// act
err := rt.publishMessageHTTP(testPubSubMessage)
@ -401,14 +401,14 @@ func TestOnNewPublishedMessage(t *testing.T) {
clientError := errors.New("Internal Error")
fakeHttpResponse := &channel.InvokeResponse{
fakeHTPResponse := &channel.InvokeResponse{
Metadata: map[string]string{http_channel.HTTPStatusCode: "500"},
Data: []byte(clientError.Error()),
}
expectedClientError := fmt.Errorf("error from app consumer: Internal Error")
mockAppChannel.On("InvokeMethod", expectedRequest).Return(fakeHttpResponse, clientError)
mockAppChannel.On("InvokeMethod", expectedRequest).Return(fakeHTPResponse, clientError)
// act
err := rt.publishMessageHTTP(testPubSubMessage)
@ -429,15 +429,15 @@ func getFakeProperties() map[string]string {
func getFakeMetadataItems() []components_v1alpha1.MetadataItem {
return []components_v1alpha1.MetadataItem{
components_v1alpha1.MetadataItem{
{
Name: "host",
Value: "localhost",
},
components_v1alpha1.MetadataItem{
{
Name: "password",
Value: "fakePassword",
},
components_v1alpha1.MetadataItem{
{
Name: "consumerID",
Value: TestRuntimeConfigID,
},

View File

@ -1,17 +1,17 @@
package testing
import (
"github.com/dapr/components-contrib/exporters"
mock "github.com/stretchr/testify/mock"
)
// MockExporter is a mock exporter object
type MockExporter struct {
mock.Mock
}
// Init is a mock initialization method
func (m *MockExporter) Init(daprID string, hostAddress string, metadata exporters.Metadata) error {
args := m.Called(daprID, hostAddress, metadata)
return args.Error(0)
}
package testing
import (
"github.com/dapr/components-contrib/exporters"
mock "github.com/stretchr/testify/mock"
)
// MockExporter is a mock exporter object
type MockExporter struct {
mock.Mock
}
// Init is a mock initialization method
func (m *MockExporter) Init(daprID string, hostAddress string, metadata exporters.Metadata) error {
args := m.Called(daprID, hostAddress, metadata)
return args.Error(0)
}