likes_test.go293 lines, 8.6 KB
| 1 | package likes_test |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "slices" |
| 10 | "strings" |
| 11 | "sync" |
| 12 | "sync/atomic" |
| 13 | "testing" |
| 14 | |
| 15 | "github.com/fiston-user/murmur/internal/jobs" |
| 16 | "github.com/fiston-user/murmur/internal/likes" |
| 17 | "github.com/fiston-user/murmur/internal/notify" |
| 18 | "github.com/fiston-user/murmur/internal/platform/replica" |
| 19 | "github.com/fiston-user/murmur/internal/platform/testdb" |
| 20 | "github.com/fiston-user/murmur/internal/posts" |
| 21 | "github.com/fiston-user/murmur/internal/timeline" |
| 22 | "github.com/fiston-user/murmur/internal/users" |
| 23 | "github.com/jackc/pgx/v5/pgxpool" |
| 24 | ) |
| 25 | |
| 26 | // app is a real server on the test database, and a worker for the jobs it queues. |
| 27 | type app struct { |
| 28 | t *testing.T |
| 29 | url string |
| 30 | db *pgxpool.Pool |
| 31 | n *notify.Handler |
| 32 | w *jobs.Worker |
| 33 | } |
| 34 | |
| 35 | func newApp(t *testing.T) *app { |
| 36 | db := testdb.New(t) |
| 37 | reads := replica.New(db, nil, nil) // no replica: every read goes to db |
| 38 | u, p, l := users.New(db, nil), posts.New(db, reads), likes.New(db) |
| 39 | n := notify.New(db, testdb.Redis(t)) |
| 40 | w := jobs.NewWorker(db) |
| 41 | w.Handle(notify.Like, n.RunLike) |
| 42 | // A post queues a fan-out job as well. Nobody follows anybody here, so there's nothing to do. |
| 43 | w.Handle(timeline.FanOut, func(context.Context, []byte) error { return nil }) |
| 44 | mux := http.NewServeMux() |
| 45 | mux.HandleFunc("POST /users", u.Create) |
| 46 | mux.HandleFunc("POST /posts", u.Auth(p.Create)) |
| 47 | mux.HandleFunc("POST /posts/{id}/like", u.Auth(l.Like)) |
| 48 | mux.HandleFunc("DELETE /posts/{id}/like", u.Auth(l.Unlike)) |
| 49 | mux.HandleFunc("GET /notifications", u.Auth(n.List)) |
| 50 | mux.HandleFunc("GET /notifications/unread", u.Auth(n.Unread)) |
| 51 | mux.HandleFunc("POST /notifications/read", u.Auth(n.Read)) |
| 52 | srv := httptest.NewServer(mux) |
| 53 | t.Cleanup(srv.Close) |
| 54 | return &app{t: t, url: srv.URL, db: db, n: n, w: w} |
| 55 | } |
| 56 | |
| 57 | // do sends one request and returns its status. A JSON answer is decoded into out (unless out is nil). |
| 58 | func (a *app) do(method, path, token, body string, out any) int { |
| 59 | req, err := http.NewRequest(method, a.url+path, strings.NewReader(body)) |
| 60 | if err != nil { |
| 61 | a.t.Error(err) |
| 62 | return 0 |
| 63 | } |
| 64 | req.Header.Set("Authorization", "Bearer "+token) |
| 65 | res, err := http.DefaultClient.Do(req) |
| 66 | if err != nil { |
| 67 | a.t.Error(err) |
| 68 | return 0 |
| 69 | } |
| 70 | defer res.Body.Close() |
| 71 | if out != nil { |
| 72 | if err := json.NewDecoder(res.Body).Decode(out); err != nil { |
| 73 | a.t.Errorf("%s %s: %v", method, path, err) |
| 74 | } |
| 75 | } |
| 76 | return res.StatusCode |
| 77 | } |
| 78 | |
| 79 | // must is do, for a request that has to answer with the status we want. |
| 80 | func (a *app) must(want int, method, path, token, body string, out any) { |
| 81 | a.t.Helper() |
| 82 | if got := a.do(method, path, token, body, out); got != want { |
| 83 | a.t.Fatalf("%s %s: status %d, want %d", method, path, got, want) |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | // signUp creates a user and returns their token. |
| 88 | func (a *app) signUp(handle string) string { |
| 89 | a.t.Helper() |
| 90 | var out struct { |
| 91 | Token string `json:"token"` |
| 92 | } |
| 93 | a.must(http.StatusCreated, "POST", "/users", "", fmt.Sprintf(`{"handle": %q}`, handle), &out) |
| 94 | return out.Token |
| 95 | } |
| 96 | |
| 97 | // settle does what the worker does, right now: it folds the deltas, and it runs every job. |
| 98 | func (a *app) settle() { |
| 99 | a.t.Helper() |
| 100 | ctx := context.Background() |
| 101 | if _, err := likes.Fold(ctx, a.db); err != nil { |
| 102 | a.t.Fatal(err) |
| 103 | } |
| 104 | for { |
| 105 | ok, err := a.w.RunOne(ctx) |
| 106 | if err != nil { |
| 107 | a.t.Fatal(err) |
| 108 | } |
| 109 | if !ok { |
| 110 | return |
| 111 | } |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | // count runs a query that returns one number. |
| 116 | func (a *app) count(sql string) int { |
| 117 | a.t.Helper() |
| 118 | var n int |
| 119 | if err := a.db.QueryRow(context.Background(), sql).Scan(&n); err != nil { |
| 120 | a.t.Fatal(err) |
| 121 | } |
| 122 | return n |
| 123 | } |
| 124 | |
| 125 | // A like is a fact, and a fact is true once: liking twice counts once. |
| 126 | func TestLikeTwice(t *testing.T) { |
| 127 | a := newApp(t) |
| 128 | ann, bob := a.signUp("ann"), a.signUp("bob") |
| 129 | a.must(http.StatusCreated, "POST", "/posts", ann, `{"body": "hello"}`, nil) |
| 130 | |
| 131 | a.must(http.StatusNoContent, "POST", "/posts/1/like", bob, "", nil) |
| 132 | a.must(http.StatusNoContent, "POST", "/posts/1/like", bob, "", nil) |
| 133 | a.settle() |
| 134 | if n := a.count(`select likes_count from posts where id = 1`); n != 1 { |
| 135 | t.Fatalf("two likes by one user: the count is %d, want 1", n) |
| 136 | } |
| 137 | a.must(http.StatusNoContent, "DELETE", "/posts/1/like", bob, "", nil) |
| 138 | a.must(http.StatusNoContent, "DELETE", "/posts/1/like", bob, "", nil) |
| 139 | a.settle() |
| 140 | if n := a.count(`select likes_count from posts where id = 1`); n != 0 { |
| 141 | t.Fatalf("after the unlike: the count is %d, want 0", n) |
| 142 | } |
| 143 | a.must(http.StatusNotFound, "POST", "/posts/2/like", bob, "", nil) |
| 144 | } |
| 145 | |
| 146 | // A hundred people like one post at the same moment, twice each, while two |
| 147 | // folders fold flat out. Nobody is lost, and nobody is counted twice. |
| 148 | func TestLikeCrowd(t *testing.T) { |
| 149 | a := newApp(t) |
| 150 | a.must(http.StatusCreated, "POST", "/posts", a.signUp("ann"), `{"body": "hello"}`, nil) |
| 151 | var fans []string |
| 152 | for i := range 100 { |
| 153 | fans = append(fans, a.signUp(fmt.Sprintf("fan%d", i))) |
| 154 | } |
| 155 | |
| 156 | var done atomic.Bool |
| 157 | var crowd, folders sync.WaitGroup |
| 158 | for range 2 { |
| 159 | folders.Go(func() { |
| 160 | for !done.Load() { |
| 161 | if _, err := likes.Fold(context.Background(), a.db); err != nil { |
| 162 | t.Error(err) |
| 163 | return |
| 164 | } |
| 165 | } |
| 166 | }) |
| 167 | } |
| 168 | start := make(chan struct{}) |
| 169 | for _, fan := range fans { |
| 170 | crowd.Go(func() { |
| 171 | <-start |
| 172 | for range 2 { |
| 173 | if got := a.do("POST", "/posts/1/like", fan, "", nil); got != http.StatusNoContent { |
| 174 | t.Errorf("a like answered %d", got) |
| 175 | } |
| 176 | } |
| 177 | }) |
| 178 | } |
| 179 | close(start) |
| 180 | crowd.Wait() |
| 181 | done.Store(true) |
| 182 | folders.Wait() |
| 183 | a.settle() |
| 184 | |
| 185 | if n := a.count(`select count(*) from likes`); n != 100 { |
| 186 | t.Fatalf("%d likes, want 100", n) |
| 187 | } |
| 188 | if n := a.count(`select likes_count from posts where id = 1`); n != 100 { |
| 189 | t.Fatalf("the count is %d, want 100", n) |
| 190 | } |
| 191 | if n := a.count(`select count(*) from like_deltas`); n != 0 { |
| 192 | t.Fatalf("%d deltas are left, want none", n) |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | // A job can run twice. The second run of a like's job writes nothing, |
| 197 | // and it doesn't fail. And a like for your own post tells nobody. |
| 198 | func TestLikeJobTwice(t *testing.T) { |
| 199 | a := newApp(t) |
| 200 | ann, bob := a.signUp("ann"), a.signUp("bob") |
| 201 | a.must(http.StatusCreated, "POST", "/posts", ann, `{"body": "hello"}`, nil) |
| 202 | a.must(http.StatusNoContent, "POST", "/posts/1/like", bob, "", nil) |
| 203 | a.must(http.StatusNoContent, "POST", "/posts/1/like", ann, "", nil) |
| 204 | a.settle() |
| 205 | |
| 206 | // The queue ran bob's job once. Now it runs a second time. |
| 207 | if err := a.n.RunLike(context.Background(), []byte(`{"liker": 2, "post": 1}`)); err != nil { |
| 208 | t.Fatalf("the second run failed: %v", err) |
| 209 | } |
| 210 | if n := a.count(`select count(*) from notifications`); n != 1 { |
| 211 | t.Fatalf("%d notifications, want 1", n) |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | // crowded gives ann a post, and n notifications about it, from n users made in SQL. |
| 216 | func (a *app) crowded(n int) (ann string) { |
| 217 | a.t.Helper() |
| 218 | ann = a.signUp("ann") |
| 219 | a.must(http.StatusCreated, "POST", "/posts", ann, `{"body": "hello"}`, nil) |
| 220 | _, err := a.db.Exec(context.Background(), ` |
| 221 | with fans as ( |
| 222 | insert into users (handle, token_hash) |
| 223 | select 'fan' || i, sha256(i::text::bytea) from generate_series(1, $1::int) i |
| 224 | returning id |
| 225 | ) |
| 226 | insert into notifications (user_id, kind, actor_id, post_id) |
| 227 | select 1, 'like', id, 1 from fans order by id`, n) |
| 228 | if err != nil { |
| 229 | a.t.Fatal(err) |
| 230 | } |
| 231 | return ann |
| 232 | } |
| 233 | |
| 234 | func TestUnread(t *testing.T) { |
| 235 | a := newApp(t) |
| 236 | ann := a.crowded(150) |
| 237 | unread := func() int { |
| 238 | t.Helper() |
| 239 | var out struct { |
| 240 | Unread int `json:"unread"` |
| 241 | } |
| 242 | a.must(http.StatusOK, "GET", "/notifications/unread", ann, "", &out) |
| 243 | return out.Unread |
| 244 | } |
| 245 | steps := []struct { |
| 246 | upTo int // ann says she has seen everything up to this id |
| 247 | want int // and this is the unread count after it |
| 248 | }{ |
| 249 | {0, notify.MaxUnread}, // 150 are unread, and the count stops at a hundred |
| 250 | {100, 50}, |
| 251 | {148, 2}, |
| 252 | {20, 2}, // the marker never moves back |
| 253 | {999, 0}, // an id she doesn't have lands on her newest one |
| 254 | } |
| 255 | for i, s := range steps { |
| 256 | if s.upTo > 0 { |
| 257 | seen := fmt.Sprintf(`{"up_to": %d}`, s.upTo) |
| 258 | a.must(http.StatusNoContent, "POST", "/notifications/read", ann, seen, nil) |
| 259 | } |
| 260 | if got := unread(); got != s.want { |
| 261 | t.Fatalf("step %d: unread = %d, want %d", i+1, got, s.want) |
| 262 | } |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | func TestNotificationPages(t *testing.T) { |
| 267 | a := newApp(t) |
| 268 | ann := a.crowded(5) |
| 269 | a.must(http.StatusNoContent, "POST", "/notifications/read", ann, `{"up_to": 3}`, nil) |
| 270 | |
| 271 | var got, unread []int64 |
| 272 | path := "/notifications?limit=2" |
| 273 | for { |
| 274 | var page notify.Page |
| 275 | a.must(http.StatusOK, "GET", path, ann, "", &page) |
| 276 | for _, n := range page.Notifications { |
| 277 | got = append(got, n.ID) |
| 278 | if n.Unread { |
| 279 | unread = append(unread, n.ID) |
| 280 | } |
| 281 | } |
| 282 | if page.NextCursor == nil { |
| 283 | break |
| 284 | } |
| 285 | path = fmt.Sprintf("/notifications?limit=2&cursor=%d", *page.NextCursor) |
| 286 | } |
| 287 | if want := []int64{5, 4, 3, 2, 1}; !slices.Equal(got, want) { |
| 288 | t.Fatalf("notification ids = %v, want %v", got, want) |
| 289 | } |
| 290 | if want := []int64{5, 4}; !slices.Equal(unread, want) { |
| 291 | t.Fatalf("unread ids = %v, want %v", unread, want) |
| 292 | } |
| 293 | } |