This file is indexed.

/usr/lib/python2.7/dist-packages/zope/exceptions/tests/test_exceptionformatter.py is in python-zope.exceptions 4.0.8-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""ExceptionFormatter tests.
"""
import unittest
import doctest
import sys


class TextExceptionFormatterTests(unittest.TestCase):

    def _getTargetClass(self):
        from zope.exceptions.exceptionformatter import TextExceptionFormatter
        return TextExceptionFormatter

    def _makeOne(self, *args, **kw):
        return self._getTargetClass()(*args, **kw)

    def test_ctor_defaults(self):
        fmt = self._makeOne()
        self.assertEqual(fmt.line_sep, '\n')
        self.assertEqual(fmt.limit, None)
        self.assertEqual(fmt.with_filenames, False)

    def test_ctor_explicit(self):
        fmt = self._makeOne(limit=20, with_filenames=True)
        self.assertEqual(fmt.line_sep, '\n')
        self.assertEqual(fmt.limit, 20)
        self.assertEqual(fmt.with_filenames, True)

    def test_escape(self):
        fmt = self._makeOne()
        self.assertEqual(fmt.escape('XXX'), 'XXX')

    def test_getPrefix(self):
        fmt = self._makeOne()
        self.assertEqual(fmt.getPrefix(),
                         'Traceback (most recent call last):')

    def test_getLimit_default(self):
        fmt = self._makeOne()
        self.assertEqual(fmt.getLimit(), 200)

    def test_getLimit_sys_has_limit(self):
        import sys
        fmt = self._makeOne()
        with _Monkey(sys, tracebacklimit=15):
            self.assertEqual(fmt.getLimit(), 15)

    def test_getLimit_explicit(self):
        fmt = self._makeOne(limit=10)
        self.assertEqual(fmt.getLimit(), 10)

    def test_formatSupplementLine(self):
        fmt = self._makeOne()
        self.assertEqual(fmt.formatSupplementLine('XXX'), '   - XXX')

    def test_formatSourceURL(self):
        fmt = self._makeOne()
        self.assertEqual(fmt.formatSourceURL('http://example.com/'),
                         ['   - http://example.com/'])

    def test_formatSupplement_no_info(self):
        fmt = self._makeOne()
        supplement = DummySupplement()
        self.assertEqual(fmt.formatSupplement(supplement, tb=None), [])

    def test_formatSupplement_w_source_url(self):
        fmt = self._makeOne()
        supplement = DummySupplement()
        supplement.source_url = 'http://example.com/'
        self.assertEqual(fmt.formatSupplement(supplement, tb=None),
                         ['   - http://example.com/'])

    def test_formatSupplement_w_line_as_marker(self):
        fmt = self._makeOne()
        supplement = DummySupplement()
        supplement.line = -1
        tb = DummyTB()
        self.assertEqual(fmt.formatSupplement(supplement, tb=tb),
                         ['   - Line 14'])

    def test_formatSupplement_w_line_no_column(self):
        fmt = self._makeOne()
        supplement = DummySupplement()
        supplement.line = 23
        self.assertEqual(fmt.formatSupplement(supplement, tb=None),
                         ['   - Line 23'])

    def test_formatSupplement_w_column_no_line(self):
        fmt = self._makeOne()
        supplement = DummySupplement()
        supplement.column = 47
        self.assertEqual(fmt.formatSupplement(supplement, tb=None),
                         ['   - Column 47'])

    def test_formatSupplement_w_line_and_column(self):
        fmt = self._makeOne()
        supplement = DummySupplement()
        supplement.line = 23
        supplement.column = 47
        self.assertEqual(fmt.formatSupplement(supplement, tb=None),
                         ['   - Line 23, Column 47'])

    def test_formatSupplement_w_expression(self):
        fmt = self._makeOne()
        supplement = DummySupplement()
        supplement.expression = 'a*x^2 + b*x + c'
        self.assertEqual(fmt.formatSupplement(supplement, tb=None),
                         ['   - Expression: a*x^2 + b*x + c'])

    def test_formatSupplement_w_warnings(self):
        fmt = self._makeOne()
        supplement = DummySupplement()
        supplement.warnings = ['Beware the ides of March!',
                               'You\'re gonna get wasted.',
                              ]
        self.assertEqual(fmt.formatSupplement(supplement, tb=None),
                         ['   - Warning: Beware the ides of March!',
                          '   - Warning: You\'re gonna get wasted.',
                         ])

    def test_formatSupplement_w_getInfo_empty(self):
        fmt = self._makeOne()
        supplement = DummySupplement()
        self.assertEqual(fmt.formatSupplement(supplement, tb=None), [])

    def test_formatSupplement_w_getInfo_text(self):
        INFO = 'Some days\nI wish I had stayed in bed.'
        fmt = self._makeOne()
        supplement = DummySupplement(INFO)
        self.assertEqual(fmt.formatSupplement(supplement, tb=None), [INFO])

    def test_formatSupplementInfo(self):
        INFO = 'Some days\nI wish I had stayed in bed.'
        fmt = self._makeOne()
        self.assertEqual(fmt.formatSupplementInfo(INFO), INFO)

    def test_formatTracebackInfo(self):
        fmt = self._makeOne()
        self.assertEqual(fmt.formatTracebackInfo('XYZZY'),
                         '   - __traceback_info__: XYZZY')

    def test_formatLine_no_tb_no_f(self):
        fmt = self._makeOne()
        self.assertRaises(ValueError, fmt.formatLine, None, None)

    def test_formatLine_w_tb_and_f(self):
        fmt = self._makeOne()
        tb = DummyTB()
        f = DummyFrame()
        self.assertRaises(ValueError, fmt.formatLine, tb, f)

    def test_formatLine_w_tb_bogus_linecache_w_filenames(self):
        fmt = self._makeOne(with_filenames=True)
        tb = DummyTB()
        tb.tb_frame = f = DummyFrame()
        lines = fmt.formatLine(tb).splitlines()
        self.assertEqual(len(lines), 1)
        self.assertEqual(lines[0],
                         '  File "%s", line %d, in %s'
                          % (f.f_code.co_filename,
                             tb.tb_lineno,
                             f.f_code.co_name,
                            ))

    def test_formatLine_w_f_bogus_linecache_w_filenames(self):
        fmt = self._makeOne(with_filenames=True)
        f = DummyFrame()
        lines = fmt.formatLine(f=f).splitlines()
        self.assertEqual(len(lines), 1)
        self.assertEqual(lines[0],
                         '  File "%s", line %d, in %s'
                          % (f.f_code.co_filename,
                             f.f_lineno,
                             f.f_code.co_name,
                            ))

    def test_formatLine_w_tb_bogus_linecache_wo_filenames(self):
        fmt = self._makeOne(with_filenames=False)
        tb = DummyTB()
        tb.tb_frame = f = DummyFrame()
        f.f_globals['__name__'] = 'dummy.filename'
        lines = fmt.formatLine(tb).splitlines()
        self.assertEqual(len(lines), 1)
        self.assertEqual(lines[0],
                         '  Module dummy.filename, line %d, in %s'
                          % (tb.tb_lineno,
                             f.f_code.co_name,
                            ))

    def test_formatLine_w_f_real_linecache_w_filenames(self):
        import sys
        fmt = self._makeOne(with_filenames=True)
        f = sys._getframe(); lineno = f.f_lineno
        result = fmt.formatLine(f=f)
        lines = result.splitlines()
        self.assertEqual(len(lines), 2)
        self.assertEqual(lines[0],
                         '  File "%s", line %d, in %s'
                          % (f.f_code.co_filename,
                             lineno + 1,
                             f.f_code.co_name,
                            ))
        self.assertEqual(lines[1],
                         '    result = fmt.formatLine(f=f)')

    def test_formatLine_w_supplement_in_locals(self):
        INFO_L = 'I wish I had stayed in bed.'
        INFO_G = 'I would rather soak my head.'
        fmt = self._makeOne(with_filenames=False)
        tb = DummyTB()
        tb.tb_frame = f = DummyFrame()
        f.f_globals['__name__'] = 'dummy.filename'
        f.f_locals['__traceback_supplement__'] = (DummySupplement, INFO_L)
        f.f_globals['__traceback_supplement__'] = (DummySupplement, INFO_G)
        lines = fmt.formatLine(tb).splitlines()
        self.assertEqual(len(lines), 2)
        self.assertEqual(lines[1], INFO_L)

    def test_formatLine_w_supplement_in_globals(self):
        INFO_G = 'I would rather soak my head.'
        fmt = self._makeOne(with_filenames=False)
        tb = DummyTB()
        tb.tb_frame = f = DummyFrame()
        f.f_globals['__name__'] = 'dummy.filename'
        f.f_globals['__traceback_supplement__'] = (DummySupplement, INFO_G)
        lines = fmt.formatLine(tb).splitlines()
        self.assertEqual(len(lines), 2)
        self.assertEqual(lines[1], INFO_G)

    def test_formatLine_w_traceback_info(self):
        INFO_T = 'I would rather soak my head.'
        fmt = self._makeOne(with_filenames=False)
        tb = DummyTB()
        tb.tb_frame = f = DummyFrame()
        f.f_globals['__name__'] = 'dummy.filename'
        f.f_locals['__traceback_info__'] = INFO_T
        lines = fmt.formatLine(tb).splitlines()
        self.assertEqual(len(lines), 2)
        self.assertEqual(lines[1], '   - __traceback_info__: %s' % INFO_T)

    def test_formatExceptionOnly(self):
        import traceback
        fmt = self._makeOne()
        err = ValueError('testing')
        self.assertEqual(fmt.formatExceptionOnly(ValueError, err),
                         ''.join(
                            traceback.format_exception_only(ValueError, err)))

    def test_formatLastLine(self):
        fmt = self._makeOne()
        self.assertEqual(fmt.formatLastLine('XXX'), 'XXX')

    def test_formatException_empty_tb_stack(self):
        import traceback
        fmt = self._makeOne()
        err = ValueError('testing')
        lines = fmt.formatException(ValueError, err, None)
        self.assertEqual(len(lines), 2)
        self.assertEqual(lines[0], 'Traceback (most recent call last):\n')
        self.assertEqual(lines[1],
                         ''.join(
                            traceback.format_exception_only(ValueError, err)))

    def test_formatException_non_empty_tb_stack(self):
        import traceback
        fmt = self._makeOne()
        err = ValueError('testing')
        tb = DummyTB()
        tb.tb_frame = DummyFrame()
        lines = fmt.formatException(ValueError, err, tb)
        self.assertEqual(len(lines), 3)
        self.assertEqual(lines[0], 'Traceback (most recent call last):\n')
        self.assertEqual(lines[1], '  Module dummy/filename.py, line 14, '
                                   'in dummy_function\n')
        self.assertEqual(lines[2],
                         ''.join(
                            traceback.format_exception_only(ValueError, err)))

    def test_formatException_deep_tb_stack_with_limit(self):
        import traceback
        fmt = self._makeOne(limit=4)
        err = ValueError('testing')
        tb = self._makeTBs(10)
        lines = fmt.formatException(ValueError, err, tb)

        self.assertEqual(len(lines), 7)

        expected = [
            'Traceback (most recent call last):\n',
            '  Module dummy/filename.py, line 4345, in dummy_function\n',
            '  Module dummy/filename.py, line 2287, in dummy_function\n',
            ('...\n'
             '6 entries omitted, because limit is 4.\n'
             'Set sys.tracebacklimit or TextExceptionFormatter.limit to'
             ' a higher value to see omitted entries\n'
             '...'),
            '  Module dummy/filename.py, line 26, in dummy_function\n',
            '  Module dummy/filename.py, line 14, in dummy_function\n',
            ''.join(traceback.format_exception_only(ValueError, err))
            ]
        self.assertEqual(lines, expected)

    def test_formatException_recursion_in_tb_stack(self):
        import traceback
        fmt = self._makeOne()
        err = ValueError('testing')
        tb_recurse = DummyTB()
        tb_recurse.tb_lineno = 27
        r_f = tb_recurse.tb_frame = DummyFrame()
        r_f.f_lineno = 27
        r_f.f_locals['__exception_formatter__'] = 1
        tb = DummyTB()
        tb.tb_frame = DummyFrame()
        tb.tb_next = tb_recurse
        lines = fmt.formatException(ValueError, err, tb)
        self.assertEqual(len(lines), 5)
        self.assertEqual(lines[0], 'Traceback (most recent call last):\n')
        self.assertEqual(lines[1], '  Module dummy/filename.py, line 14, '
                                   'in dummy_function\n')
        self.assertEqual(lines[2], '(Recursive formatException() stopped, '
                                   'trying traceback.format_tb)\n')
        self.assertEqual(lines[3], '  File "dummy/filename.py", line 27, '
                                   'in dummy_function\n')
        self.assertEqual(lines[4],
                         ''.join(
                            traceback.format_exception_only(ValueError, err)))

    def test_extractStack_wo_frame(self):
        import sys
        fmt = self._makeOne()
        f = sys._getframe(); lineno = f.f_lineno
        lines = fmt.extractStack()
        # rather don't assert this here
        # self.assertEqual(len(lines), 10)
        self.assertEqual(lines[-1], '  Module '
                         'zope.exceptions.tests.test_exceptionformatter, '
                         'line %d, in test_extractStack_wo_frame\n'
                         '    lines = fmt.extractStack()\n' % (lineno + 1))

    def test_extractStack_wo_frame_w_limit(self):
        import sys
        fmt = self._makeOne(limit=2)
        f = sys._getframe(); lineno = f.f_lineno
        lines = fmt.extractStack()
        self.assertEqual(len(lines), 3)
        self.assertEqual(lines[-1], '  Module '
                         'zope.exceptions.tests.test_exceptionformatter, '
                         'line %d, in test_extractStack_wo_frame_w_limit\n'
                         '    lines = fmt.extractStack()\n' % (lineno + 1))

    def test_extractStack_w_single_frame(self):
        fmt = self._makeOne()
        f = DummyFrame()
        lines = fmt.extractStack(f)
        self.assertEqual(len(lines), 1)
        self.assertEqual(lines[0], '  Module dummy/filename.py, line 137, '
                                   'in dummy_function\n')

    def test_extractStack_w_multiple_frames_and_limit(self):
        fmt = self._makeOne(limit=2)
        f = self._makeFrames(10)
        lines = fmt.extractStack(f)

        self.assertEqual(len(lines), 3)

        expected = [
            '  Module dummy/filename.py, line 17, in dummy_function\n',
            '...8 entries omitted, because limit is 2...\n',
            '  Module dummy/filename.py, line 1126, in dummy_function\n',
            ]

        self.assertEqual(expected, lines)

    def test_extractStack_w_recursive_frames(self):
        fmt = self._makeOne()
        f = self._makeFrames(3)
        f.f_back.f_locals['__exception_formatter__'] = 1
        lines = fmt.extractStack(f)
        self.assertEqual(len(lines), 4)

        expected = [
            '  File "dummy/filename.py", line 17, in dummy_function\n',
            '  File "dummy/filename.py", line 27, in dummy_function\n',
            '(Recursive extractStack() stopped, trying traceback.format_stack)\n',
            '  Module dummy/filename.py, line 43, in dummy_function\n',
            ]

        self.assertEqual(expected, lines)

    def test_extractStack_w_recursive_frames_and_limit(self):
        fmt = self._makeOne(limit=2)
        f = self._makeFrames(3)
        f.f_back.f_locals['__exception_formatter__'] = 1
        lines = fmt.extractStack(f)
        self.assertEqual(len(lines), 3)

        expected = [
            '  File "dummy/filename.py", line 17, in dummy_function\n',
            '...2 entries omitted, because limit is 2...\n',
            '  Module dummy/filename.py, line 43, in dummy_function\n',
            ]

        self.assertEqual(expected, lines)

    def _makeTBs(self, count):
        prev = None
        for i in range(count):
            tb = DummyTB()
            tb.tb_lineno = 14
            tb.tb_frame = DummyFrame()
            if prev is not None:
                tb.tb_lineno = int(prev.tb_lineno * 1.9)
                tb.tb_next = prev
            prev = tb
        return tb

    def _makeFrames(self, count):
        prev = None
        for i in range(count):
            f = DummyFrame()
            f.f_lineno = 17
            if prev is not None:
                f.f_lineno = int(prev.f_lineno * 1.6)
                f.f_back = prev
            prev = f
        return f


class HTMLExceptionFormatterTests(unittest.TestCase):

    def _getTargetClass(self):
        from zope.exceptions.exceptionformatter import HTMLExceptionFormatter
        return HTMLExceptionFormatter

    def _makeOne(self, *args, **kw):
        return self._getTargetClass()(*args, **kw)

    def test_ctor_defaults(self):
        fmt = self._makeOne()
        self.assertEqual(fmt.line_sep, '<br />\r\n')
        self.assertEqual(fmt.limit, None)
        self.assertEqual(fmt.with_filenames, False)

    def test_ctor_explicit(self):
        fmt = self._makeOne(limit=20, with_filenames=True)
        self.assertEqual(fmt.line_sep, '<br />\r\n')
        self.assertEqual(fmt.limit, 20)
        self.assertEqual(fmt.with_filenames, True)

    def test_escape_simple(self):
        fmt = self._makeOne()
        self.assertEqual(fmt.escape('XXX'), 'XXX')

    def test_escape_w_markup(self):
        fmt = self._makeOne()
        self.assertEqual(fmt.escape('<span>XXX & YYY<span>'),
                                    '&lt;span&gt;XXX &amp; YYY&lt;span&gt;')

    def test_getPrefix(self):
        fmt = self._makeOne()
        self.assertEqual(fmt.getPrefix(),
                         '<p>Traceback (most recent call last):</p>\r\n<ul>')

    def test_formatSupplementLine(self):
        fmt = self._makeOne()
        self.assertEqual(fmt.formatSupplementLine('XXX'), '<b>XXX</b>')

    def test_formatSupplementLine_w_markup(self):
        fmt = self._makeOne()
        self.assertEqual(fmt.formatSupplementLine('XXX & YYY'),
                         '<b>XXX &amp; YYY</b>')

    def test_formatSupplementInfo_simple(self):
        INFO = 'Some days\nI wonder.'
        fmt = self._makeOne()
        self.assertEqual(fmt.formatSupplementInfo(INFO),
                         'Some&nbsp;days<br />\r\nI&nbsp;wonder.')

    def test_formatSupplementInfo_w_markup(self):
        INFO = 'Some days\nI wonder, <b>Why?</b>.'
        fmt = self._makeOne()
        self.assertEqual(fmt.formatSupplementInfo(INFO),
                         'Some&nbsp;days<br />\r\nI&nbsp;wonder,&nbsp;'
                         '&lt;b&gt;Why?&lt;/b&gt;.')

    def test_formatTracebackInfo(self):
        fmt = self._makeOne()
        self.assertEqual(fmt.formatTracebackInfo('XXX & YYY\nZZZ'),
                         '__traceback_info__: XXX &amp; YYY<br />\r\nZZZ')

    def test_formatLine_simple(self):
        fmt = self._makeOne(with_filenames=True)
        tb = DummyTB()
        tb.tb_frame = f = DummyFrame()
        result = fmt.formatLine(tb)
        self.assertEqual(result,
                         '<li>  File "%s", line %d, in %s</li>'
                          % (f.f_code.co_filename,
                             tb.tb_lineno,
                             f.f_code.co_name,
                            ))

    def test_formatLastLine(self):
        fmt = self._makeOne()
        self.assertEqual(fmt.formatLastLine('XXX'), '</ul><p>XXX</p>')


class Test_format_exception(unittest.TestCase):

    def _callFUT(self, as_html=False):
        import sys
        from zope.exceptions.exceptionformatter import format_exception
        t, v, b = sys.exc_info()
        try:
            return ''.join(format_exception(t, v, b, as_html=as_html))
        finally:
            del b

    def test_basic_names_text(self):
        try:
            raise ExceptionForTesting
        except ExceptionForTesting:
            s = self._callFUT(False)
        # The traceback should include the name of this function.
        self.assertTrue(s.find('test_basic_names_text') >= 0)
        # The traceback should include the name of the exception.
        self.assertTrue(s.find('ExceptionForTesting') >= 0)

    def test_basic_names_html(self):
        try:
            raise ExceptionForTesting
        except ExceptionForTesting:
            s = self._callFUT(True)
        # The traceback should include the name of this function.
        self.assertTrue(s.find('test_basic_names_html') >= 0)
        # The traceback should include the name of the exception.
        self.assertTrue(s.find('ExceptionForTesting') >= 0)

    def test_traceback_info_text(self):
        try:
            __traceback_info__ = "Adam & Eve"
            raise ExceptionForTesting
        except ExceptionForTesting:
            s = self._callFUT(False)
        self.assertTrue(s.find('Adam & Eve') >= 0, s)

    def test_traceback_info_html(self):
        try:
            __traceback_info__ = "Adam & Eve"
            raise ExceptionForTesting
        except ExceptionForTesting:
            s = self._callFUT(True)
        # Be sure quoting is happening.
        self.assertTrue(s.find('Adam &amp; Eve') >= 0, s)

    def test_traceback_info_is_tuple(self):
        try:
            __traceback_info__ = ("Adam", "Eve")
            raise ExceptionForTesting
        except ExceptionForTesting:
            s = self._callFUT(False)
        self.assertTrue(s.find('Adam') >= 0, s)
        self.assertTrue(s.find('Eve') >= 0, s)

    def test_supplement_text(self, as_html=0):
        try:
            __traceback_supplement__ = (TestingTracebackSupplement,
                                        "You're one in a million")
            raise ExceptionForTesting
        except ExceptionForTesting:
            s = self._callFUT(as_html)
        # The source URL
        self.assertTrue(s.find('/somepath') >= 0, s)
        # The line number
        self.assertTrue(s.find('634') >= 0, s)
        # The column number
        self.assertTrue(s.find('57') >= 0, s)
        # The expression
        self.assertTrue(s.find("You're one in a million") >= 0, s)
        # The warning
        self.assertTrue(s.find("Repent, for the end is nigh") >= 0, s)

    def test_supplement_html(self):
        try:
            __traceback_supplement__ = (TestingTracebackSupplement,
                                        "You're one in a million")
            raise ExceptionForTesting
        except ExceptionForTesting:
            s = self._callFUT(True)
        # The source URL
        self.assertTrue(s.find('/somepath') >= 0, s)
        # The line number
        self.assertTrue(s.find('634') >= 0, s)
        # The column number
        self.assertTrue(s.find('57') >= 0, s)
        # The expression
        self.assertTrue(s.find("You're one in a million") >= 0, s)
        # The warning
        self.assertTrue(s.find("Repent, for the end is nigh") >= 0, s)

    def test_multiple_levels(self):
        # Ensure many levels are shown in a traceback.
        HOW_MANY = 10
        def f(n):
            """Produces a (n + 1)-level traceback."""
            __traceback_info__ = 'level%d' % n
            if n > 0:
                f(n - 1)
            else:
                raise ExceptionForTesting
        try:
            f(HOW_MANY)
        except ExceptionForTesting:
            s = self._callFUT(False)
        for n in range(HOW_MANY+1):
            self.assertTrue(s.find('level%d' % n) >= 0, s)

    def test_quote_last_line(self):
        class C(object):
            pass
        try:
            raise TypeError(C())
        except:
            s = self._callFUT(True)
        self.assertTrue(s.find('&lt;') >= 0, s)
        self.assertTrue(s.find('&gt;') >= 0, s)

    def test_multiline_exception(self):
        try:
            exec('syntax error\n')
        except Exception:
            s = self._callFUT(False)
        lines = s.splitlines()[-3:]
        self.assertEqual(lines[0], '    syntax error')
        self.assertTrue(lines[1].endswith('    ^')) #PyPy has a shorter prefix
        self.assertEqual(lines[2], 'SyntaxError: invalid syntax')

    def test_recursion_failure(self):
        import sys
        from zope.exceptions.exceptionformatter import TextExceptionFormatter

        class FormatterException(Exception):
            pass

        class FailingFormatter(TextExceptionFormatter):
            def formatLine(self, tb=None, f=None):
                raise FormatterException("Formatter failed")

        fmt = FailingFormatter()
        try:
            raise ExceptionForTesting
        except ExceptionForTesting:
            try:
                fmt.formatException(*sys.exc_info())
            except FormatterException:
                s = self._callFUT(False)
        # Recursion was detected
        self.assertTrue('(Recursive formatException() stopped, '
                        'trying traceback.format_tb)' in s, s)
        # and we fellback to the stdlib rather than hid the real error
        self.assertEqual(s.splitlines()[-2],
                         '    raise FormatterException("Formatter failed")')
        self.assertTrue('FormatterException: Formatter failed'
                        in s.splitlines()[-1])


class Test_print_exception(unittest.TestCase):

    def _callFUT(self, as_html=False):
        try:
            from StringIO import StringIO
        except ImportError:
            from io import StringIO
        buf = StringIO()
        import sys
        from zope.exceptions.exceptionformatter import print_exception
        t, v, b = sys.exc_info()
        try:
            print_exception(t, v, b, file=buf, as_html=as_html)
            return buf.getvalue()
        finally:
            del b

    def test_basic_names_text(self):
        try:
            raise ExceptionForTesting
        except ExceptionForTesting:
            s = self._callFUT(False)
        # The traceback should include the name of this function.
        self.assertTrue(s.find('test_basic_names_text') >= 0)
        # The traceback should include the name of the exception.
        self.assertTrue(s.find('ExceptionForTesting') >= 0)

    def test_basic_names_html(self):
        try:
            raise ExceptionForTesting
        except ExceptionForTesting:
            s = self._callFUT(True)
        # The traceback should include the name of this function.
        self.assertTrue(s.find('test_basic_names_html') >= 0)
        # The traceback should include the name of the exception.
        self.assertTrue(s.find('ExceptionForTesting') >= 0)


class Test_extract_stack(unittest.TestCase):

    def _callFUT(self, as_html=False):
        import sys
        from zope.exceptions.exceptionformatter import extract_stack
        f = sys.exc_info()[2].tb_frame
        try:
            return ''.join(extract_stack(f, as_html=as_html))
        finally:
            del f

    def test_basic_names_as_text(self, as_html=0):
        try:
            raise ExceptionForTesting
        except ExceptionForTesting:
            s = self._callFUT(False)
        # The stack trace should include the name of this function.
        self.assertTrue(s.find('test_basic_names_as_text') >= 0)

    def test_basic_names_as_html(self):
        try:
            raise ExceptionForTesting
        except ExceptionForTesting:
            s = self._callFUT(True)
        # The stack trace should include the name of this function.
        self.assertTrue(s.find('test_basic_names_as_html') >= 0)

    def test_traceback_info_text(self):
        try:
            __traceback_info__ = "Adam & Eve"
            raise ExceptionForTesting
        except ExceptionForTesting:
            s = self._callFUT(False)
        self.assertTrue(s.find('Adam & Eve') >= 0, s)

    def test_traceback_info_html(self):
        try:
            __traceback_info__ = "Adam & Eve"
            raise ExceptionForTesting
        except ExceptionForTesting:
            s = self._callFUT(True)
        self.assertTrue(s.find('Adam &amp; Eve') >= 0, s)

    def test_traceback_supplement_text(self):
        try:
            __traceback_supplement__ = (TestingTracebackSupplement,
                                        "You're one in a million")
            raise ExceptionForTesting
        except ExceptionForTesting:
            s = self._callFUT(False)
        # The source URL
        self.assertTrue(s.find('/somepath') >= 0, s)
        # The line number
        self.assertTrue(s.find('634') >= 0, s)
        # The column number
        self.assertTrue(s.find('57') >= 0, s)
        # The expression
        self.assertTrue(s.find("You're one in a million") >= 0, s)
        # The warning
        self.assertTrue(s.find("Repent, for the end is nigh") >= 0, s)

    def test_traceback_supplement_html(self):
        try:
            __traceback_supplement__ = (TestingTracebackSupplement,
                                        "You're one in a million")
            raise ExceptionForTesting
        except ExceptionForTesting:
            s = self._callFUT(True)
        # The source URL
        self.assertTrue(s.find('/somepath') >= 0, s)
        # The line number
        self.assertTrue(s.find('634') >= 0, s)
        # The column number
        self.assertTrue(s.find('57') >= 0, s)
        # The expression
        self.assertTrue(s.find("You're one in a million") >= 0, s)
        # The warning
        self.assertTrue(s.find("Repent, for the end is nigh") >= 0, s)


class ExceptionForTesting (Exception):
    pass


class TestingTracebackSupplement(object):
    source_url = '/somepath'
    line = 634
    column = 57
    warnings = ['Repent, for the end is nigh']
    def __init__(self, expression):
        self.expression = expression


class DummySupplement(object):
    def __init__(self, info=''):
        self._info = info
    def getInfo(self):
        return self._info


class DummyTB(object):
    tb_lineno = 14
    tb_next = None


class DummyFrame(object):
    f_lineno = 137
    f_back = None
    def __init__(self):
        self.f_locals = {}
        self.f_globals = {}
        self.f_code = DummyCode()

class DummyCode(object):
    co_filename = 'dummy/filename.py'
    co_name = 'dummy_function'

class _Monkey(object):
    # context-manager for replacing module names in the scope of a test.
    def __init__(self, module, **kw):
        self.module = module
        self.to_restore = dict([(key, getattr(module, key, self))
                                    for key in kw])
        for key, value in kw.items():
            setattr(module, key, value)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        for key, value in self.to_restore.items():
            if value is not self:
                setattr(self.module, key, value)
            else:
                delattr(self.module, key)


def doctest_format_exception_as_html():
    """Test for format_exception (as_html=True)

        >>> from zope.exceptions.exceptionformatter import format_exception
        >>> try:
        ...     exec('import 2 + 2')
        ... except:
        ...     print(''.join(format_exception(*sys.exc_info(), as_html=True)))
        <p>Traceback (most recent call last):</p>
        <ul>
        <li>  Module zope.exceptions.tests.test_exceptionformatter, line 2, in &lt;module&gt;<br />
            exec('import 2 + 2')</li>
        </ul><p>  File "&lt;string&gt;", line 1<br />
            import 2 + 2<br />
                   ^<br />
        SyntaxError: invalid syntax<br />
        </p>

    """


def test_suite():
    return unittest.TestSuite([
        unittest.defaultTestLoader.loadTestsFromName(__name__),
        doctest.DocTestSuite(
                optionflags=doctest.NORMALIZE_WHITESPACE),
    ])