-
Notifications
You must be signed in to change notification settings - Fork 21
/
dalga_test.go
126 lines (106 loc) · 2.5 KB
/
dalga_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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package dalga // nolint: testpackage
import (
"bytes"
"context"
"database/sql"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/cenkalti/dalga/v3/internal/log"
)
func init() {
log.EnableDebug()
}
const (
testBody = "testBody"
testTimeout = 5 * time.Second
)
func TestSchedule(t *testing.T) {
called := make(chan string)
endpoint := func(w http.ResponseWriter, r *http.Request) {
var buf bytes.Buffer
buf.ReadFrom(r.Body)
r.Body.Close()
called <- buf.String()
}
mux := http.NewServeMux()
mux.HandleFunc("/", endpoint)
srv := httptest.NewServer(mux)
defer srv.Close()
config := DefaultConfig
config.MySQL.SkipLocked = false
config.Endpoint.BaseURL = "http://" + srv.Listener.Addr().String() + "/"
d, lis, cleanup := newDalga(t, config)
defer cleanup()
ctx, cancel := context.WithCancel(context.Background())
go d.Run(ctx)
defer func() {
cancel()
<-d.NotifyDone()
}()
values := make(url.Values)
values.Set("one-off", "true")
values.Set("first-run", "1990-01-01T00:00:00Z")
scheduleURL := "http://" + lis.Addr() + "/jobs/testPath/" + testBody
req, err := http.NewRequest("PUT", scheduleURL, strings.NewReader(values.Encode()))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
var client http.Client
resp, err := client.Do(req)
if err != nil {
t.Fatalf("cannot schedule new job: %s", err.Error())
}
defer resp.Body.Close()
var buf bytes.Buffer
buf.ReadFrom(resp.Body)
if resp.StatusCode != 201 {
t.Fatalf("unexpected status code: %d, body: %q", resp.StatusCode, buf.String())
}
t.Log("PUT response:", buf.String())
t.Log("scheduled job")
select {
case body := <-called:
t.Log("endpoint is called")
if body != testBody {
t.Fatalf("Invalid body: %s", body)
}
case <-time.After(testTimeout):
t.Fatal("timeout")
}
time.Sleep(time.Second)
}
func newDalga(t *testing.T, config Config) (*Dalga, listenConfig, func()) {
db, err := sql.Open("mysql", config.MySQL.DSN())
if err != nil {
t.Fatal(err.Error())
}
defer db.Close()
err = db.Ping()
if err != nil {
t.Fatalf("cannot connect to mysql: %s", err.Error())
}
t.Log("connected to db")
d, err := New(config)
if err != nil {
t.Fatal(err)
}
err = d.table.Drop(context.Background())
if err != nil {
t.Fatal(err)
}
t.Log("dropped table")
err = d.CreateTable()
if err != nil {
t.Fatal(err)
}
t.Log("created table")
return d, config.Listen, func() {
d.Close()
_ = d.table.Drop(context.Background())
}
}