xonecas.io
8058
Ir

irvc / files

irvc / typing_test.go

1.7 KB
1package main
2
3import (
4	"path/filepath"
5	"strings"
6	"testing"
7)
8
9func testClient(h *hub, id int64, name string) *client {
10	c := &client{hub: h, userID: id, username: name, send: make(chan []byte, 8)}
11	h.clients[id] = map[*client]bool{c: true}
12	return c
13}
14
15func got(c *client) bool { return len(c.send) > 0 }
16
17func drain(cs ...*client) {
18	for _, c := range cs {
19		for len(c.send) > 0 {
20			<-c.send
21		}
22	}
23}
24
25// Typing is relayed to everyone for a text channel, only to the two
26// participants for a DM, and never faster than typingEvery per connection.
27func TestTypingRelay(t *testing.T) {
28	db := OpenDB(filepath.Join(t.TempDir(), "t.db"))
29	h := newHub(db)
30	a, b, outsider := testClient(h, 1, "a"), testClient(h, 2, "b"), testClient(h, 3, "c")
31
32	var text, dm int64
33	db.QueryRow(`SELECT id FROM channels WHERE type = 'text' LIMIT 1`).Scan(&text)
34	res, err := db.Exec(`INSERT INTO channels (type, name, position, created_at) VALUES ('dm', 'u:1:2', 0, 0)`)
35	if err != nil {
36		t.Fatal(err)
37	}
38	dm, _ = res.LastInsertId()
39
40	h.typing(a, text)
41	if !got(a) || !got(b) || !got(outsider) {
42		t.Fatal("text channel typing should reach everyone")
43	}
44	if ev := string(<-b.send); !strings.Contains(ev, `"username":"a"`) {
45		t.Fatalf("unexpected event %s", ev)
46	}
47
48	h.typing(a, text) // within typingEvery
49	if got(b) {
50		t.Fatal("typing events should be rate limited per connection")
51	}
52
53	drain(a, b, outsider)
54	a.typedAt = a.typedAt.Add(-2 * typingEvery)
55	h.typing(a, dm)
56	if !got(b) || got(outsider) {
57		t.Fatal("DM typing should reach only its participants")
58	}
59
60	outsider.typedAt = outsider.typedAt.Add(-2 * typingEvery)
61	drain(a, b, outsider)
62	h.typing(outsider, dm)
63	if got(b) || got(a) {
64		t.Fatal("a non-participant must not be able to type into a DM")
65	}
66}