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\'))
Dec... | 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 argu... | 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... | 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 f... | 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 ... | 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 ot... | 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.sa... | 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\')
>>> Exte... | 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 otherwis... | 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.62449980... | 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\')
>>> ExtendedContex... | 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. ... | 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 t... | 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)):
... |
'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()
... |
'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... |
'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... | 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.e... |
'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 expli... | 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 callab... | 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 (meas... | 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 ... |
'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 (measur... | 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' % (s... |
'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... | 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.failu... |
'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
differ... | 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:
... |
'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]))))... |
'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.... | 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.... |
'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... |
'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.failureExc... |
'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_rege... |
'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... |
'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:
... |
'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... |
'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 ... |
'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):
... |
'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=_Cmp... |
'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 leve... | 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_d... |
'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
... |
'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 r... | 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) ... |
'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.