The :mod:`site` module now reports exceptions occurring
when the :mod:`sitecustomize` module is imported, and will no longer
- catch and swallow the :exc:`KeyboardError` exception. (Fixed by
+ catch and swallow the :exc:`KeyboardInterrupt` exception. (Fixed by
Victor Stinner; :issue:`3137`.)
* The :mod:`socket` module's :class:`SSL` objects now support the
if sys.platform in ('dos','win32','win16','os2'):
# XXX Others too ?
return default
- target = _follow_symlinks(target)
+ target = _follow_symlinks(target).replace('"', '\\"')
try:
f = os.popen('file "%s" 2> %s' % (target, DEV_NULL))
except (AttributeError,os.error):
from test import support
import os
import sys
-import warnings
class NoAll(RuntimeError):
def check_all(self, modname):
names = {}
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", ".* (module|package)",
- DeprecationWarning)
+ with support.check_warnings((".* (module|package)",
+ DeprecationWarning), quiet=True):
try:
exec("import %s" % modname, names)
except:
import textwrap
import tempfile
import unittest
-import warnings
import argparse
from io import StringIO
self.assertTrue(hasattr(argparse, name))
def test_main():
- with warnings.catch_warnings():
- # silence warnings about version argument - these are expected
- warnings.filterwarnings(
- action='ignore',
- message='The "version" argument to ArgumentParser is deprecated.',
- category=DeprecationWarning)
- warnings.filterwarnings(
- action='ignore',
- message='The format_version method is deprecated',
- category=DeprecationWarning)
- warnings.filterwarnings(
- action='ignore',
- message='The print_version method is deprecated',
- category=DeprecationWarning)
-
+ # silence warnings about version argument - these are expected
+ with support.check_warnings(
+ ('The "version" argument to ArgumentParser is deprecated.',
+ DeprecationWarning),
+ ('The (format|print)_version method is deprecated',
+ DeprecationWarning)):
support.run_unittest(__name__)
# Remove global references to avoid looking like we have refleaks.
RFile.seen = {}
-import unittest, os
+import unittest
from test import support
from random import random
finally:
if (fo is not None) and (not fo.closed):
fo.close()
- try:
- os.remove(support.TESTFN)
- except (OSError, IOError):
- pass
+ support.unlink(support.TESTFN)
def test_getnewargs(self):
self.assertEqual((1+2j).__getnewargs__(), (1.0, 2.0))
"""Unit tests for contextlib.py, and other context managers."""
-
-import os
import sys
import tempfile
import unittest
from contextlib import * # Tests __all__
from test import support
+
class ContextManagerTestCase(unittest.TestCase):
def test_contextmanager_plain(self):
yield 42
finally:
state.append(999)
- try:
+ with self.assertRaises(ZeroDivisionError):
with woohoo() as x:
self.assertEqual(state, [1])
self.assertEqual(x, 42)
state.append(x)
raise ZeroDivisionError()
- except ZeroDivisionError:
- pass
- else:
- self.fail("Expected ZeroDivisionError")
self.assertEqual(state, [1, 42, 999])
def test_contextmanager_no_reraise(self):
state.append(1)
x = C()
self.assertEqual(state, [])
- try:
+ with self.assertRaises(ZeroDivisionError):
with closing(x) as y:
self.assertEqual(x, y)
- 1/0
- except ZeroDivisionError:
- self.assertEqual(state, [1])
- else:
- self.fail("Didn't raise ZeroDivisionError")
+ 1 / 0
+ self.assertEqual(state, [1])
class FileContextTestCase(unittest.TestCase):
f.write("Booh\n")
self.assertTrue(f.closed)
f = None
- try:
+ with self.assertRaises(ZeroDivisionError):
with open(tfn, "r") as f:
self.assertFalse(f.closed)
self.assertEqual(f.read(), "Booh\n")
- 1/0
- except ZeroDivisionError:
- self.assertTrue(f.closed)
- else:
- self.fail("Didn't raise ZeroDivisionError")
+ 1 / 0
+ self.assertTrue(f.closed)
finally:
- try:
- os.remove(tfn)
- except os.error:
- pass
+ support.unlink(tfn)
class LockContextTestCase(unittest.TestCase):
with lock:
self.assertTrue(locked())
self.assertFalse(locked())
- try:
+ with self.assertRaises(ZeroDivisionError):
with lock:
self.assertTrue(locked())
- 1/0
- except ZeroDivisionError:
- self.assertFalse(locked())
- else:
- self.fail("Didn't raise ZeroDivisionError")
+ 1 / 0
+ self.assertFalse(locked())
def testWithLock(self):
lock = threading.Lock()
import sys
import types
import unittest
-import warnings
from copy import deepcopy
from test import support
from test import support
import doctest
-import warnings
# NOTE: There are some additional tests relating to interaction with
# zipimport in the test_zipimport_support test module.
from test.support import run_unittest, check_syntax_error, check_warnings
import unittest
-
import warnings
def test_main():
- run_unittest(GlobalTests)
+ with warnings.catch_warnings():
+ warnings.filterwarnings("error", module="<test string>")
+ run_unittest(GlobalTests)
if __name__ == "__main__":
test_main()
with warnings.catch_warnings():
warnings.simplefilter('error', RuntimeWarning)
- try:
+ with self.assertRaises(RuntimeWarning):
hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash)
- except RuntimeWarning:
- pass
- else:
self.fail('Expected warning about missing block_size')
MockCrazyHash.block_size = 1
- try:
+ with self.assertRaises(RuntimeWarning):
hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash)
- except RuntimeWarning:
- pass
- else:
self.fail('Expected warning about small block_size')
import threading
import random
import unittest
-import warnings
import weakref
import abc
from itertools import cycle, count
class NetworkTestCase(unittest.TestCase):
def testPasswordProtectedSite(self):
- if not support.is_resource_enabled('network'):
- return
- # whole site is password-protected.
+ support.requires('network')
+ # XXX it depends on an external resource which could be unavailable
url = 'http://mueblesmoraleda.com'
parser = urllib.robotparser.RobotFileParser()
parser.set_url(url)
try:
parser.read()
- self.assertEqual(parser.can_fetch("*", url+"/robots.txt"), False)
except URLError:
- self.skipTest('mueblesmoraleda.com is unavailable')
+ self.skipTest('%s is unavailable' % url)
+ self.assertEqual(parser.can_fetch("*", url+"/robots.txt"), False)
def testPythonOrg(self):
- if not support.is_resource_enabled('network'):
- return
+ support.requires('network')
parser = urllib.robotparser.RobotFileParser(
"http://www.python.org/robots.txt")
parser.read()
from test import support
import sys
import unittest
-import warnings
class TestUntestedModules(unittest.TestCase):
def test_at_least_import_untested_modules(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore")
+ with support.check_warnings(quiet=True):
import bdb
import cgitb
import code
# except if the test is specific to the Python implementation.
import sys
+import cgi
from test import support
from test.support import findfile
<p>Example.</p>
<xi:include href="{}"/>
</document>
-""".format(SIMPLE_XMLFILE)
+""".format(cgi.escape(SIMPLE_XMLFILE, True))
def xinclude_loader(href, parse="xml", encoding=None):
try:
class CleanContext(object):
"""Provide default namespace mapping and path cache."""
+ checkwarnings = None
+
+ def __init__(self, quiet=False):
+ deprecations = (
+ # Search behaviour is broken if search path starts with "/".
+ ("This search is broken in 1.3 and earlier, and will be fixed "
+ "in a future version. If you rely on the current behaviour, "
+ "change it to '.+'", FutureWarning),
+ # Element.getchildren() and Element.getiterator() are deprecated.
+ ("This method will be removed in future versions. "
+ "Use .+ instead.", DeprecationWarning),
+ ("This method will be removed in future versions. "
+ "Use .+ instead.", PendingDeprecationWarning),
+ # XMLParser.doctype() is deprecated.
+ ("This method of XMLParser is deprecated. Define doctype.. "
+ "method on the TreeBuilder target.", DeprecationWarning))
+ self.checkwarnings = support.check_warnings(*deprecations, quiet=quiet)
def __enter__(self):
from xml.etree import ElementTree
ElementTree._namespace_map = self._nsmap.copy()
# Copy the path cache (should be empty)
ElementTree.ElementPath._cache = self._path_cache.copy()
+ self.checkwarnings.__enter__()
def __exit__(self, *args):
from xml.etree import ElementTree
# Restore mapping and path cache
ElementTree._namespace_map = self._nsmap
ElementTree.ElementPath._cache = self._path_cache
+ self.checkwarnings.__exit__(*args)
def test_main(module_name='xml.etree.ElementTree'):
- import warnings
from test import test_xml_etree
- def ignore(message, category=DeprecationWarning):
- warnings.filterwarnings("ignore", message, category)
+
+ use_py_module = (module_name == 'xml.etree.ElementTree')
# The same doctests are used for both the Python and the C implementations
assert test_xml_etree.ET.__name__ == module_name
- with warnings.catch_warnings(), CleanContext():
- # Search behaviour is broken if search path starts with "/".
- ignore("This search is broken in 1.3 and earlier, and will be fixed "
- "in a future version. If you rely on the current behaviour, "
- "change it to '.+'", FutureWarning)
- # Element.getchildren() and Element.getiterator() are deprecated.
- ignore("This method will be removed in future versions. "
- "Use .+ instead.")
- # XMLParser.doctype() is deprecated.
- ignore("This method of XMLParser is deprecated. "
- "Define doctype.. method on the TreeBuilder target.")
-
+ # XXX the C module should give the same warnings as the Python module
+ with CleanContext(quiet=not use_py_module):
support.run_doctest(test_xml_etree, verbosity=True)
# The module should not be changed by the tests