-
Notifications
You must be signed in to change notification settings - Fork 9
/
listen_test.go
97 lines (83 loc) · 2.44 KB
/
listen_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package libpq_test
import (
"database/sql"
"testing"
)
func mustExec(t *testing.T, db *sql.DB, query string) {
if _, err := db.Exec(query); err != nil {
t.Fatalf("Failed to execute [%s]: %s", query, err)
}
}
func mustScan(t *testing.T, rs *sql.Rows, dest ...interface{}) {
if err := rs.Scan(dest...); err != nil {
t.Fatalf("Failure scanning: ", err)
}
}
func TestListen(t *testing.T) {
db := getConn(t)
defer db.Close()
// start listening
notes, err := db.Query("LISTEN channel")
if err != nil {
t.Fatalf("Failed to prepare LISTEN: ", err)
}
defer notes.Close()
// make sure a plain NOTIFY with no payload works
mustExec(t, db, "NOTIFY channel")
payload := "bogus payload"
if !notes.Next() {
t.Fatalf("Did not receive NOTIFY")
}
mustScan(t, notes, &payload)
if payload != "" {
t.Fatalf("Received unexpected payload '%s' (expected '')", payload)
}
// we can also pass in a payload, and notifications arrive in order
mustExec(t, db, "NOTIFY channel, 'the first payload'")
mustExec(t, db, "NOTIFY channel, 'the second payload'")
if !notes.Next() {
t.Fatalf("Did not receive NOTIFY")
}
mustScan(t, notes, &payload)
if payload != "the first payload" {
t.Fatalf("Received unexpected payload '%s' (expected 'the first payload')", payload)
}
if !notes.Next() {
t.Fatalf("Did not receive NOTIFY")
}
mustScan(t, notes, &payload)
if payload != "the second payload" {
t.Fatalf("Received unexpected payload '%s' (expected 'the second payload')", payload)
}
}
func TestUnlisten(t *testing.T) {
db := getConn(t)
defer db.Close()
// start listening on channel1
notes, err := db.Query("LISTEN channel1")
if err != nil {
t.Fatalf("Failed to prepare LISTEN: ", err)
}
// return that connection to sql.DB's pool, and unlisten
if err = notes.Close(); err != nil {
t.Fatalf("Failure closing LISTEN query: ", err)
}
// start a new connection listening to channel 2
// the underlying DB connection should be the SAME as our previous one,
// as database.sql pools them
notes, err = db.Query("LISTEN channel2")
if err != nil {
t.Fatalf("Failed to prepare LISTEN: ", err)
}
// make sure we receive ONLY the message sent to channel2
mustExec(t, db, "NOTIFY channel1, 'to 1'")
mustExec(t, db, "NOTIFY channel2, 'to 2'")
var payload string
if !notes.Next() {
t.Fatalf("Did not receive NOTIFY")
}
mustScan(t, notes, &payload)
if payload != "to 2" {
t.Fatalf("Received unexpected payload '%s' (expected 'to 2')", payload)
}
}