-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgokismet_test.go
1272 lines (1109 loc) · 42.4 KB
/
gokismet_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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package gokismet_test
import (
"errors"
"flag"
"fmt"
"io/ioutil"
"net/http"
"path"
"reflect"
"strings"
"testing"
"time"
"github.com/deepilla/gokismet"
)
// These flags allow the test runner to provide their Akismet
// credentials on the command line. This unlocks a secret set
// of tests that run against the live Akismet server.
//
// Note: We're relying on go test's flag parsing to set these
// values. Seems to work...
var flags = struct {
APIKey *string
Site *string
}{
flag.String("akismet.key", "", "your Akismet API Key"),
flag.String("akismet.site", "", "the website associated with your Akismet API Key"),
}
const (
TestAPIKey = "123456789abc"
TestSite = "http://example.com"
)
var UTCMinus5 = time.FixedZone("UTCMinus5", -5*60*60)
var (
fnCheck = (*gokismet.Checker).Check
fnReportHam = (*gokismet.Checker).ReportHam
fnReportSpam = (*gokismet.Checker).ReportSpam
)
type (
ErrorFunc func(*gokismet.Checker, map[string]string) error
StatusErrorFunc func(*gokismet.Checker, map[string]string) (gokismet.SpamStatus, error)
)
func toStatusErrorFunc(fn ErrorFunc) StatusErrorFunc {
return func(checker *gokismet.Checker, values map[string]string) (gokismet.SpamStatus, error) {
return gokismet.StatusUnknown, fn(checker, values)
}
}
func toErrorFunc(fn StatusErrorFunc) ErrorFunc {
return func(checker *gokismet.Checker, values map[string]string) error {
_, err := fn(checker, values)
return err
}
}
// A RequestInfo contains the pertinent parts of an HTTP Request
// (i.e. any values that gokismet explicitly sets when making
// calls to Akismet).
type RequestInfo struct {
Method string
URL string
HeaderItems map[string]string
Body string
}
// NewRequestInfo creates a RequestInfo from an HTTP Request.
// Note: This function consumes the Request body. Watch what
// you do with the Request afterwards.
func NewRequestInfo(req *http.Request) (*RequestInfo, error) {
info := &RequestInfo{
Method: req.Method,
URL: req.URL.String(),
}
for k, v := range req.Header {
if info.HeaderItems == nil {
info.HeaderItems = make(map[string]string)
}
info.HeaderItems[k] = strings.Join(v, "|")
}
if req.Body != nil {
defer req.Body.Close()
body, err := ioutil.ReadAll(req.Body)
if err != nil {
return nil, err
}
info.Body = string(body)
}
return info, nil
}
// A ResponseInfo contains the pertinent parts of an HTTP Response
// (i.e. any values in the Akismet response that gokismet uses).
type ResponseInfo struct {
StatusCode int
HeaderItems map[string]string
Body string
}
// NewResponse creates a barebones HTTP Response from a ResponseInfo.
func NewResponse(info *ResponseInfo) *http.Response {
resp := &http.Response{
StatusCode: info.StatusCode,
Status: fmt.Sprintf("%d %s", info.StatusCode, http.StatusText(info.StatusCode)),
Body: ioutil.NopCloser(strings.NewReader(info.Body)),
}
for k, v := range info.HeaderItems {
if resp.Header == nil {
resp.Header = make(http.Header)
}
resp.Header.Set(k, v)
}
return resp
}
// A RequestStore is a mock Client that captures the details
// of incoming requests.
type RequestStore struct {
Requests []*RequestInfo
}
// Do stores the details of the incoming request and returns
// a nil Response.
func (rs *RequestStore) Do(req *http.Request) (*http.Response, error) {
info, err := NewRequestInfo(req)
if err != nil {
return nil, err
}
rs.Requests = append(rs.Requests, info)
return nil, errors.New("RequestStore always returns a Nil Response")
}
// A Responder is a mock Client that responds to incoming requests
// according to user-defined responses.
type Responder struct {
Responses map[string]*ResponseInfo
}
// Do returns the user-defined response for the incoming request.
// If no response exists, Do returns an error.
func (r *Responder) Do(req *http.Request) (*http.Response, error) {
// Akismet URL format is https://rest.akismet.com/1.1/verify-key.
// The last part of the URL, as returned by path.Base, is the
// name of the API call.
call := path.Base(req.URL.Path)
info := r.Responses[call]
if info == nil {
return nil, fmt.Errorf("No response for %q", call)
}
return NewResponse(info), nil
}
// AddResponses adds another Responder's user-defined responses
// to this Responder.
func (r *Responder) AddResponses(in *Responder) {
for k, v := range in.Responses {
if r.Responses == nil {
r.Responses = make(map[string]*ResponseInfo)
}
r.Responses[k] = v
}
}
// verifyingResponder is a Responder that verifies API keys.
var verifyingResponder = &Responder{
map[string]*ResponseInfo{
"verify-key": {
Body: "valid",
StatusCode: http.StatusOK,
},
},
}
// A clientAdapter is a function that supplements an existing
// Client with additional functionality.
type clientAdapter func(gokismet.Client) gokismet.Client
// adaptClient applies a series of clientAdapters to a Client.
func adaptClient(client gokismet.Client, adapters ...clientAdapter) gokismet.Client {
for _, adapter := range adapters {
client = adapter(client)
}
return client
}
// withResponder returns a clientAdapter that calls the Do
// method of the original Client and then forwards the request
// to a Responder to generate the Response.
func withResponder(responder *Responder) clientAdapter {
return func(client gokismet.Client) gokismet.Client {
return gokismet.ClientFunc(func(req *http.Request) (*http.Response, error) {
client.Do(req)
return responder.Do(req)
})
}
}
// A FieldSetter uses reflection to set the fields of a struct.
type FieldSetter struct {
val reflect.Value
}
// NewFieldSetter takes a pointer to a struct and returns
// a FieldSetter that can set the fields of that struct.
func NewFieldSetter(val interface{}) *FieldSetter {
return &FieldSetter{reflect.Indirect(reflect.ValueOf(val))}
}
// Set sets the field with the given name to the given value.
func (c *FieldSetter) Set(name string, value interface{}) error {
// FieldByName panics if val is not a struct and
// returns a nil Value if the field does not exist.
f := c.val.FieldByName(name)
if !f.IsValid() {
return fmt.Errorf("Could not set field %s: field not found", name)
}
if !f.CanSet() {
return fmt.Errorf("Could not set field %s: field not settable", name)
}
// Set panics if the type of value does not match
// the field being set.
f.Set(reflect.ValueOf(value))
return nil
}
// NumFields returns the number of fields in the struct.
func (c *FieldSetter) NumFields() int {
return c.val.NumField()
}
// RequestTests defines test cases for the TestRequest and
// TestCommentValues functions.
var RequestTests = []struct {
// Name of a field in the Comment struct.
Field string
// Value to be assigned to the field.
Value interface{}
// Expected value of Comment.Values given
// a Comment with its fields set as above.
Values map[string]string
// Expected HTTP request body given the
// key-value pairs above.
Body string
}{
{
// NOTE: The blog parameter should default to the
// verified website if not explicitly set.
Body: "blog=http%3A%2F%2Fexample.com",
},
{
Field: "UserIP",
Value: "127.0.0.1",
Values: map[string]string{
"user_ip": "127.0.0.1",
},
Body: "blog=http%3A%2F%2Fexample.com&user_ip=127.0.0.1",
},
{
Field: "UserAgent",
Value: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36",
Values: map[string]string{
"user_ip": "127.0.0.1",
"user_agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36",
},
Body: "blog=http%3A%2F%2Fexample.com&user_agent=Mozilla%2F5.0+%28X11%3B+Linux+x86_64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F41.0.2227.0+Safari%2F537.36&user_ip=127.0.0.1",
},
{
Field: "Referer",
Value: "http://www.google.com",
Values: map[string]string{
"user_ip": "127.0.0.1",
"user_agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36",
"referrer": "http://www.google.com",
},
Body: "blog=http%3A%2F%2Fexample.com&referrer=http%3A%2F%2Fwww.google.com&user_agent=Mozilla%2F5.0+%28X11%3B+Linux+x86_64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F41.0.2227.0+Safari%2F537.36&user_ip=127.0.0.1",
},
{
Field: "Page",
Value: "http://example.com/posts/this-is-a-post/",
Values: map[string]string{
"user_ip": "127.0.0.1",
"user_agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36",
"referrer": "http://www.google.com",
"permalink": "http://example.com/posts/this-is-a-post/",
},
Body: "blog=http%3A%2F%2Fexample.com&permalink=http%3A%2F%2Fexample.com%2Fposts%2Fthis-is-a-post%2F&referrer=http%3A%2F%2Fwww.google.com&user_agent=Mozilla%2F5.0+%28X11%3B+Linux+x86_64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F41.0.2227.0+Safari%2F537.36&user_ip=127.0.0.1",
},
{
Field: "PageTimestamp",
// NOTE: Timestamps should be converted to UTC time.
Value: time.Date(2016, time.March, 31, 18, 27, 59, 0, UTCMinus5),
Values: map[string]string{
"user_ip": "127.0.0.1",
"user_agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36",
"referrer": "http://www.google.com",
"permalink": "http://example.com/posts/this-is-a-post/",
"comment_post_modified_gmt": "2016-03-31T23:27:59Z",
},
Body: "blog=http%3A%2F%2Fexample.com&comment_post_modified_gmt=2016-03-31T23%3A27%3A59Z&permalink=http%3A%2F%2Fexample.com%2Fposts%2Fthis-is-a-post%2F&referrer=http%3A%2F%2Fwww.google.com&user_agent=Mozilla%2F5.0+%28X11%3B+Linux+x86_64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F41.0.2227.0+Safari%2F537.36&user_ip=127.0.0.1",
},
{
Field: "Type",
Value: "comment",
Values: map[string]string{
"user_ip": "127.0.0.1",
"user_agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36",
"referrer": "http://www.google.com",
"permalink": "http://example.com/posts/this-is-a-post/",
"comment_post_modified_gmt": "2016-03-31T23:27:59Z",
"comment_type": "comment",
},
Body: "blog=http%3A%2F%2Fexample.com&comment_post_modified_gmt=2016-03-31T23%3A27%3A59Z&comment_type=comment&permalink=http%3A%2F%2Fexample.com%2Fposts%2Fthis-is-a-post%2F&referrer=http%3A%2F%2Fwww.google.com&user_agent=Mozilla%2F5.0+%28X11%3B+Linux+x86_64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F41.0.2227.0+Safari%2F537.36&user_ip=127.0.0.1",
},
{
Field: "Author",
Value: "Funny commenter name",
Values: map[string]string{
"user_ip": "127.0.0.1",
"user_agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36",
"referrer": "http://www.google.com",
"permalink": "http://example.com/posts/this-is-a-post/",
"comment_post_modified_gmt": "2016-03-31T23:27:59Z",
"comment_type": "comment",
"comment_author": "Funny commenter name",
},
Body: "blog=http%3A%2F%2Fexample.com&comment_author=Funny+commenter+name&comment_post_modified_gmt=2016-03-31T23%3A27%3A59Z&comment_type=comment&permalink=http%3A%2F%2Fexample.com%2Fposts%2Fthis-is-a-post%2F&referrer=http%3A%2F%2Fwww.google.com&user_agent=Mozilla%2F5.0+%28X11%3B+Linux+x86_64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F41.0.2227.0+Safari%2F537.36&user_ip=127.0.0.1",
},
{
Field: "AuthorEmail",
Value: "[email protected]",
Values: map[string]string{
"user_ip": "127.0.0.1",
"user_agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36",
"referrer": "http://www.google.com",
"permalink": "http://example.com/posts/this-is-a-post/",
"comment_post_modified_gmt": "2016-03-31T23:27:59Z",
"comment_type": "comment",
"comment_author": "Funny commenter name",
"comment_author_email": "[email protected]",
},
Body: "blog=http%3A%2F%2Fexample.com&comment_author=Funny+commenter+name&comment_author_email=first.last%40gmail.com&comment_post_modified_gmt=2016-03-31T23%3A27%3A59Z&comment_type=comment&permalink=http%3A%2F%2Fexample.com%2Fposts%2Fthis-is-a-post%2F&referrer=http%3A%2F%2Fwww.google.com&user_agent=Mozilla%2F5.0+%28X11%3B+Linux+x86_64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F41.0.2227.0+Safari%2F537.36&user_ip=127.0.0.1",
},
{
Field: "AuthorSite",
Value: "http://blog.domain.com",
Values: map[string]string{
"user_ip": "127.0.0.1",
"user_agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36",
"referrer": "http://www.google.com",
"permalink": "http://example.com/posts/this-is-a-post/",
"comment_post_modified_gmt": "2016-03-31T23:27:59Z",
"comment_type": "comment",
"comment_author": "Funny commenter name",
"comment_author_email": "[email protected]",
"comment_author_url": "http://blog.domain.com",
},
Body: "blog=http%3A%2F%2Fexample.com&comment_author=Funny+commenter+name&comment_author_email=first.last%40gmail.com&comment_author_url=http%3A%2F%2Fblog.domain.com&comment_post_modified_gmt=2016-03-31T23%3A27%3A59Z&comment_type=comment&permalink=http%3A%2F%2Fexample.com%2Fposts%2Fthis-is-a-post%2F&referrer=http%3A%2F%2Fwww.google.com&user_agent=Mozilla%2F5.0+%28X11%3B+Linux+x86_64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F41.0.2227.0+Safari%2F537.36&user_ip=127.0.0.1",
},
{
Field: "Content",
Value: "<p>This blog comment contains <strong>bold</strong> and <em>italic</em> text.</p>",
Values: map[string]string{
"user_ip": "127.0.0.1",
"user_agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36",
"referrer": "http://www.google.com",
"permalink": "http://example.com/posts/this-is-a-post/",
"comment_post_modified_gmt": "2016-03-31T23:27:59Z",
"comment_type": "comment",
"comment_author": "Funny commenter name",
"comment_author_email": "[email protected]",
"comment_author_url": "http://blog.domain.com",
"comment_content": "<p>This blog comment contains <strong>bold</strong> and <em>italic</em> text.</p>",
},
Body: "blog=http%3A%2F%2Fexample.com&comment_author=Funny+commenter+name&comment_author_email=first.last%40gmail.com&comment_author_url=http%3A%2F%2Fblog.domain.com&comment_content=%3Cp%3EThis+blog+comment+contains+%3Cstrong%3Ebold%3C%2Fstrong%3E+and+%3Cem%3Eitalic%3C%2Fem%3E+text.%3C%2Fp%3E&comment_post_modified_gmt=2016-03-31T23%3A27%3A59Z&comment_type=comment&permalink=http%3A%2F%2Fexample.com%2Fposts%2Fthis-is-a-post%2F&referrer=http%3A%2F%2Fwww.google.com&user_agent=Mozilla%2F5.0+%28X11%3B+Linux+x86_64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F41.0.2227.0+Safari%2F537.36&user_ip=127.0.0.1",
},
{
Field: "Timestamp",
// NOTE: Timestamps should be converted to UTC time.
Value: time.Date(2016, time.April, 1, 9, 0, 0, 0, UTCMinus5),
Values: map[string]string{
"user_ip": "127.0.0.1",
"user_agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36",
"referrer": "http://www.google.com",
"permalink": "http://example.com/posts/this-is-a-post/",
"comment_post_modified_gmt": "2016-03-31T23:27:59Z",
"comment_type": "comment",
"comment_author": "Funny commenter name",
"comment_author_email": "[email protected]",
"comment_author_url": "http://blog.domain.com",
"comment_content": "<p>This blog comment contains <strong>bold</strong> and <em>italic</em> text.</p>",
"comment_date_gmt": "2016-04-01T14:00:00Z",
},
Body: "blog=http%3A%2F%2Fexample.com&comment_author=Funny+commenter+name&comment_author_email=first.last%40gmail.com&comment_author_url=http%3A%2F%2Fblog.domain.com&comment_content=%3Cp%3EThis+blog+comment+contains+%3Cstrong%3Ebold%3C%2Fstrong%3E+and+%3Cem%3Eitalic%3C%2Fem%3E+text.%3C%2Fp%3E&comment_date_gmt=2016-04-01T14%3A00%3A00Z&comment_post_modified_gmt=2016-03-31T23%3A27%3A59Z&comment_type=comment&permalink=http%3A%2F%2Fexample.com%2Fposts%2Fthis-is-a-post%2F&referrer=http%3A%2F%2Fwww.google.com&user_agent=Mozilla%2F5.0+%28X11%3B+Linux+x86_64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F41.0.2227.0+Safari%2F537.36&user_ip=127.0.0.1",
},
{
Field: "Site",
// NOTE: Websites specified in the comment data should override the default website.
Value: "http://anothersite.com",
Values: map[string]string{
"user_ip": "127.0.0.1",
"user_agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36",
"referrer": "http://www.google.com",
"permalink": "http://example.com/posts/this-is-a-post/",
"comment_post_modified_gmt": "2016-03-31T23:27:59Z",
"comment_type": "comment",
"comment_author": "Funny commenter name",
"comment_author_email": "[email protected]",
"comment_author_url": "http://blog.domain.com",
"comment_content": "<p>This blog comment contains <strong>bold</strong> and <em>italic</em> text.</p>",
"comment_date_gmt": "2016-04-01T14:00:00Z",
"blog": "http://anothersite.com",
},
Body: "blog=http%3A%2F%2Fanothersite.com&comment_author=Funny+commenter+name&comment_author_email=first.last%40gmail.com&comment_author_url=http%3A%2F%2Fblog.domain.com&comment_content=%3Cp%3EThis+blog+comment+contains+%3Cstrong%3Ebold%3C%2Fstrong%3E+and+%3Cem%3Eitalic%3C%2Fem%3E+text.%3C%2Fp%3E&comment_date_gmt=2016-04-01T14%3A00%3A00Z&comment_post_modified_gmt=2016-03-31T23%3A27%3A59Z&comment_type=comment&permalink=http%3A%2F%2Fexample.com%2Fposts%2Fthis-is-a-post%2F&referrer=http%3A%2F%2Fwww.google.com&user_agent=Mozilla%2F5.0+%28X11%3B+Linux+x86_64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F41.0.2227.0+Safari%2F537.36&user_ip=127.0.0.1",
},
{
Field: "SiteLanguage",
Value: "en_us",
Values: map[string]string{
"user_ip": "127.0.0.1",
"user_agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36",
"referrer": "http://www.google.com",
"permalink": "http://example.com/posts/this-is-a-post/",
"comment_post_modified_gmt": "2016-03-31T23:27:59Z",
"comment_type": "comment",
"comment_author": "Funny commenter name",
"comment_author_email": "[email protected]",
"comment_author_url": "http://blog.domain.com",
"comment_content": "<p>This blog comment contains <strong>bold</strong> and <em>italic</em> text.</p>",
"comment_date_gmt": "2016-04-01T14:00:00Z",
"blog": "http://anothersite.com",
"blog_lang": "en_us",
},
Body: "blog=http%3A%2F%2Fanothersite.com&blog_lang=en_us&comment_author=Funny+commenter+name&comment_author_email=first.last%40gmail.com&comment_author_url=http%3A%2F%2Fblog.domain.com&comment_content=%3Cp%3EThis+blog+comment+contains+%3Cstrong%3Ebold%3C%2Fstrong%3E+and+%3Cem%3Eitalic%3C%2Fem%3E+text.%3C%2Fp%3E&comment_date_gmt=2016-04-01T14%3A00%3A00Z&comment_post_modified_gmt=2016-03-31T23%3A27%3A59Z&comment_type=comment&permalink=http%3A%2F%2Fexample.com%2Fposts%2Fthis-is-a-post%2F&referrer=http%3A%2F%2Fwww.google.com&user_agent=Mozilla%2F5.0+%28X11%3B+Linux+x86_64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F41.0.2227.0+Safari%2F537.36&user_ip=127.0.0.1",
},
{
Field: "SiteCharset",
Value: "UTF-8",
Values: map[string]string{
"user_ip": "127.0.0.1",
"user_agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36",
"referrer": "http://www.google.com",
"permalink": "http://example.com/posts/this-is-a-post/",
"comment_post_modified_gmt": "2016-03-31T23:27:59Z",
"comment_type": "comment",
"comment_author": "Funny commenter name",
"comment_author_email": "[email protected]",
"comment_author_url": "http://blog.domain.com",
"comment_content": "<p>This blog comment contains <strong>bold</strong> and <em>italic</em> text.</p>",
"comment_date_gmt": "2016-04-01T14:00:00Z",
"blog": "http://anothersite.com",
"blog_lang": "en_us",
"blog_charset": "UTF-8",
},
Body: "blog=http%3A%2F%2Fanothersite.com&blog_charset=UTF-8&blog_lang=en_us&comment_author=Funny+commenter+name&comment_author_email=first.last%40gmail.com&comment_author_url=http%3A%2F%2Fblog.domain.com&comment_content=%3Cp%3EThis+blog+comment+contains+%3Cstrong%3Ebold%3C%2Fstrong%3E+and+%3Cem%3Eitalic%3C%2Fem%3E+text.%3C%2Fp%3E&comment_date_gmt=2016-04-01T14%3A00%3A00Z&comment_post_modified_gmt=2016-03-31T23%3A27%3A59Z&comment_type=comment&permalink=http%3A%2F%2Fexample.com%2Fposts%2Fthis-is-a-post%2F&referrer=http%3A%2F%2Fwww.google.com&user_agent=Mozilla%2F5.0+%28X11%3B+Linux+x86_64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F41.0.2227.0+Safari%2F537.36&user_ip=127.0.0.1",
},
}
// TestNewCheckers verifies that NewChecker and NewCheckerClient
// work as expected.
func TestNewCheckers(t *testing.T) {
// The following calls should be functionally equivalent.
ch1 := gokismet.NewChecker(TestAPIKey, TestSite)
ch2 := gokismet.NewCheckerClient(TestAPIKey, TestSite, nil)
ch3 := gokismet.NewCheckerClient(TestAPIKey, TestSite, http.DefaultClient)
if ch1 == ch2 || ch1 == ch3 || ch2 == ch3 {
t.Errorf("NewChecker functions should create distinct Checkers")
}
if *ch1 != *ch3 {
t.Errorf("Calling NewChecker should be the same as calling NewCheckerClient with the default client")
}
if *ch2 != *ch3 {
t.Errorf("Calling NewCheckerClient with a nil Client should be the same as calling it with the default client")
}
}
// TestCommentValues verifies that Comment.Values generates the
// correct key-value pairs.
func TestCommentValues(t *testing.T) {
comment := &gokismet.Comment{}
fields := NewFieldSetter(comment)
// RequestTests should have one test case for each Comment
// field plus an extra test case for when no fields are set.
if exp := fields.NumFields() + 1; len(RequestTests) != exp {
t.Fatalf("Test data is invalid: expected %d tests, got %d", exp, len(RequestTests))
}
compareValues := compareStringMap("key-value pair(s)")
// Set the Comment fields one at a time and check that
// Comment.Values returns the expected key-value pairs.
for i, test := range RequestTests {
if test.Field != "" {
if err := fields.Set(test.Field, test.Value); err != nil {
t.Fatalf("Test %d: %s", i+1, err)
}
}
errors := compareValues(test.Values, comment.Values())
for _, err := range errors {
t.Errorf("Test %d: %s", i+1, err)
}
}
}
// TestRequest_Check verifies that Checker.Check produces
// well-formed HTTP requests.
func TestRequest_Check(t *testing.T) {
fn := toErrorFunc(fnCheck)
url := "https://123456789abc.rest.akismet.com/1.1/comment-check"
testRequest(t, fn, url)
}
// TestRequest_ReportHam verifies that Checker.ReportHam produces
// well-formed HTTP requests.
func TestRequest_ReportHam(t *testing.T) {
fn := fnReportHam
url := "https://123456789abc.rest.akismet.com/1.1/submit-ham"
testRequest(t, fn, url)
}
// TestRequest_ReportSpam verifies that Checker.ReportSpam produces
// well-formed HTTP requests.
func TestRequest_ReportSpam(t *testing.T) {
fn := fnReportSpam
url := "https://123456789abc.rest.akismet.com/1.1/submit-spam"
testRequest(t, fn, url)
}
// testRequest verifies that HTTP requests for the given Checker
// method are well-formed.
func testRequest(t *testing.T, fn ErrorFunc, expectedURL string) {
client := &RequestStore{}
verifyingClient := adaptClient(client, withResponder(verifyingResponder))
ch := gokismet.NewCheckerClient(TestAPIKey, TestSite, verifyingClient)
// For each test case in the request test data, call the
// Checker method with the test's key-value pairs and
// validate the resulting request.
for i, test := range RequestTests {
fn(ch, test.Values)
// The first method call generates two requests: one to
// verify the API key and one to actually make the call.
// All subsequent method calls add one request to the
// RequestStore. So when i == 0 we should have 2 requests
// in the RequestStore. When i == 1 we should have 3, and
// so on...
if len(client.Requests) != i+2 {
t.Fatalf("Test %d: Expected %d request(s), got %d", i+1, i+2, len(client.Requests))
}
var errors []error
// Check the verify key request from the first method call.
// We only need to do this once.
if i == 0 {
exp := requestInfoFor("https://rest.akismet.com/1.1/verify-key", "blog=http%3A%2F%2Fexample.com&key=123456789abc")
errors = append(errors, compareRequestInfo(exp, client.Requests[0])...)
}
// Check the request from the most recent method call.
exp := requestInfoFor(expectedURL, test.Body)
errors = append(errors, compareRequestInfo(exp, client.Requests[i+1])...)
for _, err := range errors {
t.Errorf("Test %d: %s", i+1, err)
}
}
}
// requestInfoFor returns the expected request data for a given
// Akismet endpoint URL and query string.
func requestInfoFor(url, body string) *RequestInfo {
return &RequestInfo{
Method: "POST",
URL: url,
HeaderItems: map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "Gokismet/3.0",
},
Body: body,
}
}
// A ResponseTest defines a test case for the TestResponse functions.
type ResponseTest struct {
// Does this test need a verified API key?
IsVerified bool
// Mock Akismet responses to feed into gokismet.
Responses map[string]*ResponseInfo
// The expected spam status given the responses above.
SpamStatus gokismet.SpamStatus
// The expected error given the responses above.
Error error
}
// sharedResponseTests returns the ResponseTest cases that are common
// to all three Checker methods.
func sharedResponseTests(method string) []ResponseTest {
return []ResponseTest{
{
// Error while verifying the API key.
Error: errors.New(`No response for "verify-key"`),
},
{
// Non-200 HTTP status while verifying the API key.
Responses: map[string]*ResponseInfo{
"verify-key": {
StatusCode: http.StatusMovedPermanently,
},
},
Error: errors.New("301 Moved Permanently returned from https://rest.akismet.com/1.1/verify-key"),
},
{
// API key not verified.
Responses: map[string]*ResponseInfo{
"verify-key": {
Body: "invalid",
StatusCode: http.StatusOK,
},
},
Error: &gokismet.KeyError{
Key: "123456789abc",
Site: "http://example.com",
ValError: &gokismet.ValError{
Method: "verify-key",
Response: "invalid",
},
},
},
{
// API key not verified with help message.
Responses: map[string]*ResponseInfo{
"verify-key": {
Body: "invalid",
StatusCode: http.StatusOK,
HeaderItems: map[string]string{
"X-akismet-debug-help": "A helpful diagnostic message",
},
},
},
Error: &gokismet.KeyError{
Key: "123456789abc",
Site: "http://example.com",
ValError: &gokismet.ValError{
Method: "verify-key",
Response: "invalid",
Hint: "A helpful diagnostic message",
},
},
},
{
// Error during Akismet call.
IsVerified: true,
Error: errors.New("No response for \"" + method + "\""),
},
{
// Non-200 HTTP status from Akismet call.
IsVerified: true,
Responses: map[string]*ResponseInfo{
method: {
StatusCode: http.StatusInternalServerError,
},
},
Error: errors.New("500 Internal Server Error returned from https://123456789abc.rest.akismet.com/1.1/" + method),
},
{
// Unexpected return value from Akismet call.
IsVerified: true,
Responses: map[string]*ResponseInfo{
method: {
Body: "invalid",
StatusCode: http.StatusOK,
},
},
Error: &gokismet.ValError{
Method: method,
Response: "invalid",
},
},
{
// Unexpected return value with help message.
IsVerified: true,
Responses: map[string]*ResponseInfo{
method: {
Body: "invalid",
StatusCode: http.StatusOK,
HeaderItems: map[string]string{
"X-akismet-debug-help": "A helpful diagnostic message",
},
},
},
Error: &gokismet.ValError{
Method: method,
Response: "invalid",
Hint: "A helpful diagnostic message",
},
},
}
}
// TestResponse_Check verifies that Checker.Check returns the
// correct values for various Akismet responses.
func TestResponse_Check(t *testing.T) {
checkTests := []ResponseTest{
{
// Negative spam response.
IsVerified: true,
Responses: map[string]*ResponseInfo{
"comment-check": {
Body: "false",
StatusCode: http.StatusOK,
},
},
SpamStatus: gokismet.StatusHam,
},
{
// Positive spam response.
IsVerified: true,
Responses: map[string]*ResponseInfo{
"comment-check": {
Body: "true",
StatusCode: http.StatusOK,
},
},
SpamStatus: gokismet.StatusProbableSpam,
},
{
// Pervasive spam response.
IsVerified: true,
Responses: map[string]*ResponseInfo{
"comment-check": {
Body: "true",
StatusCode: http.StatusOK,
HeaderItems: map[string]string{
"X-akismet-pro-tip": "discard",
},
},
},
SpamStatus: gokismet.StatusDefiniteSpam,
},
}
tests := sharedResponseTests("comment-check")
tests = append(tests, checkTests...)
testResponse(t, fnCheck, tests)
}
// TestResponse_ReportHam verifies that Checker.ReportHam
// returns the correct values for various Akismet responses.
func TestResponse_ReportHam(t *testing.T) {
testResponse_Report(t, "submit-ham", fnReportHam)
}
// TestResponse_ReportSpam verifies that Checker.ReportSpam
// returns the correct values for various Akismet responses.
func TestResponse_ReportSpam(t *testing.T) {
testResponse_Report(t, "submit-spam", fnReportSpam)
}
// testResponse_Report handles the heavy lifting for the
// TestResponse_ReportHam and TestResponse_ReportSpam functions.
func testResponse_Report(t *testing.T, method string, submit ErrorFunc) {
reportTests := []ResponseTest{
{
// Success response.
IsVerified: true,
Responses: map[string]*ResponseInfo{
method: {
Body: "Thanks for making the web a better place.",
StatusCode: http.StatusOK,
},
},
},
}
tests := sharedResponseTests(method)
tests = append(tests, reportTests...)
testResponse(t, toStatusErrorFunc(submit), tests)
}
// testResponse verifies that a Checker method returns the
// correct values for the Akismet responses provided.
func testResponse(t *testing.T, fn StatusErrorFunc, tests []ResponseTest) {
for i, test := range tests {
client := &Responder{
Responses: test.Responses,
}
if test.IsVerified {
client.AddResponses(verifyingResponder)
}
ch := gokismet.NewCheckerClient(TestAPIKey, TestSite, client)
status, err := fn(ch, nil)
if status != test.SpamStatus {
t.Errorf("Test %d: Expected Spam Status %q, got %q", i+1,
statusToString(test.SpamStatus), statusToString(status))
}
errors := compareError(test.Error, err)
for _, err := range errors {
t.Errorf("Test %d: %s", i+1, err)
}
}
}
// TestError_ValError tests string formatting for the ValError
// type.
func TestError_ValError(t *testing.T) {
tests := []struct {
Method string
Response string
Hint string
Expected string
}{
{
Method: "comment-check",
Expected: `comment-check returned an empty string (expected true or false)`,
},
{
Method: "comment-check",
Hint: "A helpful diagnostic message",
Expected: `comment-check returned an empty string (A helpful diagnostic message)`,
},
{
Method: "comment-check",
Response: "invalid",
Expected: `comment-check returned "invalid" (expected true or false)`,
},
{
Method: "comment-check",
Response: "invalid",
Hint: "A helpful diagnostic message",
Expected: `comment-check returned "invalid" (A helpful diagnostic message)`,
},
{
Method: "submit-ham",
Expected: `submit-ham returned an empty string (expected a thank you message)`,
},
{
Method: "submit-ham",
Hint: "A helpful diagnostic message",
Expected: `submit-ham returned an empty string (A helpful diagnostic message)`,
},
{
Method: "submit-ham",
Response: "invalid",
Expected: `submit-ham returned "invalid" (expected a thank you message)`,
},
{
Method: "submit-ham",
Response: "invalid",
Hint: "A helpful diagnostic message",
Expected: `submit-ham returned "invalid" (A helpful diagnostic message)`,
},
{
Method: "submit-spam",
Expected: `submit-spam returned an empty string (expected a thank you message)`,
},
{
Method: "submit-spam",
Hint: "A helpful diagnostic message",
Expected: `submit-spam returned an empty string (A helpful diagnostic message)`,
},
{
Method: "submit-spam",
Response: "invalid",
Expected: `submit-spam returned "invalid" (expected a thank you message)`,
},
{
Method: "submit-spam",
Response: "invalid",
Hint: "A helpful diagnostic message",
Expected: `submit-spam returned "invalid" (A helpful diagnostic message)`,
},
}
for i, test := range tests {
err := gokismet.ValError{
Method: test.Method,
Response: test.Response,
Hint: test.Hint,
}
if got := err.Error(); got != test.Expected {
t.Errorf("Test %d: Expected %q, got %q", i+1, test.Expected, got)
}
}
}
// TestError_KeyError tests string formatting for the KeyError
// type.
func TestError_KeyError(t *testing.T) {
tests := []struct {
Response string
Hint string
Expected string
}{
{
Expected: `key 123456789abc not verified: verify-key returned an empty string`,
},
{
Hint: "A helpful diagnostic message",
Expected: `key 123456789abc not verified: verify-key returned an empty string (A helpful diagnostic message)`,
},
{
Response: "invalid",
Expected: `key 123456789abc not verified: verify-key returned "invalid"`,
},
{
Response: "invalid",
Hint: "A helpful diagnostic message",
Expected: `key 123456789abc not verified: verify-key returned "invalid" (A helpful diagnostic message)`,
},
}
for i, test := range tests {
err := gokismet.KeyError{
Key: TestAPIKey,
Site: TestSite,
ValError: &gokismet.ValError{
Method: "verify-key",
Response: test.Response,
Hint: test.Hint,
},
}
if got := err.Error(); got != test.Expected {
t.Errorf("Test %d: Expected %q, got %q", i+1, test.Expected, got)
}
}
}
// An AkismetTest defines a test case for the TestAkismet
// functions.
type AkismetTest struct {
// Additional comment parameters to pass to Akismet.
Params map[string]string
// Expected spam status returned by gokismet.
SpamStatus gokismet.SpamStatus
// Expected error returned by gokismet.
Error error
}
// TestAkismet_Check uses the live Akismet API to validate
// the results of the Checker.Check method.
func TestAkismet_Check(t *testing.T) {
tests := []AkismetTest{
{