[Jython-checkins] jython: Update of warnings and pure python _warnings. Fixes test_warnings.
frank.wierzbicki
jython-checkins at python.org
Tue Jun 12 19:54:34 CEST 2012
http://hg.python.org/jython/rev/02eb02a00774
changeset: 6700:02eb02a00774
user: Miki Tebeka <miki.tebeka at gmail.com>
date: Tue Jun 12 10:54:26 2012 -0700
summary:
Update of warnings and pure python _warnings. Fixes test_warnings.
files:
Lib/_warnings.py | 41 ++++++++++---
Lib/test/test_warnings.py | 79 ++++++++++++--------------
Lib/warnings.py | 45 +++++++++++---
3 files changed, 102 insertions(+), 63 deletions(-)
diff --git a/Lib/_warnings.py b/Lib/_warnings.py
--- a/Lib/_warnings.py
+++ b/Lib/_warnings.py
@@ -13,10 +13,8 @@
__all__ = ["filters", "default_action", "once_registry", "warn",
"warn_explicit"]
-once_registry = {}
-onceregistry = once_registry
-default_action = "default"
-defaultaction = default_action
+onceregistry = once_registry = {}
+defaultaction = default_action = "default"
def warnpy3k(message, category=None, stacklevel=1):
"""Issue a deprecation warning for Python 3.x related changes.
@@ -177,6 +175,27 @@
raise _OptionError("invalid warning category: %r" % (category,))
return cat
+class SysGlobals:
+ '''sys.__dict__ values are reflectedfields, so we use this.'''
+ def __getitem__(self, key):
+ try:
+ return getattr(sys, key)
+ except AttributeError:
+ raise KeyError(key)
+
+ def get(self, key, default=None):
+ if key in self:
+ return self[key]
+ return default
+
+ def setdefault(self, key, default=None):
+ if key not in self:
+ sys.__dict__[key] = default
+ return self[key]
+
+ def __contains__(self, key):
+ return key in sys.__dict__
+
# Code typically replaced by _warnings
def warn(message, category=None, stacklevel=1):
"""Issue a warning, or maybe ignore it or raise an exception."""
@@ -191,7 +210,7 @@
try:
caller = sys._getframe(stacklevel)
except ValueError:
- globals = sys.__dict__
+ globals = SysGlobals()
lineno = 1
else:
globals = caller.f_globals
@@ -262,11 +281,12 @@
raise message
# Other actions
if action == "once":
+ _onceregistry = globals().get('onceregistry', once_registry)
registry[key] = 1
oncekey = (text, category)
- if onceregistry.get(oncekey):
+ if _onceregistry.get(oncekey):
return
- onceregistry[oncekey] = 1
+ _onceregistry[oncekey] = 1
elif action == "always":
pass
elif action == "module":
@@ -283,7 +303,8 @@
"Unrecognized action (%r) in warnings.filters:\n %s" %
(action, item))
# Print message and context
- showwarning(message, category, filename, lineno)
+ fn = globals().get('showwarning', _show_warning)
+ fn(message, category, filename. lineno)
class WarningMessage(object):
@@ -349,7 +370,7 @@
raise RuntimeError("Cannot enter %r twice" % self)
self._entered = True
self._filters = self._module.filters
- self._module.filters = self._filters[:]
+ self._module.filters = self._module._filters = self._filters[:]
self._showwarning = self._module.showwarning
if self._record:
log = []
@@ -363,5 +384,5 @@
def __exit__(self, *exc_info):
if not self._entered:
raise RuntimeError("Cannot exit %r without entering first" % self)
- self._module.filters = self._filters
+ self._module.filters = self._module._filters = self._filters
self._module.showwarning = self._showwarning
diff --git a/Lib/test/test_warnings.py b/Lib/test/test_warnings.py
--- a/Lib/test/test_warnings.py
+++ b/Lib/test/test_warnings.py
@@ -1,5 +1,4 @@
from contextlib import contextmanager
-import marshal
import linecache
import os
import StringIO
@@ -11,14 +10,14 @@
import warning_tests
-warning_tests_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
-warning_tests_file = warning_tests_file.replace('$py', '') # Jython
-
import warnings as original_warnings
py_warnings = test_support.import_fresh_module('warnings', blocked=['_warnings'])
c_warnings = test_support.import_fresh_module('warnings', fresh=['_warnings'])
+warning_tests_py = os.path.splitext(warning_tests.__file__)[0]
+warning_tests_py = warning_tests_py.replace('$py', '') + '.py'
+
@contextmanager
def warnings_state(module):
"""Use a specific warnings implementation in warning_tests."""
@@ -359,7 +358,9 @@
# test_support.import_fresh_module utility function
def test_accelerated(self):
self.assertFalse(original_warnings is self.module)
- self.assertFalse(hasattr(self.module.warn, 'func_code'))
+ # Currently in Jython, _warnings is a Python module
+ if not test_support.is_jython:
+ self.assertFalse(hasattr(self.module.warn, 'func_code'))
class PyWarnTests(BaseTest, WarnTests):
module = py_warnings
@@ -523,7 +524,7 @@
self.assertEqual(result.count('\n'), 2,
"Too many newlines in %r" % result)
first_line, second_line = result.split('\n', 1)
- expected_file = warning_tests_file
+ expected_file = warning_tests_py
first_line_parts = first_line.rsplit(':', 3)
path, line, warning_class, message = first_line_parts
line = int(line)
@@ -555,14 +556,15 @@
def test_formatwarning(self):
message = "msg"
category = Warning
- file_name = warning_tests_file
+ file_name = warning_tests_py
line_num = 3
file_line = linecache.getline(file_name, line_num).strip()
format = "%s:%s: %s: %s\n %s\n"
expect = format % (file_name, line_num, category.__name__, message,
file_line)
- self.assertEqual(expect, self.module.formatwarning(message,
- category, file_name, line_num))
+ result = self.module.formatwarning(
+ message, category, file_name, line_num)
+ self.assertEqual(expect, result)
# Test the 'line' argument.
file_line += " for the win!"
expect = format % (file_name, line_num, category.__name__, message,
@@ -571,7 +573,7 @@
category, file_name, line_num, file_line))
def test_showwarning(self):
- file_name = warning_tests_file
+ file_name = warning_tests_py
line_num = 3
expected_file_line = linecache.getline(file_name, line_num).strip()
message = 'msg'
@@ -710,42 +712,35 @@
class EnvironmentVariableTests(BaseTest):
- def check_child(self, env, cmdline, expected):
+ def test_single_warning(self):
newenv = os.environ.copy()
- newenv["PYTHONWARNINGS"] = env
-
- cmd = [sys.executable]
- if cmdline:
- cmd.extend(["-W", cmdline])
-
- cmd.extend([
- "-c",
- "import sys, marshal; marshal.dump(sys.warnoptions, sys.stdout)",
- ])
-
- p = subprocess.Popen(cmd, stdout=subprocess.PIPE, env=newenv)
+ newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
+ p = subprocess.Popen([sys.executable,
+ "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
+ stdout=subprocess.PIPE, env=newenv)
+ self.assertEqual(p.communicate()[0], "['ignore::DeprecationWarning']")
self.assertEqual(p.wait(), 0)
- child_opts = marshal.load(p.stdout)
- self.assertEqual(set(child_opts), set(expected))
-
- def test_single_warning(self):
- self.check_child(
- "ignore::DeprecationWarning",
- None,
- ["ignore::DeprecationWarning"])
def test_comma_separated_warnings(self):
- self.check_child(
- "ignore::DeprecationWarning,ignore::UnicodeWarning",
- None,
- ['ignore::DeprecationWarning', 'ignore::UnicodeWarning'])
+ newenv = os.environ.copy()
+ newenv["PYTHONWARNINGS"] = ("ignore::DeprecationWarning,"
+ "ignore::UnicodeWarning")
+ p = subprocess.Popen([sys.executable,
+ "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
+ stdout=subprocess.PIPE, env=newenv)
+ self.assertEqual(p.communicate()[0],
+ "['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
+ self.assertEqual(p.wait(), 0)
def test_envvar_and_command_line(self):
- self.check_child(
- "ignore::DeprecationWarning",
- "ignore::UnicodeWarning",
- ['ignore::UnicodeWarning', 'ignore::DeprecationWarning'])
-
+ newenv = os.environ.copy()
+ newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
+ p = subprocess.Popen([sys.executable, "-W" "ignore::UnicodeWarning",
+ "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
+ stdout=subprocess.PIPE, env=newenv)
+ self.assertEqual(p.communicate()[0],
+ "['ignore::UnicodeWarning', 'ignore::DeprecationWarning']")
+ self.assertEqual(p.wait(), 0)
class CEnvironmentVariableTests(EnvironmentVariableTests):
module = c_warnings
@@ -770,8 +765,8 @@
CCatchWarningTests,
PyCatchWarningTests,
CEnvironmentVariableTests,
- PyEnvironmentVariableTests
- )
+ PyEnvironmentVariableTests,
+ )
if __name__ == "__main__":
diff --git a/Lib/warnings.py b/Lib/warnings.py
--- a/Lib/warnings.py
+++ b/Lib/warnings.py
@@ -169,6 +169,26 @@
raise _OptionError("invalid warning category: %r" % (category,))
return cat
+class SysGlobals:
+ '''sys.__dict__ values are reflectedfields, so we use this.'''
+ def __getitem__(self, key):
+ try:
+ return getattr(sys, key)
+ except AttributeError:
+ raise KeyError(key)
+
+ def get(self, key, default=None):
+ if key in self:
+ return self[key]
+ return default
+
+ def setdefault(self, key, default=None):
+ if key not in self:
+ sys.__dict__[key] = default
+ return self[key]
+
+ def __contains__(self, key):
+ return key in sys.__dict__
# Code typically replaced by _warnings
def warn(message, category=None, stacklevel=1):
@@ -184,7 +204,7 @@
try:
caller = sys._getframe(stacklevel)
except ValueError:
- globals = sys.__dict__
+ globals = SysGlobals()
lineno = 1
else:
globals = caller.f_globals
@@ -233,7 +253,7 @@
if registry.get(key):
return
# Search the filters
- for item in filters:
+ for item in globals().get('filters', _filters):
action, msg, cat, mod, ln = item
if ((msg is None or msg.match(text)) and
issubclass(category, cat) and
@@ -241,7 +261,7 @@
(ln == 0 or lineno == ln)):
break
else:
- action = defaultaction
+ action = globals().get('defaultaction', default_action)
# Early exit actions
if action == "ignore":
registry[key] = 1
@@ -255,11 +275,12 @@
raise message
# Other actions
if action == "once":
+ _onceregistry = globals().get('onceregistry', once_registry)
registry[key] = 1
oncekey = (text, category)
- if onceregistry.get(oncekey):
+ if _onceregistry.get(oncekey):
return
- onceregistry[oncekey] = 1
+ _onceregistry[oncekey] = 1
elif action == "always":
pass
elif action == "module":
@@ -276,7 +297,8 @@
"Unrecognized action (%r) in warnings.filters:\n %s" %
(action, item))
# Print message and context
- showwarning(message, category, filename, lineno)
+ fn = globals().get('showwarning', _show_warning)
+ fn(message, category, filename, lineno)
class WarningMessage(object):
@@ -342,7 +364,7 @@
raise RuntimeError("Cannot enter %r twice" % self)
self._entered = True
self._filters = self._module.filters
- self._module.filters = self._filters[:]
+ self._module.filters = self._module._filters = self._filters[:]
self._showwarning = self._module.showwarning
if self._record:
log = []
@@ -356,7 +378,7 @@
def __exit__(self, *exc_info):
if not self._entered:
raise RuntimeError("Cannot exit %r without entering first" % self)
- self._module.filters = self._filters
+ self._module.filters = self._module._filters = self._filters
self._module.showwarning = self._showwarning
@@ -375,10 +397,11 @@
defaultaction = default_action
onceregistry = once_registry
_warnings_defaults = True
+ _filters = filters
except ImportError:
- filters = []
- defaultaction = "default"
- onceregistry = {}
+ filters = _filters = []
+ defaultaction = default_action = "default"
+ onceregistry = once_registry = {}
# Module initialization
--
Repository URL: http://hg.python.org/jython
More information about the Jython-checkins
mailing list