test ezpz json
parent
80af3093b0
commit
12886416b7
|
|
@ -1,3 +1,13 @@
|
|||
package pttodo
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
type Schedule string
|
||||
|
||||
func (schedule Schedule) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(string(schedule))
|
||||
}
|
||||
|
||||
func (schedule *Schedule) UnmarshalJSON(b []byte) error {
|
||||
return json.Unmarshal(b, (*string)(schedule))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,47 @@
|
|||
package pttodo
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestJSONSchedule(t *testing.T) {
|
||||
cases := map[string]struct {
|
||||
input string
|
||||
wantMarshalled string
|
||||
}{
|
||||
"cron": {
|
||||
input: "* * * * *",
|
||||
wantMarshalled: `"* * * * *"`,
|
||||
},
|
||||
"int": {
|
||||
input: "123",
|
||||
wantMarshalled: `"123"`,
|
||||
},
|
||||
"duration": {
|
||||
input: "1h",
|
||||
wantMarshalled: `"1h"`,
|
||||
},
|
||||
}
|
||||
|
||||
for name, d := range cases {
|
||||
c := d
|
||||
t.Run(name, func(t *testing.T) {
|
||||
gotMarshalled, err := json.Marshal(Schedule(c.input))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal([]byte(c.wantMarshalled), gotMarshalled) {
|
||||
t.Fatal(c.wantMarshalled, gotMarshalled)
|
||||
}
|
||||
var got Schedule
|
||||
if err := json.Unmarshal(gotMarshalled, &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(got) != c.input {
|
||||
t.Fatal(got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
18
pttodo/ts.go
18
pttodo/ts.go
|
|
@ -1,3 +1,19 @@
|
|||
package pttodo
|
||||
|
||||
type TS string
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type TS int64
|
||||
|
||||
func (ts TS) MarshalJSON() ([]byte, error) {
|
||||
if ts == 0 {
|
||||
ts = TS(time.Now().Unix())
|
||||
}
|
||||
return json.Marshal(int64(ts))
|
||||
}
|
||||
|
||||
func (ts *TS) UnmarshalJSON(b []byte) error {
|
||||
return json.Unmarshal(b, (*int64)(ts))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,30 @@
|
|||
package pttodo
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestJSONTS(t *testing.T) {
|
||||
ts := TS(time.Now().Unix())
|
||||
js, err := json.Marshal(ts)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var ts2 TS
|
||||
if err := json.Unmarshal(js, &ts2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ts != ts2 {
|
||||
t.Fatal(ts2)
|
||||
}
|
||||
|
||||
if err := json.Unmarshal([]byte(`123`), &ts2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if 123 != ts2 {
|
||||
t.Fatal(ts2)
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue