Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Increase unit test coverage in various packages #1066

Merged
merged 5 commits into from
Feb 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions pkg/log/log_suite_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*
SPDX-License-Identifier: Apache-2.0
Copyright Contributors to the Submariner project.
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 log_test

import (
"testing"

"github.com/go-logr/logr"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/submariner-io/admiral/pkg/log"
logf "sigs.k8s.io/controller-runtime/pkg/log"
)

func TestLog(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Log Suite")
}

var (
rootLogSink = newLogSinkImpl()
exited bool
)

var _ = BeforeSuite(func() {
logf.SetLogger(logr.New(rootLogSink))

log.Exit = func(_ int) {
exited = true
}
})

type logSinkImpl struct {
infoCh chan []any
errorCh chan []any
}

func newLogSinkImpl() *logSinkImpl {
return &logSinkImpl{infoCh: make(chan []any, 10), errorCh: make(chan []any, 10)}
}

func (l *logSinkImpl) Init(_ logr.RuntimeInfo) {
}

func (l *logSinkImpl) Enabled(_ int) bool {
return true
}

func (l *logSinkImpl) Info(level int, msg string, keysAndValues ...any) {
l.infoCh <- append([]any{level, msg}, keysAndValues...)
}

func (l *logSinkImpl) Error(err error, msg string, keysAndValues ...any) {
l.errorCh <- append([]any{err, msg}, keysAndValues...)
}

func (l *logSinkImpl) WithValues(_ ...any) logr.LogSink {
return newLogSinkImpl()
}

func (l *logSinkImpl) WithName(_ string) logr.LogSink {
return newLogSinkImpl()
}
7 changes: 5 additions & 2 deletions pkg/log/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ const (
FatalKey = "FATAL"
)

// Exit hook for unit tests.
var Exit = os.Exit

type Logger struct {
logr.Logger
}
Expand Down Expand Up @@ -60,7 +63,7 @@ func (l Logger) Warningf(format string, args ...interface{}) {

func (l Logger) Fatal(msg string, keysAndValues ...interface{}) {
l.Logger.Error(nil, msg, append(keysAndValues, FatalKey, "true")...)
os.Exit(255)
Exit(255)
}

func (l Logger) Fatalf(format string, args ...interface{}) {
Expand All @@ -73,7 +76,7 @@ func (l Logger) FatalOnError(err error, msg string, keysAndValues ...interface{}
}

l.Logger.Error(err, msg, append(keysAndValues, FatalKey, "true")...)
os.Exit(255)
Exit(255)
}

func (l Logger) FatalfOnError(err error, format string, args ...interface{}) {
Expand Down
108 changes: 108 additions & 0 deletions pkg/log/logger_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/*
SPDX-License-Identifier: Apache-2.0
Copyright Contributors to the Submariner project.
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 log_test

import (
"errors"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/submariner-io/admiral/pkg/log"
logf "sigs.k8s.io/controller-runtime/pkg/log"
)

var _ = Describe("Logger", func() {
var logger log.Logger

BeforeEach(func() {
exited = false
logger = log.Logger{Logger: logf.Log}
})

Specify("Infof should log a formatted info message", func() {
logger.Infof("value is %d", 3)
Expect(rootLogSink.infoCh).To(Receive(HaveExactElements(0, "value is 3")))
})

Specify("Info should log an info message with keys and values", func() {
logger.Info("hello", "key", "value")
Expect(rootLogSink.infoCh).To(Receive(HaveExactElements(0, "hello", "key", "value")))
})

Specify("Errorf should log the error with a formatted message", func() {
err := errors.New("some error")
logger.Errorf(err, "value is %d", 3)
Expect(rootLogSink.errorCh).To(Receive(HaveExactElements(err, "value is 3")))
})

Specify("Error should log the error with a message and keys and values", func() {
err := errors.New("some error")
logger.Error(err, "failed", "key", "value")
Expect(rootLogSink.errorCh).To(Receive(HaveExactElements(err, "failed", "key", "value")))
})

Specify("Warningf should log a formatted info message", func() {
logger.Warningf("value is %d", 3)
Expect(rootLogSink.infoCh).To(Receive(HaveExactElements(0, "value is 3", log.WarningKey, "true")))
})

Specify("Warning should log an info message with keys and values", func() {
logger.Warning("hello", "key", "value")
Expect(rootLogSink.infoCh).To(Receive(HaveExactElements(0, "hello", "key", "value", log.WarningKey, "true")))
})

Specify("Fatalf should log a formatted error message and then exit", func() {
logger.Fatalf("value is %d", 3)
Expect(rootLogSink.errorCh).To(Receive(HaveExactElements(nil, "value is 3", log.FatalKey, "true")))
Expect(exited).To(BeTrue())
})

Specify("Fatal should log an error message with keys and values and then exit", func() {
logger.Fatal("failed", "key", "value")
Expect(rootLogSink.errorCh).To(Receive(HaveExactElements(nil, "failed", "key", "value", log.FatalKey, "true")))
Expect(exited).To(BeTrue())
})

Context("FatalfOnError", func() {
Specify("with an error specified should log the error and then exit", func() {
err := errors.New("some error")
logger.FatalfOnError(err, "value is %d", 3)
Expect(rootLogSink.errorCh).To(Receive(HaveExactElements(err, "value is 3", log.FatalKey, "true")))
Expect(exited).To(BeTrue())
})

Specify("with no error specified should not exit", func() {
logger.FatalfOnError(nil, "value is %d", 3)
Expect(rootLogSink.errorCh).NotTo(Receive())
Expect(exited).To(BeFalse())
})
})

Specify("FatalOnError should log the error and then exit", func() {
err := errors.New("some error")
logger.FatalOnError(err, "failed", "key", "value")
Expect(rootLogSink.errorCh).To(Receive(HaveExactElements(err, "failed", "key", "value", log.FatalKey, "true")))
Expect(exited).To(BeTrue())
})

Specify("V should set the log level", func() {
logger.V(2).Info("message")
Expect(rootLogSink.infoCh).To(Receive(HaveExactElements(2, "message")))
})
})
76 changes: 76 additions & 0 deletions pkg/reporter/adapter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
SPDX-License-Identifier: Apache-2.0
Copyright Contributors to the Submariner project.
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 reporter_test

import (
"errors"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/submariner-io/admiral/pkg/reporter"
)

type basicImpl struct {
reporter.Basic
endCalled chan struct{}
}

func (b *basicImpl) End() {
close(b.endCalled)
}

var _ = Describe("Adapter", func() {
stdoutCapture := newStdoutCapture()

var adapter reporter.Adapter

BeforeEach(func() {
adapter = reporter.Adapter{Basic: &basicImpl{Basic: reporter.Stdout(), endCalled: make(chan struct{})}}
stdoutCapture.start()
})

Context("Error", func() {
It("should log the error", func() {
err := errors.New("some error")
Expect(adapter.Error(err, "")).To(Equal(err))
Expect(stdoutCapture.read()).To(ContainSubstring("Some error"))
Expect(adapter.Basic.(*basicImpl).endCalled).To(BeClosed())
})

When("the error is nil", func() {
It("should not log anything", func() {
Expect(adapter.Error(nil, "failed")).To(Succeed())
Expect(stdoutCapture.read()).To(BeEmpty())
})
})

When("a message is specified", func() {
It("should wrap the error with the message", func() {
err := errors.New("some error")
actual := adapter.Error(err, "failed")

Expect(actual.Error()).To(HavePrefix("failed"))

out := stdoutCapture.read()
Expect(out).To(ContainSubstring("Failed"))
Expect(out).To(ContainSubstring(err.Error()))
})
})
})
})
74 changes: 74 additions & 0 deletions pkg/reporter/reporter_suite_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
SPDX-License-Identifier: Apache-2.0
Copyright Contributors to the Submariner project.
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 reporter_test

import (
"bytes"
"io"
"os"
"testing"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)

func TestReporter(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Reporter Suite")
}

type StdoutCapture struct {
oldStdout *os.File
readFile *os.File
writeFile *os.File
}

func newStdoutCapture() *StdoutCapture {
s := &StdoutCapture{oldStdout: os.Stdout}

AfterEach(func() {
s.done()
})

return s
}

func (s *StdoutCapture) start() {
var err error

s.readFile, s.writeFile, err = os.Pipe()
Expect(err).To(Succeed())

os.Stdout = s.writeFile
}

func (s *StdoutCapture) read() string {
s.writeFile.Close()
os.Stdout = s.oldStdout

var buf bytes.Buffer
_, err := io.Copy(&buf, s.readFile)
Expect(err).To(Succeed())

return buf.String()
}

func (s *StdoutCapture) done() {
os.Stdout = s.oldStdout
}
Loading
Loading