• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1from contextlib import contextmanager
2import linecache
3import os
4from io import StringIO
5import re
6import sys
7import textwrap
8import unittest
9from test import support
10from test.support import import_helper
11from test.support import os_helper
12from test.support import warnings_helper
13from test.support.script_helper import assert_python_ok, assert_python_failure
14
15from test.test_warnings.data import stacklevel as warning_tests
16
17import warnings as original_warnings
18
19
20py_warnings = import_helper.import_fresh_module('warnings',
21                                                blocked=['_warnings'])
22c_warnings = import_helper.import_fresh_module('warnings',
23                                               fresh=['_warnings'])
24
25Py_DEBUG = hasattr(sys, 'gettotalrefcount')
26
27@contextmanager
28def warnings_state(module):
29    """Use a specific warnings implementation in warning_tests."""
30    global __warningregistry__
31    for to_clear in (sys, warning_tests):
32        try:
33            to_clear.__warningregistry__.clear()
34        except AttributeError:
35            pass
36    try:
37        __warningregistry__.clear()
38    except NameError:
39        pass
40    original_warnings = warning_tests.warnings
41    original_filters = module.filters
42    try:
43        module.filters = original_filters[:]
44        module.simplefilter("once")
45        warning_tests.warnings = module
46        yield
47    finally:
48        warning_tests.warnings = original_warnings
49        module.filters = original_filters
50
51
52class TestWarning(Warning):
53    pass
54
55
56class BaseTest:
57
58    """Basic bookkeeping required for testing."""
59
60    def setUp(self):
61        self.old_unittest_module = unittest.case.warnings
62        # The __warningregistry__ needs to be in a pristine state for tests
63        # to work properly.
64        if '__warningregistry__' in globals():
65            del globals()['__warningregistry__']
66        if hasattr(warning_tests, '__warningregistry__'):
67            del warning_tests.__warningregistry__
68        if hasattr(sys, '__warningregistry__'):
69            del sys.__warningregistry__
70        # The 'warnings' module must be explicitly set so that the proper
71        # interaction between _warnings and 'warnings' can be controlled.
72        sys.modules['warnings'] = self.module
73        # Ensure that unittest.TestCase.assertWarns() uses the same warnings
74        # module than warnings.catch_warnings(). Otherwise,
75        # warnings.catch_warnings() will be unable to remove the added filter.
76        unittest.case.warnings = self.module
77        super(BaseTest, self).setUp()
78
79    def tearDown(self):
80        sys.modules['warnings'] = original_warnings
81        unittest.case.warnings = self.old_unittest_module
82        super(BaseTest, self).tearDown()
83
84class PublicAPITests(BaseTest):
85
86    """Ensures that the correct values are exposed in the
87    public API.
88    """
89
90    def test_module_all_attribute(self):
91        self.assertTrue(hasattr(self.module, '__all__'))
92        target_api = ["warn", "warn_explicit", "showwarning",
93                      "formatwarning", "filterwarnings", "simplefilter",
94                      "resetwarnings", "catch_warnings"]
95        self.assertSetEqual(set(self.module.__all__),
96                            set(target_api))
97
98class CPublicAPITests(PublicAPITests, unittest.TestCase):
99    module = c_warnings
100
101class PyPublicAPITests(PublicAPITests, unittest.TestCase):
102    module = py_warnings
103
104class FilterTests(BaseTest):
105
106    """Testing the filtering functionality."""
107
108    def test_error(self):
109        with original_warnings.catch_warnings(module=self.module) as w:
110            self.module.resetwarnings()
111            self.module.filterwarnings("error", category=UserWarning)
112            self.assertRaises(UserWarning, self.module.warn,
113                                "FilterTests.test_error")
114
115    def test_error_after_default(self):
116        with original_warnings.catch_warnings(module=self.module) as w:
117            self.module.resetwarnings()
118            message = "FilterTests.test_ignore_after_default"
119            def f():
120                self.module.warn(message, UserWarning)
121
122            with support.captured_stderr() as stderr:
123                f()
124            stderr = stderr.getvalue()
125            self.assertIn("UserWarning: FilterTests.test_ignore_after_default",
126                          stderr)
127            self.assertIn("self.module.warn(message, UserWarning)",
128                          stderr)
129
130            self.module.filterwarnings("error", category=UserWarning)
131            self.assertRaises(UserWarning, f)
132
133    def test_ignore(self):
134        with original_warnings.catch_warnings(record=True,
135                module=self.module) as w:
136            self.module.resetwarnings()
137            self.module.filterwarnings("ignore", category=UserWarning)
138            self.module.warn("FilterTests.test_ignore", UserWarning)
139            self.assertEqual(len(w), 0)
140            self.assertEqual(list(__warningregistry__), ['version'])
141
142    def test_ignore_after_default(self):
143        with original_warnings.catch_warnings(record=True,
144                module=self.module) as w:
145            self.module.resetwarnings()
146            message = "FilterTests.test_ignore_after_default"
147            def f():
148                self.module.warn(message, UserWarning)
149            f()
150            self.module.filterwarnings("ignore", category=UserWarning)
151            f()
152            f()
153            self.assertEqual(len(w), 1)
154
155    def test_always(self):
156        with original_warnings.catch_warnings(record=True,
157                module=self.module) as w:
158            self.module.resetwarnings()
159            self.module.filterwarnings("always", category=UserWarning)
160            message = "FilterTests.test_always"
161            def f():
162                self.module.warn(message, UserWarning)
163            f()
164            self.assertEqual(len(w), 1)
165            self.assertEqual(w[-1].message.args[0], message)
166            f()
167            self.assertEqual(len(w), 2)
168            self.assertEqual(w[-1].message.args[0], message)
169
170    def test_always_after_default(self):
171        with original_warnings.catch_warnings(record=True,
172                module=self.module) as w:
173            self.module.resetwarnings()
174            message = "FilterTests.test_always_after_ignore"
175            def f():
176                self.module.warn(message, UserWarning)
177            f()
178            self.assertEqual(len(w), 1)
179            self.assertEqual(w[-1].message.args[0], message)
180            f()
181            self.assertEqual(len(w), 1)
182            self.module.filterwarnings("always", category=UserWarning)
183            f()
184            self.assertEqual(len(w), 2)
185            self.assertEqual(w[-1].message.args[0], message)
186            f()
187            self.assertEqual(len(w), 3)
188            self.assertEqual(w[-1].message.args[0], message)
189
190    def test_default(self):
191        with original_warnings.catch_warnings(record=True,
192                module=self.module) as w:
193            self.module.resetwarnings()
194            self.module.filterwarnings("default", category=UserWarning)
195            message = UserWarning("FilterTests.test_default")
196            for x in range(2):
197                self.module.warn(message, UserWarning)
198                if x == 0:
199                    self.assertEqual(w[-1].message, message)
200                    del w[:]
201                elif x == 1:
202                    self.assertEqual(len(w), 0)
203                else:
204                    raise ValueError("loop variant unhandled")
205
206    def test_module(self):
207        with original_warnings.catch_warnings(record=True,
208                module=self.module) as w:
209            self.module.resetwarnings()
210            self.module.filterwarnings("module", category=UserWarning)
211            message = UserWarning("FilterTests.test_module")
212            self.module.warn(message, UserWarning)
213            self.assertEqual(w[-1].message, message)
214            del w[:]
215            self.module.warn(message, UserWarning)
216            self.assertEqual(len(w), 0)
217
218    def test_once(self):
219        with original_warnings.catch_warnings(record=True,
220                module=self.module) as w:
221            self.module.resetwarnings()
222            self.module.filterwarnings("once", category=UserWarning)
223            message = UserWarning("FilterTests.test_once")
224            self.module.warn_explicit(message, UserWarning, "__init__.py",
225                                    42)
226            self.assertEqual(w[-1].message, message)
227            del w[:]
228            self.module.warn_explicit(message, UserWarning, "__init__.py",
229                                    13)
230            self.assertEqual(len(w), 0)
231            self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
232                                    42)
233            self.assertEqual(len(w), 0)
234
235    def test_module_globals(self):
236        with original_warnings.catch_warnings(record=True,
237                module=self.module) as w:
238            self.module.simplefilter("always", UserWarning)
239
240            # bpo-33509: module_globals=None must not crash
241            self.module.warn_explicit('msg', UserWarning, "filename", 42,
242                                      module_globals=None)
243            self.assertEqual(len(w), 1)
244
245            # Invalid module_globals type
246            with self.assertRaises(TypeError):
247                self.module.warn_explicit('msg', UserWarning, "filename", 42,
248                                          module_globals=True)
249            self.assertEqual(len(w), 1)
250
251            # Empty module_globals
252            self.module.warn_explicit('msg', UserWarning, "filename", 42,
253                                      module_globals={})
254            self.assertEqual(len(w), 2)
255
256    def test_inheritance(self):
257        with original_warnings.catch_warnings(module=self.module) as w:
258            self.module.resetwarnings()
259            self.module.filterwarnings("error", category=Warning)
260            self.assertRaises(UserWarning, self.module.warn,
261                                "FilterTests.test_inheritance", UserWarning)
262
263    def test_ordering(self):
264        with original_warnings.catch_warnings(record=True,
265                module=self.module) as w:
266            self.module.resetwarnings()
267            self.module.filterwarnings("ignore", category=UserWarning)
268            self.module.filterwarnings("error", category=UserWarning,
269                                        append=True)
270            del w[:]
271            try:
272                self.module.warn("FilterTests.test_ordering", UserWarning)
273            except UserWarning:
274                self.fail("order handling for actions failed")
275            self.assertEqual(len(w), 0)
276
277    def test_filterwarnings(self):
278        # Test filterwarnings().
279        # Implicitly also tests resetwarnings().
280        with original_warnings.catch_warnings(record=True,
281                module=self.module) as w:
282            self.module.filterwarnings("error", "", Warning, "", 0)
283            self.assertRaises(UserWarning, self.module.warn, 'convert to error')
284
285            self.module.resetwarnings()
286            text = 'handle normally'
287            self.module.warn(text)
288            self.assertEqual(str(w[-1].message), text)
289            self.assertIs(w[-1].category, UserWarning)
290
291            self.module.filterwarnings("ignore", "", Warning, "", 0)
292            text = 'filtered out'
293            self.module.warn(text)
294            self.assertNotEqual(str(w[-1].message), text)
295
296            self.module.resetwarnings()
297            self.module.filterwarnings("error", "hex*", Warning, "", 0)
298            self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
299            text = 'nonmatching text'
300            self.module.warn(text)
301            self.assertEqual(str(w[-1].message), text)
302            self.assertIs(w[-1].category, UserWarning)
303
304    def test_message_matching(self):
305        with original_warnings.catch_warnings(record=True,
306                module=self.module) as w:
307            self.module.simplefilter("ignore", UserWarning)
308            self.module.filterwarnings("error", "match", UserWarning)
309            self.assertRaises(UserWarning, self.module.warn, "match")
310            self.assertRaises(UserWarning, self.module.warn, "match prefix")
311            self.module.warn("suffix match")
312            self.assertEqual(w, [])
313            self.module.warn("something completely different")
314            self.assertEqual(w, [])
315
316    def test_mutate_filter_list(self):
317        class X:
318            def match(self, a):
319                L[:] = []
320
321        L = [("default",X(),UserWarning,X(),0) for i in range(2)]
322        with original_warnings.catch_warnings(record=True,
323                module=self.module) as w:
324            self.module.filters = L
325            self.module.warn_explicit(UserWarning("b"), None, "f.py", 42)
326            self.assertEqual(str(w[-1].message), "b")
327
328    def test_filterwarnings_duplicate_filters(self):
329        with original_warnings.catch_warnings(module=self.module):
330            self.module.resetwarnings()
331            self.module.filterwarnings("error", category=UserWarning)
332            self.assertEqual(len(self.module.filters), 1)
333            self.module.filterwarnings("ignore", category=UserWarning)
334            self.module.filterwarnings("error", category=UserWarning)
335            self.assertEqual(
336                len(self.module.filters), 2,
337                "filterwarnings inserted duplicate filter"
338            )
339            self.assertEqual(
340                self.module.filters[0][0], "error",
341                "filterwarnings did not promote filter to "
342                "the beginning of list"
343            )
344
345    def test_simplefilter_duplicate_filters(self):
346        with original_warnings.catch_warnings(module=self.module):
347            self.module.resetwarnings()
348            self.module.simplefilter("error", category=UserWarning)
349            self.assertEqual(len(self.module.filters), 1)
350            self.module.simplefilter("ignore", category=UserWarning)
351            self.module.simplefilter("error", category=UserWarning)
352            self.assertEqual(
353                len(self.module.filters), 2,
354                "simplefilter inserted duplicate filter"
355            )
356            self.assertEqual(
357                self.module.filters[0][0], "error",
358                "simplefilter did not promote filter to the beginning of list"
359            )
360
361    def test_append_duplicate(self):
362        with original_warnings.catch_warnings(module=self.module,
363                record=True) as w:
364            self.module.resetwarnings()
365            self.module.simplefilter("ignore")
366            self.module.simplefilter("error", append=True)
367            self.module.simplefilter("ignore", append=True)
368            self.module.warn("test_append_duplicate", category=UserWarning)
369            self.assertEqual(len(self.module.filters), 2,
370                "simplefilter inserted duplicate filter"
371            )
372            self.assertEqual(len(w), 0,
373                "appended duplicate changed order of filters"
374            )
375
376class CFilterTests(FilterTests, unittest.TestCase):
377    module = c_warnings
378
379class PyFilterTests(FilterTests, unittest.TestCase):
380    module = py_warnings
381
382
383class WarnTests(BaseTest):
384
385    """Test warnings.warn() and warnings.warn_explicit()."""
386
387    def test_message(self):
388        with original_warnings.catch_warnings(record=True,
389                module=self.module) as w:
390            self.module.simplefilter("once")
391            for i in range(4):
392                text = 'multi %d' %i  # Different text on each call.
393                self.module.warn(text)
394                self.assertEqual(str(w[-1].message), text)
395                self.assertIs(w[-1].category, UserWarning)
396
397    # Issue 3639
398    def test_warn_nonstandard_types(self):
399        # warn() should handle non-standard types without issue.
400        for ob in (Warning, None, 42):
401            with original_warnings.catch_warnings(record=True,
402                    module=self.module) as w:
403                self.module.simplefilter("once")
404                self.module.warn(ob)
405                # Don't directly compare objects since
406                # ``Warning() != Warning()``.
407                self.assertEqual(str(w[-1].message), str(UserWarning(ob)))
408
409    def test_filename(self):
410        with warnings_state(self.module):
411            with original_warnings.catch_warnings(record=True,
412                    module=self.module) as w:
413                warning_tests.inner("spam1")
414                self.assertEqual(os.path.basename(w[-1].filename),
415                                    "stacklevel.py")
416                warning_tests.outer("spam2")
417                self.assertEqual(os.path.basename(w[-1].filename),
418                                    "stacklevel.py")
419
420    def test_stacklevel(self):
421        # Test stacklevel argument
422        # make sure all messages are different, so the warning won't be skipped
423        with warnings_state(self.module):
424            with original_warnings.catch_warnings(record=True,
425                    module=self.module) as w:
426                warning_tests.inner("spam3", stacklevel=1)
427                self.assertEqual(os.path.basename(w[-1].filename),
428                                    "stacklevel.py")
429                warning_tests.outer("spam4", stacklevel=1)
430                self.assertEqual(os.path.basename(w[-1].filename),
431                                    "stacklevel.py")
432
433                warning_tests.inner("spam5", stacklevel=2)
434                self.assertEqual(os.path.basename(w[-1].filename),
435                                    "__init__.py")
436                warning_tests.outer("spam6", stacklevel=2)
437                self.assertEqual(os.path.basename(w[-1].filename),
438                                    "stacklevel.py")
439                warning_tests.outer("spam6.5", stacklevel=3)
440                self.assertEqual(os.path.basename(w[-1].filename),
441                                    "__init__.py")
442
443                warning_tests.inner("spam7", stacklevel=9999)
444                self.assertEqual(os.path.basename(w[-1].filename),
445                                    "sys")
446
447    def test_stacklevel_import(self):
448        # Issue #24305: With stacklevel=2, module-level warnings should work.
449        import_helper.unload('test.test_warnings.data.import_warning')
450        with warnings_state(self.module):
451            with original_warnings.catch_warnings(record=True,
452                    module=self.module) as w:
453                self.module.simplefilter('always')
454                import test.test_warnings.data.import_warning
455                self.assertEqual(len(w), 1)
456                self.assertEqual(w[0].filename, __file__)
457
458    def test_exec_filename(self):
459        filename = "<warnings-test>"
460        codeobj = compile(("import warnings\n"
461                           "warnings.warn('hello', UserWarning)"),
462                          filename, "exec")
463        with original_warnings.catch_warnings(record=True) as w:
464            self.module.simplefilter("always", category=UserWarning)
465            exec(codeobj)
466        self.assertEqual(w[0].filename, filename)
467
468    def test_warn_explicit_non_ascii_filename(self):
469        with original_warnings.catch_warnings(record=True,
470                module=self.module) as w:
471            self.module.resetwarnings()
472            self.module.filterwarnings("always", category=UserWarning)
473            for filename in ("nonascii\xe9\u20ac", "surrogate\udc80"):
474                try:
475                    os.fsencode(filename)
476                except UnicodeEncodeError:
477                    continue
478                self.module.warn_explicit("text", UserWarning, filename, 1)
479                self.assertEqual(w[-1].filename, filename)
480
481    def test_warn_explicit_type_errors(self):
482        # warn_explicit() should error out gracefully if it is given objects
483        # of the wrong types.
484        # lineno is expected to be an integer.
485        self.assertRaises(TypeError, self.module.warn_explicit,
486                            None, UserWarning, None, None)
487        # Either 'message' needs to be an instance of Warning or 'category'
488        # needs to be a subclass.
489        self.assertRaises(TypeError, self.module.warn_explicit,
490                            None, None, None, 1)
491        # 'registry' must be a dict or None.
492        self.assertRaises((TypeError, AttributeError),
493                            self.module.warn_explicit,
494                            None, Warning, None, 1, registry=42)
495
496    def test_bad_str(self):
497        # issue 6415
498        # Warnings instance with a bad format string for __str__ should not
499        # trigger a bus error.
500        class BadStrWarning(Warning):
501            """Warning with a bad format string for __str__."""
502            def __str__(self):
503                return ("A bad formatted string %(err)" %
504                        {"err" : "there is no %(err)s"})
505
506        with self.assertRaises(ValueError):
507            self.module.warn(BadStrWarning())
508
509    def test_warning_classes(self):
510        class MyWarningClass(Warning):
511            pass
512
513        class NonWarningSubclass:
514            pass
515
516        # passing a non-subclass of Warning should raise a TypeError
517        with self.assertRaises(TypeError) as cm:
518            self.module.warn('bad warning category', '')
519        self.assertIn('category must be a Warning subclass, not ',
520                      str(cm.exception))
521
522        with self.assertRaises(TypeError) as cm:
523            self.module.warn('bad warning category', NonWarningSubclass)
524        self.assertIn('category must be a Warning subclass, not ',
525                      str(cm.exception))
526
527        # check that warning instances also raise a TypeError
528        with self.assertRaises(TypeError) as cm:
529            self.module.warn('bad warning category', MyWarningClass())
530        self.assertIn('category must be a Warning subclass, not ',
531                      str(cm.exception))
532
533        with original_warnings.catch_warnings(module=self.module):
534            self.module.resetwarnings()
535            self.module.filterwarnings('default')
536            with self.assertWarns(MyWarningClass) as cm:
537                self.module.warn('good warning category', MyWarningClass)
538            self.assertEqual('good warning category', str(cm.warning))
539
540            with self.assertWarns(UserWarning) as cm:
541                self.module.warn('good warning category', None)
542            self.assertEqual('good warning category', str(cm.warning))
543
544            with self.assertWarns(MyWarningClass) as cm:
545                self.module.warn('good warning category', MyWarningClass)
546            self.assertIsInstance(cm.warning, Warning)
547
548class CWarnTests(WarnTests, unittest.TestCase):
549    module = c_warnings
550
551    # As an early adopter, we sanity check the
552    # test.import_helper.import_fresh_module utility function
553    def test_accelerated(self):
554        self.assertIsNot(original_warnings, self.module)
555        self.assertFalse(hasattr(self.module.warn, '__code__'))
556
557class PyWarnTests(WarnTests, unittest.TestCase):
558    module = py_warnings
559
560    # As an early adopter, we sanity check the
561    # test.import_helper.import_fresh_module utility function
562    def test_pure_python(self):
563        self.assertIsNot(original_warnings, self.module)
564        self.assertTrue(hasattr(self.module.warn, '__code__'))
565
566
567class WCmdLineTests(BaseTest):
568
569    def test_improper_input(self):
570        # Uses the private _setoption() function to test the parsing
571        # of command-line warning arguments
572        with original_warnings.catch_warnings(module=self.module):
573            self.assertRaises(self.module._OptionError,
574                              self.module._setoption, '1:2:3:4:5:6')
575            self.assertRaises(self.module._OptionError,
576                              self.module._setoption, 'bogus::Warning')
577            self.assertRaises(self.module._OptionError,
578                              self.module._setoption, 'ignore:2::4:-5')
579            with self.assertRaises(self.module._OptionError):
580                self.module._setoption('ignore::123')
581            with self.assertRaises(self.module._OptionError):
582                self.module._setoption('ignore::123abc')
583            with self.assertRaises(self.module._OptionError):
584                self.module._setoption('ignore::===')
585            with self.assertRaisesRegex(self.module._OptionError, 'Wärning'):
586                self.module._setoption('ignore::Wärning')
587            self.module._setoption('error::Warning::0')
588            self.assertRaises(UserWarning, self.module.warn, 'convert to error')
589
590    def test_import_from_module(self):
591        with original_warnings.catch_warnings(module=self.module):
592            self.module._setoption('ignore::Warning')
593            with self.assertRaises(self.module._OptionError):
594                self.module._setoption('ignore::TestWarning')
595            with self.assertRaises(self.module._OptionError):
596                self.module._setoption('ignore::test.test_warnings.bogus')
597            self.module._setoption('error::test.test_warnings.TestWarning')
598            with self.assertRaises(TestWarning):
599                self.module.warn('test warning', TestWarning)
600
601
602class CWCmdLineTests(WCmdLineTests, unittest.TestCase):
603    module = c_warnings
604
605
606class PyWCmdLineTests(WCmdLineTests, unittest.TestCase):
607    module = py_warnings
608
609    def test_improper_option(self):
610        # Same as above, but check that the message is printed out when
611        # the interpreter is executed. This also checks that options are
612        # actually parsed at all.
613        rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")
614        self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)
615
616    def test_warnings_bootstrap(self):
617        # Check that the warnings module does get loaded when -W<some option>
618        # is used (see issue #10372 for an example of silent bootstrap failure).
619        rc, out, err = assert_python_ok("-Wi", "-c",
620            "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
621        # '-Wi' was observed
622        self.assertFalse(out.strip())
623        self.assertNotIn(b'RuntimeWarning', err)
624
625
626class _WarningsTests(BaseTest, unittest.TestCase):
627
628    """Tests specific to the _warnings module."""
629
630    module = c_warnings
631
632    def test_filter(self):
633        # Everything should function even if 'filters' is not in warnings.
634        with original_warnings.catch_warnings(module=self.module) as w:
635            self.module.filterwarnings("error", "", Warning, "", 0)
636            self.assertRaises(UserWarning, self.module.warn,
637                                'convert to error')
638            del self.module.filters
639            self.assertRaises(UserWarning, self.module.warn,
640                                'convert to error')
641
642    def test_onceregistry(self):
643        # Replacing or removing the onceregistry should be okay.
644        global __warningregistry__
645        message = UserWarning('onceregistry test')
646        try:
647            original_registry = self.module.onceregistry
648            __warningregistry__ = {}
649            with original_warnings.catch_warnings(record=True,
650                    module=self.module) as w:
651                self.module.resetwarnings()
652                self.module.filterwarnings("once", category=UserWarning)
653                self.module.warn_explicit(message, UserWarning, "file", 42)
654                self.assertEqual(w[-1].message, message)
655                del w[:]
656                self.module.warn_explicit(message, UserWarning, "file", 42)
657                self.assertEqual(len(w), 0)
658                # Test the resetting of onceregistry.
659                self.module.onceregistry = {}
660                __warningregistry__ = {}
661                self.module.warn('onceregistry test')
662                self.assertEqual(w[-1].message.args, message.args)
663                # Removal of onceregistry is okay.
664                del w[:]
665                del self.module.onceregistry
666                __warningregistry__ = {}
667                self.module.warn_explicit(message, UserWarning, "file", 42)
668                self.assertEqual(len(w), 0)
669        finally:
670            self.module.onceregistry = original_registry
671
672    def test_default_action(self):
673        # Replacing or removing defaultaction should be okay.
674        message = UserWarning("defaultaction test")
675        original = self.module.defaultaction
676        try:
677            with original_warnings.catch_warnings(record=True,
678                    module=self.module) as w:
679                self.module.resetwarnings()
680                registry = {}
681                self.module.warn_explicit(message, UserWarning, "<test>", 42,
682                                            registry=registry)
683                self.assertEqual(w[-1].message, message)
684                self.assertEqual(len(w), 1)
685                # One actual registry key plus the "version" key
686                self.assertEqual(len(registry), 2)
687                self.assertIn("version", registry)
688                del w[:]
689                # Test removal.
690                del self.module.defaultaction
691                __warningregistry__ = {}
692                registry = {}
693                self.module.warn_explicit(message, UserWarning, "<test>", 43,
694                                            registry=registry)
695                self.assertEqual(w[-1].message, message)
696                self.assertEqual(len(w), 1)
697                self.assertEqual(len(registry), 2)
698                del w[:]
699                # Test setting.
700                self.module.defaultaction = "ignore"
701                __warningregistry__ = {}
702                registry = {}
703                self.module.warn_explicit(message, UserWarning, "<test>", 44,
704                                            registry=registry)
705                self.assertEqual(len(w), 0)
706        finally:
707            self.module.defaultaction = original
708
709    def test_showwarning_missing(self):
710        # Test that showwarning() missing is okay.
711        text = 'del showwarning test'
712        with original_warnings.catch_warnings(module=self.module):
713            self.module.filterwarnings("always", category=UserWarning)
714            del self.module.showwarning
715            with support.captured_output('stderr') as stream:
716                self.module.warn(text)
717                result = stream.getvalue()
718        self.assertIn(text, result)
719
720    def test_showwarnmsg_missing(self):
721        # Test that _showwarnmsg() missing is okay.
722        text = 'del _showwarnmsg test'
723        with original_warnings.catch_warnings(module=self.module):
724            self.module.filterwarnings("always", category=UserWarning)
725
726            show = self.module._showwarnmsg
727            try:
728                del self.module._showwarnmsg
729                with support.captured_output('stderr') as stream:
730                    self.module.warn(text)
731                    result = stream.getvalue()
732            finally:
733                self.module._showwarnmsg = show
734        self.assertIn(text, result)
735
736    def test_showwarning_not_callable(self):
737        with original_warnings.catch_warnings(module=self.module):
738            self.module.filterwarnings("always", category=UserWarning)
739            self.module.showwarning = print
740            with support.captured_output('stdout'):
741                self.module.warn('Warning!')
742            self.module.showwarning = 23
743            self.assertRaises(TypeError, self.module.warn, "Warning!")
744
745    def test_show_warning_output(self):
746        # With showwarning() missing, make sure that output is okay.
747        text = 'test show_warning'
748        with original_warnings.catch_warnings(module=self.module):
749            self.module.filterwarnings("always", category=UserWarning)
750            del self.module.showwarning
751            with support.captured_output('stderr') as stream:
752                warning_tests.inner(text)
753                result = stream.getvalue()
754        self.assertEqual(result.count('\n'), 2,
755                             "Too many newlines in %r" % result)
756        first_line, second_line = result.split('\n', 1)
757        expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
758        first_line_parts = first_line.rsplit(':', 3)
759        path, line, warning_class, message = first_line_parts
760        line = int(line)
761        self.assertEqual(expected_file, path)
762        self.assertEqual(warning_class, ' ' + UserWarning.__name__)
763        self.assertEqual(message, ' ' + text)
764        expected_line = '  ' + linecache.getline(path, line).strip() + '\n'
765        assert expected_line
766        self.assertEqual(second_line, expected_line)
767
768    def test_filename_none(self):
769        # issue #12467: race condition if a warning is emitted at shutdown
770        globals_dict = globals()
771        oldfile = globals_dict['__file__']
772        try:
773            catch = original_warnings.catch_warnings(record=True,
774                                                     module=self.module)
775            with catch as w:
776                self.module.filterwarnings("always", category=UserWarning)
777                globals_dict['__file__'] = None
778                original_warnings.warn('test', UserWarning)
779                self.assertTrue(len(w))
780        finally:
781            globals_dict['__file__'] = oldfile
782
783    def test_stderr_none(self):
784        rc, stdout, stderr = assert_python_ok("-c",
785            "import sys; sys.stderr = None; "
786            "import warnings; warnings.simplefilter('always'); "
787            "warnings.warn('Warning!')")
788        self.assertEqual(stdout, b'')
789        self.assertNotIn(b'Warning!', stderr)
790        self.assertNotIn(b'Error', stderr)
791
792    def test_issue31285(self):
793        # warn_explicit() should neither raise a SystemError nor cause an
794        # assertion failure, in case the return value of get_source() has a
795        # bad splitlines() method.
796        def get_bad_loader(splitlines_ret_val):
797            class BadLoader:
798                def get_source(self, fullname):
799                    class BadSource(str):
800                        def splitlines(self):
801                            return splitlines_ret_val
802                    return BadSource('spam')
803            return BadLoader()
804
805        wmod = self.module
806        with original_warnings.catch_warnings(module=wmod):
807            wmod.filterwarnings('default', category=UserWarning)
808
809            with support.captured_stderr() as stderr:
810                wmod.warn_explicit(
811                    'foo', UserWarning, 'bar', 1,
812                    module_globals={'__loader__': get_bad_loader(42),
813                                    '__name__': 'foobar'})
814            self.assertIn('UserWarning: foo', stderr.getvalue())
815
816            show = wmod._showwarnmsg
817            try:
818                del wmod._showwarnmsg
819                with support.captured_stderr() as stderr:
820                    wmod.warn_explicit(
821                        'eggs', UserWarning, 'bar', 1,
822                        module_globals={'__loader__': get_bad_loader([42]),
823                                        '__name__': 'foobar'})
824                self.assertIn('UserWarning: eggs', stderr.getvalue())
825            finally:
826                wmod._showwarnmsg = show
827
828    @support.cpython_only
829    def test_issue31411(self):
830        # warn_explicit() shouldn't raise a SystemError in case
831        # warnings.onceregistry isn't a dictionary.
832        wmod = self.module
833        with original_warnings.catch_warnings(module=wmod):
834            wmod.filterwarnings('once')
835            with support.swap_attr(wmod, 'onceregistry', None):
836                with self.assertRaises(TypeError):
837                    wmod.warn_explicit('foo', Warning, 'bar', 1, registry=None)
838
839    @support.cpython_only
840    def test_issue31416(self):
841        # warn_explicit() shouldn't cause an assertion failure in case of a
842        # bad warnings.filters or warnings.defaultaction.
843        wmod = self.module
844        with original_warnings.catch_warnings(module=wmod):
845            wmod.filters = [(None, None, Warning, None, 0)]
846            with self.assertRaises(TypeError):
847                wmod.warn_explicit('foo', Warning, 'bar', 1)
848
849            wmod.filters = []
850            with support.swap_attr(wmod, 'defaultaction', None), \
851                 self.assertRaises(TypeError):
852                wmod.warn_explicit('foo', Warning, 'bar', 1)
853
854    @support.cpython_only
855    def test_issue31566(self):
856        # warn() shouldn't cause an assertion failure in case of a bad
857        # __name__ global.
858        with original_warnings.catch_warnings(module=self.module):
859            self.module.filterwarnings('error', category=UserWarning)
860            with support.swap_item(globals(), '__name__', b'foo'), \
861                 support.swap_item(globals(), '__file__', None):
862                self.assertRaises(UserWarning, self.module.warn, 'bar')
863
864
865class WarningsDisplayTests(BaseTest):
866
867    """Test the displaying of warnings and the ability to overload functions
868    related to displaying warnings."""
869
870    def test_formatwarning(self):
871        message = "msg"
872        category = Warning
873        file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
874        line_num = 3
875        file_line = linecache.getline(file_name, line_num).strip()
876        format = "%s:%s: %s: %s\n  %s\n"
877        expect = format % (file_name, line_num, category.__name__, message,
878                            file_line)
879        self.assertEqual(expect, self.module.formatwarning(message,
880                                                category, file_name, line_num))
881        # Test the 'line' argument.
882        file_line += " for the win!"
883        expect = format % (file_name, line_num, category.__name__, message,
884                            file_line)
885        self.assertEqual(expect, self.module.formatwarning(message,
886                                    category, file_name, line_num, file_line))
887
888    def test_showwarning(self):
889        file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
890        line_num = 3
891        expected_file_line = linecache.getline(file_name, line_num).strip()
892        message = 'msg'
893        category = Warning
894        file_object = StringIO()
895        expect = self.module.formatwarning(message, category, file_name,
896                                            line_num)
897        self.module.showwarning(message, category, file_name, line_num,
898                                file_object)
899        self.assertEqual(file_object.getvalue(), expect)
900        # Test 'line' argument.
901        expected_file_line += "for the win!"
902        expect = self.module.formatwarning(message, category, file_name,
903                                            line_num, expected_file_line)
904        file_object = StringIO()
905        self.module.showwarning(message, category, file_name, line_num,
906                                file_object, expected_file_line)
907        self.assertEqual(expect, file_object.getvalue())
908
909    def test_formatwarning_override(self):
910        # bpo-35178: Test that a custom formatwarning function gets the 'line'
911        # argument as a positional argument, and not only as a keyword argument
912        def myformatwarning(message, category, filename, lineno, text):
913            return f'm={message}:c={category}:f={filename}:l={lineno}:t={text}'
914
915        file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
916        line_num = 3
917        file_line = linecache.getline(file_name, line_num).strip()
918        message = 'msg'
919        category = Warning
920        file_object = StringIO()
921        expected = f'm={message}:c={category}:f={file_name}:l={line_num}' + \
922                   f':t={file_line}'
923        with support.swap_attr(self.module, 'formatwarning', myformatwarning):
924            self.module.showwarning(message, category, file_name, line_num,
925                                    file_object, file_line)
926            self.assertEqual(file_object.getvalue(), expected)
927
928
929class CWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
930    module = c_warnings
931
932class PyWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
933    module = py_warnings
934
935    def test_tracemalloc(self):
936        self.addCleanup(os_helper.unlink, os_helper.TESTFN)
937
938        with open(os_helper.TESTFN, 'w', encoding="utf-8") as fp:
939            fp.write(textwrap.dedent("""
940                def func():
941                    f = open(__file__, "rb")
942                    # Emit ResourceWarning
943                    f = None
944
945                func()
946            """))
947
948        def run(*args):
949            res = assert_python_ok(*args, PYTHONIOENCODING='utf-8')
950            stderr = res.err.decode('utf-8', 'replace')
951            stderr = '\n'.join(stderr.splitlines())
952
953            # normalize newlines
954            stderr = re.sub('<.*>', '<...>', stderr)
955            return stderr
956
957        # tracemalloc disabled
958        filename = os.path.abspath(os_helper.TESTFN)
959        stderr = run('-Wd', os_helper.TESTFN)
960        expected = textwrap.dedent(f'''
961            {filename}:5: ResourceWarning: unclosed file <...>
962              f = None
963            ResourceWarning: Enable tracemalloc to get the object allocation traceback
964        ''').strip()
965        self.assertEqual(stderr, expected)
966
967        # tracemalloc enabled
968        stderr = run('-Wd', '-X', 'tracemalloc=2', os_helper.TESTFN)
969        expected = textwrap.dedent(f'''
970            {filename}:5: ResourceWarning: unclosed file <...>
971              f = None
972            Object allocated at (most recent call last):
973              File "{filename}", lineno 7
974                func()
975              File "{filename}", lineno 3
976                f = open(__file__, "rb")
977        ''').strip()
978        self.assertEqual(stderr, expected)
979
980
981class CatchWarningTests(BaseTest):
982
983    """Test catch_warnings()."""
984
985    def test_catch_warnings_restore(self):
986        wmod = self.module
987        orig_filters = wmod.filters
988        orig_showwarning = wmod.showwarning
989        # Ensure both showwarning and filters are restored when recording
990        with wmod.catch_warnings(module=wmod, record=True):
991            wmod.filters = wmod.showwarning = object()
992        self.assertIs(wmod.filters, orig_filters)
993        self.assertIs(wmod.showwarning, orig_showwarning)
994        # Same test, but with recording disabled
995        with wmod.catch_warnings(module=wmod, record=False):
996            wmod.filters = wmod.showwarning = object()
997        self.assertIs(wmod.filters, orig_filters)
998        self.assertIs(wmod.showwarning, orig_showwarning)
999
1000    def test_catch_warnings_recording(self):
1001        wmod = self.module
1002        # Ensure warnings are recorded when requested
1003        with wmod.catch_warnings(module=wmod, record=True) as w:
1004            self.assertEqual(w, [])
1005            self.assertIs(type(w), list)
1006            wmod.simplefilter("always")
1007            wmod.warn("foo")
1008            self.assertEqual(str(w[-1].message), "foo")
1009            wmod.warn("bar")
1010            self.assertEqual(str(w[-1].message), "bar")
1011            self.assertEqual(str(w[0].message), "foo")
1012            self.assertEqual(str(w[1].message), "bar")
1013            del w[:]
1014            self.assertEqual(w, [])
1015        # Ensure warnings are not recorded when not requested
1016        orig_showwarning = wmod.showwarning
1017        with wmod.catch_warnings(module=wmod, record=False) as w:
1018            self.assertIsNone(w)
1019            self.assertIs(wmod.showwarning, orig_showwarning)
1020
1021    def test_catch_warnings_reentry_guard(self):
1022        wmod = self.module
1023        # Ensure catch_warnings is protected against incorrect usage
1024        x = wmod.catch_warnings(module=wmod, record=True)
1025        self.assertRaises(RuntimeError, x.__exit__)
1026        with x:
1027            self.assertRaises(RuntimeError, x.__enter__)
1028        # Same test, but with recording disabled
1029        x = wmod.catch_warnings(module=wmod, record=False)
1030        self.assertRaises(RuntimeError, x.__exit__)
1031        with x:
1032            self.assertRaises(RuntimeError, x.__enter__)
1033
1034    def test_catch_warnings_defaults(self):
1035        wmod = self.module
1036        orig_filters = wmod.filters
1037        orig_showwarning = wmod.showwarning
1038        # Ensure default behaviour is not to record warnings
1039        with wmod.catch_warnings(module=wmod) as w:
1040            self.assertIsNone(w)
1041            self.assertIs(wmod.showwarning, orig_showwarning)
1042            self.assertIsNot(wmod.filters, orig_filters)
1043        self.assertIs(wmod.filters, orig_filters)
1044        if wmod is sys.modules['warnings']:
1045            # Ensure the default module is this one
1046            with wmod.catch_warnings() as w:
1047                self.assertIsNone(w)
1048                self.assertIs(wmod.showwarning, orig_showwarning)
1049                self.assertIsNot(wmod.filters, orig_filters)
1050            self.assertIs(wmod.filters, orig_filters)
1051
1052    def test_record_override_showwarning_before(self):
1053        # Issue #28835: If warnings.showwarning() was overridden, make sure
1054        # that catch_warnings(record=True) overrides it again.
1055        text = "This is a warning"
1056        wmod = self.module
1057        my_log = []
1058
1059        def my_logger(message, category, filename, lineno, file=None, line=None):
1060            nonlocal my_log
1061            my_log.append(message)
1062
1063        # Override warnings.showwarning() before calling catch_warnings()
1064        with support.swap_attr(wmod, 'showwarning', my_logger):
1065            with wmod.catch_warnings(module=wmod, record=True) as log:
1066                self.assertIsNot(wmod.showwarning, my_logger)
1067
1068                wmod.simplefilter("always")
1069                wmod.warn(text)
1070
1071            self.assertIs(wmod.showwarning, my_logger)
1072
1073        self.assertEqual(len(log), 1, log)
1074        self.assertEqual(log[0].message.args[0], text)
1075        self.assertEqual(my_log, [])
1076
1077    def test_record_override_showwarning_inside(self):
1078        # Issue #28835: It is possible to override warnings.showwarning()
1079        # in the catch_warnings(record=True) context manager.
1080        text = "This is a warning"
1081        wmod = self.module
1082        my_log = []
1083
1084        def my_logger(message, category, filename, lineno, file=None, line=None):
1085            nonlocal my_log
1086            my_log.append(message)
1087
1088        with wmod.catch_warnings(module=wmod, record=True) as log:
1089            wmod.simplefilter("always")
1090            wmod.showwarning = my_logger
1091            wmod.warn(text)
1092
1093        self.assertEqual(len(my_log), 1, my_log)
1094        self.assertEqual(my_log[0].args[0], text)
1095        self.assertEqual(log, [])
1096
1097    def test_check_warnings(self):
1098        # Explicit tests for the test.support convenience wrapper
1099        wmod = self.module
1100        if wmod is not sys.modules['warnings']:
1101            self.skipTest('module to test is not loaded warnings module')
1102        with warnings_helper.check_warnings(quiet=False) as w:
1103            self.assertEqual(w.warnings, [])
1104            wmod.simplefilter("always")
1105            wmod.warn("foo")
1106            self.assertEqual(str(w.message), "foo")
1107            wmod.warn("bar")
1108            self.assertEqual(str(w.message), "bar")
1109            self.assertEqual(str(w.warnings[0].message), "foo")
1110            self.assertEqual(str(w.warnings[1].message), "bar")
1111            w.reset()
1112            self.assertEqual(w.warnings, [])
1113
1114        with warnings_helper.check_warnings():
1115            # defaults to quiet=True without argument
1116            pass
1117        with warnings_helper.check_warnings(('foo', UserWarning)):
1118            wmod.warn("foo")
1119
1120        with self.assertRaises(AssertionError):
1121            with warnings_helper.check_warnings(('', RuntimeWarning)):
1122                # defaults to quiet=False with argument
1123                pass
1124        with self.assertRaises(AssertionError):
1125            with warnings_helper.check_warnings(('foo', RuntimeWarning)):
1126                wmod.warn("foo")
1127
1128class CCatchWarningTests(CatchWarningTests, unittest.TestCase):
1129    module = c_warnings
1130
1131class PyCatchWarningTests(CatchWarningTests, unittest.TestCase):
1132    module = py_warnings
1133
1134
1135class EnvironmentVariableTests(BaseTest):
1136
1137    def test_single_warning(self):
1138        rc, stdout, stderr = assert_python_ok("-c",
1139            "import sys; sys.stdout.write(str(sys.warnoptions))",
1140            PYTHONWARNINGS="ignore::DeprecationWarning",
1141            PYTHONDEVMODE="")
1142        self.assertEqual(stdout, b"['ignore::DeprecationWarning']")
1143
1144    def test_comma_separated_warnings(self):
1145        rc, stdout, stderr = assert_python_ok("-c",
1146            "import sys; sys.stdout.write(str(sys.warnoptions))",
1147            PYTHONWARNINGS="ignore::DeprecationWarning,ignore::UnicodeWarning",
1148            PYTHONDEVMODE="")
1149        self.assertEqual(stdout,
1150            b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
1151
1152    def test_envvar_and_command_line(self):
1153        rc, stdout, stderr = assert_python_ok("-Wignore::UnicodeWarning", "-c",
1154            "import sys; sys.stdout.write(str(sys.warnoptions))",
1155            PYTHONWARNINGS="ignore::DeprecationWarning",
1156            PYTHONDEVMODE="")
1157        self.assertEqual(stdout,
1158            b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
1159
1160    def test_conflicting_envvar_and_command_line(self):
1161        rc, stdout, stderr = assert_python_failure("-Werror::DeprecationWarning", "-c",
1162            "import sys, warnings; sys.stdout.write(str(sys.warnoptions)); "
1163            "warnings.warn('Message', DeprecationWarning)",
1164            PYTHONWARNINGS="default::DeprecationWarning",
1165            PYTHONDEVMODE="")
1166        self.assertEqual(stdout,
1167            b"['default::DeprecationWarning', 'error::DeprecationWarning']")
1168        self.assertEqual(stderr.splitlines(),
1169            [b"Traceback (most recent call last):",
1170             b"  File \"<string>\", line 1, in <module>",
1171             b"DeprecationWarning: Message"])
1172
1173    def test_default_filter_configuration(self):
1174        pure_python_api = self.module is py_warnings
1175        if Py_DEBUG:
1176            expected_default_filters = []
1177        else:
1178            if pure_python_api:
1179                main_module_filter = re.compile("__main__")
1180            else:
1181                main_module_filter = "__main__"
1182            expected_default_filters = [
1183                ('default', None, DeprecationWarning, main_module_filter, 0),
1184                ('ignore', None, DeprecationWarning, None, 0),
1185                ('ignore', None, PendingDeprecationWarning, None, 0),
1186                ('ignore', None, ImportWarning, None, 0),
1187                ('ignore', None, ResourceWarning, None, 0),
1188            ]
1189        expected_output = [str(f).encode() for f in expected_default_filters]
1190
1191        if pure_python_api:
1192            # Disable the warnings acceleration module in the subprocess
1193            code = "import sys; sys.modules.pop('warnings', None); sys.modules['_warnings'] = None; "
1194        else:
1195            code = ""
1196        code += "import warnings; [print(f) for f in warnings.filters]"
1197
1198        rc, stdout, stderr = assert_python_ok("-c", code, __isolated=True)
1199        stdout_lines = [line.strip() for line in stdout.splitlines()]
1200        self.maxDiff = None
1201        self.assertEqual(stdout_lines, expected_output)
1202
1203
1204    @unittest.skipUnless(sys.getfilesystemencoding() != 'ascii',
1205                         'requires non-ascii filesystemencoding')
1206    def test_nonascii(self):
1207        PYTHONWARNINGS="ignore:DeprecationWarning" + os_helper.FS_NONASCII
1208        rc, stdout, stderr = assert_python_ok("-c",
1209            "import sys; sys.stdout.write(str(sys.warnoptions))",
1210            PYTHONIOENCODING="utf-8",
1211            PYTHONWARNINGS=PYTHONWARNINGS,
1212            PYTHONDEVMODE="")
1213        self.assertEqual(stdout, str([PYTHONWARNINGS]).encode())
1214
1215class CEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
1216    module = c_warnings
1217
1218class PyEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
1219    module = py_warnings
1220
1221
1222class BootstrapTest(unittest.TestCase):
1223    def test_issue_8766(self):
1224        # "import encodings" emits a warning whereas the warnings is not loaded
1225        # or not completely loaded (warnings imports indirectly encodings by
1226        # importing linecache) yet
1227        with os_helper.temp_cwd() as cwd, os_helper.temp_cwd('encodings'):
1228            # encodings loaded by initfsencoding()
1229            assert_python_ok('-c', 'pass', PYTHONPATH=cwd)
1230
1231            # Use -W to load warnings module at startup
1232            assert_python_ok('-c', 'pass', '-W', 'always', PYTHONPATH=cwd)
1233
1234
1235class FinalizationTest(unittest.TestCase):
1236    def test_finalization(self):
1237        # Issue #19421: warnings.warn() should not crash
1238        # during Python finalization
1239        code = """
1240import warnings
1241warn = warnings.warn
1242
1243class A:
1244    def __del__(self):
1245        warn("test")
1246
1247a=A()
1248        """
1249        rc, out, err = assert_python_ok("-c", code)
1250        self.assertEqual(err.decode().rstrip(),
1251                         '<string>:7: UserWarning: test')
1252
1253    def test_late_resource_warning(self):
1254        # Issue #21925: Emitting a ResourceWarning late during the Python
1255        # shutdown must be logged.
1256
1257        expected = b"sys:1: ResourceWarning: unclosed file "
1258
1259        # don't import the warnings module
1260        # (_warnings will try to import it)
1261        code = "f = open(%a)" % __file__
1262        rc, out, err = assert_python_ok("-Wd", "-c", code)
1263        self.assertTrue(err.startswith(expected), ascii(err))
1264
1265        # import the warnings module
1266        code = "import warnings; f = open(%a)" % __file__
1267        rc, out, err = assert_python_ok("-Wd", "-c", code)
1268        self.assertTrue(err.startswith(expected), ascii(err))
1269
1270
1271def setUpModule():
1272    py_warnings.onceregistry.clear()
1273    c_warnings.onceregistry.clear()
1274
1275tearDownModule = setUpModule
1276
1277if __name__ == "__main__":
1278    unittest.main()
1279