package form import ( "net/http" "net/http/httptest" "strings" "testing" "time" ) func TestGet(t *testing.T) { r := testReq() if v := Get(r, "a"); v != "b" { t.Error(v) } if v := Get(r, "c"); v != "4" { t.Error(v) } if v := Get(r, "d"); v != "e, f,g" { t.Error(v) } } func TestToStrArr(t *testing.T) { cases := []struct { in string out int }{ { in: "4", out: 1, }, { in: "a,b,c", out: 3, }, { in: " a, b, c ", out: 3, }, { in: "a,b, c", out: 3, }, { in: "a,b", out: 2, }, { in: "a,", out: 1, }, { in: "a", out: 1, }, { in: "", out: 0, }, } for _, c := range cases { if len(ToStrArr(c.in)) != c.out { t.Error(c) } } } func TestToTime(t *testing.T) { cases := []struct { in string out string }{ { in: "2001-02-03 04:05:06", out: "2001-02-03 04:05:06", }, { in: "5", out: "0001-01-01 00:00:00", }, { in: "1/2/03", out: "2003-01-02 00:00:00", }, { in: "11/12/03", out: "2003-11-12 00:00:00", }, { in: "01+Jan+2020+12:00+PM", out: "2020-01-01 12:00:00", }, } for _, c := range cases { time := ToTime(c.in) if v := time.Format("2006-01-02 15:04:05"); v != c.out { t.Error(c, v) } } } func TestToInt(t *testing.T) { cases := []struct { in string out int }{ { in: "4", out: 4, }, { in: "a", out: 0, }, { in: "", out: 0, }, { in: "-1", out: -1, }, { in: "5", out: 5, }, } for _, c := range cases { if ToInt(c.in) != c.out { t.Error(c) } } } func testReq() *http.Request { return httptest.NewRequest("POST", "/path/to", strings.NewReader(`{ "a": "b", "c": 4, "d": "e, f,g" }`)) } func TestToDuration(t *testing.T) { cases := map[string]struct { input string want time.Duration }{ "invalid": {}, "simple": {input: "1s", want: time.Second}, "compound": {input: "1m1s", want: time.Minute + time.Second}, "compound:unsorted": {input: "1s1m", want: time.Minute + time.Second}, "compound:extension": {input: "1d1m", want: time.Minute + time.Hour*24}, "extension:day": {input: "1d", want: 24 * time.Hour}, "extension:week": {input: "1w", want: 24 * 7 * time.Hour}, "extension:week,day": {input: "1w1d", want: 24 * 8 * time.Hour}, } for name, d := range cases { c := d t.Run(name, func(t *testing.T) { got := ToDuration(c.input) if got != c.want { t.Fatal(c.input, c.want, got) } }) } }