Skip to content

Commit 17f5ca1

Browse files
jacksontjbrian-brazil
authored andcommitted
Fix unmarshal of negative times (#193)
Signed-off-by: Thomas Jackson <[email protected]>
1 parent 1ba8873 commit 17f5ca1

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

model/time.go

+7-1
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,13 @@ func (t *Time) UnmarshalJSON(b []byte) error {
150150
return err
151151
}
152152

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

155161
default:
156162
return fmt.Errorf("invalid time %q", string(b))

model/time_test.go

+35
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
package model
1515

1616
import (
17+
"strconv"
1718
"testing"
1819
"time"
1920
)
@@ -130,3 +131,37 @@ func TestParseDuration(t *testing.T) {
130131
}
131132
}
132133
}
134+
135+
func TestTimeJSON(t *testing.T) {
136+
tests := []struct {
137+
in Time
138+
out string
139+
}{
140+
{Time(1), `0.001`},
141+
{Time(-1), `-0.001`},
142+
}
143+
144+
for i, test := range tests {
145+
t.Run(strconv.Itoa(i), func(t *testing.T) {
146+
b, err := test.in.MarshalJSON()
147+
if err != nil {
148+
t.Fatalf("Error marshaling time: %v", err)
149+
}
150+
151+
if string(b) != test.out {
152+
t.Errorf("Mismatch in marshal expected=%s actual=%s", test.out, b)
153+
}
154+
155+
var tm Time
156+
if err := tm.UnmarshalJSON(b); err != nil {
157+
t.Fatalf("Error Unmarshaling time: %v", err)
158+
}
159+
160+
if !test.in.Equal(tm) {
161+
t.Fatalf("Mismatch after Unmarshal expected=%v actual=%v", test.in, tm)
162+
}
163+
164+
})
165+
}
166+
167+
}

0 commit comments

Comments
 (0)