From 2f0e42d6c5446dac651b4dc7d03f055c5db57ec0 Mon Sep 17 00:00:00 2001 From: Alexander Apalikov Date: Thu, 30 May 2019 22:19:57 +0300 Subject: [PATCH] Add HandleError input parameter check (#798) There could be a panic on HandleError logging functionality. Add test coverage for that. --- pkg/util/runtime/runtime.go | 6 +++-- pkg/util/runtime/runtime_test.go | 46 ++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) create mode 100644 pkg/util/runtime/runtime_test.go diff --git a/pkg/util/runtime/runtime.go b/pkg/util/runtime/runtime.go index 368c576d62..3f3383209a 100644 --- a/pkg/util/runtime/runtime.go +++ b/pkg/util/runtime/runtime.go @@ -52,8 +52,10 @@ func init() { // HandleError wraps runtime.HandleError so that it is possible to // use WithField with logrus. func HandleError(logger *logrus.Entry, err error) { - // it's a bit of a double handle, but I can't see a better way to do it - logger.WithError(err).Error() + if logger != nil { + // it's a bit of a double handle, but I can't see a better way to do it + logger.WithError(err).Error() + } runtime.HandleError(err) } diff --git a/pkg/util/runtime/runtime_test.go b/pkg/util/runtime/runtime_test.go new file mode 100644 index 0000000000..81ae813051 --- /dev/null +++ b/pkg/util/runtime/runtime_test.go @@ -0,0 +1,46 @@ +// Copyright 2019 Google LLC All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package runtime handles runtime errors +// Wraps and reconfigures functionality in apimachinery/pkg/runtime +package runtime + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "k8s.io/apimachinery/pkg/util/runtime" +) + +func TestHandleError(t *testing.T) { + old := runtime.ErrorHandlers + defer func() { runtime.ErrorHandlers = old }() + var result error + runtime.ErrorHandlers = []func(error){ + func(err error) { + result = err + }, + } + HandleError(nil, nil) + assert.Nil(t, result, "No Errors for now") + + err := fmt.Errorf("test") + //test nil logger + logger := NewLoggerWithSource("test") + HandleError(logger.WithError(err), err) + if result != err { + t.Errorf("did not receive custom handler") + } +}