From 5d5bf7a741528b4a82cbe9c67f48425fe19be444 Mon Sep 17 00:00:00 2001 From: Pratiksha Kap <107430880+kappratiksha@users.noreply.github.com> Date: Tue, 21 Jun 2022 14:53:56 -0700 Subject: [PATCH] fix: adding a check for null http handler before starting the server (#138) --- funcframework/framework.go | 4 ++++ funcframework/framework_test.go | 17 ++++++++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/funcframework/framework.go b/funcframework/framework.go index 08d9ffc..ea483f6 100644 --- a/funcframework/framework.go +++ b/funcframework/framework.go @@ -142,6 +142,10 @@ func Start(port string) error { } } + if handler == nil { + return fmt.Errorf("no matching function found with name: %q", target) + } + return http.ListenAndServe(":"+port, handler) } diff --git a/funcframework/framework_test.go b/funcframework/framework_test.go index c57b73b..243d950 100644 --- a/funcframework/framework_test.go +++ b/funcframework/framework_test.go @@ -59,6 +59,7 @@ func TestHTTPFunction(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { h, err := wrapHTTPFunction("/", tc.fn) + defer func() { handler = nil }() if err != nil { t.Fatalf("registerHTTPFunction(): %v", err) } @@ -519,6 +520,7 @@ func TestCloudEventFunction(t *testing.T) { t.Run(tc.name, func(t *testing.T) { ctx := context.Background() h, err := wrapCloudEventFunction(ctx, "/", tc.fn) + defer func() { handler = nil }() if err != nil { t.Fatalf("registerCloudEventFunction(): %v", err) } @@ -591,7 +593,7 @@ func TestDeclarativeFunctionHTTP(t *testing.T) { }); err != nil { t.Fatalf("registerHTTPFunction(): %v", err) } - + defer func() { handler = nil }() // register functions functions.HTTP(funcName, func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello World!") @@ -620,6 +622,8 @@ func TestDeclarativeFunctionCloudEvent(t *testing.T) { // register functions functions.CloudEvent(funcName, dummyCloudEvent) + //cleanup global var + defer func() { handler = nil }() if _, ok := registry.Default().GetRegisteredFunction(funcName); !ok { t.Fatalf("could not get registered function: %s", funcName) } @@ -632,6 +636,17 @@ func TestDeclarativeFunctionCloudEvent(t *testing.T) { } } +func TestFunctionsNotRegisteredError(t *testing.T) { + funcName := "HelloWorld" + os.Setenv("FUNCTION_TARGET", funcName) + + wantErr := fmt.Sprintf("no matching function found with name: %q", funcName) + + if err := Start("0"); err.Error() != wantErr { + t.Fatalf("Expected error: %s and received error: %s", wantErr, err.Error()) + } +} + func dummyCloudEvent(ctx context.Context, e cloudevents.Event) error { return nil }