Unnamed: 0
int64 0
10k
| function
stringlengths 79
138k
| label
stringclasses 20
values | info
stringlengths 42
261
|
|---|---|---|---|
6,500
|
def parse(self):
"""
Parse the POST data and break it into a FILES MultiValueDict and a POST
MultiValueDict.
Returns a tuple containing the POST and FILES dictionary, respectively.
"""
# We have to import QueryDict down here to avoid a circular import.
from django.http import QueryDict
encoding = self._encoding
handlers = self._upload_handlers
# HTTP spec says that Content-Length >= 0 is valid
# handling content-length == 0 before continuing
if self._content_length == 0:
return QueryDict('', encoding=self._encoding), MultiValueDict()
# See if any of the handlers take care of the parsing.
# This allows overriding everything if need be.
for handler in handlers:
result = handler.handle_raw_input(self._input_data,
self._meta,
self._content_length,
self._boundary,
encoding)
#Check to see if it was handled
if result is not None:
return result[0], result[1]
# Create the data structures to be used later.
self._post = QueryDict('', mutable=True)
self._files = MultiValueDict()
# Instantiate the parser and stream:
stream = LazyStream(ChunkIter(self._input_data, self._chunk_size))
# Whether or not to signal a file-completion at the beginning of the loop.
old_field_name = None
counters = [0] * len(handlers)
try:
for item_type, meta_data, field_stream in Parser(stream, self._boundary):
if old_field_name:
# We run this at the beginning of the next loop
# since we cannot be sure a file is complete until
# we hit the next boundary/part of the multipart content.
self.handle_file_complete(old_field_name, counters)
old_field_name = None
try:
disposition = meta_data['content-disposition'][1]
field_name = disposition['name'].strip()
except (KeyError, IndexError, AttributeError):
continue
transfer_encoding = meta_data.get('content-transfer-encoding')
if transfer_encoding is not None:
transfer_encoding = transfer_encoding[0].strip()
field_name = force_text(field_name, encoding, errors='replace')
if item_type == FIELD:
# This is a post field, we can just set it in the post
if transfer_encoding == 'base64':
raw_data = field_stream.read()
try:
data = str(raw_data).decode('base64')
except:
data = raw_data
else:
data = field_stream.read()
self._post.appendlist(field_name,
force_text(data, encoding, errors='replace'))
elif item_type == FILE:
# This is a file, use the handler...
file_name = disposition.get('filename')
if not file_name:
continue
file_name = force_text(file_name, encoding, errors='replace')
file_name = self.IE_sanitize(unescape_entities(file_name))
content_type = meta_data.get('content-type', ('',))[0].strip()
try:
charset = meta_data.get('content-type', (0, {}))[1].get('charset', None)
except:
charset = None
try:
content_length = int(meta_data.get('content-length')[0])
except (__HOLE__, TypeError, ValueError):
content_length = None
counters = [0] * len(handlers)
try:
for handler in handlers:
try:
handler.new_file(field_name, file_name,
content_type, content_length,
charset)
except StopFutureHandlers:
break
for chunk in field_stream:
if transfer_encoding == 'base64':
# We only special-case base64 transfer encoding
# We should always read base64 streams by multiple of 4
over_bytes = len(chunk) % 4
if over_bytes:
over_chunk = field_stream.read(4 - over_bytes)
chunk += over_chunk
try:
chunk = base64.b64decode(chunk)
except Exception as e:
# Since this is only a chunk, any error is an unfixable error.
msg = "Could not decode base64 data: %r" % e
six.reraise(MultiPartParserError, MultiPartParserError(msg), sys.exc_info()[2])
for i, handler in enumerate(handlers):
chunk_length = len(chunk)
chunk = handler.receive_data_chunk(chunk,
counters[i])
counters[i] += chunk_length
if chunk is None:
# If the chunk received by the handler is None, then don't continue.
break
except SkipFile:
# Just use up the rest of this file...
exhaust(field_stream)
else:
# Handle file upload completions on next iteration.
old_field_name = field_name
else:
# If this is neither a FIELD or a FILE, just exhaust the stream.
exhaust(stream)
except StopUpload as e:
if not e.connection_reset:
exhaust(self._input_data)
else:
# Make sure that the request data is all fed
exhaust(self._input_data)
# Signal that the upload has completed.
for handler in handlers:
retval = handler.upload_complete()
if retval:
break
return self._post, self._files
|
IndexError
|
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/http/multipartparser.py/MultiPartParser.parse
|
6,501
|
def exhaust(stream_or_iterable):
"""
Completely exhausts an iterator or stream.
Raise a MultiPartParserError if the argument is not a stream or an iterable.
"""
iterator = None
try:
iterator = iter(stream_or_iterable)
except __HOLE__:
iterator = ChunkIter(stream_or_iterable, 16384)
if iterator is None:
raise MultiPartParserError('multipartparser.exhaust() was passed a non-iterable or stream parameter')
for __ in iterator:
pass
|
TypeError
|
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/http/multipartparser.py/exhaust
|
6,502
|
def process_create_sentry_role(self, seqid, iprot, oprot):
args = create_sentry_role_args()
args.read(iprot)
iprot.readMessageEnd()
result = create_sentry_role_result()
try:
result.success = self._handler.create_sentry_role(args.request)
msg_type = TMessageType.REPLY
except (TTransport.TTransportException, __HOLE__, SystemExit):
raise
except Exception as ex:
msg_type = TMessageType.EXCEPTION
logging.exception(ex)
result = TApplicationException(TApplicationException.INTERNAL_ERROR, 'Internal error')
oprot.writeMessageBegin("create_sentry_role", msg_type, seqid)
result.write(oprot)
oprot.writeMessageEnd()
oprot.trans.flush()
|
KeyboardInterrupt
|
dataset/ETHPy150Open cloudera/hue/desktop/libs/libsentry/gen-py/sentry_policy_service/SentryPolicyService.py/Processor.process_create_sentry_role
|
6,503
|
def process_drop_sentry_role(self, seqid, iprot, oprot):
args = drop_sentry_role_args()
args.read(iprot)
iprot.readMessageEnd()
result = drop_sentry_role_result()
try:
result.success = self._handler.drop_sentry_role(args.request)
msg_type = TMessageType.REPLY
except (TTransport.TTransportException, KeyboardInterrupt, __HOLE__):
raise
except Exception as ex:
msg_type = TMessageType.EXCEPTION
logging.exception(ex)
result = TApplicationException(TApplicationException.INTERNAL_ERROR, 'Internal error')
oprot.writeMessageBegin("drop_sentry_role", msg_type, seqid)
result.write(oprot)
oprot.writeMessageEnd()
oprot.trans.flush()
|
SystemExit
|
dataset/ETHPy150Open cloudera/hue/desktop/libs/libsentry/gen-py/sentry_policy_service/SentryPolicyService.py/Processor.process_drop_sentry_role
|
6,504
|
def process_alter_sentry_role_grant_privilege(self, seqid, iprot, oprot):
args = alter_sentry_role_grant_privilege_args()
args.read(iprot)
iprot.readMessageEnd()
result = alter_sentry_role_grant_privilege_result()
try:
result.success = self._handler.alter_sentry_role_grant_privilege(args.request)
msg_type = TMessageType.REPLY
except (TTransport.TTransportException, KeyboardInterrupt, __HOLE__):
raise
except Exception as ex:
msg_type = TMessageType.EXCEPTION
logging.exception(ex)
result = TApplicationException(TApplicationException.INTERNAL_ERROR, 'Internal error')
oprot.writeMessageBegin("alter_sentry_role_grant_privilege", msg_type, seqid)
result.write(oprot)
oprot.writeMessageEnd()
oprot.trans.flush()
|
SystemExit
|
dataset/ETHPy150Open cloudera/hue/desktop/libs/libsentry/gen-py/sentry_policy_service/SentryPolicyService.py/Processor.process_alter_sentry_role_grant_privilege
|
6,505
|
def process_alter_sentry_role_revoke_privilege(self, seqid, iprot, oprot):
args = alter_sentry_role_revoke_privilege_args()
args.read(iprot)
iprot.readMessageEnd()
result = alter_sentry_role_revoke_privilege_result()
try:
result.success = self._handler.alter_sentry_role_revoke_privilege(args.request)
msg_type = TMessageType.REPLY
except (TTransport.TTransportException, __HOLE__, SystemExit):
raise
except Exception as ex:
msg_type = TMessageType.EXCEPTION
logging.exception(ex)
result = TApplicationException(TApplicationException.INTERNAL_ERROR, 'Internal error')
oprot.writeMessageBegin("alter_sentry_role_revoke_privilege", msg_type, seqid)
result.write(oprot)
oprot.writeMessageEnd()
oprot.trans.flush()
|
KeyboardInterrupt
|
dataset/ETHPy150Open cloudera/hue/desktop/libs/libsentry/gen-py/sentry_policy_service/SentryPolicyService.py/Processor.process_alter_sentry_role_revoke_privilege
|
6,506
|
def process_alter_sentry_role_add_groups(self, seqid, iprot, oprot):
args = alter_sentry_role_add_groups_args()
args.read(iprot)
iprot.readMessageEnd()
result = alter_sentry_role_add_groups_result()
try:
result.success = self._handler.alter_sentry_role_add_groups(args.request)
msg_type = TMessageType.REPLY
except (TTransport.TTransportException, __HOLE__, SystemExit):
raise
except Exception as ex:
msg_type = TMessageType.EXCEPTION
logging.exception(ex)
result = TApplicationException(TApplicationException.INTERNAL_ERROR, 'Internal error')
oprot.writeMessageBegin("alter_sentry_role_add_groups", msg_type, seqid)
result.write(oprot)
oprot.writeMessageEnd()
oprot.trans.flush()
|
KeyboardInterrupt
|
dataset/ETHPy150Open cloudera/hue/desktop/libs/libsentry/gen-py/sentry_policy_service/SentryPolicyService.py/Processor.process_alter_sentry_role_add_groups
|
6,507
|
def process_alter_sentry_role_delete_groups(self, seqid, iprot, oprot):
args = alter_sentry_role_delete_groups_args()
args.read(iprot)
iprot.readMessageEnd()
result = alter_sentry_role_delete_groups_result()
try:
result.success = self._handler.alter_sentry_role_delete_groups(args.request)
msg_type = TMessageType.REPLY
except (TTransport.TTransportException, __HOLE__, SystemExit):
raise
except Exception as ex:
msg_type = TMessageType.EXCEPTION
logging.exception(ex)
result = TApplicationException(TApplicationException.INTERNAL_ERROR, 'Internal error')
oprot.writeMessageBegin("alter_sentry_role_delete_groups", msg_type, seqid)
result.write(oprot)
oprot.writeMessageEnd()
oprot.trans.flush()
|
KeyboardInterrupt
|
dataset/ETHPy150Open cloudera/hue/desktop/libs/libsentry/gen-py/sentry_policy_service/SentryPolicyService.py/Processor.process_alter_sentry_role_delete_groups
|
6,508
|
def process_list_sentry_roles_by_group(self, seqid, iprot, oprot):
args = list_sentry_roles_by_group_args()
args.read(iprot)
iprot.readMessageEnd()
result = list_sentry_roles_by_group_result()
try:
result.success = self._handler.list_sentry_roles_by_group(args.request)
msg_type = TMessageType.REPLY
except (TTransport.TTransportException, KeyboardInterrupt, __HOLE__):
raise
except Exception as ex:
msg_type = TMessageType.EXCEPTION
logging.exception(ex)
result = TApplicationException(TApplicationException.INTERNAL_ERROR, 'Internal error')
oprot.writeMessageBegin("list_sentry_roles_by_group", msg_type, seqid)
result.write(oprot)
oprot.writeMessageEnd()
oprot.trans.flush()
|
SystemExit
|
dataset/ETHPy150Open cloudera/hue/desktop/libs/libsentry/gen-py/sentry_policy_service/SentryPolicyService.py/Processor.process_list_sentry_roles_by_group
|
6,509
|
def process_list_sentry_privileges_by_role(self, seqid, iprot, oprot):
args = list_sentry_privileges_by_role_args()
args.read(iprot)
iprot.readMessageEnd()
result = list_sentry_privileges_by_role_result()
try:
result.success = self._handler.list_sentry_privileges_by_role(args.request)
msg_type = TMessageType.REPLY
except (TTransport.TTransportException, __HOLE__, SystemExit):
raise
except Exception as ex:
msg_type = TMessageType.EXCEPTION
logging.exception(ex)
result = TApplicationException(TApplicationException.INTERNAL_ERROR, 'Internal error')
oprot.writeMessageBegin("list_sentry_privileges_by_role", msg_type, seqid)
result.write(oprot)
oprot.writeMessageEnd()
oprot.trans.flush()
|
KeyboardInterrupt
|
dataset/ETHPy150Open cloudera/hue/desktop/libs/libsentry/gen-py/sentry_policy_service/SentryPolicyService.py/Processor.process_list_sentry_privileges_by_role
|
6,510
|
def process_list_sentry_privileges_for_provider(self, seqid, iprot, oprot):
args = list_sentry_privileges_for_provider_args()
args.read(iprot)
iprot.readMessageEnd()
result = list_sentry_privileges_for_provider_result()
try:
result.success = self._handler.list_sentry_privileges_for_provider(args.request)
msg_type = TMessageType.REPLY
except (TTransport.TTransportException, __HOLE__, SystemExit):
raise
except Exception as ex:
msg_type = TMessageType.EXCEPTION
logging.exception(ex)
result = TApplicationException(TApplicationException.INTERNAL_ERROR, 'Internal error')
oprot.writeMessageBegin("list_sentry_privileges_for_provider", msg_type, seqid)
result.write(oprot)
oprot.writeMessageEnd()
oprot.trans.flush()
|
KeyboardInterrupt
|
dataset/ETHPy150Open cloudera/hue/desktop/libs/libsentry/gen-py/sentry_policy_service/SentryPolicyService.py/Processor.process_list_sentry_privileges_for_provider
|
6,511
|
def process_drop_sentry_privilege(self, seqid, iprot, oprot):
args = drop_sentry_privilege_args()
args.read(iprot)
iprot.readMessageEnd()
result = drop_sentry_privilege_result()
try:
result.success = self._handler.drop_sentry_privilege(args.request)
msg_type = TMessageType.REPLY
except (TTransport.TTransportException, __HOLE__, SystemExit):
raise
except Exception as ex:
msg_type = TMessageType.EXCEPTION
logging.exception(ex)
result = TApplicationException(TApplicationException.INTERNAL_ERROR, 'Internal error')
oprot.writeMessageBegin("drop_sentry_privilege", msg_type, seqid)
result.write(oprot)
oprot.writeMessageEnd()
oprot.trans.flush()
|
KeyboardInterrupt
|
dataset/ETHPy150Open cloudera/hue/desktop/libs/libsentry/gen-py/sentry_policy_service/SentryPolicyService.py/Processor.process_drop_sentry_privilege
|
6,512
|
def process_rename_sentry_privilege(self, seqid, iprot, oprot):
args = rename_sentry_privilege_args()
args.read(iprot)
iprot.readMessageEnd()
result = rename_sentry_privilege_result()
try:
result.success = self._handler.rename_sentry_privilege(args.request)
msg_type = TMessageType.REPLY
except (TTransport.TTransportException, __HOLE__, SystemExit):
raise
except Exception as ex:
msg_type = TMessageType.EXCEPTION
logging.exception(ex)
result = TApplicationException(TApplicationException.INTERNAL_ERROR, 'Internal error')
oprot.writeMessageBegin("rename_sentry_privilege", msg_type, seqid)
result.write(oprot)
oprot.writeMessageEnd()
oprot.trans.flush()
|
KeyboardInterrupt
|
dataset/ETHPy150Open cloudera/hue/desktop/libs/libsentry/gen-py/sentry_policy_service/SentryPolicyService.py/Processor.process_rename_sentry_privilege
|
6,513
|
def process_list_sentry_privileges_by_authorizable(self, seqid, iprot, oprot):
args = list_sentry_privileges_by_authorizable_args()
args.read(iprot)
iprot.readMessageEnd()
result = list_sentry_privileges_by_authorizable_result()
try:
result.success = self._handler.list_sentry_privileges_by_authorizable(args.request)
msg_type = TMessageType.REPLY
except (TTransport.TTransportException, KeyboardInterrupt, __HOLE__):
raise
except Exception as ex:
msg_type = TMessageType.EXCEPTION
logging.exception(ex)
result = TApplicationException(TApplicationException.INTERNAL_ERROR, 'Internal error')
oprot.writeMessageBegin("list_sentry_privileges_by_authorizable", msg_type, seqid)
result.write(oprot)
oprot.writeMessageEnd()
oprot.trans.flush()
|
SystemExit
|
dataset/ETHPy150Open cloudera/hue/desktop/libs/libsentry/gen-py/sentry_policy_service/SentryPolicyService.py/Processor.process_list_sentry_privileges_by_authorizable
|
6,514
|
def process_get_sentry_config_value(self, seqid, iprot, oprot):
args = get_sentry_config_value_args()
args.read(iprot)
iprot.readMessageEnd()
result = get_sentry_config_value_result()
try:
result.success = self._handler.get_sentry_config_value(args.request)
msg_type = TMessageType.REPLY
except (TTransport.TTransportException, KeyboardInterrupt, __HOLE__):
raise
except Exception as ex:
msg_type = TMessageType.EXCEPTION
logging.exception(ex)
result = TApplicationException(TApplicationException.INTERNAL_ERROR, 'Internal error')
oprot.writeMessageBegin("get_sentry_config_value", msg_type, seqid)
result.write(oprot)
oprot.writeMessageEnd()
oprot.trans.flush()
# HELPER FUNCTIONS AND STRUCTURES
|
SystemExit
|
dataset/ETHPy150Open cloudera/hue/desktop/libs/libsentry/gen-py/sentry_policy_service/SentryPolicyService.py/Processor.process_get_sentry_config_value
|
6,515
|
def dict_constructor():
if verbose:
print "Testing dict constructor ..."
d = dict()
vereq(d, {})
d = dict({})
vereq(d, {})
d = dict({1: 2, 'a': 'b'})
vereq(d, {1: 2, 'a': 'b'})
vereq(d, dict(d.items()))
vereq(d, dict(d.iteritems()))
d = dict({'one':1, 'two':2})
vereq(d, dict(one=1, two=2))
vereq(d, dict(**d))
vereq(d, dict({"one": 1}, two=2))
vereq(d, dict([("two", 2)], one=1))
vereq(d, dict([("one", 100), ("two", 200)], **d))
verify(d is not dict(**d))
for badarg in 0, 0L, 0j, "0", [0], (0,):
try:
dict(badarg)
except TypeError:
pass
except __HOLE__:
if badarg == "0":
# It's a sequence, and its elements are also sequences (gotta
# love strings <wink>), but they aren't of length 2, so this
# one seemed better as a ValueError than a TypeError.
pass
else:
raise TestFailed("no TypeError from dict(%r)" % badarg)
else:
raise TestFailed("no TypeError from dict(%r)" % badarg)
try:
dict({}, {})
except TypeError:
pass
else:
raise TestFailed("no TypeError from dict({}, {})")
class Mapping:
# Lacks a .keys() method; will be added later.
dict = {1:2, 3:4, 'a':1j}
try:
dict(Mapping())
except TypeError:
pass
else:
raise TestFailed("no TypeError from dict(incomplete mapping)")
Mapping.keys = lambda self: self.dict.keys()
Mapping.__getitem__ = lambda self, i: self.dict[i]
d = dict(Mapping())
vereq(d, Mapping.dict)
# Init from sequence of iterable objects, each producing a 2-sequence.
class AddressBookEntry:
def __init__(self, first, last):
self.first = first
self.last = last
def __iter__(self):
return iter([self.first, self.last])
d = dict([AddressBookEntry('Tim', 'Warsaw'),
AddressBookEntry('Barry', 'Peters'),
AddressBookEntry('Tim', 'Peters'),
AddressBookEntry('Barry', 'Warsaw')])
vereq(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
d = dict(zip(range(4), range(1, 5)))
vereq(d, dict([(i, i+1) for i in range(4)]))
# Bad sequence lengths.
for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
try:
dict(bad)
except ValueError:
pass
else:
raise TestFailed("no ValueError from dict(%r)" % bad)
|
ValueError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/dict_constructor
|
6,516
|
def test_dir():
if verbose:
print "Testing dir() ..."
junk = 12
vereq(dir(), ['junk'])
del junk
# Just make sure these don't blow up!
for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:
dir(arg)
# Try classic classes.
class C:
Cdata = 1
def Cmethod(self): pass
cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
vereq(dir(C), cstuff)
verify('im_self' in dir(C.Cmethod))
c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
vereq(dir(c), cstuff)
c.cdata = 2
c.cmethod = lambda self: 0
vereq(dir(c), cstuff + ['cdata', 'cmethod'])
verify('im_self' in dir(c.Cmethod))
class A(C):
Adata = 1
def Amethod(self): pass
astuff = ['Adata', 'Amethod'] + cstuff
vereq(dir(A), astuff)
verify('im_self' in dir(A.Amethod))
a = A()
vereq(dir(a), astuff)
verify('im_self' in dir(a.Amethod))
a.adata = 42
a.amethod = lambda self: 3
vereq(dir(a), astuff + ['adata', 'amethod'])
# The same, but with new-style classes. Since these have object as a
# base class, a lot more gets sucked in.
def interesting(strings):
return [s for s in strings if not s.startswith('_')]
class C(object):
Cdata = 1
def Cmethod(self): pass
cstuff = ['Cdata', 'Cmethod']
vereq(interesting(dir(C)), cstuff)
c = C()
vereq(interesting(dir(c)), cstuff)
verify('im_self' in dir(C.Cmethod))
c.cdata = 2
c.cmethod = lambda self: 0
vereq(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
verify('im_self' in dir(c.Cmethod))
class A(C):
Adata = 1
def Amethod(self): pass
astuff = ['Adata', 'Amethod'] + cstuff
vereq(interesting(dir(A)), astuff)
verify('im_self' in dir(A.Amethod))
a = A()
vereq(interesting(dir(a)), astuff)
a.adata = 42
a.amethod = lambda self: 3
vereq(interesting(dir(a)), astuff + ['adata', 'amethod'])
verify('im_self' in dir(a.Amethod))
# Try a module subclass.
from types import ModuleType
class M(ModuleType):
pass
minstance = M("m")
minstance.b = 2
minstance.a = 1
names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
vereq(names, ['__package__', 'a', 'b'])
class M2(M):
def getdict(self):
return "Not a dict!"
__dict__ = property(getdict)
m2instance = M2("m2")
m2instance.b = 2
m2instance.a = 1
vereq(m2instance.__dict__, "Not a dict!")
try:
dir(m2instance)
except __HOLE__:
pass
# Two essentially featureless objects, just inheriting stuff from
# object.
vereq(dir(None), dir(Ellipsis))
# Nasty test case for proxied objects
class Wrapper(object):
def __init__(self, obj):
self.__obj = obj
def __repr__(self):
return "Wrapper(%s)" % repr(self.__obj)
def __getitem__(self, key):
return Wrapper(self.__obj[key])
def __len__(self):
return len(self.__obj)
def __getattr__(self, name):
return Wrapper(getattr(self.__obj, name))
class C(object):
def __getclass(self):
return Wrapper(type(self))
__class__ = property(__getclass)
dir(C()) # This used to segfault
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/test_dir
|
6,517
|
def ints():
if verbose: print "Testing int operations..."
numops(100, 3)
# The following crashes in Python 2.2
vereq((1).__nonzero__(), 1)
vereq((0).__nonzero__(), 0)
# This returns 'NotImplemented' in Python 2.2
class C(int):
def __add__(self, other):
return NotImplemented
vereq(C(5L), 5)
try:
C() + ""
except __HOLE__:
pass
else:
raise TestFailed, "NotImplemented should have caused TypeError"
import sys
try:
C(sys.maxint+1)
except OverflowError:
pass
else:
raise TestFailed, "should have raised OverflowError"
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/ints
|
6,518
|
def metaclass():
if verbose: print "Testing __metaclass__..."
class C:
__metaclass__ = type
def __init__(self):
self.__state = 0
def getstate(self):
return self.__state
def setstate(self, state):
self.__state = state
a = C()
vereq(a.getstate(), 0)
a.setstate(10)
vereq(a.getstate(), 10)
class D:
class __metaclass__(type):
def myself(cls): return cls
vereq(D.myself(), D)
d = D()
verify(d.__class__ is D)
class M1(type):
def __new__(cls, name, bases, dict):
dict['__spam__'] = 1
return type.__new__(cls, name, bases, dict)
class C:
__metaclass__ = M1
vereq(C.__spam__, 1)
c = C()
vereq(c.__spam__, 1)
class _instance(object):
pass
class M2(object):
@staticmethod
def __new__(cls, name, bases, dict):
self = object.__new__(cls)
self.name = name
self.bases = bases
self.dict = dict
return self
def __call__(self):
it = _instance()
# Early binding of methods
for key in self.dict:
if key.startswith("__"):
continue
setattr(it, key, self.dict[key].__get__(it, self))
return it
class C:
__metaclass__ = M2
def spam(self):
return 42
vereq(C.name, 'C')
vereq(C.bases, ())
verify('spam' in C.dict)
c = C()
vereq(c.spam(), 42)
# More metaclass examples
class autosuper(type):
# Automatically add __super to the class
# This trick only works for dynamic classes
def __new__(metaclass, name, bases, dict):
cls = super(autosuper, metaclass).__new__(metaclass,
name, bases, dict)
# Name mangling for __super removes leading underscores
while name[:1] == "_":
name = name[1:]
if name:
name = "_%s__super" % name
else:
name = "__super"
setattr(cls, name, super(cls))
return cls
class A:
__metaclass__ = autosuper
def meth(self):
return "A"
class B(A):
def meth(self):
return "B" + self.__super.meth()
class C(A):
def meth(self):
return "C" + self.__super.meth()
class D(C, B):
def meth(self):
return "D" + self.__super.meth()
vereq(D().meth(), "DCBA")
class E(B, C):
def meth(self):
return "E" + self.__super.meth()
vereq(E().meth(), "EBCA")
class autoproperty(type):
# Automatically create property attributes when methods
# named _get_x and/or _set_x are found
def __new__(metaclass, name, bases, dict):
hits = {}
for key, val in dict.iteritems():
if key.startswith("_get_"):
key = key[5:]
get, set = hits.get(key, (None, None))
get = val
hits[key] = get, set
elif key.startswith("_set_"):
key = key[5:]
get, set = hits.get(key, (None, None))
set = val
hits[key] = get, set
for key, (get, set) in hits.iteritems():
dict[key] = property(get, set)
return super(autoproperty, metaclass).__new__(metaclass,
name, bases, dict)
class A:
__metaclass__ = autoproperty
def _get_x(self):
return -self.__x
def _set_x(self, x):
self.__x = -x
a = A()
verify(not hasattr(a, "x"))
a.x = 12
vereq(a.x, 12)
vereq(a._A__x, -12)
class multimetaclass(autoproperty, autosuper):
# Merge of multiple cooperating metaclasses
pass
class A:
__metaclass__ = multimetaclass
def _get_x(self):
return "A"
class B(A):
def _get_x(self):
return "B" + self.__super._get_x()
class C(A):
def _get_x(self):
return "C" + self.__super._get_x()
class D(C, B):
def _get_x(self):
return "D" + self.__super._get_x()
vereq(D().x, "DCBA")
# Make sure type(x) doesn't call x.__class__.__init__
class T(type):
counter = 0
def __init__(self, *args):
T.counter += 1
class C:
__metaclass__ = T
vereq(T.counter, 1)
a = C()
vereq(type(a), C)
vereq(T.counter, 1)
class C(object): pass
c = C()
try: c()
except __HOLE__: pass
else: raise TestFailed, "calling object w/o call method should raise TypeError"
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/metaclass
|
6,519
|
def pymods():
if verbose: print "Testing Python subclass of module..."
log = []
from types import ModuleType as MT
class MM(MT):
def __init__(self, name):
MT.__init__(self, name)
def __getattribute__(self, name):
log.append(("getattr", name))
return MT.__getattribute__(self, name)
def __setattr__(self, name, value):
log.append(("setattr", name, value))
MT.__setattr__(self, name, value)
def __delattr__(self, name):
log.append(("delattr", name))
MT.__delattr__(self, name)
a = MM("a")
a.foo = 12
x = a.foo
del a.foo
vereq(log, [("setattr", "foo", 12),
("getattr", "foo"),
("delattr", "foo")])
# http://python.org/sf/1174712
try:
class Module(types.ModuleType, str):
pass
except __HOLE__:
pass
else:
raise TestFailed("inheriting from ModuleType and str at the "
"same time should fail")
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/pymods
|
6,520
|
def multi():
if verbose: print "Testing multiple inheritance..."
class C(object):
def __init__(self):
self.__state = 0
def getstate(self):
return self.__state
def setstate(self, state):
self.__state = state
a = C()
vereq(a.getstate(), 0)
a.setstate(10)
vereq(a.getstate(), 10)
class D(dict, C):
def __init__(self):
type({}).__init__(self)
C.__init__(self)
d = D()
vereq(d.keys(), [])
d["hello"] = "world"
vereq(d.items(), [("hello", "world")])
vereq(d["hello"], "world")
vereq(d.getstate(), 0)
d.setstate(10)
vereq(d.getstate(), 10)
vereq(D.__mro__, (D, dict, C, object))
# SF bug #442833
class Node(object):
def __int__(self):
return int(self.foo())
def foo(self):
return "23"
class Frag(Node, list):
def foo(self):
return "42"
vereq(Node().__int__(), 23)
vereq(int(Node()), 23)
vereq(Frag().__int__(), 42)
vereq(int(Frag()), 42)
# MI mixing classic and new-style classes.
class A:
x = 1
class B(A):
pass
class C(A):
x = 2
class D(B, C):
pass
vereq(D.x, 1)
# Classic MRO is preserved for a classic base class.
class E(D, object):
pass
vereq(E.__mro__, (E, D, B, A, C, object))
vereq(E.x, 1)
# But with a mix of classic bases, their MROs are combined using
# new-style MRO.
class F(B, C, object):
pass
vereq(F.__mro__, (F, B, C, A, object))
vereq(F.x, 2)
# Try something else.
class C:
def cmethod(self):
return "C a"
def all_method(self):
return "C b"
class M1(C, object):
def m1method(self):
return "M1 a"
def all_method(self):
return "M1 b"
vereq(M1.__mro__, (M1, C, object))
m = M1()
vereq(m.cmethod(), "C a")
vereq(m.m1method(), "M1 a")
vereq(m.all_method(), "M1 b")
class D(C):
def dmethod(self):
return "D a"
def all_method(self):
return "D b"
class M2(D, object):
def m2method(self):
return "M2 a"
def all_method(self):
return "M2 b"
vereq(M2.__mro__, (M2, D, C, object))
m = M2()
vereq(m.cmethod(), "C a")
vereq(m.dmethod(), "D a")
vereq(m.m2method(), "M2 a")
vereq(m.all_method(), "M2 b")
class M3(M1, M2, object):
def m3method(self):
return "M3 a"
def all_method(self):
return "M3 b"
vereq(M3.__mro__, (M3, M1, M2, D, C, object))
m = M3()
vereq(m.cmethod(), "C a")
vereq(m.dmethod(), "D a")
vereq(m.m1method(), "M1 a")
vereq(m.m2method(), "M2 a")
vereq(m.m3method(), "M3 a")
vereq(m.all_method(), "M3 b")
class Classic:
pass
try:
class New(Classic):
__metaclass__ = type
except __HOLE__:
pass
else:
raise TestFailed, "new class with only classic bases - shouldn't be"
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/multi
|
6,521
|
def diamond():
if verbose: print "Testing multiple inheritance special cases..."
class A(object):
def spam(self): return "A"
vereq(A().spam(), "A")
class B(A):
def boo(self): return "B"
def spam(self): return "B"
vereq(B().spam(), "B")
vereq(B().boo(), "B")
class C(A):
def boo(self): return "C"
vereq(C().spam(), "A")
vereq(C().boo(), "C")
class D(B, C): pass
vereq(D().spam(), "B")
vereq(D().boo(), "B")
vereq(D.__mro__, (D, B, C, A, object))
class E(C, B): pass
vereq(E().spam(), "B")
vereq(E().boo(), "C")
vereq(E.__mro__, (E, C, B, A, object))
# MRO order disagreement
try:
class F(D, E): pass
except TypeError:
pass
else:
raise TestFailed, "expected MRO order disagreement (F)"
try:
class G(E, D): pass
except __HOLE__:
pass
else:
raise TestFailed, "expected MRO order disagreement (G)"
# see thread python-dev/2002-October/029035.html
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/diamond
|
6,522
|
def objects():
if verbose: print "Testing object class..."
a = object()
vereq(a.__class__, object)
vereq(type(a), object)
b = object()
verify(a is not b)
verify(not hasattr(a, "foo"))
try:
a.foo = 12
except (__HOLE__, TypeError):
pass
else:
verify(0, "object() should not allow setting a foo attribute")
verify(not hasattr(object(), "__dict__"))
class Cdict(object):
pass
x = Cdict()
vereq(x.__dict__, {})
x.foo = 1
vereq(x.foo, 1)
vereq(x.__dict__, {'foo': 1})
|
AttributeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/objects
|
6,523
|
def slots():
if verbose: print "Testing __slots__..."
class C0(object):
__slots__ = []
x = C0()
verify(not hasattr(x, "__dict__"))
verify(not hasattr(x, "foo"))
class C1(object):
__slots__ = ['a']
x = C1()
verify(not hasattr(x, "__dict__"))
verify(not hasattr(x, "a"))
x.a = 1
vereq(x.a, 1)
x.a = None
veris(x.a, None)
del x.a
verify(not hasattr(x, "a"))
class C3(object):
__slots__ = ['a', 'b', 'c']
x = C3()
verify(not hasattr(x, "__dict__"))
verify(not hasattr(x, 'a'))
verify(not hasattr(x, 'b'))
verify(not hasattr(x, 'c'))
x.a = 1
x.b = 2
x.c = 3
vereq(x.a, 1)
vereq(x.b, 2)
vereq(x.c, 3)
class C4(object):
"""Validate name mangling"""
__slots__ = ['__a']
def __init__(self, value):
self.__a = value
def get(self):
return self.__a
x = C4(5)
verify(not hasattr(x, '__dict__'))
verify(not hasattr(x, '__a'))
vereq(x.get(), 5)
try:
x.__a = 6
except AttributeError:
pass
else:
raise TestFailed, "Double underscored names not mangled"
# Make sure slot names are proper identifiers
try:
class C(object):
__slots__ = [None]
except TypeError:
pass
else:
raise TestFailed, "[None] slots not caught"
try:
class C(object):
__slots__ = ["foo bar"]
except __HOLE__:
pass
else:
raise TestFailed, "['foo bar'] slots not caught"
try:
class C(object):
__slots__ = ["foo\0bar"]
except TypeError:
pass
else:
raise TestFailed, "['foo\\0bar'] slots not caught"
try:
class C(object):
__slots__ = ["1"]
except TypeError:
pass
else:
raise TestFailed, "['1'] slots not caught"
try:
class C(object):
__slots__ = [""]
except TypeError:
pass
else:
raise TestFailed, "[''] slots not caught"
class C(object):
__slots__ = ["a", "a_b", "_a", "A0123456789Z"]
# Test unicode slot names
try:
unichr
except NameError:
pass
else:
# _unicode_to_string used to modify slots in certain circumstances
slots = (unicode("foo"), unicode("bar"))
class C(object):
__slots__ = slots
x = C()
x.foo = 5
vereq(x.foo, 5)
veris(type(slots[0]), unicode)
# this used to leak references
try:
class C(object):
__slots__ = [unichr(128)]
except (TypeError, UnicodeEncodeError):
pass
else:
raise TestFailed, "[unichr(128)] slots not caught"
# Test leaks
# XXX: Jython new style classes don't support __del__
# http://bugs.jython.org/issue1057
class Counted:
#class Counted(object):
counter = 0 # counts the number of instances alive
def __init__(self):
Counted.counter += 1
def __del__(self):
Counted.counter -= 1
class C(object):
__slots__ = ['a', 'b', 'c']
x = C()
x.a = Counted()
x.b = Counted()
x.c = Counted()
vereq(Counted.counter, 3)
del x
extra_collect()
vereq(Counted.counter, 0)
class D(C):
pass
x = D()
x.a = Counted()
x.z = Counted()
vereq(Counted.counter, 2)
del x
extra_collect()
vereq(Counted.counter, 0)
class E(D):
__slots__ = ['e']
x = E()
x.a = Counted()
x.z = Counted()
x.e = Counted()
vereq(Counted.counter, 3)
del x
extra_collect()
vereq(Counted.counter, 0)
# Test cyclical leaks [SF bug 519621]
class F(object):
__slots__ = ['a', 'b']
log = []
s = F()
s.a = [Counted(), s]
vereq(Counted.counter, 1)
s = None
import gc
gc.collect()
extra_collect()
vereq(Counted.counter, 0)
# XXX: This tests a CPython GC reference count bug and Jython lacks
# gc.get_objects
import sys
"""
# Test lookup leaks [SF bug 572567]
import sys,gc
class G(object):
def __cmp__(self, other):
return 0
g = G()
orig_objects = len(gc.get_objects())
for i in xrange(10):
g==g
new_objects = len(gc.get_objects())
vereq(orig_objects, new_objects)
"""
class H(object):
__slots__ = ['a', 'b']
def __init__(self):
self.a = 1
self.b = 2
def __del__(self):
assert self.a == 1
assert self.b == 2
save_stderr = sys.stderr
sys.stderr = sys.stdout
h = H()
try:
del h
extra_collect()
finally:
sys.stderr = save_stderr
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/slots
|
6,524
|
def slotspecials():
if verbose: print "Testing __dict__ and __weakref__ in __slots__..."
class D(object):
__slots__ = ["__dict__"]
a = D()
verify(hasattr(a, "__dict__"))
verify(not hasattr(a, "__weakref__"))
a.foo = 42
vereq(a.__dict__, {"foo": 42})
class W(object):
__slots__ = ["__weakref__"]
a = W()
verify(hasattr(a, "__weakref__"))
verify(not hasattr(a, "__dict__"))
try:
a.foo = 42
except __HOLE__:
pass
else:
raise TestFailed, "shouldn't be allowed to set a.foo"
class C1(W, D):
__slots__ = []
a = C1()
verify(hasattr(a, "__dict__"))
verify(hasattr(a, "__weakref__"))
a.foo = 42
vereq(a.__dict__, {"foo": 42})
class C2(D, W):
__slots__ = []
a = C2()
verify(hasattr(a, "__dict__"))
verify(hasattr(a, "__weakref__"))
a.foo = 42
vereq(a.__dict__, {"foo": 42})
# MRO order disagreement
#
# class C3(C1, C2):
# __slots__ = []
#
# class C4(C2, C1):
# __slots__ = []
|
AttributeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/slotspecials
|
6,525
|
def dynamics():
if verbose: print "Testing class attribute propagation..."
class D(object):
pass
class E(D):
pass
class F(D):
pass
D.foo = 1
vereq(D.foo, 1)
# Test that dynamic attributes are inherited
vereq(E.foo, 1)
vereq(F.foo, 1)
# Test dynamic instances
class C(object):
pass
a = C()
verify(not hasattr(a, "foobar"))
C.foobar = 2
vereq(a.foobar, 2)
C.method = lambda self: 42
vereq(a.method(), 42)
C.__repr__ = lambda self: "C()"
vereq(repr(a), "C()")
C.__int__ = lambda self: 100
vereq(int(a), 100)
vereq(a.foobar, 2)
verify(not hasattr(a, "spam"))
def mygetattr(self, name):
if name == "spam":
return "spam"
raise AttributeError
C.__getattr__ = mygetattr
vereq(a.spam, "spam")
a.new = 12
vereq(a.new, 12)
def mysetattr(self, name, value):
if name == "spam":
raise AttributeError
return object.__setattr__(self, name, value)
C.__setattr__ = mysetattr
try:
a.spam = "not spam"
except __HOLE__:
pass
else:
verify(0, "expected AttributeError")
vereq(a.spam, "spam")
class D(C):
pass
d = D()
d.foo = 1
vereq(d.foo, 1)
# Test handling of int*seq and seq*int
class I(int):
pass
vereq("a"*I(2), "aa")
vereq(I(2)*"a", "aa")
vereq(2*I(3), 6)
vereq(I(3)*2, 6)
vereq(I(3)*I(2), 6)
# Test handling of long*seq and seq*long
class L(long):
pass
vereq("a"*L(2L), "aa")
vereq(L(2L)*"a", "aa")
vereq(2*L(3), 6)
vereq(L(3)*2, 6)
vereq(L(3)*L(2), 6)
# Test comparison of classes with dynamic metaclasses
class dynamicmetaclass(type):
pass
class someclass:
__metaclass__ = dynamicmetaclass
verify(someclass != object)
|
AttributeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/dynamics
|
6,526
|
def errors():
if verbose: print "Testing errors..."
try:
class C(list, dict):
pass
except TypeError:
pass
else:
verify(0, "inheritance from both list and dict should be illegal")
try:
class C(object, None):
pass
except TypeError:
pass
else:
verify(0, "inheritance from non-type should be illegal")
class Classic:
pass
try:
class C(type(len)):
pass
except TypeError:
pass
else:
verify(0, "inheritance from CFunction should be illegal")
try:
class C(object):
__slots__ = 1
except TypeError:
pass
else:
verify(0, "__slots__ = 1 should be illegal")
try:
class C(object):
__slots__ = [1]
except __HOLE__:
pass
else:
verify(0, "__slots__ = [1] should be illegal")
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/errors
|
6,527
|
def classmethods():
if verbose: print "Testing class methods..."
class C(object):
def foo(*a): return a
goo = classmethod(foo)
c = C()
vereq(C.goo(1), (C, 1))
vereq(c.goo(1), (C, 1))
vereq(c.foo(1), (c, 1))
class D(C):
pass
d = D()
vereq(D.goo(1), (D, 1))
vereq(d.goo(1), (D, 1))
vereq(d.foo(1), (d, 1))
vereq(D.foo(d, 1), (d, 1))
# Test for a specific crash (SF bug 528132)
def f(cls, arg): return (cls, arg)
ff = classmethod(f)
vereq(ff.__get__(0, int)(42), (int, 42))
vereq(ff.__get__(0)(42), (int, 42))
# Test super() with classmethods (SF bug 535444)
veris(C.goo.im_self, C)
veris(D.goo.im_self, D)
veris(super(D,D).goo.im_self, D)
veris(super(D,d).goo.im_self, D)
vereq(super(D,D).goo(), (D,))
vereq(super(D,d).goo(), (D,))
# Verify that argument is checked for callability (SF bug 753451)
try:
classmethod(1).__get__(1)
except __HOLE__:
pass
else:
raise TestFailed, "classmethod should check for callability"
# Verify that classmethod() doesn't allow keyword args
try:
classmethod(f, kw=1)
except TypeError:
pass
else:
raise TestFailed, "classmethod shouldn't accept keyword args"
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/classmethods
|
6,528
|
def altmro():
if verbose: print "Testing mro() and overriding it..."
class A(object):
def f(self): return "A"
class B(A):
pass
class C(A):
def f(self): return "C"
class D(B, C):
pass
vereq(D.mro(), [D, B, C, A, object])
vereq(D.__mro__, (D, B, C, A, object))
vereq(D().f(), "C")
class PerverseMetaType(type):
def mro(cls):
L = type.mro(cls)
L.reverse()
return L
class X(D,B,C,A):
__metaclass__ = PerverseMetaType
vereq(X.__mro__, (object, A, C, B, D, X))
vereq(X().f(), "A")
try:
class X(object):
class __metaclass__(type):
def mro(self):
return [self, dict, object]
except TypeError:
pass
else:
raise TestFailed, "devious mro() return not caught"
try:
class X(object):
class __metaclass__(type):
def mro(self):
return [1]
except __HOLE__:
pass
else:
raise TestFailed, "non-class mro() return not caught"
try:
class X(object):
class __metaclass__(type):
def mro(self):
return 1
except TypeError:
pass
else:
raise TestFailed, "non-sequence mro() return not caught"
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/altmro
|
6,529
|
def specials():
# Test operators like __hash__ for which a built-in default exists
if verbose: print "Testing special operators..."
# Test the default behavior for static classes
class C(object):
def __getitem__(self, i):
if 0 <= i < 10: return i
raise IndexError
c1 = C()
c2 = C()
verify(not not c1)
verify(id(c1) != id(c2))
hash(c1)
hash(c2)
vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
vereq(c1, c1)
verify(c1 != c2)
verify(not c1 != c1)
verify(not c1 == c2)
# Note that the module name appears in str/repr, and that varies
# depending on whether this test is run standalone or from a framework.
verify(str(c1).find('C object at ') >= 0)
vereq(str(c1), repr(c1))
verify(-1 not in c1)
for i in range(10):
verify(i in c1)
verify(10 not in c1)
# Test the default behavior for dynamic classes
class D(object):
def __getitem__(self, i):
if 0 <= i < 10: return i
raise IndexError
d1 = D()
d2 = D()
verify(not not d1)
verify(id(d1) != id(d2))
hash(d1)
hash(d2)
vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
vereq(d1, d1)
verify(d1 != d2)
verify(not d1 != d1)
verify(not d1 == d2)
# Note that the module name appears in str/repr, and that varies
# depending on whether this test is run standalone or from a framework.
verify(str(d1).find('D object at ') >= 0)
vereq(str(d1), repr(d1))
verify(-1 not in d1)
for i in range(10):
verify(i in d1)
verify(10 not in d1)
# Test overridden behavior for static classes
class Proxy(object):
def __init__(self, x):
self.x = x
def __nonzero__(self):
return not not self.x
def __hash__(self):
return hash(self.x)
def __eq__(self, other):
return self.x == other
def __ne__(self, other):
return self.x != other
def __cmp__(self, other):
return cmp(self.x, other.x)
def __str__(self):
return "Proxy:%s" % self.x
def __repr__(self):
return "Proxy(%r)" % self.x
def __contains__(self, value):
return value in self.x
p0 = Proxy(0)
p1 = Proxy(1)
p_1 = Proxy(-1)
verify(not p0)
verify(not not p1)
vereq(hash(p0), hash(0))
vereq(p0, p0)
verify(p0 != p1)
verify(not p0 != p0)
vereq(not p0, p1)
vereq(cmp(p0, p1), -1)
vereq(cmp(p0, p0), 0)
vereq(cmp(p0, p_1), 1)
vereq(str(p0), "Proxy:0")
vereq(repr(p0), "Proxy(0)")
p10 = Proxy(range(10))
verify(-1 not in p10)
for i in range(10):
verify(i in p10)
verify(10 not in p10)
# Test overridden behavior for dynamic classes
class DProxy(object):
def __init__(self, x):
self.x = x
def __nonzero__(self):
return not not self.x
def __hash__(self):
return hash(self.x)
def __eq__(self, other):
return self.x == other
def __ne__(self, other):
return self.x != other
def __cmp__(self, other):
return cmp(self.x, other.x)
def __str__(self):
return "DProxy:%s" % self.x
def __repr__(self):
return "DProxy(%r)" % self.x
def __contains__(self, value):
return value in self.x
p0 = DProxy(0)
p1 = DProxy(1)
p_1 = DProxy(-1)
verify(not p0)
verify(not not p1)
vereq(hash(p0), hash(0))
vereq(p0, p0)
verify(p0 != p1)
verify(not p0 != p0)
vereq(not p0, p1)
vereq(cmp(p0, p1), -1)
vereq(cmp(p0, p0), 0)
vereq(cmp(p0, p_1), 1)
vereq(str(p0), "DProxy:0")
vereq(repr(p0), "DProxy(0)")
p10 = DProxy(range(10))
verify(-1 not in p10)
for i in range(10):
verify(i in p10)
verify(10 not in p10)
# Safety test for __cmp__
def unsafecmp(a, b):
try:
a.__class__.__cmp__(a, b)
except __HOLE__:
pass
else:
raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
a.__class__, a, b)
unsafecmp(u"123", "123")
unsafecmp("123", u"123")
unsafecmp(1, 1.0)
unsafecmp(1.0, 1)
unsafecmp(1, 1L)
unsafecmp(1L, 1)
class Letter(str):
def __new__(cls, letter):
if letter == 'EPS':
return str.__new__(cls)
return str.__new__(cls, letter)
def __str__(self):
if not self:
return 'EPS'
return self
# sys.stdout needs to be the original to trigger the recursion bug
import sys
test_stdout = sys.stdout
sys.stdout = get_original_stdout()
try:
# nothing should actually be printed, this should raise an exception
print Letter('w')
except RuntimeError:
pass
else:
raise TestFailed, "expected a RuntimeError for print recursion"
sys.stdout = test_stdout
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/specials
|
6,530
|
def weakrefs():
if verbose: print "Testing weak references..."
import weakref
class C(object):
pass
c = C()
r = weakref.ref(c)
verify(r() is c)
del c
extra_collect()
verify(r() is None)
del r
class NoWeak(object):
__slots__ = ['foo']
no = NoWeak()
try:
weakref.ref(no)
except __HOLE__, msg:
verify(str(msg).find("weak reference") >= 0)
else:
# XXX: Jython allows a weakref here
if not is_jython:
verify(0, "weakref.ref(no) should be illegal")
class Weak(object):
__slots__ = ['foo', '__weakref__']
yes = Weak()
r = weakref.ref(yes)
verify(r() is yes)
del yes
extra_collect()
verify(r() is None)
del r
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/weakrefs
|
6,531
|
def properties():
if verbose: print "Testing property..."
class C(object):
def getx(self):
return self.__x
def setx(self, value):
self.__x = value
def delx(self):
del self.__x
x = property(getx, setx, delx, doc="I'm the x property.")
a = C()
verify(not hasattr(a, "x"))
a.x = 42
vereq(a._C__x, 42)
vereq(a.x, 42)
del a.x
verify(not hasattr(a, "x"))
verify(not hasattr(a, "_C__x"))
C.x.__set__(a, 100)
vereq(C.x.__get__(a), 100)
C.x.__delete__(a)
verify(not hasattr(a, "x"))
raw = C.__dict__['x']
verify(isinstance(raw, property))
attrs = dir(raw)
verify("__doc__" in attrs)
verify("fget" in attrs)
verify("fset" in attrs)
verify("fdel" in attrs)
vereq(raw.__doc__, "I'm the x property.")
verify(raw.fget is C.__dict__['getx'])
verify(raw.fset is C.__dict__['setx'])
verify(raw.fdel is C.__dict__['delx'])
for attr in "__doc__", "fget", "fset", "fdel":
try:
setattr(raw, attr, 42)
except __HOLE__, msg:
if str(msg).find('readonly') < 0:
raise TestFailed("when setting readonly attr %r on a "
"property, got unexpected TypeError "
"msg %r" % (attr, str(msg)))
else:
raise TestFailed("expected TypeError from trying to set "
"readonly %r attr on a property" % attr)
class D(object):
__getitem__ = property(lambda s: 1/0)
d = D()
try:
for i in d:
str(i)
except ZeroDivisionError:
pass
else:
raise TestFailed, "expected ZeroDivisionError from bad property"
class E(object):
def getter(self):
"getter method"
return 0
def setter(self, value):
"setter method"
pass
prop = property(getter)
vereq(prop.__doc__, "getter method")
prop2 = property(fset=setter)
vereq(prop2.__doc__, None)
# this segfaulted in 2.5b2
try:
import _testcapi
except ImportError:
pass
else:
class X(object):
p = property(_testcapi.test_with_docstring)
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/properties
|
6,532
|
def supers():
if verbose: print "Testing super..."
class A(object):
def meth(self, a):
return "A(%r)" % a
vereq(A().meth(1), "A(1)")
class B(A):
def __init__(self):
self.__super = super(B, self)
def meth(self, a):
return "B(%r)" % a + self.__super.meth(a)
vereq(B().meth(2), "B(2)A(2)")
class C(A):
def meth(self, a):
return "C(%r)" % a + self.__super.meth(a)
C._C__super = super(C)
vereq(C().meth(3), "C(3)A(3)")
class D(C, B):
def meth(self, a):
return "D(%r)" % a + super(D, self).meth(a)
vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
# Test for subclassing super
class mysuper(super):
def __init__(self, *args):
return super(mysuper, self).__init__(*args)
class E(D):
def meth(self, a):
return "E(%r)" % a + mysuper(E, self).meth(a)
vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
class F(E):
def meth(self, a):
s = self.__super # == mysuper(F, self)
return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
F._F__super = mysuper(F)
vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
# Make sure certain errors are raised
try:
super(D, 42)
except __HOLE__:
pass
else:
raise TestFailed, "shouldn't allow super(D, 42)"
try:
super(D, C())
except TypeError:
pass
else:
raise TestFailed, "shouldn't allow super(D, C())"
try:
super(D).__get__(12)
except TypeError:
pass
else:
raise TestFailed, "shouldn't allow super(D).__get__(12)"
try:
super(D).__get__(C())
except TypeError:
pass
else:
raise TestFailed, "shouldn't allow super(D).__get__(C())"
# Make sure data descriptors can be overridden and accessed via super
# (new feature in Python 2.3)
class DDbase(object):
def getx(self): return 42
x = property(getx)
class DDsub(DDbase):
def getx(self): return "hello"
x = property(getx)
dd = DDsub()
vereq(dd.x, "hello")
vereq(super(DDsub, dd).x, 42)
# Ensure that super() lookup of descriptor from classmethod
# works (SF ID# 743627)
class Base(object):
aProp = property(lambda self: "foo")
class Sub(Base):
@classmethod
def test(klass):
return super(Sub,klass).aProp
veris(Sub.test(), Base.aProp)
# Verify that super() doesn't allow keyword args
try:
super(Base, kw=1)
except TypeError:
pass
else:
raise TestFailed, "super shouldn't accept keyword args"
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/supers
|
6,533
|
def keywords():
if verbose:
print "Testing keyword args to basic type constructors ..."
vereq(int(x=1), 1)
vereq(float(x=2), 2.0)
vereq(long(x=3), 3L)
vereq(complex(imag=42, real=666), complex(666, 42))
vereq(str(object=500), '500')
vereq(unicode(string='abc', errors='strict'), u'abc')
vereq(tuple(sequence=range(3)), (0, 1, 2))
vereq(list(sequence=(0, 1, 2)), range(3))
# note: as of Python 2.3, dict() no longer has an "items" keyword arg
for constructor in (int, float, long, complex, str, unicode,
tuple, list, file):
try:
constructor(bogus_keyword_arg=1)
except __HOLE__:
pass
else:
raise TestFailed("expected TypeError from bogus keyword "
"argument to %r" % constructor)
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/keywords
|
6,534
|
def restricted():
# XXX This test is disabled because rexec is not deemed safe
return
import rexec
if verbose:
print "Testing interaction with restricted execution ..."
sandbox = rexec.RExec()
code1 = """f = open(%r, 'w')""" % TESTFN
code2 = """f = file(%r, 'w')""" % TESTFN
code3 = """\
f = open(%r)
t = type(f) # a sneaky way to get the file() constructor
f.close()
f = t(%r, 'w') # rexec can't catch this by itself
""" % (TESTFN, TESTFN)
f = open(TESTFN, 'w') # Create the file so code3 can find it.
f.close()
try:
for code in code1, code2, code3:
try:
sandbox.r_exec(code)
except __HOLE__, msg:
if str(msg).find("restricted") >= 0:
outcome = "OK"
else:
outcome = "got an exception, but not an expected one"
else:
outcome = "expected a restricted-execution exception"
if outcome != "OK":
raise TestFailed("%s, in %r" % (outcome, code))
finally:
try:
import os
os.unlink(TESTFN)
except:
pass
|
IOError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/restricted
|
6,535
|
def setclass():
if verbose: print "Testing __class__ assignment..."
class C(object): pass
class D(object): pass
class E(object): pass
class F(D, E): pass
for cls in C, D, E, F:
for cls2 in C, D, E, F:
x = cls()
x.__class__ = cls2
verify(x.__class__ is cls2)
x.__class__ = cls
verify(x.__class__ is cls)
def cant(x, C):
try:
x.__class__ = C
except TypeError:
pass
else:
raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
try:
delattr(x, "__class__")
except __HOLE__:
pass
else:
raise TestFailed, "shouldn't allow del %r.__class__" % x
cant(C(), list)
cant(list(), C)
cant(C(), 1)
cant(C(), object)
cant(object(), list)
cant(list(), object)
class Int(int): __slots__ = []
cant(2, Int)
cant(Int(), int)
cant(True, int)
cant(2, bool)
o = object()
cant(o, type(1))
cant(o, type(None))
del o
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/setclass
|
6,536
|
def setdict():
if verbose: print "Testing __dict__ assignment..."
class C(object): pass
a = C()
a.__dict__ = {'b': 1}
vereq(a.b, 1)
def cant(x, dict):
try:
x.__dict__ = dict
except (AttributeError, TypeError):
pass
else:
raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
cant(a, None)
cant(a, [])
cant(a, 1)
del a.__dict__ # Deleting __dict__ is allowed
class Base(object):
pass
def verify_dict_readonly(x):
"""
x has to be an instance of a class inheriting from Base.
"""
cant(x, {})
try:
del x.__dict__
except (__HOLE__, TypeError):
pass
else:
raise TestFailed, "shouldn't allow del %r.__dict__" % x
dict_descr = Base.__dict__["__dict__"]
try:
dict_descr.__set__(x, {})
except (AttributeError, TypeError):
pass
else:
raise TestFailed, "dict_descr allowed access to %r's dict" % x
# Classes don't allow __dict__ assignment and have readonly dicts
class Meta1(type, Base):
pass
class Meta2(Base, type):
pass
class D(object):
__metaclass__ = Meta1
class E(object):
__metaclass__ = Meta2
for cls in C, D, E:
verify_dict_readonly(cls)
class_dict = cls.__dict__
try:
class_dict["spam"] = "eggs"
except TypeError:
pass
else:
raise TestFailed, "%r's __dict__ can be modified" % cls
# Modules also disallow __dict__ assignment
class Module1(types.ModuleType, Base):
pass
class Module2(Base, types.ModuleType):
pass
for ModuleType in Module1, Module2:
mod = ModuleType("spam")
verify_dict_readonly(mod)
mod.__dict__["spam"] = "eggs"
# Exception's __dict__ can be replaced, but not deleted
class Exception1(Exception, Base):
pass
class Exception2(Base, Exception):
pass
for ExceptionType in Exception, Exception1, Exception2:
e = ExceptionType()
e.__dict__ = {"a": 1}
vereq(e.a, 1)
try:
del e.__dict__
except (TypeError, AttributeError):
pass
else:
raise TestFaied, "%r's __dict__ can be deleted" % e
|
AttributeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/setdict
|
6,537
|
def pickleslots():
if verbose: print "Testing pickling of classes with __slots__ ..."
import pickle, cPickle
# Pickling of classes with __slots__ but without __getstate__ should fail
global B, C, D, E
class B(object):
pass
for base in [object, B]:
class C(base):
__slots__ = ['a']
class D(C):
pass
try:
pickle.dumps(C())
except TypeError:
pass
else:
raise TestFailed, "should fail: pickle C instance - %s" % base
try:
cPickle.dumps(C())
except __HOLE__:
pass
else:
raise TestFailed, "should fail: cPickle C instance - %s" % base
try:
pickle.dumps(C())
except TypeError:
pass
else:
raise TestFailed, "should fail: pickle D instance - %s" % base
try:
cPickle.dumps(D())
except TypeError:
pass
else:
raise TestFailed, "should fail: cPickle D instance - %s" % base
# Give C a nice generic __getstate__ and __setstate__
class C(base):
__slots__ = ['a']
def __getstate__(self):
try:
d = self.__dict__.copy()
except AttributeError:
d = {}
for cls in self.__class__.__mro__:
for sn in cls.__dict__.get('__slots__', ()):
try:
d[sn] = getattr(self, sn)
except AttributeError:
pass
return d
def __setstate__(self, d):
for k, v in d.items():
setattr(self, k, v)
class D(C):
pass
# Now it should work
x = C()
y = pickle.loads(pickle.dumps(x))
vereq(hasattr(y, 'a'), 0)
y = cPickle.loads(cPickle.dumps(x))
vereq(hasattr(y, 'a'), 0)
x.a = 42
y = pickle.loads(pickle.dumps(x))
vereq(y.a, 42)
y = cPickle.loads(cPickle.dumps(x))
vereq(y.a, 42)
x = D()
x.a = 42
x.b = 100
y = pickle.loads(pickle.dumps(x))
vereq(y.a + y.b, 142)
y = cPickle.loads(cPickle.dumps(x))
vereq(y.a + y.b, 142)
# A subclass that adds a slot should also work
class E(C):
__slots__ = ['b']
x = E()
x.a = 42
x.b = "foo"
y = pickle.loads(pickle.dumps(x))
vereq(y.a, x.a)
vereq(y.b, x.b)
y = cPickle.loads(cPickle.dumps(x))
vereq(y.a, x.a)
vereq(y.b, x.b)
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/pickleslots
|
6,538
|
def subclasspropagation():
if verbose: print "Testing propagation of slot functions to subclasses..."
class A(object):
pass
class B(A):
pass
class C(A):
pass
class D(B, C):
pass
d = D()
orig_hash = hash(d) # related to id(d) in platform-dependent ways
A.__hash__ = lambda self: 42
vereq(hash(d), 42)
C.__hash__ = lambda self: 314
vereq(hash(d), 314)
B.__hash__ = lambda self: 144
vereq(hash(d), 144)
D.__hash__ = lambda self: 100
vereq(hash(d), 100)
del D.__hash__
vereq(hash(d), 144)
del B.__hash__
vereq(hash(d), 314)
del C.__hash__
vereq(hash(d), 42)
del A.__hash__
vereq(hash(d), orig_hash)
d.foo = 42
d.bar = 42
vereq(d.foo, 42)
vereq(d.bar, 42)
def __getattribute__(self, name):
if name == "foo":
return 24
return object.__getattribute__(self, name)
A.__getattribute__ = __getattribute__
vereq(d.foo, 24)
vereq(d.bar, 42)
def __getattr__(self, name):
if name in ("spam", "foo", "bar"):
return "hello"
raise AttributeError, name
B.__getattr__ = __getattr__
vereq(d.spam, "hello")
vereq(d.foo, 24)
vereq(d.bar, 42)
del A.__getattribute__
vereq(d.foo, 42)
del d.foo
vereq(d.foo, "hello")
vereq(d.bar, 42)
del B.__getattr__
try:
d.foo
except __HOLE__:
pass
else:
raise TestFailed, "d.foo should be undefined now"
# Test a nasty bug in recurse_down_subclasses()
import gc
class A(object):
pass
class B(A):
pass
del B
gc.collect()
A.__setitem__ = lambda *a: None # crash
|
AttributeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/subclasspropagation
|
6,539
|
def buffer_inherit():
import binascii
# SF bug [#470040] ParseTuple t# vs subclasses.
if verbose:
print "Testing that buffer interface is inherited ..."
class MyStr(str):
pass
base = 'abc'
m = MyStr(base)
# b2a_hex uses the buffer interface to get its argument's value, via
# PyArg_ParseTuple 't#' code.
vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
# It's not clear that unicode will continue to support the character
# buffer interface, and this test will fail if that's taken away.
class MyUni(unicode):
pass
base = u'abc'
m = MyUni(base)
vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
class MyInt(int):
pass
m = MyInt(42)
try:
binascii.b2a_hex(m)
raise TestFailed('subclass of int should not have a buffer interface')
except __HOLE__:
pass
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/buffer_inherit
|
6,540
|
def recursive__call__():
if verbose: print ("Testing recursive __call__() by setting to instance of "
"class ...")
class A(object):
pass
A.__call__ = A()
try:
A()()
except __HOLE__:
pass
else:
raise TestFailed("Recursion limit should have been reached for "
"__call__()")
|
RuntimeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/recursive__call__
|
6,541
|
def delhook():
if verbose: print "Testing __del__ hook..."
log = []
class C(object):
def __del__(self):
log.append(1)
c = C()
vereq(log, [])
del c
extra_collect()
vereq(log, [1])
class D(object): pass
d = D()
try: del d[0]
except __HOLE__: pass
else: raise TestFailed, "invalid del() didn't raise TypeError"
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/delhook
|
6,542
|
def hashinherit():
if verbose: print "Testing hash of mutable subclasses..."
class mydict(dict):
pass
d = mydict()
try:
hash(d)
except __HOLE__:
pass
else:
raise TestFailed, "hash() of dict subclass should fail"
class mylist(list):
pass
d = mylist()
try:
hash(d)
except TypeError:
pass
else:
raise TestFailed, "hash() of list subclass should fail"
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/hashinherit
|
6,543
|
def strops():
try: 'a' + 5
except TypeError: pass
else: raise TestFailed, "'' + 5 doesn't raise TypeError"
try: ''.split('')
except ValueError: pass
else: raise TestFailed, "''.split('') doesn't raise ValueError"
try: ''.join([0])
except TypeError: pass
else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
try: ''.rindex('5')
except ValueError: pass
else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
try: '%(n)s' % None
except TypeError: pass
else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
try: '%(n' % {}
except ValueError: pass
else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
try: '%*s' % ('abc')
except TypeError: pass
else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
try: '%*.*s' % ('abc', 5)
except TypeError: pass
else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
try: '%s' % (1, 2)
except __HOLE__: pass
else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
try: '%' % None
except ValueError: pass
else: raise TestFailed, "'%' % None doesn't raise ValueError"
vereq('534253'.isdigit(), 1)
vereq('534253x'.isdigit(), 0)
vereq('%c' % 5, '\x05')
vereq('%c' % '5', '5')
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/strops
|
6,544
|
def test_mutable_bases():
if verbose:
print "Testing mutable bases..."
# stuff that should work:
class C(object):
pass
class C2(object):
def __getattribute__(self, attr):
if attr == 'a':
return 2
else:
return super(C2, self).__getattribute__(attr)
def meth(self):
return 1
class D(C):
pass
class E(D):
pass
d = D()
e = E()
D.__bases__ = (C,)
D.__bases__ = (C2,)
vereq(d.meth(), 1)
vereq(e.meth(), 1)
vereq(d.a, 2)
vereq(e.a, 2)
vereq(C2.__subclasses__(), [D])
# stuff that shouldn't:
class L(list):
pass
try:
L.__bases__ = (dict,)
except TypeError:
pass
else:
raise TestFailed, "shouldn't turn list subclass into dict subclass"
try:
list.__bases__ = (dict,)
except TypeError:
pass
else:
raise TestFailed, "shouldn't be able to assign to list.__bases__"
try:
del D.__bases__
except TypeError:
pass
else:
raise TestFailed, "shouldn't be able to delete .__bases__"
try:
D.__bases__ = ()
except __HOLE__, msg:
if str(msg) == "a new-style class can't have only classic bases":
raise TestFailed, "wrong error message for .__bases__ = ()"
else:
raise TestFailed, "shouldn't be able to set .__bases__ to ()"
try:
D.__bases__ = (D,)
except TypeError:
pass
else:
# actually, we'll have crashed by here...
raise TestFailed, "shouldn't be able to create inheritance cycles"
try:
D.__bases__ = (C, C)
except TypeError:
pass
else:
raise TestFailed, "didn't detect repeated base classes"
try:
D.__bases__ = (E,)
except TypeError:
pass
else:
raise TestFailed, "shouldn't be able to create inheritance cycles"
# let's throw a classic class into the mix:
class Classic:
def meth2(self):
return 3
D.__bases__ = (C, Classic)
vereq(d.meth2(), 3)
vereq(e.meth2(), 3)
try:
d.a
except AttributeError:
pass
else:
raise TestFailed, "attribute should have vanished"
try:
D.__bases__ = (Classic,)
except TypeError:
pass
else:
raise TestFailed, "new-style class must have a new-style base"
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/test_mutable_bases
|
6,545
|
def test_mutable_bases_with_failing_mro():
if verbose:
print "Testing mutable bases with failing mro..."
class WorkOnce(type):
def __new__(self, name, bases, ns):
self.flag = 0
return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
def mro(self):
if self.flag > 0:
raise RuntimeError, "bozo"
else:
self.flag += 1
return type.mro(self)
class WorkAlways(type):
def mro(self):
# this is here to make sure that .mro()s aren't called
# with an exception set (which was possible at one point).
# An error message will be printed in a debug build.
# What's a good way to test for this?
return type.mro(self)
class C(object):
pass
class C2(object):
pass
class D(C):
pass
class E(D):
pass
class F(D):
__metaclass__ = WorkOnce
class G(D):
__metaclass__ = WorkAlways
# Immediate subclasses have their mro's adjusted in alphabetical
# order, so E's will get adjusted before adjusting F's fails. We
# check here that E's gets restored.
E_mro_before = E.__mro__
D_mro_before = D.__mro__
try:
D.__bases__ = (C2,)
except __HOLE__:
vereq(E.__mro__, E_mro_before)
vereq(D.__mro__, D_mro_before)
else:
raise TestFailed, "exception not propagated"
|
RuntimeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/test_mutable_bases_with_failing_mro
|
6,546
|
def test_mutable_bases_catch_mro_conflict():
if verbose:
print "Testing mutable bases catch mro conflict..."
class A(object):
pass
class B(object):
pass
class C(A, B):
pass
class D(A, B):
pass
class E(C, D):
pass
try:
C.__bases__ = (B, A)
except __HOLE__:
pass
else:
raise TestFailed, "didn't catch MRO conflict"
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/test_mutable_bases_catch_mro_conflict
|
6,547
|
def meth_class_get():
# Full coverage of descrobject.c::classmethod_get()
if verbose:
print "Testing __get__ method of METH_CLASS C methods..."
# Baseline
arg = [1, 2, 3]
res = {1: None, 2: None, 3: None}
vereq(dict.fromkeys(arg), res)
vereq({}.fromkeys(arg), res)
# Now get the descriptor
descr = dict.__dict__["fromkeys"]
# More baseline using the descriptor directly
vereq(descr.__get__(None, dict)(arg), res)
vereq(descr.__get__({})(arg), res)
# Now check various error cases
try:
descr.__get__(None, None)
except __HOLE__:
pass
else:
raise TestFailed, "shouldn't have allowed descr.__get__(None, None)"
try:
descr.__get__(42)
except TypeError:
pass
else:
raise TestFailed, "shouldn't have allowed descr.__get__(42)"
try:
descr.__get__(None, 42)
except TypeError:
pass
else:
raise TestFailed, "shouldn't have allowed descr.__get__(None, 42)"
try:
descr.__get__(None, int)
except TypeError:
pass
else:
raise TestFailed, "shouldn't have allowed descr.__get__(None, int)"
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/meth_class_get
|
6,548
|
def carloverre():
if verbose:
print "Testing prohibition of Carlo Verre's hack..."
try:
object.__setattr__(str, "foo", 42)
except TypeError:
pass
else:
raise TestFailed, "Carlo Verre __setattr__ suceeded!"
try:
object.__delattr__(str, "lower")
except __HOLE__:
pass
else:
raise TestFailed, "Carlo Verre __delattr__ succeeded!"
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/carloverre
|
6,549
|
def filefault():
if verbose:
print "Testing sys.stdout is changed in getattr..."
import sys
class StdoutGuard:
def __getattr__(self, attr):
sys.stdout = sys.__stdout__
raise RuntimeError("Premature access to sys.stdout.%s" % attr)
sys.stdout = StdoutGuard()
try:
print "Oops!"
except __HOLE__:
pass
|
RuntimeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/filefault
|
6,550
|
def test_init():
# SF 1155938
class Foo(object):
def __init__(self):
return 10
try:
Foo()
except __HOLE__:
pass
else:
raise TestFailed, "did not test __init__() for None return"
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/test_init
|
6,551
|
def methodwrapper():
# <type 'method-wrapper'> did not support any reflection before 2.5
if verbose:
print "Testing method-wrapper objects..."
l = []
vereq(l.__add__, l.__add__)
vereq(l.__add__, [].__add__)
verify(l.__add__ != [5].__add__)
verify(l.__add__ != l.__mul__)
verify(l.__add__.__name__ == '__add__')
verify(l.__add__.__self__ is l)
if not is_jython:
# XXX: method-wrapper implementation detail, not all builtin
# instance methods have __objclass__ (e.g. l.append)
verify(l.__add__.__objclass__ is list)
vereq(l.__add__.__doc__, list.__add__.__doc__)
try:
hash(l.__add__)
except __HOLE__:
pass
else:
raise TestFailed("no TypeError from hash([].__add__)")
t = ()
t += (7,)
vereq(t.__add__, (7,).__add__)
vereq(hash(t.__add__), hash((7,).__add__))
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/methodwrapper
|
6,552
|
def notimplemented():
# all binary methods should be able to return a NotImplemented
if verbose:
print "Testing NotImplemented..."
import sys
import types
import operator
def specialmethod(self, other):
return NotImplemented
def check(expr, x, y):
try:
exec expr in {'x': x, 'y': y, 'operator': operator}
except __HOLE__:
pass
else:
raise TestFailed("no TypeError from %r" % (expr,))
N1 = sys.maxint + 1L # might trigger OverflowErrors instead of TypeErrors
N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
# ValueErrors instead of TypeErrors
for metaclass in [type, types.ClassType]:
for name, expr, iexpr in [
('__add__', 'x + y', 'x += y'),
('__sub__', 'x - y', 'x -= y'),
('__mul__', 'x * y', 'x *= y'),
('__truediv__', 'operator.truediv(x, y)', None),
('__floordiv__', 'operator.floordiv(x, y)', None),
('__div__', 'x / y', 'x /= y'),
('__mod__', 'x % y', 'x %= y'),
('__divmod__', 'divmod(x, y)', None),
('__pow__', 'x ** y', 'x **= y'),
('__lshift__', 'x << y', 'x <<= y'),
('__rshift__', 'x >> y', 'x >>= y'),
('__and__', 'x & y', 'x &= y'),
('__or__', 'x | y', 'x |= y'),
('__xor__', 'x ^ y', 'x ^= y'),
('__coerce__', 'coerce(x, y)', None)]:
if name == '__coerce__':
rname = name
else:
rname = '__r' + name[2:]
A = metaclass('A', (), {name: specialmethod})
B = metaclass('B', (), {rname: specialmethod})
a = A()
b = B()
check(expr, a, a)
check(expr, a, b)
check(expr, b, a)
check(expr, b, b)
check(expr, a, N1)
check(expr, a, N2)
check(expr, N1, b)
check(expr, N2, b)
if iexpr:
check(iexpr, a, a)
check(iexpr, a, b)
check(iexpr, b, a)
check(iexpr, b, b)
check(iexpr, a, N1)
check(iexpr, a, N2)
iname = '__i' + name[2:]
C = metaclass('C', (), {iname: specialmethod})
c = C()
check(iexpr, c, a)
check(iexpr, c, b)
check(iexpr, c, N1)
check(iexpr, c, N2)
|
TypeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descr.py/notimplemented
|
6,553
|
def trainMali( mali, options ):
"""train a grammar on a multiple alignment."""
## remove empty columns and masked columns
if options.clean_mali:
mali.mGapChars = mali.mGapChars + ("n", "N")
mali.removeGaps( minimum_gaps = 1, frame=1 )
length = mali.getNumColumns()
input_model = prepareGrammar( options )
for id in mali.getIdentifiers():
if options.separator in id:
species = id.split(options.separator)[0]
mali.rename( id, species )
map_new2old = mali.mapIdentifiers()
map_old2new = IOTools.getInvertedDictionary( map_new2old, make_unique = True )
ids = mali.getIdentifiers()
if options.input_filename_tree:
nexus = TreeTools.Newick2Nexus( open(options.input_filename_tree,"r") )
tree = nexus.trees[0]
try:
tree.relabel( map_old2new, warn = True )
except __HOLE__, msg:
raise KeyError( "names in mali and tree are not congruent: %s" % msg )
else:
tree = None
filename_mali = prepareMali( mali, tree, map_old2new, options )
result = trainOnMali( input_model, filename_mali, options )
options.stdout.write( "%f\t%i" % (result.getLogLikelihood(), result.getNumIterations() ) )
outputRates( result, options )
outputAnnotations( result, options )
options.stdout.write("\n")
return result
##-----------------------------------------------------------------------------------
|
KeyError
|
dataset/ETHPy150Open CGATOxford/cgat/obsolete/xrate_blocks.py/trainMali
|
6,554
|
def _check_comm(comm):
if isinstance(comm, int):
# If it's come from Fluidity where an MPI_Comm is just an integer.
return _MPI.Comm.f2py(comm)
try:
return comm if isinstance(comm, _MPI.Comm) else comm.tompi4py()
except __HOLE__:
raise TypeError("MPI communicator must be of type mpi4py.MPI.Comm")
|
AttributeError
|
dataset/ETHPy150Open OP2/PyOP2/pyop2/mpi.py/_check_comm
|
6,555
|
def connect(self):
try:
self.connection = serial.Serial(self.device, 115200)
except __HOLE__ as e:
if e.errno == errno.EBUSY:
raise ConnectionError("Could not connect to Pebble.")
else:
raise
|
OSError
|
dataset/ETHPy150Open pebble/libpebble2/libpebble2/communication/transports/serial.py/SerialTransport.connect
|
6,556
|
def on_intlit(self, node):
value = float(str(node))
try:
ivalue = int(value)
except __HOLE__:
yield value
else:
yield ivalue if value == ivalue else value
|
ValueError
|
dataset/ETHPy150Open Evgenus/protocyt/protocyt/compiler.py/CodeGenerator.on_intlit
|
6,557
|
def hook(self, obj):
for key, val in obj.iteritems():
if isinstance(val, basestring) and (date_re.match(val) \
or time_re.match(val)):
try:
obj[key] = parse(val)
except __HOLE__:
pass
else:
if time_re.match(val):
obj[key] = obj[key].time()
return obj
|
ValueError
|
dataset/ETHPy150Open flosch/simpleapi/simpleapi/message/sajson.py/SimpleAPIDecoder.hook
|
6,558
|
def smart_fqdn_exists(fqdn, *args, **kwargs):
"""
Searching for a fqdn by actually looking at a fqdn is very inefficient.
Instead we should:
1) Look for a domain with the name of fqdn.
2) Look for a label = fqdn.split('.')[0]
and domain = fqdn.split('.')[1:]
"""
# Try approach 1
try:
search_domain = mozdns.domain.models.Domain.objects.get(name=fqdn)
label = ''
except ObjectDoesNotExist:
search_domain = None
if search_domain:
for type_, qset in _build_label_domain_queries(label, search_domain,
**kwargs):
if qset.exists():
return qset
# Try approach 2
search_domain = None
if len(fqdn.split('.')) == 1:
return None
try:
label = fqdn.split('.')[0]
domain_name = '.'.join(fqdn.split('.')[1:])
search_domain = mozdns.domain.models.Domain.objects.get(
name=domain_name)
except __HOLE__:
search_domain = None
if search_domain:
for type_, qset in _build_label_domain_queries(label, search_domain,
**kwargs):
if qset.exists():
return qset
|
ObjectDoesNotExist
|
dataset/ETHPy150Open mozilla/inventory/mozdns/search_utils.py/smart_fqdn_exists
|
6,559
|
@staticmethod
def read_file(filename, delimiter=None, header_present=True,
skip_lines=0, dialect=None, use_sniffer=True):
if delimiter is None and use_sniffer is False:
raise InternalModuleError("Must set delimiter if not using sniffer")
try:
with open(filename, 'rb') as fp:
if use_sniffer:
first_lines = ""
line = fp.readline()
for i in xrange(skip_lines):
if not line:
break
line = fp.readline()
for i in xrange(5):
if not line:
break
first_lines += line
line = fp.readline()
sniffer = csv.Sniffer()
fp.seek(0)
if delimiter is None:
dialect = sniffer.sniff(first_lines)
delimiter = dialect.delimiter
# cannot determine header without sniffing delimiter
if header_present is None:
header_present = sniffer.has_header(first_lines)
for i in xrange(skip_lines):
line = fp.readline()
if not line:
raise InternalModuleError("skip_lines greater than "
"the number of lines in the "
"file")
if dialect is not None:
reader = csv.reader(fp, dialect=dialect)
else:
reader = csv.reader(fp, delimiter=delimiter)
result = reader.next()
column_count = len(result)
if header_present:
column_names = [name.strip() for name in result]
else:
column_names = None
except __HOLE__:
raise InternalModuleError("File does not exist")
return column_count, column_names, delimiter, header_present, dialect
|
IOError
|
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/packages/tabledata/read/read_csv.py/CSVTable.read_file
|
6,560
|
def get_column(self, index, numeric=False):
if (index, numeric) in self.column_cache:
return self.column_cache[(index, numeric)]
numpy = get_numpy(False)
if numeric and numpy is not None:
result = numpy.loadtxt(
self.filename,
dtype=numpy.float32,
delimiter=self.delimiter,
skiprows=self.skip_lines,
usecols=[index])
else:
with open(self.filename, 'rb') as fp:
for i in xrange(self.skip_lines):
line = fp.readline()
if not line:
raise ValueError("skip_lines greater than the number "
"of lines in the file")
if self.dialect is not None:
reader = csv.reader(fp, dialect=self.dialect)
else:
reader = csv.reader(fp, delimiter=self.delimiter)
getter = operator.itemgetter(index)
try:
result = []
for rownb, row in enumerate(reader, 1):
result.append(getter(row))
except __HOLE__:
raise ValueError("Invalid CSV file: only %d fields on "
"line %d (column %d requested)" % (
len(row), rownb, index))
if numeric:
result = [float(e) for e in result]
self.column_cache[(index, numeric)] = result
return result
|
IndexError
|
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/packages/tabledata/read/read_csv.py/CSVTable.get_column
|
6,561
|
def create_billingcycle(membership):
"""
Creates a new billing cycle for a membership.
If a previous billing cycle exists, the end date is used as the start
date for the new one. If a previous one doesn't exist, e.g. it is a new
user, we use the time when they were approved.
"""
billing_cycle = None
try:
if membership.status != 'A':
logger.critical("%s not Approved. Cannot send bill" % repr(membership))
raise MembershipNotApproved("%s not Approved. Cannot send bill" % repr(membership))
try:
newest_existing_billing_cycle = membership.billingcycle_set.latest('end')
except __HOLE__:
newest_existing_billing_cycle = None
if newest_existing_billing_cycle != None:
cycle_start = newest_existing_billing_cycle.end
elif membership.approved != None:
cycle_start = membership.approved
else:
logger.critical("%s is missing the approved timestamp. Cannot send bill" % repr(membership))
raise MembershipNotApproved("%s is missing the approved timestamp. Cannot send bill" % repr(membership))
with transaction.atomic():
billing_cycle = BillingCycle(membership=membership, start=cycle_start)
billing_cycle.save()
bill = Bill(billingcycle=billing_cycle)
bill.save()
bill.send_as_email()
return billing_cycle
except Exception as e:
logger.critical("%s" % traceback.format_exc())
logger.critical("Transaction rolled back, billing cycle not created!")
raise
|
ObjectDoesNotExist
|
dataset/ETHPy150Open kapsiry/sikteeri/membership/management/commands/makebills.py/create_billingcycle
|
6,562
|
def visualize(data, exploitOnly=False, filters={}, display="web"):
# do the filtering on the data
for system in data['systems']:
if 'cpes' in system:
for cpe in system['cpes']:
cpe['cves']=filter(cpe['cves'], exploitOnly, filters)
for service in system['services']:
if "cves" in service:
service['cves']=filter(service['cves'], exploitOnly, filters)
# display using the correct method
try:
if not display in visuals.keys():
sys.exit("Could not visualize: Unknown display (%s)"%display)
# try to import requirements
try:
exec(visuals[display]['import'])
except:
sys.exit("Could not visualize due to missing dependencies")
exec(visuals[display]['exec'])
except __HOLE__:
pass
|
KeyboardInterrupt
|
dataset/ETHPy150Open NorthernSec/CVE-Scan/bin/visualizer.py/visualize
|
6,563
|
def main():
'''
Purpose::
Fetches
http://en.wikipedia.org/wiki/List_of_United_States_district_and_territorial_courts
and uses XPATH to extract out Regions
from United States district and territorial courts
The data is then written to a flat file one region per
line.
Input::
Output::
Assumptions::
'''
# Get arguments
args = parse_arguments()
if args.url:
url = args.url
# Make soup
try:
resp = urlopen(url)
except URLError as e:
print 'An error occured fetching %s \n %s' % (url, e.reason)
return 1
soup = BeautifulSoup(resp.read())
# Get table
try:
table = soup.find_all('table')[3]
except __HOLE__ as e:
print 'No tables found, exiting'
return 1
# Get rows
try:
rows = table.find_all('tr')
except AttributeError as e:
print 'No table rows found, exiting'
return 1
# Get data
table_data = parse_rows(rows)
f = open('US_district_and_territorial_courts.txt', 'w')
# Print data
#f.write("\n".join(str(i).encode('utf8') for i in table_data))
for i in table_data:
f.write((i).encode('utf8') +'\n')
f.close()
#write data to flat file
|
AttributeError
|
dataset/ETHPy150Open memex-explorer/memex-gate/utility/scrape_district_and_territorial_courts.py/main
|
6,564
|
def notify(subject, whom, what):
"""Send email notification.
Try to notify the addressee (``whom``) by e-mail, with Subject:
defined by ``subject`` and message body by ``what``.
"""
msg = email.message_from_string(what)
msg.add_header("From", "Certbot renewal agent <root>")
msg.add_header("To", whom)
msg.add_header("Subject", subject)
msg = msg.as_string()
try:
lmtp = smtplib.LMTP()
lmtp.connect()
lmtp.sendmail("root", [whom], msg)
except (smtplib.SMTPHeloError, smtplib.SMTPRecipientsRefused,
smtplib.SMTPSenderRefused, smtplib.SMTPDataError, socket.error):
# We should try using /usr/sbin/sendmail in this case
try:
proc = subprocess.Popen(["/usr/sbin/sendmail", "-t"],
stdin=subprocess.PIPE)
proc.communicate(msg)
except __HOLE__:
return False
return True
|
OSError
|
dataset/ETHPy150Open letsencrypt/letsencrypt/certbot/notify.py/notify
|
6,565
|
def __init__(self, *args, **kwargs):
self._fname = None
if 'file_path' in kwargs:
self.file_path = kwargs.pop('file_path')
else:
self.file_path = getattr(settings, 'SMS_FILE_PATH', None)
# Make sure self.file_path is a string.
if not isinstance(self.file_path, basestring):
raise ImproperlyConfigured('Path for saving SMS is invalid: %r' % self.file_path)
self.file_path = os.path.abspath(self.file_path)
# Make sure that self.file_path is an directory if it exists.
if os.path.exists(self.file_path) and not os.path.isdir(self.file_path):
raise ImproperlyConfigured('Path for saving SMS messages exists, but is not a directory: %s' % self.file_path)
# Try to create it, if it not exists.
elif not os.path.exists(self.file_path):
try:
os.makedirs(self.file_path)
except __HOLE__, err:
raise ImproperlyConfigured('Could not create directory for saving SMS messages: %s (%s)' % (self.file_path, err))
# Make sure that self.file_path is writable.
if not os.access(self.file_path, os.W_OK):
raise ImproperlyConfigured('Could not write to directory: %s' % self.file_path)
# Finally, call super().
# Since we're using the console-based backend as a base,
# force the stream to be None, so we don't default to stdout
kwargs['stream'] = None
super(SmsBackend, self).__init__(*args, **kwargs)
|
OSError
|
dataset/ETHPy150Open stefanfoulis/django-sendsms/sendsms/backends/filebased.py/SmsBackend.__init__
|
6,566
|
def rm_path(persist_path):
if not os.path.exists(persist_path):
return
if os.path.isdir(persist_path):
rm_func = shutil.rmtree
elif os.path.isfile(persist_path):
rm_func = os.unlink
else:
raise ValueError("Unknown how to `rm` path: %s" % (persist_path))
try:
rm_func(persist_path)
except (__HOLE__, OSError):
pass
|
IOError
|
dataset/ETHPy150Open openstack/taskflow/taskflow/examples/example_utils.py/rm_path
|
6,567
|
def __init__(self):
super(RedisBackend, self).__init__()
self._prefix = settings.REDIS_PREFIX
connection_cls = settings.REDIS_CONNECTION_CLASS
if connection_cls is not None:
self._rd = utils.import_module_attr(connection_cls)()
else:
try:
import redis
except __HOLE__:
raise ImproperlyConfigured(
"The Redis backend requires redis-py to be installed.")
if isinstance(settings.REDIS_CONNECTION, six.string_types):
self._rd = redis.from_url(settings.REDIS_CONNECTION)
else:
self._rd = redis.Redis(**settings.REDIS_CONNECTION)
|
ImportError
|
dataset/ETHPy150Open jazzband/django-constance/constance/backends/redisd.py/RedisBackend.__init__
|
6,568
|
def renderHTTP(self, ctx):
"""You know what you doing."""
self.fp.restat()
if self.type is None:
self.type, self.encoding = getTypeAndEncoding(self.fp.basename(),
self.contentTypes,
self.contentEncodings,
self.defaultType)
if not self.fp.exists():
return rend.FourOhFour()
request = inevow.IRequest(ctx)
if self.fp.isdir():
return self.redirect(request)
# fsize is the full file size
# size is the length of the part actually transmitted
fsize = size = self.getFileSize()
request.setHeader('accept-ranges','bytes')
if self.type:
request.setHeader('content-type', self.type)
if self.encoding:
request.setHeader('content-encoding', self.encoding)
try:
f = self.openForReading()
except __HOLE__, e:
import errno
if e[0] == errno.EACCES:
return ForbiddenResource().render(request)
else:
raise
if request.setLastModified(self.fp.getmtime()) is http.CACHED:
return ''
try:
range = request.getHeader('range')
if range is not None:
# This is a request for partial data...
bytesrange = string.split(range, '=')
assert bytesrange[0] == 'bytes',\
"Syntactically invalid http range header!"
start, end = string.split(bytesrange[1],'-')
if start:
f.seek(int(start))
if end:
end = int(end)
else:
end = fsize-1
request.setResponseCode(http.PARTIAL_CONTENT)
request.setHeader('content-range',"bytes %s-%s/%s" % (
str(start), str(end), str(fsize)))
#content-length should be the actual size of the stuff we're
#sending, not the full size of the on-server entity.
size = 1 + end - int(start)
request.setHeader('content-length', str(size))
except:
traceback.print_exc(file=log.logfile)
if request.method == 'HEAD':
return ''
# return data
FileTransfer(f, size, request)
# and make sure the connection doesn't get closed
return request.deferred
|
IOError
|
dataset/ETHPy150Open twisted/nevow/nevow/static.py/File.renderHTTP
|
6,569
|
@register.tag(name='captureas')
def do_captureas(parser, token):
try:
tag_name, args = token.contents.split(None, 1)
except __HOLE__:
raise template.TemplateSyntaxError("'captureas' node requires a variable name.")
nodelist = parser.parse(('endcaptureas',))
parser.delete_first_token()
return CaptureasNode(nodelist, args)
|
ValueError
|
dataset/ETHPy150Open brosner/django-notification/notification/templatetags/captureas_tag.py/do_captureas
|
6,570
|
def load(path, format=None):
"""Load pointcloud from path.
Currently supports PCD and PLY files.
Format should be "pcd", "ply", or None to infer from the pathname.
"""
format = _infer_format(path, format)
p = PointCloud()
try:
loader = getattr(p, "_from_%s_file" % format)
except __HOLE__:
raise ValueError("unknown file format %s" % format)
if loader(_encode(path)):
raise IOError("error while loading pointcloud from %r (format=%r)"
% (path, format))
return p
|
AttributeError
|
dataset/ETHPy150Open strawlab/python-pcl/pcl/__init__.py/load
|
6,571
|
def save(cloud, path, format=None, binary=False):
"""Save pointcloud to file.
Format should be "pcd", "ply", or None to infer from the pathname.
"""
format = _infer_format(path, format)
try:
dumper = getattr(cloud, "_to_%s_file" % format)
except __HOLE__:
raise ValueError("unknown file format %s" % format)
if dumper(_encode(path), binary):
raise IOError("error while saving pointcloud to %r (format=%r)"
% (path, format))
|
AttributeError
|
dataset/ETHPy150Open strawlab/python-pcl/pcl/__init__.py/save
|
6,572
|
def __init__(self, code, title="", explanation=""):
self.code = code
# There is a strict rule about constructing status line for HTTP:
# '...Status-Line, consisting of the protocol version followed by a
# numeric status code and its associated textual phrase, with each
# element separated by SP characters'
# (http://www.faqs.org/rfcs/rfc2616.html)
# 'code' and 'title' can not be empty because they correspond
# to numeric status code and its associated text
if title:
self.title = title
else:
try:
self.title = woutil.status_reasons[self.code]
except __HOLE__:
msg = _LE("Improper or unknown HTTP status code used: %d")
LOG.error(msg, code)
self.title = woutil.status_generic_reasons[self.code // 100]
self.explanation = explanation
super(ConvertedException, self).__init__()
|
KeyError
|
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/exception.py/ConvertedException.__init__
|
6,573
|
def __init__(self, message=None, **kwargs):
self.kwargs = kwargs
if 'code' not in self.kwargs:
try:
self.kwargs['code'] = self.code
except __HOLE__:
pass
if not message:
try:
message = self.msg_fmt % kwargs
except Exception:
exc_info = sys.exc_info()
# kwargs doesn't match a variable in the message
# log the issue and the kwargs
LOG.exception(_LE('Exception in string format operation'))
for name, value in six.iteritems(kwargs):
LOG.error("%s: %s" % (name, value)) # noqa
if CONF.fatal_exception_format_errors:
six.reraise(*exc_info)
else:
# at least get the core message out if something happened
message = self.msg_fmt
self.message = message
super(NovaException, self).__init__(message)
|
AttributeError
|
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/exception.py/NovaException.__init__
|
6,574
|
def _get_deployment(pod, remote, subdomain):
if remote:
dest_class = webreview_destination.WebReviewDestination
return dest_class(dest_class.Config(remote=remote, name=subdomain))
else:
try:
deployment = pod.get_deployment('webreview')
if subdomain:
deployment.config.subdomain = subdomain
return deployment
except __HOLE__:
text = ('Must provide --remote or specify a deployment named '
'"webreview" in podspec.yaml.')
raise click.ClickException(text)
|
ValueError
|
dataset/ETHPy150Open grow/grow/grow/commands/stage.py/_get_deployment
|
6,575
|
def generate_doc(config):
docdir = os.path.join(cwd,'documentation')
if not os.path.exists(docdir):
warn("Couldn't find documentation file at: %s" % docdir)
return None
try:
import markdown2 as markdown
except __HOLE__:
import markdown
documentation = []
for file in os.listdir(docdir):
if file in ignoreFiles or os.path.isdir(os.path.join(docdir, file)):
continue
md = open(os.path.join(docdir,file)).read()
html = markdown.markdown(md)
documentation.append({file:html});
return documentation
|
ImportError
|
dataset/ETHPy150Open dbankier/CoreTelephony-for-Appcelerator-Titanium/build.py/generate_doc
|
6,576
|
def get_redis_connection(config, use_strict_redis=False):
"""
Returns a redis connection from a connection config
"""
redis_cls = redis.StrictRedis if use_strict_redis else redis.Redis
if 'URL' in config:
return redis_cls.from_url(config['URL'], db=config.get('DB'))
if 'USE_REDIS_CACHE' in config.keys():
try:
from django.core.cache import caches
cache = caches[config['USE_REDIS_CACHE']]
except ImportError:
from django.core.cache import get_cache
cache = get_cache(config['USE_REDIS_CACHE'])
if hasattr(cache, 'client'):
# We're using django-redis. The cache's `client` attribute
# is a pluggable backend that return its Redis connection as
# its `client`
try:
# To get Redis connection on django-redis >= 3.4.0
# we need to use cache.client.get_client() instead of
# cache.client.client used in older versions
try:
return cache.client.get_client()
except __HOLE__:
return cache.client.client
except NotImplementedError:
pass
else:
# We're using django-redis-cache
try:
return cache._client
except AttributeError:
# For django-redis-cache > 0.13.1
return cache.get_master_client()
if 'UNIX_SOCKET_PATH' in config:
return redis_cls(unix_socket_path=config['UNIX_SOCKET_PATH'], db=config['DB'])
return redis_cls(host=config['HOST'], port=config['PORT'], db=config['DB'], password=config.get('PASSWORD', None))
|
AttributeError
|
dataset/ETHPy150Open ui/django-rq/django_rq/queues.py/get_redis_connection
|
6,577
|
def incr(self, key, delta=1):
try:
val = self._cache.incr(key, delta)
# python-memcache responds to incr on non-existent keys by
# raising a ValueError. Cmemcache returns None. In both
# cases, we should raise a ValueError though.
except __HOLE__:
val = None
if val is None:
raise ValueError("Key '%s' not found" % key)
return val
|
ValueError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/_internal/django/core/cache/backends/memcached.py/CacheClass.incr
|
6,578
|
def decr(self, key, delta=1):
try:
val = self._cache.decr(key, delta)
# python-memcache responds to decr on non-existent keys by
# raising a ValueError. Cmemcache returns None. In both
# cases, we should raise a ValueError though.
except __HOLE__:
val = None
if val is None:
raise ValueError("Key '%s' not found" % key)
return val
|
ValueError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/_internal/django/core/cache/backends/memcached.py/CacheClass.decr
|
6,579
|
def update(self):
self.clear()
logging.debug('getting status')
for line in os.popen('git status').readlines():
line = line.strip()
if line.startswith('#\t'):
try:
status, file = [l.strip() for l in line[2:].split(':')]
if self.status.has_key(file):
self.status[status].append(file)
else:
self.status[status] = [file]
except __HOLE__:
if self.status.has_key('untracked'):
self.status['untracked'].append( line[2:].strip() )
else:
self.status['untracked'] = [ line[2:].strip() ]
logging.debug('current status: %r' %self.status)
return self.status
|
ValueError
|
dataset/ETHPy150Open semk/GitFS/gitfs.py/GitStatus.update
|
6,580
|
def _find_command(path):
# path is a file
assert os.path.isfile(path)
# in dictionary lookup have keys as files and directories.
# if this path exists in there, it's a simple match
try:
return lookup[path]
except KeyError:
pass
# is the parent directory in there?
while path != '/':
path = os.path.dirname(path)
try:
return lookup[path]
except __HOLE__:
pass
|
KeyError
|
dataset/ETHPy150Open peterbe/python-gorun/gorun.py/_find_command
|
6,581
|
def start(actual_directories):
wm = WatchManager()
flags = EventsCodes.ALL_FLAGS
mask = flags['IN_MODIFY'] #| flags['IN_CREATE']
p = PTmp()
notifier = Notifier(wm, p)
for actual_directory in actual_directories:
print "DIRECTORY", actual_directory
wdd = wm.add_watch(actual_directory, mask, rec=True)
# notifier = Notifier(wm, p, timeout=10)
try:
print "Waiting for stuff to happen..."
notifier.loop()
except __HOLE__:
pass
return 0
|
KeyboardInterrupt
|
dataset/ETHPy150Open peterbe/python-gorun/gorun.py/start
|
6,582
|
def _set_collect(group, p, barrier_token, columns):
""" Get new partition dataframe from partd """
try:
return p.get(group)
except __HOLE__:
assert columns is not None, columns
# when unable to get group, create dummy DataFrame
# which has the same columns as original
return pd.DataFrame(columns=columns)
|
ValueError
|
dataset/ETHPy150Open dask/dask/dask/dataframe/shuffle.py/_set_collect
|
6,583
|
def import_class(handler_class_path_string):
sys.path.append( os.getcwd() )
handler_class_path = handler_class_path_string.split(".")
class_name = handler_class_path[-1]
package_name = ".".join(handler_class_path[:-1])
package = __import__(package_name, fromlist=[class_name])
try:
handler_class = getattr( package, class_name )
except __HOLE__:
raise AttributeError( "Can't find %s. Only %s"%(class_name, dir(package)) )
return handler_class
|
AttributeError
|
dataset/ETHPy150Open bmander/graphserver/pygs/graphserver/ext/routeserver/routeserver.py/import_class
|
6,584
|
def _handle_put(gcs_stub, filename, param_dict, headers, payload):
"""Handle PUT."""
if _iscopy(headers):
return _copy(gcs_stub, filename, headers)
token = _get_param('upload_id', param_dict)
content_range = _ContentRange(headers)
if _is_query_progress(content_range):
return _find_progress(gcs_stub, filename, token)
if not content_range.value:
raise ValueError('Missing header content-range.', httplib.BAD_REQUEST)
if (headers.get('x-goog-if-generation-match', None) == '0' and
gcs_stub.head_object(filename) is not None):
return _FakeUrlFetchResult(httplib.PRECONDITION_FAILED, {}, '')
if not token:
if content_range.length is None:
raise ValueError('Content-Range must have a final length.',
httplib.BAD_REQUEST)
elif not content_range.no_data and content_range.range[0] != 0:
raise ValueError('Content-Range must specify complete object.',
httplib.BAD_REQUEST)
else:
token = gcs_stub.post_start_creation(filename, headers)
try:
gcs_stub.put_continue_creation(token,
payload,
content_range.range,
content_range.length)
except __HOLE__, e:
return _FakeUrlFetchResult(e.args[1], {}, e.args[0])
if content_range.length is not None:
response_headers = {
'content-length': 0,
}
response_status = httplib.OK
else:
response_headers = {}
response_status = 308
return _FakeUrlFetchResult(response_status, response_headers, '')
|
ValueError
|
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/ext/cloudstorage/stub_dispatcher.py/_handle_put
|
6,585
|
def get_settings_from_client(client):
"""Pull out settings from a SoftLayer.BaseClient instance.
:param client: SoftLayer.BaseClient instance
"""
settings = {
'username': '',
'api_key': '',
'timeout': '',
'endpoint_url': '',
}
try:
settings['username'] = client.auth.username
settings['api_key'] = client.auth.api_key
except AttributeError:
pass
transport = _resolve_transport(client.transport)
try:
settings['timeout'] = transport.timeout
settings['endpoint_url'] = transport.endpoint_url
except __HOLE__:
pass
return settings
|
AttributeError
|
dataset/ETHPy150Open softlayer/softlayer-python/SoftLayer/CLI/config/__init__.py/get_settings_from_client
|
6,586
|
def get(self):
s = self.s
pos = self.pos
if self.ignore_space:
while True:
if pos >= len(s):
return u""
elif is_space(ord(s[pos])):
pos += 1
elif s[pos] == u"#":
pos = s.find(u"\n", pos)
if pos < 0:
pos = len(s)
else:
break
try:
ch = s[pos]
self.pos = pos + 1
return ch
except IndexError:
self.pos = pos
return u""
except __HOLE__:
self.pos = len(s)
return u""
|
ValueError
|
dataset/ETHPy150Open samth/pycket/pycket/regexp.py/Source.get
|
6,587
|
def getid(obj):
"""Extracts object ID.
Abstracts the common pattern of allowing both an object or an
object's ID (UUID) as a parameter when dealing with relationships.
"""
try:
return obj.id
except __HOLE__:
return obj
|
AttributeError
|
dataset/ETHPy150Open openstack/python-cloudkittyclient/cloudkittyclient/common/base.py/getid
|
6,588
|
def _list(self, url, response_key=None, obj_class=None, body=None,
expect_single=False):
resp = self.api.get(url)
if not resp.content:
raise exc.HTTPNotFound
body = resp.json()
if obj_class is None:
obj_class = self.resource_class
if response_key:
try:
data = body[response_key]
except __HOLE__:
return []
else:
data = body
if expect_single:
data = [data]
return [obj_class(self, res, loaded=True) for res in data if res]
|
KeyError
|
dataset/ETHPy150Open openstack/python-cloudkittyclient/cloudkittyclient/common/base.py/Manager._list
|
6,589
|
def update(self):
try:
return self.manager.update(**self.dirty_fields)
except __HOLE__:
raise exc.NotUpdatableError(self)
|
AttributeError
|
dataset/ETHPy150Open openstack/python-cloudkittyclient/cloudkittyclient/common/base.py/Resource.update
|
6,590
|
def _toShiftJisString(byteString):
byteString = byteString.split(b"\x00")[0]
try:
return byteString.decode("shift_jis")
except __HOLE__:
# discard truncated sjis char
return byteString[:-1].decode("shift_jis")
|
UnicodeDecodeError
|
dataset/ETHPy150Open sugiany/blender_mmd_tools/mmd_tools/core/vmd/__init__.py/_toShiftJisString
|
6,591
|
def mkdir_p(dir_path):
try:
os.makedirs(dir_path)
except __HOLE__ as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(dir_path):
pass
else:
raise
|
OSError
|
dataset/ETHPy150Open ensime/ensime-sublime/ensime.py/mkdir_p
|
6,592
|
def config_override_type(value):
try:
section, remainder = value.split(b'/', 1)
key, value = remainder.split(b'=', 1)
return (section.strip(), key.strip(), value.strip())
except __HOLE__:
raise argparse.ArgumentTypeError(
'%s must have the format section/key=value' % value)
|
ValueError
|
dataset/ETHPy150Open mopidy/mopidy/mopidy/commands.py/config_override_type
|
6,593
|
def run(self, args, config):
def on_sigterm(loop):
logger.info('GLib mainloop got SIGTERM. Exiting...')
loop.quit()
loop = GLib.MainLoop()
GLib.unix_signal_add(
GLib.PRIORITY_DEFAULT, signal.SIGTERM, on_sigterm, loop)
mixer_class = self.get_mixer_class(config, args.registry['mixer'])
backend_classes = args.registry['backend']
frontend_classes = args.registry['frontend']
exit_status_code = 0
try:
mixer = None
if mixer_class is not None:
mixer = self.start_mixer(config, mixer_class)
if mixer:
self.configure_mixer(config, mixer)
audio = self.start_audio(config, mixer)
backends = self.start_backends(config, backend_classes, audio)
core = self.start_core(config, mixer, backends, audio)
self.start_frontends(config, frontend_classes, core)
logger.info('Starting GLib mainloop')
loop.run()
except (exceptions.BackendError,
exceptions.FrontendError,
exceptions.MixerError):
logger.info('Initialization error. Exiting...')
exit_status_code = 1
except __HOLE__:
logger.info('Interrupted. Exiting...')
except Exception:
logger.exception('Uncaught exception')
finally:
loop.quit()
self.stop_frontends(frontend_classes)
self.stop_core()
self.stop_backends(backend_classes)
self.stop_audio()
if mixer_class is not None:
self.stop_mixer(mixer_class)
process.stop_remaining_actors()
return exit_status_code
|
KeyboardInterrupt
|
dataset/ETHPy150Open mopidy/mopidy/mopidy/commands.py/RootCommand.run
|
6,594
|
def get_db_prep_value(self, value, connection=None, prepared=False):
try:
return value.raw
except __HOLE__:
return value
|
AttributeError
|
dataset/ETHPy150Open zsiciarz/django-markitup/markitup/fields.py/MarkupField.get_db_prep_value
|
6,595
|
def _get_status_code(self, status_code_or_response):
try:
return status_code_or_response.status_code
except __HOLE__:
return status_code_or_response
|
AttributeError
|
dataset/ETHPy150Open sunscrapers/djet/djet/assertions.py/StatusCodeAssertionsMixin._get_status_code
|
6,596
|
def run_echo_server():
class Handler(BaseHTTPRequestHandler):
def _do(self):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
parsed = urlparse(self.path)
query_parameters = parse_qs(parsed.query)
response = {
'path': parsed.path,
'headers': dict(self.headers)
}
if query_parameters:
response['query_params'] = query_parameters
try:
try: # py2
raw_content_len = self.headers.getheader('content-length')
except __HOLE__: # py3
raw_content_len = self.headers.get('content-length')
content_len = int(raw_content_len)
except TypeError:
content_len = 0
if content_len:
body = self.rfile.read(content_len)
try: # py3
body = body.decode('UTF-8')
except AttributeError: # py2
pass
if body:
response['body'] = body
print(response)
encoded_json = json.dumps(response)
self.wfile.write(b(encoded_json))
return
do_GET = _do
do_POST = _do
do_PUT = _do
do_HEAD = _do
do_PATCH = _do
do_OPTIONS = _do
do_DELETE = _do
do_TRACE = _do
do_CONNECT = _do
server_address = ('', PORT)
httpd = HTTPServer(server_address, Handler)
httpd.serve_forever()
|
AttributeError
|
dataset/ETHPy150Open django-silk/silk/project/tests/util.py/run_echo_server
|
6,597
|
def _save(self):
""" Archive a copy of the agent object for future use """
success = False
make_backup = True
print "Attempting to save agent..."
try:
with open(self.pickle_filename, 'wb') as agent_data:
pickle.dump(self, agent_data)
if make_backup:
with open(''.join((self.pickle_filename, '.bak')),
'wb') as agent_data_bak:
pickle.dump(self, agent_data_bak)
print("Agent data saved at " + str(self.timestep) + " time steps")
except __HOLE__ as err:
print("File error: " + str(err) +
" encountered while saving agent data")
except pickle.PickleError as perr:
print("Pickling error: " + str(perr) +
" encountered while saving agent data")
else:
success = True
return success
|
IOError
|
dataset/ETHPy150Open matt2000/becca/core/agent.py/Agent._save
|
6,598
|
def restore(self):
""" Reconstitute the agent from a previously saved agent """
restored_agent = self
try:
with open(self.pickle_filename, 'rb') as agent_data:
loaded_agent = pickle.load(agent_data)
# Compare the number of channels in the restored agent with
# those in the already initialized agent. If it matches,
# accept the agent. If it doesn't,
# print a message, and keep the just-initialized agent.
if((loaded_agent.num_sensors == self.num_sensors) and
(loaded_agent.num_actions == self.num_actions)):
print(''.join(('Agent restored at timestep ',
str(loaded_agent.timestep),
' from ', self.pickle_filename)))
restored_agent = loaded_agent
else:
print("The agent " + self.pickle_filename + " does not have " +
"the same number of input and output elements as " +
"the world.")
print("Creating a new agent from scratch.")
except __HOLE__:
print("Couldn't open %s for loading" % self.pickle_filename)
except pickle.PickleError, e:
print("Error unpickling world: %s" % e)
return restored_agent
|
IOError
|
dataset/ETHPy150Open matt2000/becca/core/agent.py/Agent.restore
|
6,599
|
@register.filter
def bootstrap_message_classes(message):
"""
Return the message classes for a message
"""
extra_tags = None
try:
extra_tags = message.extra_tags
except __HOLE__:
pass
if not extra_tags:
extra_tags = ""
classes = [extra_tags]
try:
level = message.level
except AttributeError:
pass
else:
try:
classes.append(MESSAGE_LEVEL_CLASSES[level])
except KeyError:
classes.append("alert alert-danger")
return ' '.join(classes).strip()
|
AttributeError
|
dataset/ETHPy150Open dyve/django-bootstrap3/bootstrap3/templatetags/bootstrap3.py/bootstrap_message_classes
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.