From 1ee4d17b20480b2d34ef289deab57fef77729b58 Mon Sep 17 00:00:00 2001 From: Anhgelus Morhtuuzh Date: Sun, 15 Mar 2026 14:01:24 +0100 Subject: feat(human): json operations --- human_test.go | 99 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 human_test.go (limited to 'human_test.go') diff --git a/human_test.go b/human_test.go new file mode 100644 index 0000000..5109af4 --- /dev/null +++ b/human_test.go @@ -0,0 +1,99 @@ +package human_test + +import ( + "encoding/json" + "fmt" + "net/url" + "testing" + "time" + + "git.anhgelus.world/anhgelus/go-human.json" +) + +func TestURL_Json(t *testing.T) { + var r human.URL + err := json.Unmarshal([]byte(`"http://example.com"`), &r) + if err != nil { + t.Fatal(err) + } + if r.Scheme != "http" { + t.Errorf("invalid scheme: %s", r.Scheme) + } + if r.Host != "example.com" { + t.Errorf("invalid host: %s", r.Host) + } + if r.Path != "" { + t.Errorf("invalid path: %s", r.Path) + } + + err = json.Unmarshal([]byte(`"http://example.com:80/"`), &r) + if err != nil { + t.Fatal(err) + } + if r.Scheme != "http" { + t.Errorf("invalid scheme: %s", r.Scheme) + } + if r.Host != "example.com" { + t.Errorf("invalid host: %s", r.Host) + } + if r.Path != "" { + t.Errorf("invalid path: %s", r.Path) + } + + err = json.Unmarshal([]byte(`"https://foo.example.com:443/hello/world/"`), &r) + if err != nil { + t.Fatal(err) + } + if r.Scheme != "https" { + t.Errorf("invalid scheme: %s", r.Scheme) + } + if r.Host != "foo.example.com" { + t.Errorf("invalid host: %s", r.Host) + } + if r.Path != "/hello/world" { + t.Errorf("invalid path: %s", r.Path) + } + + err = json.Unmarshal([]byte(`"https://example.com:80/hello/world/?foo=bar"`), &r) + if err != nil { + t.Fatal(err) + } + if r.Scheme != "https" { + t.Errorf("invalid scheme: %s", r.Scheme) + } + if r.Host != "example.com:80" { + t.Errorf("invalid host: %s", r.Host) + } + if r.Path != "/hello/world" { + t.Errorf("invalid path: %s", r.Path) + } +} + +func TestVouch_Json(t *testing.T) { + var v human.Vouch + err := json.Unmarshal([]byte(`{"url": "https://bob.example.com","vouched_at": "2026-01-15"}`), &v) + if err != nil { + t.Fatal(err) + } + if v.URL.String() != "https://bob.example.com" { + t.Errorf("invalid url: %v", v.URL) + } + if v.VouchedAt.Format(time.DateOnly) != "2026-01-15" { + t.Errorf("invalid vouched_at: %v", v.VouchedAt) + } + + raw, _ := url.Parse(`https://bob.example.com:443/`) + now := time.Now() + cv := human.URL(*raw) + v = human.Vouch{ + URL: &cv, + VouchedAt: now, + } + b, err := json.Marshal(&v) + if err != nil { + t.Fatal(err) + } + if string(b) != fmt.Sprintf(`{"url":"https://bob.example.com","vouched_at":"%s"}`, now.Format(time.DateOnly)) { + t.Errorf("invalid marshal: %s", b) + } +} -- cgit v1.2.3