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

Replace fatal with panic #15

Merged
merged 2 commits into from
Apr 18, 2024
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
9 changes: 4 additions & 5 deletions fields.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
package spcontext

import (
stdlog "log"

"github.com/pkg/errors"
"fmt"
)

// Fields represents and contains structure metadata.
Expand All @@ -14,9 +12,10 @@ type Fields struct {
}

// With creates a new child Fields with additional fields.
// Panics if odd number of arguments were passed or key(first value of each pair) is not a string.
func (fields *Fields) With(kvs ...interface{}) *Fields {
if len(kvs)%2 != 0 {
stdlog.Fatalf("%+v", errors.New("invalid Fields.With call: odd number of arguments"))
panic("invalid Fields.With call: odd number of arguments")
}

keys := make([]string, len(kvs)/2)
Expand All @@ -25,7 +24,7 @@ func (fields *Fields) With(kvs ...interface{}) *Fields {
var ok bool
keys[i], ok = kvs[2*i].(string)
if !ok {
stdlog.Fatalf("invalid Fields.With call: non-string log field key: %v", kvs[2*i])
panic(fmt.Sprintf("invalid Fields.With call: non-string log field key: %v", kvs[2*i]))
}
values[i] = kvs[2*i+1]
}
Expand Down
41 changes: 41 additions & 0 deletions fields_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package spcontext

import (
"testing"

"github.com/franela/goblin"
"github.com/onsi/gomega"
)

func TestFieldsWith(t *testing.T) {
g := goblin.Goblin(t)
gomega.RegisterFailHandler(func(m string, _ ...int) { g.Fail(m) })

g.Describe("Happy path", func() {
f := &Fields{}
newFields := f.With("test", 1, "test2", 2)
g.It("empty base fields", func() {
gomega.Expect(f.EvaluateFields()).To(gomega.Equal([]any(nil)))
})
g.It("non empty new fields", func() {
gomega.Expect(newFields.EvaluateFields()).To(gomega.Equal([]any{"test", 1, "test2", 2}))
})
})
g.Describe("odd number of fields", func() {
f := &Fields{}
g.It("odd number of fields", func() {
gomega.Expect(func() {
f.With("test", 1, "test2") //nolint:staticcheck // negative test case
}).To(gomega.PanicWith("invalid Fields.With call: odd number of arguments"))
})
})
g.Describe("key is not string", func() {
f := &Fields{}
g.It("odd number of fields", func() {
gomega.Expect(func() {
f.With("test", 1, 3, 2)
}).To(gomega.PanicWith("invalid Fields.With call: non-string log field key: 3"))
})
})

}
Loading