source: titan/mediathek/localhoster/lib/python2.7/test/test_warnings.py @ 40661

Last change on this file since 40661 was 40661, checked in by obi, 7 years ago

reset

File size: 35.3 KB
Line 
1from contextlib import contextmanager
2import linecache
3import os
4import StringIO
5import sys
6import unittest
7import subprocess
8from test import test_support
9from test.script_helper import assert_python_ok
10
11import warning_tests
12
13import warnings as original_warnings
14
15py_warnings = test_support.import_fresh_module('warnings', blocked=['_warnings'])
16c_warnings = test_support.import_fresh_module('warnings', fresh=['_warnings'])
17
18@contextmanager
19def warnings_state(module):
20    """Use a specific warnings implementation in warning_tests."""
21    global __warningregistry__
22    for to_clear in (sys, warning_tests):
23        try:
24            to_clear.__warningregistry__.clear()
25        except AttributeError:
26            pass
27    try:
28        __warningregistry__.clear()
29    except NameError:
30        pass
31    original_warnings = warning_tests.warnings
32    original_filters = module.filters
33    try:
34        module.filters = original_filters[:]
35        module.simplefilter("once")
36        warning_tests.warnings = module
37        yield
38    finally:
39        warning_tests.warnings = original_warnings
40        module.filters = original_filters
41
42
43class BaseTest(unittest.TestCase):
44
45    """Basic bookkeeping required for testing."""
46
47    def setUp(self):
48        # The __warningregistry__ needs to be in a pristine state for tests
49        # to work properly.
50        if '__warningregistry__' in globals():
51            del globals()['__warningregistry__']
52        if hasattr(warning_tests, '__warningregistry__'):
53            del warning_tests.__warningregistry__
54        if hasattr(sys, '__warningregistry__'):
55            del sys.__warningregistry__
56        # The 'warnings' module must be explicitly set so that the proper
57        # interaction between _warnings and 'warnings' can be controlled.
58        sys.modules['warnings'] = self.module
59        super(BaseTest, self).setUp()
60
61    def tearDown(self):
62        sys.modules['warnings'] = original_warnings
63        super(BaseTest, self).tearDown()
64
65class PublicAPITests(BaseTest):
66
67    """Ensures that the correct values are exposed in the
68    public API.
69    """
70
71    def test_module_all_attribute(self):
72        self.assertTrue(hasattr(self.module, '__all__'))
73        target_api = ["warn", "warn_explicit", "showwarning",
74                      "formatwarning", "filterwarnings", "simplefilter",
75                      "resetwarnings", "catch_warnings"]
76        self.assertSetEqual(set(self.module.__all__),
77                            set(target_api))
78
79class CPublicAPITests(PublicAPITests, unittest.TestCase):
80    module = c_warnings
81
82class PyPublicAPITests(PublicAPITests, unittest.TestCase):
83    module = py_warnings
84
85class FilterTests(object):
86
87    """Testing the filtering functionality."""
88
89    def test_error(self):
90        with original_warnings.catch_warnings(module=self.module) as w:
91            self.module.resetwarnings()
92            self.module.filterwarnings("error", category=UserWarning)
93            self.assertRaises(UserWarning, self.module.warn,
94                                "FilterTests.test_error")
95
96    def test_ignore(self):
97        with original_warnings.catch_warnings(record=True,
98                module=self.module) as w:
99            self.module.resetwarnings()
100            self.module.filterwarnings("ignore", category=UserWarning)
101            self.module.warn("FilterTests.test_ignore", UserWarning)
102            self.assertEqual(len(w), 0)
103
104    def test_always(self):
105        with original_warnings.catch_warnings(record=True,
106                module=self.module) as w:
107            self.module.resetwarnings()
108            self.module.filterwarnings("always", category=UserWarning)
109            message = "FilterTests.test_always"
110            self.module.warn(message, UserWarning)
111            self.assertTrue(message, w[-1].message)
112            self.module.warn(message, UserWarning)
113            self.assertTrue(w[-1].message, message)
114
115    def test_default(self):
116        with original_warnings.catch_warnings(record=True,
117                module=self.module) as w:
118            self.module.resetwarnings()
119            self.module.filterwarnings("default", category=UserWarning)
120            message = UserWarning("FilterTests.test_default")
121            for x in xrange(2):
122                self.module.warn(message, UserWarning)
123                if x == 0:
124                    self.assertEqual(w[-1].message, message)
125                    del w[:]
126                elif x == 1:
127                    self.assertEqual(len(w), 0)
128                else:
129                    raise ValueError("loop variant unhandled")
130
131    def test_module(self):
132        with original_warnings.catch_warnings(record=True,
133                module=self.module) as w:
134            self.module.resetwarnings()
135            self.module.filterwarnings("module", category=UserWarning)
136            message = UserWarning("FilterTests.test_module")
137            self.module.warn(message, UserWarning)
138            self.assertEqual(w[-1].message, message)
139            del w[:]
140            self.module.warn(message, UserWarning)
141            self.assertEqual(len(w), 0)
142
143    def test_once(self):
144        with original_warnings.catch_warnings(record=True,
145                module=self.module) as w:
146            self.module.resetwarnings()
147            self.module.filterwarnings("once", category=UserWarning)
148            message = UserWarning("FilterTests.test_once")
149            self.module.warn_explicit(message, UserWarning, "test_warnings.py",
150                                    42)
151            self.assertEqual(w[-1].message, message)
152            del w[:]
153            self.module.warn_explicit(message, UserWarning, "test_warnings.py",
154                                    13)
155            self.assertEqual(len(w), 0)
156            self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
157                                    42)
158            self.assertEqual(len(w), 0)
159
160    def test_inheritance(self):
161        with original_warnings.catch_warnings(module=self.module) as w:
162            self.module.resetwarnings()
163            self.module.filterwarnings("error", category=Warning)
164            self.assertRaises(UserWarning, self.module.warn,
165                                "FilterTests.test_inheritance", UserWarning)
166
167    def test_ordering(self):
168        with original_warnings.catch_warnings(record=True,
169                module=self.module) as w:
170            self.module.resetwarnings()
171            self.module.filterwarnings("ignore", category=UserWarning)
172            self.module.filterwarnings("error", category=UserWarning,
173                                        append=True)
174            del w[:]
175            try:
176                self.module.warn("FilterTests.test_ordering", UserWarning)
177            except UserWarning:
178                self.fail("order handling for actions failed")
179            self.assertEqual(len(w), 0)
180
181    def test_filterwarnings(self):
182        # Test filterwarnings().
183        # Implicitly also tests resetwarnings().
184        with original_warnings.catch_warnings(record=True,
185                module=self.module) as w:
186            self.module.filterwarnings("error", "", Warning, "", 0)
187            self.assertRaises(UserWarning, self.module.warn, 'convert to error')
188
189            self.module.resetwarnings()
190            text = 'handle normally'
191            self.module.warn(text)
192            self.assertEqual(str(w[-1].message), text)
193            self.assertTrue(w[-1].category is UserWarning)
194
195            self.module.filterwarnings("ignore", "", Warning, "", 0)
196            text = 'filtered out'
197            self.module.warn(text)
198            self.assertNotEqual(str(w[-1].message), text)
199
200            self.module.resetwarnings()
201            self.module.filterwarnings("error", "hex*", Warning, "", 0)
202            self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
203            text = 'nonmatching text'
204            self.module.warn(text)
205            self.assertEqual(str(w[-1].message), text)
206            self.assertTrue(w[-1].category is UserWarning)
207
208class CFilterTests(BaseTest, FilterTests):
209    module = c_warnings
210
211class PyFilterTests(BaseTest, FilterTests):
212    module = py_warnings
213
214
215class WarnTests(unittest.TestCase):
216
217    """Test warnings.warn() and warnings.warn_explicit()."""
218
219    def test_message(self):
220        with original_warnings.catch_warnings(record=True,
221                module=self.module) as w:
222            self.module.simplefilter("once")
223            for i in range(4):
224                text = 'multi %d' %i  # Different text on each call.
225                self.module.warn(text)
226                self.assertEqual(str(w[-1].message), text)
227                self.assertTrue(w[-1].category is UserWarning)
228
229    def test_filename(self):
230        with warnings_state(self.module):
231            with original_warnings.catch_warnings(record=True,
232                    module=self.module) as w:
233                warning_tests.inner("spam1")
234                self.assertEqual(os.path.basename(w[-1].filename),
235                                    "warning_tests.py")
236                warning_tests.outer("spam2")
237                self.assertEqual(os.path.basename(w[-1].filename),
238                                    "warning_tests.py")
239
240    def test_stacklevel(self):
241        # Test stacklevel argument
242        # make sure all messages are different, so the warning won't be skipped
243        with warnings_state(self.module):
244            with original_warnings.catch_warnings(record=True,
245                    module=self.module) as w:
246                warning_tests.inner("spam3", stacklevel=1)
247                self.assertEqual(os.path.basename(w[-1].filename),
248                                    "warning_tests.py")
249                warning_tests.outer("spam4", stacklevel=1)
250                self.assertEqual(os.path.basename(w[-1].filename),
251                                    "warning_tests.py")
252
253                warning_tests.inner("spam5", stacklevel=2)
254                self.assertEqual(os.path.basename(w[-1].filename),
255                                    "test_warnings.py")
256                warning_tests.outer("spam6", stacklevel=2)
257                self.assertEqual(os.path.basename(w[-1].filename),
258                                    "warning_tests.py")
259                warning_tests.outer("spam6.5", stacklevel=3)
260                self.assertEqual(os.path.basename(w[-1].filename),
261                                    "test_warnings.py")
262
263                warning_tests.inner("spam7", stacklevel=9999)
264                self.assertEqual(os.path.basename(w[-1].filename),
265                                    "sys")
266
267    def test_missing_filename_not_main(self):
268        # If __file__ is not specified and __main__ is not the module name,
269        # then __file__ should be set to the module name.
270        filename = warning_tests.__file__
271        try:
272            del warning_tests.__file__
273            with warnings_state(self.module):
274                with original_warnings.catch_warnings(record=True,
275                        module=self.module) as w:
276                    warning_tests.inner("spam8", stacklevel=1)
277                    self.assertEqual(w[-1].filename, warning_tests.__name__)
278        finally:
279            warning_tests.__file__ = filename
280
281    @unittest.skipUnless(hasattr(sys, 'argv'), 'test needs sys.argv')
282    def test_missing_filename_main_with_argv(self):
283        # If __file__ is not specified and the caller is __main__ and sys.argv
284        # exists, then use sys.argv[0] as the file.
285        filename = warning_tests.__file__
286        module_name = warning_tests.__name__
287        try:
288            del warning_tests.__file__
289            warning_tests.__name__ = '__main__'
290            with warnings_state(self.module):
291                with original_warnings.catch_warnings(record=True,
292                        module=self.module) as w:
293                    warning_tests.inner('spam9', stacklevel=1)
294                    self.assertEqual(w[-1].filename, sys.argv[0])
295        finally:
296            warning_tests.__file__ = filename
297            warning_tests.__name__ = module_name
298
299    def test_missing_filename_main_without_argv(self):
300        # If __file__ is not specified, the caller is __main__, and sys.argv
301        # is not set, then '__main__' is the file name.
302        filename = warning_tests.__file__
303        module_name = warning_tests.__name__
304        argv = sys.argv
305        try:
306            del warning_tests.__file__
307            warning_tests.__name__ = '__main__'
308            del sys.argv
309            with warnings_state(self.module):
310                with original_warnings.catch_warnings(record=True,
311                        module=self.module) as w:
312                    warning_tests.inner('spam10', stacklevel=1)
313                    self.assertEqual(w[-1].filename, '__main__')
314        finally:
315            warning_tests.__file__ = filename
316            warning_tests.__name__ = module_name
317            sys.argv = argv
318
319    def test_missing_filename_main_with_argv_empty_string(self):
320        # If __file__ is not specified, the caller is __main__, and sys.argv[0]
321        # is the empty string, then '__main__ is the file name.
322        # Tests issue 2743.
323        file_name = warning_tests.__file__
324        module_name = warning_tests.__name__
325        argv = sys.argv
326        try:
327            del warning_tests.__file__
328            warning_tests.__name__ = '__main__'
329            sys.argv = ['']
330            with warnings_state(self.module):
331                with original_warnings.catch_warnings(record=True,
332                        module=self.module) as w:
333                    warning_tests.inner('spam11', stacklevel=1)
334                    self.assertEqual(w[-1].filename, '__main__')
335        finally:
336            warning_tests.__file__ = file_name
337            warning_tests.__name__ = module_name
338            sys.argv = argv
339
340    def test_warn_explicit_type_errors(self):
341        # warn_explicit() should error out gracefully if it is given objects
342        # of the wrong types.
343        # lineno is expected to be an integer.
344        self.assertRaises(TypeError, self.module.warn_explicit,
345                            None, UserWarning, None, None)
346        # Either 'message' needs to be an instance of Warning or 'category'
347        # needs to be a subclass.
348        self.assertRaises(TypeError, self.module.warn_explicit,
349                            None, None, None, 1)
350        # 'registry' must be a dict or None.
351        self.assertRaises((TypeError, AttributeError),
352                            self.module.warn_explicit,
353                            None, Warning, None, 1, registry=42)
354
355    def test_bad_str(self):
356        # issue 6415
357        # Warnings instance with a bad format string for __str__ should not
358        # trigger a bus error.
359        class BadStrWarning(Warning):
360            """Warning with a bad format string for __str__."""
361            def __str__(self):
362                return ("A bad formatted string %(err)" %
363                        {"err" : "there is no %(err)s"})
364
365        with self.assertRaises(ValueError):
366            self.module.warn(BadStrWarning())
367
368
369class CWarnTests(BaseTest, WarnTests):
370    module = c_warnings
371
372    # As an early adopter, we sanity check the
373    # test_support.import_fresh_module utility function
374    def test_accelerated(self):
375        self.assertFalse(original_warnings is self.module)
376        self.assertFalse(hasattr(self.module.warn, 'func_code'))
377
378class PyWarnTests(BaseTest, WarnTests):
379    module = py_warnings
380
381    # As an early adopter, we sanity check the
382    # test_support.import_fresh_module utility function
383    def test_pure_python(self):
384        self.assertFalse(original_warnings is self.module)
385        self.assertTrue(hasattr(self.module.warn, 'func_code'))
386
387
388class WCmdLineTests(unittest.TestCase):
389
390    def test_improper_input(self):
391        # Uses the private _setoption() function to test the parsing
392        # of command-line warning arguments
393        with original_warnings.catch_warnings(module=self.module):
394            self.assertRaises(self.module._OptionError,
395                              self.module._setoption, '1:2:3:4:5:6')
396            self.assertRaises(self.module._OptionError,
397                              self.module._setoption, 'bogus::Warning')
398            self.assertRaises(self.module._OptionError,
399                              self.module._setoption, 'ignore:2::4:-5')
400            self.module._setoption('error::Warning::0')
401            self.assertRaises(UserWarning, self.module.warn, 'convert to error')
402
403    def test_improper_option(self):
404        # Same as above, but check that the message is printed out when
405        # the interpreter is executed. This also checks that options are
406        # actually parsed at all.
407        rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")
408        self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)
409
410    def test_warnings_bootstrap(self):
411        # Check that the warnings module does get loaded when -W<some option>
412        # is used (see issue #10372 for an example of silent bootstrap failure).
413        rc, out, err = assert_python_ok("-Wi", "-c",
414            "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
415        # '-Wi' was observed
416        self.assertFalse(out.strip())
417        self.assertNotIn(b'RuntimeWarning', err)
418
419class CWCmdLineTests(BaseTest, WCmdLineTests):
420    module = c_warnings
421
422class PyWCmdLineTests(BaseTest, WCmdLineTests):
423    module = py_warnings
424
425
426class _WarningsTests(BaseTest):
427
428    """Tests specific to the _warnings module."""
429
430    module = c_warnings
431
432    def test_filter(self):
433        # Everything should function even if 'filters' is not in warnings.
434        with original_warnings.catch_warnings(module=self.module) as w:
435            self.module.filterwarnings("error", "", Warning, "", 0)
436            self.assertRaises(UserWarning, self.module.warn,
437                                'convert to error')
438            del self.module.filters
439            self.assertRaises(UserWarning, self.module.warn,
440                                'convert to error')
441
442    def test_onceregistry(self):
443        # Replacing or removing the onceregistry should be okay.
444        global __warningregistry__
445        message = UserWarning('onceregistry test')
446        try:
447            original_registry = self.module.onceregistry
448            __warningregistry__ = {}
449            with original_warnings.catch_warnings(record=True,
450                    module=self.module) as w:
451                self.module.resetwarnings()
452                self.module.filterwarnings("once", category=UserWarning)
453                self.module.warn_explicit(message, UserWarning, "file", 42)
454                self.assertEqual(w[-1].message, message)
455                del w[:]
456                self.module.warn_explicit(message, UserWarning, "file", 42)
457                self.assertEqual(len(w), 0)
458                # Test the resetting of onceregistry.
459                self.module.onceregistry = {}
460                __warningregistry__ = {}
461                self.module.warn('onceregistry test')
462                self.assertEqual(w[-1].message.args, message.args)
463                # Removal of onceregistry is okay.
464                del w[:]
465                del self.module.onceregistry
466                __warningregistry__ = {}
467                self.module.warn_explicit(message, UserWarning, "file", 42)
468                self.assertEqual(len(w), 0)
469        finally:
470            self.module.onceregistry = original_registry
471
472    def test_default_action(self):
473        # Replacing or removing defaultaction should be okay.
474        message = UserWarning("defaultaction test")
475        original = self.module.defaultaction
476        try:
477            with original_warnings.catch_warnings(record=True,
478                    module=self.module) as w:
479                self.module.resetwarnings()
480                registry = {}
481                self.module.warn_explicit(message, UserWarning, "<test>", 42,
482                                            registry=registry)
483                self.assertEqual(w[-1].message, message)
484                self.assertEqual(len(w), 1)
485                self.assertEqual(len(registry), 1)
486                del w[:]
487                # Test removal.
488                del self.module.defaultaction
489                __warningregistry__ = {}
490                registry = {}
491                self.module.warn_explicit(message, UserWarning, "<test>", 43,
492                                            registry=registry)
493                self.assertEqual(w[-1].message, message)
494                self.assertEqual(len(w), 1)
495                self.assertEqual(len(registry), 1)
496                del w[:]
497                # Test setting.
498                self.module.defaultaction = "ignore"
499                __warningregistry__ = {}
500                registry = {}
501                self.module.warn_explicit(message, UserWarning, "<test>", 44,
502                                            registry=registry)
503                self.assertEqual(len(w), 0)
504        finally:
505            self.module.defaultaction = original
506
507    def test_showwarning_missing(self):
508        # Test that showwarning() missing is okay.
509        text = 'del showwarning test'
510        with original_warnings.catch_warnings(module=self.module):
511            self.module.filterwarnings("always", category=UserWarning)
512            del self.module.showwarning
513            with test_support.captured_output('stderr') as stream:
514                self.module.warn(text)
515                result = stream.getvalue()
516        self.assertIn(text, result)
517
518    def test_showwarning_not_callable(self):
519        with original_warnings.catch_warnings(module=self.module):
520            self.module.filterwarnings("always", category=UserWarning)
521            old_showwarning = self.module.showwarning
522            self.module.showwarning = 23
523            try:
524                self.assertRaises(TypeError, self.module.warn, "Warning!")
525            finally:
526                self.module.showwarning = old_showwarning
527
528    def test_show_warning_output(self):
529        # With showarning() missing, make sure that output is okay.
530        text = 'test show_warning'
531        with original_warnings.catch_warnings(module=self.module):
532            self.module.filterwarnings("always", category=UserWarning)
533            del self.module.showwarning
534            with test_support.captured_output('stderr') as stream:
535                warning_tests.inner(text)
536                result = stream.getvalue()
537        self.assertEqual(result.count('\n'), 2,
538                             "Too many newlines in %r" % result)
539        first_line, second_line = result.split('\n', 1)
540        expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
541        first_line_parts = first_line.rsplit(':', 3)
542        path, line, warning_class, message = first_line_parts
543        line = int(line)
544        self.assertEqual(expected_file, path)
545        self.assertEqual(warning_class, ' ' + UserWarning.__name__)
546        self.assertEqual(message, ' ' + text)
547        expected_line = '  ' + linecache.getline(path, line).strip() + '\n'
548        assert expected_line
549        self.assertEqual(second_line, expected_line)
550
551    def test_filename_none(self):
552        # issue #12467: race condition if a warning is emitted at shutdown
553        globals_dict = globals()
554        oldfile = globals_dict['__file__']
555        try:
556            with original_warnings.catch_warnings(module=self.module) as w:
557                self.module.filterwarnings("always", category=UserWarning)
558                globals_dict['__file__'] = None
559                self.module.warn('test', UserWarning)
560        finally:
561            globals_dict['__file__'] = oldfile
562
563    def test_stderr_none(self):
564        rc, stdout, stderr = assert_python_ok("-c",
565            "import sys; sys.stderr = None; "
566            "import warnings; warnings.simplefilter('always'); "
567            "warnings.warn('Warning!')")
568        self.assertEqual(stdout, b'')
569        self.assertNotIn(b'Warning!', stderr)
570        self.assertNotIn(b'Error', stderr)
571
572
573class WarningsDisplayTests(unittest.TestCase):
574
575    """Test the displaying of warnings and the ability to overload functions
576    related to displaying warnings."""
577
578    def test_formatwarning(self):
579        message = "msg"
580        category = Warning
581        file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
582        line_num = 3
583        file_line = linecache.getline(file_name, line_num).strip()
584        format = "%s:%s: %s: %s\n  %s\n"
585        expect = format % (file_name, line_num, category.__name__, message,
586                            file_line)
587        self.assertEqual(expect, self.module.formatwarning(message,
588                                                category, file_name, line_num))
589        # Test the 'line' argument.
590        file_line += " for the win!"
591        expect = format % (file_name, line_num, category.__name__, message,
592                            file_line)
593        self.assertEqual(expect, self.module.formatwarning(message,
594                                    category, file_name, line_num, file_line))
595
596    @test_support.requires_unicode
597    def test_formatwarning_unicode_msg(self):
598        message = u"msg"
599        category = Warning
600        file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
601        line_num = 3
602        file_line = linecache.getline(file_name, line_num).strip()
603        format = "%s:%s: %s: %s\n  %s\n"
604        expect = format % (file_name, line_num, category.__name__, message,
605                            file_line)
606        self.assertEqual(expect, self.module.formatwarning(message,
607                                                category, file_name, line_num))
608        # Test the 'line' argument.
609        file_line += " for the win!"
610        expect = format % (file_name, line_num, category.__name__, message,
611                            file_line)
612        self.assertEqual(expect, self.module.formatwarning(message,
613                                    category, file_name, line_num, file_line))
614
615    @test_support.requires_unicode
616    @unittest.skipUnless(test_support.FS_NONASCII, 'need test_support.FS_NONASCII')
617    def test_formatwarning_unicode_msg_nonascii_filename(self):
618        message = u"msg"
619        category = Warning
620        unicode_file_name = test_support.FS_NONASCII + u'.py'
621        file_name = unicode_file_name.encode(sys.getfilesystemencoding())
622        line_num = 3
623        file_line = 'spam'
624        format = "%s:%s: %s: %s\n  %s\n"
625        expect = format % (file_name, line_num, category.__name__, str(message),
626                            file_line)
627        self.assertEqual(expect, self.module.formatwarning(message,
628                                    category, file_name, line_num, file_line))
629        message = u"\xb5sg"
630        expect = format % (unicode_file_name, line_num, category.__name__, message,
631                            file_line)
632        self.assertEqual(expect, self.module.formatwarning(message,
633                                    category, file_name, line_num, file_line))
634
635    @test_support.requires_unicode
636    def test_formatwarning_unicode_msg_nonascii_fileline(self):
637        message = u"msg"
638        category = Warning
639        file_name = 'file.py'
640        line_num = 3
641        file_line = 'sp\xe4m'
642        format = "%s:%s: %s: %s\n  %s\n"
643        expect = format % (file_name, line_num, category.__name__, str(message),
644                            file_line)
645        self.assertEqual(expect, self.module.formatwarning(message,
646                                    category, file_name, line_num, file_line))
647        message = u"\xb5sg"
648        expect = format % (file_name, line_num, category.__name__, message,
649                            unicode(file_line, 'latin1'))
650        self.assertEqual(expect, self.module.formatwarning(message,
651                                    category, file_name, line_num, file_line))
652
653    def test_showwarning(self):
654        file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
655        line_num = 3
656        expected_file_line = linecache.getline(file_name, line_num).strip()
657        message = 'msg'
658        category = Warning
659        file_object = StringIO.StringIO()
660        expect = self.module.formatwarning(message, category, file_name,
661                                            line_num)
662        self.module.showwarning(message, category, file_name, line_num,
663                                file_object)
664        self.assertEqual(file_object.getvalue(), expect)
665        # Test 'line' argument.
666        expected_file_line += "for the win!"
667        expect = self.module.formatwarning(message, category, file_name,
668                                            line_num, expected_file_line)
669        file_object = StringIO.StringIO()
670        self.module.showwarning(message, category, file_name, line_num,
671                                file_object, expected_file_line)
672        self.assertEqual(expect, file_object.getvalue())
673
674class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
675    module = c_warnings
676
677class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
678    module = py_warnings
679
680
681class CatchWarningTests(BaseTest):
682
683    """Test catch_warnings()."""
684
685    def test_catch_warnings_restore(self):
686        wmod = self.module
687        orig_filters = wmod.filters
688        orig_showwarning = wmod.showwarning
689        # Ensure both showwarning and filters are restored when recording
690        with wmod.catch_warnings(module=wmod, record=True):
691            wmod.filters = wmod.showwarning = object()
692        self.assertTrue(wmod.filters is orig_filters)
693        self.assertTrue(wmod.showwarning is orig_showwarning)
694        # Same test, but with recording disabled
695        with wmod.catch_warnings(module=wmod, record=False):
696            wmod.filters = wmod.showwarning = object()
697        self.assertTrue(wmod.filters is orig_filters)
698        self.assertTrue(wmod.showwarning is orig_showwarning)
699
700    def test_catch_warnings_recording(self):
701        wmod = self.module
702        # Ensure warnings are recorded when requested
703        with wmod.catch_warnings(module=wmod, record=True) as w:
704            self.assertEqual(w, [])
705            self.assertTrue(type(w) is list)
706            wmod.simplefilter("always")
707            wmod.warn("foo")
708            self.assertEqual(str(w[-1].message), "foo")
709            wmod.warn("bar")
710            self.assertEqual(str(w[-1].message), "bar")
711            self.assertEqual(str(w[0].message), "foo")
712            self.assertEqual(str(w[1].message), "bar")
713            del w[:]
714            self.assertEqual(w, [])
715        # Ensure warnings are not recorded when not requested
716        orig_showwarning = wmod.showwarning
717        with wmod.catch_warnings(module=wmod, record=False) as w:
718            self.assertTrue(w is None)
719            self.assertTrue(wmod.showwarning is orig_showwarning)
720
721    def test_catch_warnings_reentry_guard(self):
722        wmod = self.module
723        # Ensure catch_warnings is protected against incorrect usage
724        x = wmod.catch_warnings(module=wmod, record=True)
725        self.assertRaises(RuntimeError, x.__exit__)
726        with x:
727            self.assertRaises(RuntimeError, x.__enter__)
728        # Same test, but with recording disabled
729        x = wmod.catch_warnings(module=wmod, record=False)
730        self.assertRaises(RuntimeError, x.__exit__)
731        with x:
732            self.assertRaises(RuntimeError, x.__enter__)
733
734    def test_catch_warnings_defaults(self):
735        wmod = self.module
736        orig_filters = wmod.filters
737        orig_showwarning = wmod.showwarning
738        # Ensure default behaviour is not to record warnings
739        with wmod.catch_warnings(module=wmod) as w:
740            self.assertTrue(w is None)
741            self.assertTrue(wmod.showwarning is orig_showwarning)
742            self.assertTrue(wmod.filters is not orig_filters)
743        self.assertTrue(wmod.filters is orig_filters)
744        if wmod is sys.modules['warnings']:
745            # Ensure the default module is this one
746            with wmod.catch_warnings() as w:
747                self.assertTrue(w is None)
748                self.assertTrue(wmod.showwarning is orig_showwarning)
749                self.assertTrue(wmod.filters is not orig_filters)
750            self.assertTrue(wmod.filters is orig_filters)
751
752    def test_check_warnings(self):
753        # Explicit tests for the test_support convenience wrapper
754        wmod = self.module
755        if wmod is not sys.modules['warnings']:
756            self.skipTest('module to test is not loaded warnings module')
757        with test_support.check_warnings(quiet=False) as w:
758            self.assertEqual(w.warnings, [])
759            wmod.simplefilter("always")
760            wmod.warn("foo")
761            self.assertEqual(str(w.message), "foo")
762            wmod.warn("bar")
763            self.assertEqual(str(w.message), "bar")
764            self.assertEqual(str(w.warnings[0].message), "foo")
765            self.assertEqual(str(w.warnings[1].message), "bar")
766            w.reset()
767            self.assertEqual(w.warnings, [])
768
769        with test_support.check_warnings():
770            # defaults to quiet=True without argument
771            pass
772        with test_support.check_warnings(('foo', UserWarning)):
773            wmod.warn("foo")
774
775        with self.assertRaises(AssertionError):
776            with test_support.check_warnings(('', RuntimeWarning)):
777                # defaults to quiet=False with argument
778                pass
779        with self.assertRaises(AssertionError):
780            with test_support.check_warnings(('foo', RuntimeWarning)):
781                wmod.warn("foo")
782
783
784class CCatchWarningTests(CatchWarningTests):
785    module = c_warnings
786
787class PyCatchWarningTests(CatchWarningTests):
788    module = py_warnings
789
790
791class EnvironmentVariableTests(BaseTest):
792
793    def test_single_warning(self):
794        newenv = os.environ.copy()
795        newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
796        p = subprocess.Popen([sys.executable,
797                "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
798                stdout=subprocess.PIPE, env=newenv)
799        self.assertEqual(p.communicate()[0], "['ignore::DeprecationWarning']")
800        self.assertEqual(p.wait(), 0)
801
802    def test_comma_separated_warnings(self):
803        newenv = os.environ.copy()
804        newenv["PYTHONWARNINGS"] = ("ignore::DeprecationWarning,"
805                                    "ignore::UnicodeWarning")
806        p = subprocess.Popen([sys.executable,
807                "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
808                stdout=subprocess.PIPE, env=newenv)
809        self.assertEqual(p.communicate()[0],
810                "['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
811        self.assertEqual(p.wait(), 0)
812
813    def test_envvar_and_command_line(self):
814        newenv = os.environ.copy()
815        newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
816        p = subprocess.Popen([sys.executable, "-W" "ignore::UnicodeWarning",
817                "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
818                stdout=subprocess.PIPE, env=newenv)
819        self.assertEqual(p.communicate()[0],
820                "['ignore::UnicodeWarning', 'ignore::DeprecationWarning']")
821        self.assertEqual(p.wait(), 0)
822
823class CEnvironmentVariableTests(EnvironmentVariableTests):
824    module = c_warnings
825
826class PyEnvironmentVariableTests(EnvironmentVariableTests):
827    module = py_warnings
828
829
830def test_main():
831    py_warnings.onceregistry.clear()
832    c_warnings.onceregistry.clear()
833    test_support.run_unittest(CFilterTests, PyFilterTests,
834                                CWarnTests, PyWarnTests,
835                                CWCmdLineTests, PyWCmdLineTests,
836                                _WarningsTests,
837                                CWarningsDisplayTests, PyWarningsDisplayTests,
838                                CCatchWarningTests, PyCatchWarningTests,
839                                CEnvironmentVariableTests,
840                                PyEnvironmentVariableTests
841                             )
842
843
844if __name__ == "__main__":
845    test_main()
Note: See TracBrowser for help on using the repository browser.