Skip to content

Commit

Permalink
more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
lionelvillard committed Jul 14, 2020
1 parent 127aec5 commit 0513cd3
Show file tree
Hide file tree
Showing 3 changed files with 126 additions and 22 deletions.
20 changes: 16 additions & 4 deletions pkg/adapter/mtping/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ package mtping
import (
"testing"

"knative.dev/pkg/apis"

"github.com/google/go-cmp/cmp"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
Expand All @@ -45,7 +47,13 @@ func TestProject(t *testing.T) {
Schedule: "* * * * ?",
JsonData: "some data",
},
Status: sourcesv1alpha2.PingSourceStatus{},
Status: sourcesv1alpha2.PingSourceStatus{
duckv1.SourceStatus{
SinkURI: &apis.URL{
Host: "asink",
},
},
},
},
expected: PingConfig{
ObjectReference: corev1.ObjectReference{
Expand All @@ -54,7 +62,7 @@ func TestProject(t *testing.T) {
},
Schedule: "* * * * ?",
JsonData: "some data",
SinkURI: "",
SinkURI: "//asink",
}},
"TestAddRunRemoveScheduleWithExtensionOverride": {
source: sourcesv1alpha2.PingSource{
Expand All @@ -71,7 +79,11 @@ func TestProject(t *testing.T) {
Schedule: "* * * * ?",
JsonData: "some data",
},
Status: sourcesv1alpha2.PingSourceStatus{},
Status: sourcesv1alpha2.PingSourceStatus{
duckv1.SourceStatus{
SinkURI: &apis.URL{Host: "anothersink"},
},
},
},
expected: PingConfig{
ObjectReference: corev1.ObjectReference{
Expand All @@ -81,7 +93,7 @@ func TestProject(t *testing.T) {
Schedule: "* * * * ?",
JsonData: "some data",
Extensions: map[string]string{"1": "one", "2": "two"},
SinkURI: "",
SinkURI: "//anothersink",
}},
}
for n, tc := range testCases {
Expand Down
33 changes: 19 additions & 14 deletions pkg/adapter/v2/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,11 @@ func MainWithContext(ctx context.Context, component string, ector EnvConfigConst

func MainWithEnv(ctx context.Context, component string, env EnvConfigAccessor, ctor AdapterConstructor) {
if IsInjectorEnabled(ctx) {
ctx = SetupAndStartInformers(ctx, env.GetLogger())
ictx, informers := SetupInformers(ctx, env.GetLogger())
if informers != nil {
StartInformers(ctx, informers) // none-blocking
}
ctx = ictx
}
MainWithInformers(ctx, component, env, ctor)
}
Expand Down Expand Up @@ -136,7 +140,6 @@ func MainWithInformers(ctx context.Context, component string, env EnvConfigAcces
}
crStatusEventClient = crstatusevent.NewCRStatusEventClient(metricsConfig.ConfigMap)
}

}

reporter, err := source.NewStatsReporter()
Expand All @@ -160,6 +163,7 @@ func MainWithInformers(ctx context.Context, component string, env EnvConfigAcces
logger.Fatal("Error building cloud event client", zap.Error(err))
}

// Setup config watcher if enabled.
if IsConfigMapWatcherEnabled(ctx) {
cmw := SetupConfigMapWatchOrDie(ctx, component, env.GetNamespace())
ctx = WithConfigMapWatcher(ctx, cmw)
Expand All @@ -168,6 +172,7 @@ func MainWithInformers(ctx context.Context, component string, env EnvConfigAcces
// Configuring the adapter
adapter := ctor(ctx, env, eventsClient)

// Start config watcher if enabled.
if IsConfigMapWatcherEnabled(ctx) {
logger.Info("Starting configuration manager...")
if err := ConfigMapWatcherFromContext(ctx).Start(ctx.Done()); err != nil {
Expand Down Expand Up @@ -202,7 +207,7 @@ func ConstructEnvOrDie(ector EnvConfigConstructor) EnvConfigAccessor {
return env
}

func SetupAndStartInformers(ctx context.Context, logger *zap.SugaredLogger) context.Context {
func SetupInformers(ctx context.Context, logger *zap.SugaredLogger) (context.Context, []controller.Informer) {
// Run the injectors, but only if strictly necessary to relax the dependency on kubeconfig.
if len(injection.Default.GetInformers()) > 0 || len(injection.Default.GetClients()) > 0 ||
len(injection.Default.GetDucks()) > 0 || len(injection.Default.GetInformerFactories()) > 0 {
Expand All @@ -212,18 +217,18 @@ func SetupAndStartInformers(ctx context.Context, logger *zap.SugaredLogger) cont
logger.Infof("Registering %d ducks", len(injection.Default.GetDucks()))

cfg := sharedmain.ParseAndGetConfigOrDie()
ictx, informers := injection.Default.SetupInformers(ctx, cfg)
ctx = ictx

// Start the injection clients and informers.
go func(ctx context.Context) {
if err := controller.StartInformers(ctx.Done(), informers...); err != nil {
panic(fmt.Sprintf("Failed to start informers - %s", err))
}
<-ctx.Done()
}(ctx)
return injection.Default.SetupInformers(ctx, cfg)
}
return ctx
return ctx, nil
}

func StartInformers(ctx context.Context, informers []controller.Informer) {
go func() {
if err := controller.StartInformers(ctx.Done(), informers...); err != nil {
panic(fmt.Sprintf("Failed to start informers - %s", err))
}
<-ctx.Done()
}()
}

func flush(logger *zap.SugaredLogger) {
Expand Down
95 changes: 91 additions & 4 deletions pkg/adapter/v2/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,57 @@ import (

cloudevents "github.com/cloudevents/sdk-go/v2"
"go.opencensus.io/stats/view"
_ "knative.dev/pkg/client/injection/kube/client/fake"
"knative.dev/pkg/leaderelection"
"knative.dev/pkg/metrics"

rectesting "knative.dev/pkg/reconciler/testing"
_ "knative.dev/pkg/system/testing"
)

type myAdapter struct{}

func TestMainWithContextNoLeaderElection(t *testing.T) {
func TestMainWithNothing(t *testing.T) {
os.Setenv("K_SINK", "http://sink")
os.Setenv("NAMESPACE", "ns")
os.Setenv("K_METRICS_CONFIG", "error config")
os.Setenv("K_LOGGING_CONFIG", "error config")
os.Setenv("MODE", "mymode")

defer func() {
os.Unsetenv("K_SINK")
os.Unsetenv("NAMESPACE")
os.Unsetenv("K_METRICS_CONFIG")
os.Unsetenv("K_LOGGING_CONFIG")
os.Unsetenv("MODE")
}()

Main("mycomponent",
func() EnvConfigAccessor { return &myEnvConfig{} },
func(ctx context.Context, processed EnvConfigAccessor, client cloudevents.Client) Adapter {
env := processed.(*myEnvConfig)

if env.Mode != "mymode" {
t.Errorf("Expected mode mymode, got: %s", env.Mode)
}

if env.Sink != "http://sink" {
t.Errorf("Expected sinkURI http://sink, got: %s", env.Sink)
}

if leaderelection.HasLeaderElection(ctx) {
t.Error("Expected no leader election, but got leader election")
}
return &myAdapter{}
})

defer view.Unregister(metrics.NewMemStatsAll().DefaultViews()...)
}

func TestMainWithInformerNoLeaderElection(t *testing.T) {
os.Setenv("K_SINK", "http://sink")
os.Setenv("NAMESPACE", "ns")
os.Setenv("K_METRICS_CONFIG", "metrics")
os.Setenv("K_LOGGING_CONFIG", "logging")
os.Setenv("K_METRICS_CONFIG", "error config")
os.Setenv("K_LOGGING_CONFIG", "error config")
os.Setenv("MODE", "mymode")

defer func() {
Expand Down Expand Up @@ -73,6 +111,55 @@ func TestMainWithContextNoLeaderElection(t *testing.T) {
defer view.Unregister(metrics.NewMemStatsAll().DefaultViews()...)
}

func TestMainWithContextWithConfigWatcher(t *testing.T) {
os.Setenv("K_SINK", "http://sink")
os.Setenv("NAMESPACE", "ns")
os.Setenv("K_METRICS_CONFIG", "{}")
os.Setenv("K_LOGGING_CONFIG", "{}")
os.Setenv("MODE", "mymode")

defer func() {
os.Unsetenv("K_SINK")
os.Unsetenv("NAMESPACE")
os.Unsetenv("K_METRICS_CONFIG")
os.Unsetenv("K_LOGGING_CONFIG")
os.Unsetenv("MODE")
}()

ctx, _ := rectesting.SetupFakeContext(t)
WithConfigMapWatcherEnabled(ctx)
ctx, cancel := context.WithCancel(ctx)

MainWithContext(ctx,
"mycomponent",
func() EnvConfigAccessor { return &myEnvConfig{} },
func(ctx context.Context, processed EnvConfigAccessor, client cloudevents.Client) Adapter {
env := processed.(*myEnvConfig)

if env.Mode != "mymode" {
t.Errorf("Expected mode mymode, got: %s", env.Mode)
}

if env.Sink != "http://sink" {
t.Errorf("Expected sinkURI http://sink, got: %s", env.Sink)
}

if leaderelection.HasLeaderElection(ctx) {
t.Error("Expected no leader election, but got leader election")
}
return &myAdapter{}
})

cancel()
defer view.Unregister(metrics.NewMemStatsAll().DefaultViews()...)
}

func TestStartInformers(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
StartInformers(ctx, nil)
cancel()
}

func (m *myAdapter) Start(_ context.Context) error {
return nil
}

0 comments on commit 0513cd3

Please sign in to comment.