def test_registry_badargs(self):
self.assertRaises(TypeError, csv.list_dialects, None)
self.assertRaises(TypeError, csv.get_dialect)
self.assertRaises(csv.Error, csv.get_dialect, None)
self.assertRaises(csv.Error, csv.get_dialect, "nonesuch")
self.assertRaises(TypeError, csv.unregister_dialect)
self.assertRaises(csv.Error, csv.unregister_dialect, None)
self.assertRaises(csv.Error, csv.unregister_dialect, "nonesuch")
self.assertRaises(TypeError, csv.register_dialect, None)
self.assertRaises(TypeError, csv.register_dialect, None, None)
self.assertRaises(TypeError, csv.register_dialect, "nonesuch", 0, 0)
self.assertRaises(TypeError, csv.register_dialect, "nonesuch",
badargument=None)
self.assertRaises(TypeError, csv.register_dialect, "nonesuch",
quoting=None)
self.assertRaises(TypeError, csv.register_dialect, [])
python类Error()的实例源码
def _test_arg_valid(self, ctor, arg):
self.assertRaises(TypeError, ctor)
self.assertRaises(TypeError, ctor, None)
self.assertRaises(TypeError, ctor, arg, bad_attr = 0)
self.assertRaises(TypeError, ctor, arg, delimiter = 0)
self.assertRaises(TypeError, ctor, arg, delimiter = 'XX')
self.assertRaises(csv.Error, ctor, arg, 'foo')
self.assertRaises(TypeError, ctor, arg, delimiter=None)
self.assertRaises(TypeError, ctor, arg, delimiter=1)
self.assertRaises(TypeError, ctor, arg, quotechar=1)
self.assertRaises(TypeError, ctor, arg, lineterminator=None)
self.assertRaises(TypeError, ctor, arg, lineterminator=1)
self.assertRaises(TypeError, ctor, arg, quoting=None)
self.assertRaises(TypeError, ctor, arg,
quoting=csv.QUOTE_ALL, quotechar='')
self.assertRaises(TypeError, ctor, arg,
quoting=csv.QUOTE_ALL, quotechar=None)
def test_write_arg_valid(self):
self._write_error_test(csv.Error, None)
self._write_test((), '')
self._write_test([None], '""')
self._write_error_test(csv.Error, [None], quoting = csv.QUOTE_NONE)
# Check that exceptions are passed up the chain
class BadList:
def __len__(self):
return 10;
def __getitem__(self, i):
if i > 2:
raise OSError
self._write_error_test(OSError, BadList())
class BadItem:
def __str__(self):
raise OSError
self._write_error_test(OSError, [BadItem()])
def test_write_escape(self):
self._write_test(['a',1,'p,q'], 'a,1,"p,q"',
escapechar='\\')
self._write_error_test(csv.Error, ['a',1,'p,"q"'],
escapechar=None, doublequote=False)
self._write_test(['a',1,'p,"q"'], 'a,1,"p,\\"q\\""',
escapechar='\\', doublequote = False)
self._write_test(['"'], '""""',
escapechar='\\', quoting = csv.QUOTE_MINIMAL)
self._write_test(['"'], '\\"',
escapechar='\\', quoting = csv.QUOTE_MINIMAL,
doublequote = False)
self._write_test(['"'], '\\"',
escapechar='\\', quoting = csv.QUOTE_NONE)
self._write_test(['a',1,'p,q'], 'a,1,p\\,q',
escapechar='\\', quoting = csv.QUOTE_NONE)
def test_read_bigfield(self):
# This exercises the buffer realloc functionality and field size
# limits.
limit = csv.field_size_limit()
try:
size = 50000
bigstring = 'X' * size
bigline = '%s,%s' % (bigstring, bigstring)
self._read_test([bigline], [[bigstring, bigstring]])
csv.field_size_limit(size)
self._read_test([bigline], [[bigstring, bigstring]])
self.assertEqual(csv.field_size_limit(), size)
csv.field_size_limit(size-1)
self.assertRaises(csv.Error, self._read_test, [bigline], [])
self.assertRaises(TypeError, csv.field_size_limit, None)
self.assertRaises(TypeError, csv.field_size_limit, 1, None)
finally:
csv.field_size_limit(limit)
def test_registry_badargs(self):
self.assertRaises(TypeError, csv.list_dialects, None)
self.assertRaises(TypeError, csv.get_dialect)
self.assertRaises(csv.Error, csv.get_dialect, None)
self.assertRaises(csv.Error, csv.get_dialect, "nonesuch")
self.assertRaises(TypeError, csv.unregister_dialect)
self.assertRaises(csv.Error, csv.unregister_dialect, None)
self.assertRaises(csv.Error, csv.unregister_dialect, "nonesuch")
self.assertRaises(TypeError, csv.register_dialect, None)
self.assertRaises(TypeError, csv.register_dialect, None, None)
self.assertRaises(TypeError, csv.register_dialect, "nonesuch", 0, 0)
self.assertRaises(TypeError, csv.register_dialect, "nonesuch",
badargument=None)
self.assertRaises(TypeError, csv.register_dialect, "nonesuch",
quoting=None)
self.assertRaises(TypeError, csv.register_dialect, [])
def _test_arg_valid(self, ctor, arg):
self.assertRaises(TypeError, ctor)
self.assertRaises(TypeError, ctor, None)
self.assertRaises(TypeError, ctor, arg, bad_attr = 0)
self.assertRaises(TypeError, ctor, arg, delimiter = 0)
self.assertRaises(TypeError, ctor, arg, delimiter = 'XX')
self.assertRaises(csv.Error, ctor, arg, 'foo')
self.assertRaises(TypeError, ctor, arg, delimiter=None)
self.assertRaises(TypeError, ctor, arg, delimiter=1)
self.assertRaises(TypeError, ctor, arg, quotechar=1)
self.assertRaises(TypeError, ctor, arg, lineterminator=None)
self.assertRaises(TypeError, ctor, arg, lineterminator=1)
self.assertRaises(TypeError, ctor, arg, quoting=None)
self.assertRaises(TypeError, ctor, arg,
quoting=csv.QUOTE_ALL, quotechar='')
self.assertRaises(TypeError, ctor, arg,
quoting=csv.QUOTE_ALL, quotechar=None)
def test_write_arg_valid(self):
self.assertRaises(csv.Error, self._write_test, None, '')
self._write_test((), '')
self._write_test([None], '""')
self.assertRaises(csv.Error, self._write_test,
[None], None, quoting = csv.QUOTE_NONE)
# Check that exceptions are passed up the chain
class BadList:
def __len__(self):
return 10;
def __getitem__(self, i):
if i > 2:
raise IOError
self.assertRaises(IOError, self._write_test, BadList(), '')
class BadItem:
def __str__(self):
raise IOError
self.assertRaises(IOError, self._write_test, [BadItem()], '')
def test_write_escape(self):
self._write_test(['a',1,'p,q'], 'a,1,"p,q"',
escapechar='\\')
self.assertRaises(csv.Error,
self._write_test,
['a',1,'p,"q"'], 'a,1,"p,\\"q\\""',
escapechar=None, doublequote=False)
self._write_test(['a',1,'p,"q"'], 'a,1,"p,\\"q\\""',
escapechar='\\', doublequote = False)
self._write_test(['"'], '""""',
escapechar='\\', quoting = csv.QUOTE_MINIMAL)
self._write_test(['"'], '\\"',
escapechar='\\', quoting = csv.QUOTE_MINIMAL,
doublequote = False)
self._write_test(['"'], '\\"',
escapechar='\\', quoting = csv.QUOTE_NONE)
self._write_test(['a',1,'p,q'], 'a,1,p\\,q',
escapechar='\\', quoting = csv.QUOTE_NONE)
def test_read_bigfield(self):
# This exercises the buffer realloc functionality and field size
# limits.
limit = csv.field_size_limit()
try:
size = 50000
bigstring = 'X' * size
bigline = '%s,%s' % (bigstring, bigstring)
self._read_test([bigline], [[bigstring, bigstring]])
csv.field_size_limit(size)
self._read_test([bigline], [[bigstring, bigstring]])
self.assertEqual(csv.field_size_limit(), size)
csv.field_size_limit(size-1)
self.assertRaises(csv.Error, self._read_test, [bigline], [])
self.assertRaises(TypeError, csv.field_size_limit, None)
self.assertRaises(TypeError, csv.field_size_limit, 1, None)
finally:
csv.field_size_limit(limit)
def test_registry_badargs(self):
self.assertRaises(TypeError, csv.list_dialects, None)
self.assertRaises(TypeError, csv.get_dialect)
self.assertRaises(csv.Error, csv.get_dialect, None)
self.assertRaises(csv.Error, csv.get_dialect, "nonesuch")
self.assertRaises(TypeError, csv.unregister_dialect)
self.assertRaises(csv.Error, csv.unregister_dialect, None)
self.assertRaises(csv.Error, csv.unregister_dialect, "nonesuch")
self.assertRaises(TypeError, csv.register_dialect, None)
self.assertRaises(TypeError, csv.register_dialect, None, None)
self.assertRaises(TypeError, csv.register_dialect, "nonesuch", 0, 0)
self.assertRaises(TypeError, csv.register_dialect, "nonesuch",
badargument=None)
self.assertRaises(TypeError, csv.register_dialect, "nonesuch",
quoting=None)
self.assertRaises(TypeError, csv.register_dialect, [])
def _get_reader(self, data):
"""Return the CSV reader for the given payload source
Returns:
StringIO: CSV reader object if the parse was successful OR
False if parse was unsuccessful
"""
delimiter = self.options.get('delimiter', self.__default_delimiter)
# TODO(ryandeivert): either subclass a current parser or add a new
# parser to support parsing CSV data that contains a header line
try:
csv_data = StringIO.StringIO(data)
reader = csv.reader(csv_data, delimiter=delimiter)
except (ValueError, csv.Error):
return False
return reader
def Readfile(file_path, remove_linebreaks=0, ignore_error=0):
data = []
if file_path == '-':
try:
data = sys.stdin.readlines()
except:
if not ignore_error:
Error(_('You must feed me with data on STDIN!'))
else:
try:
f = open(file_path)
data = f.readlines()
f.close()
except:
if not ignore_error:
Error(_("Cannot read file:") + ' ' + file_path)
if remove_linebreaks:
data = map(lambda x:re.sub('[\n\r]+$', '', x), data)
Message(_("File read (%d lines): %s") % (len(data), file_path), 2)
return data
def _set_prop(self, line=''):
"Extract info from original line and set data holders."
# Detect title type (numbered or not)
id_ = line.lstrip()[0]
if id_ == '=': kind = 'title'
elif id_ == '+': kind = 'numtitle'
else: Error("Unknown Title ID '%s'"%id_)
# Extract line info
match = regex[kind].search(line)
level = len(match.group('id'))
txt = match.group('txt').strip()
label = match.group('label')
# Parse info & save
if CONF['enum-title']: kind = 'numtitle' # force
if rules['titleblocks']:
self.tag = TAGS.get('%s%dOpen'%(kind,level)) or \
TAGS.get('title%dOpen'%level)
else:
self.tag = TAGS.get(kind+`level`) or \
TAGS.get('title'+`level`)
self.last_level = self.level
self.kind = kind
self.level = level
self.txt = txt
self.label = label
def blockin(self, block):
ret = []
if block not in self.allblocks:
Error("Invalid block '%s'"%block)
# First, let's close other possible open blocks
while self.block() and block not in self.contains[self.block()]:
ret.extend(self.blockout())
# Now we can gladly add this new one
self.BLK.append(block)
self.HLD.append([])
self.PRP.append({})
self.count += 1
if block == 'table': self.tableparser = TableMaster()
# Deeper and deeper
self.depth = len(self.BLK)
Debug('block ++ (%s): %s' % (block,self.BLK), 3)
return ret
def expand(self, line=''):
"Expand all macros found on the line"
while self.rgx.search(line):
m = self.rgx.search(line)
name = self.name = m.group('name').lower()
fmt = m.group('fmt') or self.dft_fmt.get(name)
if name == 'date':
txt = time.strftime(fmt,self.currdate)
elif name == 'mtime':
if self.infile in (STDIN, MODULEIN):
fdate = self.currdate
else:
mtime = os.path.getmtime(self.infile)
fdate = time.localtime(mtime)
txt = time.strftime(fmt,fdate)
elif name == 'infile' or name == 'outfile':
self.set_file_info(name)
txt = self.walk_file_format(fmt)
else:
Error("Unknown macro name '%s'"%name)
line = self.rgx.sub(txt,line,1)
return line
##############################################################################
def __init__(self, f, fieldnames=None, encoding=UTF8, **kwds):
self.encoding = encoding
try:
self.reader = csv.reader(UTF8Recoder(f, encoding) if self.encoding != UTF8 else f, dialect=csv.excel, **kwds)
if not fieldnames:
self.fieldnames = self.reader.next()
if len(self.fieldnames) > 0 and self.fieldnames[0].startswith(codecs.BOM_UTF8):
self.fieldnames[0] = self.fieldnames[0].replace(codecs.BOM_UTF8, u'', 1)
else:
self.fieldnames = fieldnames
except (csv.Error, StopIteration):
self.fieldnames = []
except LookupError as e:
Cmd.Backup()
usageErrorExit(e)
self.numfields = len(self.fieldnames)
def Readfile(file_path, remove_linebreaks=0, ignore_error=0):
data = []
if file_path == '-':
try:
data = sys.stdin.readlines()
except:
if not ignore_error:
Error(_('You must feed me with data on STDIN!'))
else:
try:
f = open(file_path)
data = f.readlines()
f.close()
except:
if not ignore_error:
Error(_("Cannot read file:") + ' ' + file_path)
if remove_linebreaks:
data = map(lambda x:re.sub('[\n\r]+$', '', x), data)
Message(_("File read (%d lines): %s") % (len(data), file_path), 2)
return data
def _set_prop(self, line=''):
"Extract info from original line and set data holders."
# Detect title type (numbered or not)
id_ = line.lstrip()[0]
if id_ == '=': kind = 'title'
elif id_ == '+': kind = 'numtitle'
else: Error("Unknown Title ID '%s'"%id_)
# Extract line info
match = regex[kind].search(line)
level = len(match.group('id'))
txt = match.group('txt').strip()
label = match.group('label')
# Parse info & save
if CONF['enum-title']: kind = 'numtitle' # force
if rules['titleblocks']:
self.tag = TAGS.get('%s%dOpen'%(kind,level)) or \
TAGS.get('title%dOpen'%level)
else:
self.tag = TAGS.get(kind+`level`) or \
TAGS.get('title'+`level`)
self.last_level = self.level
self.kind = kind
self.level = level
self.txt = txt
self.label = label
def blockin(self, block):
ret = []
if block not in self.allblocks:
Error("Invalid block '%s'"%block)
# First, let's close other possible open blocks
while self.block() and block not in self.contains[self.block()]:
ret.extend(self.blockout())
# Now we can gladly add this new one
self.BLK.append(block)
self.HLD.append([])
self.PRP.append({})
self.count += 1
if block == 'table': self.tableparser = TableMaster()
# Deeper and deeper
self.depth = len(self.BLK)
Debug('block ++ (%s): %s' % (block,self.BLK), 3)
return ret