-
-
Notifications
You must be signed in to change notification settings - Fork 31.7k
/
Copy path__init__.py
2028 lines (1711 loc) · 78.7 KB
/
__init__.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
from contextlib import contextmanager
import linecache
import os
import importlib
import inspect
from io import StringIO
import re
import sys
import textwrap
import types
from typing import overload, get_overloads
import unittest
from test import support
from test.support import import_helper
from test.support import os_helper
from test.support import warnings_helper
from test.support import force_not_colorized
from test.support.script_helper import assert_python_ok, assert_python_failure
from test.test_warnings.data import package_helper
from test.test_warnings.data import stacklevel as warning_tests
import warnings as original_warnings
from warnings import deprecated
py_warnings = import_helper.import_fresh_module('_py_warnings')
py_warnings._set_module(py_warnings)
c_warnings = import_helper.import_fresh_module(
"warnings", fresh=["_warnings", "_py_warnings"]
)
c_warnings._set_module(c_warnings)
@contextmanager
def warnings_state(module):
"""Use a specific warnings implementation in warning_tests."""
global __warningregistry__
for to_clear in (sys, warning_tests):
try:
to_clear.__warningregistry__.clear()
except AttributeError:
pass
try:
__warningregistry__.clear()
except NameError:
pass
original_warnings = warning_tests.warnings
if module._use_context:
saved_context, context = module._new_context()
else:
original_filters = module.filters
module.filters = original_filters[:]
try:
module.simplefilter("once")
warning_tests.warnings = module
yield
finally:
warning_tests.warnings = original_warnings
if module._use_context:
module._set_context(saved_context)
else:
module.filters = original_filters
class TestWarning(Warning):
pass
class BaseTest:
"""Basic bookkeeping required for testing."""
def setUp(self):
self.old_unittest_module = unittest.case.warnings
# The __warningregistry__ needs to be in a pristine state for tests
# to work properly.
if '__warningregistry__' in globals():
del globals()['__warningregistry__']
if hasattr(warning_tests, '__warningregistry__'):
del warning_tests.__warningregistry__
if hasattr(sys, '__warningregistry__'):
del sys.__warningregistry__
# The 'warnings' module must be explicitly set so that the proper
# interaction between _warnings and 'warnings' can be controlled.
sys.modules['warnings'] = self.module
# Ensure that unittest.TestCase.assertWarns() uses the same warnings
# module than warnings.catch_warnings(). Otherwise,
# warnings.catch_warnings() will be unable to remove the added filter.
unittest.case.warnings = self.module
super(BaseTest, self).setUp()
def tearDown(self):
sys.modules['warnings'] = original_warnings
unittest.case.warnings = self.old_unittest_module
super(BaseTest, self).tearDown()
class PublicAPITests(BaseTest):
"""Ensures that the correct values are exposed in the
public API.
"""
def test_module_all_attribute(self):
self.assertTrue(hasattr(self.module, '__all__'))
target_api = ["warn", "warn_explicit", "showwarning",
"formatwarning", "filterwarnings", "simplefilter",
"resetwarnings", "catch_warnings", "deprecated"]
self.assertSetEqual(set(self.module.__all__),
set(target_api))
class CPublicAPITests(PublicAPITests, unittest.TestCase):
module = c_warnings
class PyPublicAPITests(PublicAPITests, unittest.TestCase):
module = py_warnings
class FilterTests(BaseTest):
"""Testing the filtering functionality."""
def test_error(self):
with self.module.catch_warnings() as w:
self.module.resetwarnings()
self.module.filterwarnings("error", category=UserWarning)
self.assertRaises(UserWarning, self.module.warn,
"FilterTests.test_error")
def test_error_after_default(self):
with self.module.catch_warnings() as w:
self.module.resetwarnings()
message = "FilterTests.test_ignore_after_default"
def f():
self.module.warn(message, UserWarning)
with support.captured_stderr() as stderr:
f()
stderr = stderr.getvalue()
self.assertIn("UserWarning: FilterTests.test_ignore_after_default",
stderr)
self.assertIn("self.module.warn(message, UserWarning)",
stderr)
self.module.filterwarnings("error", category=UserWarning)
self.assertRaises(UserWarning, f)
def test_ignore(self):
with self.module.catch_warnings(record=True) as w:
self.module.resetwarnings()
self.module.filterwarnings("ignore", category=UserWarning)
self.module.warn("FilterTests.test_ignore", UserWarning)
self.assertEqual(len(w), 0)
self.assertEqual(list(__warningregistry__), ['version'])
def test_ignore_after_default(self):
with self.module.catch_warnings(record=True) as w:
self.module.resetwarnings()
message = "FilterTests.test_ignore_after_default"
def f():
self.module.warn(message, UserWarning)
f()
self.module.filterwarnings("ignore", category=UserWarning)
f()
f()
self.assertEqual(len(w), 1)
def test_always_and_all(self):
for mode in {"always", "all"}:
with self.module.catch_warnings(record=True) as w:
self.module.resetwarnings()
self.module.filterwarnings(mode, category=UserWarning)
message = "FilterTests.test_always_and_all"
def f():
self.module.warn(message, UserWarning)
f()
self.assertEqual(len(w), 1)
self.assertEqual(w[-1].message.args[0], message)
f()
self.assertEqual(len(w), 2)
self.assertEqual(w[-1].message.args[0], message)
def test_always_and_all_after_default(self):
for mode in {"always", "all"}:
with self.module.catch_warnings(record=True) as w:
self.module.resetwarnings()
message = "FilterTests.test_always_and_all_after_ignore"
def f():
self.module.warn(message, UserWarning)
f()
self.assertEqual(len(w), 1)
self.assertEqual(w[-1].message.args[0], message)
f()
self.assertEqual(len(w), 1)
self.module.filterwarnings(mode, category=UserWarning)
f()
self.assertEqual(len(w), 2)
self.assertEqual(w[-1].message.args[0], message)
f()
self.assertEqual(len(w), 3)
self.assertEqual(w[-1].message.args[0], message)
def test_default(self):
with self.module.catch_warnings(record=True) as w:
self.module.resetwarnings()
self.module.filterwarnings("default", category=UserWarning)
message = UserWarning("FilterTests.test_default")
for x in range(2):
self.module.warn(message, UserWarning)
if x == 0:
self.assertEqual(w[-1].message, message)
del w[:]
elif x == 1:
self.assertEqual(len(w), 0)
else:
raise ValueError("loop variant unhandled")
def test_module(self):
with self.module.catch_warnings(record=True) as w:
self.module.resetwarnings()
self.module.filterwarnings("module", category=UserWarning)
message = UserWarning("FilterTests.test_module")
self.module.warn(message, UserWarning)
self.assertEqual(w[-1].message, message)
del w[:]
self.module.warn(message, UserWarning)
self.assertEqual(len(w), 0)
def test_once(self):
with self.module.catch_warnings(record=True) as w:
self.module.resetwarnings()
self.module.filterwarnings("once", category=UserWarning)
message = UserWarning("FilterTests.test_once")
self.module.warn_explicit(message, UserWarning, "__init__.py",
42)
self.assertEqual(w[-1].message, message)
del w[:]
self.module.warn_explicit(message, UserWarning, "__init__.py",
13)
self.assertEqual(len(w), 0)
self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
42)
self.assertEqual(len(w), 0)
def test_module_globals(self):
with self.module.catch_warnings(record=True) as w:
self.module.simplefilter("always", UserWarning)
# bpo-33509: module_globals=None must not crash
self.module.warn_explicit('msg', UserWarning, "filename", 42,
module_globals=None)
self.assertEqual(len(w), 1)
# Invalid module_globals type
with self.assertRaises(TypeError):
self.module.warn_explicit('msg', UserWarning, "filename", 42,
module_globals=True)
self.assertEqual(len(w), 1)
# Empty module_globals
self.module.warn_explicit('msg', UserWarning, "filename", 42,
module_globals={})
self.assertEqual(len(w), 2)
def test_inheritance(self):
with self.module.catch_warnings() as w:
self.module.resetwarnings()
self.module.filterwarnings("error", category=Warning)
self.assertRaises(UserWarning, self.module.warn,
"FilterTests.test_inheritance", UserWarning)
def test_ordering(self):
with self.module.catch_warnings(record=True) as w:
self.module.resetwarnings()
self.module.filterwarnings("ignore", category=UserWarning)
self.module.filterwarnings("error", category=UserWarning,
append=True)
del w[:]
try:
self.module.warn("FilterTests.test_ordering", UserWarning)
except UserWarning:
self.fail("order handling for actions failed")
self.assertEqual(len(w), 0)
def test_filterwarnings(self):
# Test filterwarnings().
# Implicitly also tests resetwarnings().
with self.module.catch_warnings(record=True) as w:
self.module.filterwarnings("error", "", Warning, "", 0)
self.assertRaises(UserWarning, self.module.warn, 'convert to error')
self.module.resetwarnings()
text = 'handle normally'
self.module.warn(text)
self.assertEqual(str(w[-1].message), text)
self.assertIs(w[-1].category, UserWarning)
self.module.filterwarnings("ignore", "", Warning, "", 0)
text = 'filtered out'
self.module.warn(text)
self.assertNotEqual(str(w[-1].message), text)
self.module.resetwarnings()
self.module.filterwarnings("error", "hex*", Warning, "", 0)
self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
text = 'nonmatching text'
self.module.warn(text)
self.assertEqual(str(w[-1].message), text)
self.assertIs(w[-1].category, UserWarning)
def test_message_matching(self):
with self.module.catch_warnings(record=True) as w:
self.module.simplefilter("ignore", UserWarning)
self.module.filterwarnings("error", "match", UserWarning)
self.assertRaises(UserWarning, self.module.warn, "match")
self.assertRaises(UserWarning, self.module.warn, "match prefix")
self.module.warn("suffix match")
self.assertEqual(w, [])
self.module.warn("something completely different")
self.assertEqual(w, [])
def test_mutate_filter_list(self):
class X:
def match(self, a):
L[:] = []
L = [("default",X(),UserWarning,X(),0) for i in range(2)]
with self.module.catch_warnings(record=True) as w:
self.module.filters = L
self.module.warn_explicit(UserWarning("b"), None, "f.py", 42)
self.assertEqual(str(w[-1].message), "b")
def test_filterwarnings_duplicate_filters(self):
with self.module.catch_warnings():
self.module.resetwarnings()
self.module.filterwarnings("error", category=UserWarning)
self.assertEqual(len(self.module._get_filters()), 1)
self.module.filterwarnings("ignore", category=UserWarning)
self.module.filterwarnings("error", category=UserWarning)
self.assertEqual(
len(self.module._get_filters()), 2,
"filterwarnings inserted duplicate filter"
)
self.assertEqual(
self.module._get_filters()[0][0], "error",
"filterwarnings did not promote filter to "
"the beginning of list"
)
def test_simplefilter_duplicate_filters(self):
with self.module.catch_warnings():
self.module.resetwarnings()
self.module.simplefilter("error", category=UserWarning)
self.assertEqual(len(self.module._get_filters()), 1)
self.module.simplefilter("ignore", category=UserWarning)
self.module.simplefilter("error", category=UserWarning)
self.assertEqual(
len(self.module._get_filters()), 2,
"simplefilter inserted duplicate filter"
)
self.assertEqual(
self.module._get_filters()[0][0], "error",
"simplefilter did not promote filter to the beginning of list"
)
def test_append_duplicate(self):
with self.module.catch_warnings(record=True) as w:
self.module.resetwarnings()
self.module.simplefilter("ignore")
self.module.simplefilter("error", append=True)
self.module.simplefilter("ignore", append=True)
self.module.warn("test_append_duplicate", category=UserWarning)
self.assertEqual(len(self.module._get_filters()), 2,
"simplefilter inserted duplicate filter"
)
self.assertEqual(len(w), 0,
"appended duplicate changed order of filters"
)
def test_argument_validation(self):
with self.assertRaises(ValueError):
self.module.filterwarnings(action='foo')
with self.assertRaises(TypeError):
self.module.filterwarnings('ignore', message=0)
with self.assertRaises(TypeError):
self.module.filterwarnings('ignore', category=0)
with self.assertRaises(TypeError):
self.module.filterwarnings('ignore', category=int)
with self.assertRaises(TypeError):
self.module.filterwarnings('ignore', module=0)
with self.assertRaises(TypeError):
self.module.filterwarnings('ignore', lineno=int)
with self.assertRaises(ValueError):
self.module.filterwarnings('ignore', lineno=-1)
with self.assertRaises(ValueError):
self.module.simplefilter(action='foo')
with self.assertRaises(TypeError):
self.module.simplefilter('ignore', lineno=int)
with self.assertRaises(ValueError):
self.module.simplefilter('ignore', lineno=-1)
def test_catchwarnings_with_simplefilter_ignore(self):
with self.module.catch_warnings(module=self.module):
self.module.resetwarnings()
self.module.simplefilter("error")
with self.module.catch_warnings(action="ignore"):
self.module.warn("This will be ignored")
def test_catchwarnings_with_simplefilter_error(self):
with self.module.catch_warnings():
self.module.resetwarnings()
with self.module.catch_warnings(
action="error", category=FutureWarning
):
with support.captured_stderr() as stderr:
error_msg = "Other types of warnings are not errors"
self.module.warn(error_msg)
self.assertRaises(FutureWarning,
self.module.warn, FutureWarning("msg"))
stderr = stderr.getvalue()
self.assertIn(error_msg, stderr)
class CFilterTests(FilterTests, unittest.TestCase):
module = c_warnings
class PyFilterTests(FilterTests, unittest.TestCase):
module = py_warnings
class WarnTests(BaseTest):
"""Test warnings.warn() and warnings.warn_explicit()."""
def test_message(self):
with self.module.catch_warnings(record=True) as w:
self.module.simplefilter("once")
for i in range(4):
text = 'multi %d' %i # Different text on each call.
self.module.warn(text)
self.assertEqual(str(w[-1].message), text)
self.assertIs(w[-1].category, UserWarning)
# Issue 3639
def test_warn_nonstandard_types(self):
# warn() should handle non-standard types without issue.
for ob in (Warning, None, 42):
with self.module.catch_warnings(record=True) as w:
self.module.simplefilter("once")
self.module.warn(ob)
# Don't directly compare objects since
# ``Warning() != Warning()``.
self.assertEqual(str(w[-1].message), str(UserWarning(ob)))
def test_filename(self):
with warnings_state(self.module):
with self.module.catch_warnings(record=True) as w:
warning_tests.inner("spam1")
self.assertEqual(os.path.basename(w[-1].filename),
"stacklevel.py")
warning_tests.outer("spam2")
self.assertEqual(os.path.basename(w[-1].filename),
"stacklevel.py")
def test_stacklevel(self):
# Test stacklevel argument
# make sure all messages are different, so the warning won't be skipped
with warnings_state(self.module):
with self.module.catch_warnings(record=True) as w:
warning_tests.inner("spam3", stacklevel=1)
self.assertEqual(os.path.basename(w[-1].filename),
"stacklevel.py")
warning_tests.outer("spam4", stacklevel=1)
self.assertEqual(os.path.basename(w[-1].filename),
"stacklevel.py")
warning_tests.inner("spam5", stacklevel=2)
self.assertEqual(os.path.basename(w[-1].filename),
"__init__.py")
warning_tests.outer("spam6", stacklevel=2)
self.assertEqual(os.path.basename(w[-1].filename),
"stacklevel.py")
warning_tests.outer("spam6.5", stacklevel=3)
self.assertEqual(os.path.basename(w[-1].filename),
"__init__.py")
warning_tests.inner("spam7", stacklevel=9999)
self.assertEqual(os.path.basename(w[-1].filename),
"<sys>")
def test_stacklevel_import(self):
# Issue #24305: With stacklevel=2, module-level warnings should work.
import_helper.unload('test.test_warnings.data.import_warning')
with warnings_state(self.module):
with self.module.catch_warnings(record=True) as w:
self.module.simplefilter('always')
import test.test_warnings.data.import_warning # noqa: F401
self.assertEqual(len(w), 1)
self.assertEqual(w[0].filename, __file__)
def test_skip_file_prefixes(self):
with warnings_state(self.module):
with self.module.catch_warnings(record=True) as w:
self.module.simplefilter('always')
# Warning never attributed to the data/ package.
package_helper.inner_api(
"inner_api", stacklevel=2,
warnings_module=warning_tests.warnings)
self.assertEqual(w[-1].filename, __file__)
warning_tests.package("package api", stacklevel=2)
self.assertEqual(w[-1].filename, __file__)
self.assertEqual(w[-2].filename, w[-1].filename)
# Low stacklevels are overridden to 2 behavior.
warning_tests.package("package api 1", stacklevel=1)
self.assertEqual(w[-1].filename, __file__)
warning_tests.package("package api 0", stacklevel=0)
self.assertEqual(w[-1].filename, __file__)
warning_tests.package("package api -99", stacklevel=-99)
self.assertEqual(w[-1].filename, __file__)
# The stacklevel still goes up out of the package.
warning_tests.package("prefix02", stacklevel=3)
self.assertIn("unittest", w[-1].filename)
def test_skip_file_prefixes_file_path(self):
# see: gh-126209
with warnings_state(self.module):
skipped = warning_tests.__file__
with self.module.catch_warnings(record=True) as w:
warning_tests.outer("msg", skip_file_prefixes=(skipped,))
self.assertEqual(len(w), 1)
self.assertNotEqual(w[-1].filename, skipped)
def test_skip_file_prefixes_type_errors(self):
with warnings_state(self.module):
warn = warning_tests.warnings.warn
with self.assertRaises(TypeError):
warn("msg", skip_file_prefixes=[])
with self.assertRaises(TypeError):
warn("msg", skip_file_prefixes=(b"bytes",))
with self.assertRaises(TypeError):
warn("msg", skip_file_prefixes="a sequence of strs")
def test_exec_filename(self):
filename = "<warnings-test>"
codeobj = compile(("import warnings\n"
"warnings.warn('hello', UserWarning)"),
filename, "exec")
with self.module.catch_warnings(record=True) as w:
self.module.simplefilter("always", category=UserWarning)
exec(codeobj)
self.assertEqual(w[0].filename, filename)
def test_warn_explicit_non_ascii_filename(self):
with self.module.catch_warnings(record=True) as w:
self.module.resetwarnings()
self.module.filterwarnings("always", category=UserWarning)
filenames = ["nonascii\xe9\u20ac"]
if not support.is_emscripten:
# JavaScript does not like surrogates.
# Invalid UTF-8 leading byte 0x80 encountered when
# deserializing a UTF-8 string in wasm memory to a JS
# string!
filenames.append("surrogate\udc80")
for filename in filenames:
try:
os.fsencode(filename)
except UnicodeEncodeError:
continue
self.module.warn_explicit("text", UserWarning, filename, 1)
self.assertEqual(w[-1].filename, filename)
def test_warn_explicit_type_errors(self):
# warn_explicit() should error out gracefully if it is given objects
# of the wrong types.
# lineno is expected to be an integer.
self.assertRaises(TypeError, self.module.warn_explicit,
None, UserWarning, None, None)
# Either 'message' needs to be an instance of Warning or 'category'
# needs to be a subclass.
self.assertRaises(TypeError, self.module.warn_explicit,
None, None, None, 1)
# 'registry' must be a dict or None.
self.assertRaises((TypeError, AttributeError),
self.module.warn_explicit,
None, Warning, None, 1, registry=42)
def test_bad_str(self):
# issue 6415
# Warnings instance with a bad format string for __str__ should not
# trigger a bus error.
class BadStrWarning(Warning):
"""Warning with a bad format string for __str__."""
def __str__(self):
return ("A bad formatted string %(err)" %
{"err" : "there is no %(err)s"})
with self.assertRaises(ValueError):
self.module.warn(BadStrWarning())
def test_warning_classes(self):
class MyWarningClass(Warning):
pass
class NonWarningSubclass:
pass
# passing a non-subclass of Warning should raise a TypeError
with self.assertRaises(TypeError) as cm:
self.module.warn('bad warning category', '')
self.assertIn('category must be a Warning subclass, not ',
str(cm.exception))
with self.assertRaises(TypeError) as cm:
self.module.warn('bad warning category', NonWarningSubclass)
self.assertIn('category must be a Warning subclass, not ',
str(cm.exception))
# check that warning instances also raise a TypeError
with self.assertRaises(TypeError) as cm:
self.module.warn('bad warning category', MyWarningClass())
self.assertIn('category must be a Warning subclass, not ',
str(cm.exception))
with self.module.catch_warnings():
self.module.resetwarnings()
self.module.filterwarnings('default')
with self.assertWarns(MyWarningClass) as cm:
self.module.warn('good warning category', MyWarningClass)
self.assertEqual('good warning category', str(cm.warning))
with self.assertWarns(UserWarning) as cm:
self.module.warn('good warning category', None)
self.assertEqual('good warning category', str(cm.warning))
with self.assertWarns(MyWarningClass) as cm:
self.module.warn('good warning category', MyWarningClass)
self.assertIsInstance(cm.warning, Warning)
def check_module_globals(self, module_globals):
with self.module.catch_warnings(record=True) as w:
self.module.filterwarnings('default')
self.module.warn_explicit(
'eggs', UserWarning, 'bar', 1,
module_globals=module_globals)
self.assertEqual(len(w), 1)
self.assertEqual(w[0].category, UserWarning)
self.assertEqual(str(w[0].message), 'eggs')
def check_module_globals_error(self, module_globals, errmsg, errtype=ValueError):
if self.module is py_warnings:
self.check_module_globals(module_globals)
return
with self.module.catch_warnings(record=True) as w:
self.module.filterwarnings('always')
with self.assertRaisesRegex(errtype, re.escape(errmsg)):
self.module.warn_explicit(
'eggs', UserWarning, 'bar', 1,
module_globals=module_globals)
self.assertEqual(len(w), 0)
def check_module_globals_deprecated(self, module_globals, msg):
if self.module is py_warnings:
self.check_module_globals(module_globals)
return
with self.module.catch_warnings(record=True) as w:
self.module.filterwarnings('always')
self.module.warn_explicit(
'eggs', UserWarning, 'bar', 1,
module_globals=module_globals)
self.assertEqual(len(w), 2)
self.assertEqual(w[0].category, DeprecationWarning)
self.assertEqual(str(w[0].message), msg)
self.assertEqual(w[1].category, UserWarning)
self.assertEqual(str(w[1].message), 'eggs')
def test_gh86298_no_loader_and_no_spec(self):
self.check_module_globals({'__name__': 'bar'})
def test_gh86298_loader_is_none_and_no_spec(self):
self.check_module_globals({'__name__': 'bar', '__loader__': None})
def test_gh86298_no_loader_and_spec_is_none(self):
self.check_module_globals_error(
{'__name__': 'bar', '__spec__': None},
'Module globals is missing a __spec__.loader')
def test_gh86298_loader_is_none_and_spec_is_none(self):
self.check_module_globals_error(
{'__name__': 'bar', '__loader__': None, '__spec__': None},
'Module globals is missing a __spec__.loader')
def test_gh86298_loader_is_none_and_spec_loader_is_none(self):
self.check_module_globals_error(
{'__name__': 'bar', '__loader__': None,
'__spec__': types.SimpleNamespace(loader=None)},
'Module globals is missing a __spec__.loader')
def test_gh86298_no_spec(self):
self.check_module_globals_deprecated(
{'__name__': 'bar', '__loader__': object()},
'Module globals is missing a __spec__.loader')
def test_gh86298_spec_is_none(self):
self.check_module_globals_deprecated(
{'__name__': 'bar', '__loader__': object(), '__spec__': None},
'Module globals is missing a __spec__.loader')
def test_gh86298_no_spec_loader(self):
self.check_module_globals_deprecated(
{'__name__': 'bar', '__loader__': object(),
'__spec__': types.SimpleNamespace()},
'Module globals is missing a __spec__.loader')
def test_gh86298_loader_and_spec_loader_disagree(self):
self.check_module_globals_deprecated(
{'__name__': 'bar', '__loader__': object(),
'__spec__': types.SimpleNamespace(loader=object())},
'Module globals; __loader__ != __spec__.loader')
def test_gh86298_no_loader_and_no_spec_loader(self):
self.check_module_globals_error(
{'__name__': 'bar', '__spec__': types.SimpleNamespace()},
'Module globals is missing a __spec__.loader', AttributeError)
def test_gh86298_no_loader_with_spec_loader_okay(self):
self.check_module_globals(
{'__name__': 'bar',
'__spec__': types.SimpleNamespace(loader=object())})
class CWarnTests(WarnTests, unittest.TestCase):
module = c_warnings
# As an early adopter, we sanity check the
# test.import_helper.import_fresh_module utility function
def test_accelerated(self):
self.assertIsNot(original_warnings, self.module)
self.assertFalse(hasattr(self.module.warn, '__code__'))
class PyWarnTests(WarnTests, unittest.TestCase):
module = py_warnings
# As an early adopter, we sanity check the
# test.import_helper.import_fresh_module utility function
def test_pure_python(self):
self.assertIsNot(original_warnings, self.module)
self.assertTrue(hasattr(self.module.warn, '__code__'))
class WCmdLineTests(BaseTest):
def test_improper_input(self):
# Uses the private _setoption() function to test the parsing
# of command-line warning arguments
with self.module.catch_warnings():
self.assertRaises(self.module._OptionError,
self.module._setoption, '1:2:3:4:5:6')
self.assertRaises(self.module._OptionError,
self.module._setoption, 'bogus::Warning')
self.assertRaises(self.module._OptionError,
self.module._setoption, 'ignore:2::4:-5')
with self.assertRaises(self.module._OptionError):
self.module._setoption('ignore::123')
with self.assertRaises(self.module._OptionError):
self.module._setoption('ignore::123abc')
with self.assertRaises(self.module._OptionError):
self.module._setoption('ignore::===')
with self.assertRaisesRegex(self.module._OptionError, 'Wärning'):
self.module._setoption('ignore::Wärning')
self.module._setoption('error::Warning::0')
self.assertRaises(UserWarning, self.module.warn, 'convert to error')
def test_import_from_module(self):
with self.module.catch_warnings():
self.module._setoption('ignore::Warning')
with self.assertRaises(self.module._OptionError):
self.module._setoption('ignore::TestWarning')
with self.assertRaises(self.module._OptionError):
self.module._setoption('ignore::test.test_warnings.bogus')
self.module._setoption('error::test.test_warnings.TestWarning')
with self.assertRaises(TestWarning):
self.module.warn('test warning', TestWarning)
class CWCmdLineTests(WCmdLineTests, unittest.TestCase):
module = c_warnings
class PyWCmdLineTests(WCmdLineTests, unittest.TestCase):
module = py_warnings
def test_improper_option(self):
# Same as above, but check that the message is printed out when
# the interpreter is executed. This also checks that options are
# actually parsed at all.
rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")
self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)
def test_warnings_bootstrap(self):
# Check that the warnings module does get loaded when -W<some option>
# is used (see issue #10372 for an example of silent bootstrap failure).
rc, out, err = assert_python_ok("-Wi", "-c",
"import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
# '-Wi' was observed
self.assertFalse(out.strip())
self.assertNotIn(b'RuntimeWarning', err)
class _WarningsTests(BaseTest, unittest.TestCase):
"""Tests specific to the _warnings module."""
module = c_warnings
def test_filter(self):
# Everything should function even if 'filters' is not in warnings.
with self.module.catch_warnings() as w:
self.module.filterwarnings("error", "", Warning, "", 0)
self.assertRaises(UserWarning, self.module.warn,
'convert to error')
del self.module.filters
self.assertRaises(UserWarning, self.module.warn,
'convert to error')
def test_onceregistry(self):
# Replacing or removing the onceregistry should be okay.
global __warningregistry__
message = UserWarning('onceregistry test')
try:
original_registry = self.module.onceregistry
__warningregistry__ = {}
with self.module.catch_warnings(record=True) as w:
self.module.resetwarnings()
self.module.filterwarnings("once", category=UserWarning)
self.module.warn_explicit(message, UserWarning, "file", 42)
self.assertEqual(w[-1].message, message)
del w[:]
self.module.warn_explicit(message, UserWarning, "file", 42)
self.assertEqual(len(w), 0)
# Test the resetting of onceregistry.
self.module.onceregistry = {}
__warningregistry__ = {}
self.module.warn('onceregistry test')
self.assertEqual(w[-1].message.args, message.args)
# Removal of onceregistry is okay.
del w[:]
del self.module.onceregistry
__warningregistry__ = {}
self.module.warn_explicit(message, UserWarning, "file", 42)
self.assertEqual(len(w), 0)
finally:
self.module.onceregistry = original_registry
def test_default_action(self):
# Replacing or removing defaultaction should be okay.
message = UserWarning("defaultaction test")
original = self.module.defaultaction
try:
with self.module.catch_warnings(record=True) as w:
self.module.resetwarnings()
registry = {}
self.module.warn_explicit(message, UserWarning, "<test>", 42,
registry=registry)
self.assertEqual(w[-1].message, message)
self.assertEqual(len(w), 1)
# One actual registry key plus the "version" key
self.assertEqual(len(registry), 2)
self.assertIn("version", registry)
del w[:]
# Test removal.
del self.module.defaultaction
__warningregistry__ = {}
registry = {}
self.module.warn_explicit(message, UserWarning, "<test>", 43,
registry=registry)
self.assertEqual(w[-1].message, message)
self.assertEqual(len(w), 1)
self.assertEqual(len(registry), 2)
del w[:]
# Test setting.
self.module.defaultaction = "ignore"
__warningregistry__ = {}
registry = {}
self.module.warn_explicit(message, UserWarning, "<test>", 44,
registry=registry)
self.assertEqual(len(w), 0)
finally:
self.module.defaultaction = original
def test_showwarning_missing(self):
# Test that showwarning() missing is okay.
if self.module._use_context:
# If _use_context is true, the warnings module does not
# override/restore showwarning()
return
text = 'del showwarning test'
with self.module.catch_warnings():
self.module.filterwarnings("always", category=UserWarning)
del self.module.showwarning
with support.captured_output('stderr') as stream:
self.module.warn(text)
result = stream.getvalue()
self.assertIn(text, result)
def test_showwarnmsg_missing(self):
# Test that _showwarnmsg() missing is okay.
text = 'del _showwarnmsg test'
with self.module.catch_warnings():
self.module.filterwarnings("always", category=UserWarning)
show = self.module._showwarnmsg
try:
del self.module._showwarnmsg
with support.captured_output('stderr') as stream:
self.module.warn(text)
result = stream.getvalue()
finally:
self.module._showwarnmsg = show
self.assertIn(text, result)
def test_showwarning_not_callable(self):
orig = self.module.showwarning
try:
with self.module.catch_warnings():
self.module.filterwarnings("always", category=UserWarning)
self.module.showwarning = print
with support.captured_output('stdout'):
self.module.warn('Warning!')
self.module.showwarning = 23
self.assertRaises(TypeError, self.module.warn, "Warning!")
finally:
self.module.showwarning = orig
def test_show_warning_output(self):
# With showwarning() missing, make sure that output is okay.
orig = self.module.showwarning
try:
text = 'test show_warning'
with self.module.catch_warnings():
self.module.filterwarnings("always", category=UserWarning)
del self.module.showwarning
with support.captured_output('stderr') as stream:
warning_tests.inner(text)
result = stream.getvalue()
self.assertEqual(result.count('\n'), 2,
"Too many newlines in %r" % result)
first_line, second_line = result.split('\n', 1)
expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
first_line_parts = first_line.rsplit(':', 3)
path, line, warning_class, message = first_line_parts
line = int(line)
self.assertEqual(expected_file, path)
self.assertEqual(warning_class, ' ' + UserWarning.__name__)
self.assertEqual(message, ' ' + text)
expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
assert expected_line
self.assertEqual(second_line, expected_line)
finally:
self.module.showwarning = orig
def test_filename_none(self):
# issue #12467: race condition if a warning is emitted at shutdown
globals_dict = globals()
oldfile = globals_dict['__file__']
try:
catch = self.module.catch_warnings(record=True)
with catch as w:
self.module.filterwarnings("always", category=UserWarning)
globals_dict['__file__'] = None
self.module.warn('test', UserWarning)
self.assertTrue(len(w))
finally:
globals_dict['__file__'] = oldfile
def test_stderr_none(self):
rc, stdout, stderr = assert_python_ok("-c",
"import sys; sys.stderr = None; "
"import warnings; warnings.simplefilter('always'); "
"warnings.warn('Warning!')")
self.assertEqual(stdout, b'')
self.assertNotIn(b'Warning!', stderr)
self.assertNotIn(b'Error', stderr)
def test_issue31285(self):
# warn_explicit() should neither raise a SystemError nor cause an
# assertion failure, in case the return value of get_source() has a
# bad splitlines() method.
get_source_called = []
def get_module_globals(*, splitlines_ret_val):
class BadSource(str):
def splitlines(self):
return splitlines_ret_val
class BadLoader:
def get_source(self, fullname):
get_source_called.append(splitlines_ret_val)
return BadSource('spam')
loader = BadLoader()
spec = importlib.machinery.ModuleSpec('foobar', loader)