-
Notifications
You must be signed in to change notification settings - Fork 0
/
98_test.go
executable file
·499 lines (437 loc) · 11.5 KB
/
98_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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"math/rand"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strconv"
"strings"
"testing"
"time"
"github.com/dchest/captcha"
clr "github.com/mewkiz/pkg/term"
)
var ()
/*
cosgo test suite:
So far, testing for a few things:
1. POST URL Key MUST ALWAYS be served in the normal home page
2. POST URL Key MUST ALWAYS be present in user's POST message submissions
3. mbox gets bytes written to it on successful message send
4. Asset directories are restored (static, template) if they dont exist
5. Mbox is created on boot
6. CRONJOBs will not be broken, CLI Flags and Usage will not change for a while.
TODO:
1. Config tests
2. Benchmarks
3. Stress test
4. Template fields testing
*/
var times []time.Duration
var redwanted = clr.Red("Wanted:")
var rednotfound = ""
// grep is helper function to display the relative (target) line from a source string.
func grep(source interface{}, target string) string {
var str string
switch source.(type) {
case []byte:
str = string(source.([]byte))
case string:
str = source.(string)
default:
// working on it
}
defer func() {
backup([]byte(str))
}()
lines := strings.Split(str, "\n")
for _, line := range lines {
if strings.Contains(line, target) {
return clr.MagentaBold("Found: ") + clr.MagentaBold(line)
}
}
return ""
}
// In the case of a failed test, backup the response to /tmp/c_test_ThisTest_X
func backup(b []byte) {
tmpfile, _ := ioutil.TempFile(os.TempDir(), "c_test_"+strconv.Itoa(int(time.Now().Truncate(1*time.Minute).Unix())))
n, e := tmpfile.Write(b)
if e != nil {
panic(e)
}
fmt.Println("\t" + clr.Green(strconv.Itoa(n)+" bytes saved to "+tmpfile.Name()))
}
var originalFlags []string
func init() {
rand.NewSource(time.Now().UnixNano())
*quiet = true
*mboxfile = "testing.mbox"
originalFlags = os.Args
}
func randomDuration() (times []time.Duration) {
t := uint64(rand.Uint32()*4) * uint64(rand.Uint32()) * uint64(rand.Uint32()*rand.Uint32()) / uint64(rand.Intn(10000)+1)
times = append(times, time.Duration(t))
return times
}
func BenchmarkHumanize(b *testing.B) {
for i := 0; i < 1000; i++ {
b.StopTimer()
rands := randomDuration()
for _, t := range rands {
b.StartTimer()
humanize(t)
b.StopTimer()
}
}
}
func TestHumanize(t *testing.T) {
d := time.Duration(time.Hour * 24 * 7 * 4 * 8)
s := humanize(d)
if s != "8 months ago" {
fmt.Println("\tGot:", s)
fmt.Println("\t"+redwanted, "8 months ago")
t.FailNow()
}
// Output: 8 months ago
}
// TestHomeHandler tests the home page, and makes sure the URLKey is in the output.
func TestHomeHandler(t *testing.T) {
c := setup()
cwd, _ := os.Getwd()
c.route(cwd)
ts := httptest.NewServer(http.HandlerFunc(c.homeHandler))
defer ts.Close()
time.Sleep(100 * time.Millisecond)
key := c.URLKey
res, err := http.Get(ts.URL)
if err != nil {
log.Fatal(err)
}
greeting, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Fatal(err)
}
keyline := `<form id="contact-form" action="/` + key + `/send" method="POST">`
if !strings.Contains(string(greeting), keyline) {
fmt.Println("\t"+redwanted, keyline)
fmt.Println("\t" + grep(greeting, `<form id="contact-form" action="/`))
t.FailNow()
}
return
}
// TestEmailHandler tests that the URLKey allows sending message (later we test the mbox)
func TestEmailHandler(t *testing.T) {
verifyCaptcha = func(r *http.Request) bool { return true } // hack the captcha
//*logfile = os.DevNull
c2 := setup()
cwd, _ := os.Getwd()
c2.route(cwd)
ts := httptest.NewServer(c2.r)
defer ts.Close()
time.Sleep(100 * time.Millisecond)
res, err := http.Get(ts.URL)
if err != nil {
log.Fatal(err)
}
greeting, err := ioutil.ReadAll(res.Body)
res.Body.Close()
cut := strings.Split(string(greeting), `<p><img id="image" src="/captcha/`)
captcha := cut[1][:20]
v := &url.Values{}
v.Add("email", "[email protected]")
v.Add("subject", "hello world")
v.Add("message", "from test")
v.Add("cosgo", "123")
v.Add("captchaId", captcha)
res, err = http.PostForm(ts.URL+"/"+c2.URLKey+"/send", *v)
if err != nil {
fmt.Println(err)
t.FailNow()
}
greeting, err = ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
fmt.Println(err)
t.FailNow()
}
keyline := `Thanks! Your message was sent.`
if !strings.Contains(string(greeting), keyline) {
fmt.Println("\t"+redwanted, keyline)
fmt.Println("\t" + grep(greeting, `Your message`))
if *debug {
fmt.Println(string(greeting))
}
t.FailNow()
}
return
}
// TestEmailHandlerIncorrectKey tests that an incorrect URLKey doesn't work
func TestEmailHandlerIncorrectKey(t *testing.T) {
verifyCaptcha = func(r *http.Request) bool { return true } // hack the captcha
//*logfile = os.DevNull
c2 := setup()
cwd, _ := os.Getwd()
c2.route(cwd)
ts := httptest.NewServer(c2.r)
defer ts.Close()
time.Sleep(100 * time.Millisecond)
res, err := http.Get(ts.URL)
if err != nil {
log.Fatal(err)
}
greeting, err := ioutil.ReadAll(res.Body)
res.Body.Close()
cut := strings.Split(string(greeting), `<p><img id="image" src="/captcha/`)
captcha := cut[1][:20]
v := &url.Values{}
v.Add("email", "[email protected]")
v.Add("subject", "hello world")
v.Add("message", "bad user")
v.Add("cosgo", "123")
v.Add("captchaId", captcha)
time.Sleep(100 * time.Millisecond)
res, err = http.PostForm(ts.URL+"/fake"+c2.URLKey+"/send", *v)
if err != nil {
fmt.Println(err)
t.FailNow()
}
greeting, err = ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
fmt.Println(err)
t.FailNow()
}
keyline := `Your message was not sent: Bad endpoint.`
if !strings.Contains(string(greeting), keyline) {
fmt.Println("\t"+redwanted, keyline)
fmt.Println("\t" + grep(greeting, `Your message`))
if *debug {
fmt.Println(string(greeting))
}
t.FailNow()
}
//fmt.Println("\tFound it :)")
//fmt.Println()
return
}
// TestEmailHandlerIncorrectEmail tests that an incorrect email doesn't work
func TestEmailHandlerIncorrectEmail(t *testing.T) {
verifyCaptcha = func(r *http.Request) bool { return true } // hack the captcha
//*logfile = os.DevNull
c2 := setup()
cwd, _ := os.Getwd()
c2.route(cwd)
ts := httptest.NewServer(c2.r)
defer ts.Close()
time.Sleep(100 * time.Millisecond)
res, err := http.Get(ts.URL)
if err != nil {
log.Fatal(err)
}
greeting, err := ioutil.ReadAll(res.Body)
res.Body.Close()
cut := strings.Split(string(greeting), `<p><img id="image" src="/captcha/`)
captcha := cut[1][:20]
v := &url.Values{}
v.Add("email", "joejoe.com")
v.Add("subject", "hello world")
v.Add("message", "bad user")
v.Add("cosgo", "123")
v.Add("captchaId", captcha)
res, err = http.PostForm(ts.URL+"/"+c2.URLKey+"/send", *v)
if err != nil {
fmt.Println(err)
t.FailNow()
}
greeting, err = ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
fmt.Println(err)
t.FailNow()
}
keyline := `Your message was not sent: Bad email address.`
if !strings.Contains(string(greeting), keyline) {
fmt.Println("\t"+redwanted, keyline)
fmt.Println("\t" + grep(greeting, `Your message`))
if *debug {
fmt.Println(string(greeting))
}
t.FailNow()
}
// fmt.Println("\tFound it :)")
// fmt.Println()
return
}
// TestMbox tests only that the amount of bytes in the test mbox is 235.
// This test needs some work
func TestMbox(t *testing.T) {
b, e := ioutil.ReadFile(*mboxfile)
if e != nil {
fmt.Println(e)
os.Exit(2)
}
// Remove test mbox file
defer func() {
e = os.Remove(*mboxfile)
if e != nil {
t.FailNow()
}
}()
if len(b) != 235 {
fmt.Println(len(b), "!= 245")
t.FailNow()
}
// fmt.Println("\tContents of test mbox:", *mboxfile)
//fmt.Println(string(b))
fmt.Println("\tRemoving test mbox:", *mboxfile)
}
func TestAssets(t *testing.T) {
tmpdir, er := ioutil.TempDir(os.TempDir(), "cosgoTest")
if er != nil {
panic(er)
}
os.Chdir(tmpdir)
c2 := setup()
c2 = setup()
cwd, _ := os.Getwd()
c2.route(cwd)
files, e := ioutil.ReadDir(tmpdir)
if e != nil {
panic(e)
}
var static, template, mbox bool
for _, i := range files {
if i.Name() == "static" {
static = true
}
if i.Name() == "templates" {
template = true
}
if i.Name() == "testing.mbox" {
mbox = true
}
}
fmt.Println("\tCreated mbox:", mbox)
fmt.Println("\tCreated static:", static)
fmt.Println("\tCreated template dir:", template)
if !mbox || !template || !static {
t.FailNow()
}
}
// func TestMain(m *testing.M) {
// flag.Parse()
// os.Exit(m.Run())
// }
// TestEmailHandlerTimeout tests what happens after a refresh
func TestEmailHandlerTimeout(t *testing.T) {
verifyCaptcha = func(r *http.Request) bool { return true } // hack the captcha
//*logfile = os.DevNull
*refreshTime = 10 * time.Nanosecond // Really quick...
//flag.Parse()
c3 := setup() // Timer is started
cwd, _ := os.Getwd()
c3.route(cwd)
ts := httptest.NewServer(c3.r)
t1 := time.Now()
defer ts.Close()
res, err := http.Get(ts.URL)
if err != nil {
log.Fatal(err)
}
greeting, err := ioutil.ReadAll(res.Body)
res.Body.Close()
v := &url.Values{}
v.Add("email", "[email protected]")
v.Add("subject", "hello world")
v.Add("message", "from test")
fmt.Println("Fake:", captcha.New())
c3.rw.RLock()
oldkey := c3.URLKey
c3.rw.RUnlock()
var t2 time.Time
for {
time.Sleep(10 * time.Nanosecond)
// Wait for key to change
if oldkey != c3.URLKey {
t2 = time.Now()
break
}
}
fmt.Printf("Took %s to change keys\n", t2.Sub(t1))
res, err = http.PostForm(ts.URL+"/"+oldkey+"/send", *v)
if err != nil {
fmt.Println(err)
t.FailNow()
}
greeting, err = ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
fmt.Println(err)
t.FailNow()
}
keyline := `Your message was not sent: Bad endpoint.`
if !strings.Contains(string(greeting), keyline) {
fmt.Println("\t"+redwanted, keyline)
fmt.Println("\t" + grep(greeting, `Your message`))
if *debug {
fmt.Println(string(greeting))
}
t.FailNow()
}
// fmt.Println("\tFound it :)")
// fmt.Println()
return
}
// Test that this line does not break:
// 'cosgo -gpg /etc/aerth.asc -fastcgi -log cosgo.log -port 8089'
// Lots of flags: bind config debug fastcgi gpg log mbox new nolog port quiet sg title to
// No more breaking crontabs on cosgo upgrades!
// These flag tests need to be at the bottom of the test suite
func TestFlags(t *testing.T) {
// This causes some races so...
if !*debug {
return
}
const PanicOnError = true
devnull, _ := os.OpenFile(os.DevNull, os.O_WRONLY, 0700)
flag.CommandLine.SetOutput(devnull)
flag.CommandLine.Init("testflags", flag.ErrorHandling(2))
flag.Usage = func() {}
orig := os.Args
os.Args = []string{"cosgo", "-gpg", "/etc/aerth.asc", "-fastcgi", "-log", "cosgo.log", "-port", "8089"}
flag.Parse()
os.Args = []string{"cosgo", "-mbox", "test.mbox", "-bind", "0.0.0.0", "-debug"}
flag.Parse()
os.Args = []string{"cosgo", "-title", "Test Page", "-fastcgi", "-log", "cosgo.log", "-port", "8089"}
flag.Parse()
os.Args = []string{"cosgo", "-config", "/tmp/config.cosgo", "-nolog", "-sg", "sgkey123", "-to", "[email protected]"}
flag.Parse()
os.Args = orig
flag.Parse()
return
}
func TestBadFlags(t *testing.T) {
// Test that this line *does* break:
teststring := []string{"-bad"}
const ContinueOnError = true
devnull, _ := os.OpenFile(os.DevNull, os.O_WRONLY, 0700)
flag.CommandLine.SetOutput(devnull)
flag.Usage = func() {}
flag.CommandLine.Init("testflags", flag.ErrorHandling(0))
e := flag.CommandLine.Parse(teststring)
if e == nil {
fmt.Println("\tExpected Error. Got nil.")
t.FailNow()
} else if e.Error() == "flag provided but not defined: -bad" {
//
} else {
fmt.Println("\tExpected a different error:", e)
}
return
}