feed_test.go270 lines, 9.3 KB
| 1 | package feed_test |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "slices" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | |
| 13 | "github.com/fiston-user/murmur/internal/feed" |
| 14 | "github.com/fiston-user/murmur/internal/jobs" |
| 15 | "github.com/fiston-user/murmur/internal/likes" |
| 16 | "github.com/fiston-user/murmur/internal/notify" |
| 17 | "github.com/fiston-user/murmur/internal/platform/replica" |
| 18 | "github.com/fiston-user/murmur/internal/platform/testdb" |
| 19 | "github.com/fiston-user/murmur/internal/posts" |
| 20 | "github.com/fiston-user/murmur/internal/timeline" |
| 21 | "github.com/fiston-user/murmur/internal/users" |
| 22 | "github.com/jackc/pgx/v5/pgxpool" |
| 23 | "github.com/redis/go-redis/v9" |
| 24 | ) |
| 25 | |
| 26 | // client talks to a real server on a real database, for one test. |
| 27 | type client struct { |
| 28 | t *testing.T |
| 29 | url string |
| 30 | rdb *redis.Client |
| 31 | w *jobs.Worker |
| 32 | db *pgxpool.Pool |
| 33 | tl *timeline.Store |
| 34 | } |
| 35 | |
| 36 | func newClient(t *testing.T) *client { |
| 37 | db, rdb := testdb.New(t), testdb.Redis(t) |
| 38 | tl := timeline.New(db, rdb, 2) |
| 39 | reads := replica.New(db, nil, rdb) // no replica: every read goes to db |
| 40 | u, p, f := users.New(db, tl), posts.New(db, reads), feed.New(reads, tl) |
| 41 | w := jobs.NewWorker(db) |
| 42 | w.Handle(timeline.FanOut, tl.RunFanOut) |
| 43 | n := notify.New(db, rdb) |
| 44 | w.Handle(notify.Like, n.RunLike) |
| 45 | mux := http.NewServeMux() |
| 46 | mux.HandleFunc("POST /users", u.Create) |
| 47 | mux.HandleFunc("POST /posts", u.Auth(p.Create)) |
| 48 | mux.HandleFunc("POST /users/{handle}/follow", u.Auth(u.Follow)) |
| 49 | mux.HandleFunc("GET /feed", u.Auth(f.List)) |
| 50 | mux.HandleFunc("GET /users/{handle}/posts", u.Maybe(p.List)) |
| 51 | mux.HandleFunc("POST /posts/{id}/like", u.Auth(likes.New(db).Like)) |
| 52 | mux.HandleFunc("GET /notifications", u.Auth(n.List)) |
| 53 | srv := httptest.NewServer(mux) |
| 54 | t.Cleanup(srv.Close) |
| 55 | return &client{t: t, url: srv.URL, rdb: rdb, w: w, tl: tl, db: db} |
| 56 | } |
| 57 | |
| 58 | // call sends one request, checks the status, and decodes a JSON answer into out (unless out is nil). |
| 59 | func (c *client) call(method, path, token, body string, want int, out any) { |
| 60 | c.t.Helper() |
| 61 | req, err := http.NewRequest(method, c.url+path, strings.NewReader(body)) |
| 62 | if err != nil { |
| 63 | c.t.Fatal(err) |
| 64 | } |
| 65 | if token != "" { // no token: nobody |
| 66 | req.Header.Set("Authorization", "Bearer "+token) |
| 67 | } |
| 68 | res, err := http.DefaultClient.Do(req) |
| 69 | if err != nil { |
| 70 | c.t.Fatal(err) |
| 71 | } |
| 72 | defer res.Body.Close() |
| 73 | if res.StatusCode != want { |
| 74 | c.t.Fatalf("%s %s: status %d, want %d", method, path, res.StatusCode, want) |
| 75 | } |
| 76 | c.work() // run what this request queued |
| 77 | if out == nil { |
| 78 | return |
| 79 | } |
| 80 | if err := json.NewDecoder(res.Body).Decode(out); err != nil { |
| 81 | c.t.Fatalf("%s %s: %v", method, path, err) |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | // work runs the queue until it's empty, like the worker does, minus the sleep. |
| 86 | func (c *client) work() { |
| 87 | c.t.Helper() |
| 88 | for { |
| 89 | ok, err := c.w.RunOne(context.Background()) |
| 90 | if err != nil { |
| 91 | c.t.Fatal(err) |
| 92 | } |
| 93 | if !ok { |
| 94 | return |
| 95 | } |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | // signUp creates a user and returns their token. |
| 100 | func (c *client) signUp(handle string) string { |
| 101 | c.t.Helper() |
| 102 | var out struct { |
| 103 | Token string `json:"token"` |
| 104 | } |
| 105 | c.call("POST", "/users", "", fmt.Sprintf(`{"handle": %q}`, handle), http.StatusCreated, &out) |
| 106 | return out.Token |
| 107 | } |
| 108 | |
| 109 | func TestFeedPaging(t *testing.T) { |
| 110 | c := newClient(t) |
| 111 | alice, bob, carol := c.signUp("alice"), c.signUp("bob"), c.signUp("carol") |
| 112 | c.call("POST", "/users/alice/follow", carol, "", http.StatusNoContent, nil) |
| 113 | c.call("POST", "/users/bob/follow", carol, "", http.StatusNoContent, nil) |
| 114 | for i, token := range []string{alice, bob, alice, bob, carol} { |
| 115 | c.call("POST", "/posts", token, fmt.Sprintf(`{"body": "post %d"}`, i+1), http.StatusCreated, nil) |
| 116 | } |
| 117 | |
| 118 | var got []int64 |
| 119 | path := "/feed?limit=2" |
| 120 | for { |
| 121 | var page feed.Page |
| 122 | c.call("GET", path, carol, "", http.StatusOK, &page) |
| 123 | for _, p := range page.Posts { |
| 124 | got = append(got, p.ID) |
| 125 | } |
| 126 | if page.NextCursor == nil { |
| 127 | break |
| 128 | } |
| 129 | path = fmt.Sprintf("/feed?limit=2&cursor=%d", *page.NextCursor) |
| 130 | c.call("POST", "/posts", bob, `{"body": "while you were reading"}`, http.StatusCreated, nil) |
| 131 | } |
| 132 | if want := []int64{4, 3, 2, 1}; !slices.Equal(got, want) { |
| 133 | t.Fatalf("feed ids = %v, want %v", got, want) |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | func TestTimeline(t *testing.T) { |
| 138 | c := newClient(t) |
| 139 | ctx := context.Background() |
| 140 | alice, bob := c.signUp("alice"), c.signUp("bob") |
| 141 | c.call("POST", "/users/alice/follow", bob, "", http.StatusNoContent, nil) |
| 142 | post := func(token string) { |
| 143 | c.call("POST", "/posts", token, `{"body": "hello"}`, http.StatusCreated, nil) |
| 144 | } |
| 145 | post(alice) |
| 146 | post(alice) |
| 147 | |
| 148 | // Bob has never read his feed, so those two posts must not start a timeline for him. |
| 149 | if n := c.rdb.Exists(ctx, "timeline:2").Val(); n != 0 { |
| 150 | t.Fatal("a post started a timeline for a reader who has none") |
| 151 | } |
| 152 | // His first read builds it, with both posts. |
| 153 | var page feed.Page |
| 154 | c.call("GET", "/feed", bob, "", http.StatusOK, &page) |
| 155 | if len(page.Posts) != 2 { |
| 156 | t.Fatalf("first read: %d posts, want 2", len(page.Posts)) |
| 157 | } |
| 158 | // From now on, a new post reaches it. The zero is the marker. |
| 159 | post(alice) |
| 160 | got := c.rdb.ZRange(ctx, "timeline:2", 0, -1).Val() |
| 161 | if want := []string{"0", "1", "2", "3"}; !slices.Equal(got, want) { |
| 162 | t.Fatalf("cached timeline = %v, want %v", got, want) |
| 163 | } |
| 164 | // Reads come from Redis. To prove it, we plant one of bob's own posts. |
| 165 | post(bob) |
| 166 | c.rdb.ZAdd(ctx, "timeline:2", redis.Z{Score: 4, Member: 4}) |
| 167 | c.call("GET", "/feed?limit=1", bob, "", http.StatusOK, &page) |
| 168 | if len(page.Posts) != 1 || page.Posts[0].ID != 4 { |
| 169 | t.Fatalf("page = %+v, want post 4: the read didn't come from Redis", page.Posts) |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | func TestBigAccount(t *testing.T) { |
| 174 | c := newClient(t) // in these tests, two followers make an account big |
| 175 | ctx := context.Background() |
| 176 | alice, bob, carol, dave := c.signUp("alice"), c.signUp("bob"), c.signUp("carol"), c.signUp("dave") |
| 177 | c.call("POST", "/users/alice/follow", bob, "", http.StatusNoContent, nil) |
| 178 | c.call("POST", "/users/alice/follow", carol, "", http.StatusNoContent, nil) |
| 179 | // Bob follows dave twice. That must count once, or dave would be big too. |
| 180 | c.call("POST", "/users/dave/follow", bob, "", http.StatusNoContent, nil) |
| 181 | c.call("POST", "/users/dave/follow", bob, "", http.StatusNoContent, nil) |
| 182 | // Bob reads once, so he has a timeline for posts to land in. |
| 183 | c.call("GET", "/feed", bob, "", http.StatusOK, nil) |
| 184 | for _, token := range []string{dave, alice, dave, alice} { |
| 185 | c.call("POST", "/posts", token, `{"body": "hello"}`, http.StatusCreated, nil) |
| 186 | } |
| 187 | |
| 188 | // Dave is small, so his posts were pushed. Alice is big, so hers were not. |
| 189 | got := c.rdb.ZRange(ctx, "timeline:2", 0, -1).Val() |
| 190 | if want := []string{"0", "1", "3"}; !slices.Equal(got, want) { |
| 191 | t.Fatalf("bob's timeline = %v, want %v", got, want) |
| 192 | } |
| 193 | // And still, alice's newest post is on top of bob's feed. |
| 194 | var page feed.Page |
| 195 | c.call("GET", "/feed?limit=1", bob, "", http.StatusOK, &page) |
| 196 | if len(page.Posts) != 1 || page.Posts[0].ID != 4 { |
| 197 | t.Fatalf("page = %+v, want post 4, pulled from a big account", page.Posts) |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | // A job can run twice. The second fan-out of a post must change nothing. |
| 202 | func TestFanOutTwice(t *testing.T) { |
| 203 | c := newClient(t) |
| 204 | ctx := context.Background() |
| 205 | alice, bob := c.signUp("alice"), c.signUp("bob") |
| 206 | c.call("POST", "/users/alice/follow", bob, "", http.StatusNoContent, nil) |
| 207 | c.call("GET", "/feed", bob, "", http.StatusOK, nil) // bob has a timeline now |
| 208 | c.call("POST", "/posts", alice, `{"body": "hello"}`, http.StatusCreated, nil) |
| 209 | |
| 210 | // The queue ran this job once. Now it runs a second time. |
| 211 | if err := c.tl.RunFanOut(ctx, []byte(`{"author": 1, "post": 1}`)); err != nil { |
| 212 | t.Fatal(err) |
| 213 | } |
| 214 | got := c.rdb.ZRange(ctx, "timeline:2", 0, -1).Val() |
| 215 | if want := []string{"0", "1"}; !slices.Equal(got, want) { |
| 216 | t.Fatalf("bob's timeline = %v, want %v", got, want) |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | // A list says how many like each post, and if the caller does. A profile pages like the feed. |
| 221 | func TestLiked(t *testing.T) { |
| 222 | c := newClient(t) |
| 223 | alice, bob := c.signUp("alice"), c.signUp("bob") |
| 224 | c.call("POST", "/users/alice/follow", bob, "", http.StatusNoContent, nil) |
| 225 | for i := range 3 { |
| 226 | c.call("POST", "/posts", alice, fmt.Sprintf(`{"body": "hello %d"}`, i+1), |
| 227 | http.StatusCreated, nil) |
| 228 | } |
| 229 | c.call("POST", "/posts/2/like", bob, "", http.StatusNoContent, nil) |
| 230 | if _, err := likes.Fold(context.Background(), c.db); err != nil { |
| 231 | t.Fatal(err) |
| 232 | } |
| 233 | |
| 234 | // each post as "id likes liked", and the next cursor |
| 235 | list := func(path, token string) []string { |
| 236 | var page struct { |
| 237 | NextCursor *int64 `json:"next_cursor"` |
| 238 | Posts []posts.Listed `json:"posts"` |
| 239 | } |
| 240 | c.call("GET", path, token, "", http.StatusOK, &page) |
| 241 | var got []string |
| 242 | for _, p := range page.Posts { |
| 243 | got = append(got, fmt.Sprint(p.ID, " ", p.Likes, " ", p.Liked)) |
| 244 | } |
| 245 | if page.NextCursor != nil { |
| 246 | got = append(got, fmt.Sprint("next ", *page.NextCursor)) |
| 247 | } |
| 248 | return got |
| 249 | } |
| 250 | for _, tc := range []struct { |
| 251 | name, path, token string |
| 252 | want []string |
| 253 | }{ |
| 254 | {"the feed", "/feed", bob, []string{"3 0 false", "2 1 true", "1 0 false"}}, |
| 255 | {"a profile", "/users/alice/posts?limit=2", bob, []string{"3 0 false", "2 1 true", "next 2"}}, |
| 256 | {"its next page", "/users/alice/posts?limit=2&cursor=2", bob, []string{"1 0 false"}}, |
| 257 | {"for nobody", "/users/alice/posts", "", []string{"3 0 false", "2 1 false", "1 0 false"}}, |
| 258 | } { |
| 259 | if got := list(tc.path, tc.token); !slices.Equal(got, tc.want) { |
| 260 | t.Errorf("%s: got %q, want %q", tc.name, got, tc.want) |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | // alice hears about it, with the words of the post that was liked |
| 265 | var told notify.Page |
| 266 | c.call("GET", "/notifications", alice, "", http.StatusOK, &told) |
| 267 | if len(told.Notifications) != 1 || told.Notifications[0].Body != "hello 2" { |
| 268 | t.Errorf("notifications = %+v, want one, for \"hello 2\"", told.Notifications) |
| 269 | } |
| 270 | } |