Skip to content

Commit

Permalink
Replace fatal with panic (#15)
Browse files Browse the repository at this point in the history
* Replace fatal with panic

* Add nolint to non-even number of args
  • Loading branch information
ilya-hontarau authored Apr 18, 2024
1 parent 744dd76 commit 48b1258
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 5 deletions.
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"))
})
})

}

0 comments on commit 48b1258

Please sign in to comment.