-
Notifications
You must be signed in to change notification settings - Fork 85
/
test_mixpanel.py
692 lines (604 loc) · 23.8 KB
/
test_mixpanel.py
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
from __future__ import absolute_import, unicode_literals
import datetime
import decimal
import json
import time
import pytest
import responses
import six
from six.moves import range, urllib
import mixpanel
class LogConsumer(object):
def __init__(self):
self.log = []
def send(self, endpoint, event, api_key=None, api_secret=None):
entry = [endpoint, json.loads(event)]
if api_key != (None, None):
if api_key:
entry.append(api_key)
if api_secret:
entry.append(api_secret)
self.log.append(tuple(entry))
def clear(self):
self.log = []
class TestMixpanelBase:
TOKEN = '12345'
def setup_method(self, method):
self.consumer = LogConsumer()
self.mp = mixpanel.Mixpanel(self.TOKEN, consumer=self.consumer)
self.mp._now = lambda: 1000.1
self.mp._make_insert_id = lambda: "abcdefg"
class TestMixpanelTracking(TestMixpanelBase):
def test_track(self):
self.mp.track('ID', 'button press', {'size': 'big', 'color': 'blue', '$insert_id': 'abc123'})
assert self.consumer.log == [(
'events', {
'event': 'button press',
'properties': {
'token': self.TOKEN,
'size': 'big',
'color': 'blue',
'distinct_id': 'ID',
'time': self.mp._now(),
'$insert_id': 'abc123',
'mp_lib': 'python',
'$lib_version': mixpanel.__version__,
}
}
)]
def test_track_makes_insert_id(self):
self.mp.track('ID', 'button press', {'size': 'big'})
props = self.consumer.log[0][1]["properties"]
assert "$insert_id" in props
assert isinstance(props["$insert_id"], six.text_type)
assert len(props["$insert_id"]) > 0
def test_track_empty(self):
self.mp.track('person_xyz', 'login', {})
assert self.consumer.log == [(
'events', {
'event': 'login',
'properties': {
'token': self.TOKEN,
'distinct_id': 'person_xyz',
'time': self.mp._now(),
'$insert_id': self.mp._make_insert_id(),
'mp_lib': 'python',
'$lib_version': mixpanel.__version__,
},
},
)]
def test_import_data(self):
timestamp = time.time()
self.mp.import_data('MY_API_KEY', 'ID', 'button press', timestamp,
{'size': 'big', 'color': 'blue', '$insert_id': 'abc123'},
api_secret='MY_SECRET')
assert self.consumer.log == [(
'imports', {
'event': 'button press',
'properties': {
'token': self.TOKEN,
'size': 'big',
'color': 'blue',
'distinct_id': 'ID',
'time': timestamp,
'$insert_id': 'abc123',
'mp_lib': 'python',
'$lib_version': mixpanel.__version__,
},
},
('MY_API_KEY', 'MY_SECRET'),
)]
def test_track_meta(self):
self.mp.track('ID', 'button press', {'size': 'big', 'color': 'blue', '$insert_id': 'abc123'},
meta={'ip': 0})
assert self.consumer.log == [(
'events', {
'event': 'button press',
'properties': {
'token': self.TOKEN,
'size': 'big',
'color': 'blue',
'distinct_id': 'ID',
'time': self.mp._now(),
'$insert_id': 'abc123',
'mp_lib': 'python',
'$lib_version': mixpanel.__version__,
},
'ip': 0,
}
)]
class TestMixpanelPeople(TestMixpanelBase):
def test_people_set(self):
self.mp.people_set('amq', {'birth month': 'october', 'favorite color': 'purple'})
assert self.consumer.log == [(
'people', {
'$time': self.mp._now(),
'$token': self.TOKEN,
'$distinct_id': 'amq',
'$set': {
'birth month': 'october',
'favorite color': 'purple',
},
}
)]
def test_people_set_once(self):
self.mp.people_set_once('amq', {'birth month': 'october', 'favorite color': 'purple'})
assert self.consumer.log == [(
'people', {
'$time': self.mp._now(),
'$token': self.TOKEN,
'$distinct_id': 'amq',
'$set_once': {
'birth month': 'october',
'favorite color': 'purple',
},
}
)]
def test_people_increment(self):
self.mp.people_increment('amq', {'Albums Released': 1})
assert self.consumer.log == [(
'people', {
'$time': self.mp._now(),
'$token': self.TOKEN,
'$distinct_id': 'amq',
'$add': {
'Albums Released': 1,
},
}
)]
def test_people_append(self):
self.mp.people_append('amq', {'birth month': 'october', 'favorite color': 'purple'})
assert self.consumer.log == [(
'people', {
'$time': self.mp._now(),
'$token': self.TOKEN,
'$distinct_id': 'amq',
'$append': {
'birth month': 'october',
'favorite color': 'purple',
},
}
)]
def test_people_union(self):
self.mp.people_union('amq', {'Albums': ['Diamond Dogs']})
assert self.consumer.log == [(
'people', {
'$time': self.mp._now(),
'$token': self.TOKEN,
'$distinct_id': 'amq',
'$union': {
'Albums': ['Diamond Dogs'],
},
}
)]
def test_people_unset(self):
self.mp.people_unset('amq', ['Albums', 'Singles'])
assert self.consumer.log == [(
'people', {
'$time': self.mp._now(),
'$token': self.TOKEN,
'$distinct_id': 'amq',
'$unset': ['Albums', 'Singles'],
}
)]
def test_people_remove(self):
self.mp.people_remove('amq', {'Albums': 'Diamond Dogs'})
assert self.consumer.log == [(
'people', {
'$time': self.mp._now(),
'$token': self.TOKEN,
'$distinct_id': 'amq',
'$remove': {'Albums': 'Diamond Dogs'},
}
)]
def test_people_track_charge(self):
self.mp.people_track_charge('amq', 12.65, {'$time': '2013-04-01T09:02:00'})
assert self.consumer.log == [(
'people', {
'$time': self.mp._now(),
'$token': self.TOKEN,
'$distinct_id': 'amq',
'$append': {
'$transactions': {
'$time': '2013-04-01T09:02:00',
'$amount': 12.65,
},
},
}
)]
def test_people_track_charge_without_properties(self):
self.mp.people_track_charge('amq', 12.65)
assert self.consumer.log == [(
'people', {
'$time': self.mp._now(),
'$token': self.TOKEN,
'$distinct_id': 'amq',
'$append': {
'$transactions': {
'$amount': 12.65,
},
},
}
)]
def test_people_clear_charges(self):
self.mp.people_clear_charges('amq')
assert self.consumer.log == [(
'people', {
'$time': self.mp._now(),
'$token': self.TOKEN,
'$distinct_id': 'amq',
'$unset': ['$transactions'],
}
)]
def test_people_set_created_date_string(self):
created = '2014-02-14T01:02:03'
self.mp.people_set('amq', {'$created': created, 'favorite color': 'purple'})
assert self.consumer.log == [(
'people', {
'$time': self.mp._now(),
'$token': self.TOKEN,
'$distinct_id': 'amq',
'$set': {
'$created': created,
'favorite color': 'purple',
},
}
)]
def test_people_set_created_date_datetime(self):
created = datetime.datetime(2014, 2, 14, 1, 2, 3)
self.mp.people_set('amq', {'$created': created, 'favorite color': 'purple'})
assert self.consumer.log == [(
'people', {
'$time': self.mp._now(),
'$token': self.TOKEN,
'$distinct_id': 'amq',
'$set': {
'$created': '2014-02-14T01:02:03',
'favorite color': 'purple',
},
}
)]
def test_people_meta(self):
self.mp.people_set('amq', {'birth month': 'october', 'favorite color': 'purple'},
meta={'$ip': 0, '$ignore_time': True})
assert self.consumer.log == [(
'people', {
'$time': self.mp._now(),
'$token': self.TOKEN,
'$distinct_id': 'amq',
'$set': {
'birth month': 'october',
'favorite color': 'purple',
},
'$ip': 0,
'$ignore_time': True,
}
)]
class TestMixpanelIdentity(TestMixpanelBase):
def test_alias(self):
# More complicated since alias() forces a synchronous call.
with responses.RequestsMock() as rsps:
rsps.add(
responses.POST,
'https://api.mixpanel.com/track',
json={"status": 1, "error": None},
status=200,
)
self.mp.alias('ALIAS', 'ORIGINAL ID')
assert self.consumer.log == []
call = rsps.calls[0]
assert call.request.method == "POST"
assert call.request.url == "https://api.mixpanel.com/track"
posted_data = dict(urllib.parse.parse_qsl(six.ensure_str(call.request.body)))
assert json.loads(posted_data["data"]) == {"event":"$create_alias","properties":{"alias":"ALIAS","token":"12345","distinct_id":"ORIGINAL ID"}}
def test_merge(self):
self.mp.merge('my_good_api_key', 'd1', 'd2')
assert self.consumer.log == [(
'imports',
{
'event': '$merge',
'properties': {
'$distinct_ids': ['d1', 'd2'],
'token': self.TOKEN,
}
},
('my_good_api_key', None),
)]
self.consumer.clear()
self.mp.merge('my_good_api_key', 'd1', 'd2', api_secret='my_secret')
assert self.consumer.log == [(
'imports',
{
'event': '$merge',
'properties': {
'$distinct_ids': ['d1', 'd2'],
'token': self.TOKEN,
}
},
('my_good_api_key', 'my_secret'),
)]
class TestMixpanelGroups(TestMixpanelBase):
def test_group_set(self):
self.mp.group_set('company', 'amq', {'birth month': 'october', 'favorite color': 'purple'})
assert self.consumer.log == [(
'groups', {
'$time': self.mp._now(),
'$token': self.TOKEN,
'$group_key': 'company',
'$group_id': 'amq',
'$set': {
'birth month': 'october',
'favorite color': 'purple',
},
}
)]
def test_group_set_once(self):
self.mp.group_set_once('company', 'amq', {'birth month': 'october', 'favorite color': 'purple'})
assert self.consumer.log == [(
'groups', {
'$time': self.mp._now(),
'$token': self.TOKEN,
'$group_key': 'company',
'$group_id': 'amq',
'$set_once': {
'birth month': 'october',
'favorite color': 'purple',
},
}
)]
def test_group_union(self):
self.mp.group_union('company', 'amq', {'Albums': ['Diamond Dogs']})
assert self.consumer.log == [(
'groups', {
'$time': self.mp._now(),
'$token': self.TOKEN,
'$group_key': 'company',
'$group_id': 'amq',
'$union': {
'Albums': ['Diamond Dogs'],
},
}
)]
def test_group_unset(self):
self.mp.group_unset('company', 'amq', ['Albums', 'Singles'])
assert self.consumer.log == [(
'groups', {
'$time': self.mp._now(),
'$token': self.TOKEN,
'$group_key': 'company',
'$group_id': 'amq',
'$unset': ['Albums', 'Singles'],
}
)]
def test_group_remove(self):
self.mp.group_remove('company', 'amq', {'Albums': 'Diamond Dogs'})
assert self.consumer.log == [(
'groups', {
'$time': self.mp._now(),
'$token': self.TOKEN,
'$group_key': 'company',
'$group_id': 'amq',
'$remove': {'Albums': 'Diamond Dogs'},
}
)]
def test_custom_json_serializer(self):
decimal_string = '12.05'
with pytest.raises(TypeError) as excinfo:
self.mp.track('ID', 'button press', {'size': decimal.Decimal(decimal_string)})
assert "not JSON serializable" in str(excinfo.value)
class CustomSerializer(mixpanel.DatetimeSerializer):
def default(self, obj):
if isinstance(obj, decimal.Decimal):
return obj.to_eng_string()
self.mp._serializer = CustomSerializer
self.mp.track('ID', 'button press', {'size': decimal.Decimal(decimal_string), '$insert_id': 'abc123'})
assert self.consumer.log == [(
'events', {
'event': 'button press',
'properties': {
'token': self.TOKEN,
'size': decimal_string,
'distinct_id': 'ID',
'time': self.mp._now(),
'$insert_id': 'abc123',
'mp_lib': 'python',
'$lib_version': mixpanel.__version__,
}
}
)]
class TestConsumer:
@classmethod
def setup_class(cls):
cls.consumer = mixpanel.Consumer(request_timeout=30)
def test_send_events(self):
with responses.RequestsMock() as rsps:
rsps.add(
responses.POST,
'https://api.mixpanel.com/track',
json={"status": 1, "error": None},
status=200,
match=[responses.urlencoded_params_matcher({"ip": "0", "verbose": "1", "data": '{"foo":"bar"}'})],
)
self.consumer.send('events', '{"foo":"bar"}')
def test_send_people(self):
with responses.RequestsMock() as rsps:
rsps.add(
responses.POST,
'https://api.mixpanel.com/engage',
json={"status": 1, "error": None},
status=200,
match=[responses.urlencoded_params_matcher({"ip": "0", "verbose": "1", "data": '{"foo":"bar"}'})],
)
self.consumer.send('people', '{"foo":"bar"}')
def test_server_success(self):
with responses.RequestsMock() as rsps:
rsps.add(
responses.POST,
'https://api.mixpanel.com/track',
json={"status": 1, "error": None},
status=200,
match=[responses.urlencoded_params_matcher({"ip": "0", "verbose": "1", "data": '{"foo":"bar"}'})],
)
self.consumer.send('events', '{"foo":"bar"}')
def test_server_invalid_data(self):
with responses.RequestsMock() as rsps:
error_msg = "bad data"
rsps.add(
responses.POST,
'https://api.mixpanel.com/track',
json={"status": 0, "error": error_msg},
status=200,
match=[responses.urlencoded_params_matcher({"ip": "0", "verbose": "1", "data": '{INVALID "foo":"bar"}'})],
)
with pytest.raises(mixpanel.MixpanelException) as exc:
self.consumer.send('events', '{INVALID "foo":"bar"}')
assert error_msg in str(exc)
def test_server_unauthorized(self):
with responses.RequestsMock() as rsps:
rsps.add(
responses.POST,
'https://api.mixpanel.com/track',
json={"status": 0, "error": "unauthed"},
status=401,
match=[responses.urlencoded_params_matcher({"ip": "0", "verbose": "1", "data": '{"foo":"bar"}'})],
)
with pytest.raises(mixpanel.MixpanelException) as exc:
self.consumer.send('events', '{"foo":"bar"}')
assert "unauthed" in str(exc)
def test_server_forbidden(self):
with responses.RequestsMock() as rsps:
rsps.add(
responses.POST,
'https://api.mixpanel.com/track',
json={"status": 0, "error": "forbade"},
status=403,
match=[responses.urlencoded_params_matcher({"ip": "0", "verbose": "1", "data": '{"foo":"bar"}'})],
)
with pytest.raises(mixpanel.MixpanelException) as exc:
self.consumer.send('events', '{"foo":"bar"}')
assert "forbade" in str(exc)
def test_server_5xx(self):
with responses.RequestsMock() as rsps:
rsps.add(
responses.POST,
'https://api.mixpanel.com/track',
body="Internal server error",
status=500,
match=[responses.urlencoded_params_matcher({"ip": "0", "verbose": "1", "data": '{"foo":"bar"}'})],
)
with pytest.raises(mixpanel.MixpanelException) as exc:
self.consumer.send('events', '{"foo":"bar"}')
def test_consumer_override_api_host(self):
consumer = mixpanel.Consumer(api_host="api-zoltan.mixpanel.com")
with responses.RequestsMock() as rsps:
rsps.add(
responses.POST,
'https://api-zoltan.mixpanel.com/track',
json={"status": 1, "error": None},
status=200,
match=[responses.urlencoded_params_matcher({"ip": "0", "verbose": "1", "data": '{"foo":"bar"}'})],
)
consumer.send('events', '{"foo":"bar"}')
with responses.RequestsMock() as rsps:
rsps.add(
responses.POST,
'https://api-zoltan.mixpanel.com/engage',
json={"status": 1, "error": None},
status=200,
match=[responses.urlencoded_params_matcher({"ip": "0", "verbose": "1", "data": '{"foo":"bar"}'})],
)
consumer.send('people', '{"foo":"bar"}')
def test_unknown_endpoint(self):
with pytest.raises(mixpanel.MixpanelException):
self.consumer.send('unknown', '1')
class TestBufferedConsumer:
@classmethod
def setup_class(cls):
cls.MAX_LENGTH = 10
cls.consumer = mixpanel.BufferedConsumer(cls.MAX_LENGTH)
cls.consumer._consumer = LogConsumer()
cls.log = cls.consumer._consumer.log
def setup_method(self):
del self.log[:]
def test_buffer_hold_and_flush(self):
self.consumer.send('events', '"Event"')
assert len(self.log) == 0
self.consumer.flush()
assert self.log == [('events', ['Event'])]
def test_buffer_fills_up(self):
for i in range(self.MAX_LENGTH - 1):
self.consumer.send('events', '"Event"')
assert len(self.log) == 0
self.consumer.send('events', '"Last Event"')
assert len(self.log) == 1
assert self.log == [('events', [
'Event', 'Event', 'Event', 'Event', 'Event',
'Event', 'Event', 'Event', 'Event', 'Last Event',
])]
def test_unknown_endpoint_raises_on_send(self):
# Ensure the exception isn't hidden until a flush.
with pytest.raises(mixpanel.MixpanelException):
self.consumer.send('unknown', '1')
def test_useful_reraise_in_flush_endpoint(self):
with responses.RequestsMock() as rsps:
rsps.add(
responses.POST,
'https://api.mixpanel.com/track',
json={"status": 0, "error": "arbitrary error"},
status=200,
)
broken_json = '{broken JSON'
consumer = mixpanel.BufferedConsumer(2)
consumer.send('events', broken_json)
with pytest.raises(mixpanel.MixpanelException) as excinfo:
consumer.flush()
assert excinfo.value.message == '[%s]' % broken_json
assert excinfo.value.endpoint == 'events'
def test_send_remembers_api_key(self):
self.consumer.send('imports', '"Event"', api_key='MY_API_KEY')
assert len(self.log) == 0
self.consumer.flush()
assert self.log == [('imports', ['Event'], ('MY_API_KEY', None))]
def test_send_remembers_api_secret(self):
self.consumer.send('imports', '"Event"', api_secret='ZZZZZZ')
assert len(self.log) == 0
self.consumer.flush()
assert self.log == [('imports', ['Event'], (None, 'ZZZZZZ'))]
class TestFunctional:
@classmethod
def setup_class(cls):
cls.TOKEN = '12345'
cls.mp = mixpanel.Mixpanel(cls.TOKEN)
cls.mp._now = lambda: 1000
def test_track_functional(self):
with responses.RequestsMock() as rsps:
rsps.add(
responses.POST,
'https://api.mixpanel.com/track',
json={"status": 1, "error": None},
status=200,
)
self.mp.track('player1', 'button_press', {'size': 'big', 'color': 'blue', '$insert_id': 'xyz1200'})
body = six.ensure_str(rsps.calls[0].request.body)
wrapper = dict(urllib.parse.parse_qsl(body))
data = json.loads(wrapper["data"])
del wrapper["data"]
assert {"ip": "0", "verbose": "1"} == wrapper
expected_data = {'event': 'button_press', 'properties': {'size': 'big', 'color': 'blue', 'mp_lib': 'python', 'token': '12345', 'distinct_id': 'player1', '$lib_version': mixpanel.__version__, 'time': 1000, '$insert_id': 'xyz1200'}}
assert expected_data == data
def test_people_set_functional(self):
with responses.RequestsMock() as rsps:
rsps.add(
responses.POST,
'https://api.mixpanel.com/engage',
json={"status": 1, "error": None},
status=200,
)
self.mp.people_set('amq', {'birth month': 'october', 'favorite color': 'purple'})
body = six.ensure_str(rsps.calls[0].request.body)
wrapper = dict(urllib.parse.parse_qsl(body))
data = json.loads(wrapper["data"])
del wrapper["data"]
assert {"ip": "0", "verbose": "1"} == wrapper
expected_data = {'$distinct_id': 'amq', '$set': {'birth month': 'october', 'favorite color': 'purple'}, '$time': 1000, '$token': '12345'}
assert expected_data == data