»Core Development>Code coverage>Lib/test/test_warnings/__init__.py

Python code coverage for Lib/test/test_warnings/__init__.py

1n/afrom contextlib import contextmanager
2n/aimport linecache
3n/aimport os
4n/afrom io import StringIO
5n/aimport re
6n/aimport sys
7n/aimport textwrap
8n/aimport unittest
9n/afrom test import support
10n/afrom test.support.script_helper import assert_python_ok, assert_python_failure
12n/afrom test.test_warnings.data import stacklevel as warning_tests
14n/aimport warnings as original_warnings
16n/apy_warnings = support.import_fresh_module('warnings', blocked=['_warnings'])
17n/ac_warnings = support.import_fresh_module('warnings', fresh=['_warnings'])
20n/adef warnings_state(module):
21n/a """Use a specific warnings implementation in warning_tests."""
22n/a global __warningregistry__
23n/a for to_clear in (sys, warning_tests):
24n/a try:
25n/a to_clear.__warningregistry__.clear()
26n/a except AttributeError:
27n/a pass
28n/a try:
29n/a __warningregistry__.clear()
30n/a except NameError:
31n/a pass
32n/a original_warnings = warning_tests.warnings
33n/a original_filters = module.filters
34n/a try:
35n/a module.filters = original_filters[:]
36n/a module.simplefilter("once")
37n/a warning_tests.warnings = module
38n/a yield
39n/a finally:
40n/a warning_tests.warnings = original_warnings
41n/a module.filters = original_filters
44n/aclass BaseTest:
46n/a """Basic bookkeeping required for testing."""
48n/a def setUp(self):
49n/a self.old_unittest_module = unittest.case.warnings
50n/a # The __warningregistry__ needs to be in a pristine state for tests
51n/a # to work properly.
52n/a if '__warningregistry__' in globals():
53n/a del globals()['__warningregistry__']
54n/a if hasattr(warning_tests, '__warningregistry__'):
55n/a del warning_tests.__warningregistry__
56n/a if hasattr(sys, '__warningregistry__'):
57n/a del sys.__warningregistry__
58n/a # The 'warnings' module must be explicitly set so that the proper
59n/a # interaction between _warnings and 'warnings' can be controlled.
60n/a sys.modules['warnings'] = self.module
61n/a # Ensure that unittest.TestCase.assertWarns() uses the same warnings
62n/a # module than warnings.catch_warnings(). Otherwise,
63n/a # warnings.catch_warnings() will be unable to remove the added filter.
64n/a unittest.case.warnings = self.module
65n/a super(BaseTest, self).setUp()
67n/a def tearDown(self):
68n/a sys.modules['warnings'] = original_warnings
69n/a unittest.case.warnings = self.old_unittest_module
70n/a super(BaseTest, self).tearDown()
72n/aclass PublicAPITests(BaseTest):
74n/a """Ensures that the correct values are exposed in the
75n/a public API.
76n/a """
78n/a def test_module_all_attribute(self):
79n/a self.assertTrue(hasattr(self.module, '__all__'))
80n/a target_api = ["warn", "warn_explicit", "showwarning",
81n/a "formatwarning", "filterwarnings", "simplefilter",
82n/a "resetwarnings", "catch_warnings"]
83n/a self.assertSetEqual(set(self.module.__all__),
84n/a set(target_api))
86n/aclass CPublicAPITests(PublicAPITests, unittest.TestCase):
87n/a module = c_warnings
89n/aclass PyPublicAPITests(PublicAPITests, unittest.TestCase):
90n/a module = py_warnings
92n/aclass FilterTests(BaseTest):
94n/a """Testing the filtering functionality."""
96n/a def test_error(self):
97n/a with original_warnings.catch_warnings(module=self.module) as w:
98n/a self.module.resetwarnings()
99n/a self.module.filterwarnings("error", category=UserWarning)
100n/a self.assertRaises(UserWarning, self.module.warn,
101n/a "FilterTests.test_error")
103n/a def test_error_after_default(self):
104n/a with original_warnings.catch_warnings(module=self.module) as w:
105n/a self.module.resetwarnings()
106n/a message = "FilterTests.test_ignore_after_default"
107n/a def f():
108n/a self.module.warn(message, UserWarning)
110n/a with support.captured_stderr() as stderr:
111n/a f()
112n/a stderr = stderr.getvalue()
113n/a self.assertIn("UserWarning: FilterTests.test_ignore_after_default",
114n/a stderr)
115n/a self.assertIn("self.module.warn(message, UserWarning)",
116n/a stderr)
118n/a self.module.filterwarnings("error", category=UserWarning)
119n/a self.assertRaises(UserWarning, f)
121n/a def test_ignore(self):
122n/a with original_warnings.catch_warnings(record=True,
123n/a module=self.module) as w:
124n/a self.module.resetwarnings()
125n/a self.module.filterwarnings("ignore", category=UserWarning)
126n/a self.module.warn("FilterTests.test_ignore", UserWarning)
127n/a self.assertEqual(len(w), 0)
129n/a def test_ignore_after_default(self):
130n/a with original_warnings.catch_warnings(record=True,
131n/a module=self.module) as w:
132n/a self.module.resetwarnings()
133n/a message = "FilterTests.test_ignore_after_default"
134n/a def f():
135n/a self.module.warn(message, UserWarning)
136n/a f()
137n/a self.module.filterwarnings("ignore", category=UserWarning)
138n/a f()
139n/a f()
140n/a self.assertEqual(len(w), 1)
142n/a def test_always(self):
143n/a with original_warnings.catch_warnings(record=True,
144n/a module=self.module) as w:
145n/a self.module.resetwarnings()
146n/a self.module.filterwarnings("always", category=UserWarning)
147n/a message = "FilterTests.test_always"
148n/a self.module.warn(message, UserWarning)
149n/a self.assertTrue(message, w[-1].message)
150n/a self.module.warn(message, UserWarning)
151n/a self.assertTrue(w[-1].message, message)
153n/a def test_always_after_default(self):
154n/a with original_warnings.catch_warnings(record=True,
155n/a module=self.module) as w:
156n/a self.module.resetwarnings()
157n/a message = "FilterTests.test_always_after_ignore"
158n/a def f():
159n/a self.module.warn(message, UserWarning)
160n/a f()
161n/a self.assertEqual(len(w), 1)
162n/a self.assertEqual(w[-1].message.args[0], message)
163n/a f()
164n/a self.assertEqual(len(w), 1)
165n/a self.module.filterwarnings("always", category=UserWarning)
166n/a f()
167n/a self.assertEqual(len(w), 2)
168n/a self.assertEqual(w[-1].message.args[0], message)
169n/a f()
170n/a self.assertEqual(len(w), 3)
171n/a self.assertEqual(w[-1].message.args[0], message)
173n/a def test_default(self):
174n/a with original_warnings.catch_warnings(record=True,
175n/a module=self.module) as w:
176n/a self.module.resetwarnings()
177n/a self.module.filterwarnings("default", category=UserWarning)
178n/a message = UserWarning("FilterTests.test_default")
179n/a for x in range(2):
180n/a self.module.warn(message, UserWarning)
181n/a if x == 0:
182n/a self.assertEqual(w[-1].message, message)
183n/a del w[:]
184n/a elif x == 1:
185n/a self.assertEqual(len(w), 0)
186n/a else:
187n/a raise ValueError("loop variant unhandled")
189n/a def test_module(self):
190n/a with original_warnings.catch_warnings(record=True,
191n/a module=self.module) as w:
192n/a self.module.resetwarnings()
193n/a self.module.filterwarnings("module", category=UserWarning)
194n/a message = UserWarning("FilterTests.test_module")
195n/a self.module.warn(message, UserWarning)
196n/a self.assertEqual(w[-1].message, message)
197n/a del w[:]
198n/a self.module.warn(message, UserWarning)
199n/a self.assertEqual(len(w), 0)
201n/a def test_once(self):
202n/a with original_warnings.catch_warnings(record=True,
203n/a module=self.module) as w:
204n/a self.module.resetwarnings()
205n/a self.module.filterwarnings("once", category=UserWarning)
206n/a message = UserWarning("FilterTests.test_once")
207n/a self.module.warn_explicit(message, UserWarning, "__init__.py",
208n/a 42)
209n/a self.assertEqual(w[-1].message, message)
210n/a del w[:]
211n/a self.module.warn_explicit(message, UserWarning, "__init__.py",
212n/a 13)
213n/a self.assertEqual(len(w), 0)
214n/a self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
215n/a 42)
216n/a self.assertEqual(len(w), 0)
218n/a def test_inheritance(self):
219n/a with original_warnings.catch_warnings(module=self.module) as w:
220n/a self.module.resetwarnings()
221n/a self.module.filterwarnings("error", category=Warning)
222n/a self.assertRaises(UserWarning, self.module.warn,
223n/a "FilterTests.test_inheritance", UserWarning)
225n/a def test_ordering(self):
226n/a with original_warnings.catch_warnings(record=True,
227n/a module=self.module) as w:
228n/a self.module.resetwarnings()
229n/a self.module.filterwarnings("ignore", category=UserWarning)
230n/a self.module.filterwarnings("error", category=UserWarning,
231n/a append=True)
232n/a del w[:]
233n/a try:
234n/a self.module.warn("FilterTests.test_ordering", UserWarning)
235n/a except UserWarning:
236n/a self.fail("order handling for actions failed")
237n/a self.assertEqual(len(w), 0)
239n/a def test_filterwarnings(self):
240n/a # Test filterwarnings().
241n/a # Implicitly also tests resetwarnings().
242n/a with original_warnings.catch_warnings(record=True,
243n/a module=self.module) as w:
244n/a self.module.filterwarnings("error", "", Warning, "", 0)
245n/a self.assertRaises(UserWarning, self.module.warn, 'convert to error')
247n/a self.module.resetwarnings()
248n/a text = 'handle normally'
249n/a self.module.warn(text)
250n/a self.assertEqual(str(w[-1].message), text)
251n/a self.assertTrue(w[-1].category is UserWarning)
253n/a self.module.filterwarnings("ignore", "", Warning, "", 0)
254n/a text = 'filtered out'
255n/a self.module.warn(text)
256n/a self.assertNotEqual(str(w[-1].message), text)
258n/a self.module.resetwarnings()
259n/a self.module.filterwarnings("error", "hex*", Warning, "", 0)
260n/a self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
261n/a text = 'nonmatching text'
262n/a self.module.warn(text)
263n/a self.assertEqual(str(w[-1].message), text)
264n/a self.assertTrue(w[-1].category is UserWarning)
266n/a def test_message_matching(self):
267n/a with original_warnings.catch_warnings(record=True,
268n/a module=self.module) as w:
269n/a self.module.simplefilter("ignore", UserWarning)
270n/a self.module.filterwarnings("error", "match", UserWarning)
271n/a self.assertRaises(UserWarning, self.module.warn, "match")
272n/a self.assertRaises(UserWarning, self.module.warn, "match prefix")
273n/a self.module.warn("suffix match")
274n/a self.assertEqual(w, [])
275n/a self.module.warn("something completely different")
276n/a self.assertEqual(w, [])
278n/a def test_mutate_filter_list(self):
279n/a class X:
280n/a def match(self, a):
281n/a L[:] = []
283n/a L = [("default",X(),UserWarning,X(),0) for i in range(2)]
284n/a with original_warnings.catch_warnings(record=True,
285n/a module=self.module) as w:
286n/a self.module.filters = L
287n/a self.module.warn_explicit(UserWarning("b"), None, "f.py", 42)
288n/a self.assertEqual(str(w[-1].message), "b")
290n/a def test_filterwarnings_duplicate_filters(self):
291n/a with original_warnings.catch_warnings(module=self.module):
292n/a self.module.resetwarnings()
293n/a self.module.filterwarnings("error", category=UserWarning)
294n/a self.assertEqual(len(self.module.filters), 1)
295n/a self.module.filterwarnings("ignore", category=UserWarning)
296n/a self.module.filterwarnings("error", category=UserWarning)
297n/a self.assertEqual(
298n/a len(self.module.filters), 2,
299n/a "filterwarnings inserted duplicate filter"
300n/a )
301n/a self.assertEqual(
302n/a self.module.filters[0][0], "error",
303n/a "filterwarnings did not promote filter to "
304n/a "the beginning of list"
305n/a )
307n/a def test_simplefilter_duplicate_filters(self):
308n/a with original_warnings.catch_warnings(module=self.module):
309n/a self.module.resetwarnings()
310n/a self.module.simplefilter("error", category=UserWarning)
311n/a self.assertEqual(len(self.module.filters), 1)
312n/a self.module.simplefilter("ignore", category=UserWarning)
313n/a self.module.simplefilter("error", category=UserWarning)
314n/a self.assertEqual(
315n/a len(self.module.filters), 2,
316n/a "simplefilter inserted duplicate filter"
317n/a )
318n/a self.assertEqual(
319n/a self.module.filters[0][0], "error",
320n/a "simplefilter did not promote filter to the beginning of list"
321n/a )
322n/a def test_append_duplicate(self):
323n/a with original_warnings.catch_warnings(module=self.module,
324n/a record=True) as w:
325n/a self.module.resetwarnings()
326n/a self.module.simplefilter("ignore")
327n/a self.module.simplefilter("error", append=True)
328n/a self.module.simplefilter("ignore", append=True)
329n/a self.module.warn("test_append_duplicate", category=UserWarning)
330n/a self.assertEqual(len(self.module.filters), 2,
331n/a "simplefilter inserted duplicate filter"
332n/a )
333n/a self.assertEqual(len(w), 0,
334n/a "appended duplicate changed order of filters"
335n/a )
337n/aclass CFilterTests(FilterTests, unittest.TestCase):
338n/a module = c_warnings
340n/aclass PyFilterTests(FilterTests, unittest.TestCase):
341n/a module = py_warnings
344n/aclass WarnTests(BaseTest):
346n/a """Test warnings.warn() and warnings.warn_explicit()."""
348n/a def test_message(self):
349n/a with original_warnings.catch_warnings(record=True,
350n/a module=self.module) as w:
351n/a self.module.simplefilter("once")
352n/a for i in range(4):
353n/a text = 'multi %d' %i # Different text on each call.
354n/a self.module.warn(text)
355n/a self.assertEqual(str(w[-1].message), text)
356n/a self.assertTrue(w[-1].category is UserWarning)
358n/a # Issue 3639
359n/a def test_warn_nonstandard_types(self):
360n/a # warn() should handle non-standard types without issue.
361n/a for ob in (Warning, None, 42):
362n/a with original_warnings.catch_warnings(record=True,
363n/a module=self.module) as w:
364n/a self.module.simplefilter("once")
365n/a self.module.warn(ob)
366n/a # Don't directly compare objects since
367n/a # ``Warning() != Warning()``.
368n/a self.assertEqual(str(w[-1].message), str(UserWarning(ob)))
370n/a def test_filename(self):
371n/a with warnings_state(self.module):
372n/a with original_warnings.catch_warnings(record=True,
373n/a module=self.module) as w:
374n/a warning_tests.inner("spam1")
375n/a self.assertEqual(os.path.basename(w[-1].filename),
376n/a "stacklevel.py")
377n/a warning_tests.outer("spam2")
378n/a self.assertEqual(os.path.basename(w[-1].filename),
379n/a "stacklevel.py")
381n/a def test_stacklevel(self):
382n/a # Test stacklevel argument
383n/a # make sure all messages are different, so the warning won't be skipped
384n/a with warnings_state(self.module):
385n/a with original_warnings.catch_warnings(record=True,
386n/a module=self.module) as w:
387n/a warning_tests.inner("spam3", stacklevel=1)
388n/a self.assertEqual(os.path.basename(w[-1].filename),
389n/a "stacklevel.py")
390n/a warning_tests.outer("spam4", stacklevel=1)
391n/a self.assertEqual(os.path.basename(w[-1].filename),
392n/a "stacklevel.py")
394n/a warning_tests.inner("spam5", stacklevel=2)
395n/a self.assertEqual(os.path.basename(w[-1].filename),
396n/a "__init__.py")
397n/a warning_tests.outer("spam6", stacklevel=2)
398n/a self.assertEqual(os.path.basename(w[-1].filename),
399n/a "stacklevel.py")
400n/a warning_tests.outer("spam6.5", stacklevel=3)
401n/a self.assertEqual(os.path.basename(w[-1].filename),
402n/a "__init__.py")
404n/a warning_tests.inner("spam7", stacklevel=9999)
405n/a self.assertEqual(os.path.basename(w[-1].filename),
406n/a "sys")
408n/a def test_stacklevel_import(self):
409n/a # Issue #24305: With stacklevel=2, module-level warnings should work.
410n/a support.unload('test.test_warnings.data.import_warning')
411n/a with warnings_state(self.module):
412n/a with original_warnings.catch_warnings(record=True,
413n/a module=self.module) as w:
414n/a self.module.simplefilter('always')
415n/a import test.test_warnings.data.import_warning
416n/a self.assertEqual(len(w), 1)
417n/a self.assertEqual(w[0].filename, __file__)
419n/a def test_missing_filename_not_main(self):
420n/a # If __file__ is not specified and __main__ is not the module name,
421n/a # then __file__ should be set to the module name.
422n/a filename = warning_tests.__file__
423n/a try:
424n/a del warning_tests.__file__
425n/a with warnings_state(self.module):
426n/a with original_warnings.catch_warnings(record=True,
427n/a module=self.module) as w:
428n/a warning_tests.inner("spam8", stacklevel=1)
429n/a self.assertEqual(w[-1].filename, warning_tests.__name__)
430n/a finally:
431n/a warning_tests.__file__ = filename
433n/a @unittest.skipUnless(hasattr(sys, 'argv'), 'test needs sys.argv')
434n/a def test_missing_filename_main_with_argv(self):
435n/a # If __file__ is not specified and the caller is __main__ and sys.argv
436n/a # exists, then use sys.argv[0] as the file.
437n/a filename = warning_tests.__file__
438n/a module_name = warning_tests.__name__
439n/a try:
440n/a del warning_tests.__file__
441n/a warning_tests.__name__ = '__main__'
442n/a with warnings_state(self.module):
443n/a with original_warnings.catch_warnings(record=True,
444n/a module=self.module) as w:
445n/a warning_tests.inner('spam9', stacklevel=1)
446n/a self.assertEqual(w[-1].filename, sys.argv[0])
447n/a finally:
448n/a warning_tests.__file__ = filename
449n/a warning_tests.__name__ = module_name
451n/a def test_missing_filename_main_without_argv(self):
452n/a # If __file__ is not specified, the caller is __main__, and sys.argv
453n/a # is not set, then '__main__' is the file name.
454n/a filename = warning_tests.__file__
455n/a module_name = warning_tests.__name__
456n/a argv = sys.argv
457n/a try:
458n/a del warning_tests.__file__
459n/a warning_tests.__name__ = '__main__'
460n/a del sys.argv
461n/a with warnings_state(self.module):
462n/a with original_warnings.catch_warnings(record=True,
463n/a module=self.module) as w:
464n/a warning_tests.inner('spam10', stacklevel=1)
465n/a self.assertEqual(w[-1].filename, '__main__')
466n/a finally:
467n/a warning_tests.__file__ = filename
468n/a warning_tests.__name__ = module_name
469n/a sys.argv = argv
471n/a def test_missing_filename_main_with_argv_empty_string(self):
472n/a # If __file__ is not specified, the caller is __main__, and sys.argv[0]
473n/a # is the empty string, then '__main__ is the file name.
474n/a # Tests issue 2743.
475n/a file_name = warning_tests.__file__
476n/a module_name = warning_tests.__name__
477n/a argv = sys.argv
478n/a try:
479n/a del warning_tests.__file__
480n/a warning_tests.__name__ = '__main__'
481n/a sys.argv = ['']
482n/a with warnings_state(self.module):
483n/a with original_warnings.catch_warnings(record=True,
484n/a module=self.module) as w:
485n/a warning_tests.inner('spam11', stacklevel=1)
486n/a self.assertEqual(w[-1].filename, '__main__')
487n/a finally:
488n/a warning_tests.__file__ = file_name
489n/a warning_tests.__name__ = module_name
490n/a sys.argv = argv
492n/a def test_warn_explicit_non_ascii_filename(self):
493n/a with original_warnings.catch_warnings(record=True,
494n/a module=self.module) as w:
495n/a self.module.resetwarnings()
496n/a self.module.filterwarnings("always", category=UserWarning)
497n/a for filename in ("nonascii\xe9\u20ac", "surrogate\udc80"):
498n/a try:
499n/a os.fsencode(filename)
500n/a except UnicodeEncodeError:
501n/a continue
502n/a self.module.warn_explicit("text", UserWarning, filename, 1)
503n/a self.assertEqual(w[-1].filename, filename)
505n/a def test_warn_explicit_type_errors(self):
506n/a # warn_explicit() should error out gracefully if it is given objects
507n/a # of the wrong types.
508n/a # lineno is expected to be an integer.
509n/a self.assertRaises(TypeError, self.module.warn_explicit,
510n/a None, UserWarning, None, None)
511n/a # Either 'message' needs to be an instance of Warning or 'category'
512n/a # needs to be a subclass.
513n/a self.assertRaises(TypeError, self.module.warn_explicit,
514n/a None, None, None, 1)
515n/a # 'registry' must be a dict or None.
516n/a self.assertRaises((TypeError, AttributeError),
517n/a self.module.warn_explicit,
518n/a None, Warning, None, 1, registry=42)
520n/a def test_bad_str(self):
521n/a # issue 6415
522n/a # Warnings instance with a bad format string for __str__ should not
523n/a # trigger a bus error.
524n/a class BadStrWarning(Warning):
525n/a """Warning with a bad format string for __str__."""
526n/a def __str__(self):
527n/a return ("A bad formatted string %(err)" %
528n/a {"err" : "there is no %(err)s"})
530n/a with self.assertRaises(ValueError):
531n/a self.module.warn(BadStrWarning())
533n/a def test_warning_classes(self):
534n/a class MyWarningClass(Warning):
535n/a pass
537n/a class NonWarningSubclass:
538n/a pass
540n/a # passing a non-subclass of Warning should raise a TypeError
541n/a with self.assertRaises(TypeError) as cm:
542n/a self.module.warn('bad warning category', '')
543n/a self.assertIn('category must be a Warning subclass, not ',
544n/a str(cm.exception))
546n/a with self.assertRaises(TypeError) as cm:
547n/a self.module.warn('bad warning category', NonWarningSubclass)
548n/a self.assertIn('category must be a Warning subclass, not ',
549n/a str(cm.exception))
551n/a # check that warning instances also raise a TypeError
552n/a with self.assertRaises(TypeError) as cm:
553n/a self.module.warn('bad warning category', MyWarningClass())
554n/a self.assertIn('category must be a Warning subclass, not ',
555n/a str(cm.exception))
557n/a with original_warnings.catch_warnings(module=self.module):
558n/a self.module.resetwarnings()
559n/a self.module.filterwarnings('default')
560n/a with self.assertWarns(MyWarningClass) as cm:
561n/a self.module.warn('good warning category', MyWarningClass)
562n/a self.assertEqual('good warning category', str(cm.warning))
564n/a with self.assertWarns(UserWarning) as cm:
565n/a self.module.warn('good warning category', None)
566n/a self.assertEqual('good warning category', str(cm.warning))
568n/a with self.assertWarns(MyWarningClass) as cm:
569n/a self.module.warn('good warning category', MyWarningClass)
570n/a self.assertIsInstance(cm.warning, Warning)
572n/aclass CWarnTests(WarnTests, unittest.TestCase):
573n/a module = c_warnings
575n/a # As an early adopter, we sanity check the
576n/a # test.support.import_fresh_module utility function
577n/a def test_accelerated(self):
578n/a self.assertFalse(original_warnings is self.module)
579n/a self.assertFalse(hasattr(self.module.warn, '__code__'))
581n/aclass PyWarnTests(WarnTests, unittest.TestCase):
582n/a module = py_warnings
584n/a # As an early adopter, we sanity check the
585n/a # test.support.import_fresh_module utility function
586n/a def test_pure_python(self):
587n/a self.assertFalse(original_warnings is self.module)
588n/a self.assertTrue(hasattr(self.module.warn, '__code__'))
591n/aclass WCmdLineTests(BaseTest):
593n/a def test_improper_input(self):
594n/a # Uses the private _setoption() function to test the parsing
595n/a # of command-line warning arguments
596n/a with original_warnings.catch_warnings(module=self.module):
597n/a self.assertRaises(self.module._OptionError,
598n/a self.module._setoption, '1:2:3:4:5:6')
599n/a self.assertRaises(self.module._OptionError,
600n/a self.module._setoption, 'bogus::Warning')
601n/a self.assertRaises(self.module._OptionError,
602n/a self.module._setoption, 'ignore:2::4:-5')
603n/a self.module._setoption('error::Warning::0')
604n/a self.assertRaises(UserWarning, self.module.warn, 'convert to error')
607n/aclass CWCmdLineTests(WCmdLineTests, unittest.TestCase):
608n/a module = c_warnings
611n/aclass PyWCmdLineTests(WCmdLineTests, unittest.TestCase):
612n/a module = py_warnings
614n/a def test_improper_option(self):
615n/a # Same as above, but check that the message is printed out when
616n/a # the interpreter is executed. This also checks that options are
617n/a # actually parsed at all.
618n/a rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")
619n/a self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)
621n/a def test_warnings_bootstrap(self):
622n/a # Check that the warnings module does get loaded when -W<some option>
623n/a # is used (see issue #10372 for an example of silent bootstrap failure).
624n/a rc, out, err = assert_python_ok("-Wi", "-c",
625n/a "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
626n/a # '-Wi' was observed
627n/a self.assertFalse(out.strip())
628n/a self.assertNotIn(b'RuntimeWarning', err)
631n/aclass _WarningsTests(BaseTest, unittest.TestCase):
633n/a """Tests specific to the _warnings module."""
635n/a module = c_warnings
637n/a def test_filter(self):
638n/a # Everything should function even if 'filters' is not in warnings.
639n/a with original_warnings.catch_warnings(module=self.module) as w:
640n/a self.module.filterwarnings("error", "", Warning, "", 0)
641n/a self.assertRaises(UserWarning, self.module.warn,
642n/a 'convert to error')
643n/a del self.module.filters
644n/a self.assertRaises(UserWarning, self.module.warn,
645n/a 'convert to error')
647n/a def test_onceregistry(self):
648n/a # Replacing or removing the onceregistry should be okay.
649n/a global __warningregistry__
650n/a message = UserWarning('onceregistry test')
651n/a try:
652n/a original_registry = self.module.onceregistry
653n/a __warningregistry__ = {}
654n/a with original_warnings.catch_warnings(record=True,
655n/a module=self.module) as w:
656n/a self.module.resetwarnings()
657n/a self.module.filterwarnings("once", category=UserWarning)
658n/a self.module.warn_explicit(message, UserWarning, "file", 42)
659n/a self.assertEqual(w[-1].message, message)
660n/a del w[:]
661n/a self.module.warn_explicit(message, UserWarning, "file", 42)
662n/a self.assertEqual(len(w), 0)
663n/a # Test the resetting of onceregistry.
664n/a self.module.onceregistry = {}
665n/a __warningregistry__ = {}
666n/a self.module.warn('onceregistry test')
667n/a self.assertEqual(w[-1].message.args, message.args)
668n/a # Removal of onceregistry is okay.
669n/a del w[:]
670n/a del self.module.onceregistry
671n/a __warningregistry__ = {}
672n/a self.module.warn_explicit(message, UserWarning, "file", 42)
673n/a self.assertEqual(len(w), 0)
674n/a finally:
675n/a self.module.onceregistry = original_registry
677n/a def test_default_action(self):
678n/a # Replacing or removing defaultaction should be okay.
679n/a message = UserWarning("defaultaction test")
680n/a original = self.module.defaultaction
681n/a try:
682n/a with original_warnings.catch_warnings(record=True,
683n/a module=self.module) as w:
684n/a self.module.resetwarnings()
685n/a registry = {}
686n/a self.module.warn_explicit(message, UserWarning, "<test>", 42,
687n/a registry=registry)
688n/a self.assertEqual(w[-1].message, message)
689n/a self.assertEqual(len(w), 1)
690n/a # One actual registry key plus the "version" key
691n/a self.assertEqual(len(registry), 2)
692n/a self.assertIn("version", registry)
693n/a del w[:]
694n/a # Test removal.
695n/a del self.module.defaultaction
696n/a __warningregistry__ = {}
697n/a registry = {}
698n/a self.module.warn_explicit(message, UserWarning, "<test>", 43,
699n/a registry=registry)
700n/a self.assertEqual(w[-1].message, message)
701n/a self.assertEqual(len(w), 1)
702n/a self.assertEqual(len(registry), 2)
703n/a del w[:]
704n/a # Test setting.
705n/a self.module.defaultaction = "ignore"
706n/a __warningregistry__ = {}
707n/a registry = {}
708n/a self.module.warn_explicit(message, UserWarning, "<test>", 44,
709n/a registry=registry)
710n/a self.assertEqual(len(w), 0)
711n/a finally:
712n/a self.module.defaultaction = original
714n/a def test_showwarning_missing(self):
715n/a # Test that showwarning() missing is okay.
716n/a text = 'del showwarning test'
717n/a with original_warnings.catch_warnings(module=self.module):
718n/a self.module.filterwarnings("always", category=UserWarning)
719n/a del self.module.showwarning
720n/a with support.captured_output('stderr') as stream:
721n/a self.module.warn(text)
722n/a result = stream.getvalue()
723n/a self.assertIn(text, result)
725n/a def test_showwarnmsg_missing(self):
726n/a # Test that _showwarnmsg() missing is okay.
727n/a text = 'del _showwarnmsg test'
728n/a with original_warnings.catch_warnings(module=self.module):
729n/a self.module.filterwarnings("always", category=UserWarning)
730n/a del self.module._showwarnmsg
731n/a with support.captured_output('stderr') as stream:
732n/a self.module.warn(text)
733n/a result = stream.getvalue()
734n/a self.assertIn(text, result)
736n/a def test_showwarning_not_callable(self):
737n/a with original_warnings.catch_warnings(module=self.module):
738n/a self.module.filterwarnings("always", category=UserWarning)
739n/a self.module.showwarning = print
740n/a with support.captured_output('stdout'):
741n/a self.module.warn('Warning!')
742n/a self.module.showwarning = 23
743n/a self.assertRaises(TypeError, self.module.warn, "Warning!")
745n/a def test_show_warning_output(self):
746n/a # With showarning() missing, make sure that output is okay.
747n/a text = 'test show_warning'
748n/a with original_warnings.catch_warnings(module=self.module):
749n/a self.module.filterwarnings("always", category=UserWarning)
750n/a del self.module.showwarning
751n/a with support.captured_output('stderr') as stream:
752n/a warning_tests.inner(text)
753n/a result = stream.getvalue()
754n/a self.assertEqual(result.count('\n'), 2,
755n/a "Too many newlines in %r" % result)
756n/a first_line, second_line = result.split('\n', 1)
757n/a expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
758n/a first_line_parts = first_line.rsplit(':', 3)
759n/a path, line, warning_class, message = first_line_parts
760n/a line = int(line)
761n/a self.assertEqual(expected_file, path)
762n/a self.assertEqual(warning_class, ' ' + UserWarning.__name__)
763n/a self.assertEqual(message, ' ' + text)
764n/a expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
765n/a assert expected_line
766n/a self.assertEqual(second_line, expected_line)
768n/a def test_filename_none(self):
769n/a # issue #12467: race condition if a warning is emitted at shutdown
770n/a globals_dict = globals()
771n/a oldfile = globals_dict['__file__']
772n/a try:
773n/a catch = original_warnings.catch_warnings(record=True,
774n/a module=self.module)
775n/a with catch as w:
776n/a self.module.filterwarnings("always", category=UserWarning)
777n/a globals_dict['__file__'] = None
778n/a original_warnings.warn('test', UserWarning)
779n/a self.assertTrue(len(w))
780n/a finally:
781n/a globals_dict['__file__'] = oldfile
783n/a def test_stderr_none(self):
784n/a rc, stdout, stderr = assert_python_ok("-c",
785n/a "import sys; sys.stderr = None; "
786n/a "import warnings; warnings.simplefilter('always'); "
787n/a "warnings.warn('Warning!')")
788n/a self.assertEqual(stdout, b'')
789n/a self.assertNotIn(b'Warning!', stderr)
790n/a self.assertNotIn(b'Error', stderr)
793n/aclass WarningsDisplayTests(BaseTest):
795n/a """Test the displaying of warnings and the ability to overload functions
796n/a related to displaying warnings."""
798n/a def test_formatwarning(self):
799n/a message = "msg"
800n/a category = Warning
801n/a file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
802n/a line_num = 3
803n/a file_line = linecache.getline(file_name, line_num).strip()
804n/a format = "%s:%s: %s: %s\n %s\n"
805n/a expect = format % (file_name, line_num, category.__name__, message,
806n/a file_line)
807n/a self.assertEqual(expect, self.module.formatwarning(message,
808n/a category, file_name, line_num))
809n/a # Test the 'line' argument.
810n/a file_line += " for the win!"
811n/a expect = format % (file_name, line_num, category.__name__, message,
812n/a file_line)
813n/a self.assertEqual(expect, self.module.formatwarning(message,
814n/a category, file_name, line_num, file_line))
816n/a def test_showwarning(self):
817n/a file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
818n/a line_num = 3
819n/a expected_file_line = linecache.getline(file_name, line_num).strip()
820n/a message = 'msg'
821n/a category = Warning
822n/a file_object = StringIO()
823n/a expect = self.module.formatwarning(message, category, file_name,
824n/a line_num)
825n/a self.module.showwarning(message, category, file_name, line_num,
826n/a file_object)
827n/a self.assertEqual(file_object.getvalue(), expect)
828n/a # Test 'line' argument.
829n/a expected_file_line += "for the win!"
830n/a expect = self.module.formatwarning(message, category, file_name,
831n/a line_num, expected_file_line)
832n/a file_object = StringIO()
833n/a self.module.showwarning(message, category, file_name, line_num,
834n/a file_object, expected_file_line)
835n/a self.assertEqual(expect, file_object.getvalue())
838n/aclass CWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
839n/a module = c_warnings
841n/aclass PyWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
842n/a module = py_warnings
844n/a def test_tracemalloc(self):
845n/a self.addCleanup(support.unlink, support.TESTFN)
847n/a with open(support.TESTFN, 'w') as fp:
848n/a fp.write(textwrap.dedent("""
849n/a def func():
850n/a f = open(__file__)
851n/a # Emit ResourceWarning
852n/a f = None
854n/a func()
855n/a """))
857n/a res = assert_python_ok('-Wd', '-X', 'tracemalloc=2', support.TESTFN)
859n/a stderr = res.err.decode('ascii', 'replace')
860n/a # normalize newlines
861n/a stderr = '\n'.join(stderr.splitlines())
862n/a stderr = re.sub('<.*>', '<...>', stderr)
863n/a expected = textwrap.dedent('''
864n/a {fname}:5: ResourceWarning: unclosed file <...>
865n/a f = None
866n/a Object allocated at (most recent call first):
867n/a File "{fname}", lineno 3
868n/a f = open(__file__)
869n/a File "{fname}", lineno 7
870n/a func()
871n/a ''')
872n/a expected = expected.format(fname=support.TESTFN).strip()
873n/a self.assertEqual(stderr, expected)
876n/aclass CatchWarningTests(BaseTest):
878n/a """Test catch_warnings()."""
880n/a def test_catch_warnings_restore(self):
881n/a wmod = self.module
882n/a orig_filters = wmod.filters
883n/a orig_showwarning = wmod.showwarning
884n/a # Ensure both showwarning and filters are restored when recording
885n/a with wmod.catch_warnings(module=wmod, record=True):
886n/a wmod.filters = wmod.showwarning = object()
887n/a self.assertTrue(wmod.filters is orig_filters)
888n/a self.assertTrue(wmod.showwarning is orig_showwarning)
889n/a # Same test, but with recording disabled
890n/a with wmod.catch_warnings(module=wmod, record=False):
891n/a wmod.filters = wmod.showwarning = object()
892n/a self.assertTrue(wmod.filters is orig_filters)
893n/a self.assertTrue(wmod.showwarning is orig_showwarning)
895n/a def test_catch_warnings_recording(self):
896n/a wmod = self.module
897n/a # Ensure warnings are recorded when requested
898n/a with wmod.catch_warnings(module=wmod, record=True) as w:
899n/a self.assertEqual(w, [])
900n/a self.assertTrue(type(w) is list)
901n/a wmod.simplefilter("always")
902n/a wmod.warn("foo")
903n/a self.assertEqual(str(w[-1].message), "foo")
904n/a wmod.warn("bar")
905n/a self.assertEqual(str(w[-1].message), "bar")
906n/a self.assertEqual(str(w[0].message), "foo")
907n/a self.assertEqual(str(w[1].message), "bar")
908n/a del w[:]
909n/a self.assertEqual(w, [])
910n/a # Ensure warnings are not recorded when not requested
911n/a orig_showwarning = wmod.showwarning
912n/a with wmod.catch_warnings(module=wmod, record=False) as w:
913n/a self.assertTrue(w is None)
914n/a self.assertTrue(wmod.showwarning is orig_showwarning)
916n/a def test_catch_warnings_reentry_guard(self):
917n/a wmod = self.module
918n/a # Ensure catch_warnings is protected against incorrect usage
919n/a x = wmod.catch_warnings(module=wmod, record=True)
920n/a self.assertRaises(RuntimeError, x.__exit__)
921n/a with x:
922n/a self.assertRaises(RuntimeError, x.__enter__)
923n/a # Same test, but with recording disabled
924n/a x = wmod.catch_warnings(module=wmod, record=False)
925n/a self.assertRaises(RuntimeError, x.__exit__)
926n/a with x:
927n/a self.assertRaises(RuntimeError, x.__enter__)
929n/a def test_catch_warnings_defaults(self):
930n/a wmod = self.module
931n/a orig_filters = wmod.filters
932n/a orig_showwarning = wmod.showwarning
933n/a # Ensure default behaviour is not to record warnings
934n/a with wmod.catch_warnings(module=wmod) as w:
935n/a self.assertTrue(w is None)
936n/a self.assertTrue(wmod.showwarning is orig_showwarning)
937n/a self.assertTrue(wmod.filters is not orig_filters)
938n/a self.assertTrue(wmod.filters is orig_filters)
939n/a if wmod is sys.modules['warnings']:
940n/a # Ensure the default module is this one
941n/a with wmod.catch_warnings() as w:
942n/a self.assertTrue(w is None)
943n/a self.assertTrue(wmod.showwarning is orig_showwarning)
944n/a self.assertTrue(wmod.filters is not orig_filters)
945n/a self.assertTrue(wmod.filters is orig_filters)
947n/a def test_record_override_showwarning_before(self):
948n/a # Issue #28835: If warnings.showwarning() was overriden, make sure
949n/a # that catch_warnings(record=True) overrides it again.
950n/a text = "This is a warning"
951n/a wmod = self.module
952n/a my_log = []
954n/a def my_logger(message, category, filename, lineno, file=None, line=None):
955n/a nonlocal my_log
956n/a my_log.append(message)
958n/a # Override warnings.showwarning() before calling catch_warnings()
959n/a with support.swap_attr(wmod, 'showwarning', my_logger):
960n/a with wmod.catch_warnings(module=wmod, record=True) as log:
961n/a self.assertIsNot(wmod.showwarning, my_logger)
963n/a wmod.simplefilter("always")
964n/a wmod.warn(text)
966n/a self.assertIs(wmod.showwarning, my_logger)
968n/a self.assertEqual(len(log), 1, log)
969n/a self.assertEqual(log[0].message.args[0], text)
970n/a self.assertEqual(my_log, [])
972n/a def test_record_override_showwarning_inside(self):
973n/a # Issue #28835: It is possible to override warnings.showwarning()
974n/a # in the catch_warnings(record=True) context manager.
975n/a text = "This is a warning"
976n/a wmod = self.module
977n/a my_log = []
979n/a def my_logger(message, category, filename, lineno, file=None, line=None):
980n/a nonlocal my_log
981n/a my_log.append(message)
983n/a with wmod.catch_warnings(module=wmod, record=True) as log:
984n/a wmod.simplefilter("always")
985n/a wmod.showwarning = my_logger
986n/a wmod.warn(text)
988n/a self.assertEqual(len(my_log), 1, my_log)
989n/a self.assertEqual(my_log[0].args[0], text)
990n/a self.assertEqual(log, [])
992n/a def test_check_warnings(self):
993n/a # Explicit tests for the test.support convenience wrapper
994n/a wmod = self.module
995n/a if wmod is not sys.modules['warnings']:
996n/a self.skipTest('module to test is not loaded warnings module')
997n/a with support.check_warnings(quiet=False) as w:
998n/a self.assertEqual(w.warnings, [])
999n/a wmod.simplefilter("always")
1000n/a wmod.warn("foo")
1001n/a self.assertEqual(str(w.message), "foo")
1002n/a wmod.warn("bar")
1003n/a self.assertEqual(str(w.message), "bar")
1004n/a self.assertEqual(str(w.warnings[0].message), "foo")
1005n/a self.assertEqual(str(w.warnings[1].message), "bar")
1006n/a w.reset()
1007n/a self.assertEqual(w.warnings, [])
1009n/a with support.check_warnings():
1010n/a # defaults to quiet=True without argument
1011n/a pass
1012n/a with support.check_warnings(('foo', UserWarning)):
1013n/a wmod.warn("foo")
1015n/a with self.assertRaises(AssertionError):
1016n/a with support.check_warnings(('', RuntimeWarning)):
1017n/a # defaults to quiet=False with argument
1018n/a pass
1019n/a with self.assertRaises(AssertionError):
1020n/a with support.check_warnings(('foo', RuntimeWarning)):
1021n/a wmod.warn("foo")
1023n/aclass CCatchWarningTests(CatchWarningTests, unittest.TestCase):
1024n/a module = c_warnings
1026n/aclass PyCatchWarningTests(CatchWarningTests, unittest.TestCase):
1027n/a module = py_warnings
1030n/aclass EnvironmentVariableTests(BaseTest):
1032n/a def test_single_warning(self):
1033n/a rc, stdout, stderr = assert_python_ok("-c",
1034n/a "import sys; sys.stdout.write(str(sys.warnoptions))",
1035n/a PYTHONWARNINGS="ignore::DeprecationWarning")
1036n/a self.assertEqual(stdout, b"['ignore::DeprecationWarning']")
1038n/a def test_comma_separated_warnings(self):
1039n/a rc, stdout, stderr = assert_python_ok("-c",
1040n/a "import sys; sys.stdout.write(str(sys.warnoptions))",
1041n/a PYTHONWARNINGS="ignore::DeprecationWarning,ignore::UnicodeWarning")
1042n/a self.assertEqual(stdout,
1043n/a b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
1045n/a def test_envvar_and_command_line(self):
1046n/a rc, stdout, stderr = assert_python_ok("-Wignore::UnicodeWarning", "-c",
1047n/a "import sys; sys.stdout.write(str(sys.warnoptions))",
1048n/a PYTHONWARNINGS="ignore::DeprecationWarning")
1049n/a self.assertEqual(stdout,
1050n/a b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
1052n/a def test_conflicting_envvar_and_command_line(self):
1053n/a rc, stdout, stderr = assert_python_failure("-Werror::DeprecationWarning", "-c",
1054n/a "import sys, warnings; sys.stdout.write(str(sys.warnoptions)); "
1055n/a "warnings.warn('Message', DeprecationWarning)",
1056n/a PYTHONWARNINGS="default::DeprecationWarning")
1057n/a self.assertEqual(stdout,
1058n/a b"['default::DeprecationWarning', 'error::DeprecationWarning']")
1059n/a self.assertEqual(stderr.splitlines(),
1060n/a [b"Traceback (most recent call last):",
1061n/a b" File \"<string>\", line 1, in <module>",
1062n/a b"DeprecationWarning: Message"])
1064n/a @unittest.skipUnless(sys.getfilesystemencoding() != 'ascii',
1065n/a 'requires non-ascii filesystemencoding')
1066n/a def test_nonascii(self):
1067n/a rc, stdout, stderr = assert_python_ok("-c",
1068n/a "import sys; sys.stdout.write(str(sys.warnoptions))",
1069n/a PYTHONIOENCODING="utf-8",
1070n/a PYTHONWARNINGS="ignore:DeprecaciónWarning")
1071n/a self.assertEqual(stdout,
1072n/a "['ignore:DeprecaciónWarning']".encode('utf-8'))
1074n/aclass CEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
1075n/a module = c_warnings
1077n/aclass PyEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
1078n/a module = py_warnings
1081n/aclass BootstrapTest(unittest.TestCase):
1082n/a def test_issue_8766(self):
1083n/a # "import encodings" emits a warning whereas the warnings is not loaded
1084n/a # or not completely loaded (warnings imports indirectly encodings by
1085n/a # importing linecache) yet
1086n/a with support.temp_cwd() as cwd, support.temp_cwd('encodings'):
1087n/a # encodings loaded by initfsencoding()
1088n/a assert_python_ok('-c', 'pass', PYTHONPATH=cwd)
1090n/a # Use -W to load warnings module at startup
1091n/a assert_python_ok('-c', 'pass', '-W', 'always', PYTHONPATH=cwd)
1094n/aclass FinalizationTest(unittest.TestCase):
1095n/a @support.requires_type_collecting
1096n/a def test_finalization(self):
1097n/a # Issue #19421: warnings.warn() should not crash
1098n/a # during Python finalization
1099n/a code = """
1100n/aimport warnings
1101n/awarn = warnings.warn
1103n/aclass A:
1104n/a def __del__(self):
1105n/a warn("test")
1108n/a """
1109n/a rc, out, err = assert_python_ok("-c", code)
1110n/a # note: "__main__" filename is not correct, it should be the name
1111n/a # of the script
1112n/a self.assertEqual(err, b'__main__:7: UserWarning: test')
1114n/a def test_late_resource_warning(self):
1115n/a # Issue #21925: Emitting a ResourceWarning late during the Python
1116n/a # shutdown must be logged.
1118n/a expected = b"sys:1: ResourceWarning: unclosed file "
1120n/a # don't import the warnings module
1121n/a # (_warnings will try to import it)
1122n/a code = "f = open(%a)" % __file__
1123n/a rc, out, err = assert_python_ok("-Wd", "-c", code)
1124n/a self.assertTrue(err.startswith(expected), ascii(err))
1126n/a # import the warnings module
1127n/a code = "import warnings; f = open(%a)" % __file__
1128n/a rc, out, err = assert_python_ok("-Wd", "-c", code)
1129n/a self.assertTrue(err.startswith(expected), ascii(err))
1132n/adef setUpModule():
1133n/a py_warnings.onceregistry.clear()
1134n/a c_warnings.onceregistry.clear()
1136n/atearDownModule = setUpModule
1138n/aif __name__ == "__main__":
1139n/a unittest.main()