| 1 |
from contextlib import contextmanager |
| 2 |
import linecache |
| 3 |
import os |
| 4 |
from io import StringIO |
| 5 |
import re |
| 6 |
import sys |
| 7 |
import textwrap |
| 8 |
import unittest |
| 9 |
from test import support |
| 10 |
from test.support import import_helper |
| 11 |
from test.support import os_helper |
| 12 |
from test.support import warnings_helper |
| 13 |
from test.support.script_helper import assert_python_ok, assert_python_failure |
| 14 |
|
| 15 |
from test.test_warnings.data import stacklevel as warning_tests |
| 16 |
|
| 17 |
import warnings as original_warnings |
| 18 |
|
| 19 |
|
| 20 |
py_warnings = import_helper.import_fresh_module('warnings', |
| 21 |
blocked=['_warnings']) |
| 22 |
c_warnings = import_helper.import_fresh_module('warnings', |
| 23 |
fresh=['_warnings']) |
| 24 |
|
| 25 |
Py_DEBUG = hasattr(sys, 'gettotalrefcount') |
| 26 |
|
| 27 |
@contextmanager |
| 28 |
def 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 |
|
| 52 |
class TestWarning(Warning): |
| 53 |
pass |
| 54 |
|
| 55 |
|
| 56 |
class BaseTest: |
| 57 |
|
| 58 |
"""Basic bookkeeping required for testing.""" |
| 59 |
|
| 60 |
def setUp(self): |
| 61 |
self.old_unittest_module = unittest.case.warnings |
| 62 |
|
| 63 |
|
| 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 |
|
| 71 |
|
| 72 |
sys.modules['warnings'] = self.module |
| 73 |
|
| 74 |
|
| 75 |
|
| 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 |
|
| 84 |
class 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 |
|
| 98 |
class CPublicAPITests(PublicAPITests, unittest.TestCase): |
| 99 |
module = c_warnings |
| 100 |
|
| 101 |
class PyPublicAPITests(PublicAPITests, unittest.TestCase): |
| 102 |
module = py_warnings |
| 103 |
|
| 104 |
class 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 |
|
| 241 |
self.module.warn_explicit('msg', UserWarning, "filename", 42, |
| 242 |
module_globals=None) |
| 243 |
self.assertEqual(len(w), 1) |
| 244 |
|
| 245 |
|
| 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 |
|
| 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 |
|
| 279 |
|
| 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 |
|
| 376 |
def test_catchwarnings_with_simplefilter_ignore(self): |
| 377 |
with original_warnings.catch_warnings(module=self.module): |
| 378 |
self.module.resetwarnings() |
| 379 |
self.module.simplefilter("error") |
| 380 |
with self.module.catch_warnings( |
| 381 |
module=self.module, action="ignore" |
| 382 |
): |
| 383 |
self.module.warn("This will be ignored") |
| 384 |
|
| 385 |
def test_catchwarnings_with_simplefilter_error(self): |
| 386 |
with original_warnings.catch_warnings(module=self.module): |
| 387 |
self.module.resetwarnings() |
| 388 |
with self.module.catch_warnings( |
| 389 |
module=self.module, action="error", category=FutureWarning |
| 390 |
): |
| 391 |
with support.captured_stderr() as stderr: |
| 392 |
error_msg = "Other types of warnings are not errors" |
| 393 |
self.module.warn(error_msg) |
| 394 |
self.assertRaises(FutureWarning, |
| 395 |
self.module.warn, FutureWarning("msg")) |
| 396 |
stderr = stderr.getvalue() |
| 397 |
self.assertIn(error_msg, stderr) |
| 398 |
|
| 399 |
class CFilterTests(FilterTests, unittest.TestCase): |
| 400 |
module = c_warnings |
| 401 |
|
| 402 |
class PyFilterTests(FilterTests, unittest.TestCase): |
| 403 |
module = py_warnings |
| 404 |
|
| 405 |
|
| 406 |
class WarnTests(BaseTest): |
| 407 |
|
| 408 |
"""Test warnings.warn() and warnings.warn_explicit().""" |
| 409 |
|
| 410 |
def test_message(self): |
| 411 |
with original_warnings.catch_warnings(record=True, |
| 412 |
module=self.module) as w: |
| 413 |
self.module.simplefilter("once") |
| 414 |
for i in range(4): |
| 415 |
text = 'multi %d' %i |
| 416 |
self.module.warn(text) |
| 417 |
self.assertEqual(str(w[-1].message), text) |
| 418 |
self.assertIs(w[-1].category, UserWarning) |
| 419 |
|
| 420 |
|
| 421 |
def test_warn_nonstandard_types(self): |
| 422 |
|
| 423 |
for ob in (Warning, None, 42): |
| 424 |
with original_warnings.catch_warnings(record=True, |
| 425 |
module=self.module) as w: |
| 426 |
self.module.simplefilter("once") |
| 427 |
self.module.warn(ob) |
| 428 |
|
| 429 |
|
| 430 |
self.assertEqual(str(w[-1].message), str(UserWarning(ob))) |
| 431 |
|
| 432 |
def test_filename(self): |
| 433 |
with warnings_state(self.module): |
| 434 |
with original_warnings.catch_warnings(record=True, |
| 435 |
module=self.module) as w: |
| 436 |
warning_tests.inner("spam1") |
| 437 |
self.assertEqual(os.path.basename(w[-1].filename), |
| 438 |
"stacklevel.py") |
| 439 |
warning_tests.outer("spam2") |
| 440 |
self.assertEqual(os.path.basename(w[-1].filename), |
| 441 |
"stacklevel.py") |
| 442 |
|
| 443 |
def test_stacklevel(self): |
| 444 |
|
| 445 |
|
| 446 |
with warnings_state(self.module): |
| 447 |
with original_warnings.catch_warnings(record=True, |
| 448 |
module=self.module) as w: |
| 449 |
warning_tests.inner("spam3", stacklevel=1) |
| 450 |
self.assertEqual(os.path.basename(w[-1].filename), |
| 451 |
"stacklevel.py") |
| 452 |
warning_tests.outer("spam4", stacklevel=1) |
| 453 |
self.assertEqual(os.path.basename(w[-1].filename), |
| 454 |
"stacklevel.py") |
| 455 |
|
| 456 |
warning_tests.inner("spam5", stacklevel=2) |
| 457 |
self.assertEqual(os.path.basename(w[-1].filename), |
| 458 |
"__init__.py") |
| 459 |
warning_tests.outer("spam6", stacklevel=2) |
| 460 |
self.assertEqual(os.path.basename(w[-1].filename), |
| 461 |
"stacklevel.py") |
| 462 |
warning_tests.outer("spam6.5", stacklevel=3) |
| 463 |
self.assertEqual(os.path.basename(w[-1].filename), |
| 464 |
"__init__.py") |
| 465 |
|
| 466 |
warning_tests.inner("spam7", stacklevel=9999) |
| 467 |
self.assertEqual(os.path.basename(w[-1].filename), |
| 468 |
"sys") |
| 469 |
|
| 470 |
def test_stacklevel_import(self): |
| 471 |
|
| 472 |
import_helper.unload('test.test_warnings.data.import_warning') |
| 473 |
with warnings_state(self.module): |
| 474 |
with original_warnings.catch_warnings(record=True, |
| 475 |
module=self.module) as w: |
| 476 |
self.module.simplefilter('always') |
| 477 |
import test.test_warnings.data.import_warning |
| 478 |
self.assertEqual(len(w), 1) |
| 479 |
self.assertEqual(w[0].filename, __file__) |
| 480 |
|
| 481 |
def test_exec_filename(self): |
| 482 |
filename = "<warnings-test>" |
| 483 |
codeobj = compile(("import warnings\n" |
| 484 |
"warnings.warn('hello', UserWarning)"), |
| 485 |
filename, "exec") |
| 486 |
with original_warnings.catch_warnings(record=True) as w: |
| 487 |
self.module.simplefilter("always", category=UserWarning) |
| 488 |
exec(codeobj) |
| 489 |
self.assertEqual(w[0].filename, filename) |
| 490 |
|
| 491 |
def test_warn_explicit_non_ascii_filename(self): |
| 492 |
with original_warnings.catch_warnings(record=True, |
| 493 |
module=self.module) as w: |
| 494 |
self.module.resetwarnings() |
| 495 |
self.module.filterwarnings("always", category=UserWarning) |
| 496 |
filenames = ["nonascii\xe9\u20ac"] |
| 497 |
if not support.is_emscripten: |
| 498 |
|
| 499 |
|
| 500 |
|
| 501 |
|
| 502 |
filenames.append("surrogate\udc80") |
| 503 |
for filename in filenames: |
| 504 |
try: |
| 505 |
os.fsencode(filename) |
| 506 |
except UnicodeEncodeError: |
| 507 |
continue |
| 508 |
self.module.warn_explicit("text", UserWarning, filename, 1) |
| 509 |
self.assertEqual(w[-1].filename, filename) |
| 510 |
|
| 511 |
def test_warn_explicit_type_errors(self): |
| 512 |
|
| 513 |
|
| 514 |
|
| 515 |
self.assertRaises(TypeError, self.module.warn_explicit, |
| 516 |
None, UserWarning, None, None) |
| 517 |
|
| 518 |
|
| 519 |
self.assertRaises(TypeError, self.module.warn_explicit, |
| 520 |
None, None, None, 1) |
| 521 |
|
| 522 |
self.assertRaises((TypeError, AttributeError), |
| 523 |
self.module.warn_explicit, |
| 524 |
None, Warning, None, 1, registry=42) |
| 525 |
|
| 526 |
def test_bad_str(self): |
| 527 |
|
| 528 |
|
| 529 |
|
| 530 |
class BadStrWarning(Warning): |
| 531 |
"""Warning with a bad format string for __str__.""" |
| 532 |
def __str__(self): |
| 533 |
return ("A bad formatted string %(err)" % |
| 534 |
{"err" : "there is no %(err)s"}) |
| 535 |
|
| 536 |
with self.assertRaises(ValueError): |
| 537 |
self.module.warn(BadStrWarning()) |
| 538 |
|
| 539 |
def test_warning_classes(self): |
| 540 |
class MyWarningClass(Warning): |
| 541 |
pass |
| 542 |
|
| 543 |
class NonWarningSubclass: |
| 544 |
pass |
| 545 |
|
| 546 |
|
| 547 |
with self.assertRaises(TypeError) as cm: |
| 548 |
self.module.warn('bad warning category', '') |
| 549 |
self.assertIn('category must be a Warning subclass, not ', |
| 550 |
str(cm.exception)) |
| 551 |
|
| 552 |
with self.assertRaises(TypeError) as cm: |
| 553 |
self.module.warn('bad warning category', NonWarningSubclass) |
| 554 |
self.assertIn('category must be a Warning subclass, not ', |
| 555 |
str(cm.exception)) |
| 556 |
|
| 557 |
|
| 558 |
with self.assertRaises(TypeError) as cm: |
| 559 |
self.module.warn('bad warning category', MyWarningClass()) |
| 560 |
self.assertIn('category must be a Warning subclass, not ', |
| 561 |
str(cm.exception)) |
| 562 |
|
| 563 |
with original_warnings.catch_warnings(module=self.module): |
| 564 |
self.module.resetwarnings() |
| 565 |
self.module.filterwarnings('default') |
| 566 |
with self.assertWarns(MyWarningClass) as cm: |
| 567 |
self.module.warn('good warning category', MyWarningClass) |
| 568 |
self.assertEqual('good warning category', str(cm.warning)) |
| 569 |
|
| 570 |
with self.assertWarns(UserWarning) as cm: |
| 571 |
self.module.warn('good warning category', None) |
| 572 |
self.assertEqual('good warning category', str(cm.warning)) |
| 573 |
|
| 574 |
with self.assertWarns(MyWarningClass) as cm: |
| 575 |
self.module.warn('good warning category', MyWarningClass) |
| 576 |
self.assertIsInstance(cm.warning, Warning) |
| 577 |
|
| 578 |
class CWarnTests(WarnTests, unittest.TestCase): |
| 579 |
module = c_warnings |
| 580 |
|
| 581 |
|
| 582 |
|
| 583 |
def test_accelerated(self): |
| 584 |
import inspect |
| 585 |
self.assertIsNot(original_warnings, self.module) |
| 586 |
self.assertTrue(inspect.isbuiltin(self.module.warn)) |
| 587 |
|
| 588 |
class PyWarnTests(WarnTests, unittest.TestCase): |
| 589 |
module = py_warnings |
| 590 |
|
| 591 |
|
| 592 |
|
| 593 |
def test_pure_python(self): |
| 594 |
import inspect |
| 595 |
self.assertIsNot(original_warnings, self.module) |
| 596 |
self.assertFalse(inspect.isbuiltin(self.module.warn)) |
| 597 |
|
| 598 |
|
| 599 |
class WCmdLineTests(BaseTest): |
| 600 |
|
| 601 |
def test_improper_input(self): |
| 602 |
|
| 603 |
|
| 604 |
with original_warnings.catch_warnings(module=self.module): |
| 605 |
self.assertRaises(self.module._OptionError, |
| 606 |
self.module._setoption, '1:2:3:4:5:6') |
| 607 |
self.assertRaises(self.module._OptionError, |
| 608 |
self.module._setoption, 'bogus::Warning') |
| 609 |
self.assertRaises(self.module._OptionError, |
| 610 |
self.module._setoption, 'ignore:2::4:-5') |
| 611 |
with self.assertRaises(self.module._OptionError): |
| 612 |
self.module._setoption('ignore::123') |
| 613 |
with self.assertRaises(self.module._OptionError): |
| 614 |
self.module._setoption('ignore::123abc') |
| 615 |
with self.assertRaises(self.module._OptionError): |
| 616 |
self.module._setoption('ignore::===') |
| 617 |
with self.assertRaisesRegex(self.module._OptionError, 'Wärning'): |
| 618 |
self.module._setoption('ignore::Wärning') |
| 619 |
self.module._setoption('error::Warning::0') |
| 620 |
self.assertRaises(UserWarning, self.module.warn, 'convert to error') |
| 621 |
|
| 622 |
def test_import_from_module(self): |
| 623 |
with original_warnings.catch_warnings(module=self.module): |
| 624 |
self.module._setoption('ignore::Warning') |
| 625 |
with self.assertRaises(self.module._OptionError): |
| 626 |
self.module._setoption('ignore::TestWarning') |
| 627 |
with self.assertRaises(self.module._OptionError): |
| 628 |
self.module._setoption('ignore::test.test_warnings.bogus') |
| 629 |
self.module._setoption('error::test.test_warnings.TestWarning') |
| 630 |
with self.assertRaises(TestWarning): |
| 631 |
self.module.warn('test warning', TestWarning) |
| 632 |
|
| 633 |
|
| 634 |
class CWCmdLineTests(WCmdLineTests, unittest.TestCase): |
| 635 |
module = c_warnings |
| 636 |
|
| 637 |
|
| 638 |
class PyWCmdLineTests(WCmdLineTests, unittest.TestCase): |
| 639 |
module = py_warnings |
| 640 |
|
| 641 |
def test_improper_option(self): |
| 642 |
|
| 643 |
|
| 644 |
|
| 645 |
rc, out, err = assert_python_ok("-Wxxx", "-c", "pass") |
| 646 |
self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err) |
| 647 |
|
| 648 |
def test_warnings_bootstrap(self): |
| 649 |
|
| 650 |
|
| 651 |
rc, out, err = assert_python_ok("-Wi", "-c", |
| 652 |
"import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)") |
| 653 |
|
| 654 |
self.assertFalse(out.strip()) |
| 655 |
self.assertNotIn(b'RuntimeWarning', err) |
| 656 |
|
| 657 |
|
| 658 |
class _WarningsTests(BaseTest, unittest.TestCase): |
| 659 |
|
| 660 |
"""Tests specific to the _warnings module.""" |
| 661 |
|
| 662 |
module = c_warnings |
| 663 |
|
| 664 |
def test_filter(self): |
| 665 |
|
| 666 |
with original_warnings.catch_warnings(module=self.module) as w: |
| 667 |
self.module.filterwarnings("error", "", Warning, "", 0) |
| 668 |
self.assertRaises(UserWarning, self.module.warn, |
| 669 |
'convert to error') |
| 670 |
del self.module.filters |
| 671 |
self.assertRaises(UserWarning, self.module.warn, |
| 672 |
'convert to error') |
| 673 |
|
| 674 |
def test_onceregistry(self): |
| 675 |
|
| 676 |
global __warningregistry__ |
| 677 |
message = UserWarning('onceregistry test') |
| 678 |
try: |
| 679 |
original_registry = self.module.onceregistry |
| 680 |
__warningregistry__ = {} |
| 681 |
with original_warnings.catch_warnings(record=True, |
| 682 |
module=self.module) as w: |
| 683 |
self.module.resetwarnings() |
| 684 |
self.module.filterwarnings("once", category=UserWarning) |
| 685 |
self.module.warn_explicit(message, UserWarning, "file", 42) |
| 686 |
self.assertEqual(w[-1].message, message) |
| 687 |
del w[:] |
| 688 |
self.module.warn_explicit(message, UserWarning, "file", 42) |
| 689 |
self.assertEqual(len(w), 0) |
| 690 |
|
| 691 |
self.module.onceregistry = {} |
| 692 |
__warningregistry__ = {} |
| 693 |
self.module.warn('onceregistry test') |
| 694 |
self.assertEqual(w[-1].message.args, message.args) |
| 695 |
|
| 696 |
del w[:] |
| 697 |
del self.module.onceregistry |
| 698 |
__warningregistry__ = {} |
| 699 |
self.module.warn_explicit(message, UserWarning, "file", 42) |
| 700 |
self.assertEqual(len(w), 0) |
| 701 |
finally: |
| 702 |
self.module.onceregistry = original_registry |
| 703 |
|
| 704 |
def test_default_action(self): |
| 705 |
|
| 706 |
message = UserWarning("defaultaction test") |
| 707 |
original = self.module.defaultaction |
| 708 |
try: |
| 709 |
with original_warnings.catch_warnings(record=True, |
| 710 |
module=self.module) as w: |
| 711 |
self.module.resetwarnings() |
| 712 |
registry = {} |
| 713 |
self.module.warn_explicit(message, UserWarning, "<test>", 42, |
| 714 |
registry=registry) |
| 715 |
self.assertEqual(w[-1].message, message) |
| 716 |
self.assertEqual(len(w), 1) |
| 717 |
|
| 718 |
self.assertEqual(len(registry), 2) |
| 719 |
self.assertIn("version", registry) |
| 720 |
del w[:] |
| 721 |
|
| 722 |
del self.module.defaultaction |
| 723 |
__warningregistry__ = {} |
| 724 |
registry = {} |
| 725 |
self.module.warn_explicit(message, UserWarning, "<test>", 43, |
| 726 |
registry=registry) |
| 727 |
self.assertEqual(w[-1].message, message) |
| 728 |
self.assertEqual(len(w), 1) |
| 729 |
self.assertEqual(len(registry), 2) |
| 730 |
del w[:] |
| 731 |
|
| 732 |
self.module.defaultaction = "ignore" |
| 733 |
__warningregistry__ = {} |
| 734 |
registry = {} |
| 735 |
self.module.warn_explicit(message, UserWarning, "<test>", 44, |
| 736 |
registry=registry) |
| 737 |
self.assertEqual(len(w), 0) |
| 738 |
finally: |
| 739 |
self.module.defaultaction = original |
| 740 |
|
| 741 |
def test_showwarning_missing(self): |
| 742 |
|
| 743 |
text = 'del showwarning test' |
| 744 |
with original_warnings.catch_warnings(module=self.module): |
| 745 |
self.module.filterwarnings("always", category=UserWarning) |
| 746 |
del self.module.showwarning |
| 747 |
with support.captured_output('stderr') as stream: |
| 748 |
self.module.warn(text) |
| 749 |
result = stream.getvalue() |
| 750 |
self.assertIn(text, result) |
| 751 |
|
| 752 |
def test_showwarnmsg_missing(self): |
| 753 |
|
| 754 |
text = 'del _showwarnmsg test' |
| 755 |
with original_warnings.catch_warnings(module=self.module): |
| 756 |
self.module.filterwarnings("always", category=UserWarning) |
| 757 |
|
| 758 |
show = self.module._showwarnmsg |
| 759 |
try: |
| 760 |
del self.module._showwarnmsg |
| 761 |
with support.captured_output('stderr') as stream: |
| 762 |
self.module.warn(text) |
| 763 |
result = stream.getvalue() |
| 764 |
finally: |
| 765 |
self.module._showwarnmsg = show |
| 766 |
self.assertIn(text, result) |
| 767 |
|
| 768 |
def test_showwarning_not_callable(self): |
| 769 |
with original_warnings.catch_warnings(module=self.module): |
| 770 |
self.module.filterwarnings("always", category=UserWarning) |
| 771 |
self.module.showwarning = print |
| 772 |
with support.captured_output('stdout'): |
| 773 |
self.module.warn('Warning!') |
| 774 |
self.module.showwarning = 23 |
| 775 |
self.assertRaises(TypeError, self.module.warn, "Warning!") |
| 776 |
|
| 777 |
def test_show_warning_output(self): |
| 778 |
|
| 779 |
text = 'test show_warning' |
| 780 |
with original_warnings.catch_warnings(module=self.module): |
| 781 |
self.module.filterwarnings("always", category=UserWarning) |
| 782 |
del self.module.showwarning |
| 783 |
with support.captured_output('stderr') as stream: |
| 784 |
warning_tests.inner(text) |
| 785 |
result = stream.getvalue() |
| 786 |
self.assertEqual(result.count('\n'), 2, |
| 787 |
"Too many newlines in %r" % result) |
| 788 |
first_line, second_line = result.split('\n', 1) |
| 789 |
expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py' |
| 790 |
first_line_parts = first_line.rsplit(':', 3) |
| 791 |
path, line, warning_class, message = first_line_parts |
| 792 |
line = int(line) |
| 793 |
self.assertEqual(expected_file, path) |
| 794 |
self.assertEqual(warning_class, ' ' + UserWarning.__name__) |
| 795 |
self.assertEqual(message, ' ' + text) |
| 796 |
expected_line = ' ' + linecache.getline(path, line).strip() + '\n' |
| 797 |
assert expected_line |
| 798 |
self.assertEqual(second_line, expected_line) |
| 799 |
|
| 800 |
def test_filename_none(self): |
| 801 |
|
| 802 |
globals_dict = globals() |
| 803 |
oldfile = globals_dict['__file__'] |
| 804 |
try: |
| 805 |
catch = original_warnings.catch_warnings(record=True, |
| 806 |
module=self.module) |
| 807 |
with catch as w: |
| 808 |
self.module.filterwarnings("always", category=UserWarning) |
| 809 |
globals_dict['__file__'] = None |
| 810 |
original_warnings.warn('test', UserWarning) |
| 811 |
self.assertTrue(len(w)) |
| 812 |
finally: |
| 813 |
globals_dict['__file__'] = oldfile |
| 814 |
|
| 815 |
def test_stderr_none(self): |
| 816 |
rc, stdout, stderr = assert_python_ok("-c", |
| 817 |
"import sys; sys.stderr = None; " |
| 818 |
"import warnings; warnings.simplefilter('always'); " |
| 819 |
"warnings.warn('Warning!')") |
| 820 |
self.assertEqual(stdout, b'') |
| 821 |
self.assertNotIn(b'Warning!', stderr) |
| 822 |
self.assertNotIn(b'Error', stderr) |
| 823 |
|
| 824 |
def test_issue31285(self): |
| 825 |
|
| 826 |
|
| 827 |
|
| 828 |
def get_bad_loader(splitlines_ret_val): |
| 829 |
class BadLoader: |
| 830 |
def get_source(self, fullname): |
| 831 |
class BadSource(str): |
| 832 |
def splitlines(self): |
| 833 |
return splitlines_ret_val |
| 834 |
return BadSource('spam') |
| 835 |
return BadLoader() |
| 836 |
|
| 837 |
wmod = self.module |
| 838 |
with original_warnings.catch_warnings(module=wmod): |
| 839 |
wmod.filterwarnings('default', category=UserWarning) |
| 840 |
|
| 841 |
with support.captured_stderr() as stderr: |
| 842 |
wmod.warn_explicit( |
| 843 |
'foo', UserWarning, 'bar', 1, |
| 844 |
module_globals={'__loader__': get_bad_loader(42), |
| 845 |
'__name__': 'foobar'}) |
| 846 |
self.assertIn('UserWarning: foo', stderr.getvalue()) |
| 847 |
|
| 848 |
show = wmod._showwarnmsg |
| 849 |
try: |
| 850 |
del wmod._showwarnmsg |
| 851 |
with support.captured_stderr() as stderr: |
| 852 |
wmod.warn_explicit( |
| 853 |
'eggs', UserWarning, 'bar', 1, |
| 854 |
module_globals={'__loader__': get_bad_loader([42]), |
| 855 |
'__name__': 'foobar'}) |
| 856 |
self.assertIn('UserWarning: eggs', stderr.getvalue()) |
| 857 |
finally: |
| 858 |
wmod._showwarnmsg = show |
| 859 |
|
| 860 |
@support.cpython_only |
| 861 |
def test_issue31411(self): |
| 862 |
|
| 863 |
|
| 864 |
wmod = self.module |
| 865 |
with original_warnings.catch_warnings(module=wmod): |
| 866 |
wmod.filterwarnings('once') |
| 867 |
with support.swap_attr(wmod, 'onceregistry', None): |
| 868 |
with self.assertRaises(TypeError): |
| 869 |
wmod.warn_explicit('foo', Warning, 'bar', 1, registry=None) |
| 870 |
|
| 871 |
@support.cpython_only |
| 872 |
def test_issue31416(self): |
| 873 |
|
| 874 |
|
| 875 |
wmod = self.module |
| 876 |
with original_warnings.catch_warnings(module=wmod): |
| 877 |
wmod.filters = [(None, None, Warning, None, 0)] |
| 878 |
with self.assertRaises(TypeError): |
| 879 |
wmod.warn_explicit('foo', Warning, 'bar', 1) |
| 880 |
|
| 881 |
wmod.filters = [] |
| 882 |
with support.swap_attr(wmod, 'defaultaction', None), \ |
| 883 |
self.assertRaises(TypeError): |
| 884 |
wmod.warn_explicit('foo', Warning, 'bar', 1) |
| 885 |
|
| 886 |
@support.cpython_only |
| 887 |
def test_issue31566(self): |
| 888 |
|
| 889 |
|
| 890 |
with original_warnings.catch_warnings(module=self.module): |
| 891 |
self.module.filterwarnings('error', category=UserWarning) |
| 892 |
with support.swap_item(globals(), '__name__', b'foo'), \ |
| 893 |
support.swap_item(globals(), '__file__', None): |
| 894 |
self.assertRaises(UserWarning, self.module.warn, 'bar') |
| 895 |
|
| 896 |
|
| 897 |
class WarningsDisplayTests(BaseTest): |
| 898 |
|
| 899 |
"""Test the displaying of warnings and the ability to overload functions |
| 900 |
related to displaying warnings.""" |
| 901 |
|
| 902 |
def test_formatwarning(self): |
| 903 |
message = "msg" |
| 904 |
category = Warning |
| 905 |
file_name = os.path.splitext(warning_tests.__file__)[0] + '.py' |
| 906 |
line_num = 3 |
| 907 |
file_line = linecache.getline(file_name, line_num).strip() |
| 908 |
format = "%s:%s: %s: %s\n %s\n" |
| 909 |
expect = format % (file_name, line_num, category.__name__, message, |
| 910 |
file_line) |
| 911 |
self.assertEqual(expect, self.module.formatwarning(message, |
| 912 |
category, file_name, line_num)) |
| 913 |
|
| 914 |
file_line += " for the win!" |
| 915 |
expect = format % (file_name, line_num, category.__name__, message, |
| 916 |
file_line) |
| 917 |
self.assertEqual(expect, self.module.formatwarning(message, |
| 918 |
category, file_name, line_num, file_line)) |
| 919 |
|
| 920 |
def test_showwarning(self): |
| 921 |
file_name = os.path.splitext(warning_tests.__file__)[0] + '.py' |
| 922 |
line_num = 3 |
| 923 |
expected_file_line = linecache.getline(file_name, line_num).strip() |
| 924 |
message = 'msg' |
| 925 |
category = Warning |
| 926 |
file_object = StringIO() |
| 927 |
expect = self.module.formatwarning(message, category, file_name, |
| 928 |
line_num) |
| 929 |
self.module.showwarning(message, category, file_name, line_num, |
| 930 |
file_object) |
| 931 |
self.assertEqual(file_object.getvalue(), expect) |
| 932 |
|
| 933 |
expected_file_line += "for the win!" |
| 934 |
expect = self.module.formatwarning(message, category, file_name, |
| 935 |
line_num, expected_file_line) |
| 936 |
file_object = StringIO() |
| 937 |
self.module.showwarning(message, category, file_name, line_num, |
| 938 |
file_object, expected_file_line) |
| 939 |
self.assertEqual(expect, file_object.getvalue()) |
| 940 |
|
| 941 |
def test_formatwarning_override(self): |
| 942 |
|
| 943 |
|
| 944 |
def myformatwarning(message, category, filename, lineno, text): |
| 945 |
return f'm={message}:c={category}:f={filename}:l={lineno}:t={text}' |
| 946 |
|
| 947 |
file_name = os.path.splitext(warning_tests.__file__)[0] + '.py' |
| 948 |
line_num = 3 |
| 949 |
file_line = linecache.getline(file_name, line_num).strip() |
| 950 |
message = 'msg' |
| 951 |
category = Warning |
| 952 |
file_object = StringIO() |
| 953 |
expected = f'm={message}:c={category}:f={file_name}:l={line_num}' + \ |
| 954 |
f':t={file_line}' |
| 955 |
with support.swap_attr(self.module, 'formatwarning', myformatwarning): |
| 956 |
self.module.showwarning(message, category, file_name, line_num, |
| 957 |
file_object, file_line) |
| 958 |
self.assertEqual(file_object.getvalue(), expected) |
| 959 |
|
| 960 |
|
| 961 |
class CWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase): |
| 962 |
module = c_warnings |
| 963 |
|
| 964 |
class PyWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase): |
| 965 |
module = py_warnings |
| 966 |
|
| 967 |
@support.cpython_only |
| 968 |
def test_tracemalloc(self): |
| 969 |
self.addCleanup(os_helper.unlink, os_helper.TESTFN) |
| 970 |
|
| 971 |
with open(os_helper.TESTFN, 'w', encoding="utf-8") as fp: |
| 972 |
fp.write(textwrap.dedent(""" |
| 973 |
def func(): |
| 974 |
f = open(__file__, "rb") |
| 975 |
# Emit ResourceWarning |
| 976 |
f = None |
| 977 |
|
| 978 |
func() |
| 979 |
""")) |
| 980 |
|
| 981 |
def run(*args): |
| 982 |
res = assert_python_ok(*args, PYTHONIOENCODING='utf-8') |
| 983 |
stderr = res.err.decode('utf-8', 'replace') |
| 984 |
stderr = '\n'.join(stderr.splitlines()) |
| 985 |
|
| 986 |
|
| 987 |
stderr = re.sub('<.*>', '<...>', stderr) |
| 988 |
return stderr |
| 989 |
|
| 990 |
|
| 991 |
filename = os.path.abspath(os_helper.TESTFN) |
| 992 |
stderr = run('-Wd', os_helper.TESTFN) |
| 993 |
expected = textwrap.dedent(f''' |
| 994 |
{filename}:5: ResourceWarning: unclosed file <...> |
| 995 |
f = None |
| 996 |
ResourceWarning: Enable tracemalloc to get the object allocation traceback |
| 997 |
''').strip() |
| 998 |
self.assertEqual(stderr, expected) |
| 999 |
|
| 1000 |
|
| 1001 |
stderr = run('-Wd', '-X', 'tracemalloc=2', os_helper.TESTFN) |
| 1002 |
expected = textwrap.dedent(f''' |
| 1003 |
{filename}:5: ResourceWarning: unclosed file <...> |
| 1004 |
f = None |
| 1005 |
Object allocated at (most recent call last): |
| 1006 |
File "{filename}", lineno 7 |
| 1007 |
func() |
| 1008 |
File "{filename}", lineno 3 |
| 1009 |
f = open(__file__, "rb") |
| 1010 |
''').strip() |
| 1011 |
self.assertEqual(stderr, expected) |
| 1012 |
|
| 1013 |
|
| 1014 |
class CatchWarningTests(BaseTest): |
| 1015 |
|
| 1016 |
"""Test catch_warnings().""" |
| 1017 |
|
| 1018 |
def test_catch_warnings_restore(self): |
| 1019 |
wmod = self.module |
| 1020 |
orig_filters = wmod.filters |
| 1021 |
orig_showwarning = wmod.showwarning |
| 1022 |
|
| 1023 |
with wmod.catch_warnings(module=wmod, record=True): |
| 1024 |
wmod.filters = wmod.showwarning = object() |
| 1025 |
self.assertIs(wmod.filters, orig_filters) |
| 1026 |
self.assertIs(wmod.showwarning, orig_showwarning) |
| 1027 |
|
| 1028 |
with wmod.catch_warnings(module=wmod, record=False): |
| 1029 |
wmod.filters = wmod.showwarning = object() |
| 1030 |
self.assertIs(wmod.filters, orig_filters) |
| 1031 |
self.assertIs(wmod.showwarning, orig_showwarning) |
| 1032 |
|
| 1033 |
def test_catch_warnings_recording(self): |
| 1034 |
wmod = self.module |
| 1035 |
|
| 1036 |
with wmod.catch_warnings(module=wmod, record=True) as w: |
| 1037 |
self.assertEqual(w, []) |
| 1038 |
self.assertIs(type(w), list) |
| 1039 |
wmod.simplefilter("always") |
| 1040 |
wmod.warn("foo") |
| 1041 |
self.assertEqual(str(w[-1].message), "foo") |
| 1042 |
wmod.warn("bar") |
| 1043 |
self.assertEqual(str(w[-1].message), "bar") |
| 1044 |
self.assertEqual(str(w[0].message), "foo") |
| 1045 |
self.assertEqual(str(w[1].message), "bar") |
| 1046 |
del w[:] |
| 1047 |
self.assertEqual(w, []) |
| 1048 |
|
| 1049 |
orig_showwarning = wmod.showwarning |
| 1050 |
with wmod.catch_warnings(module=wmod, record=False) as w: |
| 1051 |
self.assertIsNone(w) |
| 1052 |
self.assertIs(wmod.showwarning, orig_showwarning) |
| 1053 |
|
| 1054 |
def test_catch_warnings_reentry_guard(self): |
| 1055 |
wmod = self.module |
| 1056 |
|
| 1057 |
x = wmod.catch_warnings(module=wmod, record=True) |
| 1058 |
self.assertRaises(RuntimeError, x.__exit__) |
| 1059 |
with x: |
| 1060 |
self.assertRaises(RuntimeError, x.__enter__) |
| 1061 |
|
| 1062 |
x = wmod.catch_warnings(module=wmod, record=False) |
| 1063 |
self.assertRaises(RuntimeError, x.__exit__) |
| 1064 |
with x: |
| 1065 |
self.assertRaises(RuntimeError, x.__enter__) |
| 1066 |
|
| 1067 |
def test_catch_warnings_defaults(self): |
| 1068 |
wmod = self.module |
| 1069 |
orig_filters = wmod.filters |
| 1070 |
orig_showwarning = wmod.showwarning |
| 1071 |
|
| 1072 |
with wmod.catch_warnings(module=wmod) as w: |
| 1073 |
self.assertIsNone(w) |
| 1074 |
self.assertIs(wmod.showwarning, orig_showwarning) |
| 1075 |
self.assertIsNot(wmod.filters, orig_filters) |
| 1076 |
self.assertIs(wmod.filters, orig_filters) |
| 1077 |
if wmod is sys.modules['warnings']: |
| 1078 |
|
| 1079 |
with wmod.catch_warnings() as w: |
| 1080 |
self.assertIsNone(w) |
| 1081 |
self.assertIs(wmod.showwarning, orig_showwarning) |
| 1082 |
self.assertIsNot(wmod.filters, orig_filters) |
| 1083 |
self.assertIs(wmod.filters, orig_filters) |
| 1084 |
|
| 1085 |
def test_record_override_showwarning_before(self): |
| 1086 |
|
| 1087 |
|
| 1088 |
text = "This is a warning" |
| 1089 |
wmod = self.module |
| 1090 |
my_log = [] |
| 1091 |
|
| 1092 |
def my_logger(message, category, filename, lineno, file=None, line=None): |
| 1093 |
nonlocal my_log |
| 1094 |
my_log.append(message) |
| 1095 |
|
| 1096 |
|
| 1097 |
with support.swap_attr(wmod, 'showwarning', my_logger): |
| 1098 |
with wmod.catch_warnings(module=wmod, record=True) as log: |
| 1099 |
self.assertIsNot(wmod.showwarning, my_logger) |
| 1100 |
|
| 1101 |
wmod.simplefilter("always") |
| 1102 |
wmod.warn(text) |
| 1103 |
|
| 1104 |
self.assertIs(wmod.showwarning, my_logger) |
| 1105 |
|
| 1106 |
self.assertEqual(len(log), 1, log) |
| 1107 |
self.assertEqual(log[0].message.args[0], text) |
| 1108 |
self.assertEqual(my_log, []) |
| 1109 |
|
| 1110 |
def test_record_override_showwarning_inside(self): |
| 1111 |
|
| 1112 |
|
| 1113 |
text = "This is a warning" |
| 1114 |
wmod = self.module |
| 1115 |
my_log = [] |
| 1116 |
|
| 1117 |
def my_logger(message, category, filename, lineno, file=None, line=None): |
| 1118 |
nonlocal my_log |
| 1119 |
my_log.append(message) |
| 1120 |
|
| 1121 |
with wmod.catch_warnings(module=wmod, record=True) as log: |
| 1122 |
wmod.simplefilter("always") |
| 1123 |
wmod.showwarning = my_logger |
| 1124 |
wmod.warn(text) |
| 1125 |
|
| 1126 |
self.assertEqual(len(my_log), 1, my_log) |
| 1127 |
self.assertEqual(my_log[0].args[0], text) |
| 1128 |
self.assertEqual(log, []) |
| 1129 |
|
| 1130 |
def test_check_warnings(self): |
| 1131 |
|
| 1132 |
wmod = self.module |
| 1133 |
if wmod is not sys.modules['warnings']: |
| 1134 |
self.skipTest('module to test is not loaded warnings module') |
| 1135 |
with warnings_helper.check_warnings(quiet=False) as w: |
| 1136 |
self.assertEqual(w.warnings, []) |
| 1137 |
wmod.simplefilter("always") |
| 1138 |
wmod.warn("foo") |
| 1139 |
self.assertEqual(str(w.message), "foo") |
| 1140 |
wmod.warn("bar") |
| 1141 |
self.assertEqual(str(w.message), "bar") |
| 1142 |
self.assertEqual(str(w.warnings[0].message), "foo") |
| 1143 |
self.assertEqual(str(w.warnings[1].message), "bar") |
| 1144 |
w.reset() |
| 1145 |
self.assertEqual(w.warnings, []) |
| 1146 |
|
| 1147 |
with warnings_helper.check_warnings(): |
| 1148 |
|
| 1149 |
pass |
| 1150 |
with warnings_helper.check_warnings(('foo', UserWarning)): |
| 1151 |
wmod.warn("foo") |
| 1152 |
|
| 1153 |
with self.assertRaises(AssertionError): |
| 1154 |
with warnings_helper.check_warnings(('', RuntimeWarning)): |
| 1155 |
|
| 1156 |
pass |
| 1157 |
with self.assertRaises(AssertionError): |
| 1158 |
with warnings_helper.check_warnings(('foo', RuntimeWarning)): |
| 1159 |
wmod.warn("foo") |
| 1160 |
|
| 1161 |
class CCatchWarningTests(CatchWarningTests, unittest.TestCase): |
| 1162 |
module = c_warnings |
| 1163 |
|
| 1164 |
class PyCatchWarningTests(CatchWarningTests, unittest.TestCase): |
| 1165 |
module = py_warnings |
| 1166 |
|
| 1167 |
|
| 1168 |
class EnvironmentVariableTests(BaseTest): |
| 1169 |
|
| 1170 |
def test_single_warning(self): |
| 1171 |
rc, stdout, stderr = assert_python_ok("-c", |
| 1172 |
"import sys; sys.stdout.write(str(sys.warnoptions))", |
| 1173 |
PYTHONWARNINGS="ignore::DeprecationWarning", |
| 1174 |
PYTHONDEVMODE="") |
| 1175 |
self.assertEqual(stdout, b"['ignore::DeprecationWarning']") |
| 1176 |
|
| 1177 |
def test_comma_separated_warnings(self): |
| 1178 |
rc, stdout, stderr = assert_python_ok("-c", |
| 1179 |
"import sys; sys.stdout.write(str(sys.warnoptions))", |
| 1180 |
PYTHONWARNINGS="ignore::DeprecationWarning,ignore::UnicodeWarning", |
| 1181 |
PYTHONDEVMODE="") |
| 1182 |
self.assertEqual(stdout, |
| 1183 |
b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']") |
| 1184 |
|
| 1185 |
def test_envvar_and_command_line(self): |
| 1186 |
rc, stdout, stderr = assert_python_ok("-Wignore::UnicodeWarning", "-c", |
| 1187 |
"import sys; sys.stdout.write(str(sys.warnoptions))", |
| 1188 |
PYTHONWARNINGS="ignore::DeprecationWarning", |
| 1189 |
PYTHONDEVMODE="") |
| 1190 |
self.assertEqual(stdout, |
| 1191 |
b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']") |
| 1192 |
|
| 1193 |
def test_conflicting_envvar_and_command_line(self): |
| 1194 |
rc, stdout, stderr = assert_python_failure("-Werror::DeprecationWarning", "-c", |
| 1195 |
"import sys, warnings; sys.stdout.write(str(sys.warnoptions)); " |
| 1196 |
"warnings.warn('Message', DeprecationWarning)", |
| 1197 |
PYTHONWARNINGS="default::DeprecationWarning", |
| 1198 |
PYTHONDEVMODE="") |
| 1199 |
self.assertEqual(stdout, |
| 1200 |
b"['default::DeprecationWarning', 'error::DeprecationWarning']") |
| 1201 |
self.assertEqual(stderr.splitlines(), |
| 1202 |
[b"Traceback (most recent call last):", |
| 1203 |
b" File \"<string>\", line 1, in <module>", |
| 1204 |
b"DeprecationWarning: Message"]) |
| 1205 |
|
| 1206 |
def test_default_filter_configuration(self): |
| 1207 |
pure_python_api = self.module is py_warnings |
| 1208 |
if Py_DEBUG: |
| 1209 |
expected_default_filters = [] |
| 1210 |
else: |
| 1211 |
if pure_python_api: |
| 1212 |
main_module_filter = re.compile("__main__") |
| 1213 |
else: |
| 1214 |
main_module_filter = "__main__" |
| 1215 |
expected_default_filters = [ |
| 1216 |
('default', None, DeprecationWarning, main_module_filter, 0), |
| 1217 |
('ignore', None, DeprecationWarning, None, 0), |
| 1218 |
('ignore', None, PendingDeprecationWarning, None, 0), |
| 1219 |
('ignore', None, ImportWarning, None, 0), |
| 1220 |
('ignore', None, ResourceWarning, None, 0), |
| 1221 |
] |
| 1222 |
expected_output = [str(f).encode() for f in expected_default_filters] |
| 1223 |
|
| 1224 |
if pure_python_api: |
| 1225 |
|
| 1226 |
code = "import sys; sys.modules.pop('warnings', None); sys.modules['_warnings'] = None; " |
| 1227 |
else: |
| 1228 |
code = "" |
| 1229 |
code += "import warnings; [print(f) for f in warnings.filters]" |
| 1230 |
|
| 1231 |
rc, stdout, stderr = assert_python_ok("-c", code, __isolated=True) |
| 1232 |
stdout_lines = [line.strip() for line in stdout.splitlines()] |
| 1233 |
self.maxDiff = None |
| 1234 |
self.assertEqual(stdout_lines, expected_output) |
| 1235 |
|
| 1236 |
|
| 1237 |
@unittest.skipUnless(sys.getfilesystemencoding() != 'ascii', |
| 1238 |
'requires non-ascii filesystemencoding') |
| 1239 |
def test_nonascii(self): |
| 1240 |
PYTHONWARNINGS="ignore:DeprecationWarning" + os_helper.FS_NONASCII |
| 1241 |
rc, stdout, stderr = assert_python_ok("-c", |
| 1242 |
"import sys; sys.stdout.write(str(sys.warnoptions))", |
| 1243 |
PYTHONIOENCODING="utf-8", |
| 1244 |
PYTHONWARNINGS=PYTHONWARNINGS, |
| 1245 |
PYTHONDEVMODE="") |
| 1246 |
self.assertEqual(stdout, str([PYTHONWARNINGS]).encode()) |
| 1247 |
|
| 1248 |
class CEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase): |
| 1249 |
module = c_warnings |
| 1250 |
|
| 1251 |
class PyEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase): |
| 1252 |
module = py_warnings |
| 1253 |
|
| 1254 |
|
| 1255 |
class _DeprecatedTest(BaseTest, unittest.TestCase): |
| 1256 |
|
| 1257 |
"""Test _deprecated().""" |
| 1258 |
|
| 1259 |
module = original_warnings |
| 1260 |
|
| 1261 |
def test_warning(self): |
| 1262 |
version = (3, 11, 0, "final", 0) |
| 1263 |
test = [(4, 12), (4, 11), (4, 0), (3, 12)] |
| 1264 |
for remove in test: |
| 1265 |
msg = rf".*test_warnings.*{remove[0]}\.{remove[1]}" |
| 1266 |
filter = msg, DeprecationWarning |
| 1267 |
with self.subTest(remove=remove): |
| 1268 |
with warnings_helper.check_warnings(filter, quiet=False): |
| 1269 |
self.module._deprecated("test_warnings", remove=remove, |
| 1270 |
_version=version) |
| 1271 |
|
| 1272 |
version = (3, 11, 0, "alpha", 0) |
| 1273 |
msg = r".*test_warnings.*3\.11" |
| 1274 |
with warnings_helper.check_warnings((msg, DeprecationWarning), quiet=False): |
| 1275 |
self.module._deprecated("test_warnings", remove=(3, 11), |
| 1276 |
_version=version) |
| 1277 |
|
| 1278 |
def test_RuntimeError(self): |
| 1279 |
version = (3, 11, 0, "final", 0) |
| 1280 |
test = [(2, 0), (2, 12), (3, 10)] |
| 1281 |
for remove in test: |
| 1282 |
with self.subTest(remove=remove): |
| 1283 |
with self.assertRaises(RuntimeError): |
| 1284 |
self.module._deprecated("test_warnings", remove=remove, |
| 1285 |
_version=version) |
| 1286 |
for level in ["beta", "candidate", "final"]: |
| 1287 |
version = (3, 11, 0, level, 0) |
| 1288 |
with self.subTest(releaselevel=level): |
| 1289 |
with self.assertRaises(RuntimeError): |
| 1290 |
self.module._deprecated("test_warnings", remove=(3, 11), |
| 1291 |
_version=version) |
| 1292 |
|
| 1293 |
|
| 1294 |
class BootstrapTest(unittest.TestCase): |
| 1295 |
|
| 1296 |
def test_issue_8766(self): |
| 1297 |
|
| 1298 |
|
| 1299 |
|
| 1300 |
with os_helper.temp_cwd() as cwd, os_helper.temp_cwd('encodings'): |
| 1301 |
|
| 1302 |
assert_python_ok('-c', 'pass', PYTHONPATH=cwd) |
| 1303 |
|
| 1304 |
|
| 1305 |
assert_python_ok('-c', 'pass', '-W', 'always', PYTHONPATH=cwd) |
| 1306 |
|
| 1307 |
|
| 1308 |
class FinalizationTest(unittest.TestCase): |
| 1309 |
@support.cpython_only |
| 1310 |
def test_finalization(self): |
| 1311 |
|
| 1312 |
|
| 1313 |
code = """ |
| 1314 |
import warnings |
| 1315 |
warn = warnings.warn |
| 1316 |
|
| 1317 |
class A: |
| 1318 |
def __del__(self): |
| 1319 |
warn("test") |
| 1320 |
|
| 1321 |
a=A() |
| 1322 |
""" |
| 1323 |
rc, out, err = assert_python_ok("-c", code) |
| 1324 |
self.assertEqual(err.decode().rstrip(), |
| 1325 |
'<string>:7: UserWarning: test') |
| 1326 |
|
| 1327 |
@support.cpython_only |
| 1328 |
def test_late_resource_warning(self): |
| 1329 |
|
| 1330 |
|
| 1331 |
|
| 1332 |
expected = b"sys:1: ResourceWarning: unclosed file " |
| 1333 |
|
| 1334 |
|
| 1335 |
|
| 1336 |
code = "f = open(%a)" % __file__ |
| 1337 |
rc, out, err = assert_python_ok("-Wd", "-c", code) |
| 1338 |
self.assertTrue(err.startswith(expected), ascii(err)) |
| 1339 |
|
| 1340 |
|
| 1341 |
code = "import warnings; f = open(%a)" % __file__ |
| 1342 |
rc, out, err = assert_python_ok("-Wd", "-c", code) |
| 1343 |
self.assertTrue(err.startswith(expected), ascii(err)) |
| 1344 |
|
| 1345 |
|
| 1346 |
def setUpModule(): |
| 1347 |
py_warnings.onceregistry.clear() |
| 1348 |
c_warnings.onceregistry.clear() |
| 1349 |
|
| 1350 |
tearDownModule = setUpModule |
| 1351 |
|
| 1352 |
if __name__ == "__main__": |
| 1353 |
unittest.main() |