/
tests.py
1710 lines (1457 loc) · 65 KB
/
tests.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
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
# -*- coding: utf-8 -*-
import copy
import datetime
import logging
import six
import socket
import time
import random
import pprint
import pkg_resources
from webob import Request
from appenlight_client import client, make_appenlight_middleware
from appenlight_client.exceptions import get_current_traceback
from appenlight_client.ext.logging import register_logging
from appenlight_client.wsgi import AppenlightWSGIWrapper
from appenlight_client.utils import fullyQualifiedName, import_from_module, filter_callable
logging.basicConfig()
fname = pkg_resources.resource_filename('appenlight_client',
'templates/default_template.ini')
timing_conf = client.get_config(path_to_config=fname)
# set api key
for k, v in six.iteritems(timing_conf):
if 'appenlight.timing' in k:
timing_conf[k] = 0.0000001
timing_conf.pop('appenlight.timing.dbapi2_sqlite3', None)
# this sets up timing decoration for us
global_client = client.BaseClient(config=timing_conf)
global_client.unregister_logger()
from appenlight_client.timing import local_timing, get_local_storage, time_trace
def example_filter_callable(structure, section=None):
return 'filtered-data'
TEST_ENVIRON = {
'bfg.routes.matchdict': {'action': u'error'},
'HTTP_COOKIE': 'country=US; http_referer="http://localhost:5000/"; test_group_id=5; sessionId=ec3ae5;',
'SERVER_SOFTWARE': 'waitress',
'SCRIPT_NAME': '',
'REQUEST_METHOD': 'GET',
'PATH_INFO': '/test/error',
'SERVER_PROTOCOL': 'HTTP/1.1',
'QUERY_STRING': 'aaa=1&bbb=2',
'paste.throw_errors': True,
'CONNECTION_TYPE': 'keep-alive',
'HTTP_USER_AGENT': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0.1) Gecko/20100101 Firefox/10.0.1',
'SERVER_NAME': 'localhost',
'REMOTE_ADDR': '127.0.0.1',
'wsgi.url_scheme': 'http',
'SERVER_PORT': '6543',
'HTTP_HOST': 'localhost:6543',
'wsgi.multithread': True,
'HTTP_CACHE_CONTROL': 'max-age=0',
'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'wsgi.version': (1, 0),
'wsgi.run_once': False,
'wsgi.multiprocess': False,
'HTTP_ACCEPT_LANGUAGE': 'en-us,en;q=0.5',
'HTTP_ACCEPT_ENCODING': 'gzip, deflate',
'REMOTE_USER': 'foo'
}
REQ_START_TIME = datetime.datetime.utcnow()
REQ_END_TIME = datetime.datetime.utcnow() + datetime.timedelta(seconds=1)
SERVER_NAME = socket.getfqdn() # different on every machine
PARSED_REPORT_404 = {
'error': '404 Not Found',
'server': SERVER_NAME,
'priority': 5,
'client': 'appenlight-python',
'language': 'python',
'username': u'foo',
'url': 'http://localhost:6543/test/error?aaa=1&bbb=2',
'ip': '127.0.0.1',
'start_time': REQ_START_TIME,
'slow_calls': [],
'request': {'COOKIES': {},
'POST': {},
'GET': {u'aaa': [u'1'], u'bbb': [u'2']},
'HTTP_METHOD': 'GET',
},
'user_agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0.1) Gecko/20100101 Firefox/10.0.1',
'message': u'',
'end_time': REQ_END_TIME,
'request_stats': {},
'http_status': 404}
PARSED_REPORT_500 = {
# this will be different everywhere
'error': u'Exception: Test Exception',
'server': SERVER_NAME,
'priority': 5,
'client': 'appenlight-python',
'language': 'python',
'traceback': [
{'cline': u"raise Exception('Test Exception')",
'file': 'appenlight_client/tests.py',
'fn': 'test_py_report_500_traceback',
'line': 454,
'vars': []},
{'cline': u'Exception: Test Exception',
'file': '',
'fn': '',
'line': '',
'vars': []}],
'username': u'foo',
'url': 'http://localhost:6543/test/error?aaa=1&bbb=2',
'ip': '127.0.0.1',
'start_time': REQ_START_TIME,
'slow_calls': [],
'request': {
'HTTP_ACCEPT': u'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'COOKIES': {},
'SERVER_NAME': u'localhost',
'GET': {u'aaa': [u'1'],
u'bbb': [u'2']},
'HTTP_ACCEPT': u'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'HTTP_ACCEPT_ENCODING': u'gzip, deflate',
'HTTP_ACCEPT_LANGUAGE': u'en-us,en;q=0.5',
'HTTP_CACHE_CONTROL': u'max-age=0',
'HTTP_HOST': u'localhost:6543',
'HTTP_METHOD': 'GET',
'REMOTE_USER': u'foo',
'HTTP_HOST': u'localhost:6543',
'POST': {},
'HTTP_CACHE_CONTROL': u'max-age=0',
'HTTP_ACCEPT_ENCODING': u'gzip, deflate',
'HTTP_METHOD': 'GET'},
'user_agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0.1) Gecko/20100101 Firefox/10.0.1',
'message': u'',
'end_time': REQ_END_TIME,
'request_stats': {},
'http_status': 500}
PARSED_SLOW_REPORT = {
'error': '',
'server': SERVER_NAME,
'priority': 5,
'client': 'appenlight-python',
'language': 'python',
'username': u'foo',
'url': 'http://localhost:6543/test/error?aaa=1&bbb=2',
'ip': '127.0.0.1',
'start_time': REQ_START_TIME,
'slow_calls': [],
'request': {'COOKIES': {},
'POST': {},
'GET': {u'aaa': [u'1'], u'bbb': [u'2'], },
'HTTP_ACCEPT': u'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'HTTP_ACCEPT_ENCODING': u'gzip, deflate',
'HTTP_ACCEPT_LANGUAGE': u'en-us,en;q=0.5',
'HTTP_CACHE_CONTROL': u'max-age=0',
'HTTP_HOST': u'localhost:6543',
'HTTP_METHOD': 'GET',
'REMOTE_USER': u'foo',
'SERVER_NAME': u'localhost',
},
'user_agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0.1) Gecko/20100101 Firefox/10.0.1',
'message': u'',
'end_time': REQ_END_TIME,
'request_stats': {},
'http_status': 200}
class BaseTest(object):
def setUpClient(self, config=None):
timing_conf['appenlight.api_key'] = 'default_test_key'
if config is None:
config = {'appenlight.api_key': 'default_test_key'}
self.client = client.BaseClient(config)
def teardown_method(self, method):
storage = get_local_storage(local_timing)
storage.clear()
if hasattr(self, 'client'):
self.client.purge_data()
self.client.unregister_logger()
class TestClientConfig(BaseTest):
def test_empty_init(self):
self.setUpClient()
assert isinstance(self.client, (client.Client, client.BaseClient))
def test_api_key(self):
config = {'appenlight.api_key': '12345AAAAA'}
self.setUpClient(config)
assert self.client.config['api_key'] == config['appenlight.api_key']
def test_default_transport(self):
self.setUpClient()
assert self.client.config['transport'] == 'appenlight_client.transports.requests:HTTPTransport'
def test_transport_config(self):
config = {
'appenlight.transport_config': 'https://api.appenlight.com?threaded=0&timeout=10'}
self.setUpClient(config)
superset = self.client.transport.transport_config.items()
subset = {'url': 'https://api.appenlight.com', 'timeout': 10, 'threaded': 0}
for i in six.iteritems(subset):
assert i in superset
def test_enabled_client(self):
self.setUpClient()
assert self.client.config['enabled'] is True
def test_disabled_client(self):
config = {'appenlight': "false"}
self.setUpClient(config)
assert self.client.config['enabled'] is False
def test_disabled_client_no_key(self):
self.setUpClient({})
assert self.client.config['enabled'] is False
def test_server_name(self):
config = {'appenlight.server_name': "some_name"}
self.setUpClient(config)
assert self.client.config['server_name'] == config['appenlight.server_name']
def test_default_server_name(self):
self.setUpClient()
assert self.client.config['server_name'] == socket.getfqdn()
def test_client_name(self):
config = {'appenlight.client': "pythonX"}
self.setUpClient(config)
assert self.client.config['client'] == config['appenlight.client']
def test_default_client_name(self):
self.setUpClient()
assert self.client.config['client'] == 'python3' if client.PY3 else 'python'
def test_reraise_exceptions(self):
config = {'appenlight.reraise_exceptions': "false"}
self.setUpClient(config)
assert self.client.config['reraise_exceptions'] is False
def test_default_reraise_exceptions(self):
self.setUpClient()
assert self.client.config['reraise_exceptions'] is True
def test_default_slow_requests(self):
self.setUpClient()
assert self.client.config['slow_requests'] is True
def test_disabled_slow_requests(self):
config = {'appenlight.reraise_exceptions': "false"}
self.setUpClient(config)
assert self.client.config['reraise_exceptions'] is False
def test_default_slow_request_time(self):
self.setUpClient()
assert self.client.config['slow_request_time'] == datetime.timedelta(seconds=1)
def test_custom_slow_request_time(self):
config = {'appenlight.slow_request_time': "2"}
self.setUpClient(config)
assert self.client.config['slow_request_time'] == datetime.timedelta(seconds=2)
def test_too_low_custom_slow_request_time(self):
config = {'appenlight.slow_request_time': "0.001"}
self.setUpClient(config)
assert self.client.config['slow_request_time'] == datetime.timedelta(seconds=0.01)
def test_default_logging(self):
self.setUpClient()
assert self.client.config['logging'] is True
def test_custom_logging(self):
config = {'appenlight.logging': "false"}
self.setUpClient(config)
assert self.client.config['logging'] is False
def test_default_logging_on_error(self):
self.setUpClient()
assert self.client.config['logging_on_error'] is False
def test_custom_logging_on_error(self):
config = {'appenlight.logging_on_error': "true"}
self.setUpClient(config)
assert self.client.config['logging_on_error'] is True
def test_default_report_404(self):
self.setUpClient()
assert self.client.config['report_404'] is False
def test_custom_report_404r(self):
config = {'appenlight.report_404': "true"}
self.setUpClient(config)
assert self.client.config['report_404'] is True
def test_default_report_errors(self):
self.setUpClient()
assert self.client.config['report_errors'] is True
def test_custom_report_errors(self):
config = {'appenlight.report_errors': "false"}
self.setUpClient(config)
assert self.client.config['report_errors'] is False
def test_default_buffer_flush_interval(self):
self.setUpClient()
assert self.client.config['buffer_flush_interval'] == datetime.timedelta(seconds=5)
def test_custom_buffer_flush_interval(self):
config = {'appenlight.buffer_flush_interval': "10"}
self.setUpClient(config)
assert self.client.config['buffer_flush_interval'] == datetime.timedelta(seconds=10)
def test_custom_small_buffer_flush_interval(self):
config = {'appenlight.buffer_flush_interval': "0"}
self.setUpClient(config)
assert self.client.config['buffer_flush_interval'] == datetime.timedelta(seconds=1)
def test_default_buffer_clear_on_send(self):
self.setUpClient()
assert self.client.config['buffer_clear_on_send'] is False
def test_custom_buffer_clear_on_send(self):
config = {'appenlight.buffer_clear_on_send': "true"}
self.setUpClient(config)
assert self.client.config['buffer_clear_on_send'] is True
def test_default_force_send(self):
self.setUpClient()
assert self.client.config['force_send'] is False
def test_custom_force_send(self):
config = {'appenlight.force_send': "1"}
self.setUpClient(config)
assert self.client.config['force_send'] is True
def test_default_request_keys_blacklist(self):
self.setUpClient()
assert set(self.client.config['request_keys_blacklist']) == set(['password', 'passwd', 'pwd', 'auth_tkt',
'secret',
'csrf', 'xsrf', 'auth',
'session', 'pass', 'config', 'settings',
'environ'])
def test_custom_request_keys_blacklist(self):
config = {'appenlight.request_keys_blacklist': "aa,bb,cc"}
self.setUpClient(config)
assert set(self.client.config['request_keys_blacklist']) == set(['password', 'passwd', 'pwd', 'auth_tkt',
'secret',
'csrf', 'xsrf', 'auth', 'session', 'pass',
'config', 'settings',
'environ', 'aa', 'bb', 'cc'])
def test_default_environ_keys_whitelist(self):
self.setUpClient()
assert self.client.config['environ_keys_whitelist'] == ['REMOTE_USER', 'REMOTE_ADDR', 'SERVER_NAME',
'CONTENT_TYPE', 'HTTP_REFERER']
def test_custom_environ_keys_whitelist(self):
config = {'appenlight.environ_keys_whitelist': "aa,bb,cc"}
self.setUpClient(config)
assert self.client.config['environ_keys_whitelist'] == ['REMOTE_USER', 'REMOTE_ADDR', 'SERVER_NAME',
'CONTENT_TYPE','HTTP_REFERER', 'aa', 'bb', 'cc']
def test_default_log_namespace_blacklist(self):
self.setUpClient()
assert self.client.config['log_namespace_blacklist'] == ['appenlight_client.client',
'appenlight_client.transports.requests']
def test_custom_log_namespace_blacklist(self):
config = {'appenlight.log_namespace_blacklist': "aa,bb,cc.dd"}
self.setUpClient(config)
assert self.client.config['log_namespace_blacklist'] == ['appenlight_client.client',
'appenlight_client.transports.requests',
'aa', 'bb', 'cc.dd']
def test_default_filter_callable(self):
self.setUpClient()
assert self.client.filter_callable == filter_callable
def test_bad_filter_callable(self):
config = {'appenlight.filter_callable': "foo.bar.baz:callable_name"}
self.setUpClient(config)
assert self.client.filter_callable == filter_callable
def test_custom_filter_callable(self):
config = {'appenlight.filter_callable':
"appenlight_client.tests:example_filter_callable"}
self.setUpClient(config)
assert self.client.filter_callable.__name__ == example_filter_callable.__name__
def test_default_logging_handler_present(self):
self.setUpClient()
assert len(self.client.log_handlers) > 0
def test_custom_logging_handler_present(self):
config = {'appenlight.logging': "false"}
self.setUpClient(config)
assert len(self.client.log_handlers) == 0
def test_default_logging_handler_level(self):
self.setUpClient()
assert self.client.log_handlers[0].level == logging.WARNING
def test_custom_logging_handler_level(self):
config = {'appenlight.logging.level': "CRITICAL",
'appenlight.api_key': '12345'}
self.setUpClient(config)
assert self.client.log_handlers[0].level == logging.CRITICAL
def test_default_timing_config(self):
self.setUpClient()
assert self.client.config['timing'] == {}
def test_timing_config_disable(self):
config = {'appenlight.timing.dbapi2_psycopg2': 'false',
'appenlight.api_key': '12345'}
self.setUpClient(config)
assert self.client.config['timing']['dbapi2_psycopg2'] is False
def test_timing_config_custom(self):
config = {'appenlight.timing.dbapi2_psycopg2': '5',
'appenlight.api_key': '12345'}
self.setUpClient(config)
assert self.client.config['timing']['dbapi2_psycopg2'] == 5
def test_timing_config_mixed(self):
config = {'appenlight.timing.dbapi2_psycopg2': '5',
'appenlight.timing': {'urllib': 11, 'dbapi2_oursql': 6},
'appenlight.api_key': '12345'
}
self.setUpClient(config)
assert self.client.config['timing']['dbapi2_psycopg2'] == 5
assert self.client.config['timing']['dbapi2_oursql'] == 6
assert self.client.config['timing']['urllib'] == 11
def generate_error():
pass
class TestClientTransport(BaseTest):
def test_check_if_deliver_false(self):
self.setUpClient()
self.client.last_submit = datetime.datetime.now()
assert self.client.check_if_deliver() is False
def test_check_if_deliver_forced(self):
self.setUpClient()
self.client.transport.log_queue = ['dummy']
assert self.client.check_if_deliver(force_send=True) is True
def test_send_error_failure_queue(self):
self.setUpClient()
self.client.py_report(TEST_ENVIRON, http_status=404)
self.client.check_if_deliver(force_send=True)
get_local_storage(local_timing).clear()
assert self.client.transport.report_queue == []
def test_http_transport_failure(self):
self.setUpClient()
self.client.py_report(TEST_ENVIRON, http_status=404)
result = self.client.transport.send(self.client.transport.report_queue, 'reports')
get_local_storage(local_timing).clear()
assert result is False
def test_http_transport_success(self):
# requires valid key for test
return True
self.setUpClient(
{'appenlight.api_key': 'XXX',
'appenlight.transport_config': 'http://127.0.0.1:6543?threaded=1&timeout=5'})
self.client.py_report(TEST_ENVIRON, http_status=404)
result = self.client.transport.send(self.client.transport.report_queue, 'reports')
get_local_storage(local_timing).clear()
assert result is True
def test_http_transport_timeout(self):
# requires valid key for test
self.setUpClient(
{'appenlight.api_key': 'XXX',
'appenlight.transport_config': 'http://127.0.0.1:6543?threaded=1&timeout=0.0001'})
self.client.py_report(TEST_ENVIRON, http_status=404)
result = self.client.transport.send(self.client.transport.report_queue, 'reports')
get_local_storage(local_timing).clear()
assert result is False
def test_wrong_server_failure(self):
# requires valid key for test
self.setUpClient(
{'appenlight.api_key': 'XXX',
'appenlight.transport_config': 'http://foo.bar.baz.com:6543?threaded=1&timeout=5'})
self.client.py_report(TEST_ENVIRON, http_status=404)
result = self.client.transport.send(self.client.transport.report_queue, 'reports')
get_local_storage(local_timing).clear()
assert result is False
def test_default_buffer_clear(self):
self.setUpClient(
{'appenlight.api_key': 'XXX',
'appenlight.transport_config': 'http://foo.bar.baz.com:6543?threaded=1&timeout=5'})
for x in xrange(10):
self.client.py_report(TEST_ENVIRON, http_status=404)
result = self.client.check_if_deliver(force_send=True)
get_local_storage(local_timing).clear()
assert len(self.client.transport.report_queue) == 0
def test_default_buffer_non_empty(self):
self.setUpClient(
{'appenlight.api_key': 'XXX',
'appenlight.transport_config': 'http://foo.bar.baz.com:6543?threaded=1&timeout=5'})
for x in xrange(255):
self.client.py_report(TEST_ENVIRON, http_status=404)
result = self.client.check_if_deliver(force_send=True)
get_local_storage(local_timing).clear()
assert len(self.client.transport.report_queue) > 0
def test_custom_buffer_clear(self):
self.setUpClient(
{'appenlight.api_key': 'XXX',
'appenlight.transport_config': 'http://foo.bar.baz.com:6543?threaded=1&timeout=5',
'appenlight.buffer_clear_on_send': "true"
})
for x in xrange(255):
self.client.py_report(TEST_ENVIRON, http_status=404)
result = self.client.check_if_deliver(force_send=True)
get_local_storage(local_timing).clear()
assert len(self.client.transport.report_queue) == 0
def test_wrong_transport(self):
self.setUpClient(
{'appenlight.api_key': 'XXX',
'appenlight.transport': 'fooblabla.bar.baz:NonExistantTransport'})
def test_default_transport(self):
import appenlight_client.transports.requests as ae_transport
self.setUpClient(
{'appenlight.api_key': 'XXX',
'appenlight.transport': ''})
assert isinstance(self.client.transport, ae_transport.HTTPTransport)
class TestErrorParsing(BaseTest):
def test_py_report_404(self):
self.setUpClient()
self.client.py_report(TEST_ENVIRON, http_status=404,
start_time=REQ_START_TIME, end_time=REQ_END_TIME)
subset = PARSED_REPORT_404
superset = self.client.transport.report_queue[0].items()
for i in six.iteritems(subset):
assert i in superset
def test_py_report_500_no_traceback(self):
self.setUpClient()
self.client.py_report(TEST_ENVIRON, http_status=500,
start_time=REQ_START_TIME,
end_time=REQ_END_TIME)
bogus_500_report = copy.deepcopy(PARSED_REPORT_500)
bogus_500_report['http_status'] = 500
bogus_500_report['error'] = ''
del bogus_500_report['traceback']
bogus_500_report['request_stats'] = {}
subset = bogus_500_report
superset = self.client.transport.report_queue[0].items()
for i in six.iteritems(subset):
assert i in superset
def test_py_report_500_traceback(self):
self.setUpClient({'appenlight.api_key': 'XXX',
'appenlight.report_local_vars': 'false'})
bogus_report = copy.deepcopy(PARSED_REPORT_500)
try:
raise Exception('Test Exception')
except:
traceback = get_current_traceback(skip=1, show_hidden_frames=True,
ignore_system_exceptions=True)
self.client.py_report(TEST_ENVIRON, traceback=traceback,
http_status=500,
start_time=REQ_START_TIME,
end_time=REQ_END_TIME)
line_no = \
self.client.transport.report_queue[0]['traceback'][0]['line']
assert int(line_no) > 0
# set line number to match as this will change over time
bogus_report['traceback'][0]['line'] = line_no
subset = bogus_report
superset = self.client.transport.report_queue[0].items()
for i in six.iteritems(subset):
assert i in superset
def test_frameinfo(self):
self.setUpClient(config={'appenlight.report_local_vars': 'true'})
test = 1
b = {1: 'a', '2': 2, 'ccc': 'ddd'}
obj = object()
e_obj = client.BaseClient({})
unic = 'grzegżółka'
a_list = [1, 2, 4, 5, 6, client.BaseClient({}), 'dupa']
long_val = 'imlong' * 100
datetest = datetime.datetime.utcnow()
try:
raise Exception('Test Exception')
except:
traceback = get_current_traceback(skip=1, show_hidden_frames=True,
ignore_system_exceptions=True)
self.client.py_report(TEST_ENVIRON, traceback=traceback,
http_status=500)
assert len(self.client.transport.report_queue[0]['traceback'][0]['vars']) == 9
def test_frameinfo_dict(self):
self.setUpClient(config={'appenlight.report_local_vars': 'true'})
example_dict = {1: u'a', 'foo': u'bar'}
try:
raise Exception('Test Exception')
except:
traceback = get_current_traceback(
skip=1,
show_hidden_frames=True,
ignore_system_exceptions=True
)
self.client.py_report(
TEST_ENVIRON,
traceback=traceback,
http_status=500
)
vars = dict(self.client.transport.report_queue[0]['traceback'][0]['vars'])
assert vars['example_dict'], {'1': u"u'a'", "'foo'": u"u'bar'"}
def test_cookie_parsing(self):
self.setUpClient(config={'appenlight.cookie_keys_whitelist': 'country, sessionId, test_group_id, http_referer'})
proper_values = {u'country': u'US',
u'sessionId': u'***',
u'test_group_id': u'5',
u'http_referer': u'http://localhost:5000/'}
try:
raise Exception('Test Exception')
except:
traceback = get_current_traceback(skip=1, show_hidden_frames=True,
ignore_system_exceptions=True)
self.client.py_report(TEST_ENVIRON, traceback=traceback,
http_status=500)
assert self.client.transport.report_queue[0]['request']['COOKIES'] == proper_values
class TestLogs(BaseTest):
def test_py_log(self):
self.setUpClient()
handler_cls = import_from_module('appenlight_client.ext.logging.logger:ThreadLocalHandler')
handler = register_logging(logging.root, self.client.config, cls=handler_cls)
logger = logging.getLogger('testing')
msg = 'test entry %s' % random.random()
logger.critical(msg)
records = self.client.log_handlers_get_records()
self.client.py_log(TEST_ENVIRON, records=records)
fake_log = {'log_level': 'CRITICAL',
'namespace': 'testing',
'server': 'test-foo', # this will be different everywhere
'request_id': None,
'date': '2012-08-13T21:20:37.418.307066',
'message': msg}
# update fields depenand on machine
self.client.transport.log_queue[0]['date'] = fake_log['date']
self.client.transport.log_queue[0]['server'] = fake_log['server']
assert self.client.transport.log_queue[0] == fake_log
def test_log_limits(self):
self.setUpClient(config={'appenlight.api_key': 'default_test_key',
'appenlight.logging.max_thread_logs': '15'})
pprint.pprint(self.client.config)
handler_cls = import_from_module('appenlight_client.ext.logging.logger:ThreadLocalHandler')
handler = register_logging(logging.root, self.client.config, cls=handler_cls)
logger = logging.getLogger('testing')
msg = 'test entry %s' % random.random()
for x in range(0, 50):
logger.critical(msg)
records = self.client.log_handlers_get_records()
total_records = len(records)
assert total_records == 15
def test_errors_attached_to_logs(self):
self.setUpClient()
handler_cls = import_from_module('appenlight_client.ext.logging.logger:ThreadLocalHandler')
handler = register_logging(logging.root, self.client.config, cls=handler_cls)
logger = logging.getLogger('testing')
some_num = random.random()
try:
raise Exception('This is a test')
except Exception as e:
logger.exception('Exception happened %s' % some_num)
records = self.client.log_handlers_get_records()
self.client.py_log(TEST_ENVIRON, records=records)
fake_log = {'log_level': 'ERROR',
'namespace': 'testing',
'server': 'test-foo', # this will be different everywhere
'request_id': None,
'date': '2012-08-13T21:20:37.418.307066',
'message': 'Exception happened %s\nTraceback (most recent call last):' % some_num}
# update fields depenand on machine
self.client.transport.log_queue[0]['date'] = fake_log['date']
self.client.transport.log_queue[0]['server'] = fake_log['server']
assert self.client.transport.log_queue[0]['message'].startswith(fake_log['message'])
def test_errors_not_attached_to_logs(self):
self.setUpClient({'appenlight.logging_attach_exc_text': 'false',
'appenlight.api_key': 'test_errors_not_attached_to_logs'})
handler_cls = import_from_module('appenlight_client.ext.logging.logger:ThreadLocalHandler')
handler = register_logging(logging.root, self.client.config, cls=handler_cls)
logger = logging.getLogger('testing')
log_msg = 'Exception happened %s' % random.random()
try:
raise Exception('This is a test')
except Exception as e:
logger.exception(log_msg)
records = self.client.log_handlers_get_records()
self.client.py_log(TEST_ENVIRON, records=records)
fake_log = {'log_level': 'ERROR',
'namespace': 'testing',
'server': 'test-foo', # this will be different everywhere
'request_id': None,
'date': '2012-08-13T21:20:37.418.307066',
'message': log_msg}
# update fields depenand on machine
self.client.transport.log_queue[0]['date'] = fake_log['date']
self.client.transport.log_queue[0]['server'] = fake_log['server']
assert self.client.transport.log_queue[0]['message'] == fake_log['message']
def test_tags_attached_to_logs(self):
self.setUpClient()
handler_cls = import_from_module('appenlight_client.ext.logging.logger:ThreadLocalHandler')
handler = register_logging(logging.root, self.client.config, cls=handler_cls)
logger = logging.getLogger('testing')
utcnow = datetime.datetime.utcnow()
class StrTestObj(object):
def __repr__(self):
return "<StrTestObj>"
logger.critical('test entry',
extra={"foobar": "baz",
"count": 15,
"price": 5.5,
"date": utcnow,
"obj": StrTestObj(),
"dictionary": {"a": "5"}
}
)
records = self.client.log_handlers_get_records()
self.client.py_log(TEST_ENVIRON, records=records)
fake_log = {'log_level': 'CRITICAL',
'namespace': 'testing',
'server': 'test-foo', # this will be different everywhere
'request_id': None,
'date': utcnow.isoformat(),
'message': 'test entry',
'tags': [("foobar", "baz"),
("count", 15),
("price", 5.5),
("date", utcnow),
("obj", u'<StrTestObj>'),
("dictionary", u"{'a': '5'}")
]}
# update fields depenand on machine
self.client.transport.log_queue[0]['server'] = fake_log['server']
self.client.transport.log_queue[0]['date'] = fake_log['date']
new_log = self.client.transport.log_queue[0]
assert new_log['log_level'] == fake_log['log_level']
assert new_log['namespace'] == fake_log['namespace']
assert new_log['server'] == fake_log['server']
assert new_log['request_id'] == fake_log['request_id']
assert new_log['date'] == fake_log['date']
assert new_log['message'] == fake_log['message']
assert set(new_log['tags']) == set(fake_log['tags'])
def test_primary_key_attached(self):
self.setUpClient()
handler_cls = import_from_module('appenlight_client.ext.logging.logger:ThreadLocalHandler')
handler = register_logging(logging.root, self.client.config, cls=handler_cls)
logger = logging.getLogger('testing')
logger.critical('test entry',
extra={"foobar": "baz",
"count": 15,
"price": 5.5,
'ae_primary_key': 15,
"dictionary": {"a": "5"}
}
)
records = self.client.log_handlers_get_records()
self.client.py_log(TEST_ENVIRON, records=records)
new_log = self.client.transport.log_queue[0]
assert new_log['primary_key'] == '15'
def test_permanent_log(self):
self.setUpClient()
handler_cls = import_from_module('appenlight_client.ext.logging.logger:ThreadLocalHandler')
handler = register_logging(logging.root, self.client.config, cls=handler_cls)
logger = logging.getLogger('testing')
logger.critical('test entry',
extra={"foobar": "baz",
"count": 15,
"price": 5.5,
'ae_permanent': 1,
"dictionary": {"a": "5"}
}
)
records = self.client.log_handlers_get_records()
self.client.py_log(TEST_ENVIRON, records=records)
new_log = self.client.transport.log_queue[0]
assert new_log['permanent'] == True
def test_ignore_self_logs(self):
self.setUpClient()
handler_cls = import_from_module('appenlight_client.ext.logging.logger:ThreadLocalHandler')
handler = register_logging(logging.root, self.client.config, cls=handler_cls)
self.client.py_report(TEST_ENVIRON, http_status=500)
self.client.py_report(TEST_ENVIRON, start_time=REQ_START_TIME,
end_time=REQ_END_TIME)
records = self.client.log_handlers_get_records()
self.client.py_log(TEST_ENVIRON, records=records)
assert len(self.client.transport.log_queue) == 0
def test_multiple_handlers(self):
self.setUpClient()
logger = logging.getLogger('testing')
logger2 = logging.getLogger('other logger')
handler_cls = import_from_module('appenlight_client.ext.logging.logger:ThreadLocalHandler')
handler2 = register_logging(logger2, self.client.config, cls=handler_cls)
handler2.setLevel(logging.WARNING)
self.client.log_handlers.append(handler2)
logger.critical('test entry',
extra={"foobar": "baz",
"count": 15,
"price": 5.5,
'ae_permanent': 1,
"dictionary": {"a": "5"}
}
)
logger.info('this is info')
logger.debug('debug d')
logger2.debug('debug d2')
logger2.info('this is info')
logger2.warning('this is warning')
records = self.client.log_handlers_get_records()
new_log = records[0]
assert new_log['permanent'] is True
assert len(records) == 2
class TestSlowReportParsing(BaseTest):
def test_py_report_slow(self):
self.setUpClient()
self.maxDiff = None
self.client.py_report(TEST_ENVIRON, start_time=REQ_START_TIME,
end_time=REQ_END_TIME)
subset = PARSED_SLOW_REPORT
superset = self.client.transport.report_queue[0].items()
for i in six.iteritems(subset):
assert i in superset
class TestMakeMiddleware(BaseTest):
def test_make_middleware(self):
def app(environ, start_response):
start_response('200 OK', [('content-type', 'text/html')])
return ['Hello world!']
app = make_appenlight_middleware(app, {'appenlight.api_key': '12345'})
assert isinstance(app, AppenlightWSGIWrapper) is True
def test_make_middleware_disabled(self):
def app(environ, start_response):
start_response('200 OK', [('content-type', 'text/html')])
return ['Hello world!']
app = make_appenlight_middleware(app, {'appenlight': 'false'})
assert isinstance(app, AppenlightWSGIWrapper) is False
class TestCustomTiming(BaseTest):
def setup_method(self, method):
self.setUpClient(timing_conf)
def test_custom_time_trace(self):
@time_trace(name='foo_func', min_duration=0.1)
def foo(arg):
time.sleep(0.2)
return arg
foo('a')
stats, result = get_local_storage(local_timing).get_thread_stats()
assert len(result) == 1
def test_custom_nested_timimg(self):
@time_trace(name='baz_func', min_duration=0.1)
def baz(arg):
time.sleep(0.12)
return arg
@time_trace(name='foo_func', min_duration=0.1)
def foo(arg):
time.sleep(0.12)
return baz(arg)
@time_trace(name='bar_func', min_duration=0.1)
def bar(arg):
return foo(arg)
bar('a')
stats, result = get_local_storage(local_timing).get_thread_stats()
assert len(result) == 3
class TestTimingHTTPLibs(BaseTest):
def setup_method(self, method):
self.setUpClient(timing_conf)
def test_urllib_URLOpener_open(self):
import urllib
opener = urllib.URLopener()
opener.open("https://ubuntu.com/")
stats, result = get_local_storage(local_timing).get_thread_stats()
assert len(result) == 1
def test_urllib_urlretrieve(self):
import urllib
urllib.urlretrieve("https://ubuntu.com/")
stats, result = get_local_storage(local_timing).get_thread_stats()
assert len(result) == 1
def test_urllib2(self):
import urllib2
urllib2.urlopen("https://ubuntu.com/")
stats, result = get_local_storage(local_timing).get_thread_stats()
assert len(result) == 1
def test_urllib3(self):
try:
import urllib3
except ImportError:
return
http = urllib3.PoolManager()
http.request('GET', "https://ubuntu.com/")
stats, result = get_local_storage(local_timing).get_thread_stats()
assert len(result) == 1
def test_requests(self):
try:
import requests
except ImportError:
return
requests.get("https://ubuntu.com/")
stats, result = get_local_storage(local_timing).get_thread_stats()
assert len(result) == 1
def test_httplib(self):
import httplib
h2 = httplib.HTTPConnection("ubuntu.com")
h2.request("GET", "/")
stats, result = get_local_storage(local_timing).get_thread_stats()
assert len(result) == 1
class TestRedisPY(BaseTest):
def setup_method(self, method):
self.setUpClient(timing_conf)
def test_redis_py_command(self):
try:
import redis
except ImportError:
return
client = redis.StrictRedis()
client.setex('testval', 10, 'foo')
stats, result = get_local_storage(local_timing).get_thread_stats()
assert len(result) == 1