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

feat: config.Duration implement TextMarshaller (close #164) #166

Merged
merged 5 commits into from
Jul 30, 2021
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
12 changes: 12 additions & 0 deletions config/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,15 @@ func (d *Duration) UnmarshalJSON(b []byte) error {
return errors.New("invalid duration")
}
}

// MarshalText implements encoding.TextMarshaler
func (d Duration) MarshalText() ([]byte, error) {
return []byte(d.String()), nil
}

// UnmarshalText implements encoding.TextUnmarshaler
func (d *Duration) UnmarshalText(text []byte) error {
var err error
d.Duration, err = time.ParseDuration(string(text))
return err
}
55 changes: 49 additions & 6 deletions config/time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,40 @@ func TestDuration_UnmarshalJSON(t *testing.T) {
c := c
t.Run(c.name, func(t *testing.T) {
t.Parallel()
v1 := Duration{}
yaml.Unmarshal([]byte(c.value), &v1)
assert.Equal(t, c.expected, v1)
v2 := Duration{}
json.Unmarshal([]byte(c.value), &v2)
assert.Equal(t, c.expected, v2)
d := Duration{}
err := json.Unmarshal([]byte(c.value), &d)
assert.NoError(t, err)
assert.Equal(t, c.expected, d)
})
}
}

func TestDuration_UnmarshalYaml(t *testing.T) {
var cases = []struct {
name string
value string
expected Duration
}{
{
"simple",
`"5s"`,
Duration{5 * time.Second},
},
{
"float",
`65000000000.0`,
Duration{5*time.Second + time.Minute},
},
}

for _, c := range cases {
c := c
t.Run(c.name, func(t *testing.T) {
t.Parallel()
d := Duration{}
err := yaml.Unmarshal([]byte(c.value), &d)
assert.NoError(t, err)
assert.Equal(t, c.expected, d)
})
}
}
Expand Down Expand Up @@ -93,10 +121,25 @@ func TestDuration_IsZero(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
d := Duration{tt.val}
if got := d.IsZero(); got != tt.want {
t.Errorf("IsZero() = %v, want %v", got, tt.want)
}
})
}
}

func TestDuration_UnmarshalText(t *testing.T) {
var d Duration
err := d.UnmarshalText([]byte("1s"))
assert.NoError(t, err)
assert.Equal(t, Duration{time.Second}, d)
}

func TestDuration_MarshalText(t *testing.T) {
d := Duration{time.Second}
b, err := d.MarshalText()
assert.NoError(t, err)
assert.Equal(t, []byte("1s"), b)
}