Skip to content

Commit

Permalink
Fix unmarshal of negative times (#193)
Browse files Browse the repository at this point in the history
Signed-off-by: Thomas Jackson <jacksontj.89@gmail.com>
  • Loading branch information
jacksontj authored and brian-brazil committed May 16, 2019
1 parent 1ba8873 commit 17f5ca1
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
8 changes: 7 additions & 1 deletion model/time.go
Expand Up @@ -150,7 +150,13 @@ func (t *Time) UnmarshalJSON(b []byte) error {
return err
}

*t = Time(v + va)
// If the value was something like -0.1 the negative is lost in the
// parsing because of the leading zero, this ensures that we capture it.
if len(p[0]) > 0 && p[0][0] == '-' && v+va > 0 {
*t = Time(v+va) * -1
} else {
*t = Time(v + va)
}

default:
return fmt.Errorf("invalid time %q", string(b))
Expand Down
35 changes: 35 additions & 0 deletions model/time_test.go
Expand Up @@ -14,6 +14,7 @@
package model

import (
"strconv"
"testing"
"time"
)
Expand Down Expand Up @@ -130,3 +131,37 @@ func TestParseDuration(t *testing.T) {
}
}
}

func TestTimeJSON(t *testing.T) {
tests := []struct {
in Time
out string
}{
{Time(1), `0.001`},
{Time(-1), `-0.001`},
}

for i, test := range tests {
t.Run(strconv.Itoa(i), func(t *testing.T) {
b, err := test.in.MarshalJSON()
if err != nil {
t.Fatalf("Error marshaling time: %v", err)
}

if string(b) != test.out {
t.Errorf("Mismatch in marshal expected=%s actual=%s", test.out, b)
}

var tm Time
if err := tm.UnmarshalJSON(b); err != nil {
t.Fatalf("Error Unmarshaling time: %v", err)
}

if !test.in.Equal(tm) {
t.Fatalf("Mismatch after Unmarshal expected=%v actual=%v", test.in, tm)
}

})
}

}

0 comments on commit 17f5ca1

Please sign in to comment.