Skip to content
Permalink
Browse files

Fix unmarshal of negative times (#193)

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 17f5ca1748182ddf24fc33a5a7caaaf790a52fcc
Showing with 42 additions and 1 deletion.
  1. +7 −1 model/time.go
  2. +35 −0 model/time_test.go
@@ -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))
@@ -14,6 +14,7 @@
package model

import (
"strconv"
"testing"
"time"
)
@@ -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.
You can’t perform that action at this time.