forked from PostHog/posthog-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
posthog_test.go
969 lines (809 loc) · 24.1 KB
/
posthog_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
package posthog
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// Helper type used to implement the io.Reader interface on function values.
type readFunc func([]byte) (int, error)
func (f readFunc) Read(b []byte) (int, error) { return f(b) }
// Helper type used to implement the http.RoundTripper interface on function
// values.
type roundTripperFunc func(*http.Request) (*http.Response, error)
func (f roundTripperFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
func (f roundTripperFunc) CancelRequest(r *http.Request) {}
// Instances of this type are used to mock the client callbacks in unit tests.
type testCallback struct {
success func(APIMessage)
failure func(APIMessage, error)
}
func (c testCallback) Success(m APIMessage) {
if c.success != nil {
c.success(m)
}
}
func (c testCallback) Failure(m APIMessage, e error) {
if c.failure != nil {
c.failure(m, e)
}
}
// Instances of this type are used to mock the client logger in unit tests.
type testLogger struct {
logf func(string, ...interface{})
errorf func(string, ...interface{})
}
func (l testLogger) Logf(format string, args ...interface{}) {
if l.logf != nil {
l.logf(format, args...)
}
}
func (l testLogger) Errorf(format string, args ...interface{}) {
if l.errorf != nil {
l.errorf(format, args...)
}
}
var _ Message = (*testErrorMessage)(nil)
// Instances of this type are used to force message validation errors in unit
// tests.
type testErrorMessage struct{}
type testAPIErrorMessage struct{}
func (m testErrorMessage) internal() {
}
func (m testErrorMessage) Validate() error { return testError }
func (m testErrorMessage) APIfy() APIMessage {
return testAPIErrorMessage{}
}
var (
// A control error returned by mock functions to emulate a failure.
//lint:ignore ST1012 variable name is fine :D
testError = errors.New("test error")
// HTTP transport that always succeeds.
testTransportOK = roundTripperFunc(func(r *http.Request) (*http.Response, error) {
return &http.Response{
Status: http.StatusText(http.StatusOK),
StatusCode: http.StatusOK,
Proto: r.Proto,
ProtoMajor: r.ProtoMajor,
ProtoMinor: r.ProtoMinor,
Body: ioutil.NopCloser(strings.NewReader("")),
Request: r,
}, nil
})
// HTTP transport that sleeps for a little while and eventually succeeds.
testTransportDelayed = roundTripperFunc(func(r *http.Request) (*http.Response, error) {
time.Sleep(10 * time.Millisecond)
return testTransportOK.RoundTrip(r)
})
// HTTP transport that always returns a 400.
testTransportBadRequest = roundTripperFunc(func(r *http.Request) (*http.Response, error) {
return &http.Response{
Status: http.StatusText(http.StatusBadRequest),
StatusCode: http.StatusBadRequest,
Proto: r.Proto,
ProtoMajor: r.ProtoMajor,
ProtoMinor: r.ProtoMinor,
Body: ioutil.NopCloser(strings.NewReader("")),
Request: r,
}, nil
})
// HTTP transport that always returns a 400 with an erroring body reader.
testTransportBodyError = roundTripperFunc(func(r *http.Request) (*http.Response, error) {
return &http.Response{
Status: http.StatusText(http.StatusBadRequest),
StatusCode: http.StatusBadRequest,
Proto: r.Proto,
ProtoMajor: r.ProtoMajor,
ProtoMinor: r.ProtoMinor,
Body: ioutil.NopCloser(readFunc(func(b []byte) (int, error) { return 0, testError })),
Request: r,
}, nil
})
// HTTP transport that always return an error.
testTransportError = roundTripperFunc(func(r *http.Request) (*http.Response, error) {
return nil, testError
})
)
func fixture(name string) string {
f, err := os.Open(filepath.Join("fixtures", name))
if err != nil {
panic(err)
}
defer f.Close()
b, err := ioutil.ReadAll(f)
if err != nil {
panic(err)
}
return string(b)
}
func mockId() string { return "I'm unique" }
func mockTime() time.Time {
// time.Unix(0, 0) fails on Circle
return time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
}
func mockServer() (chan []byte, *httptest.Server) {
done := make(chan []byte, 1)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
buf := bytes.NewBuffer(nil)
io.Copy(buf, r.Body)
var v interface{}
err := json.Unmarshal(buf.Bytes(), &v)
if err != nil {
panic(err)
}
b, err := json.MarshalIndent(v, "", " ")
if err != nil {
panic(err)
}
done <- b
}))
return done, server
}
func ExampleCapture() {
body, server := mockServer()
defer server.Close()
client, _ := NewWithConfig("Csyjlnlun3OzyNJAafdlv", Config{
Endpoint: server.URL,
BatchSize: 1,
now: mockTime,
uid: mockId,
})
defer client.Close()
client.Enqueue(Capture{
Event: "Download",
DistinctId: "123456",
Properties: Properties{
"application": "PostHog Go",
"version": "1.0.0",
"platform": "macos", // :)
},
SendFeatureFlags: false,
})
fmt.Printf("%s\n", <-body)
// Output:
// {
// "api_key": "Csyjlnlun3OzyNJAafdlv",
// "batch": [
// {
// "distinct_id": "123456",
// "event": "Download",
// "library": "posthog-go",
// "library_version": "1.0.0",
// "properties": {
// "$lib": "posthog-go",
// "$lib_version": "1.0.0",
// "application": "PostHog Go",
// "platform": "macos",
// "version": "1.0.0"
// },
// "send_feature_flags": false,
// "timestamp": "2009-11-10T23:00:00Z",
// "type": "capture"
// }
// ]
// }
}
func TestEnqueue(t *testing.T) {
tests := map[string]struct {
ref string
msg Message
}{
"alias": {
strings.TrimSpace(fixture("test-enqueue-alias.json")),
Alias{Alias: "A", DistinctId: "B"},
},
"identify": {
strings.TrimSpace(fixture("test-enqueue-identify.json")),
Identify{
DistinctId: "B",
Properties: Properties{"email": "[email protected]"},
},
},
"groupIdentify": {
strings.TrimSpace(fixture("test-enqueue-group-identify.json")),
GroupIdentify{
DistinctId: "$organization_id:5",
Type: "organization",
Key: "id:5",
Properties: Properties{},
},
},
"capture": {
strings.TrimSpace(fixture("test-enqueue-capture.json")),
Capture{
Event: "Download",
DistinctId: "123456",
Properties: Properties{
"application": "PostHog Go",
"version": "1.0.0",
"platform": "macos", // :)
},
SendFeatureFlags: false,
},
},
"*alias": {
strings.TrimSpace(fixture("test-enqueue-alias.json")),
&Alias{Alias: "A", DistinctId: "B"},
},
"*identify": {
strings.TrimSpace(fixture("test-enqueue-identify.json")),
&Identify{
DistinctId: "B",
Properties: Properties{"email": "[email protected]"},
},
},
"*groupIdentify": {
strings.TrimSpace(fixture("test-enqueue-group-identify.json")),
&GroupIdentify{
DistinctId: "$organization_id:5",
Type: "organization",
Key: "id:5",
Properties: Properties{},
},
},
"*capture": {
strings.TrimSpace(fixture("test-enqueue-capture.json")),
&Capture{
Event: "Download",
DistinctId: "123456",
Properties: Properties{
"application": "PostHog Go",
"version": "1.0.0",
"platform": "macos", // :)
},
SendFeatureFlags: false,
},
},
}
body, server := mockServer()
defer server.Close()
client, _ := NewWithConfig("Csyjlnlun3OzyNJAafdlv", Config{
Endpoint: server.URL,
Verbose: true,
Logger: t,
BatchSize: 1,
now: mockTime,
uid: mockId,
})
defer client.Close()
for name, test := range tests {
if err := client.Enqueue(test.msg); err != nil {
t.Error(err)
return
}
if res := string(<-body); res != test.ref {
t.Errorf("%s: invalid response:\n- expected %s\n- received: %s", name, test.ref, res)
}
}
}
var _ Message = (*customMessage)(nil)
type customMessage struct {
}
type customAPIMessage struct {
}
func (c *customMessage) internal() {
}
func (c *customMessage) Validate() error {
return nil
}
func (c *customMessage) APIfy() APIMessage {
return customAPIMessage{}
}
func TestEnqueuingCustomTypeFails(t *testing.T) {
client := New("0123456789")
err := client.Enqueue(&customMessage{})
if err.Error() != "messages with custom types cannot be enqueued: *posthog.customMessage" {
t.Errorf("invalid/missing error when queuing unsupported message: %v", err)
}
}
func TestCaptureWithInterval(t *testing.T) {
const interval = 100 * time.Millisecond
var ref = strings.TrimSpace(fixture("test-interval-capture.json"))
body, server := mockServer()
defer server.Close()
t0 := time.Now()
client, _ := NewWithConfig("Csyjlnlun3OzyNJAafdlv", Config{
Endpoint: server.URL,
Interval: interval,
Verbose: true,
Logger: t,
now: mockTime,
uid: mockId,
})
defer client.Close()
client.Enqueue(Capture{
Event: "Download",
DistinctId: "123456",
Properties: Properties{
"application": "PostHog Go",
"version": "1.0.0",
"platform": "macos", // :)
},
SendFeatureFlags: false,
})
// Will flush in 100 milliseconds
if res := string(<-body); ref != res {
t.Errorf("invalid response:\n- expected %s\n- received: %s", ref, res)
}
if t1 := time.Now(); t1.Sub(t0) < interval {
t.Error("the flushing interval is too short:", interval)
}
}
func TestCaptureWithTimestamp(t *testing.T) {
var ref = strings.TrimSpace(fixture("test-timestamp-capture.json"))
body, server := mockServer()
defer server.Close()
client, _ := NewWithConfig("Csyjlnlun3OzyNJAafdlv", Config{
Endpoint: server.URL,
Verbose: true,
Logger: t,
BatchSize: 1,
now: mockTime,
uid: mockId,
})
defer client.Close()
client.Enqueue(Capture{
Event: "Download",
DistinctId: "123456",
Properties: Properties{
"application": "PostHog Go",
"version": "1.0.0",
"platform": "macos", // :)
},
SendFeatureFlags: false,
Timestamp: time.Date(2015, time.July, 10, 23, 0, 0, 0, time.UTC),
})
if res := string(<-body); ref != res {
t.Errorf("invalid response:\n- expected %s\n- received: %s", ref, res)
}
}
func TestCaptureMany(t *testing.T) {
var ref = strings.TrimSpace(fixture("test-many-capture.json"))
body, server := mockServer()
defer server.Close()
client, _ := NewWithConfig("Csyjlnlun3OzyNJAafdlv", Config{
Endpoint: server.URL,
Verbose: true,
Logger: t,
BatchSize: 3,
now: mockTime,
uid: mockId,
})
defer client.Close()
for i := 0; i < 5; i++ {
client.Enqueue(Capture{
Event: "Download",
DistinctId: "123456",
Properties: Properties{
"application": "PostHog Go",
"version": i,
},
SendFeatureFlags: false,
})
}
if res := string(<-body); ref != res {
t.Errorf("invalid response:\n- expected %s\n- received: %s", ref, res)
}
}
func TestClientCloseTwice(t *testing.T) {
client := New("0123456789")
if err := client.Close(); err != nil {
t.Error("closing a client should not a return an error")
}
if err := client.Close(); err != ErrClosed {
t.Error("closing a client a second time should return ErrClosed:", err)
}
if err := client.Enqueue(Capture{DistinctId: "1", Event: "A"}); err != ErrClosed {
t.Error("using a client after it was closed should return ErrClosed:", err)
}
}
func TestClientConfigError(t *testing.T) {
client, err := NewWithConfig("0123456789", Config{
Interval: -1 * time.Second,
})
if err == nil {
t.Error("no error returned when creating a client with an invalid config")
}
if _, ok := err.(ConfigError); !ok {
t.Errorf("invalid error type returned when creating a client with an invalid config: %T", err)
}
if client != nil {
t.Error("invalid non-nil client object returned when creating a client with and invalid config:", client)
client.Close()
}
}
func TestClientEnqueueError(t *testing.T) {
client := New("0123456789")
defer client.Close()
if err := client.Enqueue(testErrorMessage{}); err != testError {
t.Error("invlaid error returned when queueing an invalid message:", err)
}
}
func TestClientCallback(t *testing.T) {
reschan := make(chan bool, 1)
errchan := make(chan error, 1)
client, _ := NewWithConfig("0123456789", Config{
Logger: testLogger{t.Logf, t.Logf},
Callback: testCallback{
func(m APIMessage) { reschan <- true },
func(m APIMessage, e error) { errchan <- e },
},
Transport: testTransportOK,
})
client.Enqueue(Capture{
DistinctId: "A",
Event: "B",
})
client.Close()
select {
case <-reschan:
case err := <-errchan:
t.Error("failure callback triggered:", err)
}
}
func TestClientMarshalMessageError(t *testing.T) {
errchan := make(chan error, 1)
client, _ := NewWithConfig("0123456789", Config{
Logger: testLogger{t.Logf, t.Logf},
Callback: testCallback{
nil,
func(m APIMessage, e error) { errchan <- e },
},
Transport: testTransportOK,
})
// Functions cannot be serializable, this should break the JSON marshaling
// and trigger the failure callback.
client.Enqueue(Capture{
DistinctId: "A",
Event: "B",
Properties: Properties{"invalid": func() {}},
})
client.Close()
if err := <-errchan; err == nil {
t.Error("failure callback not triggered for unserializable message")
} else if _, ok := err.(*json.UnsupportedTypeError); !ok {
t.Errorf("invalid error type returned by unserializable message: %T", err)
}
}
func TestClientNewRequestError(t *testing.T) {
errchan := make(chan error, 1)
client, _ := NewWithConfig("0123456789", Config{
Endpoint: "://localhost:80", // Malformed endpoint URL.
Logger: testLogger{t.Logf, t.Logf},
Callback: testCallback{
nil,
func(m APIMessage, e error) { errchan <- e },
},
Transport: testTransportOK,
})
client.Enqueue(Capture{DistinctId: "A", Event: "B"})
client.Close()
if err := <-errchan; err == nil {
t.Error("failure callback not triggered for an invalid request")
}
}
func TestClientRoundTripperError(t *testing.T) {
errchan := make(chan error, 1)
client, _ := NewWithConfig("0123456789", Config{
Logger: testLogger{t.Logf, t.Logf},
Callback: testCallback{
nil,
func(m APIMessage, e error) { errchan <- e },
},
Transport: testTransportError,
})
client.Enqueue(Capture{DistinctId: "A", Event: "B"})
client.Close()
if err := <-errchan; err == nil {
t.Error("failure callback not triggered for an invalid request")
} else if e, ok := err.(*url.Error); !ok {
t.Errorf("invalid error returned by round tripper: %T: %s", err, err)
} else if e.Err != testError {
t.Errorf("invalid error returned by round tripper: %T: %s", e.Err, e.Err)
}
}
func TestClientRetryError(t *testing.T) {
errchan := make(chan error, 1)
client, _ := NewWithConfig("0123456789", Config{
Logger: testLogger{t.Logf, t.Logf},
Callback: testCallback{
nil,
func(m APIMessage, e error) { errchan <- e },
},
Transport: roundTripperFunc(func(r *http.Request) (*http.Response, error) {
return nil, testError
}),
BatchSize: 1,
RetryAfter: func(i int) time.Duration { return time.Millisecond },
})
client.Enqueue(Capture{DistinctId: "A", Event: "B"})
// Each retry should happen ~1 millisecond, this should give enough time to
// the test to trigger the failure callback.
time.Sleep(50 * time.Millisecond)
if err := <-errchan; err == nil {
t.Error("failure callback not triggered for a retry falure")
} else if e, ok := err.(*url.Error); !ok {
t.Errorf("invalid error returned by round tripper: %T: %s", err, err)
} else if e.Err != testError {
t.Errorf("invalid error returned by round tripper: %T: %s", e.Err, e.Err)
}
client.Close()
}
func TestClientResponse400(t *testing.T) {
errchan := make(chan error, 1)
client, _ := NewWithConfig("0123456789", Config{
Logger: testLogger{t.Logf, t.Logf},
Callback: testCallback{
nil,
func(m APIMessage, e error) { errchan <- e },
},
// This HTTP transport always return 400's.
Transport: testTransportBadRequest,
})
client.Enqueue(Capture{DistinctId: "A", Event: "B"})
client.Close()
if err := <-errchan; err == nil {
t.Error("failure callback not triggered for a 400 response")
}
}
func TestClientResponseBodyError(t *testing.T) {
errchan := make(chan error, 1)
client, _ := NewWithConfig("0123456789", Config{
Logger: testLogger{t.Logf, t.Logf},
Callback: testCallback{
nil,
func(m APIMessage, e error) { errchan <- e },
},
// This HTTP transport always return 400's with an erroring body.
Transport: testTransportBodyError,
})
client.Enqueue(Capture{DistinctId: "A", Event: "B"})
client.Close()
if err := <-errchan; err == nil {
t.Error("failure callback not triggered for a 400 response")
} else if err != testError {
t.Errorf("invalid error returned by erroring response body: %T: %s", err, err)
}
}
func TestClientMaxConcurrentRequests(t *testing.T) {
reschan := make(chan bool, 1)
errchan := make(chan error, 1)
client, _ := NewWithConfig("0123456789", Config{
Logger: testLogger{t.Logf, t.Logf},
Callback: testCallback{
func(m APIMessage) { reschan <- true },
func(m APIMessage, e error) { errchan <- e },
},
Transport: testTransportDelayed,
// Only one concurreny request can be submitted, because the transport
// introduces a short delay one of the uploads should fail.
BatchSize: 1,
maxConcurrentRequests: 1,
})
client.Enqueue(Capture{DistinctId: "A", Event: "B"})
client.Enqueue(Capture{DistinctId: "A", Event: "B"})
client.Close()
if _, ok := <-reschan; !ok {
t.Error("one of the requests should have succeeded but the result channel was empty")
}
if err := <-errchan; err == nil {
t.Error("failure callback not triggered after reaching the request limit")
} else if err != ErrTooManyRequests {
t.Errorf("invalid error returned by erroring response body: %T: %s", err, err)
}
}
func TestFeatureFlagsWithNoPersonalApiKey(t *testing.T) {
// silence Errorf by tossing them in channel and not reading back
errchan := make(chan error, 1)
defer close(errchan)
client, _ := NewWithConfig("Csyjlnlun3OzyNJAafdlv", Config{
Logger: testLogger{t.Logf, t.Logf},
Callback: testCallback{
func(m APIMessage) {},
func(m APIMessage, e error) { errchan <- e },
},
})
defer client.Close()
receivedErrors := [4]error{}
receivedErrors[0] = client.ReloadFeatureFlags()
_, receivedErrors[1] = client.IsFeatureEnabled(
FeatureFlagPayload{
Key: "some key",
DistinctId: "some id",
},
)
_, receivedErrors[2] = client.GetFeatureFlag(
FeatureFlagPayload{
Key: "some key",
DistinctId: "some id",
},
)
_, receivedErrors[3] = client.GetFeatureFlags()
for _, receivedError := range receivedErrors {
if receivedError == nil || receivedError.Error() != "specifying a PersonalApiKey is required for using feature flags" {
t.Errorf("feature flags methods should return error without personal api key")
return
}
}
}
func TestSimpleFlagOld(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(fixture("test-api-feature-flag.json")))
}))
defer server.Close()
client, _ := NewWithConfig("Csyjlnlun3OzyNJAafdlv", Config{
PersonalApiKey: "some very secret key",
Endpoint: server.URL,
})
defer client.Close()
isEnabled, checkErr := client.IsFeatureEnabled(
FeatureFlagPayload{
Key: "simpleFlag",
DistinctId: "hey",
},
)
if checkErr != nil || isEnabled != true {
t.Errorf("simple flag with null rollout percentage should be on for everyone")
}
// flagValue, valueError := client.GetFeatureFlag("simpleFlag", "hey", false, Groups{}, NewProperties(), map[string]Properties{})
// if valueError != nil || flagValue != true {
// t.Errorf("simple flag with null rollout percentage should have value 'true'")
// }
}
func TestSimpleFlagCalculation(t *testing.T) {
isEnabled, err := checkIfSimpleFlagEnabled("a", "b", 42)
if err != nil || !isEnabled {
t.Errorf("calculation for a.b should succeed and be true")
}
isEnabled, err = checkIfSimpleFlagEnabled("a", "b", 40)
if err != nil || isEnabled {
t.Errorf("calculation for a.b should succeed and be false")
}
}
func TestComplexFlag(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/decide") {
w.Write([]byte(fixture("test-decide-v2.json")))
} else if strings.HasPrefix(r.URL.Path, "/api/feature_flag/local_evaluation") {
w.Write([]byte(fixture("test-api-feature-flag.json")))
} else if !strings.HasPrefix(r.URL.Path, "/batch") {
t.Errorf("client called an endpoint it shouldn't have")
}
}))
defer server.Close()
client, _ := NewWithConfig("Csyjlnlun3OzyNJAafdlv", Config{
PersonalApiKey: "some very secret key",
Endpoint: server.URL,
})
defer client.Close()
isEnabled, checkErr := client.IsFeatureEnabled(
FeatureFlagPayload{
Key: "enabled-flag",
DistinctId: "hey",
},
)
if checkErr != nil || isEnabled != true {
t.Errorf("flag listed in /decide/ response should be marked as enabled")
}
flagValue, valueErr := client.GetFeatureFlag(
FeatureFlagPayload{
Key: "enabled-flag",
DistinctId: "hey",
},
)
if valueErr != nil || flagValue != true {
t.Errorf("flag listed in /decide/ response should be true")
}
}
func TestMultiVariateFlag(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/decide") {
w.Write([]byte(fixture("test-decide-v2.json")))
} else if strings.HasPrefix(r.URL.Path, "/api/feature_flag/local_evaluation") {
w.Write([]byte("{}"))
} else if !strings.HasPrefix(r.URL.Path, "/batch") {
t.Errorf("client called an endpoint it shouldn't have")
}
}))
defer server.Close()
client, _ := NewWithConfig("Csyjlnlun3OzyNJAafdlv", Config{
PersonalApiKey: "some very secret key",
Endpoint: server.URL,
})
defer client.Close()
isEnabled, checkErr := client.IsFeatureEnabled(
FeatureFlagPayload{
Key: "multi-variate-flag",
DistinctId: "hey",
},
)
if checkErr != nil || isEnabled == false {
t.Errorf("flag listed in /decide/ response should be marked as enabled")
}
flagValue, err := client.GetFeatureFlag(
FeatureFlagPayload{
Key: "multi-variate-flag",
DistinctId: "hey",
},
)
if err != nil || flagValue != "hello" {
t.Errorf("flag listed in /decide/ response should have value 'hello'")
}
}
func TestDisabledFlag(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/decide") {
w.Write([]byte(fixture("test-decide-v2.json")))
} else if strings.HasPrefix(r.URL.Path, "/api/feature_flag/local_evaluation") {
w.Write([]byte("{}"))
} else if !strings.HasPrefix(r.URL.Path, "/batch") {
t.Errorf("client called an endpoint it shouldn't have")
}
}))
defer server.Close()
client, _ := NewWithConfig("Csyjlnlun3OzyNJAafdlv", Config{
PersonalApiKey: "some very secret key",
Endpoint: server.URL,
})
defer client.Close()
isEnabled, checkErr := client.IsFeatureEnabled(
FeatureFlagPayload{
Key: "disabled-flag",
DistinctId: "hey",
},
)
if checkErr != nil || isEnabled == true {
t.Errorf("flag listed in /decide/ response should be marked as disabled")
}
flagValue, err := client.GetFeatureFlag(
FeatureFlagPayload{
Key: "disabled-flag",
DistinctId: "hey",
},
)
if err != nil || flagValue != false {
t.Errorf("flag listed in /decide/ response should have value 'false'")
}
}
func TestCaptureSendFlags(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(fixture("test-api-feature-flag.json")))
}))
defer server.Close()
client, _ := NewWithConfig("Csyjlnlun3OzyNJAafdlv", Config{
Endpoint: server.URL,
Verbose: true,
Logger: t,
BatchSize: 1,
now: mockTime,
uid: mockId,
PersonalApiKey: "some very secret key",
})
defer client.Close()
// Without this call client.Close hangs forever
// Ref: https://github.com/PostHog/posthog-go/issues/28
client.IsFeatureEnabled(
FeatureFlagPayload{
Key: "simpleFlag",
DistinctId: "hey",
},
)
err := client.Enqueue(Capture{
Event: "Download",
DistinctId: "123456",
SendFeatureFlags: true,
})
if err != nil {
t.Fatal(err)
}
}