Skip to content

Commit

Permalink
config: implement TextMarshaler for LogLevel
Browse files Browse the repository at this point in the history
Signed-off-by: Hank Donnay <hdonnay@redhat.com>
  • Loading branch information
hdonnay committed Mar 21, 2022
1 parent 6a99b61 commit f1bb53e
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 2 deletions.
20 changes: 18 additions & 2 deletions config/enums.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package config

import (
"encoding"
"errors"
"fmt"
"strings"
)
Expand Down Expand Up @@ -75,5 +76,20 @@ func (l *LogLevel) UnmarshalText(b []byte) (err error) {
return nil
}

// Assert LogLevel implements TextUnmarshaler.
var _ encoding.TextUnmarshaler = (*LogLevel)(nil)
// MarshalText implements encoding.TextMarshaler.
func (l *LogLevel) MarshalText() ([]byte, error) {
if l == nil {
return nil, errors.New("invalid LogLevel pointer: <nil>")
}
i := *l
if i < 0 || i >= LogLevel(len(_LogLevel_index)-1) {
return nil, fmt.Errorf("invalid LogLevel: %q", l.String())
}
return []byte(_LogLevel_name[_LogLevel_index[i]:_LogLevel_index[i+1]]), nil
}

// Assert LogLevel implements TextUnmarshaler and TextMarshaler.
var (
_ encoding.TextUnmarshaler = (*LogLevel)(nil)
_ encoding.TextMarshaler = (*LogLevel)(nil)
)
47 changes: 47 additions & 0 deletions config/enums_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package config_test

import (
"bytes"
"testing"

"github.com/quay/clair/config"
)

func TestEnumMarshal(t *testing.T) {
t.Run("LogLevel", func(t *testing.T) {
tt := [][]byte{
[]byte("info"),
[]byte("debug-color"),
[]byte("debug"),
[]byte("warn"),
[]byte("error"),
[]byte("fatal"),
[]byte("panic"),
}
t.Run("Marshal", func(t *testing.T) {
for i, want := range tt {
l := config.LogLevel(i)
got, err := l.MarshalText()
if err != nil {
t.Error(err)
continue
}
if !bytes.Equal(got, want) {
t.Errorf("got: %q, want: %q", got, want)
}
}
})
t.Run("Unmarshal", func(t *testing.T) {
for want, in := range tt {
var l config.LogLevel
if err := l.UnmarshalText(in); err != nil {
t.Error(err)
continue
}
if got := int(l); got != want {
t.Errorf("got: %q, want: %q", got, want)
}
}
})
})
}

0 comments on commit f1bb53e

Please sign in to comment.