|
| 1 | +package omikuji |
| 2 | + |
| 3 | +import ( |
| 4 | + "io/ioutil" |
| 5 | + "net/http" |
| 6 | + "net/http/httptest" |
| 7 | + "strings" |
| 8 | + "testing" |
| 9 | + "time" |
| 10 | +) |
| 11 | + |
| 12 | +func TestIsNewYear(t *testing.T) { |
| 13 | + cases := map[string]struct { |
| 14 | + month int |
| 15 | + day int |
| 16 | + expected bool |
| 17 | + }{ |
| 18 | + "December31st": { |
| 19 | + 12, |
| 20 | + 31, |
| 21 | + false, |
| 22 | + }, |
| 23 | + "January1st": { |
| 24 | + 1, |
| 25 | + 1, |
| 26 | + true, |
| 27 | + }, |
| 28 | + "January2nd": { |
| 29 | + 1, 2, true, |
| 30 | + }, |
| 31 | + "January3rd": { |
| 32 | + 1, 3, true, |
| 33 | + }, |
| 34 | + "January4th": { |
| 35 | + 1, 4, false, |
| 36 | + }, |
| 37 | + } |
| 38 | + |
| 39 | + for k, v := range cases { |
| 40 | + k := k |
| 41 | + v := v |
| 42 | + |
| 43 | + t.Run(k, func(t *testing.T) { |
| 44 | + t.Helper() |
| 45 | + handler := New( |
| 46 | + ClockFunc(func() time.Time { |
| 47 | + return time.Date(2018, time.Month(v.month), v.day, 6, 0, 0, 0, time.Local) |
| 48 | + }), |
| 49 | + ) |
| 50 | + |
| 51 | + if handler.isNewYear() != v.expected { |
| 52 | + t.Errorf("expected=%v, actual=%v", v.expected, !v.expected) |
| 53 | + } |
| 54 | + }) |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +func TestCreateResponseJSON(t *testing.T) { |
| 59 | + handler := New(nil) |
| 60 | + result := "test" |
| 61 | + expected := "{\"result\":\"test\"}\n" |
| 62 | + json, err := handler.createResponseJSON(result) |
| 63 | + if err != nil { |
| 64 | + t.Fatal("should not come here") |
| 65 | + } |
| 66 | + if strings.Compare(json, expected) != 0 { |
| 67 | + t.Errorf("expected='%v', actual='%v'", expected, json) |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +func TestHandler(t *testing.T) { |
| 72 | + handler := New(ClockFunc(func() time.Time { |
| 73 | + return time.Date(2018, 1, 1, 6, 0, 0, 0, time.Local) |
| 74 | + })) |
| 75 | + |
| 76 | + w := httptest.NewRecorder() |
| 77 | + r := httptest.NewRequest("GET", "/", nil) |
| 78 | + handler.handlerFunc(w, r) |
| 79 | + rw := w.Result() |
| 80 | + defer rw.Body.Close() |
| 81 | + |
| 82 | + if rw.StatusCode != http.StatusOK { |
| 83 | + t.Fatal("unexpected status code") |
| 84 | + } |
| 85 | + |
| 86 | + b, err := ioutil.ReadAll(rw.Body) |
| 87 | + if err != nil { |
| 88 | + t.Fatal("unexpected error") |
| 89 | + } |
| 90 | + expected := "{\"result\":\"大吉\"}\n" |
| 91 | + |
| 92 | + if s := string(b); s != expected { |
| 93 | + t.Errorf("expected='%v', actual='%v'", expected, s) |
| 94 | + } |
| 95 | +} |
0 commit comments