Python-checkins
Threads by month
- ----- 2025 -----
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2015 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2014 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2013 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2012 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2011 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2010 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2009 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2008 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2007 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2006 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2005 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2004 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2003 -----
- December
- November
- October
- September
- August
December 2010
- 15 participants
- 768 discussions

Dec. 1, 2010
Author: georg.brandl
Date: Wed Dec 1 16:32:43 2010
New Revision: 86913
Log:
Add missing word, and add a better reference to the actual function.
Modified:
python/branches/py3k/Doc/reference/expressions.rst
Modified: python/branches/py3k/Doc/reference/expressions.rst
==============================================================================
--- python/branches/py3k/Doc/reference/expressions.rst (original)
+++ python/branches/py3k/Doc/reference/expressions.rst Wed Dec 1 16:32:43 2010
@@ -1322,8 +1322,8 @@
true numerically due to roundoff. For example, and assuming a platform on which
a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
- 1e100``, which is numerically exactly equal to ``1e100``. Function :func:`fmod`
- in the :mod:`math` module returns a result whose sign matches the sign of the
+ 1e100``, which is numerically exactly equal to ``1e100``. The function
+ :func:`math.fmod` returns a result whose sign matches the sign of the
first argument instead, and so returns ``-1e-100`` in this case. Which approach
is more appropriate depends on the application.
@@ -1344,7 +1344,8 @@
the :keyword:`is` operator, like those involving comparisons between instance
methods, or constants. Check their documentation for more info.
-.. [#] The ``%`` is also used for string formatting; the same precedence applies.
+.. [#] The ``%`` operator is also used for string formatting; the same
+ precedence applies.
.. [#] The power operator ``**`` binds less tightly than an arithmetic or
bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.
1
0

Dec. 1, 2010
Author: raymond.hettinger
Date: Wed Dec 1 11:49:19 2010
New Revision: 86912
Log:
Add recipe to itertools doc.
Modified:
python/branches/py3k/Doc/library/itertools.rst
Modified: python/branches/py3k/Doc/library/itertools.rst
==============================================================================
--- python/branches/py3k/Doc/library/itertools.rst (original)
+++ python/branches/py3k/Doc/library/itertools.rst Wed Dec 1 11:49:19 2010
@@ -653,6 +653,14 @@
pending -= 1
nexts = cycle(islice(nexts, pending))
+ def accumulate(iterable):
+ 'Emit a running total'
+ # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
+ total = 0
+ for element in iterable:
+ total += element
+ yield total
+
def partition(pred, iterable):
'Use a predicate to partition entries into false entries and true entries'
# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
1
0
py3k results for svn r86909 (hg cset 502eca1dc051)
--------------------------------------------------
Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogT8QCJk', '-x']
1
0

r86911 - in python/branches/py3k: Doc/library/functools.rst Lib/functools.py Lib/test/test_functools.py
by raymond.hettinger Dec. 1, 2010
by raymond.hettinger Dec. 1, 2010
Dec. 1, 2010
Author: raymond.hettinger
Date: Wed Dec 1 04:45:41 2010
New Revision: 86911
Log:
Issue 10593: Adopt Nick's suggestion for an lru_cache with maxsize=None.
Modified:
python/branches/py3k/Doc/library/functools.rst
python/branches/py3k/Lib/functools.py
python/branches/py3k/Lib/test/test_functools.py
Modified: python/branches/py3k/Doc/library/functools.rst
==============================================================================
--- python/branches/py3k/Doc/library/functools.rst (original)
+++ python/branches/py3k/Doc/library/functools.rst Wed Dec 1 04:45:41 2010
@@ -32,7 +32,7 @@
A compare function is any callable that accept two arguments, compares them,
and returns a negative number for less-than, zero for equality, or a positive
number for greater-than. A key function is a callable that accepts one
- argument and returns another value that indicates the position in the desired
+ argument and returns another value indicating the position in the desired
collation sequence.
Example::
@@ -51,10 +51,14 @@
Since a dictionary is used to cache results, the positional and keyword
arguments to the function must be hashable.
+ If *maxsize* is set to None, the LRU feature is disabled and the cache
+ can grow without bound.
+
To help measure the effectiveness of the cache and tune the *maxsize*
parameter, the wrapped function is instrumented with a :func:`cache_info`
function that returns a :term:`named tuple` showing *hits*, *misses*,
- *maxsize* and *currsize*.
+ *maxsize* and *currsize*. In a multi-threaded environment, the hits
+ and misses are approximate.
The decorator also provides a :func:`cache_clear` function for clearing or
invalidating the cache.
@@ -89,12 +93,25 @@
>>> print(get_pep.cache_info())
CacheInfo(hits=3, misses=8, maxsize=20, currsize=8)
- .. versionadded:: 3.2
+ Example of efficiently computing
+ `Fibonacci numbers <http://en.wikipedia.org/wiki/Fibonacci_number>`_
+ using a cache to implement a
+ `dynamic programming <http://en.wikipedia.org/wiki/Dynamic_programming>`_
+ technique::
+
+ @lru_cache(maxsize=None)
+ def fib(n):
+ if n < 2:
+ return n
+ return fib(n-1) + fib(n-2)
- .. seealso::
+ >>> print([fib(n) for n in range(16)])
+ [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
- Recipe for a `plain cache without the LRU feature
- <http://code.activestate.com/recipes/577479-simple-caching-decorator/>`_.
+ >>> print(fib.cache_info())
+ CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
+
+ .. versionadded:: 3.2
.. decorator:: total_ordering
Modified: python/branches/py3k/Lib/functools.py
==============================================================================
--- python/branches/py3k/Lib/functools.py (original)
+++ python/branches/py3k/Lib/functools.py Wed Dec 1 04:45:41 2010
@@ -119,6 +119,9 @@
def lru_cache(maxsize=100):
"""Least-recently-used cache decorator.
+ If *maxsize* is set to None, the LRU features are disabled and the cache
+ can grow without bound.
+
Arguments to the cached function must be hashable.
View the cache statistics named tuple (hits, misses, maxsize, currsize) with
@@ -136,32 +139,51 @@
def decorating_function(user_function,
tuple=tuple, sorted=sorted, len=len, KeyError=KeyError):
- cache = OrderedDict() # ordered least recent to most recent
- cache_popitem = cache.popitem
- cache_renew = cache.move_to_end
hits = misses = 0
kwd_mark = object() # separates positional and keyword args
lock = Lock()
- @wraps(user_function)
- def wrapper(*args, **kwds):
- nonlocal hits, misses
- key = args
- if kwds:
- key += (kwd_mark,) + tuple(sorted(kwds.items()))
- try:
- with lock:
+ if maxsize is None:
+ cache = dict() # simple cache without ordering or size limit
+
+ @wraps(user_function)
+ def wrapper(*args, **kwds):
+ nonlocal hits, misses
+ key = args
+ if kwds:
+ key += (kwd_mark,) + tuple(sorted(kwds.items()))
+ try:
result = cache[key]
- cache_renew(key) # record recent use of this key
hits += 1
- except KeyError:
- result = user_function(*args, **kwds)
- with lock:
- cache[key] = result # record recent use of this key
+ except KeyError:
+ result = user_function(*args, **kwds)
+ cache[key] = result
misses += 1
- if len(cache) > maxsize:
- cache_popitem(0) # purge least recently used cache entry
- return result
+ return result
+ else:
+ cache = OrderedDict() # ordered least recent to most recent
+ cache_popitem = cache.popitem
+ cache_renew = cache.move_to_end
+
+ @wraps(user_function)
+ def wrapper(*args, **kwds):
+ nonlocal hits, misses
+ key = args
+ if kwds:
+ key += (kwd_mark,) + tuple(sorted(kwds.items()))
+ try:
+ with lock:
+ result = cache[key]
+ cache_renew(key) # record recent use of this key
+ hits += 1
+ except KeyError:
+ result = user_function(*args, **kwds)
+ with lock:
+ cache[key] = result # record recent use of this key
+ misses += 1
+ if len(cache) > maxsize:
+ cache_popitem(0) # purge least recently used cache entry
+ return result
def cache_info():
"""Report cache statistics"""
Modified: python/branches/py3k/Lib/test/test_functools.py
==============================================================================
--- python/branches/py3k/Lib/test/test_functools.py (original)
+++ python/branches/py3k/Lib/test/test_functools.py Wed Dec 1 04:45:41 2010
@@ -586,6 +586,20 @@
self.assertEqual(misses, 4)
self.assertEqual(currsize, 2)
+ def test_lru_with_maxsize_none(self):
+ @functools.lru_cache(maxsize=None)
+ def fib(n):
+ if n < 2:
+ return n
+ return fib(n-1) + fib(n-2)
+ self.assertEqual([fib(n) for n in range(16)],
+ [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610])
+ self.assertEqual(fib.cache_info(),
+ functools._CacheInfo(hits=28, misses=16, maxsize=None, currsize=16))
+ fib.cache_clear()
+ self.assertEqual(fib.cache_info(),
+ functools._CacheInfo(hits=0, misses=0, maxsize=None, currsize=0))
+
def test_main(verbose=None):
test_classes = (
TestPartial,
1
0
Author: ezio.melotti
Date: Wed Dec 1 03:32:32 2010
New Revision: 86910
Log:
#10273: Rename assertRegexpMatches and assertRaisesRegexp to assertRegex and assertRaisesRegex.
Modified:
python/branches/py3k/Doc/library/unittest.rst
python/branches/py3k/Lib/test/test_abc.py
python/branches/py3k/Lib/test/test_asyncore.py
python/branches/py3k/Lib/test/test_concurrent_futures.py
python/branches/py3k/Lib/test/test_contextlib.py
python/branches/py3k/Lib/test/test_dis.py
python/branches/py3k/Lib/test/test_memoryview.py
python/branches/py3k/Lib/test/test_runpy.py
python/branches/py3k/Lib/test/test_smtplib.py
python/branches/py3k/Lib/test/test_ssl.py
python/branches/py3k/Lib/test/test_unicode.py
python/branches/py3k/Lib/test/test_urlparse.py
python/branches/py3k/Lib/test/test_xmlrpc.py
python/branches/py3k/Lib/test/test_zlib.py
python/branches/py3k/Lib/unittest/case.py
python/branches/py3k/Lib/unittest/test/test_assertions.py
python/branches/py3k/Lib/unittest/test/test_case.py
python/branches/py3k/Lib/unittest/test/test_discovery.py
python/branches/py3k/Lib/unittest/test/test_loader.py
python/branches/py3k/Lib/unittest/test/test_setups.py
python/branches/py3k/Misc/NEWS
Modified: python/branches/py3k/Doc/library/unittest.rst
==============================================================================
--- python/branches/py3k/Doc/library/unittest.rst (original)
+++ python/branches/py3k/Doc/library/unittest.rst Wed Dec 1 03:32:32 2010
@@ -835,7 +835,7 @@
+-----------------------------------------+-----------------------------+---------------+
All the assert methods (except :meth:`assertRaises`,
- :meth:`assertRaisesRegexp`, :meth:`assertWarns`, :meth:`assertWarnsRegexp`)
+ :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex`)
accept a *msg* argument that, if specified, is used as the error message on
failure (see also :data:`longMessage`).
@@ -919,14 +919,14 @@
| :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | |
| <TestCase.assertRaises>` | | |
+---------------------------------------------------------+--------------------------------------+------------+
- | :meth:`assertRaisesRegexp(exc, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | 3.1 |
- | <TestCase.assertRaisesRegexp>` | and the message matches `re` | |
+ | :meth:`assertRaisesRegex(exc, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | 3.1 |
+ | <TestCase.assertRaisesRegex>` | and the message matches `re` | |
+---------------------------------------------------------+--------------------------------------+------------+
| :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `warn` | 3.2 |
| <TestCase.assertWarns>` | | |
+---------------------------------------------------------+--------------------------------------+------------+
- | :meth:`assertWarnsRegexp(warn, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `warn` | 3.2 |
- | <TestCase.assertWarnsRegexp>` | and the message matches `re` | |
+ | :meth:`assertWarnsRegex(warn, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `warn` | 3.2 |
+ | <TestCase.assertWarnsRegex>` | and the message matches `re` | |
+---------------------------------------------------------+--------------------------------------+------------+
.. method:: assertRaises(exception, callable, *args, **kwds)
@@ -962,23 +962,25 @@
Added the :attr:`exception` attribute.
- .. method:: assertRaisesRegexp(exception, regexp, callable, *args, **kwds)
- assertRaisesRegexp(exception, regexp)
+ .. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds)
+ assertRaisesRegex(exception, regex)
- Like :meth:`assertRaises` but also tests that *regexp* matches
- on the string representation of the raised exception. *regexp* may be
+ Like :meth:`assertRaises` but also tests that *regex* matches
+ on the string representation of the raised exception. *regex* may be
a regular expression object or a string containing a regular expression
suitable for use by :func:`re.search`. Examples::
- self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$',
- int, 'XYZ')
+ self.assertRaisesRegex(ValueError, 'invalid literal for.*XYZ$',
+ int, 'XYZ')
or::
- with self.assertRaisesRegexp(ValueError, 'literal'):
+ with self.assertRaisesRegex(ValueError, 'literal'):
int('XYZ')
- .. versionadded:: 3.1
+ .. versionadded:: 3.1 ``assertRaisesRegexp``
+ .. versionchanged:: 3.2
+ The method has been renamed to :meth:`assertRaisesRegex`
.. method:: assertWarns(warning, callable, *args, **kwds)
@@ -1015,21 +1017,21 @@
.. versionadded:: 3.2
- .. method:: assertWarnsRegexp(warning, regexp, callable, *args, **kwds)
- assertWarnsRegexp(warning, regexp)
+ .. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds)
+ assertWarnsRegex(warning, regex)
- Like :meth:`assertWarns` but also tests that *regexp* matches on the
- message of the triggered warning. *regexp* may be a regular expression
+ Like :meth:`assertWarns` but also tests that *regex* matches on the
+ message of the triggered warning. *regex* may be a regular expression
object or a string containing a regular expression suitable for use
by :func:`re.search`. Example::
- self.assertWarnsRegexp(DeprecationWarning,
- r'legacy_function\(\) is deprecated',
- legacy_function, 'XYZ')
+ self.assertWarnsRegex(DeprecationWarning,
+ r'legacy_function\(\) is deprecated',
+ legacy_function, 'XYZ')
or::
- with self.assertWarnsRegexp(RuntimeWarning, 'unsafe frobnicating'):
+ with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
frobnicate('/etc/passwd')
.. versionadded:: 3.2
@@ -1059,11 +1061,11 @@
| :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 |
| <TestCase.assertLessEqual>` | | |
+---------------------------------------+--------------------------------+--------------+
- | :meth:`assertRegexpMatches(s, re) | ``regex.search(s)`` | 3.1 |
- | <TestCase.assertRegexpMatches>` | | |
+ | :meth:`assertRegex(s, re) | ``regex.search(s)`` | 3.1 |
+ | <TestCase.assertRegex>` | | |
+---------------------------------------+--------------------------------+--------------+
- | :meth:`assertNotRegexpMatches(s, re) | ``not regex.search(s)`` | 3.2 |
- | <TestCase.assertNotRegexpMatches>` | | |
+ | :meth:`assertNotRegex(s, re) | ``not regex.search(s)`` | 3.2 |
+ | <TestCase.assertNotRegex>` | | |
+---------------------------------------+--------------------------------+--------------+
| :meth:`assertDictContainsSubset(a, b) | all the key/value pairs | 3.1 |
| <TestCase.assertDictContainsSubset>` | in `a` exist in `b` | |
@@ -1108,17 +1110,19 @@
.. versionadded:: 3.1
- .. method:: assertRegexpMatches(text, regexp, msg=None)
- assertNotRegexpMatches(text, regexp, msg=None)
+ .. method:: assertRegex(text, regex, msg=None)
+ assertNotRegex(text, regex, msg=None)
- Test that a *regexp* search matches (or does not match) *text*. In case
+ Test that a *regex* search matches (or does not match) *text*. In case
of failure, the error message will include the pattern and the *text* (or
- the pattern and the part of *text* that unexpectedly matched). *regexp*
+ the pattern and the part of *text* that unexpectedly matched). *regex*
may be a regular expression object or a string containing a regular
expression suitable for use by :func:`re.search`.
- .. versionadded:: 3.1 :meth:`~TestCase.assertRegexpMatches`
- .. versionadded:: 3.2 :meth:`~TestCase.assertNotRegexpMatches`
+ .. versionadded:: 3.1 ``.assertRegexpMatches``
+ .. versionchanged:: 3.2
+ ``.assertRegexpMatches`` has been renamed to :meth:`.assertRegex`
+ .. versionadded:: 3.2 :meth:`.assertNotRegex`
.. method:: assertDictContainsSubset(expected, actual, msg=None)
@@ -1420,13 +1424,17 @@
:meth:`.assertRaises` failUnlessRaises
:meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals
:meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals
+ :meth:`.assertRegex` assertRegexpMatches
+ :meth:`.assertRaisesRegex` assertRaisesRegexp
============================== ====================== ======================
.. deprecated-removed:: 3.1 3.3
the fail* aliases listed in the second column.
.. deprecated:: 3.2
the assert* aliases listed in the third column.
-
+ .. deprecated:: 3.2
+ ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to
+ :meth:`.assertRegex` and :meth:`.assertRaisesRegex`
.. _testsuite-objects:
Modified: python/branches/py3k/Lib/test/test_abc.py
==============================================================================
--- python/branches/py3k/Lib/test/test_abc.py (original)
+++ python/branches/py3k/Lib/test/test_abc.py Wed Dec 1 03:32:32 2010
@@ -192,8 +192,8 @@
def test_register_non_class(self):
class A(metaclass=abc.ABCMeta):
pass
- self.assertRaisesRegexp(TypeError, "Can only register classes",
- A.register, 4)
+ self.assertRaisesRegex(TypeError, "Can only register classes",
+ A.register, 4)
def test_registration_transitiveness(self):
class A(metaclass=abc.ABCMeta):
Modified: python/branches/py3k/Lib/test/test_asyncore.py
==============================================================================
--- python/branches/py3k/Lib/test/test_asyncore.py (original)
+++ python/branches/py3k/Lib/test/test_asyncore.py Wed Dec 1 03:32:32 2010
@@ -312,8 +312,8 @@
d = asyncore.dispatcher(socket.socket())
# make sure the error message no longer refers to the socket
# object but the dispatcher instance instead
- self.assertRaisesRegexp(AttributeError, 'dispatcher instance',
- getattr, d, 'foo')
+ self.assertRaisesRegex(AttributeError, 'dispatcher instance',
+ getattr, d, 'foo')
# cheap inheritance with the underlying socket is supposed
# to still work but a DeprecationWarning is expected
with warnings.catch_warnings(record=True) as w:
Modified: python/branches/py3k/Lib/test/test_concurrent_futures.py
==============================================================================
--- python/branches/py3k/Lib/test/test_concurrent_futures.py (original)
+++ python/branches/py3k/Lib/test/test_concurrent_futures.py Wed Dec 1 03:32:32 2010
@@ -682,18 +682,18 @@
self.assertTrue(was_cancelled)
def test_repr(self):
- self.assertRegexpMatches(repr(PENDING_FUTURE),
- '<Future at 0x[0-9a-f]+ state=pending>')
- self.assertRegexpMatches(repr(RUNNING_FUTURE),
- '<Future at 0x[0-9a-f]+ state=running>')
- self.assertRegexpMatches(repr(CANCELLED_FUTURE),
- '<Future at 0x[0-9a-f]+ state=cancelled>')
- self.assertRegexpMatches(repr(CANCELLED_AND_NOTIFIED_FUTURE),
- '<Future at 0x[0-9a-f]+ state=cancelled>')
- self.assertRegexpMatches(
+ self.assertRegex(repr(PENDING_FUTURE),
+ '<Future at 0x[0-9a-f]+ state=pending>')
+ self.assertRegex(repr(RUNNING_FUTURE),
+ '<Future at 0x[0-9a-f]+ state=running>')
+ self.assertRegex(repr(CANCELLED_FUTURE),
+ '<Future at 0x[0-9a-f]+ state=cancelled>')
+ self.assertRegex(repr(CANCELLED_AND_NOTIFIED_FUTURE),
+ '<Future at 0x[0-9a-f]+ state=cancelled>')
+ self.assertRegex(
repr(EXCEPTION_FUTURE),
'<Future at 0x[0-9a-f]+ state=finished raised IOError>')
- self.assertRegexpMatches(
+ self.assertRegex(
repr(SUCCESSFUL_FUTURE),
'<Future at 0x[0-9a-f]+ state=finished returned int>')
Modified: python/branches/py3k/Lib/test/test_contextlib.py
==============================================================================
--- python/branches/py3k/Lib/test/test_contextlib.py (original)
+++ python/branches/py3k/Lib/test/test_contextlib.py Wed Dec 1 03:32:32 2010
@@ -231,7 +231,7 @@
def test_contextdecorator_with_exception(self):
context = mycontext()
- with self.assertRaisesRegexp(NameError, 'foo'):
+ with self.assertRaisesRegex(NameError, 'foo'):
with context:
raise NameError('foo')
self.assertIsNotNone(context.exc)
@@ -265,7 +265,7 @@
self.assertTrue(context.started)
raise NameError('foo')
- with self.assertRaisesRegexp(NameError, 'foo'):
+ with self.assertRaisesRegex(NameError, 'foo'):
test()
self.assertIsNotNone(context.exc)
self.assertIs(context.exc[0], NameError)
Modified: python/branches/py3k/Lib/test/test_dis.py
==============================================================================
--- python/branches/py3k/Lib/test/test_dis.py (original)
+++ python/branches/py3k/Lib/test/test_dis.py Wed Dec 1 03:32:32 2010
@@ -354,14 +354,14 @@
def test_code_info(self):
self.maxDiff = 1000
for x, expected in self.test_pairs:
- self.assertRegexpMatches(dis.code_info(x), expected)
+ self.assertRegex(dis.code_info(x), expected)
def test_show_code(self):
self.maxDiff = 1000
for x, expected in self.test_pairs:
with captured_stdout() as output:
dis.show_code(x)
- self.assertRegexpMatches(output.getvalue(), expected+"\n")
+ self.assertRegex(output.getvalue(), expected+"\n")
def test_main():
run_unittest(DisTests, CodeInfoTests)
Modified: python/branches/py3k/Lib/test/test_memoryview.py
==============================================================================
--- python/branches/py3k/Lib/test/test_memoryview.py (original)
+++ python/branches/py3k/Lib/test/test_memoryview.py Wed Dec 1 03:32:32 2010
@@ -226,7 +226,7 @@
self.assertTrue(wr() is None, wr())
def _check_released(self, m, tp):
- check = self.assertRaisesRegexp(ValueError, "released")
+ check = self.assertRaisesRegex(ValueError, "released")
with check: bytes(m)
with check: m.tobytes()
with check: m.tolist()
Modified: python/branches/py3k/Lib/test/test_runpy.py
==============================================================================
--- python/branches/py3k/Lib/test/test_runpy.py (original)
+++ python/branches/py3k/Lib/test/test_runpy.py Wed Dec 1 03:32:32 2010
@@ -329,7 +329,7 @@
def _check_import_error(self, script_name, msg):
msg = re.escape(msg)
- self.assertRaisesRegexp(ImportError, msg, run_path, script_name)
+ self.assertRaisesRegex(ImportError, msg, run_path, script_name)
def test_basic_script(self):
with temp_dir() as script_dir:
@@ -403,7 +403,7 @@
script_name = self._make_test_script(script_dir, mod_name, source)
zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
msg = "recursion depth exceeded"
- self.assertRaisesRegexp(RuntimeError, msg, run_path, zip_name)
+ self.assertRaisesRegex(RuntimeError, msg, run_path, zip_name)
Modified: python/branches/py3k/Lib/test/test_smtplib.py
==============================================================================
--- python/branches/py3k/Lib/test/test_smtplib.py (original)
+++ python/branches/py3k/Lib/test/test_smtplib.py Wed Dec 1 03:32:32 2010
@@ -319,12 +319,12 @@
self.assertEqual(self.output.getvalue(), mexpect)
debugout = smtpd.DEBUGSTREAM.getvalue()
sender = re.compile("^sender: foo(a)bar.com$", re.MULTILINE)
- self.assertRegexpMatches(debugout, sender)
+ self.assertRegex(debugout, sender)
for addr in ('John', 'Sally', 'Fred', 'root@localhost',
'warped(a)silly.walks.com'):
to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
re.MULTILINE)
- self.assertRegexpMatches(debugout, to_addr)
+ self.assertRegex(debugout, to_addr)
def testSendMessageWithSomeAddresses(self):
# Make sure nothing breaks if not all of the three 'to' headers exist
@@ -347,11 +347,11 @@
self.assertEqual(self.output.getvalue(), mexpect)
debugout = smtpd.DEBUGSTREAM.getvalue()
sender = re.compile("^sender: foo(a)bar.com$", re.MULTILINE)
- self.assertRegexpMatches(debugout, sender)
+ self.assertRegex(debugout, sender)
for addr in ('John', 'Dinsdale'):
to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
re.MULTILINE)
- self.assertRegexpMatches(debugout, to_addr)
+ self.assertRegex(debugout, to_addr)
class NonConnectingTests(unittest.TestCase):
Modified: python/branches/py3k/Lib/test/test_ssl.py
==============================================================================
--- python/branches/py3k/Lib/test/test_ssl.py (original)
+++ python/branches/py3k/Lib/test/test_ssl.py Wed Dec 1 03:32:32 2010
@@ -185,17 +185,17 @@
def test_errors(self):
sock = socket.socket()
- self.assertRaisesRegexp(ValueError,
+ self.assertRaisesRegex(ValueError,
"certfile must be specified",
ssl.wrap_socket, sock, keyfile=CERTFILE)
- self.assertRaisesRegexp(ValueError,
+ self.assertRaisesRegex(ValueError,
"certfile must be specified for server-side operations",
ssl.wrap_socket, sock, server_side=True)
- self.assertRaisesRegexp(ValueError,
+ self.assertRaisesRegex(ValueError,
"certfile must be specified for server-side operations",
ssl.wrap_socket, sock, server_side=True, certfile="")
s = ssl.wrap_socket(sock, server_side=True, certfile=CERTFILE)
- self.assertRaisesRegexp(ValueError, "can't connect in server-side mode",
+ self.assertRaisesRegex(ValueError, "can't connect in server-side mode",
s.connect, (HOST, 8080))
with self.assertRaises(IOError) as cm:
with socket.socket() as sock:
@@ -310,7 +310,7 @@
ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
ctx.set_ciphers("ALL")
ctx.set_ciphers("DEFAULT")
- with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"):
+ with self.assertRaisesRegex(ssl.SSLError, "No cipher can be selected"):
ctx.set_ciphers("^$:,;?*'dorothyx")
@skip_if_broken_ubuntu_ssl
@@ -358,24 +358,24 @@
with self.assertRaises(IOError) as cm:
ctx.load_cert_chain(WRONGCERT)
self.assertEqual(cm.exception.errno, errno.ENOENT)
- with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"):
+ with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
ctx.load_cert_chain(BADCERT)
- with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"):
+ with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
ctx.load_cert_chain(EMPTYCERT)
# Separate key and cert
ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
ctx.load_cert_chain(ONLYCERT, ONLYKEY)
ctx.load_cert_chain(certfile=ONLYCERT, keyfile=ONLYKEY)
ctx.load_cert_chain(certfile=BYTES_ONLYCERT, keyfile=BYTES_ONLYKEY)
- with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"):
+ with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
ctx.load_cert_chain(ONLYCERT)
- with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"):
+ with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
ctx.load_cert_chain(ONLYKEY)
- with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"):
+ with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
ctx.load_cert_chain(certfile=ONLYKEY, keyfile=ONLYCERT)
# Mismatching key and cert
ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
- with self.assertRaisesRegexp(ssl.SSLError, "key values mismatch"):
+ with self.assertRaisesRegex(ssl.SSLError, "key values mismatch"):
ctx.load_cert_chain(SVN_PYTHON_ORG_ROOT_CERT, ONLYKEY)
def test_load_verify_locations(self):
@@ -389,7 +389,7 @@
with self.assertRaises(IOError) as cm:
ctx.load_verify_locations(WRONGCERT)
self.assertEqual(cm.exception.errno, errno.ENOENT)
- with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"):
+ with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
ctx.load_verify_locations(BADCERT)
ctx.load_verify_locations(CERTFILE, CAPATH)
ctx.load_verify_locations(CERTFILE, capath=BYTES_CAPATH)
@@ -434,8 +434,8 @@
# this should fail because we have no verification certs
s = ssl.wrap_socket(socket.socket(socket.AF_INET),
cert_reqs=ssl.CERT_REQUIRED)
- self.assertRaisesRegexp(ssl.SSLError, "certificate verify failed",
- s.connect, ("svn.python.org", 443))
+ self.assertRaisesRegex(ssl.SSLError, "certificate verify failed",
+ s.connect, ("svn.python.org", 443))
s.close()
# this should succeed because we specify the root cert
@@ -469,7 +469,7 @@
# This should fail because we have no verification certs
ctx.verify_mode = ssl.CERT_REQUIRED
s = ctx.wrap_socket(socket.socket(socket.AF_INET))
- self.assertRaisesRegexp(ssl.SSLError, "certificate verify failed",
+ self.assertRaisesRegex(ssl.SSLError, "certificate verify failed",
s.connect, ("svn.python.org", 443))
s.close()
# This should succeed because we specify the root cert
@@ -587,7 +587,7 @@
cert_reqs=ssl.CERT_NONE, ciphers="DEFAULT")
s.connect(remote)
# Error checking can happen at instantiation or when connecting
- with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"):
+ with self.assertRaisesRegex(ssl.SSLError, "No cipher can be selected"):
with socket.socket(socket.AF_INET) as sock:
s = ssl.wrap_socket(sock,
cert_reqs=ssl.CERT_NONE, ciphers="^$:,;?*'dorothyx")
@@ -1499,8 +1499,8 @@
c.settimeout(0.2)
c.connect((host, port))
# Will attempt handshake and time out
- self.assertRaisesRegexp(ssl.SSLError, "timed out",
- ssl.wrap_socket, c)
+ self.assertRaisesRegex(ssl.SSLError, "timed out",
+ ssl.wrap_socket, c)
finally:
c.close()
try:
@@ -1508,8 +1508,8 @@
c = ssl.wrap_socket(c)
c.settimeout(0.2)
# Will attempt handshake and time out
- self.assertRaisesRegexp(ssl.SSLError, "timed out",
- c.connect, (host, port))
+ self.assertRaisesRegex(ssl.SSLError, "timed out",
+ c.connect, (host, port))
finally:
c.close()
finally:
Modified: python/branches/py3k/Lib/test/test_unicode.py
==============================================================================
--- python/branches/py3k/Lib/test/test_unicode.py (original)
+++ python/branches/py3k/Lib/test/test_unicode.py Wed Dec 1 03:32:32 2010
@@ -1427,7 +1427,7 @@
# non-ascii format, ascii argument: ensure that PyUnicode_FromFormat()
# raises an error for a non-ascii format string.
- self.assertRaisesRegexp(ValueError,
+ self.assertRaisesRegex(ValueError,
'^PyUnicode_FromFormatV\(\) expects an ASCII-encoded format '
'string, got a non-ASCII byte: 0xe9$',
format_unicode, b'unicode\xe9=%s', 'ascii')
Modified: python/branches/py3k/Lib/test/test_urlparse.py
==============================================================================
--- python/branches/py3k/Lib/test/test_urlparse.py (original)
+++ python/branches/py3k/Lib/test/test_urlparse.py Wed Dec 1 03:32:32 2010
@@ -629,25 +629,25 @@
def test_mixed_types_rejected(self):
# Several functions that process either strings or ASCII encoded bytes
# accept multiple arguments. Check they reject mixed type input
- with self.assertRaisesRegexp(TypeError, "Cannot mix str"):
+ with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlparse("www.python.org", b"http")
- with self.assertRaisesRegexp(TypeError, "Cannot mix str"):
+ with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlparse(b"www.python.org", "http")
- with self.assertRaisesRegexp(TypeError, "Cannot mix str"):
+ with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlsplit("www.python.org", b"http")
- with self.assertRaisesRegexp(TypeError, "Cannot mix str"):
+ with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlsplit(b"www.python.org", "http")
- with self.assertRaisesRegexp(TypeError, "Cannot mix str"):
+ with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlunparse(( b"http", "www.python.org","","","",""))
- with self.assertRaisesRegexp(TypeError, "Cannot mix str"):
+ with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlunparse(("http", b"www.python.org","","","",""))
- with self.assertRaisesRegexp(TypeError, "Cannot mix str"):
+ with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlunsplit((b"http", "www.python.org","","",""))
- with self.assertRaisesRegexp(TypeError, "Cannot mix str"):
+ with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlunsplit(("http", b"www.python.org","","",""))
- with self.assertRaisesRegexp(TypeError, "Cannot mix str"):
+ with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urljoin("http://python.org", b"http://python.org")
- with self.assertRaisesRegexp(TypeError, "Cannot mix str"):
+ with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urljoin(b"http://python.org", "http://python.org")
def _check_result_type(self, str_type):
Modified: python/branches/py3k/Lib/test/test_xmlrpc.py
==============================================================================
--- python/branches/py3k/Lib/test/test_xmlrpc.py (original)
+++ python/branches/py3k/Lib/test/test_xmlrpc.py Wed Dec 1 03:32:32 2010
@@ -715,8 +715,8 @@
t.encode_threshold = None
t.fake_gzip = True
p = xmlrpclib.ServerProxy(URL, transport=t)
- cm = self.assertRaisesRegexp(xmlrpclib.ProtocolError,
- re.compile(r"\b400\b"))
+ cm = self.assertRaisesRegex(xmlrpclib.ProtocolError,
+ re.compile(r"\b400\b"))
with cm:
p.pow(6, 8)
Modified: python/branches/py3k/Lib/test/test_zlib.py
==============================================================================
--- python/branches/py3k/Lib/test/test_zlib.py (original)
+++ python/branches/py3k/Lib/test/test_zlib.py Wed Dec 1 03:32:32 2010
@@ -143,7 +143,7 @@
def test_incomplete_stream(self):
# An useful error message is given
x = zlib.compress(HAMLET_SCENE)
- self.assertRaisesRegexp(zlib.error,
+ self.assertRaisesRegex(zlib.error,
"Error -5 while decompressing data: incomplete or truncated stream",
zlib.decompress, x[:-1])
Modified: python/branches/py3k/Lib/unittest/case.py
==============================================================================
--- python/branches/py3k/Lib/unittest/case.py (original)
+++ python/branches/py3k/Lib/unittest/case.py Wed Dec 1 03:32:32 2010
@@ -94,7 +94,7 @@
class _AssertRaisesBaseContext(object):
def __init__(self, expected, test_case, callable_obj=None,
- expected_regexp=None):
+ expected_regex=None):
self.expected = expected
self.failureException = test_case.failureException
if callable_obj is not None:
@@ -104,9 +104,9 @@
self.obj_name = str(callable_obj)
else:
self.obj_name = None
- if isinstance(expected_regexp, (bytes, str)):
- expected_regexp = re.compile(expected_regexp)
- self.expected_regexp = expected_regexp
+ if isinstance(expected_regex, (bytes, str)):
+ expected_regex = re.compile(expected_regex)
+ self.expected_regex = expected_regex
class _AssertRaisesContext(_AssertRaisesBaseContext):
@@ -132,13 +132,13 @@
return False
# store exception, without traceback, for later retrieval
self.exception = exc_value.with_traceback(None)
- if self.expected_regexp is None:
+ if self.expected_regex is None:
return True
- expected_regexp = self.expected_regexp
- if not expected_regexp.search(str(exc_value)):
+ expected_regex = self.expected_regex
+ if not expected_regex.search(str(exc_value)):
raise self.failureException('"%s" does not match "%s"' %
- (expected_regexp.pattern, str(exc_value)))
+ (expected_regex.pattern, str(exc_value)))
return True
@@ -172,8 +172,8 @@
continue
if first_matching is None:
first_matching = w
- if (self.expected_regexp is not None and
- not self.expected_regexp.search(str(w))):
+ if (self.expected_regex is not None and
+ not self.expected_regex.search(str(w))):
continue
# store warning for later retrieval
self.warning = w
@@ -183,7 +183,7 @@
# Now we simply try to choose a helpful failure message
if first_matching is not None:
raise self.failureException('"%s" does not match "%s"' %
- (self.expected_regexp.pattern, str(first_matching)))
+ (self.expected_regex.pattern, str(first_matching)))
if self.obj_name:
raise self.failureException("{0} not triggered by {1}"
.format(exc_name, self.obj_name))
@@ -689,24 +689,6 @@
raise self.failureException(msg)
- def _deprecate(original_func):
- def deprecated_func(*args, **kwargs):
- warnings.warn(
- 'Please use {0} instead.'.format(original_func.__name__),
- DeprecationWarning, 2)
- return original_func(*args, **kwargs)
- return deprecated_func
-
- # The fail* methods can be removed in 3.3, the 5 assert* methods will
- # have to stay around for a few more versions. See #9424.
- failUnlessEqual = assertEquals = _deprecate(assertEqual)
- failIfEqual = assertNotEquals = _deprecate(assertNotEqual)
- failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual)
- failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual)
- failUnless = assert_ = _deprecate(assertTrue)
- failUnlessRaises = _deprecate(assertRaises)
- failIf = _deprecate(assertFalse)
-
def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
"""An equality assertion for ordered sequences (like lists and tuples).
@@ -1095,27 +1077,27 @@
standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls)
self.fail(self._formatMessage(msg, standardMsg))
- def assertRaisesRegexp(self, expected_exception, expected_regexp,
- callable_obj=None, *args, **kwargs):
- """Asserts that the message in a raised exception matches a regexp.
+ def assertRaisesRegex(self, expected_exception, expected_regex,
+ callable_obj=None, *args, **kwargs):
+ """Asserts that the message in a raised exception matches a regex.
Args:
expected_exception: Exception class expected to be raised.
- expected_regexp: Regexp (re pattern object or string) expected
+ expected_regex: Regex (re pattern object or string) expected
to be found in error message.
callable_obj: Function to be called.
args: Extra args.
kwargs: Extra kwargs.
"""
context = _AssertRaisesContext(expected_exception, self, callable_obj,
- expected_regexp)
+ expected_regex)
if callable_obj is None:
return context
with context:
callable_obj(*args, **kwargs)
- def assertWarnsRegexp(self, expected_warning, expected_regexp,
- callable_obj=None, *args, **kwargs):
+ def assertWarnsRegex(self, expected_warning, expected_regex,
+ callable_obj=None, *args, **kwargs):
"""Asserts that the message in a triggered warning matches a regexp.
Basic functioning is similar to assertWarns() with the addition
that only warnings whose messages also match the regular expression
@@ -1123,42 +1105,64 @@
Args:
expected_warning: Warning class expected to be triggered.
- expected_regexp: Regexp (re pattern object or string) expected
+ expected_regex: Regex (re pattern object or string) expected
to be found in error message.
callable_obj: Function to be called.
args: Extra args.
kwargs: Extra kwargs.
"""
context = _AssertWarnsContext(expected_warning, self, callable_obj,
- expected_regexp)
+ expected_regex)
if callable_obj is None:
return context
with context:
callable_obj(*args, **kwargs)
- def assertRegexpMatches(self, text, expected_regexp, msg=None):
+ def assertRegex(self, text, expected_regex, msg=None):
"""Fail the test unless the text matches the regular expression."""
- if isinstance(expected_regexp, (str, bytes)):
- expected_regexp = re.compile(expected_regexp)
- if not expected_regexp.search(text):
- msg = msg or "Regexp didn't match"
- msg = '%s: %r not found in %r' % (msg, expected_regexp.pattern, text)
+ if isinstance(expected_regex, (str, bytes)):
+ expected_regex = re.compile(expected_regex)
+ if not expected_regex.search(text):
+ msg = msg or "Regex didn't match"
+ msg = '%s: %r not found in %r' % (msg, expected_regex.pattern, text)
raise self.failureException(msg)
- def assertNotRegexpMatches(self, text, unexpected_regexp, msg=None):
+ def assertNotRegexMatches(self, text, unexpected_regex, msg=None):
"""Fail the test if the text matches the regular expression."""
- if isinstance(unexpected_regexp, (str, bytes)):
- unexpected_regexp = re.compile(unexpected_regexp)
- match = unexpected_regexp.search(text)
+ if isinstance(unexpected_regex, (str, bytes)):
+ unexpected_regex = re.compile(unexpected_regex)
+ match = unexpected_regex.search(text)
if match:
- msg = msg or "Regexp matched"
+ msg = msg or "Regex matched"
msg = '%s: %r matches %r in %r' % (msg,
text[match.start():match.end()],
- unexpected_regexp.pattern,
+ unexpected_regex.pattern,
text)
raise self.failureException(msg)
+ def _deprecate(original_func):
+ def deprecated_func(*args, **kwargs):
+ warnings.warn(
+ 'Please use {0} instead.'.format(original_func.__name__),
+ DeprecationWarning, 2)
+ return original_func(*args, **kwargs)
+ return deprecated_func
+
+ # The fail* methods can be removed in 3.3, the 5 assert* methods will
+ # have to stay around for a few more versions. See #9424.
+ failUnlessEqual = assertEquals = _deprecate(assertEqual)
+ failIfEqual = assertNotEquals = _deprecate(assertNotEqual)
+ failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual)
+ failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual)
+ failUnless = assert_ = _deprecate(assertTrue)
+ failUnlessRaises = _deprecate(assertRaises)
+ failIf = _deprecate(assertFalse)
+ assertRaisesRegexp = _deprecate(assertRaisesRegex)
+ assertRegexpMatches = _deprecate(assertRegex)
+
+
+
class FunctionTestCase(TestCase):
"""A test case that wraps a test function.
Modified: python/branches/py3k/Lib/unittest/test/test_assertions.py
==============================================================================
--- python/branches/py3k/Lib/unittest/test/test_assertions.py (original)
+++ python/branches/py3k/Lib/unittest/test/test_assertions.py Wed Dec 1 03:32:32 2010
@@ -92,15 +92,15 @@
else:
self.fail("assertRaises() didn't let exception pass through")
- def testAssertNotRegexpMatches(self):
- self.assertNotRegexpMatches('Ala ma kota', r'r+')
+ def testAssertNotRegexMatches(self):
+ self.assertNotRegexMatches('Ala ma kota', r'r+')
try:
- self.assertNotRegexpMatches('Ala ma kota', r'k.t', 'Message')
+ self.assertNotRegexMatches('Ala ma kota', r'k.t', 'Message')
except self.failureException as e:
self.assertIn("'kot'", e.args[0])
self.assertIn('Message', e.args[0])
else:
- self.fail('assertNotRegexpMatches should have failed.')
+ self.fail('assertNotRegexMatches should have failed.')
class TestLongMessage(unittest.TestCase):
@@ -153,15 +153,15 @@
test = self.testableTrue
return getattr(test, methodName)
- for i, expected_regexp in enumerate(errors):
+ for i, expected_regex in enumerate(errors):
testMethod = getMethod(i)
kwargs = {}
withMsg = i % 2
if withMsg:
kwargs = {"msg": "oops"}
- with self.assertRaisesRegexp(self.failureException,
- expected_regexp=expected_regexp):
+ with self.assertRaisesRegex(self.failureException,
+ expected_regex=expected_regex):
testMethod(*args, **kwargs)
def testAssertTrue(self):
Modified: python/branches/py3k/Lib/unittest/test/test_case.py
==============================================================================
--- python/branches/py3k/Lib/unittest/test/test_case.py (original)
+++ python/branches/py3k/Lib/unittest/test/test_case.py Wed Dec 1 03:32:32 2010
@@ -872,44 +872,44 @@
self.assertIsNotNone('DjZoPloGears on Rails')
self.assertRaises(self.failureException, self.assertIsNotNone, None)
- def testAssertRegexpMatches(self):
- self.assertRegexpMatches('asdfabasdf', r'ab+')
- self.assertRaises(self.failureException, self.assertRegexpMatches,
+ def testAssertRegex(self):
+ self.assertRegex('asdfabasdf', r'ab+')
+ self.assertRaises(self.failureException, self.assertRegex,
'saaas', r'aaaa')
- def testAssertRaisesRegexp(self):
+ def testAssertRaisesRegex(self):
class ExceptionMock(Exception):
pass
def Stub():
raise ExceptionMock('We expect')
- self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
- self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
+ self.assertRaisesRegex(ExceptionMock, re.compile('expect$'), Stub)
+ self.assertRaisesRegex(ExceptionMock, 'expect$', Stub)
- def testAssertNotRaisesRegexp(self):
- self.assertRaisesRegexp(
+ def testAssertNotRaisesRegex(self):
+ self.assertRaisesRegex(
self.failureException, '^Exception not raised by <lambda>$',
- self.assertRaisesRegexp, Exception, re.compile('x'),
+ self.assertRaisesRegex, Exception, re.compile('x'),
lambda: None)
- self.assertRaisesRegexp(
+ self.assertRaisesRegex(
self.failureException, '^Exception not raised by <lambda>$',
- self.assertRaisesRegexp, Exception, 'x',
+ self.assertRaisesRegex, Exception, 'x',
lambda: None)
- def testAssertRaisesRegexpMismatch(self):
+ def testAssertRaisesRegexMismatch(self):
def Stub():
raise Exception('Unexpected')
- self.assertRaisesRegexp(
+ self.assertRaisesRegex(
self.failureException,
r'"\^Expected\$" does not match "Unexpected"',
- self.assertRaisesRegexp, Exception, '^Expected$',
+ self.assertRaisesRegex, Exception, '^Expected$',
Stub)
- self.assertRaisesRegexp(
+ self.assertRaisesRegex(
self.failureException,
r'"\^Expected\$" does not match "Unexpected"',
- self.assertRaisesRegexp, Exception,
+ self.assertRaisesRegex, Exception,
re.compile('^Expected$'), Stub)
def testAssertRaisesExcValue(self):
@@ -993,26 +993,26 @@
with self.assertWarns(DeprecationWarning):
_runtime_warn()
- def testAssertWarnsRegexpCallable(self):
+ def testAssertWarnsRegexCallable(self):
def _runtime_warn(msg):
warnings.warn(msg, RuntimeWarning)
- self.assertWarnsRegexp(RuntimeWarning, "o+",
- _runtime_warn, "foox")
+ self.assertWarnsRegex(RuntimeWarning, "o+",
+ _runtime_warn, "foox")
# Failure when no warning is triggered
with self.assertRaises(self.failureException):
- self.assertWarnsRegexp(RuntimeWarning, "o+",
- lambda: 0)
+ self.assertWarnsRegex(RuntimeWarning, "o+",
+ lambda: 0)
# Failure when another warning is triggered
with warnings.catch_warnings():
# Force default filter (in case tests are run with -We)
warnings.simplefilter("default", RuntimeWarning)
with self.assertRaises(self.failureException):
- self.assertWarnsRegexp(DeprecationWarning, "o+",
- _runtime_warn, "foox")
+ self.assertWarnsRegex(DeprecationWarning, "o+",
+ _runtime_warn, "foox")
# Failure when message doesn't match
with self.assertRaises(self.failureException):
- self.assertWarnsRegexp(RuntimeWarning, "o+",
- _runtime_warn, "barz")
+ self.assertWarnsRegex(RuntimeWarning, "o+",
+ _runtime_warn, "barz")
# A little trickier: we ask RuntimeWarnings to be raised, and then
# check for some of them. It is implementation-defined whether
# non-matching RuntimeWarnings are simply re-raised, or produce a
@@ -1020,15 +1020,15 @@
with warnings.catch_warnings():
warnings.simplefilter("error", RuntimeWarning)
with self.assertRaises((RuntimeWarning, self.failureException)):
- self.assertWarnsRegexp(RuntimeWarning, "o+",
- _runtime_warn, "barz")
+ self.assertWarnsRegex(RuntimeWarning, "o+",
+ _runtime_warn, "barz")
- def testAssertWarnsRegexpContext(self):
- # Same as above, but with assertWarnsRegexp as a context manager
+ def testAssertWarnsRegexContext(self):
+ # Same as above, but with assertWarnsRegex as a context manager
def _runtime_warn(msg):
warnings.warn(msg, RuntimeWarning)
_runtime_warn_lineno = inspect.getsourcelines(_runtime_warn)[1]
- with self.assertWarnsRegexp(RuntimeWarning, "o+") as cm:
+ with self.assertWarnsRegex(RuntimeWarning, "o+") as cm:
_runtime_warn("foox")
self.assertIsInstance(cm.warning, RuntimeWarning)
self.assertEqual(cm.warning.args[0], "foox")
@@ -1036,18 +1036,18 @@
self.assertEqual(cm.lineno, _runtime_warn_lineno + 1)
# Failure when no warning is triggered
with self.assertRaises(self.failureException):
- with self.assertWarnsRegexp(RuntimeWarning, "o+"):
+ with self.assertWarnsRegex(RuntimeWarning, "o+"):
pass
# Failure when another warning is triggered
with warnings.catch_warnings():
# Force default filter (in case tests are run with -We)
warnings.simplefilter("default", RuntimeWarning)
with self.assertRaises(self.failureException):
- with self.assertWarnsRegexp(DeprecationWarning, "o+"):
+ with self.assertWarnsRegex(DeprecationWarning, "o+"):
_runtime_warn("foox")
# Failure when message doesn't match
with self.assertRaises(self.failureException):
- with self.assertWarnsRegexp(RuntimeWarning, "o+"):
+ with self.assertWarnsRegex(RuntimeWarning, "o+"):
_runtime_warn("barz")
# A little trickier: we ask RuntimeWarnings to be raised, and then
# check for some of them. It is implementation-defined whether
@@ -1056,7 +1056,7 @@
with warnings.catch_warnings():
warnings.simplefilter("error", RuntimeWarning)
with self.assertRaises((RuntimeWarning, self.failureException)):
- with self.assertWarnsRegexp(RuntimeWarning, "o+"):
+ with self.assertWarnsRegex(RuntimeWarning, "o+"):
_runtime_warn("barz")
def testDeprecatedMethodNames(self):
@@ -1078,7 +1078,9 @@
(self.assert_, (True,)),
(self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')),
(self.failIf, (False,)),
- (self.assertSameElements, ([1, 1, 2, 3], [1, 2, 3]))
+ (self.assertSameElements, ([1, 1, 2, 3], [1, 2, 3])),
+ (self.assertRaisesRegexp, (KeyError, 'foo', lambda: {}['foo'])),
+ (self.assertRegexpMatches, ('bar', 'bar')),
)
for meth, args in old:
with self.assertWarns(DeprecationWarning):
Modified: python/branches/py3k/Lib/unittest/test/test_discovery.py
==============================================================================
--- python/branches/py3k/Lib/unittest/test/test_discovery.py (original)
+++ python/branches/py3k/Lib/unittest/test/test_discovery.py Wed Dec 1 03:32:32 2010
@@ -354,7 +354,7 @@
expected_dir = os.path.abspath('foo')
msg = re.escape(r"'foo' module incorrectly imported from %r. Expected %r. "
"Is this module globally installed?" % (mod_dir, expected_dir))
- self.assertRaisesRegexp(
+ self.assertRaisesRegex(
ImportError, '^%s$' % msg, loader.discover,
start_dir='foo', pattern='foo.py'
)
Modified: python/branches/py3k/Lib/unittest/test/test_loader.py
==============================================================================
--- python/branches/py3k/Lib/unittest/test/test_loader.py (original)
+++ python/branches/py3k/Lib/unittest/test/test_loader.py Wed Dec 1 03:32:32 2010
@@ -186,7 +186,7 @@
self.assertEqual(suite.countTestCases(), 1)
test = list(suite)[0]
- self.assertRaisesRegexp(TypeError, "some failure", test.m)
+ self.assertRaisesRegex(TypeError, "some failure", test.m)
################################################################
### /Tests for TestLoader.loadTestsFromModule()
Modified: python/branches/py3k/Lib/unittest/test/test_setups.py
==============================================================================
--- python/branches/py3k/Lib/unittest/test/test_setups.py (original)
+++ python/branches/py3k/Lib/unittest/test/test_setups.py Wed Dec 1 03:32:32 2010
@@ -500,7 +500,7 @@
messages = ('setUpModule', 'tearDownModule', 'setUpClass', 'tearDownClass', 'test_something')
for phase, msg in enumerate(messages):
- with self.assertRaisesRegexp(Exception, msg):
+ with self.assertRaisesRegex(Exception, msg):
suite.debug()
if __name__ == '__main__':
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Wed Dec 1 03:32:32 2010
@@ -46,6 +46,9 @@
Library
-------
+- Issue #10273: Rename `assertRegexpMatches` and `assertRaisesRegexp` to
+ `assertRegex` and `assertRaisesRegex`.
+
- Issue #10535: Enable silenced warnings in unittest by default.
- Issue #9873: The URL parsing functions in urllib.parse now accept
1
0

r86909 - in python/branches/py3k: Lib/unittest/test/test_runner.py Misc/NEWS
by ezio.melotti Dec. 1, 2010
by ezio.melotti Dec. 1, 2010
Dec. 1, 2010
Author: ezio.melotti
Date: Wed Dec 1 02:45:53 2010
New Revision: 86909
Log:
Fix test failure in debug builds and add NEWS entry for r86908
Modified:
python/branches/py3k/Lib/unittest/test/test_runner.py
python/branches/py3k/Misc/NEWS
Modified: python/branches/py3k/Lib/unittest/test/test_runner.py
==============================================================================
--- python/branches/py3k/Lib/unittest/test/test_runner.py (original)
+++ python/branches/py3k/Lib/unittest/test/test_runner.py Wed Dec 1 02:45:53 2010
@@ -266,7 +266,7 @@
# no args -> all the warnings are printed, unittest warnings only once
p = subprocess.Popen([sys.executable, '_test_warnings.py'], **opts)
out, err = get_parse_out_err(p)
- self.assertEqual(err[-1], b'OK')
+ self.assertIn(b'OK', err)
# check that the total number of warnings in the output is correct
self.assertEqual(len(out), 12)
# check that the numbers of the different kind of warnings is correct
@@ -287,7 +287,7 @@
for args in args_list:
p = subprocess.Popen(args, **opts)
out, err = get_parse_out_err(p)
- self.assertEqual(err[-1], b'OK')
+ self.assertIn(b'OK', err)
self.assertEqual(len(out), 0)
@@ -296,7 +296,7 @@
p = subprocess.Popen([sys.executable, '_test_warnings.py', 'always'],
**opts)
out, err = get_parse_out_err(p)
- self.assertEqual(err[-1], b'OK')
+ self.assertIn(b'OK', err)
self.assertEqual(len(out), 14)
for msg in [b'dw', b'iw', b'uw', b'rw']:
self.assertEqual(out.count(msg), 3)
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Wed Dec 1 02:45:53 2010
@@ -46,6 +46,8 @@
Library
-------
+- Issue #10535: Enable silenced warnings in unittest by default.
+
- Issue #9873: The URL parsing functions in urllib.parse now accept
ASCII byte sequences as input in addition to character strings.
1
0

Dec. 1, 2010
Author: ezio.melotti
Date: Wed Dec 1 01:56:10 2010
New Revision: 86908
Log:
#10535: Enable silenced warnings in unittest by default
Added:
python/branches/py3k/Lib/unittest/test/_test_warnings.py
Modified:
python/branches/py3k/Doc/library/unittest.rst
python/branches/py3k/Doc/library/warnings.rst
python/branches/py3k/Lib/unittest/main.py
python/branches/py3k/Lib/unittest/runner.py
python/branches/py3k/Lib/unittest/test/test_break.py
python/branches/py3k/Lib/unittest/test/test_program.py
python/branches/py3k/Lib/unittest/test/test_runner.py
Modified: python/branches/py3k/Doc/library/unittest.rst
==============================================================================
--- python/branches/py3k/Doc/library/unittest.rst (original)
+++ python/branches/py3k/Doc/library/unittest.rst Wed Dec 1 01:56:10 2010
@@ -1845,12 +1845,21 @@
instead of repeatedly creating new instances.
-.. class:: TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1, runnerclass=None)
+.. class:: TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1, runnerclass=None, warnings=None)
A basic test runner implementation which prints results on standard error. It
has a few configurable parameters, but is essentially very simple. Graphical
applications which run test suites should provide alternate implementations.
+ By default this runner shows :exc:`DeprecationWarning`,
+ :exc:`PendingDeprecationWarning`, and :exc:`ImportWarning` even if they are
+ :ref:`ignored by default <warning-ignored>`. Deprecation warnings caused by
+ :ref:`deprecated unittest methods <deprecated-aliases>` are also
+ special-cased and, when the warning filters are ``'default'`` or ``'always'``,
+ they will appear only once per-module, in order to avoid too many warning
+ messages. This behavior can be overridden using the :option`-Wd` or
+ :option:`-Wa` options and leaving *warnings* to ``None``.
+
.. method:: _makeResult()
This method returns the instance of ``TestResult`` used by :meth:`run`.
@@ -1864,7 +1873,9 @@
stream, descriptions, verbosity
-.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=unittest.loader.defaultTestLoader, exit=True, verbosity=1, failfast=None, catchbreak=None, buffer=None)
+ .. versionchanged:: 3.2 Added the ``warnings`` argument
+
+.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=unittest.loader.defaultTestLoader, exit=True, verbosity=1, failfast=None, catchbreak=None, buffer=None, warnings=None)
A command-line program that runs a set of tests; this is primarily for making
test modules conveniently executable. The simplest use for this function is to
@@ -1893,12 +1904,17 @@
The ``failfast``, ``catchbreak`` and ``buffer`` parameters have the same
effect as the same-name `command-line options`_.
+ The *warning* argument specifies the :ref:`warning filter <warning-filter>`
+ that should be used while running the tests. If it's not specified, it will
+ remain ``None`` if a :option:`-W` option is passed to :program:`python`,
+ otherwise it will be set to ``'default'``.
+
Calling ``main`` actually returns an instance of the ``TestProgram`` class.
This stores the result of the tests run as the ``result`` attribute.
.. versionchanged:: 3.2
- The ``exit``, ``verbosity``, ``failfast``, ``catchbreak`` and ``buffer``
- parameters were added.
+ The ``exit``, ``verbosity``, ``failfast``, ``catchbreak``, ``buffer``,
+ and ``warnings`` parameters were added.
load_tests Protocol
Modified: python/branches/py3k/Doc/library/warnings.rst
==============================================================================
--- python/branches/py3k/Doc/library/warnings.rst (original)
+++ python/branches/py3k/Doc/library/warnings.rst Wed Dec 1 01:56:10 2010
@@ -249,6 +249,8 @@
entries from the warnings list before each new operation).
+.. _warning-ignored:
+
Updating Code For New Versions of Python
----------------------------------------
@@ -279,6 +281,9 @@
developer want to be notified that your code is using a deprecated module, to a
user this information is essentially noise and provides no benefit to them.
+The :mod:`unittest` module has been also updated to use the ``'default'``
+filter while running tests.
+
.. _warning-functions:
Modified: python/branches/py3k/Lib/unittest/main.py
==============================================================================
--- python/branches/py3k/Lib/unittest/main.py (original)
+++ python/branches/py3k/Lib/unittest/main.py Wed Dec 1 01:56:10 2010
@@ -67,12 +67,12 @@
USAGE = USAGE_FROM_MODULE
# defaults for testing
- failfast = catchbreak = buffer = progName = None
+ failfast = catchbreak = buffer = progName = warnings = None
def __init__(self, module='__main__', defaultTest=None, argv=None,
testRunner=None, testLoader=loader.defaultTestLoader,
exit=True, verbosity=1, failfast=None, catchbreak=None,
- buffer=None):
+ buffer=None, warnings=None):
if isinstance(module, str):
self.module = __import__(module)
for part in module.split('.')[1:]:
@@ -87,6 +87,18 @@
self.catchbreak = catchbreak
self.verbosity = verbosity
self.buffer = buffer
+ if warnings is None and not sys.warnoptions:
+ # even if DreprecationWarnings are ignored by default
+ # print them anyway unless other warnings settings are
+ # specified by the warnings arg or the -W python flag
+ self.warnings = 'default'
+ else:
+ # here self.warnings is set either to the value passed
+ # to the warnings args or to None.
+ # If the user didn't pass a value self.warnings will
+ # be None. This means that the behavior is unchanged
+ # and depends on the values passed to -W.
+ self.warnings = warnings
self.defaultTest = defaultTest
self.testRunner = testRunner
self.testLoader = testLoader
@@ -220,7 +232,8 @@
try:
testRunner = self.testRunner(verbosity=self.verbosity,
failfast=self.failfast,
- buffer=self.buffer)
+ buffer=self.buffer,
+ warnings=self.warnings)
except TypeError:
# didn't accept the verbosity, buffer or failfast arguments
testRunner = self.testRunner()
Modified: python/branches/py3k/Lib/unittest/runner.py
==============================================================================
--- python/branches/py3k/Lib/unittest/runner.py (original)
+++ python/branches/py3k/Lib/unittest/runner.py Wed Dec 1 01:56:10 2010
@@ -2,6 +2,7 @@
import sys
import time
+import warnings
from . import result
from .signals import registerResult
@@ -125,12 +126,13 @@
resultclass = TextTestResult
def __init__(self, stream=sys.stderr, descriptions=True, verbosity=1,
- failfast=False, buffer=False, resultclass=None):
+ failfast=False, buffer=False, resultclass=None, warnings=None):
self.stream = _WritelnDecorator(stream)
self.descriptions = descriptions
self.verbosity = verbosity
self.failfast = failfast
self.buffer = buffer
+ self.warnings = warnings
if resultclass is not None:
self.resultclass = resultclass
@@ -143,17 +145,30 @@
registerResult(result)
result.failfast = self.failfast
result.buffer = self.buffer
- startTime = time.time()
- startTestRun = getattr(result, 'startTestRun', None)
- if startTestRun is not None:
- startTestRun()
- try:
- test(result)
- finally:
- stopTestRun = getattr(result, 'stopTestRun', None)
- if stopTestRun is not None:
- stopTestRun()
- stopTime = time.time()
+ with warnings.catch_warnings():
+ if self.warnings:
+ # if self.warnings is set, use it to filter all the warnings
+ warnings.simplefilter(self.warnings)
+ # if the filter is 'default' or 'always', special-case the
+ # warnings from the deprecated unittest methods to show them
+ # no more than once per module, because they can be fairly
+ # noisy. The -Wd and -Wa flags can be used to bypass this
+ # only when self.warnings is None.
+ if self.warnings in ['default', 'always']:
+ warnings.filterwarnings('module',
+ category=DeprecationWarning,
+ message='Please use assert\w+ instead.')
+ startTime = time.time()
+ startTestRun = getattr(result, 'startTestRun', None)
+ if startTestRun is not None:
+ startTestRun()
+ try:
+ test(result)
+ finally:
+ stopTestRun = getattr(result, 'stopTestRun', None)
+ if stopTestRun is not None:
+ stopTestRun()
+ stopTime = time.time()
timeTaken = stopTime - startTime
result.printErrors()
if hasattr(result, 'separator2'):
Added: python/branches/py3k/Lib/unittest/test/_test_warnings.py
==============================================================================
--- (empty file)
+++ python/branches/py3k/Lib/unittest/test/_test_warnings.py Wed Dec 1 01:56:10 2010
@@ -0,0 +1,74 @@
+# helper module for test_runner.Test_TextTestRunner.test_warnings
+
+"""
+This module has a number of tests that raise different kinds of warnings.
+When the tests are run, the warnings are caught and their messages are printed
+to stdout. This module also accepts an arg that is then passed to
+unittest.main to affect the behavior of warnings.
+Test_TextTestRunner.test_warnings executes this script with different
+combinations of warnings args and -W flags and check that the output is correct.
+See #10535.
+"""
+
+import io
+import sys
+import unittest
+import warnings
+
+def warnfun():
+ warnings.warn('rw', RuntimeWarning)
+
+class TestWarnings(unittest.TestCase):
+ # unittest warnings will be printed at most once per type (max one message
+ # for the fail* methods, and one for the assert* methods)
+ def test_assert(self):
+ self.assertEquals(2+2, 4)
+ self.assertEquals(2*2, 4)
+ self.assertEquals(2**2, 4)
+
+ def test_fail(self):
+ self.failUnless(1)
+ self.failUnless(True)
+
+ def test_other_unittest(self):
+ self.assertAlmostEqual(2+2, 4)
+ self.assertNotAlmostEqual(4+4, 2)
+
+ # these warnings are normally silenced, but they are printed in unittest
+ def test_deprecation(self):
+ warnings.warn('dw', DeprecationWarning)
+ warnings.warn('dw', DeprecationWarning)
+ warnings.warn('dw', DeprecationWarning)
+
+ def test_import(self):
+ warnings.warn('iw', ImportWarning)
+ warnings.warn('iw', ImportWarning)
+ warnings.warn('iw', ImportWarning)
+
+ # user warnings should always be printed
+ def test_warning(self):
+ warnings.warn('uw')
+ warnings.warn('uw')
+ warnings.warn('uw')
+
+ # these warnings come from the same place; they will be printed
+ # only once by default or three times if the 'always' filter is used
+ def test_function(self):
+
+ warnfun()
+ warnfun()
+ warnfun()
+
+
+
+if __name__ == '__main__':
+ with warnings.catch_warnings(record=True) as ws:
+ # if an arg is provided pass it to unittest.main as 'warnings'
+ if len(sys.argv) == 2:
+ unittest.main(exit=False, warnings=sys.argv.pop())
+ else:
+ unittest.main(exit=False)
+
+ # print all the warning messages collected
+ for w in ws:
+ print(w.message)
Modified: python/branches/py3k/Lib/unittest/test/test_break.py
==============================================================================
--- python/branches/py3k/Lib/unittest/test/test_break.py (original)
+++ python/branches/py3k/Lib/unittest/test/test_break.py Wed Dec 1 01:56:10 2010
@@ -209,7 +209,8 @@
self.assertEqual(FakeRunner.initArgs, [((), {'buffer': None,
'verbosity': verbosity,
- 'failfast': failfast})])
+ 'failfast': failfast,
+ 'warnings': None})])
self.assertEqual(FakeRunner.runArgs, [test])
self.assertEqual(p.result, result)
@@ -222,7 +223,8 @@
self.assertEqual(FakeRunner.initArgs, [((), {'buffer': None,
'verbosity': verbosity,
- 'failfast': failfast})])
+ 'failfast': failfast,
+ 'warnings': None})])
self.assertEqual(FakeRunner.runArgs, [test])
self.assertEqual(p.result, result)
Modified: python/branches/py3k/Lib/unittest/test/test_program.py
==============================================================================
--- python/branches/py3k/Lib/unittest/test/test_program.py (original)
+++ python/branches/py3k/Lib/unittest/test/test_program.py Wed Dec 1 01:56:10 2010
@@ -182,6 +182,27 @@
program.parseArgs([None, opt])
self.assertEqual(getattr(program, attr), not_none)
+ def testWarning(self):
+ """Test the warnings argument"""
+ # see #10535
+ class FakeTP(unittest.TestProgram):
+ def parseArgs(self, *args, **kw): pass
+ def runTests(self, *args, **kw): pass
+ warnoptions = sys.warnoptions
+ try:
+ sys.warnoptions[:] = []
+ # no warn options, no arg -> default
+ self.assertEqual(FakeTP().warnings, 'default')
+ # no warn options, w/ arg -> arg value
+ self.assertEqual(FakeTP(warnings='ignore').warnings, 'ignore')
+ sys.warnoptions[:] = ['somevalue']
+ # warn options, no arg -> None
+ # warn options, w/ arg -> arg value
+ self.assertEqual(FakeTP().warnings, None)
+ self.assertEqual(FakeTP(warnings='ignore').warnings, 'ignore')
+ finally:
+ sys.warnoptions[:] = warnoptions
+
def testRunTestsRunnerClass(self):
program = self.program
@@ -189,12 +210,14 @@
program.verbosity = 'verbosity'
program.failfast = 'failfast'
program.buffer = 'buffer'
+ program.warnings = 'warnings'
program.runTests()
self.assertEqual(FakeRunner.initArgs, {'verbosity': 'verbosity',
'failfast': 'failfast',
- 'buffer': 'buffer'})
+ 'buffer': 'buffer',
+ 'warnings': 'warnings'})
self.assertEqual(FakeRunner.test, 'test')
self.assertIs(program.result, RESULT)
Modified: python/branches/py3k/Lib/unittest/test/test_runner.py
==============================================================================
--- python/branches/py3k/Lib/unittest/test/test_runner.py (original)
+++ python/branches/py3k/Lib/unittest/test/test_runner.py Wed Dec 1 01:56:10 2010
@@ -1,5 +1,8 @@
import io
+import os
+import sys
import pickle
+import subprocess
import unittest
@@ -144,6 +147,7 @@
self.assertFalse(runner.failfast)
self.assertFalse(runner.buffer)
self.assertEqual(runner.verbosity, 1)
+ self.assertEqual(runner.warnings, None)
self.assertTrue(runner.descriptions)
self.assertEqual(runner.resultclass, unittest.TextTestResult)
@@ -244,3 +248,57 @@
expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
self.assertEqual(runner._makeResult(), expectedresult)
+
+ def test_warnings(self):
+ """
+ Check that warnings argument of TextTestRunner correctly affects the
+ behavior of the warnings.
+ """
+ # see #10535 and the _test_warnings file for more information
+
+ def get_parse_out_err(p):
+ return [b.splitlines() for b in p.communicate()]
+ opts = dict(stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ cwd=os.path.dirname(__file__))
+ ae_msg = b'Please use assertEqual instead.'
+ at_msg = b'Please use assertTrue instead.'
+
+ # no args -> all the warnings are printed, unittest warnings only once
+ p = subprocess.Popen([sys.executable, '_test_warnings.py'], **opts)
+ out, err = get_parse_out_err(p)
+ self.assertEqual(err[-1], b'OK')
+ # check that the total number of warnings in the output is correct
+ self.assertEqual(len(out), 12)
+ # check that the numbers of the different kind of warnings is correct
+ for msg in [b'dw', b'iw', b'uw']:
+ self.assertEqual(out.count(msg), 3)
+ for msg in [ae_msg, at_msg, b'rw']:
+ self.assertEqual(out.count(msg), 1)
+
+ args_list = (
+ # passing 'ignore' as warnings arg -> no warnings
+ [sys.executable, '_test_warnings.py', 'ignore'],
+ # -W doesn't affect the result if the arg is passed
+ [sys.executable, '-Wa', '_test_warnings.py', 'ignore'],
+ # -W affects the result if the arg is not passed
+ [sys.executable, '-Wi', '_test_warnings.py']
+ )
+ # in all these cases no warnings are printed
+ for args in args_list:
+ p = subprocess.Popen(args, **opts)
+ out, err = get_parse_out_err(p)
+ self.assertEqual(err[-1], b'OK')
+ self.assertEqual(len(out), 0)
+
+
+ # passing 'always' as warnings arg -> all the warnings printed,
+ # unittest warnings only once
+ p = subprocess.Popen([sys.executable, '_test_warnings.py', 'always'],
+ **opts)
+ out, err = get_parse_out_err(p)
+ self.assertEqual(err[-1], b'OK')
+ self.assertEqual(len(out), 14)
+ for msg in [b'dw', b'iw', b'uw', b'rw']:
+ self.assertEqual(out.count(msg), 3)
+ for msg in [ae_msg, at_msg]:
+ self.assertEqual(out.count(msg), 1)
1
0

r86907 - in python/branches/py3k: Doc/library/functools.rst Lib/functools.py
by raymond.hettinger Dec. 1, 2010
by raymond.hettinger Dec. 1, 2010
Dec. 1, 2010
Author: raymond.hettinger
Date: Wed Dec 1 01:47:56 2010
New Revision: 86907
Log:
Doc and docstring nits.
Modified:
python/branches/py3k/Doc/library/functools.rst
python/branches/py3k/Lib/functools.py
Modified: python/branches/py3k/Doc/library/functools.rst
==============================================================================
--- python/branches/py3k/Doc/library/functools.rst (original)
+++ python/branches/py3k/Doc/library/functools.rst Wed Dec 1 01:47:56 2010
@@ -91,6 +91,10 @@
.. versionadded:: 3.2
+ .. seealso::
+
+ Recipe for a `plain cache without the LRU feature
+ <http://code.activestate.com/recipes/577479-simple-caching-decorator/>`_.
.. decorator:: total_ordering
Modified: python/branches/py3k/Lib/functools.py
==============================================================================
--- python/branches/py3k/Lib/functools.py (original)
+++ python/branches/py3k/Lib/functools.py Wed Dec 1 01:47:56 2010
@@ -121,9 +121,9 @@
Arguments to the cached function must be hashable.
- View the cache statistics named tuple (maxsize, size, hits, misses) with
+ View the cache statistics named tuple (hits, misses, maxsize, currsize) with
f.cache_info(). Clear the cache and statistics with f.cache_clear().
- And access the underlying function with f.__wrapped__.
+ Access the underlying function with f.__wrapped__.
See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
1
0