desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'original docstring'
| @property
def spam(self):
| return 1
|
'new docstring'
| @spam.getter
def spam(self):
| return 8
|
'Create time tuple based on current time.'
| def setUp(self):
| self.time_tuple = time.localtime()
self.LT_ins = _strptime.LocaleTime()
|
'Helper method that tests testing against directive based on the
tuple_position of time_tuple. Uses error_msg as error message.'
| def compare_against_time(self, testing, directive, tuple_position, error_msg):
| strftime_output = time.strftime(directive, self.time_tuple).lower()
comparison = testing[self.time_tuple[tuple_position]]
self.assertIn(strftime_output, testing, ('%s: not found in tuple' % error_msg))
self.assertEqual(comparison, strftime_output, ('%s: position within tuple incorrect; %s != %s' % (error_msg, comparison, strftime_output)))
|
'Construct generic TimeRE object.'
| def setUp(self):
| self.time_re = _strptime.TimeRE()
self.locale_time = _strptime.LocaleTime()
|
'Create testing time tuple.'
| def setUp(self):
| self.time_tuple = time.gmtime()
|
'Helper fxn in testing.'
| def helper(self, directive, position):
| strf_output = time.strftime(('%' + directive), self.time_tuple)
strp_output = _strptime._strptime_time(strf_output, ('%' + directive))
self.assertTrue((strp_output[position] == self.time_tuple[position]), ("testing of '%s' directive failed; '%s' -> %s != %s" % (directive, strf_output, strp_output[position], self.time_tuple[position])))
|
'Issue 15701= - HTTPError interface has info method available from URLError.'
| def test_HTTPError_interface_call(self):
| err = urllib2.HTTPError(msg='something bad happened', url=None, code=None, hdrs='Content-Length:42', fp=None)
self.assertTrue(hasattr(err, 'reason'))
assert hasattr(err, 'reason')
assert hasattr(err, 'info')
assert callable(err.info)
try:
err.info()
except AttributeError:
self.fail('err.info() failed')
self.assertEqual(err.info(), 'Content-Length:42')
|
'Asserts that both the types and values are the same.'
| def assertTypedEquals(self, expected, actual):
| self.assertEqual(type(expected), type(actual))
self.assertEqual(expected, actual)
|
'Asserts that callable(*args, **kwargs) raises exc_type(message).'
| def assertRaisesMessage(self, exc_type, message, callable, *args, **kwargs):
| try:
callable(*args, **kwargs)
except exc_type as e:
self.assertEqual(message, str(e))
else:
self.fail(('%s not raised' % exc_type.__name__))
|
'Test an empty maildir mailbox'
| def test_empty_maildir(self):
| self.mbox = mailbox.Maildir(test_support.TESTFN)
self.assertTrue((len(self.mbox) == 0))
self.assertTrue((self.mbox.next() is None))
self.assertTrue((self.mbox.next() is None))
|
'Check that compileall recreates bytecode when the new metadata is
used.'
| @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
def recreation_check(self, metadata):
| py_compile.compile(self.source_path)
self.assertEqual(*self.data())
with open(self.bc_path, 'rb') as file:
bc = file.read()[len(metadata):]
with open(self.bc_path, 'wb') as file:
file.write(metadata)
file.write(bc)
self.assertNotEqual(*self.data())
compileall.compile_dir(self.directory, force=False, quiet=True)
self.assertTrue(*self.data())
|
'Setup the default logging stream to an internal StringIO instance,
so that we can examine log output as we want.'
| def setUp(self):
| logger_dict = logging.getLogger().manager.loggerDict
logging._acquireLock()
try:
self.saved_handlers = logging._handlers.copy()
self.saved_handler_list = logging._handlerList[:]
self.saved_loggers = logger_dict.copy()
self.saved_level_names = logging._levelNames.copy()
finally:
logging._releaseLock()
logging.getLogger('\xab\xd7\xbb')
logging.getLogger(u'\u013f\xd6G')
self.root_logger = logging.getLogger('')
self.original_logging_level = self.root_logger.getEffectiveLevel()
self.stream = cStringIO.StringIO()
self.root_logger.setLevel(logging.DEBUG)
self.root_hdlr = logging.StreamHandler(self.stream)
self.root_formatter = logging.Formatter(self.log_format)
self.root_hdlr.setFormatter(self.root_formatter)
self.root_logger.addHandler(self.root_hdlr)
|
'Remove our logging stream, and restore the original logging
level.'
| def tearDown(self):
| self.stream.close()
self.root_logger.removeHandler(self.root_hdlr)
while self.root_logger.handlers:
h = self.root_logger.handlers[0]
self.root_logger.removeHandler(h)
h.close()
self.root_logger.setLevel(self.original_logging_level)
logging._acquireLock()
try:
logging._levelNames.clear()
logging._levelNames.update(self.saved_level_names)
logging._handlers.clear()
logging._handlers.update(self.saved_handlers)
logging._handlerList[:] = self.saved_handler_list
loggerDict = logging.getLogger().manager.loggerDict
loggerDict.clear()
loggerDict.update(self.saved_loggers)
finally:
logging._releaseLock()
|
'Match the collected log lines against the regular expression
self.expected_log_pat, and compare the extracted group values to
the expected_values list of tuples.'
| def assert_log_lines(self, expected_values, stream=None):
| stream = (stream or self.stream)
pat = re.compile(self.expected_log_pat)
try:
stream.reset()
actual_lines = stream.readlines()
except AttributeError:
actual_lines = stream.getvalue().splitlines()
self.assertEqual(len(actual_lines), len(expected_values))
for (actual, expected) in zip(actual_lines, expected_values):
match = pat.search(actual)
if (not match):
self.fail(('Log line does not match expected pattern:\n' + actual))
self.assertEqual(tuple(match.groups()), expected)
s = stream.read()
if s:
self.fail(('Remaining output at end of log stream:\n' + s))
|
'Generate a message consisting solely of an auto-incrementing
integer.'
| def next_message(self):
| self.message_num += 1
return ('%d' % self.message_num)
|
'Handle multiple requests - each expected to be of 4-byte length,
followed by the LogRecord in pickle format. Logs the record
according to whatever policy is configured locally.'
| def handle(self):
| while True:
chunk = self.connection.recv(4)
if (len(chunk) < 4):
break
slen = struct.unpack('>L', chunk)[0]
chunk = self.connection.recv(slen)
while (len(chunk) < slen):
chunk = (chunk + self.connection.recv((slen - len(chunk))))
obj = self.unpickle(chunk)
record = logging.makeLogRecord(obj)
self.handle_log_record(record)
|
'Set up a TCP server to receive log messages, and a SocketHandler
pointing to that server\'s address and port.'
| def setUp(self):
| BaseTest.setUp(self)
self.tcpserver = LogRecordSocketReceiver(port=0)
self.port = self.tcpserver.socket.getsockname()[1]
self.threads = [threading.Thread(target=self.tcpserver.serve_until_stopped)]
for thread in self.threads:
thread.start()
self.sock_hdlr = logging.handlers.SocketHandler('localhost', self.port)
self.sock_hdlr.setFormatter(self.root_formatter)
self.root_logger.removeHandler(self.root_logger.handlers[0])
self.root_logger.addHandler(self.sock_hdlr)
|
'Shutdown the TCP server.'
| def tearDown(self):
| try:
self.tcpserver.abort = True
del self.tcpserver
self.root_logger.removeHandler(self.sock_hdlr)
self.sock_hdlr.close()
for thread in self.threads:
thread.join(2.0)
finally:
BaseTest.tearDown(self)
|
'Get the log output as received by the TCP server.'
| def get_output(self):
| self.root_logger.critical(LogRecordStreamHandler.TCP_LOG_END)
self.tcpserver.finished.wait(2.0)
return self.tcpserver.log_output
|
'Create a dict to remember potentially destroyed objects.'
| def setUp(self):
| BaseTest.setUp(self)
self._survivors = {}
|
'Watch the given objects for survival, by creating weakrefs to
them.'
| def _watch_for_survival(self, *args):
| for obj in args:
key = (id(obj), repr(obj))
self._survivors[key] = weakref.ref(obj)
|
'Assert that all objects watched for survival have survived.'
| def _assertTruesurvival(self):
| gc.collect()
dead = []
for ((id_, repr_), ref) in self._survivors.items():
if (ref() is None):
dead.append(repr_)
if dead:
self.fail(('%d objects should have survived but have been destroyed: %s' % (len(dead), ', '.join(dead))))
|
'Another
docstring
containing
tabs'
| def abuse(self, a, b, c):
| self.argue(a, b, c)
|
'Test that lambda functionality stays the same. The output produced
currently is, I suspect invalid because of the unencoded brackets in the
HTML, "<lambda>".
The subtraction lambda method is tested.'
| def test_lambda(self):
| self.client.request('GET', '/')
response = self.client.getresponse()
self.assertIn('<dl><dt><a name="-<lambda>"><strong><lambda></strong></a>(x, y)</dt></dl>', response.read())
|
'Test that the server correctly automatically wraps references to
PEPS and RFCs with links, and that it linkifies text starting with
http or ftp protocol prefixes.
The documentation for the "add" method contains the test material.'
| @make_request_and_skipIf((sys.flags.optimize >= 2), 'Docstrings are omitted with -O2 and above')
def test_autolinking(self):
| self.client.request('GET', '/')
response = self.client.getresponse()
self.assertIn('<dl><dt><a name="-add"><strong>add</strong></a>(x, y)</dt><dd><tt>Add two instances together. This follows <a href="http://www.python.org/dev/peps/pep-0008/">PEP008</a>, but has nothing<br>\nto do with <a href="http://www.rfc-editor.org/rfc/rfc1952.txt">RFC1952</a>. Case should matter: pEp008 and rFC1952. Things<br>\nthat start with http and ftp should be auto-linked, too:<br>\n<a href="http://google.com">http://google.com</a>.</tt></dd></dl>', response.read())
|
'Test the precense of three consecutive system.* methods.
This also tests their use of parameter type recognition and the
systems related to that process.'
| @make_request_and_skipIf((sys.flags.optimize >= 2), 'Docstrings are omitted with -O2 and above')
def test_system_methods(self):
| self.client.request('GET', '/')
response = self.client.getresponse()
self.assertIn('<dl><dt><a name="-system.listMethods"><strong>system.listMethods</strong></a>()</dt><dd><tt><a href="#-system.listMethods">system.listMethods</a>() => [\'add\', \'subtract\', \'multiple\']<br>\n <br>\nReturns a list of the methods supported by the server.</tt></dd></dl>\n <dl><dt><a name="-system.methodHelp"><strong>system.methodHelp</strong></a>(method_name)</dt><dd><tt><a href="#-system.methodHelp">system.methodHelp</a>(\'add\') => "Adds two integers together"<br>\n <br>\nReturns a string containing documentation for the specified method.</tt></dd></dl>\n <dl><dt><a name="-system.methodSignature"><strong>system.methodSignature</strong></a>(method_name)</dt><dd><tt><a href="#-system.methodSignature">system.methodSignature</a>(\'add\') => [double, int, int]<br>\n <br>\nReturns a list describing the signature of the method. In the<br>\nabove example, the add method takes two integers as arguments<br>\nand returns a double result.<br>\n <br>\nThis server does NOT support system.methodSignature.</tt></dd></dl>', response.read())
|
'Test that selfdot values are made strong automatically in the
documentation.'
| def test_autolink_dotted_methods(self):
| self.client.request('GET', '/')
response = self.client.getresponse()
self.assertIn('Try self.<strong>add</strong>, too.', response.read())
|
'Return true iff floats x and y "are close".'
| def assertCloseAbs(self, x, y, eps=1e-09):
| if (abs(x) > abs(y)):
(x, y) = (y, x)
if (y == 0):
return (abs(x) < eps)
if (x == 0):
return (abs(y) < eps)
self.assertTrue((abs(((x - y) / y)) < eps))
|
'assert that floats x and y are identical, in the sense that:
(1) both x and y are nans, or
(2) both x and y are infinities, with the same sign, or
(3) both x and y are zeros, with the same sign, or
(4) x and y are both finite and nonzero, and x == y'
| def assertFloatsAreIdentical(self, x, y):
| msg = 'floats {!r} and {!r} are not identical'
if (isnan(x) or isnan(y)):
if (isnan(x) and isnan(y)):
return
elif (x == y):
if (x != 0.0):
return
elif (copysign(1.0, x) == copysign(1.0, y)):
return
else:
msg += ': zeros have different signs'
self.fail(msg.format(x, y))
|
'Return true iff complexes x and y "are close".'
| def assertClose(self, x, y, eps=1e-09):
| self.assertCloseAbs(x.real, y.real, eps)
self.assertCloseAbs(x.imag, y.imag, eps)
|
'Compute complex z=x*y, and check that z/x==y and z/y==x.'
| def check_div(self, x, y):
| z = (x * y)
if (x != 0):
q = (z / x)
self.assertClose(q, y)
q = z.__div__(x)
self.assertClose(q, y)
q = z.__truediv__(x)
self.assertClose(q, y)
if (y != 0):
q = (z / y)
self.assertClose(q, x)
q = z.__div__(y)
self.assertClose(q, x)
q = z.__truediv__(y)
self.assertClose(q, x)
|
'Common code for chown, fchown and lchown tests.'
| def _test_all_chown_common(self, chown_func, first_param, stat_func):
| def check_stat(uid, gid):
if (stat_func is not None):
stat = stat_func(first_param)
self.assertEqual(stat.st_uid, uid)
self.assertEqual(stat.st_gid, gid)
uid = os.getuid()
gid = os.getgid()
chown_func(first_param, uid, gid)
check_stat(uid, gid)
chown_func(first_param, (-1), gid)
check_stat(uid, gid)
chown_func(first_param, uid, (-1))
check_stat(uid, gid)
if (uid == 0):
big_value = (2 ** 31)
chown_func(first_param, big_value, big_value)
check_stat(big_value, big_value)
chown_func(first_param, (-1), (-1))
check_stat(big_value, big_value)
chown_func(first_param, uid, gid)
check_stat(uid, gid)
elif (platform.system() in ('HP-UX', 'SunOS')):
raise unittest.SkipTest('Skipping because of non-standard chown() behavior')
else:
self.assertRaises(OSError, chown_func, first_param, 0, 0)
check_stat(uid, gid)
self.assertRaises(OSError, chown_func, first_param, 0, (-1))
check_stat(uid, gid)
if (0 not in os.getgroups()):
self.assertRaises(OSError, chown_func, first_param, (-1), 0)
check_stat(uid, gid)
for t in (str, float):
self.assertRaises(TypeError, chown_func, first_param, t(uid), gid)
check_stat(uid, gid)
self.assertRaises(TypeError, chown_func, first_param, uid, t(gid))
check_stat(uid, gid)
|
'Check addresses and the date.'
| def check(self, msg, results):
| m = self.create_message(msg)
i = 0
for (n, a) in (m.getaddrlist('to') + m.getaddrlist('cc')):
try:
(mn, ma) = (results[i][0], results[i][1])
except IndexError:
print 'extra parsed address:', repr(n), repr(a)
continue
i = (i + 1)
self.assertEqual(mn, n, ('Un-expected name: %r != %r' % (mn, n)))
self.assertEqual(ma, a, ('Un-expected address: %r != %r' % (ma, a)))
if ((mn == n) and (ma == a)):
pass
else:
print 'not found:', repr(n), repr(a)
out = m.getdate('date')
if out:
self.assertEqual(out, (1999, 1, 13, 23, 57, 35, 0, 1, 0), 'date conversion failed')
|
'Construct a bunch of `n` threads running the same function `f`.
If `wait_before_exit` is True, the threads won\'t terminate until
do_finish() is called.'
| def __init__(self, f, n, wait_before_exit=False):
| self.f = f
self.n = n
self.started = []
self.finished = []
self._can_exit = (not wait_before_exit)
def task():
tid = get_ident()
self.started.append(tid)
try:
f()
finally:
self.finished.append(tid)
while (not self._can_exit):
_wait()
try:
for i in range(n):
start_new_thread(task, ())
except:
self._can_exit = True
raise
|
'Helper function that checks if str(exc) == unicode(exc) == msg'
| def check_same_msg(self, exc, msg):
| self.assertEqual(str(exc), msg)
self.assertEqual(str(exc), unicode(exc))
|
'Check same msg for built-in exceptions'
| def test_builtin_exceptions(self):
| exceptions = [SyntaxError('invalid syntax', ('<string>', 1, 3, '2+*3')), IOError(2, 'No such file or directory'), KeyError('both should have the same quotes'), UnicodeDecodeError('ascii', '\xc3\xa0', 0, 1, 'ordinal not in range(128)'), UnicodeEncodeError('ascii', u'\u1234', 0, 1, 'ordinal not in range(128)')]
for exception in exceptions:
self.assertEqual(str(exception), unicode(exception))
|
'Check same msg for Exception with 0 args'
| def test_0_args(self):
| self.check_same_msg(Exception(), '')
|
'Check same msg for exceptions with 0 args and overridden __str__'
| def test_0_args_with_overridden___str__(self):
| for msg in ('foo', u'foo'):
self.check_same_msg(ExcWithOverriddenStr(msg=msg), msg)
e = ExcWithOverriddenStr(msg=u'f\xf6\xf6')
self.assertRaises(UnicodeEncodeError, str, e)
self.assertEqual(unicode(e), u'f\xf6\xf6')
|
'Check same msg for Exceptions with 1 arg'
| def test_1_arg(self):
| for arg in ('foo', u'foo'):
self.check_same_msg(Exception(arg), arg)
e = Exception(u'f\xf6\xf6')
self.assertRaises(UnicodeEncodeError, str, e)
self.assertEqual(unicode(e), u'f\xf6\xf6')
|
'Check same msg for exceptions with overridden __str__ and 1 arg'
| def test_1_arg_with_overridden___str__(self):
| for msg in ('foo', u'foo'):
self.check_same_msg(ExcWithOverriddenStr('arg', msg=msg), msg)
e = ExcWithOverriddenStr('arg', msg=u'f\xf6\xf6')
self.assertRaises(UnicodeEncodeError, str, e)
self.assertEqual(unicode(e), u'f\xf6\xf6')
|
'Check same msg for Exceptions with many args'
| def test_many_args(self):
| argslist = [(3, 'foo'), (1, u'foo', 'bar'), (4, u'f\xf6\xf6', u'bar', 'baz')]
for args in argslist:
self.check_same_msg(Exception(*args), repr(args))
|
'Check same msg for exceptions with overridden __str__ and many args'
| def test_many_args_with_overridden___str__(self):
| for msg in ('foo', u'foo'):
e = ExcWithOverriddenStr('arg1', u'arg2', u'f\xf6\xf6', msg=msg)
self.check_same_msg(e, msg)
e = ExcWithOverriddenStr('arg1', u'f\xf6\xf6', u'arg3', msg=u'f\xf6\xf6')
self.assertRaises(UnicodeEncodeError, str, e)
self.assertEqual(unicode(e), u'f\xf6\xf6')
|
'Return true iff _ExpectedSkips knows about the current platform.'
| def isvalid(self):
| return self.valid
|
'Return set of test names we expect to skip on current platform.
self.isvalid() must be true.'
| def getexpected(self):
| assert self.isvalid()
return self.expected
|
'Wait for child to finish, ignoring EINTR.'
| def wait(self, child):
| while True:
try:
child.wait()
return
except OSError as e:
if (e.errno != errno.EINTR):
raise
|
'Install a no-op signal handler that can be set to allow
interrupts or not, and arrange for the original signal handler to be
re-installed when the test is finished.'
| def setUp(self):
| self.signum = signal.SIGUSR1
oldhandler = signal.signal(self.signum, (lambda x, y: None))
self.addCleanup(signal.signal, self.signum, oldhandler)
|
'Perform a read during which a signal will arrive. Return True if the
read is interrupted by the signal and raises an exception. Return False
if it returns normally.'
| def readpipe_interrupted(self):
| (r, w) = os.pipe()
self.addCleanup(os.close, r)
ppid = os.getpid()
pid = os.fork()
if (pid == 0):
try:
time.sleep(0.2)
os.kill(ppid, self.signum)
time.sleep(0.2)
finally:
exit_subprocess()
else:
self.addCleanup(os.waitpid, pid, 0)
os.close(w)
try:
d = os.read(r, 1)
return False
except OSError as err:
if (err.errno != errno.EINTR):
raise
return True
|
'If a signal handler is installed and siginterrupt is not called
at all, when that signal arrives, it interrupts a syscall that\'s in
progress.'
| def test_without_siginterrupt(self):
| i = self.readpipe_interrupted()
self.assertTrue(i)
i = self.readpipe_interrupted()
self.assertTrue(i)
|
'If a signal handler is installed and siginterrupt is called with
a true value for the second argument, when that signal arrives, it
interrupts a syscall that\'s in progress.'
| def test_siginterrupt_on(self):
| signal.siginterrupt(self.signum, 1)
i = self.readpipe_interrupted()
self.assertTrue(i)
i = self.readpipe_interrupted()
self.assertTrue(i)
|
'If a signal handler is installed and siginterrupt is called with
a false value for the second argument, when that signal arrives, it
does not interrupt a syscall that\'s in progress.'
| def test_siginterrupt_off(self):
| signal.siginterrupt(self.signum, 0)
i = self.readpipe_interrupted()
self.assertFalse(i)
i = self.readpipe_interrupted()
self.assertFalse(i)
|
'Implement isinstance(inst, cls).'
| def __instancecheck__(cls, inst):
| return any((cls.__subclasscheck__(c) for c in set([type(inst), inst.__class__])))
|
'Implement issubclass(sub, cls).'
| def __subclasscheck__(cls, sub):
| candidates = (cls.__dict__.get('__subclass__', set()) | set([cls]))
return any(((c in candidates) for c in sub.mro()))
|
'headers: list of RFC822-style \'Key: value\' strings'
| def __init__(self, headers=[], url=None):
| import mimetools, StringIO
f = StringIO.StringIO('\n'.join(headers))
self._headers = mimetools.Message(f)
self._url = url
|
'succeed iff {l1} - {ignore} == {l2} - {ignore}'
| def assertListEq(self, l1, l2, ignore):
| missing = ((set(l1) ^ set(l2)) - set(ignore))
if missing:
print >>sys.stderr, ('l1=%r\nl2=%r\nignore=%r' % (l1, l2, ignore))
self.fail(('%r missing' % missing.pop()))
|
'succeed iff hasattr(obj,attr) or attr in ignore.'
| def assertHasattr(self, obj, attr, ignore):
| if (attr in ignore):
return
if (not hasattr(obj, attr)):
print '???', attr
self.assertTrue(hasattr(obj, attr), ('expected hasattr(%r, %r)' % (obj, attr)))
|
'succeed iff key in obj or key in ignore.'
| def assertHaskey(self, obj, key, ignore):
| if (key in ignore):
return
if (key not in obj):
print >>sys.stderr, '***', key
self.assertIn(key, obj)
|
'succeed iff a == b or a in ignore or b in ignore'
| def assertEqualsOrIgnored(self, a, b, ignore):
| if ((a not in ignore) and (b not in ignore)):
self.assertEqual(a, b)
|
'succeed iff pyclbr.readmodule_ex(modulename) corresponds
to the actual module object, module. Any identifiers in
ignore are ignored. If no module is provided, the appropriate
module is loaded with __import__.'
| def checkModule(self, moduleName, module=None, ignore=()):
| if (module is None):
module = __import__(moduleName, globals(), {}, ['<silly>'])
dict = pyclbr.readmodule_ex(moduleName)
def ismethod(oclass, obj, name):
classdict = oclass.__dict__
if isinstance(obj, FunctionType):
if (not isinstance(classdict[name], StaticMethodType)):
return False
else:
if (not isinstance(obj, MethodType)):
return False
if (obj.im_self is not None):
if ((not isinstance(classdict[name], ClassMethodType)) or (obj.im_self is not oclass)):
return False
elif (not isinstance(classdict[name], FunctionType)):
return False
objname = obj.__name__
if (objname.startswith('__') and (not objname.endswith('__'))):
objname = ('_%s%s' % (obj.im_class.__name__, objname))
return (objname == name)
for (name, value) in dict.items():
if (name in ignore):
continue
self.assertHasattr(module, name, ignore)
py_item = getattr(module, name)
if isinstance(value, pyclbr.Function):
self.assertIsInstance(py_item, (FunctionType, BuiltinFunctionType))
if (py_item.__module__ != moduleName):
continue
self.assertEqual(py_item.__module__, value.module)
else:
self.assertIsInstance(py_item, (ClassType, type))
if (py_item.__module__ != moduleName):
continue
real_bases = [base.__name__ for base in py_item.__bases__]
pyclbr_bases = [getattr(base, 'name', base) for base in value.super]
try:
self.assertListEq(real_bases, pyclbr_bases, ignore)
except:
print >>sys.stderr, ('class=%s' % py_item)
raise
actualMethods = []
for m in py_item.__dict__.keys():
if ismethod(py_item, getattr(py_item, m), m):
actualMethods.append(m)
foundMethods = []
for m in value.methods.keys():
if ((m[:2] == '__') and (m[(-2):] != '__')):
foundMethods.append((('_' + name) + m))
else:
foundMethods.append(m)
try:
self.assertListEq(foundMethods, actualMethods, ignore)
self.assertEqual(py_item.__module__, value.module)
self.assertEqualsOrIgnored(py_item.__name__, value.name, ignore)
except:
print >>sys.stderr, ('class=%s' % py_item)
raise
def defined_in(item, module):
if isinstance(item, ClassType):
return (item.__module__ == module.__name__)
if isinstance(item, FunctionType):
return (item.func_globals is module.__dict__)
return False
for name in dir(module):
item = getattr(module, name)
if isinstance(item, (ClassType, FunctionType)):
if defined_in(item, module):
self.assertHaskey(dict, name, ignore)
|
'Constructor: Rat([num[, den]]).
The arguments must be ints or longs, and default to (0, 1).'
| def __init__(self, num=0L, den=1L):
| if (not isint(num)):
raise TypeError, ('Rat numerator must be int or long (%r)' % num)
if (not isint(den)):
raise TypeError, ('Rat denominator must be int or long (%r)' % den)
if (den == 0):
raise ZeroDivisionError, 'zero denominator'
g = gcd(den, num)
self.__num = long((num // g))
self.__den = long((den // g))
|
'Accessor function for read-only \'num\' attribute of Rat.'
| def _get_num(self):
| return self.__num
|
'Accessor function for read-only \'den\' attribute of Rat.'
| def _get_den(self):
| return self.__den
|
'Convert a Rat to a string resembling a Rat constructor call.'
| def __repr__(self):
| return ('Rat(%d, %d)' % (self.__num, self.__den))
|
'Convert a Rat to a string resembling a decimal numeric value.'
| def __str__(self):
| return str(float(self))
|
'Convert a Rat to a float.'
| def __float__(self):
| return ((self.__num * 1.0) / self.__den)
|
'Convert a Rat to an int; self.den must be 1.'
| def __int__(self):
| if (self.__den == 1):
try:
return int(self.__num)
except OverflowError:
raise OverflowError, ('%s too large to convert to int' % repr(self))
raise ValueError, ("can't convert %s to int" % repr(self))
|
'Convert a Rat to a long; self.den must be 1.'
| def __long__(self):
| if (self.__den == 1):
return long(self.__num)
raise ValueError, ("can't convert %s to long" % repr(self))
|
'Add two Rats, or a Rat and a number.'
| def __add__(self, other):
| if isint(other):
other = Rat(other)
if isRat(other):
return Rat(((self.__num * other.__den) + (other.__num * self.__den)), (self.__den * other.__den))
if isnum(other):
return (float(self) + other)
return NotImplemented
|
'Subtract two Rats, or a Rat and a number.'
| def __sub__(self, other):
| if isint(other):
other = Rat(other)
if isRat(other):
return Rat(((self.__num * other.__den) - (other.__num * self.__den)), (self.__den * other.__den))
if isnum(other):
return (float(self) - other)
return NotImplemented
|
'Subtract two Rats, or a Rat and a number (reversed args).'
| def __rsub__(self, other):
| if isint(other):
other = Rat(other)
if isRat(other):
return Rat(((other.__num * self.__den) - (self.__num * other.__den)), (self.__den * other.__den))
if isnum(other):
return (other - float(self))
return NotImplemented
|
'Multiply two Rats, or a Rat and a number.'
| def __mul__(self, other):
| if isRat(other):
return Rat((self.__num * other.__num), (self.__den * other.__den))
if isint(other):
return Rat((self.__num * other), self.__den)
if isnum(other):
return (float(self) * other)
return NotImplemented
|
'Divide two Rats, or a Rat and a number.'
| def __truediv__(self, other):
| if isRat(other):
return Rat((self.__num * other.__den), (self.__den * other.__num))
if isint(other):
return Rat(self.__num, (self.__den * other))
if isnum(other):
return (float(self) / other)
return NotImplemented
|
'Divide two Rats, or a Rat and a number (reversed args).'
| def __rtruediv__(self, other):
| if isRat(other):
return Rat((other.__num * self.__den), (other.__den * self.__num))
if isint(other):
return Rat((other * self.__den), self.__num)
if isnum(other):
return (other / float(self))
return NotImplemented
|
'Divide two Rats, returning the floored result.'
| def __floordiv__(self, other):
| if isint(other):
other = Rat(other)
elif (not isRat(other)):
return NotImplemented
x = (self / other)
return (x.__num // x.__den)
|
'Divide two Rats, returning the floored result (reversed args).'
| def __rfloordiv__(self, other):
| x = (other / self)
return (x.__num // x.__den)
|
'Divide two Rats, returning quotient and remainder.'
| def __divmod__(self, other):
| if isint(other):
other = Rat(other)
elif (not isRat(other)):
return NotImplemented
x = (self // other)
return (x, (self - (other * x)))
|
'Divide two Rats, returning quotient and remainder (reversed args).'
| def __rdivmod__(self, other):
| if isint(other):
other = Rat(other)
elif (not isRat(other)):
return NotImplemented
return divmod(other, self)
|
'Take one Rat modulo another.'
| def __mod__(self, other):
| return divmod(self, other)[1]
|
'Take one Rat modulo another (reversed args).'
| def __rmod__(self, other):
| return divmod(other, self)[1]
|
'Compare two Rats for equality.'
| def __eq__(self, other):
| if isint(other):
return ((self.__den == 1) and (self.__num == other))
if isRat(other):
return ((self.__num == other.__num) and (self.__den == other.__den))
if isnum(other):
return (float(self) == other)
return NotImplemented
|
'Compare two Rats for inequality.'
| def __ne__(self, other):
| return (not (self == other))
|
'Make sure the specified module, when imported, raises a
DeprecationWarning and specifies itself in the message.'
| def check_removal(self, module_name, optional=False):
| if (module_name in sys.modules):
mod = sys.modules[module_name]
filename = getattr(mod, '__file__', '')
mod = None
if (not filename.endswith(('.py', '.pyc', '.pyo'))):
if test_support.verbose:
print ('Cannot test the Python 3 DeprecationWarning of the %s module, the C module is already loaded' % module_name)
return
with CleanImport(module_name):
with warnings.catch_warnings():
warnings.filterwarnings('error', '.+ (module|package) .+ removed', DeprecationWarning, __name__)
warnings.filterwarnings('error', '.+ removed .+ (module|package)', DeprecationWarning, __name__)
try:
__import__(module_name, level=0)
except DeprecationWarning as exc:
self.assertIn(module_name, exc.args[0], ("%s warning didn't contain module name" % module_name))
except ImportError:
if (not optional):
self.fail('Non-optional module {0} raised an ImportError.'.format(module_name))
else:
if (not check_deprecated_module(module_name)):
self.fail('DeprecationWarning not raised for {0}'.format(module_name))
|
'Generic buffered read method test harness to verify EINTR behavior.
Also validates that Python signal handlers are run during the read.
Args:
data_to_write: String to write to the child process for reading
before sending it a signal, confirming the signal was handled,
writing a final newline char and closing the infile pipe.
read_and_verify_code: Single "line" of code to read from a file
object named \'infile\' and validate the result. This will be
executed as part of a python subprocess fed data_to_write.
method_name: The name of the read method being tested, for use in
an error message on failure.
universal_newlines: If True, infile will be opened in universal
newline mode in the child process.'
| def _test_reading(self, data_to_write, read_and_verify_code, method_name, universal_newlines=False):
| if universal_newlines:
data_to_write = data_to_write.replace('\n', '\r\n')
infile_setup_code = 'infile = os.fdopen(sys.stdin.fileno(), "rU")'
else:
infile_setup_code = 'infile = sys.stdin'
assert (len(data_to_write) < 512), 'data_to_write must fit in pipe buf.'
child_code = (((('import os, signal, sys ;signal.signal(signal.SIGINT, lambda s, f: sys.stderr.write("$\\n")) ;' + infile_setup_code) + ' ;') + 'assert isinstance(infile, file) ;sys.stderr.write("Go.\\n") ;') + read_and_verify_code)
reader_process = subprocess.Popen([sys.executable, '-c', child_code], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
go = reader_process.stderr.read(4)
if (go != 'Go.\n'):
reader_process.kill()
self.fail(('Error from %s process while awaiting "Go":\n%s' % (method_name, (go + reader_process.stderr.read()))))
reader_process.stdin.write(data_to_write)
signals_sent = 0
rlist = []
while (not rlist):
(rlist, _, _) = select.select([reader_process.stderr], (), (), 0.05)
reader_process.send_signal(signal.SIGINT)
time.sleep(0.1)
signals_sent += 1
if (signals_sent > 200):
reader_process.kill()
self.fail(('failed to handle signal during %s.' % method_name))
signal_line = reader_process.stderr.readline()
if (signal_line != '$\n'):
reader_process.kill()
self.fail(('Error from %s process while awaiting signal:\n%s' % (method_name, (signal_line + reader_process.stderr.read()))))
(stdout, stderr) = reader_process.communicate(input='\n')
if (reader_process.returncode != 0):
self.fail(('%s() process exited rc=%d.\nSTDOUT:\n%s\nSTDERR:\n%s' % (method_name, reader_process.returncode, stdout, stderr)))
|
'file.readline must handle signals and not lose data.'
| def test_readline(self, universal_newlines=False):
| self._test_reading(data_to_write='hello, world!', read_and_verify_code='line = infile.readline() ;expected_line = "hello, world!\\n" ;assert line == expected_line, ("read %r expected %r" % (line, expected_line))', method_name='readline', universal_newlines=universal_newlines)
|
'file.readlines must handle signals and not lose data.'
| def test_readlines(self, universal_newlines=False):
| self._test_reading(data_to_write='hello\nworld!', read_and_verify_code='lines = infile.readlines() ;expected_lines = ["hello\\n", "world!\\n"] ;assert lines == expected_lines, ("readlines returned wrong data.\\n" "got lines %r\\nexpected %r" % (lines, expected_lines))', method_name='readlines', universal_newlines=universal_newlines)
|
'Unbounded file.read() must handle signals and not lose data.'
| def test_readall(self):
| self._test_reading(data_to_write='hello, world!abcdefghijklm', read_and_verify_code='data = infile.read() ;expected_data = "hello, world!abcdefghijklm\\n";assert data == expected_data, ("read %r expected %r" % (data, expected_data))', method_name='unbounded read')
|
'file.readinto must handle signals and not lose data.'
| def test_readinto(self):
| self._test_reading(data_to_write='hello, world!', read_and_verify_code='data = bytearray(50) ;num_read = infile.readinto(data) ;expected_data = "hello, world!\\n";assert data[:num_read] == expected_data, ("read %r expected %r" % (data, expected_data))', method_name='readinto')
|
'Run \'script\' lines with pdb and the pdb \'commands\'.'
| def run_pdb(self, script, commands):
| filename = 'main.py'
with open(filename, 'w') as f:
f.write(textwrap.dedent(script))
self.addCleanup(test_support.unlink, filename)
cmd = [sys.executable, '-m', 'pdb', filename]
stdout = stderr = None
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
(stdout, stderr) = proc.communicate(commands)
proc.stdout.close()
proc.stdin.close()
return (stdout, stderr)
|
'In issue 7750, it was found that if the filename has a sequence that
resolves to an escape character in a Python string (such as ), it
will be treated as the escaped character.'
| def test_filename_correct(self):
| test_fn = '.\\test_mod.py'
code = 'print("testing pdb")'
with open(test_fn, 'w') as f:
f.write(code)
self.addCleanup(os.remove, test_fn)
cmd = [sys.executable, '-m', 'pdb', test_fn]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
(stdout, stderr) = proc.communicate('quit\n')
self.assertIn(code, stdout, 'pdb munged the filename')
|
'>>> print TwoNames().f()
f'
| def f(self):
| return 'f'
|
'Writes a file in the given path.
path can be a string or a sequence.'
| def write_file(self, path, content='xxx'):
| if isinstance(path, (list, tuple)):
path = os.path.join(*path)
f = open(path, 'w')
try:
f.write(content)
finally:
f.close()
|
'Create a temporary directory that will be cleaned up.
Returns the path of the directory.'
| def mkdtemp(self):
| d = tempfile.mkdtemp()
self.tempdirs.append(d)
return d
|
'assert that dedent() has no effect on \'text\''
| def assertUnchanged(self, text):
| self.assertEqual(text, dedent(text))
|
'Test the normal data case on both master_fd and stdin.'
| def test__copy_to_each(self):
| (read_from_stdout_fd, mock_stdout_fd) = self._pipe()
pty.STDOUT_FILENO = mock_stdout_fd
(mock_stdin_fd, write_to_stdin_fd) = self._pipe()
pty.STDIN_FILENO = mock_stdin_fd
socketpair = socket.socketpair()
masters = [s.fileno() for s in socketpair]
self.fds.extend(masters)
os.write(masters[1], 'from master')
os.write(write_to_stdin_fd, 'from stdin')
pty.select = self._mock_select
self.select_rfds_lengths.append(2)
self.select_rfds_results.append([mock_stdin_fd, masters[0]])
self.select_rfds_lengths.append(2)
with self.assertRaises(IndexError):
pty._copy(masters[0])
rfds = select.select([read_from_stdout_fd, masters[1]], [], [], 0)[0]
self.assertEqual([read_from_stdout_fd, masters[1]], rfds)
self.assertEqual(os.read(read_from_stdout_fd, 20), 'from master')
self.assertEqual(os.read(masters[1], 20), 'from stdin')
|
'Test the empty read EOF case on both master_fd and stdin.'
| def test__copy_eof_on_all(self):
| (read_from_stdout_fd, mock_stdout_fd) = self._pipe()
pty.STDOUT_FILENO = mock_stdout_fd
(mock_stdin_fd, write_to_stdin_fd) = self._pipe()
pty.STDIN_FILENO = mock_stdin_fd
socketpair = socket.socketpair()
masters = [s.fileno() for s in socketpair]
self.fds.extend(masters)
os.close(masters[1])
socketpair[1].close()
os.close(write_to_stdin_fd)
pty.select = self._mock_select
self.select_rfds_lengths.append(2)
self.select_rfds_results.append([mock_stdin_fd, masters[0]])
self.select_rfds_lengths.append(0)
with self.assertRaises(IndexError):
pty._copy(masters[0])
|
'A trace function that raises an exception in response to a
specific trace event.'
| def trace(self, frame, event, arg):
| if (event == self.raiseOnEvent):
raise ValueError
else:
return self.trace
|
'The function to trace; raises an exception if that\'s the case
we\'re testing, so that the \'exception\' trace event fires.'
| def f(self):
| if (self.raiseOnEvent == 'exception'):
x = 0
y = (1 // x)
else:
return 1
|
'Tests that an exception raised in response to the given event is
handled OK.'
| def run_test_for_event(self, event):
| self.raiseOnEvent = event
try:
for i in xrange((sys.getrecursionlimit() + 1)):
sys.settrace(self.trace)
try:
self.f()
except ValueError:
pass
else:
self.fail('exception not raised!')
except RuntimeError:
self.fail('recursion counter not reset')
|
'Attach a mock as an attribute of this one, replacing its name and
parent. Calls to the attached mock will be recorded in the
`method_calls` and `mock_calls` attributes of this one.'
| def attach_mock(self, mock, attribute):
| mock._mock_parent = None
mock._mock_new_parent = None
mock._mock_name = ''
mock._mock_new_name = None
setattr(self, attribute, mock)
|
'Add a spec to a mock. `spec` can either be an object or a
list of strings. Only attributes on the `spec` can be fetched as
attributes from the mock.
If `spec_set` is True then only attributes on the spec can be set.'
| def mock_add_spec(self, spec, spec_set=False):
| self._mock_add_spec(spec, spec_set)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.