def warn(message, category=None, stacklevel=1): if isinstance(message, Warning): category = message.__class__ if category is None: category = UserWarning try: caller = sys._getframe(stacklevel) except ValueError: globals = sys.__dict__ lineno = 1 globals = caller.f_globals lineno = caller.f_lineno if '__name__' in globals: module = globals['__name__'] else: module = '<string>' filename = globals.get('__file__') if filename: fnl = filename.lower() if fnl.endswith(('.pyc', '.pyo')): filename = filename[:-1] else: if module == '__main__': try: filename = sys.argv[0] except AttributeError: filename = '__main__' if not filename: filename = module registry = globals.setdefault('__warningregistry__', {}) warn_explicit(message, category, filename, lineno, module, registry, globals)
def test_warn_unicode(self): import _warnings, sys old = sys.stderr try: class Grab: def write(self, u): self.data.append(u) sys.stderr = Grab() sys.stderr.data = data = [] _warnings.warn_explicit("9238exbexn8", Warning, "<string>", 1421, module_globals=globals()) assert isinstance(''.join(data), str) _warnings.warn_explicit(u"\u1234\u5678", UserWarning, "<str2>", 831, module_globals=globals()) assert isinstance(''.join(data), unicode) assert ''.join(data).endswith( u'<str2>:831: UserWarning: \u1234\u5678\n') finally: sys.stderr = old
def test_warn_unicode(): if '__pypy__' not in sys.builtin_module_names: # see bc4acc4caa28 pytest.skip("this checks that non-ascii warnings are not silently " "swallowed, like they are with CPython 2.7 (buggily?)") old = sys.stderr, warnings.showwarning try: class Grab: def write(self, u): self.data.append(u) sys.stderr = Grab() sys.stderr.data = data = [] if sys.version_info > (3, 0, 0): # Copy from lib-python/3/warnings.py def orig_showwarning(message, category, filename, lineno, file=None, line=None): msg = warnings.WarningMessage(message, category, filename, lineno, file, line) warnings._showwarnmsg_impl(msg) warnings.showwarning = orig_showwarning _unicode = str else: warnings.showwarning = warnings._show_warning _unicode = unicode # ^^^ disables any catch_warnings() issued by the test runner _warnings.warn_explicit("9238exbexn8", Warning, "<string>", 1421, module_globals=globals()) assert data # the warning was not swallowed assert isinstance(''.join(data), str) _warnings.warn_explicit(u"\u1234\u5678", UserWarning, "<str2>", 831, module_globals=globals()) assert isinstance(''.join(data), _unicode) assert ''.join(data).endswith( u'<str2>:831: UserWarning: \u1234\u5678\n') finally: sys.stderr, warnings.showwarning = old
def warn(message, category = None, stacklevel = 1): if isinstance(message, Warning): category = message.__class__ if category is None: category = UserWarning try: caller = sys._getframe(stacklevel) except ValueError: globals = sys.__dict__ lineno = 1 else: globals = caller.f_globals lineno = caller.f_lineno if '__name__' in globals: module = globals['__name__'] else: module = '<string>' filename = globals.get('__file__') if filename: fnl = filename.lower() if fnl.endswith(('.pyc', '.pyo')): filename = filename[:-1] else: if module == '__main__': try: filename = sys.argv[0] except AttributeError: filename = '__main__' if not filename: filename = module registry = globals.setdefault('__warningregistry__', {}) warn_explicit(message, category, filename, lineno, module, registry, globals)
def test_surrogate_in_filename(): for filename in ("nonascii\xe9\u20ac", "surrogate\udc80"): try: __pypy__.fsencode(filename) except UnicodeEncodeError: continue _warnings.warn_explicit("text", UserWarning, filename, 1)
def test_default_action(): warnings.defaultaction = 'ignore' warnings.resetwarnings() with warnings.catch_warnings(record=True) as w: __warningregistry__ = {} _warnings.warn_explicit("message", UserWarning, "<test>", 44, registry={}) assert len(w) == 0 warnings.defaultaction = 'default'
def test_default_action(self): import warnings, _warnings warnings.defaultaction = 'ignore' warnings.resetwarnings() with warnings.catch_warnings(record=True) as w: __warningregistry__ = {} _warnings.warn_explicit("message", UserWarning, "<test>", 44, registry={}) assert len(w) == 0 warnings.defaultaction = 'default'
def test_warn_explicit(): _warnings.warn_explicit("some message", DeprecationWarning, "<string>", 1, module_globals=globals()) _warnings.warn_explicit("some message", Warning, "<string>", 1, module_globals=globals())
def warn(message, category=None, stacklevel=1, source=None): """Issue a warning, or maybe ignore it or raise an exception.""" # Check if message is already a Warning object if isinstance(message, Warning): category = message.__class__ # Check category argument if category is None: category = UserWarning if not (isinstance(category, type) and issubclass(category, Warning)): raise TypeError( "category must be a Warning subclass, " "not '{:s}'".format(type(category).__name__) ) # Get context information try: if stacklevel <= 1 or _is_internal_frame(sys._getframe(1)): # If frame is too small to care or if the warning originated in # internal code, then do not try to hide any frames. frame = sys._getframe(stacklevel) else: frame = sys._getframe(1) # Look for one frame less since the above line starts us off. for x in range(stacklevel - 1): frame = _next_external_frame(frame) if frame is None: raise ValueError except ValueError: globals = sys.__dict__ lineno = 1 else: globals = frame.f_globals lineno = frame.f_lineno if "__name__" in globals: module = globals["__name__"] else: module = "<string>" filename = globals.get("__file__") if filename: fnl = filename.lower() if fnl.endswith(".pyc"): filename = filename[:-1] else: if module == "__main__": try: filename = sys.argv[0] except AttributeError: # embedded interpreters don't have sys.argv, see bug #839151 filename = "__main__" if not filename: filename = module registry = globals.setdefault("__warningregistry__", {}) warn_explicit( message, category, filename, lineno, module, registry, globals, source )
def test_ignore(): warnings.resetwarnings() with warnings.catch_warnings(record=True) as w: __warningregistry__ = {} warnings.filterwarnings("ignore", category=UserWarning) _warnings.warn_explicit("message", UserWarning, "<test>", 44, registry=__warningregistry__) assert len(w) == 0 assert len(__warningregistry__) == 0
def warn(message, category=None, stacklevel=1, source=None): """Issue a warning, or maybe ignore it or raise an exception.""" # Check if message is already a Warning object if isinstance(message, Warning): category = message.__class__ # Check category argument if category is None: category = UserWarning if not (isinstance(category, type) and issubclass(category, Warning)): raise TypeError("category must be a Warning subclass, " "not '{:s}'".format(type(category).__name__)) # Get context information try: if stacklevel <= 1 or _is_internal_frame(sys._getframe(1)): # If frame is too small to care or if the warning originated in # internal code, then do not try to hide any frames. frame = sys._getframe(stacklevel) else: frame = sys._getframe(1) # Look for one frame less since the above line starts us off. for x in range(stacklevel-1): frame = _next_external_frame(frame) if frame is None: raise ValueError except ValueError: globals = sys.__dict__ lineno = 1 else: globals = frame.f_globals lineno = frame.f_lineno if '__name__' in globals: module = globals['__name__'] else: module = "<string>" filename = globals.get('__file__') if filename: fnl = filename.lower() if fnl.endswith(".pyc"): filename = filename[:-1] else: if module == "__main__": try: filename = sys.argv[0] except AttributeError: # embedded interpreters don't have sys.argv, see bug #839151 filename = '__main__' if not filename: filename = module registry = globals.setdefault("__warningregistry__", {}) warn_explicit(message, category, filename, lineno, module, registry, globals, source)
def test_issue31285(): def get_bad_loader(splitlines_ret_val): class BadLoader: def get_source(self, fullname): class BadSource(str): def splitlines(self): return splitlines_ret_val return BadSource('spam') return BadLoader() # does not raise: _warnings.warn_explicit( 'eggs', UserWarning, 'bar', 1, module_globals={'__loader__': get_bad_loader(42), '__name__': 'foobar'})
def warn(message, category=None, stacklevel=1): """Issue a warning, or maybe ignore it or raise an exception.""" # Check if message is already a Warning object if isinstance(message, Warning): category = message.__class__ # Check category argument if category is None: category = UserWarning assert issubclass(category, Warning) # Get context information try: # Pyston change: manually skip the call to _getframe. # A ValueError() is supposed to specify that the "depth" argument is greater # than the stack level, so it doesn't seem appropriate for us to throw as # a signal that it's unimplemented. raise ValueError() caller = sys._getframe(stacklevel) except ValueError: globals = sys.__dict__ lineno = 1 else: globals = caller.f_globals lineno = caller.f_lineno if '__name__' in globals: module = globals['__name__'] else: module = "<string>" filename = globals.get('__file__') if filename: fnl = filename.lower() if fnl.endswith((".pyc", ".pyo")): filename = filename[:-1] else: if module == "__main__": try: filename = sys.argv[0] except AttributeError: # embedded interpreters don't have sys.argv, see bug #839151 filename = '__main__' if not filename: filename = module registry = globals.setdefault("__warningregistry__", {}) warn_explicit(message, category, filename, lineno, module, registry, globals)
def warn(message, category=None, stacklevel=1, source=None): """Issue a warning, or maybe ignore it or raise an exception.""" if isinstance(message, Warning): category = message.__class__ if category is None: category = UserWarning if not (isinstance(category, type) and issubclass(category, Warning)): raise TypeError( "category must be a Warning subclass, not '{:s}'".format( type(category).__name__)) try: if stacklevel <= 1 or _is_internal_frame(sys._getframe(1)): frame = sys._getframe(stacklevel) else: frame = sys._getframe(1) for x in range(stacklevel - 1): frame = _next_external_frame(frame) if frame is None: raise ValueError except ValueError: globals = sys.__dict__ lineno = 1 else: globals = frame.f_globals lineno = frame.f_lineno if '__name__' in globals: module = globals['__name__'] else: module = '<string>' filename = globals.get('__file__') if filename: fnl = filename.lower() if fnl.endswith('.pyc'): filename = filename[:-1] else: if module == '__main__': try: filename = sys.argv[0] except AttributeError: filename = '__main__' if not filename: filename = module registry = globals.setdefault('__warningregistry__', {}) warn_explicit(message, category, filename, lineno, module, registry, globals, source)
def warn(message, category=None, stacklevel=1): """Issue a warning, or maybe ignore it or raise an exception.""" # Check if message is already a Warning object if isinstance(message, Warning): category = message.__class__ # Check category argument if category is None: category = UserWarning assert issubclass(category, Warning) # Get context information try: caller = sys._getframe(stacklevel) except ValueError: globals = sys.__dict__ lineno = 1 caller=None #fixme brython error else: #if caller is not None: globals = caller.f_globals lineno = caller.f_lineno if '__name__' in globals: module = globals['__name__'] else: module = "<string>" filename = globals.get('__file__') if filename: fnl = filename.lower() if fnl.endswith((".pyc", ".pyo")): filename = filename[:-1] else: if module == "__main__": try: filename = sys.argv[0] except AttributeError: # embedded interpreters don't have sys.argv, see bug #839151 filename = '__main__' if not filename: filename = module registry = globals.setdefault("__warningregistry__", {}) warn_explicit(message, category, filename, lineno, module, registry, globals)
def warn(message, category=None, stacklevel=1, source=None): """Issue a warning, or maybe ignore it or raise an exception.""" # Check if message is already a Warning object if isinstance(message, Warning): category = message.__class__ # Check category argument if category is None: category = UserWarning if not (isinstance(category, type) and issubclass(category, Warning)): raise TypeError("category must be a Warning subclass, " "not '{:s}'".format(type(category).__name__)) # Get context information try: if stacklevel <= 1 or _is_internal_frame(sys._getframe(1)): # If frame is too small to care or if the warning originated in # internal code, then do not try to hide any frames. frame = sys._getframe(stacklevel) else: frame = sys._getframe(1) # Look for one frame less since the above line starts us off. for x in range(stacklevel - 1): frame = _next_external_frame(frame) if frame is None: raise ValueError except ValueError: globals = sys.__dict__ filename = "sys" lineno = 1 else: globals = frame.f_globals filename = frame.f_code.co_filename lineno = frame.f_lineno if '__name__' in globals: module = globals['__name__'] else: module = "<string>" registry = globals.setdefault("__warningregistry__", {}) warn_explicit(message, category, filename, lineno, module, registry, globals, source)
def warn(message, category=None, stacklevel=1): """Issue a warning, or maybe ignore it or raise an exception.""" if isinstance(message, Warning): category = message.__class__ if category is None: category = UserWarning if not issubclass(category, Warning): raise AssertionError try: caller = sys._getframe(stacklevel) except ValueError: globals = sys.__dict__ lineno = 1 else: globals = caller.f_globals lineno = caller.f_lineno if '__name__' in globals: module = globals['__name__'] else: module = '<string>' filename = globals.get('__file__') if filename: fnl = filename.lower() filename = fnl.endswith(('.pyc', '.pyo')) and filename[:-1] else: if module == '__main__': try: filename = sys.argv[0] except AttributeError: filename = '__main__' if not filename: filename = module registry = globals.setdefault('__warningregistry__', {}) warn_explicit(message, category, filename, lineno, module, registry, globals) return
def test_sanity(self): global EXPECTED try: with stderr_trapper() as output: # generate test output _warnings.warn("Warning Message!") expect(UserWarning, "Warning Message!") for warn_type in WARN_TYPES: _warnings.warn(warn_type("Type-overriding message!"), UnicodeWarning) expect(warn_type, "Type-overriding message!") _warnings.warn("Another Warning Message!", warn_type) expect(warn_type, "Another Warning Message!") _warnings.warn_explicit("Explicit Warning!", warn_type, "nonexistent_file.py", 12) expect(warn_type, "Explicit Warning!") _warnings.warn_explicit("Explicit Warning!", warn_type, "test_python26.py", 34) expect(warn_type, "Explicit Warning!") _warnings.warn_explicit("Explicit Warning!", warn_type, "nonexistent_file.py", 56, "module.py") expect(warn_type, "Explicit Warning!") _warnings.warn_explicit("Explicit Warning!", warn_type, "test_python26.py", 78, "module.py") expect(warn_type, "Explicit Warning!") temp_messages = output.messages #No point in going further if the number of lines is not what we expect nlines = len([x for x in temp_messages if not x.startswith(" ")]) self.assertEqual(nlines, len(EXPECTED)) # match lines for line in temp_messages: if line.startswith(" "): continue temp = EXPECTED.pop(0).rstrip() self.assertTrue(line.endswith(temp), str(line) + " does not end with " + temp) finally: # remove generated files cleanup()
fnl = filename.lower() if fnl.endswith(".pyc"): filename = filename[:-1] else: if module == "__main__": try: filename = sys.argv[0] except AttributeError: # embedded interpreters don't have sys.argv, see bug #839151 filename = '__main__' if not filename: filename = module ======= >>>>>>> 716b15a33aed978ded8a6bde17855cb6c6aa7f78 registry = globals.setdefault("__warningregistry__", {}) warn_explicit(message, category, filename, lineno, module, registry, globals, source) def warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None, source=None): lineno = int(lineno) if module is None: module = filename or "<unknown>" if module[-3:].lower() == ".py": module = module[:-3] # XXX What about leading pathname? if registry is None: registry = {} if registry.get('version', 0) != _filters_version: registry.clear() registry['version'] = _filters_version if isinstance(message, Warning):
def test_warn_explicit(self): import _warnings _warnings.warn_explicit("some message", DeprecationWarning, "<string>", 1, module_globals=globals()) _warnings.warn_explicit("some message", Warning, "<string>", 1, module_globals=globals())