desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Plus corresponds to unary prefix plus in Python.
The operation is evaluated using the same rules as add; the
operation plus(a) is calculated as add(\'0\', a) where the \'0\'
has the same exponent as the operand.
>>> ExtendedContext.plus(Decimal(\'1.3\'))
Decimal(\'1.3\')
>>> ExtendedContext.plus(Decimal(\'-1.3\'))
Decimal(\'-1.3\')
>>> ExtendedContext.plus(-1)
Decimal(\'-1\')'
| def plus(self, a):
| a = _convert_other(a, raiseit=True)
return a.__pos__(context=self)
|
'Raises a to the power of b, to modulo if given.
With two arguments, compute a**b. If a is negative then b
must be integral. The result will be inexact unless b is
integral and the result is finite and can be expressed exactly
in \'precision\' digits.
With three arguments, compute (a**b) % modulo. For the
three argument form, the following restrictions on the
arguments hold:
- all three arguments must be integral
- b must be nonnegative
- at least one of a or b must be nonzero
- modulo must be nonzero and have at most \'precision\' digits
The result of pow(a, b, modulo) is identical to the result
that would be obtained by computing (a**b) % modulo with
unbounded precision, but is computed more efficiently. It is
always exact.
>>> c = ExtendedContext.copy()
>>> c.Emin = -999
>>> c.Emax = 999
>>> c.power(Decimal(\'2\'), Decimal(\'3\'))
Decimal(\'8\')
>>> c.power(Decimal(\'-2\'), Decimal(\'3\'))
Decimal(\'-8\')
>>> c.power(Decimal(\'2\'), Decimal(\'-3\'))
Decimal(\'0.125\')
>>> c.power(Decimal(\'1.7\'), Decimal(\'8\'))
Decimal(\'69.7575744\')
>>> c.power(Decimal(\'10\'), Decimal(\'0.301029996\'))
Decimal(\'2.00000000\')
>>> c.power(Decimal(\'Infinity\'), Decimal(\'-1\'))
Decimal(\'0\')
>>> c.power(Decimal(\'Infinity\'), Decimal(\'0\'))
Decimal(\'1\')
>>> c.power(Decimal(\'Infinity\'), Decimal(\'1\'))
Decimal(\'Infinity\')
>>> c.power(Decimal(\'-Infinity\'), Decimal(\'-1\'))
Decimal(\'-0\')
>>> c.power(Decimal(\'-Infinity\'), Decimal(\'0\'))
Decimal(\'1\')
>>> c.power(Decimal(\'-Infinity\'), Decimal(\'1\'))
Decimal(\'-Infinity\')
>>> c.power(Decimal(\'-Infinity\'), Decimal(\'2\'))
Decimal(\'Infinity\')
>>> c.power(Decimal(\'0\'), Decimal(\'0\'))
Decimal(\'NaN\')
>>> c.power(Decimal(\'3\'), Decimal(\'7\'), Decimal(\'16\'))
Decimal(\'11\')
>>> c.power(Decimal(\'-3\'), Decimal(\'7\'), Decimal(\'16\'))
Decimal(\'-11\')
>>> c.power(Decimal(\'-3\'), Decimal(\'8\'), Decimal(\'16\'))
Decimal(\'1\')
>>> c.power(Decimal(\'3\'), Decimal(\'7\'), Decimal(\'-16\'))
Decimal(\'11\')
>>> c.power(Decimal(\'23E12345\'), Decimal(\'67E189\'), Decimal(\'123456789\'))
Decimal(\'11729830\')
>>> c.power(Decimal(\'-0\'), Decimal(\'17\'), Decimal(\'1729\'))
Decimal(\'-0\')
>>> c.power(Decimal(\'-23\'), Decimal(\'0\'), Decimal(\'65537\'))
Decimal(\'1\')
>>> ExtendedContext.power(7, 7)
Decimal(\'823543\')
>>> ExtendedContext.power(Decimal(7), 7)
Decimal(\'823543\')
>>> ExtendedContext.power(7, Decimal(7), 2)
Decimal(\'1\')'
| def power(self, a, b, modulo=None):
| a = _convert_other(a, raiseit=True)
r = a.__pow__(b, modulo, context=self)
if (r is NotImplemented):
raise TypeError(('Unable to convert %s to Decimal' % b))
else:
return r
|
'Returns a value equal to \'a\' (rounded), having the exponent of \'b\'.
The coefficient of the result is derived from that of the left-hand
operand. It may be rounded using the current rounding setting (if the
exponent is being increased), multiplied by a positive power of ten (if
the exponent is being decreased), or is unchanged (if the exponent is
already equal to that of the right-hand operand).
Unlike other operations, if the length of the coefficient after the
quantize operation would be greater than precision then an Invalid
operation condition is raised. This guarantees that, unless there is
an error condition, the exponent of the result of a quantize is always
equal to that of the right-hand operand.
Also unlike other operations, quantize will never raise Underflow, even
if the result is subnormal and inexact.
>>> ExtendedContext.quantize(Decimal(\'2.17\'), Decimal(\'0.001\'))
Decimal(\'2.170\')
>>> ExtendedContext.quantize(Decimal(\'2.17\'), Decimal(\'0.01\'))
Decimal(\'2.17\')
>>> ExtendedContext.quantize(Decimal(\'2.17\'), Decimal(\'0.1\'))
Decimal(\'2.2\')
>>> ExtendedContext.quantize(Decimal(\'2.17\'), Decimal(\'1e+0\'))
Decimal(\'2\')
>>> ExtendedContext.quantize(Decimal(\'2.17\'), Decimal(\'1e+1\'))
Decimal(\'0E+1\')
>>> ExtendedContext.quantize(Decimal(\'-Inf\'), Decimal(\'Infinity\'))
Decimal(\'-Infinity\')
>>> ExtendedContext.quantize(Decimal(\'2\'), Decimal(\'Infinity\'))
Decimal(\'NaN\')
>>> ExtendedContext.quantize(Decimal(\'-0.1\'), Decimal(\'1\'))
Decimal(\'-0\')
>>> ExtendedContext.quantize(Decimal(\'-0\'), Decimal(\'1e+5\'))
Decimal(\'-0E+5\')
>>> ExtendedContext.quantize(Decimal(\'+35236450.6\'), Decimal(\'1e-2\'))
Decimal(\'NaN\')
>>> ExtendedContext.quantize(Decimal(\'-35236450.6\'), Decimal(\'1e-2\'))
Decimal(\'NaN\')
>>> ExtendedContext.quantize(Decimal(\'217\'), Decimal(\'1e-1\'))
Decimal(\'217.0\')
>>> ExtendedContext.quantize(Decimal(\'217\'), Decimal(\'1e-0\'))
Decimal(\'217\')
>>> ExtendedContext.quantize(Decimal(\'217\'), Decimal(\'1e+1\'))
Decimal(\'2.2E+2\')
>>> ExtendedContext.quantize(Decimal(\'217\'), Decimal(\'1e+2\'))
Decimal(\'2E+2\')
>>> ExtendedContext.quantize(1, 2)
Decimal(\'1\')
>>> ExtendedContext.quantize(Decimal(1), 2)
Decimal(\'1\')
>>> ExtendedContext.quantize(1, Decimal(2))
Decimal(\'1\')'
| def quantize(self, a, b):
| a = _convert_other(a, raiseit=True)
return a.quantize(b, context=self)
|
'Just returns 10, as this is Decimal, :)
>>> ExtendedContext.radix()
Decimal(\'10\')'
| def radix(self):
| return Decimal(10)
|
'Returns the remainder from integer division.
The result is the residue of the dividend after the operation of
calculating integer division as described for divide-integer, rounded
to precision digits if necessary. The sign of the result, if
non-zero, is the same as that of the original dividend.
This operation will fail under the same conditions as integer division
(that is, if integer division on the same two operands would fail, the
remainder cannot be calculated).
>>> ExtendedContext.remainder(Decimal(\'2.1\'), Decimal(\'3\'))
Decimal(\'2.1\')
>>> ExtendedContext.remainder(Decimal(\'10\'), Decimal(\'3\'))
Decimal(\'1\')
>>> ExtendedContext.remainder(Decimal(\'-10\'), Decimal(\'3\'))
Decimal(\'-1\')
>>> ExtendedContext.remainder(Decimal(\'10.2\'), Decimal(\'1\'))
Decimal(\'0.2\')
>>> ExtendedContext.remainder(Decimal(\'10\'), Decimal(\'0.3\'))
Decimal(\'0.1\')
>>> ExtendedContext.remainder(Decimal(\'3.6\'), Decimal(\'1.3\'))
Decimal(\'1.0\')
>>> ExtendedContext.remainder(22, 6)
Decimal(\'4\')
>>> ExtendedContext.remainder(Decimal(22), 6)
Decimal(\'4\')
>>> ExtendedContext.remainder(22, Decimal(6))
Decimal(\'4\')'
| def remainder(self, a, b):
| a = _convert_other(a, raiseit=True)
r = a.__mod__(b, context=self)
if (r is NotImplemented):
raise TypeError(('Unable to convert %s to Decimal' % b))
else:
return r
|
'Returns to be "a - b * n", where n is the integer nearest the exact
value of "x / b" (if two integers are equally near then the even one
is chosen). If the result is equal to 0 then its sign will be the
sign of a.
This operation will fail under the same conditions as integer division
(that is, if integer division on the same two operands would fail, the
remainder cannot be calculated).
>>> ExtendedContext.remainder_near(Decimal(\'2.1\'), Decimal(\'3\'))
Decimal(\'-0.9\')
>>> ExtendedContext.remainder_near(Decimal(\'10\'), Decimal(\'6\'))
Decimal(\'-2\')
>>> ExtendedContext.remainder_near(Decimal(\'10\'), Decimal(\'3\'))
Decimal(\'1\')
>>> ExtendedContext.remainder_near(Decimal(\'-10\'), Decimal(\'3\'))
Decimal(\'-1\')
>>> ExtendedContext.remainder_near(Decimal(\'10.2\'), Decimal(\'1\'))
Decimal(\'0.2\')
>>> ExtendedContext.remainder_near(Decimal(\'10\'), Decimal(\'0.3\'))
Decimal(\'0.1\')
>>> ExtendedContext.remainder_near(Decimal(\'3.6\'), Decimal(\'1.3\'))
Decimal(\'-0.3\')
>>> ExtendedContext.remainder_near(3, 11)
Decimal(\'3\')
>>> ExtendedContext.remainder_near(Decimal(3), 11)
Decimal(\'3\')
>>> ExtendedContext.remainder_near(3, Decimal(11))
Decimal(\'3\')'
| def remainder_near(self, a, b):
| a = _convert_other(a, raiseit=True)
return a.remainder_near(b, context=self)
|
'Returns a rotated copy of a, b times.
The coefficient of the result is a rotated copy of the digits in
the coefficient of the first operand. The number of places of
rotation is taken from the absolute value of the second operand,
with the rotation being to the left if the second operand is
positive or to the right otherwise.
>>> ExtendedContext.rotate(Decimal(\'34\'), Decimal(\'8\'))
Decimal(\'400000003\')
>>> ExtendedContext.rotate(Decimal(\'12\'), Decimal(\'9\'))
Decimal(\'12\')
>>> ExtendedContext.rotate(Decimal(\'123456789\'), Decimal(\'-2\'))
Decimal(\'891234567\')
>>> ExtendedContext.rotate(Decimal(\'123456789\'), Decimal(\'0\'))
Decimal(\'123456789\')
>>> ExtendedContext.rotate(Decimal(\'123456789\'), Decimal(\'+2\'))
Decimal(\'345678912\')
>>> ExtendedContext.rotate(1333333, 1)
Decimal(\'13333330\')
>>> ExtendedContext.rotate(Decimal(1333333), 1)
Decimal(\'13333330\')
>>> ExtendedContext.rotate(1333333, Decimal(1))
Decimal(\'13333330\')'
| def rotate(self, a, b):
| a = _convert_other(a, raiseit=True)
return a.rotate(b, context=self)
|
'Returns True if the two operands have the same exponent.
The result is never affected by either the sign or the coefficient of
either operand.
>>> ExtendedContext.same_quantum(Decimal(\'2.17\'), Decimal(\'0.001\'))
False
>>> ExtendedContext.same_quantum(Decimal(\'2.17\'), Decimal(\'0.01\'))
True
>>> ExtendedContext.same_quantum(Decimal(\'2.17\'), Decimal(\'1\'))
False
>>> ExtendedContext.same_quantum(Decimal(\'Inf\'), Decimal(\'-Inf\'))
True
>>> ExtendedContext.same_quantum(10000, -1)
True
>>> ExtendedContext.same_quantum(Decimal(10000), -1)
True
>>> ExtendedContext.same_quantum(10000, Decimal(-1))
True'
| def same_quantum(self, a, b):
| a = _convert_other(a, raiseit=True)
return a.same_quantum(b)
|
'Returns the first operand after adding the second value its exp.
>>> ExtendedContext.scaleb(Decimal(\'7.50\'), Decimal(\'-2\'))
Decimal(\'0.0750\')
>>> ExtendedContext.scaleb(Decimal(\'7.50\'), Decimal(\'0\'))
Decimal(\'7.50\')
>>> ExtendedContext.scaleb(Decimal(\'7.50\'), Decimal(\'3\'))
Decimal(\'7.50E+3\')
>>> ExtendedContext.scaleb(1, 4)
Decimal(\'1E+4\')
>>> ExtendedContext.scaleb(Decimal(1), 4)
Decimal(\'1E+4\')
>>> ExtendedContext.scaleb(1, Decimal(4))
Decimal(\'1E+4\')'
| def scaleb(self, a, b):
| a = _convert_other(a, raiseit=True)
return a.scaleb(b, context=self)
|
'Returns a shifted copy of a, b times.
The coefficient of the result is a shifted copy of the digits
in the coefficient of the first operand. The number of places
to shift is taken from the absolute value of the second operand,
with the shift being to the left if the second operand is
positive or to the right otherwise. Digits shifted into the
coefficient are zeros.
>>> ExtendedContext.shift(Decimal(\'34\'), Decimal(\'8\'))
Decimal(\'400000000\')
>>> ExtendedContext.shift(Decimal(\'12\'), Decimal(\'9\'))
Decimal(\'0\')
>>> ExtendedContext.shift(Decimal(\'123456789\'), Decimal(\'-2\'))
Decimal(\'1234567\')
>>> ExtendedContext.shift(Decimal(\'123456789\'), Decimal(\'0\'))
Decimal(\'123456789\')
>>> ExtendedContext.shift(Decimal(\'123456789\'), Decimal(\'+2\'))
Decimal(\'345678900\')
>>> ExtendedContext.shift(88888888, 2)
Decimal(\'888888800\')
>>> ExtendedContext.shift(Decimal(88888888), 2)
Decimal(\'888888800\')
>>> ExtendedContext.shift(88888888, Decimal(2))
Decimal(\'888888800\')'
| def shift(self, a, b):
| a = _convert_other(a, raiseit=True)
return a.shift(b, context=self)
|
'Square root of a non-negative number to context precision.
If the result must be inexact, it is rounded using the round-half-even
algorithm.
>>> ExtendedContext.sqrt(Decimal(\'0\'))
Decimal(\'0\')
>>> ExtendedContext.sqrt(Decimal(\'-0\'))
Decimal(\'-0\')
>>> ExtendedContext.sqrt(Decimal(\'0.39\'))
Decimal(\'0.624499800\')
>>> ExtendedContext.sqrt(Decimal(\'100\'))
Decimal(\'10\')
>>> ExtendedContext.sqrt(Decimal(\'1\'))
Decimal(\'1\')
>>> ExtendedContext.sqrt(Decimal(\'1.0\'))
Decimal(\'1.0\')
>>> ExtendedContext.sqrt(Decimal(\'1.00\'))
Decimal(\'1.0\')
>>> ExtendedContext.sqrt(Decimal(\'7\'))
Decimal(\'2.64575131\')
>>> ExtendedContext.sqrt(Decimal(\'10\'))
Decimal(\'3.16227766\')
>>> ExtendedContext.sqrt(2)
Decimal(\'1.41421356\')
>>> ExtendedContext.prec
9'
| def sqrt(self, a):
| a = _convert_other(a, raiseit=True)
return a.sqrt(context=self)
|
'Return the difference between the two operands.
>>> ExtendedContext.subtract(Decimal(\'1.3\'), Decimal(\'1.07\'))
Decimal(\'0.23\')
>>> ExtendedContext.subtract(Decimal(\'1.3\'), Decimal(\'1.30\'))
Decimal(\'0.00\')
>>> ExtendedContext.subtract(Decimal(\'1.3\'), Decimal(\'2.07\'))
Decimal(\'-0.77\')
>>> ExtendedContext.subtract(8, 5)
Decimal(\'3\')
>>> ExtendedContext.subtract(Decimal(8), 5)
Decimal(\'3\')
>>> ExtendedContext.subtract(8, Decimal(5))
Decimal(\'3\')'
| def subtract(self, a, b):
| a = _convert_other(a, raiseit=True)
r = a.__sub__(b, context=self)
if (r is NotImplemented):
raise TypeError(('Unable to convert %s to Decimal' % b))
else:
return r
|
'Converts a number to a string, using scientific notation.
The operation is not affected by the context.'
| def to_eng_string(self, a):
| a = _convert_other(a, raiseit=True)
return a.to_eng_string(context=self)
|
'Converts a number to a string, using scientific notation.
The operation is not affected by the context.'
| def to_sci_string(self, a):
| a = _convert_other(a, raiseit=True)
return a.__str__(context=self)
|
'Rounds to an integer.
When the operand has a negative exponent, the result is the same
as using the quantize() operation using the given operand as the
left-hand-operand, 1E+0 as the right-hand-operand, and the precision
of the operand as the precision setting; Inexact and Rounded flags
are allowed in this operation. The rounding mode is taken from the
context.
>>> ExtendedContext.to_integral_exact(Decimal(\'2.1\'))
Decimal(\'2\')
>>> ExtendedContext.to_integral_exact(Decimal(\'100\'))
Decimal(\'100\')
>>> ExtendedContext.to_integral_exact(Decimal(\'100.0\'))
Decimal(\'100\')
>>> ExtendedContext.to_integral_exact(Decimal(\'101.5\'))
Decimal(\'102\')
>>> ExtendedContext.to_integral_exact(Decimal(\'-101.5\'))
Decimal(\'-102\')
>>> ExtendedContext.to_integral_exact(Decimal(\'10E+5\'))
Decimal(\'1.0E+6\')
>>> ExtendedContext.to_integral_exact(Decimal(\'7.89E+77\'))
Decimal(\'7.89E+77\')
>>> ExtendedContext.to_integral_exact(Decimal(\'-Inf\'))
Decimal(\'-Infinity\')'
| def to_integral_exact(self, a):
| a = _convert_other(a, raiseit=True)
return a.to_integral_exact(context=self)
|
'Rounds to an integer.
When the operand has a negative exponent, the result is the same
as using the quantize() operation using the given operand as the
left-hand-operand, 1E+0 as the right-hand-operand, and the precision
of the operand as the precision setting, except that no flags will
be set. The rounding mode is taken from the context.
>>> ExtendedContext.to_integral_value(Decimal(\'2.1\'))
Decimal(\'2\')
>>> ExtendedContext.to_integral_value(Decimal(\'100\'))
Decimal(\'100\')
>>> ExtendedContext.to_integral_value(Decimal(\'100.0\'))
Decimal(\'100\')
>>> ExtendedContext.to_integral_value(Decimal(\'101.5\'))
Decimal(\'102\')
>>> ExtendedContext.to_integral_value(Decimal(\'-101.5\'))
Decimal(\'-102\')
>>> ExtendedContext.to_integral_value(Decimal(\'10E+5\'))
Decimal(\'1.0E+6\')
>>> ExtendedContext.to_integral_value(Decimal(\'7.89E+77\'))
Decimal(\'7.89E+77\')
>>> ExtendedContext.to_integral_value(Decimal(\'-Inf\'))
Decimal(\'-Infinity\')'
| def to_integral_value(self, a):
| a = _convert_other(a, raiseit=True)
return a.to_integral_value(context=self)
|
'Given an integer p >= 0, return floor(10**p)*log(10).
For example, self.getdigits(3) returns 2302.'
| def getdigits(self, p):
| if (p < 0):
raise ValueError('p should be nonnegative')
if (p >= len(self.digits)):
extra = 3
while True:
M = (10 ** ((p + extra) + 2))
digits = str(_div_nearest(_ilog((10 * M), M), 100))
if (digits[(- extra):] != ('0' * extra)):
break
extra += 3
self.digits = digits.rstrip('0')[:(-1)]
return int(self.digits[:(p + 1)])
|
'Create a new HMAC object.
key: key for the keyed hash object.
msg: Initial input for the hash, if provided.
digestmod: A module supporting PEP 247. *OR*
A hashlib constructor returning a new hash object.
Defaults to hashlib.md5.'
| def __init__(self, key, msg=None, digestmod=None):
| if (key is _secret_backdoor_key):
return
if (digestmod is None):
import hashlib
digestmod = hashlib.md5
if hasattr(digestmod, '__call__'):
self.digest_cons = digestmod
else:
self.digest_cons = (lambda d='': digestmod.new(d))
self.outer = self.digest_cons()
self.inner = self.digest_cons()
self.digest_size = self.inner.digest_size
if hasattr(self.inner, 'block_size'):
blocksize = self.inner.block_size
if (blocksize < 16):
_warnings.warn(('block_size of %d seems too small; using our default of %d.' % (blocksize, self.blocksize)), RuntimeWarning, 2)
blocksize = self.blocksize
else:
_warnings.warn(('No block_size attribute on given digest object; Assuming %d.' % self.blocksize), RuntimeWarning, 2)
blocksize = self.blocksize
if (len(key) > blocksize):
key = self.digest_cons(key).digest()
key = (key + (chr(0) * (blocksize - len(key))))
self.outer.update(key.translate(trans_5C))
self.inner.update(key.translate(trans_36))
if (msg is not None):
self.update(msg)
|
'Update this hashing object with the string msg.'
| def update(self, msg):
| self.inner.update(msg)
|
'Return a separate copy of this hashing object.
An update to this copy won\'t affect the original object.'
| def copy(self):
| other = self.__class__(_secret_backdoor_key)
other.digest_cons = self.digest_cons
other.digest_size = self.digest_size
other.inner = self.inner.copy()
other.outer = self.outer.copy()
return other
|
'Return a hash object for the current state.
To be used only internally with digest() and hexdigest().'
| def _current(self):
| h = self.outer.copy()
h.update(self.inner.digest())
return h
|
'Return the hash value of this hashing object.
This returns a string containing 8-bit data. The object is
not altered in any way by this function; you can continue
updating the object after calling this function.'
| def digest(self):
| h = self._current()
return h.digest()
|
'Like digest(), but returns a string of hexadecimal digits instead.'
| def hexdigest(self):
| h = self._current()
return h.hexdigest()
|
'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'):
| self._testMethodName = methodName
self._resultForDoCleanups = None
try:
testMethod = getattr(self, methodName)
except AttributeError:
raise ValueError(('no such test method in %s: %s' % (self.__class__, methodName)))
self._testMethodDoc = testMethod.__doc__
self._cleanups = []
self._type_equality_funcs = {}
self.addTypeEqualityFunc(dict, self.assertDictEqual)
self.addTypeEqualityFunc(list, self.assertListEqual)
self.addTypeEqualityFunc(tuple, self.assertTupleEqual)
self.addTypeEqualityFunc(set, self.assertSetEqual)
self.addTypeEqualityFunc(frozenset, self.assertSetEqual)
self.addTypeEqualityFunc(unicode, self.assertMultiLineEqual)
|
'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):
| self._type_equality_funcs[typeobj] = function
|
'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):
| self._cleanups.append((function, args, kwargs))
|
'Hook method for setting up the test fixture before exercising it.'
| def setUp(self):
| pass
|
'Hook method for deconstructing the test fixture after testing it.'
| def tearDown(self):
| pass
|
'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):
| doc = self._testMethodDoc
return ((doc and doc.split('\n')[0].strip()) or None)
|
'Execute all cleanup functions. Normally called for you after
tearDown.'
| def doCleanups(self):
| result = self._resultForDoCleanups
ok = True
while self._cleanups:
(function, args, kwargs) = self._cleanups.pop((-1))
try:
function(*args, **kwargs)
except KeyboardInterrupt:
raise
except:
ok = False
result.addError(self, sys.exc_info())
return ok
|
'Run the test without collecting errors in a TestResult'
| def debug(self):
| self.setUp()
getattr(self, self._testMethodName)()
self.tearDown()
while self._cleanups:
(function, args, kwargs) = self._cleanups.pop((-1))
function(*args, **kwargs)
|
'Skip this test.'
| def skipTest(self, reason):
| raise SkipTest(reason)
|
'Fail immediately, with the given message.'
| def fail(self, msg=None):
| raise self.failureException(msg)
|
'Check that the expression is false.'
| def assertFalse(self, expr, msg=None):
| if expr:
msg = self._formatMessage(msg, ('%s is not false' % safe_repr(expr)))
raise self.failureException(msg)
|
'Check that the expression is true.'
| def assertTrue(self, expr, msg=None):
| if (not expr):
msg = self._formatMessage(msg, ('%s is not true' % safe_repr(expr)))
raise self.failureException(msg)
|
'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):
| if (not self.longMessage):
return (msg or standardMsg)
if (msg is None):
return standardMsg
try:
return ('%s : %s' % (standardMsg, msg))
except UnicodeDecodeError:
return ('%s : %s' % (safe_repr(standardMsg), safe_repr(msg)))
|
'Fail unless an exception of class excClass is thrown
by callableObj when invoked with arguments args and keyword
arguments kwargs. If a different type of exception is
thrown, 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 callableObj omitted or None, will return a
context object used like this::
with self.assertRaises(SomeException):
do_something()
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, excClass, callableObj=None, *args, **kwargs):
| context = _AssertRaisesContext(excClass, self)
if (callableObj is None):
return context
with context:
callableObj(*args, **kwargs)
|
'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):
| if (type(first) is type(second)):
asserter = self._type_equality_funcs.get(type(first))
if (asserter is not None):
return asserter
return self._baseAssertEqual
|
'The default assertEqual implementation, not type specific.'
| def _baseAssertEqual(self, first, second, msg=None):
| if (not (first == second)):
standardMsg = ('%s != %s' % (safe_repr(first), safe_repr(second)))
msg = self._formatMessage(msg, standardMsg)
raise self.failureException(msg)
|
'Fail if the two objects are unequal as determined by the \'==\'
operator.'
| def assertEqual(self, first, second, msg=None):
| assertion_func = self._getAssertEqualityFunc(first, second)
assertion_func(first, second, msg=msg)
|
'Fail if the two objects are equal as determined by the \'==\'
operator.'
| def assertNotEqual(self, first, second, msg=None):
| if (not (first != second)):
msg = self._formatMessage(msg, ('%s == %s' % (safe_repr(first), safe_repr(second))))
raise self.failureException(msg)
|
'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
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 signficant 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):
| if (first == second):
return
if ((delta is not None) and (places is not None)):
raise TypeError('specify delta or places not both')
if (delta is not None):
if (abs((first - second)) <= delta):
return
standardMsg = ('%s != %s within %s delta' % (safe_repr(first), safe_repr(second), safe_repr(delta)))
else:
if (places is None):
places = 7
if (round(abs((second - first)), 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)
|
'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
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 signficant digit).
Objects that are equal automatically fail.'
| def assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None):
| if ((delta is not None) and (places is not None)):
raise TypeError('specify delta or places not both')
if (delta is not None):
if ((not (first == second)) and (abs((first - second)) > delta)):
return
standardMsg = ('%s == %s within %s delta' % (safe_repr(first), safe_repr(second), safe_repr(delta)))
else:
if (places is None):
places = 7
if ((not (first == second)) and (round(abs((second - first)), 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)
|
'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):
| 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
seq1_repr = safe_repr(seq1)
seq2_repr = safe_repr(seq2)
if (len(seq1_repr) > 30):
seq1_repr = (seq1_repr[:30] + '...')
if (len(seq2_repr) > 30):
seq2_repr = (seq2_repr[:30] + '...')
elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr)
differing = ('%ss differ: %s != %s\n' % elements)
for i in xrange(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, item1, item2))
break
else:
if ((len1 == len2) and (seq_type is None) and (type(seq1) != type(seq2))):
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, 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, 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)
|
'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):
| self.assertSequenceEqual(list1, list2, msg, seq_type=list)
|
'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):
| self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
|
'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):
| 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))
|
'Just like self.assertTrue(a in b), but with a nicer default message.'
| def assertIn(self, member, container, msg=None):
| if (member not in container):
standardMsg = ('%s not found in %s' % (safe_repr(member), safe_repr(container)))
self.fail(self._formatMessage(msg, standardMsg))
|
'Just like self.assertTrue(a not in b), but with a nicer default message.'
| def assertNotIn(self, member, container, msg=None):
| if (member in container):
standardMsg = ('%s unexpectedly found in %s' % (safe_repr(member), safe_repr(container)))
self.fail(self._formatMessage(msg, standardMsg))
|
'Just like self.assertTrue(a is b), but with a nicer default message.'
| def assertIs(self, expr1, expr2, msg=None):
| if (expr1 is not expr2):
standardMsg = ('%s is not %s' % (safe_repr(expr1), safe_repr(expr2)))
self.fail(self._formatMessage(msg, standardMsg))
|
'Just like self.assertTrue(a is not b), but with a nicer default message.'
| def assertIsNot(self, expr1, expr2, msg=None):
| if (expr1 is expr2):
standardMsg = ('unexpectedly identical: %s' % (safe_repr(expr1),))
self.fail(self._formatMessage(msg, standardMsg))
|
'Checks whether actual is a superset of expected.'
| def assertDictContainsSubset(self, expected, actual, msg=None):
| missing = []
mismatched = []
for (key, value) in expected.iteritems():
if (key not in actual):
missing.append(key)
elif (value != actual[key]):
mismatched.append(('%s, expected: %s, actual: %s' % (safe_repr(key), safe_repr(value), safe_repr(actual[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))
|
'An unordered sequence specific comparison. It asserts that
actual_seq and expected_seq have the same element counts.
Equivalent to::
self.assertEqual(Counter(iter(actual_seq)),
Counter(iter(expected_seq)))
Asserts that each element has the same count in both sequences.
Example:
- [0, 1, 1] and [1, 0, 1] compare equal.
- [0, 0, 1] and [0, 1] compare unequal.'
| def assertItemsEqual(self, expected_seq, actual_seq, msg=None):
| (first_seq, second_seq) = (list(actual_seq), list(expected_seq))
with warnings.catch_warnings():
if sys.py3kwarning:
for _msg in ['(code|dict|type) inequality comparisons', 'builtin_function_or_method order comparisons', 'comparing unequal types']:
warnings.filterwarnings('ignore', _msg, DeprecationWarning)
try:
first = collections.Counter(first_seq)
second = collections.Counter(second_seq)
except TypeError:
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)
|
'Assert that two multi-line strings are equal.'
| def assertMultiLineEqual(self, first, second, msg=None):
| self.assertIsInstance(first, basestring, 'First argument is not a string')
self.assertIsInstance(second, basestring, 'Second argument is not a string')
if (first != second):
if ((len(first) > self._diffThreshold) or (len(second) > self._diffThreshold)):
self._baseAssertEqual(first, second, msg)
firstlines = first.splitlines(True)
secondlines = second.splitlines(True)
if ((len(firstlines) == 1) and (first.strip('\r\n') == first)):
firstlines = [(first + '\n')]
secondlines = [(second + '\n')]
standardMsg = ('%s != %s' % (safe_repr(first, True), safe_repr(second, True)))
diff = ('\n' + ''.join(difflib.ndiff(firstlines, secondlines)))
standardMsg = self._truncateMessage(standardMsg, diff)
self.fail(self._formatMessage(msg, standardMsg))
|
'Just like self.assertTrue(a < b), but with a nicer default message.'
| def assertLess(self, a, b, msg=None):
| if (not (a < b)):
standardMsg = ('%s not less than %s' % (safe_repr(a), safe_repr(b)))
self.fail(self._formatMessage(msg, standardMsg))
|
'Just like self.assertTrue(a <= b), but with a nicer default message.'
| def assertLessEqual(self, a, b, msg=None):
| 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))
|
'Just like self.assertTrue(a > b), but with a nicer default message.'
| def assertGreater(self, a, b, msg=None):
| if (not (a > b)):
standardMsg = ('%s not greater than %s' % (safe_repr(a), safe_repr(b)))
self.fail(self._formatMessage(msg, standardMsg))
|
'Just like self.assertTrue(a >= b), but with a nicer default message.'
| def assertGreaterEqual(self, a, b, msg=None):
| 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))
|
'Same as self.assertTrue(obj is None), with a nicer default message.'
| def assertIsNone(self, obj, msg=None):
| if (obj is not None):
standardMsg = ('%s is not None' % (safe_repr(obj),))
self.fail(self._formatMessage(msg, standardMsg))
|
'Included for symmetry with assertIsNone.'
| def assertIsNotNone(self, obj, msg=None):
| if (obj is None):
standardMsg = 'unexpectedly None'
self.fail(self._formatMessage(msg, standardMsg))
|
'Same as self.assertTrue(isinstance(obj, cls)), with a nicer
default message.'
| def assertIsInstance(self, obj, cls, msg=None):
| if (not isinstance(obj, cls)):
standardMsg = ('%s is not an instance of %r' % (safe_repr(obj), cls))
self.fail(self._formatMessage(msg, standardMsg))
|
'Included for symmetry with assertIsInstance.'
| def assertNotIsInstance(self, obj, cls, msg=None):
| if isinstance(obj, cls):
standardMsg = ('%s is an instance of %r' % (safe_repr(obj), cls))
self.fail(self._formatMessage(msg, standardMsg))
|
'Asserts that the message in a raised exception matches a regexp.
Args:
expected_exception: Exception class expected to be raised.
expected_regexp: Regexp (re pattern object or string) expected
to be found in error message.
callable_obj: Function to be called.
args: Extra args.
kwargs: Extra kwargs.'
| def assertRaisesRegexp(self, expected_exception, expected_regexp, callable_obj=None, *args, **kwargs):
| context = _AssertRaisesContext(expected_exception, self, expected_regexp)
if (callable_obj is None):
return context
with context:
callable_obj(*args, **kwargs)
|
'Fail the test unless the text matches the regular expression.'
| def assertRegexpMatches(self, text, expected_regexp, msg=None):
| if isinstance(expected_regexp, basestring):
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))
raise self.failureException(msg)
|
'Fail the test if the text matches the regular expression.'
| def assertNotRegexpMatches(self, text, unexpected_regexp, msg=None):
| if isinstance(unexpected_regexp, basestring):
unexpected_regexp = re.compile(unexpected_regexp)
match = unexpected_regexp.search(text)
if match:
msg = (msg or 'Regexp matched')
msg = ('%s: %r matches %r in %r' % (msg, text[match.start():match.end()], unexpected_regexp.pattern, text))
raise self.failureException(msg)
|
'Called when the given test is about to be run'
| def startTest(self, test):
| self.testsRun += 1
self._mirrorOutput = False
self._setupStdout()
|
'Called when the given test has been run'
| def stopTest(self, test):
| self._restoreStdout()
self._mirrorOutput = False
|
'Called when an error has occurred. \'err\' is a tuple of values as
returned by sys.exc_info().'
| @failfast
def addError(self, test, err):
| self.errors.append((test, self._exc_info_to_string(err, test)))
self._mirrorOutput = True
|
'Called when an error has occurred. \'err\' is a tuple of values as
returned by sys.exc_info().'
| @failfast
def addFailure(self, test, err):
| self.failures.append((test, self._exc_info_to_string(err, test)))
self._mirrorOutput = True
|
'Called when a test has completed successfully'
| def addSuccess(self, test):
| pass
|
'Called when a test is skipped.'
| def addSkip(self, test, reason):
| self.skipped.append((test, reason))
|
'Called when an expected failure/error occured.'
| def addExpectedFailure(self, test, err):
| self.expectedFailures.append((test, self._exc_info_to_string(err, test)))
|
'Called when a test was expected to fail, but succeed.'
| @failfast
def addUnexpectedSuccess(self, test):
| self.unexpectedSuccesses.append(test)
|
'Tells whether or not this result was a success'
| def wasSuccessful(self):
| return (len(self.failures) == len(self.errors) == 0)
|
'Indicates that the tests should be aborted'
| def stop(self):
| self.shouldStop = True
|
'Converts a sys.exc_info()-style tuple of values into a string.'
| def _exc_info_to_string(self, err, test):
| (exctype, value, tb) = err
while (tb and self._is_relevant_tb_level(tb)):
tb = tb.tb_next
if (exctype is test.failureException):
length = self._count_relevant_tb_levels(tb)
msgLines = traceback.format_exception(exctype, value, tb, length)
else:
msgLines = traceback.format_exception(exctype, value, tb)
if self.buffer:
output = sys.stdout.getvalue()
error = sys.stderr.getvalue()
if output:
if (not output.endswith('\n')):
output += '\n'
msgLines.append((STDOUT_LINE % output))
if error:
if (not error.endswith('\n')):
error += '\n'
msgLines.append((STDERR_LINE % error))
return ''.join(msgLines)
|
'Run the given test case or test suite.'
| def run(self, test):
| result = self._makeResult()
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()
timeTaken = (stopTime - startTime)
result.printErrors()
if hasattr(result, 'separator2'):
self.stream.writeln(result.separator2)
run = result.testsRun
self.stream.writeln(('Ran %d test%s in %.3fs' % (run, (((run != 1) and 's') or ''), timeTaken)))
self.stream.writeln()
expectedFails = unexpectedSuccesses = skipped = 0
try:
results = map(len, (result.expectedFailures, result.unexpectedSuccesses, result.skipped))
except AttributeError:
pass
else:
(expectedFails, unexpectedSuccesses, skipped) = results
infos = []
if (not result.wasSuccessful()):
self.stream.write('FAILED')
(failed, errored) = map(len, (result.failures, result.errors))
if failed:
infos.append(('failures=%d' % failed))
if errored:
infos.append(('errors=%d' % errored))
else:
self.stream.write('OK')
if skipped:
infos.append(('skipped=%d' % skipped))
if expectedFails:
infos.append(('expected failures=%d' % expectedFails))
if unexpectedSuccesses:
infos.append(('unexpected successes=%d' % unexpectedSuccesses))
if infos:
self.stream.writeln((' (%s)' % (', '.join(infos),)))
else:
self.stream.write('\n')
return result
|
'Return a suite of all tests cases contained in testCaseClass'
| def loadTestsFromTestCase(self, testCaseClass):
| if issubclass(testCaseClass, suite.TestSuite):
raise TypeError('Test cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?')
testCaseNames = self.getTestCaseNames(testCaseClass)
if ((not testCaseNames) and hasattr(testCaseClass, 'runTest')):
testCaseNames = ['runTest']
loaded_suite = self.suiteClass(map(testCaseClass, testCaseNames))
return loaded_suite
|
'Return a suite of all tests cases contained in the given module'
| def loadTestsFromModule(self, module, use_load_tests=True):
| tests = []
for name in dir(module):
obj = getattr(module, name)
if (isinstance(obj, type) and issubclass(obj, case.TestCase)):
tests.append(self.loadTestsFromTestCase(obj))
load_tests = getattr(module, 'load_tests', None)
tests = self.suiteClass(tests)
if (use_load_tests and (load_tests is not None)):
try:
return load_tests(self, tests, None)
except Exception as e:
return _make_failed_load_tests(module.__name__, e, self.suiteClass)
return tests
|
'Return a suite of all tests cases given a string specifier.
The name may resolve either to a module, a test case class, a
test method within a test case class, or a callable object which
returns a TestCase or TestSuite instance.
The method optionally resolves the names relative to a given module.'
| def loadTestsFromName(self, name, module=None):
| parts = name.split('.')
if (module is None):
parts_copy = parts[:]
while parts_copy:
try:
module = __import__('.'.join(parts_copy))
break
except ImportError:
del parts_copy[(-1)]
if (not parts_copy):
raise
parts = parts[1:]
obj = module
for part in parts:
(parent, obj) = (obj, getattr(obj, part))
if isinstance(obj, types.ModuleType):
return self.loadTestsFromModule(obj)
elif (isinstance(obj, type) and issubclass(obj, case.TestCase)):
return self.loadTestsFromTestCase(obj)
elif (isinstance(obj, types.UnboundMethodType) and isinstance(parent, type) and issubclass(parent, case.TestCase)):
return self.suiteClass([parent(obj.__name__)])
elif isinstance(obj, suite.TestSuite):
return obj
elif hasattr(obj, '__call__'):
test = obj()
if isinstance(test, suite.TestSuite):
return test
elif isinstance(test, case.TestCase):
return self.suiteClass([test])
else:
raise TypeError(('calling %s returned %s, not a test' % (obj, test)))
else:
raise TypeError(("don't know how to make test from: %s" % obj))
|
'Return a suite of all tests cases found using the given sequence
of string specifiers. See \'loadTestsFromName()\'.'
| def loadTestsFromNames(self, names, module=None):
| suites = [self.loadTestsFromName(name, module) for name in names]
return self.suiteClass(suites)
|
'Return a sorted sequence of method names found within testCaseClass'
| def getTestCaseNames(self, testCaseClass):
| def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):
return (attrname.startswith(prefix) and hasattr(getattr(testCaseClass, attrname), '__call__'))
testFnNames = filter(isTestMethod, dir(testCaseClass))
if self.sortTestMethodsUsing:
testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing))
return testFnNames
|
'Find and return all test modules from the specified start
directory, recursing into subdirectories to find them. Only test files
that match the pattern will be loaded. (Using shell style pattern
matching.)
All test modules must be importable from the top level of the project.
If the start directory is not the top level directory then the top
level directory must be specified separately.
If a test package name (directory with \'__init__.py\') matches the
pattern then the package will be checked for a \'load_tests\' function. If
this exists then it will be called with loader, tests, pattern.
If load_tests exists then discovery does *not* recurse into the package,
load_tests is responsible for loading all tests in the package.
The pattern is deliberately not stored as a loader attribute so that
packages can continue discovery themselves. top_level_dir is stored so
load_tests does not need to pass this argument in to loader.discover().'
| def discover(self, start_dir, pattern='test*.py', top_level_dir=None):
| set_implicit_top = False
if ((top_level_dir is None) and (self._top_level_dir is not None)):
top_level_dir = self._top_level_dir
elif (top_level_dir is None):
set_implicit_top = True
top_level_dir = start_dir
top_level_dir = os.path.abspath(top_level_dir)
if (not (top_level_dir in sys.path)):
sys.path.insert(0, top_level_dir)
self._top_level_dir = top_level_dir
is_not_importable = False
if os.path.isdir(os.path.abspath(start_dir)):
start_dir = os.path.abspath(start_dir)
if (start_dir != top_level_dir):
is_not_importable = (not os.path.isfile(os.path.join(start_dir, '__init__.py')))
else:
try:
__import__(start_dir)
except ImportError:
is_not_importable = True
else:
the_module = sys.modules[start_dir]
top_part = start_dir.split('.')[0]
start_dir = os.path.abspath(os.path.dirname(the_module.__file__))
if set_implicit_top:
self._top_level_dir = self._get_directory_containing_module(top_part)
sys.path.remove(top_level_dir)
if is_not_importable:
raise ImportError(('Start directory is not importable: %r' % start_dir))
tests = list(self._find_tests(start_dir, pattern))
return self.suiteClass(tests)
|
'Used by discovery. Yields test suites it loads.'
| def _find_tests(self, start_dir, pattern):
| paths = os.listdir(start_dir)
for path in paths:
full_path = os.path.join(start_dir, path)
if os.path.isfile(full_path):
if (not VALID_MODULE_NAME.match(path)):
continue
if (not self._match_path(path, full_path, pattern)):
continue
name = self._get_name_from_path(full_path)
try:
module = self._get_module_from_name(name)
except:
(yield _make_failed_import_test(name, self.suiteClass))
else:
mod_file = os.path.abspath(getattr(module, '__file__', full_path))
realpath = os.path.splitext(mod_file)[0]
fullpath_noext = os.path.splitext(full_path)[0]
if (realpath.lower() != fullpath_noext.lower()):
module_dir = os.path.dirname(realpath)
mod_name = os.path.splitext(os.path.basename(full_path))[0]
expected_dir = os.path.dirname(full_path)
msg = '%r module incorrectly imported from %r. Expected %r. Is this module globally installed?'
raise ImportError((msg % (mod_name, module_dir, expected_dir)))
(yield self.loadTestsFromModule(module))
elif os.path.isdir(full_path):
if (not os.path.isfile(os.path.join(full_path, '__init__.py'))):
continue
load_tests = None
tests = None
if fnmatch(path, pattern):
name = self._get_name_from_path(full_path)
package = self._get_module_from_name(name)
load_tests = getattr(package, 'load_tests', None)
tests = self.loadTestsFromModule(package, use_load_tests=False)
if (load_tests is None):
if (tests is not None):
(yield tests)
for test in self._find_tests(full_path, pattern):
(yield test)
else:
try:
(yield load_tests(self, tests, pattern))
except Exception as e:
(yield _make_failed_load_tests(package.__name__, e, self.suiteClass))
|
'Tests shortDescription() for a method with a docstring.'
| @unittest.skipIf((sys.flags.optimize >= 2), 'Docstrings are omitted with -O2 and above')
def testShortDescriptionWithOneLineDocstring(self):
| self.assertEqual(self.shortDescription(), 'Tests shortDescription() for a method with a docstring.')
|
'Tests shortDescription() for a method with a longer docstring.
This method ensures that only the first line of a docstring is
returned used in the short description, no matter how long the
whole thing is.'
| @unittest.skipIf((sys.flags.optimize >= 2), 'Docstrings are omitted with -O2 and above')
def testShortDescriptionWithMultiLineDocstring(self):
| self.assertEqual(self.shortDescription(), 'Tests shortDescription() for a method with a longer docstring.')
|
'Test undocumented method name synonyms.
Please do not use these methods names in your own code.
This test confirms their continued existence and functionality
in order to avoid breaking existing code.'
| def testSynonymAssertMethodNames(self):
| self.assertNotEquals(3, 5)
self.assertEquals(3, 3)
self.assertAlmostEquals(2.0, 2.0)
self.assertNotAlmostEquals(3.0, 5.0)
self.assert_(True)
|
'Test fail* methods pending deprecation, they will warn in 3.2.
Do not use these methods. They will go away in 3.3.'
| def testPendingDeprecationMethodNames(self):
| with test_support.check_warnings():
self.failIfEqual(3, 5)
self.failUnlessEqual(3, 3)
self.failUnlessAlmostEqual(2.0, 2.0)
self.failIfAlmostEqual(3.0, 5.0)
self.failUnless(True)
self.failUnlessRaises(TypeError, (lambda _: (3.14 + u'spam')))
self.failIf(False)
|
'Tests getDescription() for a method with a docstring.'
| @unittest.skipIf((sys.flags.optimize >= 2), 'Docstrings are omitted with -O2 and above')
def testGetDescriptionWithOneLineDocstring(self):
| result = unittest.TextTestResult(None, True, 1)
self.assertEqual(result.getDescription(self), (('testGetDescriptionWithOneLineDocstring (' + __name__) + '.Test_TestResult)\nTests getDescription() for a method with a docstring.'))
|
'Tests getDescription() for a method with a longer docstring.
The second line of the docstring.'
| @unittest.skipIf((sys.flags.optimize >= 2), 'Docstrings are omitted with -O2 and above')
def testGetDescriptionWithMultiLineDocstring(self):
| result = unittest.TextTestResult(None, True, 1)
self.assertEqual(result.getDescription(self), (('testGetDescriptionWithMultiLineDocstring (' + __name__) + '.Test_TestResult)\nTests getDescription() for a method with a longer docstring.'))
|
'Run the tests without collecting errors in a TestResult'
| def debug(self):
| for test in self:
test.debug()
|
'Run the tests without collecting errors in a TestResult'
| def debug(self):
| debug = _DebugResult()
self.run(debug, True)
|
'A file object is its own iterator, for example iter(f) returns f
(unless f is closed). When a file is used as an iterator, typically
in a for loop (for example, for line in f: print line), the next()
method is called repeatedly. This method returns the next input line,
or raises StopIteration when EOF is hit.'
| def next(self):
| _complain_ifclosed(self.closed)
r = self.readline()
if (not r):
raise StopIteration
return r
|
'Free the memory buffer.'
| def close(self):
| if (not self.closed):
self.closed = True
del self.buf, self.pos
|
'Returns False because StringIO objects are not connected to a
tty-like device.'
| def isatty(self):
| _complain_ifclosed(self.closed)
return False
|
'Set the file\'s current position.
The mode argument is optional and defaults to 0 (absolute file
positioning); other values are 1 (seek relative to the current
position) and 2 (seek relative to the file\'s end).
There is no return value.'
| def seek(self, pos, mode=0):
| _complain_ifclosed(self.closed)
if self.buflist:
self.buf += ''.join(self.buflist)
self.buflist = []
if (mode == 1):
pos += self.pos
elif (mode == 2):
pos += self.len
self.pos = max(0, pos)
|
'Return the file\'s current position.'
| def tell(self):
| _complain_ifclosed(self.closed)
return self.pos
|
'Read at most size bytes from the file
(less if the read hits EOF before obtaining size bytes).
If the size argument is negative or omitted, read all data until EOF
is reached. The bytes are returned as a string object. An empty
string is returned when EOF is encountered immediately.'
| def read(self, n=(-1)):
| _complain_ifclosed(self.closed)
if self.buflist:
self.buf += ''.join(self.buflist)
self.buflist = []
if ((n is None) or (n < 0)):
newpos = self.len
else:
newpos = min((self.pos + n), self.len)
r = self.buf[self.pos:newpos]
self.pos = newpos
return r
|
'Read one entire line from the file.
A trailing newline character is kept in the string (but may be absent
when a file ends with an incomplete line). If the size argument is
present and non-negative, it is a maximum byte count (including the
trailing newline) and an incomplete line may be returned.
An empty string is returned only when EOF is encountered immediately.
Note: Unlike stdio\'s fgets(), the returned string contains null
characters (\'\0\') if they occurred in the input.'
| def readline(self, length=None):
| _complain_ifclosed(self.closed)
if self.buflist:
self.buf += ''.join(self.buflist)
self.buflist = []
i = self.buf.find('\n', self.pos)
if (i < 0):
newpos = self.len
else:
newpos = (i + 1)
if ((length is not None) and (length > 0)):
if ((self.pos + length) < newpos):
newpos = (self.pos + length)
r = self.buf[self.pos:newpos]
self.pos = newpos
return r
|
'Read until EOF using readline() and return a list containing the
lines thus read.
If the optional sizehint argument is present, instead of reading up
to EOF, whole lines totalling approximately sizehint bytes (or more
to accommodate a final whole line).'
| def readlines(self, sizehint=0):
| total = 0
lines = []
line = self.readline()
while line:
lines.append(line)
total += len(line)
if (0 < sizehint <= total):
break
line = self.readline()
return lines
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.