test ezpz json

master
Bel LaPointe 2021-12-31 15:23:59 -05:00
parent 80af3093b0
commit 12886416b7
4 changed files with 104 additions and 1 deletions

View File

@ -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))
}

47
pttodo/schedule_test.go Normal file
View File

@ -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)
}
})
}
}

View File

@ -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))
}

30
pttodo/ts_test.go Normal file
View File

@ -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)
}
}