index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
41,848 |
wield.bunch.bunch
|
__hash__
| null |
def __hash__(self):
try:
return self.__dict__["__hash"]
except KeyError:
pass
d2 = dict(self._mydict)
for k in self.hash_ignore:
d2.pop(k)
l = tuple(sorted(d2.items()))
self.__dict__["__hash"] = hash(l)
return self.__dict__["__hash"]
|
(self)
|
41,849 |
wield.bunch.bunch
|
__init__
| null |
def __init__(self, inner_dict=None, hash_ignore=(), *args, **kwds):
if inner_dict is None or args or kwds:
if args:
_mydict = dict(inner_dict, *args, **kwds)
else:
_mydict = dict(**kwds)
else:
_mydict = dict(inner_dict)
self.__dict__["hash_ignore"] = set(hash_ignore)
self.__dict__["_mydict"] = _mydict
return
|
(self, inner_dict=None, hash_ignore=(), *args, **kwds)
|
41,855 |
wield.bunch.bunch
|
__pop__
| null |
def __pop__(self, key):
raise RuntimeError("Bunch is Frozen")
|
(self, key)
|
41,856 |
wield.bunch.bunch
|
__popitem__
| null |
def __popitem__(self, key):
raise RuntimeError("Bunch is Frozen")
|
(self, key)
|
41,858 |
wield.bunch.bunch
|
__setattr__
| null |
def __setattr__(self, key, item):
raise RuntimeError("Bunch is Frozen")
|
(self, key, item)
|
41,859 |
wield.bunch.bunch
|
__setitem__
| null |
def __setitem__(self, key, item):
raise RuntimeError("Bunch is Frozen")
|
(self, key, item)
|
41,862 |
wield.bunch.bunch
|
_insertion_hack
|
Allows one to insert an item even after construction. This violates the
"frozen" immutability property, but allows constructing FrozenBunch's
that link to each other. This should only be done immediately after
construction, before hash is ever called
|
def _insertion_hack(self, key, item):
"""
Allows one to insert an item even after construction. This violates the
"frozen" immutability property, but allows constructing FrozenBunch's
that link to each other. This should only be done immediately after
construction, before hash is ever called
"""
self._mydict[key] = item
|
(self, key, item)
|
41,879 |
rfc3339
|
LocalTimeTestCase
|
Test the use of the timezone saved locally. Since it is hard to test using
doctest.
|
class LocalTimeTestCase(unittest.TestCase):
'''
Test the use of the timezone saved locally. Since it is hard to test using
doctest.
'''
def setUp(self):
local_utcoffset = _utc_offset(datetime.now(),
use_system_timezone=True)
self.local_utcoffset = timedelta(seconds=local_utcoffset)
self.local_timezone = _timezone(local_utcoffset)
def test_datetime(self):
d = datetime.now()
self.assertEqual(rfc3339(d),
d.strftime('%Y-%m-%dT%H:%M:%S') + self.local_timezone)
def test_datetime_timezone(self):
class FixedNoDst(tzinfo):
'A timezone info with fixed offset, not DST'
def utcoffset(self, dt):
return timedelta(hours=2, minutes=30)
def dst(self, dt):
return None
fixed_no_dst = FixedNoDst()
class Fixed(FixedNoDst):
'A timezone info with DST'
def utcoffset(self, dt):
return timedelta(hours=3, minutes=15)
def dst(self, dt):
return timedelta(hours=3, minutes=15)
fixed = Fixed()
d = datetime.now().replace(tzinfo=fixed_no_dst)
timezone = _timezone(_timedelta_to_seconds(fixed_no_dst.\
utcoffset(None)))
self.assertEqual(rfc3339(d),
d.strftime('%Y-%m-%dT%H:%M:%S') + timezone)
d = datetime.now().replace(tzinfo=fixed)
timezone = _timezone(_timedelta_to_seconds(fixed.dst(None)))
self.assertEqual(rfc3339(d),
d.strftime('%Y-%m-%dT%H:%M:%S') + timezone)
def test_datetime_utc(self):
d = datetime.now()
d_utc = d - self.local_utcoffset
self.assertEqual(rfc3339(d, utc=True),
d_utc.strftime('%Y-%m-%dT%H:%M:%SZ'))
def test_date(self):
d = date.today()
self.assertEqual(rfc3339(d),
d.strftime('%Y-%m-%dT%H:%M:%S') + self.local_timezone)
def test_date_utc(self):
d = date.today()
# Convert `date` to `datetime`, since `date` ignores seconds and hours
# in timedeltas:
# >>> date(2008, 9, 7) + timedelta(hours=23)
# date(2008, 9, 7)
d_utc = datetime(*d.timetuple()[:3]) - self.local_utcoffset
self.assertEqual(rfc3339(d, utc=True),
d_utc.strftime('%Y-%m-%dT%H:%M:%SZ'))
def test_timestamp(self):
d = time.time()
self.assertEqual(
rfc3339(d),
datetime.fromtimestamp(d).
strftime('%Y-%m-%dT%H:%M:%S') + self.local_timezone)
def test_timestamp_utc(self):
d = time.time()
# utc -> local timezone
d_utc = datetime.utcfromtimestamp(d) + self.local_utcoffset
self.assertEqual(rfc3339(d),
(d_utc.strftime('%Y-%m-%dT%H:%M:%S') +
self.local_timezone))
def test_before_1970(self):
d = date(1885, 1, 4)
self.assertTrue(rfc3339(d).startswith('1885-01-04T00:00:00'))
self.assertEqual(rfc3339(d, utc=True, use_system_timezone=False),
'1885-01-04T00:00:00Z')
def test_1920(self):
d = date(1920, 2, 29)
x = rfc3339(d, utc=False, use_system_timezone=True)
self.assertTrue(x.startswith('1920-02-29T00:00:00'))
# If these tests start failing it probably means there was a policy change
# for the Pacific time zone.
# See http://en.wikipedia.org/wiki/Pacific_Time_Zone.
if 'PST' in time.tzname:
def testPDTChange(self):
'''Test Daylight saving change'''
# PDT switch happens at 2AM on March 14, 2010
# 1:59AM PST
self.assertEqual(rfc3339(datetime(2010, 3, 14, 1, 59)),
'2010-03-14T01:59:00-08:00')
# 3AM PDT
self.assertEqual(rfc3339(datetime(2010, 3, 14, 3, 0)),
'2010-03-14T03:00:00-07:00')
def testPSTChange(self):
'''Test Standard time change'''
# PST switch happens at 2AM on November 6, 2010
# 0:59AM PDT
self.assertEqual(rfc3339(datetime(2010, 11, 7, 0, 59)),
'2010-11-07T00:59:00-07:00')
# 1:00AM PST
# There's no way to have 1:00AM PST without a proper tzinfo
self.assertEqual(rfc3339(datetime(2010, 11, 7, 1, 0)),
'2010-11-07T01:00:00-07:00')
def test_millisecond(self):
x = datetime(2018, 9, 20, 13, 11, 21, 123000)
self.assertEqual(
format_millisecond(
datetime(2018, 9, 20, 13, 11, 21, 123000),
utc=True,
use_system_timezone=False),
'2018-09-20T13:11:21.123Z')
def test_microsecond(self):
x = datetime(2018, 9, 20, 13, 11, 21, 12345)
self.assertEqual(
format_microsecond(
datetime(2018, 9, 20, 13, 11, 21, 12345),
utc=True,
use_system_timezone=False),
'2018-09-20T13:11:21.012345Z')
|
(methodName='runTest')
|
41,880 |
unittest.case
|
__call__
| null |
def __call__(self, *args, **kwds):
return self.run(*args, **kwds)
|
(self, *args, **kwds)
|
41,881 |
unittest.case
|
__eq__
| null |
def __eq__(self, other):
if type(self) is not type(other):
return NotImplemented
return self._testMethodName == other._testMethodName
|
(self, other)
|
41,882 |
unittest.case
|
__hash__
| null |
def __hash__(self):
return hash((type(self), self._testMethodName))
|
(self)
|
41,883 |
unittest.case
|
__init__
|
Create an instance of the class that will use the named test
method when executed. Raises a ValueError if the instance does
not have a method with the specified name.
|
def __init__(self, methodName='runTest'):
"""Create an instance of the class that will use the named test
method when executed. Raises a ValueError if the instance does
not have a method with the specified name.
"""
self._testMethodName = methodName
self._outcome = None
self._testMethodDoc = 'No test'
try:
testMethod = getattr(self, methodName)
except AttributeError:
if methodName != 'runTest':
# we allow instantiation with no explicit method name
# but not an *incorrect* or missing method name
raise ValueError("no such test method in %s: %s" %
(self.__class__, methodName))
else:
self._testMethodDoc = testMethod.__doc__
self._cleanups = []
self._subtest = None
# Map types to custom assertEqual functions that will compare
# instances of said type in more detail to generate a more useful
# error message.
self._type_equality_funcs = {}
self.addTypeEqualityFunc(dict, 'assertDictEqual')
self.addTypeEqualityFunc(list, 'assertListEqual')
self.addTypeEqualityFunc(tuple, 'assertTupleEqual')
self.addTypeEqualityFunc(set, 'assertSetEqual')
self.addTypeEqualityFunc(frozenset, 'assertSetEqual')
self.addTypeEqualityFunc(str, 'assertMultiLineEqual')
|
(self, methodName='runTest')
|
41,884 |
unittest.case
|
__repr__
| null |
def __repr__(self):
return "<%s testMethod=%s>" % \
(strclass(self.__class__), self._testMethodName)
|
(self)
|
41,885 |
unittest.case
|
__str__
| null |
def __str__(self):
return "%s (%s)" % (self._testMethodName, strclass(self.__class__))
|
(self)
|
41,886 |
unittest.case
|
_addExpectedFailure
| null |
def _addExpectedFailure(self, result, exc_info):
try:
addExpectedFailure = result.addExpectedFailure
except AttributeError:
warnings.warn("TestResult has no addExpectedFailure method, reporting as passes",
RuntimeWarning)
result.addSuccess(self)
else:
addExpectedFailure(self, exc_info)
|
(self, result, exc_info)
|
41,887 |
unittest.case
|
_addSkip
| null |
def _addSkip(self, result, test_case, reason):
addSkip = getattr(result, 'addSkip', None)
if addSkip is not None:
addSkip(test_case, reason)
else:
warnings.warn("TestResult has no addSkip method, skips not reported",
RuntimeWarning, 2)
result.addSuccess(test_case)
|
(self, result, test_case, reason)
|
41,888 |
unittest.case
|
_addUnexpectedSuccess
| null |
def _addUnexpectedSuccess(self, result):
try:
addUnexpectedSuccess = result.addUnexpectedSuccess
except AttributeError:
warnings.warn("TestResult has no addUnexpectedSuccess method, reporting as failure",
RuntimeWarning)
# We need to pass an actual exception and traceback to addFailure,
# otherwise the legacy result can choke.
try:
raise _UnexpectedSuccess from None
except _UnexpectedSuccess:
result.addFailure(self, sys.exc_info())
else:
addUnexpectedSuccess(self)
|
(self, result)
|
41,889 |
unittest.case
|
_baseAssertEqual
|
The default assertEqual implementation, not type specific.
|
def _baseAssertEqual(self, first, second, msg=None):
"""The default assertEqual implementation, not type specific."""
if not first == second:
standardMsg = '%s != %s' % _common_shorten_repr(first, second)
msg = self._formatMessage(msg, standardMsg)
raise self.failureException(msg)
|
(self, first, second, msg=None)
|
41,890 |
unittest.case
|
_callCleanup
| null |
def _callCleanup(self, function, /, *args, **kwargs):
function(*args, **kwargs)
|
(self, function, /, *args, **kwargs)
|
41,891 |
unittest.case
|
_callSetUp
| null |
def _callSetUp(self):
self.setUp()
|
(self)
|
41,892 |
unittest.case
|
_callTearDown
| null |
def _callTearDown(self):
self.tearDown()
|
(self)
|
41,893 |
unittest.case
|
_callTestMethod
| null |
def _callTestMethod(self, method):
method()
|
(self, method)
|
41,894 |
unittest.case
|
_deprecate
| null |
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
|
(original_func)
|
41,895 |
unittest.case
|
_feedErrorsToResult
| null |
def _feedErrorsToResult(self, result, errors):
for test, exc_info in errors:
if isinstance(test, _SubTest):
result.addSubTest(test.test_case, test, exc_info)
elif exc_info is not None:
if issubclass(exc_info[0], self.failureException):
result.addFailure(test, exc_info)
else:
result.addError(test, exc_info)
|
(self, result, errors)
|
41,896 |
unittest.case
|
_formatMessage
|
Honour the longMessage attribute when generating failure messages.
If longMessage is False this means:
* Use only an explicit message if it is provided
* Otherwise use the standard message for the assert
If longMessage is True:
* Use the standard message
* If an explicit message is provided, plus ' : ' and the explicit message
|
def _formatMessage(self, msg, standardMsg):
"""Honour the longMessage attribute when generating failure messages.
If longMessage is False this means:
* Use only an explicit message if it is provided
* Otherwise use the standard message for the assert
If longMessage is True:
* Use the standard message
* If an explicit message is provided, plus ' : ' and the explicit message
"""
if not self.longMessage:
return msg or standardMsg
if msg is None:
return standardMsg
try:
# don't switch to '{}' formatting in Python 2.X
# it changes the way unicode input is handled
return '%s : %s' % (standardMsg, msg)
except UnicodeDecodeError:
return '%s : %s' % (safe_repr(standardMsg), safe_repr(msg))
|
(self, msg, standardMsg)
|
41,897 |
unittest.case
|
_getAssertEqualityFunc
|
Get a detailed comparison function for the types of the two args.
Returns: A callable accepting (first, second, msg=None) that will
raise a failure exception if first != second with a useful human
readable error message for those types.
|
def _getAssertEqualityFunc(self, first, second):
"""Get a detailed comparison function for the types of the two args.
Returns: A callable accepting (first, second, msg=None) that will
raise a failure exception if first != second with a useful human
readable error message for those types.
"""
#
# NOTE(gregory.p.smith): I considered isinstance(first, type(second))
# and vice versa. I opted for the conservative approach in case
# subclasses are not intended to be compared in detail to their super
# class instances using a type equality func. This means testing
# subtypes won't automagically use the detailed comparison. Callers
# should use their type specific assertSpamEqual method to compare
# subclasses if the detailed comparison is desired and appropriate.
# See the discussion in http://bugs.python.org/issue2578.
#
if type(first) is type(second):
asserter = self._type_equality_funcs.get(type(first))
if asserter is not None:
if isinstance(asserter, str):
asserter = getattr(self, asserter)
return asserter
return self._baseAssertEqual
|
(self, first, second)
|
41,898 |
unittest.case
|
_truncateMessage
| null |
def _truncateMessage(self, message, diff):
max_diff = self.maxDiff
if max_diff is None or len(diff) <= max_diff:
return message + diff
return message + (DIFF_OMITTED % len(diff))
|
(self, message, diff)
|
41,899 |
unittest.case
|
addCleanup
|
Add a function, with arguments, to be called when the test is
completed. Functions added are called on a LIFO basis and are
called after tearDown on test failure or success.
Cleanup items are called even if setUp fails (unlike tearDown).
|
def addCleanup(self, function, /, *args, **kwargs):
"""Add a function, with arguments, to be called when the test is
completed. Functions added are called on a LIFO basis and are
called after tearDown on test failure or success.
Cleanup items are called even if setUp fails (unlike tearDown)."""
self._cleanups.append((function, args, kwargs))
|
(self, function, /, *args, **kwargs)
|
41,900 |
unittest.case
|
addTypeEqualityFunc
|
Add a type specific assertEqual style function to compare a type.
This method is for use by TestCase subclasses that need to register
their own type equality functions to provide nicer error messages.
Args:
typeobj: The data type to call this function on when both values
are of the same type in assertEqual().
function: The callable taking two arguments and an optional
msg= argument that raises self.failureException with a
useful error message when the two arguments are not equal.
|
def addTypeEqualityFunc(self, typeobj, function):
"""Add a type specific assertEqual style function to compare a type.
This method is for use by TestCase subclasses that need to register
their own type equality functions to provide nicer error messages.
Args:
typeobj: The data type to call this function on when both values
are of the same type in assertEqual().
function: The callable taking two arguments and an optional
msg= argument that raises self.failureException with a
useful error message when the two arguments are not equal.
"""
self._type_equality_funcs[typeobj] = function
|
(self, typeobj, function)
|
41,901 |
unittest.case
|
assertAlmostEqual
|
Fail if the two objects are unequal as determined by their
difference rounded to the given number of decimal places
(default 7) and comparing to zero, or by comparing that the
difference between the two objects is more than the given
delta.
Note that decimal places (from zero) are usually not the same
as significant digits (measured from the most significant digit).
If the two objects compare equal then they will automatically
compare almost equal.
|
def assertAlmostEqual(self, first, second, places=None, msg=None,
delta=None):
"""Fail if the two objects are unequal as determined by their
difference rounded to the given number of decimal places
(default 7) and comparing to zero, or by comparing that the
difference between the two objects is more than the given
delta.
Note that decimal places (from zero) are usually not the same
as significant digits (measured from the most significant digit).
If the two objects compare equal then they will automatically
compare almost equal.
"""
if first == second:
# shortcut
return
if delta is not None and places is not None:
raise TypeError("specify delta or places not both")
diff = abs(first - second)
if delta is not None:
if diff <= delta:
return
standardMsg = '%s != %s within %s delta (%s difference)' % (
safe_repr(first),
safe_repr(second),
safe_repr(delta),
safe_repr(diff))
else:
if places is None:
places = 7
if round(diff, places) == 0:
return
standardMsg = '%s != %s within %r places (%s difference)' % (
safe_repr(first),
safe_repr(second),
places,
safe_repr(diff))
msg = self._formatMessage(msg, standardMsg)
raise self.failureException(msg)
|
(self, first, second, places=None, msg=None, delta=None)
|
41,903 |
unittest.case
|
assertCountEqual
|
Asserts that two iterables have the same elements, the same number of
times, without regard to order.
self.assertEqual(Counter(list(first)),
Counter(list(second)))
Example:
- [0, 1, 1] and [1, 0, 1] compare equal.
- [0, 0, 1] and [0, 1] compare unequal.
|
def assertCountEqual(self, first, second, msg=None):
"""Asserts that two iterables have the same elements, the same number of
times, without regard to order.
self.assertEqual(Counter(list(first)),
Counter(list(second)))
Example:
- [0, 1, 1] and [1, 0, 1] compare equal.
- [0, 0, 1] and [0, 1] compare unequal.
"""
first_seq, second_seq = list(first), list(second)
try:
first = collections.Counter(first_seq)
second = collections.Counter(second_seq)
except TypeError:
# Handle case with unhashable elements
differences = _count_diff_all_purpose(first_seq, second_seq)
else:
if first == second:
return
differences = _count_diff_hashable(first_seq, second_seq)
if differences:
standardMsg = 'Element counts were not equal:\n'
lines = ['First has %d, Second has %d: %r' % diff for diff in differences]
diffMsg = '\n'.join(lines)
standardMsg = self._truncateMessage(standardMsg, diffMsg)
msg = self._formatMessage(msg, standardMsg)
self.fail(msg)
|
(self, first, second, msg=None)
|
41,904 |
unittest.case
|
assertDictContainsSubset
|
Checks whether dictionary is a superset of subset.
|
def assertDictContainsSubset(self, subset, dictionary, msg=None):
"""Checks whether dictionary is a superset of subset."""
warnings.warn('assertDictContainsSubset is deprecated',
DeprecationWarning,
stacklevel=2)
missing = []
mismatched = []
for key, value in subset.items():
if key not in dictionary:
missing.append(key)
elif value != dictionary[key]:
mismatched.append('%s, expected: %s, actual: %s' %
(safe_repr(key), safe_repr(value),
safe_repr(dictionary[key])))
if not (missing or mismatched):
return
standardMsg = ''
if missing:
standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in
missing)
if mismatched:
if standardMsg:
standardMsg += '; '
standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
self.fail(self._formatMessage(msg, standardMsg))
|
(self, subset, dictionary, msg=None)
|
41,905 |
unittest.case
|
assertDictEqual
| null |
def assertDictEqual(self, d1, d2, msg=None):
self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')
if d1 != d2:
standardMsg = '%s != %s' % _common_shorten_repr(d1, d2)
diff = ('\n' + '\n'.join(difflib.ndiff(
pprint.pformat(d1).splitlines(),
pprint.pformat(d2).splitlines())))
standardMsg = self._truncateMessage(standardMsg, diff)
self.fail(self._formatMessage(msg, standardMsg))
|
(self, d1, d2, msg=None)
|
41,906 |
unittest.case
|
assertEqual
|
Fail if the two objects are unequal as determined by the '=='
operator.
|
def assertEqual(self, first, second, msg=None):
"""Fail if the two objects are unequal as determined by the '=='
operator.
"""
assertion_func = self._getAssertEqualityFunc(first, second)
assertion_func(first, second, msg=msg)
|
(self, first, second, msg=None)
|
41,908 |
unittest.case
|
assertFalse
|
Check that the expression is false.
|
def assertFalse(self, expr, msg=None):
"""Check that the expression is false."""
if expr:
msg = self._formatMessage(msg, "%s is not false" % safe_repr(expr))
raise self.failureException(msg)
|
(self, expr, msg=None)
|
41,909 |
unittest.case
|
assertGreater
|
Just like self.assertTrue(a > b), but with a nicer default message.
|
def assertGreater(self, a, b, msg=None):
"""Just like self.assertTrue(a > b), but with a nicer default message."""
if not a > b:
standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b))
self.fail(self._formatMessage(msg, standardMsg))
|
(self, a, b, msg=None)
|
41,910 |
unittest.case
|
assertGreaterEqual
|
Just like self.assertTrue(a >= b), but with a nicer default message.
|
def assertGreaterEqual(self, a, b, msg=None):
"""Just like self.assertTrue(a >= b), but with a nicer default message."""
if not a >= b:
standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b))
self.fail(self._formatMessage(msg, standardMsg))
|
(self, a, b, msg=None)
|
41,911 |
unittest.case
|
assertIn
|
Just like self.assertTrue(a in b), but with a nicer default message.
|
def assertIn(self, member, container, msg=None):
"""Just like self.assertTrue(a in b), but with a nicer default message."""
if member not in container:
standardMsg = '%s not found in %s' % (safe_repr(member),
safe_repr(container))
self.fail(self._formatMessage(msg, standardMsg))
|
(self, member, container, msg=None)
|
41,912 |
unittest.case
|
assertIs
|
Just like self.assertTrue(a is b), but with a nicer default message.
|
def assertIs(self, expr1, expr2, msg=None):
"""Just like self.assertTrue(a is b), but with a nicer default message."""
if expr1 is not expr2:
standardMsg = '%s is not %s' % (safe_repr(expr1),
safe_repr(expr2))
self.fail(self._formatMessage(msg, standardMsg))
|
(self, expr1, expr2, msg=None)
|
41,913 |
unittest.case
|
assertIsInstance
|
Same as self.assertTrue(isinstance(obj, cls)), with a nicer
default message.
|
def assertIsInstance(self, obj, cls, msg=None):
"""Same as self.assertTrue(isinstance(obj, cls)), with a nicer
default message."""
if not isinstance(obj, cls):
standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls)
self.fail(self._formatMessage(msg, standardMsg))
|
(self, obj, cls, msg=None)
|
41,914 |
unittest.case
|
assertIsNone
|
Same as self.assertTrue(obj is None), with a nicer default message.
|
def assertIsNone(self, obj, msg=None):
"""Same as self.assertTrue(obj is None), with a nicer default message."""
if obj is not None:
standardMsg = '%s is not None' % (safe_repr(obj),)
self.fail(self._formatMessage(msg, standardMsg))
|
(self, obj, msg=None)
|
41,915 |
unittest.case
|
assertIsNot
|
Just like self.assertTrue(a is not b), but with a nicer default message.
|
def assertIsNot(self, expr1, expr2, msg=None):
"""Just like self.assertTrue(a is not b), but with a nicer default message."""
if expr1 is expr2:
standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),)
self.fail(self._formatMessage(msg, standardMsg))
|
(self, expr1, expr2, msg=None)
|
41,916 |
unittest.case
|
assertIsNotNone
|
Included for symmetry with assertIsNone.
|
def assertIsNotNone(self, obj, msg=None):
"""Included for symmetry with assertIsNone."""
if obj is None:
standardMsg = 'unexpectedly None'
self.fail(self._formatMessage(msg, standardMsg))
|
(self, obj, msg=None)
|
41,917 |
unittest.case
|
assertLess
|
Just like self.assertTrue(a < b), but with a nicer default message.
|
def assertLess(self, a, b, msg=None):
"""Just like self.assertTrue(a < b), but with a nicer default message."""
if not a < b:
standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b))
self.fail(self._formatMessage(msg, standardMsg))
|
(self, a, b, msg=None)
|
41,918 |
unittest.case
|
assertLessEqual
|
Just like self.assertTrue(a <= b), but with a nicer default message.
|
def assertLessEqual(self, a, b, msg=None):
"""Just like self.assertTrue(a <= b), but with a nicer default message."""
if not a <= b:
standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b))
self.fail(self._formatMessage(msg, standardMsg))
|
(self, a, b, msg=None)
|
41,919 |
unittest.case
|
assertListEqual
|
A list-specific equality assertion.
Args:
list1: The first list to compare.
list2: The second list to compare.
msg: Optional message to use on failure instead of a list of
differences.
|
def assertListEqual(self, list1, list2, msg=None):
"""A list-specific equality assertion.
Args:
list1: The first list to compare.
list2: The second list to compare.
msg: Optional message to use on failure instead of a list of
differences.
"""
self.assertSequenceEqual(list1, list2, msg, seq_type=list)
|
(self, list1, list2, msg=None)
|
41,920 |
unittest.case
|
assertLogs
|
Fail unless a log message of level *level* or higher is emitted
on *logger_name* or its children. If omitted, *level* defaults to
INFO and *logger* defaults to the root logger.
This method must be used as a context manager, and will yield
a recording object with two attributes: `output` and `records`.
At the end of the context manager, the `output` attribute will
be a list of the matching formatted log messages and the
`records` attribute will be a list of the corresponding LogRecord
objects.
Example::
with self.assertLogs('foo', level='INFO') as cm:
logging.getLogger('foo').info('first message')
logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
'ERROR:foo.bar:second message'])
|
def assertLogs(self, logger=None, level=None):
"""Fail unless a log message of level *level* or higher is emitted
on *logger_name* or its children. If omitted, *level* defaults to
INFO and *logger* defaults to the root logger.
This method must be used as a context manager, and will yield
a recording object with two attributes: `output` and `records`.
At the end of the context manager, the `output` attribute will
be a list of the matching formatted log messages and the
`records` attribute will be a list of the corresponding LogRecord
objects.
Example::
with self.assertLogs('foo', level='INFO') as cm:
logging.getLogger('foo').info('first message')
logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
'ERROR:foo.bar:second message'])
"""
# Lazy import to avoid importing logging if it is not needed.
from ._log import _AssertLogsContext
return _AssertLogsContext(self, logger, level, no_logs=False)
|
(self, logger=None, level=None)
|
41,921 |
unittest.case
|
assertMultiLineEqual
|
Assert that two multi-line strings are equal.
|
def assertMultiLineEqual(self, first, second, msg=None):
"""Assert that two multi-line strings are equal."""
self.assertIsInstance(first, str, 'First argument is not a string')
self.assertIsInstance(second, str, 'Second argument is not a string')
if first != second:
# don't use difflib if the strings are too long
if (len(first) > self._diffThreshold or
len(second) > self._diffThreshold):
self._baseAssertEqual(first, second, msg)
firstlines = first.splitlines(keepends=True)
secondlines = second.splitlines(keepends=True)
if len(firstlines) == 1 and first.strip('\r\n') == first:
firstlines = [first + '\n']
secondlines = [second + '\n']
standardMsg = '%s != %s' % _common_shorten_repr(first, second)
diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))
standardMsg = self._truncateMessage(standardMsg, diff)
self.fail(self._formatMessage(msg, standardMsg))
|
(self, first, second, msg=None)
|
41,922 |
unittest.case
|
assertNoLogs
|
Fail unless no log messages of level *level* or higher are emitted
on *logger_name* or its children.
This method must be used as a context manager.
|
def assertNoLogs(self, logger=None, level=None):
""" Fail unless no log messages of level *level* or higher are emitted
on *logger_name* or its children.
This method must be used as a context manager.
"""
from ._log import _AssertLogsContext
return _AssertLogsContext(self, logger, level, no_logs=True)
|
(self, logger=None, level=None)
|
41,923 |
unittest.case
|
assertNotAlmostEqual
|
Fail if the two objects are equal as determined by their
difference rounded to the given number of decimal places
(default 7) and comparing to zero, or by comparing that the
difference between the two objects is less than the given delta.
Note that decimal places (from zero) are usually not the same
as significant digits (measured from the most significant digit).
Objects that are equal automatically fail.
|
def assertNotAlmostEqual(self, first, second, places=None, msg=None,
delta=None):
"""Fail if the two objects are equal as determined by their
difference rounded to the given number of decimal places
(default 7) and comparing to zero, or by comparing that the
difference between the two objects is less than the given delta.
Note that decimal places (from zero) are usually not the same
as significant digits (measured from the most significant digit).
Objects that are equal automatically fail.
"""
if delta is not None and places is not None:
raise TypeError("specify delta or places not both")
diff = abs(first - second)
if delta is not None:
if not (first == second) and diff > delta:
return
standardMsg = '%s == %s within %s delta (%s difference)' % (
safe_repr(first),
safe_repr(second),
safe_repr(delta),
safe_repr(diff))
else:
if places is None:
places = 7
if not (first == second) and round(diff, places) != 0:
return
standardMsg = '%s == %s within %r places' % (safe_repr(first),
safe_repr(second),
places)
msg = self._formatMessage(msg, standardMsg)
raise self.failureException(msg)
|
(self, first, second, places=None, msg=None, delta=None)
|
41,925 |
unittest.case
|
assertNotEqual
|
Fail if the two objects are equal as determined by the '!='
operator.
|
def assertNotEqual(self, first, second, msg=None):
"""Fail if the two objects are equal as determined by the '!='
operator.
"""
if not first != second:
msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first),
safe_repr(second)))
raise self.failureException(msg)
|
(self, first, second, msg=None)
|
41,927 |
unittest.case
|
assertNotIn
|
Just like self.assertTrue(a not in b), but with a nicer default message.
|
def assertNotIn(self, member, container, msg=None):
"""Just like self.assertTrue(a not in b), but with a nicer default message."""
if member in container:
standardMsg = '%s unexpectedly found in %s' % (safe_repr(member),
safe_repr(container))
self.fail(self._formatMessage(msg, standardMsg))
|
(self, member, container, msg=None)
|
41,928 |
unittest.case
|
assertNotIsInstance
|
Included for symmetry with assertIsInstance.
|
def assertNotIsInstance(self, obj, cls, msg=None):
"""Included for symmetry with assertIsInstance."""
if isinstance(obj, cls):
standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls)
self.fail(self._formatMessage(msg, standardMsg))
|
(self, obj, cls, msg=None)
|
41,929 |
unittest.case
|
assertNotRegex
|
Fail the test if the text matches the regular expression.
|
def assertNotRegex(self, text, unexpected_regex, msg=None):
"""Fail the test if the text matches the regular expression."""
if isinstance(unexpected_regex, (str, bytes)):
unexpected_regex = re.compile(unexpected_regex)
match = unexpected_regex.search(text)
if match:
standardMsg = 'Regex matched: %r matches %r in %r' % (
text[match.start() : match.end()],
unexpected_regex.pattern,
text)
# _formatMessage ensures the longMessage option is respected
msg = self._formatMessage(msg, standardMsg)
raise self.failureException(msg)
|
(self, text, unexpected_regex, msg=None)
|
41,931 |
unittest.case
|
assertRaises
|
Fail unless an exception of class expected_exception is raised
by the callable when invoked with specified positional and
keyword arguments. If a different type of exception is
raised, it will not be caught, and the test case will be
deemed to have suffered an error, exactly as for an
unexpected exception.
If called with the callable and arguments omitted, will return a
context object used like this::
with self.assertRaises(SomeException):
do_something()
An optional keyword argument 'msg' can be provided when assertRaises
is used as a context object.
The context manager keeps a reference to the exception as
the 'exception' attribute. This allows you to inspect the
exception after the assertion::
with self.assertRaises(SomeException) as cm:
do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
|
def assertRaises(self, expected_exception, *args, **kwargs):
"""Fail unless an exception of class expected_exception is raised
by the callable when invoked with specified positional and
keyword arguments. If a different type of exception is
raised, it will not be caught, and the test case will be
deemed to have suffered an error, exactly as for an
unexpected exception.
If called with the callable and arguments omitted, will return a
context object used like this::
with self.assertRaises(SomeException):
do_something()
An optional keyword argument 'msg' can be provided when assertRaises
is used as a context object.
The context manager keeps a reference to the exception as
the 'exception' attribute. This allows you to inspect the
exception after the assertion::
with self.assertRaises(SomeException) as cm:
do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
"""
context = _AssertRaisesContext(expected_exception, self)
try:
return context.handle('assertRaises', args, kwargs)
finally:
# bpo-23890: manually break a reference cycle
context = None
|
(self, expected_exception, *args, **kwargs)
|
41,932 |
unittest.case
|
assertRaisesRegex
|
Asserts that the message in a raised exception matches a regex.
Args:
expected_exception: Exception class expected to be raised.
expected_regex: Regex (re.Pattern object or string) expected
to be found in error message.
args: Function to be called and extra positional args.
kwargs: Extra kwargs.
msg: Optional message used in case of failure. Can only be used
when assertRaisesRegex is used as a context manager.
|
def assertRaisesRegex(self, expected_exception, expected_regex,
*args, **kwargs):
"""Asserts that the message in a raised exception matches a regex.
Args:
expected_exception: Exception class expected to be raised.
expected_regex: Regex (re.Pattern object or string) expected
to be found in error message.
args: Function to be called and extra positional args.
kwargs: Extra kwargs.
msg: Optional message used in case of failure. Can only be used
when assertRaisesRegex is used as a context manager.
"""
context = _AssertRaisesContext(expected_exception, self, expected_regex)
return context.handle('assertRaisesRegex', args, kwargs)
|
(self, expected_exception, expected_regex, *args, **kwargs)
|
41,934 |
unittest.case
|
assertRegex
|
Fail the test unless the text matches the regular expression.
|
def assertRegex(self, text, expected_regex, msg=None):
"""Fail the test unless the text matches the regular expression."""
if isinstance(expected_regex, (str, bytes)):
assert expected_regex, "expected_regex must not be empty."
expected_regex = re.compile(expected_regex)
if not expected_regex.search(text):
standardMsg = "Regex didn't match: %r not found in %r" % (
expected_regex.pattern, text)
# _formatMessage ensures the longMessage option is respected
msg = self._formatMessage(msg, standardMsg)
raise self.failureException(msg)
|
(self, text, expected_regex, msg=None)
|
41,936 |
unittest.case
|
assertSequenceEqual
|
An equality assertion for ordered sequences (like lists and tuples).
For the purposes of this function, a valid ordered sequence type is one
which can be indexed, has a length, and has an equality operator.
Args:
seq1: The first sequence to compare.
seq2: The second sequence to compare.
seq_type: The expected datatype of the sequences, or None if no
datatype should be enforced.
msg: Optional message to use on failure instead of a list of
differences.
|
def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
"""An equality assertion for ordered sequences (like lists and tuples).
For the purposes of this function, a valid ordered sequence type is one
which can be indexed, has a length, and has an equality operator.
Args:
seq1: The first sequence to compare.
seq2: The second sequence to compare.
seq_type: The expected datatype of the sequences, or None if no
datatype should be enforced.
msg: Optional message to use on failure instead of a list of
differences.
"""
if seq_type is not None:
seq_type_name = seq_type.__name__
if not isinstance(seq1, seq_type):
raise self.failureException('First sequence is not a %s: %s'
% (seq_type_name, safe_repr(seq1)))
if not isinstance(seq2, seq_type):
raise self.failureException('Second sequence is not a %s: %s'
% (seq_type_name, safe_repr(seq2)))
else:
seq_type_name = "sequence"
differing = None
try:
len1 = len(seq1)
except (TypeError, NotImplementedError):
differing = 'First %s has no length. Non-sequence?' % (
seq_type_name)
if differing is None:
try:
len2 = len(seq2)
except (TypeError, NotImplementedError):
differing = 'Second %s has no length. Non-sequence?' % (
seq_type_name)
if differing is None:
if seq1 == seq2:
return
differing = '%ss differ: %s != %s\n' % (
(seq_type_name.capitalize(),) +
_common_shorten_repr(seq1, seq2))
for i in range(min(len1, len2)):
try:
item1 = seq1[i]
except (TypeError, IndexError, NotImplementedError):
differing += ('\nUnable to index element %d of first %s\n' %
(i, seq_type_name))
break
try:
item2 = seq2[i]
except (TypeError, IndexError, NotImplementedError):
differing += ('\nUnable to index element %d of second %s\n' %
(i, seq_type_name))
break
if item1 != item2:
differing += ('\nFirst differing element %d:\n%s\n%s\n' %
((i,) + _common_shorten_repr(item1, item2)))
break
else:
if (len1 == len2 and seq_type is None and
type(seq1) != type(seq2)):
# The sequences are the same, but have differing types.
return
if len1 > len2:
differing += ('\nFirst %s contains %d additional '
'elements.\n' % (seq_type_name, len1 - len2))
try:
differing += ('First extra element %d:\n%s\n' %
(len2, safe_repr(seq1[len2])))
except (TypeError, IndexError, NotImplementedError):
differing += ('Unable to index element %d '
'of first %s\n' % (len2, seq_type_name))
elif len1 < len2:
differing += ('\nSecond %s contains %d additional '
'elements.\n' % (seq_type_name, len2 - len1))
try:
differing += ('First extra element %d:\n%s\n' %
(len1, safe_repr(seq2[len1])))
except (TypeError, IndexError, NotImplementedError):
differing += ('Unable to index element %d '
'of second %s\n' % (len1, seq_type_name))
standardMsg = differing
diffMsg = '\n' + '\n'.join(
difflib.ndiff(pprint.pformat(seq1).splitlines(),
pprint.pformat(seq2).splitlines()))
standardMsg = self._truncateMessage(standardMsg, diffMsg)
msg = self._formatMessage(msg, standardMsg)
self.fail(msg)
|
(self, seq1, seq2, msg=None, seq_type=None)
|
41,937 |
unittest.case
|
assertSetEqual
|
A set-specific equality assertion.
Args:
set1: The first set to compare.
set2: The second set to compare.
msg: Optional message to use on failure instead of a list of
differences.
assertSetEqual uses ducktyping to support different types of sets, and
is optimized for sets specifically (parameters must support a
difference method).
|
def assertSetEqual(self, set1, set2, msg=None):
"""A set-specific equality assertion.
Args:
set1: The first set to compare.
set2: The second set to compare.
msg: Optional message to use on failure instead of a list of
differences.
assertSetEqual uses ducktyping to support different types of sets, and
is optimized for sets specifically (parameters must support a
difference method).
"""
try:
difference1 = set1.difference(set2)
except TypeError as e:
self.fail('invalid type when attempting set difference: %s' % e)
except AttributeError as e:
self.fail('first argument does not support set difference: %s' % e)
try:
difference2 = set2.difference(set1)
except TypeError as e:
self.fail('invalid type when attempting set difference: %s' % e)
except AttributeError as e:
self.fail('second argument does not support set difference: %s' % e)
if not (difference1 or difference2):
return
lines = []
if difference1:
lines.append('Items in the first set but not the second:')
for item in difference1:
lines.append(repr(item))
if difference2:
lines.append('Items in the second set but not the first:')
for item in difference2:
lines.append(repr(item))
standardMsg = '\n'.join(lines)
self.fail(self._formatMessage(msg, standardMsg))
|
(self, set1, set2, msg=None)
|
41,938 |
unittest.case
|
assertTrue
|
Check that the expression is true.
|
def assertTrue(self, expr, msg=None):
"""Check that the expression is true."""
if not expr:
msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr))
raise self.failureException(msg)
|
(self, expr, msg=None)
|
41,939 |
unittest.case
|
assertTupleEqual
|
A tuple-specific equality assertion.
Args:
tuple1: The first tuple to compare.
tuple2: The second tuple to compare.
msg: Optional message to use on failure instead of a list of
differences.
|
def assertTupleEqual(self, tuple1, tuple2, msg=None):
"""A tuple-specific equality assertion.
Args:
tuple1: The first tuple to compare.
tuple2: The second tuple to compare.
msg: Optional message to use on failure instead of a list of
differences.
"""
self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
|
(self, tuple1, tuple2, msg=None)
|
41,940 |
unittest.case
|
assertWarns
|
Fail unless a warning of class warnClass is triggered
by the callable when invoked with specified positional and
keyword arguments. If a different type of warning is
triggered, it will not be handled: depending on the other
warning filtering rules in effect, it might be silenced, printed
out, or raised as an exception.
If called with the callable and arguments omitted, will return a
context object used like this::
with self.assertWarns(SomeWarning):
do_something()
An optional keyword argument 'msg' can be provided when assertWarns
is used as a context object.
The context manager keeps a reference to the first matching
warning as the 'warning' attribute; similarly, the 'filename'
and 'lineno' attributes give you information about the line
of Python code from which the warning was triggered.
This allows you to inspect the warning after the assertion::
with self.assertWarns(SomeWarning) as cm:
do_something()
the_warning = cm.warning
self.assertEqual(the_warning.some_attribute, 147)
|
def assertWarns(self, expected_warning, *args, **kwargs):
"""Fail unless a warning of class warnClass is triggered
by the callable when invoked with specified positional and
keyword arguments. If a different type of warning is
triggered, it will not be handled: depending on the other
warning filtering rules in effect, it might be silenced, printed
out, or raised as an exception.
If called with the callable and arguments omitted, will return a
context object used like this::
with self.assertWarns(SomeWarning):
do_something()
An optional keyword argument 'msg' can be provided when assertWarns
is used as a context object.
The context manager keeps a reference to the first matching
warning as the 'warning' attribute; similarly, the 'filename'
and 'lineno' attributes give you information about the line
of Python code from which the warning was triggered.
This allows you to inspect the warning after the assertion::
with self.assertWarns(SomeWarning) as cm:
do_something()
the_warning = cm.warning
self.assertEqual(the_warning.some_attribute, 147)
"""
context = _AssertWarnsContext(expected_warning, self)
return context.handle('assertWarns', args, kwargs)
|
(self, expected_warning, *args, **kwargs)
|
41,941 |
unittest.case
|
assertWarnsRegex
|
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
are considered successful matches.
Args:
expected_warning: Warning class expected to be triggered.
expected_regex: Regex (re.Pattern object or string) expected
to be found in error message.
args: Function to be called and extra positional args.
kwargs: Extra kwargs.
msg: Optional message used in case of failure. Can only be used
when assertWarnsRegex is used as a context manager.
|
def assertWarnsRegex(self, expected_warning, expected_regex,
*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
are considered successful matches.
Args:
expected_warning: Warning class expected to be triggered.
expected_regex: Regex (re.Pattern object or string) expected
to be found in error message.
args: Function to be called and extra positional args.
kwargs: Extra kwargs.
msg: Optional message used in case of failure. Can only be used
when assertWarnsRegex is used as a context manager.
"""
context = _AssertWarnsContext(expected_warning, self, expected_regex)
return context.handle('assertWarnsRegex', args, kwargs)
|
(self, expected_warning, expected_regex, *args, **kwargs)
|
41,943 |
unittest.case
|
countTestCases
| null |
def countTestCases(self):
return 1
|
(self)
|
41,944 |
unittest.case
|
debug
|
Run the test without collecting errors in a TestResult
|
def debug(self):
"""Run the test without collecting errors in a TestResult"""
testMethod = getattr(self, self._testMethodName)
if (getattr(self.__class__, "__unittest_skip__", False) or
getattr(testMethod, "__unittest_skip__", False)):
# If the class or method was skipped.
skip_why = (getattr(self.__class__, '__unittest_skip_why__', '')
or getattr(testMethod, '__unittest_skip_why__', ''))
raise SkipTest(skip_why)
self._callSetUp()
self._callTestMethod(testMethod)
self._callTearDown()
while self._cleanups:
function, args, kwargs = self._cleanups.pop()
self._callCleanup(function, *args, **kwargs)
|
(self)
|
41,945 |
unittest.case
|
defaultTestResult
| null |
def defaultTestResult(self):
return result.TestResult()
|
(self)
|
41,946 |
unittest.case
|
doCleanups
|
Execute all cleanup functions. Normally called for you after
tearDown.
|
def doCleanups(self):
"""Execute all cleanup functions. Normally called for you after
tearDown."""
outcome = self._outcome or _Outcome()
while self._cleanups:
function, args, kwargs = self._cleanups.pop()
with outcome.testPartExecutor(self):
self._callCleanup(function, *args, **kwargs)
# return this for backwards compatibility
# even though we no longer use it internally
return outcome.success
|
(self)
|
41,947 |
unittest.case
|
fail
|
Fail immediately, with the given message.
|
def fail(self, msg=None):
"""Fail immediately, with the given message."""
raise self.failureException(msg)
|
(self, msg=None)
|
41,955 |
unittest.case
|
id
| null |
def id(self):
return "%s.%s" % (strclass(self.__class__), self._testMethodName)
|
(self)
|
41,956 |
unittest.case
|
run
| null |
def run(self, result=None):
if result is None:
result = self.defaultTestResult()
startTestRun = getattr(result, 'startTestRun', None)
stopTestRun = getattr(result, 'stopTestRun', None)
if startTestRun is not None:
startTestRun()
else:
stopTestRun = None
result.startTest(self)
try:
testMethod = getattr(self, self._testMethodName)
if (getattr(self.__class__, "__unittest_skip__", False) or
getattr(testMethod, "__unittest_skip__", False)):
# If the class or method was skipped.
skip_why = (getattr(self.__class__, '__unittest_skip_why__', '')
or getattr(testMethod, '__unittest_skip_why__', ''))
self._addSkip(result, self, skip_why)
return result
expecting_failure = (
getattr(self, "__unittest_expecting_failure__", False) or
getattr(testMethod, "__unittest_expecting_failure__", False)
)
outcome = _Outcome(result)
try:
self._outcome = outcome
with outcome.testPartExecutor(self):
self._callSetUp()
if outcome.success:
outcome.expecting_failure = expecting_failure
with outcome.testPartExecutor(self, isTest=True):
self._callTestMethod(testMethod)
outcome.expecting_failure = False
with outcome.testPartExecutor(self):
self._callTearDown()
self.doCleanups()
for test, reason in outcome.skipped:
self._addSkip(result, test, reason)
self._feedErrorsToResult(result, outcome.errors)
if outcome.success:
if expecting_failure:
if outcome.expectedFailure:
self._addExpectedFailure(result, outcome.expectedFailure)
else:
self._addUnexpectedSuccess(result)
else:
result.addSuccess(self)
return result
finally:
# explicitly break reference cycles:
# outcome.errors -> frame -> outcome -> outcome.errors
# outcome.expectedFailure -> frame -> outcome -> outcome.expectedFailure
outcome.errors.clear()
outcome.expectedFailure = None
# clear the outcome, no more needed
self._outcome = None
finally:
result.stopTest(self)
if stopTestRun is not None:
stopTestRun()
|
(self, result=None)
|
41,957 |
rfc3339
|
setUp
| null |
def setUp(self):
local_utcoffset = _utc_offset(datetime.now(),
use_system_timezone=True)
self.local_utcoffset = timedelta(seconds=local_utcoffset)
self.local_timezone = _timezone(local_utcoffset)
|
(self)
|
41,958 |
unittest.case
|
shortDescription
|
Returns a one-line description of the test, or None if no
description has been provided.
The default implementation of this method returns the first line of
the specified test method's docstring.
|
def shortDescription(self):
"""Returns a one-line description of the test, or None if no
description has been provided.
The default implementation of this method returns the first line of
the specified test method's docstring.
"""
doc = self._testMethodDoc
return doc.strip().split("\n")[0].strip() if doc else None
|
(self)
|
41,959 |
unittest.case
|
skipTest
|
Skip this test.
|
def skipTest(self, reason):
"""Skip this test."""
raise SkipTest(reason)
|
(self, reason)
|
41,960 |
unittest.case
|
subTest
|
Return a context manager that will return the enclosed block
of code in a subtest identified by the optional message and
keyword parameters. A failure in the subtest marks the test
case as failed but resumes execution at the end of the enclosed
block, allowing further test code to be executed.
|
def __exit__(self, exc_type, exc_value, tb):
self.warnings_manager.__exit__(exc_type, exc_value, tb)
if exc_type is not None:
# let unexpected exceptions pass through
return
try:
exc_name = self.expected.__name__
except AttributeError:
exc_name = str(self.expected)
first_matching = None
for m in self.warnings:
w = m.message
if not isinstance(w, self.expected):
continue
if first_matching is None:
first_matching = 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
self.filename = m.filename
self.lineno = m.lineno
return
# Now we simply try to choose a helpful failure message
if first_matching is not None:
self._raiseFailure('"{}" does not match "{}"'.format(
self.expected_regex.pattern, str(first_matching)))
if self.obj_name:
self._raiseFailure("{} not triggered by {}".format(exc_name,
self.obj_name))
else:
self._raiseFailure("{} not triggered".format(exc_name))
|
(self, msg=<object object at 0x7f49041999f0>, **params)
|
41,961 |
unittest.case
|
tearDown
|
Hook method for deconstructing the test fixture after testing it.
|
def tearDown(self):
"Hook method for deconstructing the test fixture after testing it."
pass
|
(self)
|
41,962 |
rfc3339
|
test_1920
| null |
def test_1920(self):
d = date(1920, 2, 29)
x = rfc3339(d, utc=False, use_system_timezone=True)
self.assertTrue(x.startswith('1920-02-29T00:00:00'))
|
(self)
|
41,963 |
rfc3339
|
test_before_1970
| null |
def test_before_1970(self):
d = date(1885, 1, 4)
self.assertTrue(rfc3339(d).startswith('1885-01-04T00:00:00'))
self.assertEqual(rfc3339(d, utc=True, use_system_timezone=False),
'1885-01-04T00:00:00Z')
|
(self)
|
41,964 |
rfc3339
|
test_date
| null |
def test_date(self):
d = date.today()
self.assertEqual(rfc3339(d),
d.strftime('%Y-%m-%dT%H:%M:%S') + self.local_timezone)
|
(self)
|
41,965 |
rfc3339
|
test_date_utc
| null |
def test_date_utc(self):
d = date.today()
# Convert `date` to `datetime`, since `date` ignores seconds and hours
# in timedeltas:
# >>> date(2008, 9, 7) + timedelta(hours=23)
# date(2008, 9, 7)
d_utc = datetime(*d.timetuple()[:3]) - self.local_utcoffset
self.assertEqual(rfc3339(d, utc=True),
d_utc.strftime('%Y-%m-%dT%H:%M:%SZ'))
|
(self)
|
41,966 |
rfc3339
|
test_datetime
| null |
def test_datetime(self):
d = datetime.now()
self.assertEqual(rfc3339(d),
d.strftime('%Y-%m-%dT%H:%M:%S') + self.local_timezone)
|
(self)
|
41,967 |
rfc3339
|
test_datetime_timezone
| null |
def test_datetime_timezone(self):
class FixedNoDst(tzinfo):
'A timezone info with fixed offset, not DST'
def utcoffset(self, dt):
return timedelta(hours=2, minutes=30)
def dst(self, dt):
return None
fixed_no_dst = FixedNoDst()
class Fixed(FixedNoDst):
'A timezone info with DST'
def utcoffset(self, dt):
return timedelta(hours=3, minutes=15)
def dst(self, dt):
return timedelta(hours=3, minutes=15)
fixed = Fixed()
d = datetime.now().replace(tzinfo=fixed_no_dst)
timezone = _timezone(_timedelta_to_seconds(fixed_no_dst.\
utcoffset(None)))
self.assertEqual(rfc3339(d),
d.strftime('%Y-%m-%dT%H:%M:%S') + timezone)
d = datetime.now().replace(tzinfo=fixed)
timezone = _timezone(_timedelta_to_seconds(fixed.dst(None)))
self.assertEqual(rfc3339(d),
d.strftime('%Y-%m-%dT%H:%M:%S') + timezone)
|
(self)
|
41,968 |
rfc3339
|
test_datetime_utc
| null |
def test_datetime_utc(self):
d = datetime.now()
d_utc = d - self.local_utcoffset
self.assertEqual(rfc3339(d, utc=True),
d_utc.strftime('%Y-%m-%dT%H:%M:%SZ'))
|
(self)
|
41,969 |
rfc3339
|
test_microsecond
| null |
def test_microsecond(self):
x = datetime(2018, 9, 20, 13, 11, 21, 12345)
self.assertEqual(
format_microsecond(
datetime(2018, 9, 20, 13, 11, 21, 12345),
utc=True,
use_system_timezone=False),
'2018-09-20T13:11:21.012345Z')
|
(self)
|
41,970 |
rfc3339
|
test_millisecond
| null |
def test_millisecond(self):
x = datetime(2018, 9, 20, 13, 11, 21, 123000)
self.assertEqual(
format_millisecond(
datetime(2018, 9, 20, 13, 11, 21, 123000),
utc=True,
use_system_timezone=False),
'2018-09-20T13:11:21.123Z')
|
(self)
|
41,971 |
rfc3339
|
test_timestamp
| null |
def test_timestamp(self):
d = time.time()
self.assertEqual(
rfc3339(d),
datetime.fromtimestamp(d).
strftime('%Y-%m-%dT%H:%M:%S') + self.local_timezone)
|
(self)
|
41,972 |
rfc3339
|
test_timestamp_utc
| null |
def test_timestamp_utc(self):
d = time.time()
# utc -> local timezone
d_utc = datetime.utcfromtimestamp(d) + self.local_utcoffset
self.assertEqual(rfc3339(d),
(d_utc.strftime('%Y-%m-%dT%H:%M:%S') +
self.local_timezone))
|
(self)
|
41,973 |
rfc3339
|
_format
| null |
def _format(timestamp, string_format, utc, use_system_timezone):
# Try to convert timestamp to datetime
try:
if use_system_timezone:
timestamp = datetime.fromtimestamp(timestamp)
else:
timestamp = datetime.utcfromtimestamp(timestamp)
except TypeError:
pass
if not isinstance(timestamp, date):
raise TypeError('Expected timestamp or date object. Got %r.' %
type(timestamp))
if not isinstance(timestamp, datetime):
timestamp = datetime(*timestamp.timetuple()[:3])
utc_offset = _utc_offset(timestamp, use_system_timezone)
if utc:
# local time -> utc
return string_format(timestamp - timedelta(seconds=utc_offset), 'Z')
else:
return string_format(timestamp , _timezone(utc_offset))
|
(timestamp, string_format, utc, use_system_timezone)
|
41,974 |
rfc3339
|
_string
| null |
def _string(d, timezone):
return ('%04d-%02d-%02dT%02d:%02d:%02d%s' %
(d.year, d.month, d.day, d.hour, d.minute, d.second, timezone))
|
(d, timezone)
|
41,975 |
rfc3339
|
_string_microseconds
| null |
def _string_microseconds(d, timezone):
return ('%04d-%02d-%02dT%02d:%02d:%02d.%06d%s' %
(d.year, d.month, d.day, d.hour, d.minute, d.second, d.microsecond, timezone))
|
(d, timezone)
|
41,976 |
rfc3339
|
_string_milliseconds
| null |
def _string_milliseconds(d, timezone):
return ('%04d-%02d-%02dT%02d:%02d:%02d.%03d%s' %
(d.year, d.month, d.day, d.hour, d.minute, d.second, d.microsecond / 1000, timezone))
|
(d, timezone)
|
41,977 |
rfc3339
|
_timedelta_to_seconds
|
>>> _timedelta_to_seconds(timedelta(hours=3))
10800
>>> _timedelta_to_seconds(timedelta(hours=3, minutes=15))
11700
>>> _timedelta_to_seconds(timedelta(hours=-8))
-28800
|
def _timedelta_to_seconds(td):
'''
>>> _timedelta_to_seconds(timedelta(hours=3))
10800
>>> _timedelta_to_seconds(timedelta(hours=3, minutes=15))
11700
>>> _timedelta_to_seconds(timedelta(hours=-8))
-28800
'''
return int((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6)
|
(td)
|
41,978 |
rfc3339
|
_timezone
|
Return a string representing the timezone offset.
>>> _timezone(0)
'+00:00'
>>> _timezone(3600)
'+01:00'
>>> _timezone(-28800)
'-08:00'
>>> _timezone(-8 * 60 * 60)
'-08:00'
>>> _timezone(-30 * 60)
'-00:30'
|
def _timezone(utc_offset):
'''
Return a string representing the timezone offset.
>>> _timezone(0)
'+00:00'
>>> _timezone(3600)
'+01:00'
>>> _timezone(-28800)
'-08:00'
>>> _timezone(-8 * 60 * 60)
'-08:00'
>>> _timezone(-30 * 60)
'-00:30'
'''
# Python's division uses floor(), not round() like in other languages:
# -1 / 2 == -1 and not -1 / 2 == 0
# That's why we use abs(utc_offset).
hours = abs(utc_offset) // 3600
minutes = abs(utc_offset) % 3600 // 60
sign = (utc_offset < 0 and '-') or '+'
return '%c%02d:%02d' % (sign, hours, minutes)
|
(utc_offset)
|
41,979 |
rfc3339
|
_utc_offset
|
Return the UTC offset of `timestamp`. If `timestamp` does not have any `tzinfo`, use
the timezone informations stored locally on the system.
>>> if time.localtime().tm_isdst:
... system_timezone = -time.altzone
... else:
... system_timezone = -time.timezone
>>> _utc_offset(datetime.now(), True) == system_timezone
True
>>> _utc_offset(datetime.now(), False)
0
|
def _utc_offset(timestamp, use_system_timezone):
'''
Return the UTC offset of `timestamp`. If `timestamp` does not have any `tzinfo`, use
the timezone informations stored locally on the system.
>>> if time.localtime().tm_isdst:
... system_timezone = -time.altzone
... else:
... system_timezone = -time.timezone
>>> _utc_offset(datetime.now(), True) == system_timezone
True
>>> _utc_offset(datetime.now(), False)
0
'''
if (isinstance(timestamp, datetime) and
timestamp.tzinfo is not None):
return _timedelta_to_seconds(timestamp.utcoffset())
elif use_system_timezone:
if timestamp.year < 1970:
# We use 1972 because 1970 doesn't have a leap day (feb 29)
t = time.mktime(timestamp.replace(year=1972).timetuple())
else:
t = time.mktime(timestamp.timetuple())
if time.localtime(t).tm_isdst: # pragma: no cover
return -time.altzone
else:
return -time.timezone
else:
return 0
|
(timestamp, use_system_timezone)
|
41,982 |
rfc3339
|
format
|
Return a string formatted according to the :RFC:`3339`. If called with
`utc=True`, it normalizes `timestamp` to the UTC date. If `timestamp` does
not have any timezone information, uses the local timezone::
>>> d = datetime(2008, 4, 2, 20)
>>> rfc3339(d, utc=True, use_system_timezone=False)
'2008-04-02T20:00:00Z'
>>> rfc3339(d) # doctest: +ELLIPSIS
'2008-04-02T20:00:00...'
If called with `use_system_timezone=False` don't use the local timezone if
`timestamp` does not have timezone informations and consider the offset to UTC
to be zero::
>>> rfc3339(d, use_system_timezone=False)
'2008-04-02T20:00:00+00:00'
`timestamp` must be a `datetime`, `date` or a timestamp as
returned by `time.time()`::
>>> rfc3339(0, utc=True, use_system_timezone=False)
'1970-01-01T00:00:00Z'
>>> rfc3339(date(2008, 9, 6), utc=True,
... use_system_timezone=False)
'2008-09-06T00:00:00Z'
>>> rfc3339(date(2008, 9, 6),
... use_system_timezone=False)
'2008-09-06T00:00:00+00:00'
>>> rfc3339('foo bar') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: Expected timestamp or date object. Got <... 'str'>.
For dates before January 1st 1970, the timezones will be the ones used in
1970. It might not be accurate, but on most sytem there is no timezone
information before 1970.
|
def format(timestamp, utc=False, use_system_timezone=True):
'''
Return a string formatted according to the :RFC:`3339`. If called with
`utc=True`, it normalizes `timestamp` to the UTC date. If `timestamp` does
not have any timezone information, uses the local timezone::
>>> d = datetime(2008, 4, 2, 20)
>>> rfc3339(d, utc=True, use_system_timezone=False)
'2008-04-02T20:00:00Z'
>>> rfc3339(d) # doctest: +ELLIPSIS
'2008-04-02T20:00:00...'
If called with `use_system_timezone=False` don't use the local timezone if
`timestamp` does not have timezone informations and consider the offset to UTC
to be zero::
>>> rfc3339(d, use_system_timezone=False)
'2008-04-02T20:00:00+00:00'
`timestamp` must be a `datetime`, `date` or a timestamp as
returned by `time.time()`::
>>> rfc3339(0, utc=True, use_system_timezone=False)
'1970-01-01T00:00:00Z'
>>> rfc3339(date(2008, 9, 6), utc=True,
... use_system_timezone=False)
'2008-09-06T00:00:00Z'
>>> rfc3339(date(2008, 9, 6),
... use_system_timezone=False)
'2008-09-06T00:00:00+00:00'
>>> rfc3339('foo bar') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: Expected timestamp or date object. Got <... 'str'>.
For dates before January 1st 1970, the timezones will be the ones used in
1970. It might not be accurate, but on most sytem there is no timezone
information before 1970.
'''
return _format(timestamp, _string, utc, use_system_timezone)
|
(timestamp, utc=False, use_system_timezone=True)
|
41,983 |
rfc3339
|
format_microsecond
|
Same as `rfc3339.format` but with the microsecond fraction after the seconds.
|
def format_microsecond(timestamp, utc=False, use_system_timezone=True):
'''
Same as `rfc3339.format` but with the microsecond fraction after the seconds.
'''
return _format(timestamp, _string_microseconds, utc, use_system_timezone)
|
(timestamp, utc=False, use_system_timezone=True)
|
41,984 |
rfc3339
|
format_millisecond
|
Same as `rfc3339.format` but with the millisecond fraction after the seconds.
|
def format_millisecond(timestamp, utc=False, use_system_timezone=True):
'''
Same as `rfc3339.format` but with the millisecond fraction after the seconds.
'''
return _format(timestamp, _string_milliseconds, utc, use_system_timezone)
|
(timestamp, utc=False, use_system_timezone=True)
|
41,988 |
datetime
|
tzinfo
|
Abstract base class for time zone info objects.
|
class tzinfo:
"""Abstract base class for time zone info classes.
Subclasses must override the name(), utcoffset() and dst() methods.
"""
__slots__ = ()
def tzname(self, dt):
"datetime -> string name of time zone."
raise NotImplementedError("tzinfo subclass must override tzname()")
def utcoffset(self, dt):
"datetime -> timedelta, positive for east of UTC, negative for west of UTC"
raise NotImplementedError("tzinfo subclass must override utcoffset()")
def dst(self, dt):
"""datetime -> DST offset as timedelta, positive for east of UTC.
Return 0 if DST not in effect. utcoffset() must include the DST
offset.
"""
raise NotImplementedError("tzinfo subclass must override dst()")
def fromutc(self, dt):
"datetime in UTC -> datetime in local time."
if not isinstance(dt, datetime):
raise TypeError("fromutc() requires a datetime argument")
if dt.tzinfo is not self:
raise ValueError("dt.tzinfo is not self")
dtoff = dt.utcoffset()
if dtoff is None:
raise ValueError("fromutc() requires a non-None utcoffset() "
"result")
# See the long comment block at the end of this file for an
# explanation of this algorithm.
dtdst = dt.dst()
if dtdst is None:
raise ValueError("fromutc() requires a non-None dst() result")
delta = dtoff - dtdst
if delta:
dt += delta
dtdst = dt.dst()
if dtdst is None:
raise ValueError("fromutc(): dt.dst gave inconsistent "
"results; cannot convert")
return dt + dtdst
# Pickle support.
def __reduce__(self):
getinitargs = getattr(self, "__getinitargs__", None)
if getinitargs:
args = getinitargs()
else:
args = ()
getstate = getattr(self, "__getstate__", None)
if getstate:
state = getstate()
else:
state = getattr(self, "__dict__", None) or None
if state is None:
return (self.__class__, args)
else:
return (self.__class__, args, state)
| null |
41,990 |
opt_einsum_fx._efficient_shape_prop
|
EfficientShapeProp
|
Like ShapeProp, traverses a graph Node-by-Node
and records the shape and type of the result
into each Node.
Except we treat 'einsum' as a special case.
We don't actually execute 'einsum' on tensors,
since the einsums will typically not be optimized
yet (ShapeProp is called before optimization),
and inefficient summation order can create
enormous intermediate tensors, which often creates
needless out-of-memory errors.
So we override 'run_node' only for 'einsums'.
It's straightforward to determine the shape of the
result just from the output indices.
(The call to opt_einsum that will typically follow
this, also doesn't actually build the tensors
during its exploration.)
|
class EfficientShapeProp(torch.fx.Interpreter):
"""
Like ShapeProp, traverses a graph Node-by-Node
and records the shape and type of the result
into each Node.
Except we treat 'einsum' as a special case.
We don't actually execute 'einsum' on tensors,
since the einsums will typically not be optimized
yet (ShapeProp is called before optimization),
and inefficient summation order can create
enormous intermediate tensors, which often creates
needless out-of-memory errors.
So we override 'run_node' only for 'einsums'.
It's straightforward to determine the shape of the
result just from the output indices.
(The call to opt_einsum that will typically follow
this, also doesn't actually build the tensors
during its exploration.)
"""
def run_node(self, n: Node) -> Any:
if n.op == "call_function" and n.target in _EINSUM_FUNCS:
args, kwargs = self.fetch_args_kwargs_from_env(n)
equation, *operands = args
shapes = [op.shape for op in operands]
assert len({op.dtype for op in operands}) == 1
meta = SimpleMeta(einsum_shape(equation, *shapes), operands[0].dtype)
result = torch.zeros((1,) * len(meta.shape), dtype=meta.dtype, device=operands[0].device).expand(meta.shape)
elif n.op == "call_function" and n.target == torch.tensordot:
args, kwargs = self.fetch_args_kwargs_from_env(n)
shape_a = [dim for i, dim in enumerate(args[0].shape) if i not in kwargs['dims'][0]]
shape_b = [dim for i, dim in enumerate(args[1].shape) if i not in kwargs['dims'][1]]
assert len({op.dtype for op in args}) == 1
meta = SimpleMeta(shape_a + shape_b, args[0].dtype)
result = torch.zeros((1,) * len(meta.shape), dtype=meta.dtype, device=args[0].device).expand(meta.shape)
else:
result = super().run_node(n)
if isinstance(result, torch.Tensor):
meta = SimpleMeta(result.shape, result.dtype)
else:
meta = None
n.meta = dict()
n.meta['tensor_meta'] = meta
n.meta['type'] = type(result)
return result
def propagate(self, *args):
return super().run(*args)
|
(module: torch.nn.modules.module.Module, garbage_collect_values: bool = True, graph: Optional[torch.fx.graph.Graph] = None)
|
41,991 |
torch.fx.interpreter
|
__init__
|
.. note::
Backwards-compatibility for this API is guaranteed.
|
@compatibility(is_backward_compatible=True)
def __init__(self, module: torch.nn.Module, garbage_collect_values: bool = True, graph: Optional[Graph] = None):
self.module = module
self.submodules = dict(self.module.named_modules())
if graph is not None:
self.graph = graph
else:
self.graph = self.module.graph
self.env : Dict[Node, Any] = {}
self.name = "Interpreter"
self.garbage_collect_values = garbage_collect_values
self.extra_traceback = True
if self.garbage_collect_values:
# Run through reverse nodes and record the first instance of a use
# of a given node. This represents the *last* use of the node in the
# execution order of the program, which we will use to free unused
# values
node_to_last_use : Dict[Node, Node] = {}
self.user_to_last_uses : Dict[Node, List[Node]] = {}
def register_last_uses(n : Node, user : Node):
if n not in node_to_last_use:
node_to_last_use[n] = user
self.user_to_last_uses.setdefault(user, []).append(n)
for node in reversed(self.graph.nodes):
map_arg(node.args, lambda n: register_last_uses(n, node))
map_arg(node.kwargs, lambda n: register_last_uses(n, node))
|
(self, module: torch.nn.modules.module.Module, garbage_collect_values: bool = True, graph: Optional[torch.fx.graph.Graph] = None)
|
41,992 |
torch.fx.interpreter
|
_set_current_node
| null |
@compatibility(is_backward_compatible=True)
def call_method(self, target : 'Target', args : Tuple[Argument, ...], kwargs : Dict[str, Any]) -> Any:
"""
Execute a ``call_method`` node and return the result.
Args:
target (Target): The call target for this node. See
`Node <https://pytorch.org/docs/master/fx.html#torch.fx.Node>`__ for
details on semantics
args (Tuple): Tuple of positional args for this invocation
kwargs (Dict): Dict of keyword arguments for this invocation
Return
Any: The value returned by the method invocation
"""
# args[0] is the `self` object for this method call
self_obj, *args_tail = args
# Execute the method and return the result
assert isinstance(target, str)
return getattr(self_obj, target)(*args_tail, **kwargs)
|
(self, node)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.