Index: build.Lib.include.properties =================================================================== --- build.Lib.include.properties (revision 3071) +++ build.Lib.include.properties (working copy) @@ -35,6 +35,7 @@ copy.py copy_reg.py Cookie.py +csv.py difflib.py dircache.py dircmp.py Index: src/org/python/modules/Setup.java =================================================================== --- src/org/python/modules/Setup.java (revision 3071) +++ src/org/python/modules/Setup.java (working copy) @@ -54,6 +54,7 @@ "array:org.python.modules.ArrayModule", "sets:org.python.modules.sets.Sets", "_random:org.python.modules.random.RandomModule", - "cmath" + "cmath", + "_csv", }; } Index: src/org/python/modules/_csv.java =================================================================== --- src/org/python/modules/_csv.java (revision 0) +++ src/org/python/modules/_csv.java (revision 0) @@ -0,0 +1,992 @@ +//csv module + +/* + This module provides the low-level underpinnings of a CSV reading/writing + module. Users should not use this module directly, but import the csv.py + module instead. + */ +package org.python.modules; + +import org.python.core.ArgParser; +import org.python.core.Py; +import org.python.core.PyClass; +import org.python.core.PyDictionary; +import org.python.core.PyException; +import org.python.core.PyFieldDescr; +import org.python.core.PyInstance; +import org.python.core.PyInteger; +import org.python.core.PyIterator; +import org.python.core.PyList; +import org.python.core.PyNewWrapper; +import org.python.core.PyNone; +import org.python.core.PyObject; +import org.python.core.PyString; +import org.python.core.PyType; + +public class _csv { + + // version + public static String __version__ = "1.0"; + + // CSV Exception + public static PyObject Error = new PyString("_csv.Error"); + + // Dialect registry + private static PyDictionary dialects = new PyDictionary(); + + // enum ParserState (_csv.c) + private static final int START_RECORD = 0; + + private static final int START_FIELD = 1; + + private static final int ESCAPED_CHAR = 2; + + private static final int IN_FIELD = 3; + + private static final int IN_QUOTED_FIELD = 4; + + private static final int ESCAPE_IN_QUOTED_FIELD = 5; + + private static final int QUOTE_IN_QUOTED_FIELD = 6; + + // enum QuoteSytle (_csv.c) + public static final int QUOTE_MINIMAL = 0; + + public static final int QUOTE_ALL = 1; + + public static final int QUOTE_NONNUMERIC = 2; + + public static final int QUOTE_NONE = 3; + + // struct DialectObj (_csv.c) + public static class Dialect extends PyObject { + public String __doc__ = "CSV dialect\n" + + "\n" + + "The Dialect type records CSV parsing and generation options.\n"; + + // is " represented by ""? + public boolean doublequote; + + // field separator + public char delimiter; + + // quote character + public char quotechar; + + // escape character + public char escapechar; + + // ignore spaces following delimiter? + public boolean skipinitialspace; + + // string to write between records + public PyObject lineterminator; + + // style of quoting to write + public int quoting; + + // raise exception on bad CSV + public boolean strict; + + public static void typeSetup(PyObject dict, PyType.Newstyle marker) { + dict.__setitem__("__new__", new PyNewWrapper(PyObject.class, + "__new__", -1, -1) { + public PyObject new_impl(boolean init, PyType subtype, + PyObject[] args, String[] kws) { + return new Dialect(args, kws); + } + }); + + dict.__setitem__("doublequote", new PyFieldDescr("doublequote", + Dialect.class, "doublequote")); + dict.__setitem__("delimiter", new PyFieldDescr("delimiter", + Dialect.class, "delimiter")); + dict.__setitem__("quotechar", new PyFieldDescr("quotechar", + Dialect.class, "quotechar")); + dict.__setitem__("escapechar", new PyFieldDescr("escapechar", + Dialect.class, "escapechar")); + dict.__setitem__("skipinitialspace", new PyFieldDescr( + "skipinitialspace", Dialect.class, "skipinitialspace")); + dict.__setitem__("lineterminator", new PyFieldDescr( + "lineterminator", Dialect.class, "lineterminator")); + dict.__setitem__("quoting", new PyFieldDescr("quoting", + Dialect.class, "quoting")); + dict.__setitem__("strict", new PyFieldDescr("strict", + Dialect.class, "strict")); + } + + public void __delattr__(String name) { + throw Py.TypeError("Cannot delete numeric/char attribute"); + } + + public PyObject __findattr__(String name) { + // instead of get_None_as_nullchar in _csv.c + if ("escapechar".equals(name) && escapechar == '\0') { + return Py.None; + } + return super.__findattr__(name); + } + + public void __setattr__(String name, PyObject value) { + if ("lineterminator".equals(name)) { + // instead of set_string in _csv.c + if (!(value instanceof PyString)) { + throw Py + .TypeError("Bad argument type for built-in operation"); + } + } else if ("escapechar".equals(name)) { + // instead of set_None_as_nullchar in _csv.c + if (value instanceof PyNone) { + escapechar = '\0'; + return; + } else if (value instanceof PyString) { + PyString str = (PyString) value; + if (str.__len__() != 1) { + throw Py.TypeError("Bad argument"); + } + } else { + throw Py.TypeError("Bad argument"); + } + } else if ("quoting".equals(name) && value instanceof PyInteger) { + PyInteger num_obj = (PyInteger) value; + int num = num_obj.getValue(); + if(num < QUOTE_MINIMAL || num > QUOTE_NONE) { + throw Py.TypeError("bad argument type for built-in operation"); + } + } + super.__setattr__(name, value); + } + + // dialect_init (_csv.c) + public Dialect(PyObject[] args, String[] kwargs) { + super(); + + PyObject dialect = null; + PyString name_obj = null; + PyObject value_obj = null; + ArgParser ap = null; + + this.quotechar = '"'; + this.delimiter = ','; + this.escapechar = '\0'; + this.skipinitialspace = false; + this.lineterminator = new PyString("\r\n"); + if (this.lineterminator == null) { + throw Error("Error creating dialect - lineterminator creation failed."); + } + this.quoting = QUOTE_MINIMAL; + this.doublequote = true; + this.strict = false; + + try { + ap = new ArgParser("Dialect.init", args, kwargs, new String[] { + "csvfile", "dialect", "delimiter", "doublequote", + "escapechar", "lineterminator", "quotechar", "quoting", + "skipinitialspace", "strict" }); + dialect = ap.getPyObject(1, new PyString("excel")); + } catch (PyException ex) { + throw Py.AttributeError(ex.value.toString()); + } + + if (dialect != null) { + + // If dialect is a string, look it up in our registry + if (dialect instanceof PyString) { + PyObject new_dia = get_dialect_from_registry(dialect); + if (new_dia == null) { + throw Error("Error creating dialect - retrieval from registry failed."); + } + dialect = new_dia; + } + + // A class rather than an instance? Instantiate + if (dialect instanceof PyClass) { + PyObject new_dia; + new_dia = dialect.__call__(); + if (new_dia == null) { + throw Error("message"); + } + dialect = new_dia; + } + + // Make sure we finally have an instance + PyObject dir_list = (PyList) dialect.__dir__(); + if (!(dialect instanceof PyInstance) || (dir_list == null)) { + throw Py.TypeError("dialect must be an instance"); + } + + // And extract the attributes + for (int i = 0; i < dir_list.__len__(); ++i) { + String s; + name_obj = (PyString) dir_list.__getitem__(i); + s = name_obj.toString(); + if (s == null) { + throw Error("Error initialising Dialect"); + } + + if (s.charAt(0) == '_') { + continue; + } + value_obj = dialect.__getattr__(name_obj); + if (value_obj != null) { + this.__setattr__(name_obj, value_obj); + } + } + } + // Check if keyword arguments were specified to override + // specified dialect parameters. + // There must be a better way to do this (?) but it will do for now + if (kwargs != null) { + for (int i = 0; i < kwargs.length; ++i) { + if (kwargs[i].equals("delimiter")) { + this.__setattr__(Py.newString(kwargs[i]), ap.getPyObject(2)); + } else if (kwargs[i].equals("doublequote")) { + this.__setattr__(Py.newString(kwargs[i]), ap.getPyObject(3)); + } else if (kwargs[i].equals("escapechar")) { + this.__setattr__(Py.newString(kwargs[i]), ap.getPyObject(4)); + } else if (kwargs[i].equals("lineterminator")) { + this.__setattr__(Py.newString(kwargs[i]), ap.getPyObject(5)); + } else if (kwargs[i].equals("quotechar")) { + this.__setattr__(Py.newString(kwargs[i]), ap.getPyObject(6)); + } else if (kwargs[i].equals("quoting")) { + this.__setattr__(Py.newString(kwargs[i]), ap.getPyObject(7)); + } else if (kwargs[i].equals("skipinitialspace")) { + this.__setattr__(Py.newString(kwargs[i]), ap.getPyObject(8)); + } else if (kwargs[i].equals("strict")) { + this.__setattr__(Py.newString(kwargs[i]), ap.getPyObject(9)); + } + } + } + } + } + + // struct ReaderObj (_csv.c) + public static class Reader extends PyIterator { + public String __doc__ = "CSV reader\n" + + "\n" + + "Reader objects are responsible for reading and parsing tabular data\n" + + "in CSV format.\n"; + + // Parsing dialect + public Dialect dialect; + + // Iterate over this for input lines + private PyObject input_iter; + + // Field list for current record + private PyList fields; + + // Current CSV parse state + private int state; + + // Build current field in here + private StringBuffer field; + + // did we have a parse error? + private boolean had_parse_error; + + // csv_reader (_csv.c) + public Reader(PyObject[] args, String[] keywords) { + super(); + + this.dialect = null; + this.input_iter = null; + this.fields = null; + this.field = null; + this.had_parse_error = false; + this.state = START_RECORD; + + if (args.length < 1) { + throw Py.TypeError("expected at least 1 argument, got 0"); + } + + // The "csvfile" parameter is the only positional argument that + // must exist and is referred to as the input_iter in the source. + // Py.iter() (rather unobviously!) throws a TypeError if input_iter + // is not an iterator. + input_iter = args[0]; + input_iter = Py.iter(input_iter, "argument 1 must be an iterator"); + + // Dialect is responsible for extracting the dialect argument + // and all the keyword parameters that make up "fmtparam". + dialect = new Dialect(args, keywords); + + fields = new PyList(); + field = new StringBuffer(); + } + + + // Reader_iternext (_csv.c) + public PyObject __iternext__() { + PyObject lineobj; + PyObject fields; + String line; + + do { + lineobj = input_iter.__iternext__(); + if (lineobj == null) { + // End of input OR exception + if (this.field.length() != 0) { + throw Error("newline inside string"); + } else { + return null; + } + } + + if (this.had_parse_error) { + this.fields = new PyList(); + this.state = START_RECORD; + this.had_parse_error = false; + } + + line = lineobj.toString(); + if (line == null) { + return null; + } + if (line.contains("\0")) { + this.had_parse_error = true; + throw Error("string with NUL bytes"); + } + // parsing below is based on _csv.c which + // expects all strings to be terminated with + // a nul byte. + line += "\0"; + + // Process line of text - send '\n' to processing code to + // represent end of line. End of line which is not at end of + // string is an error. + int idx = 0; + while (idx < line.length() - 1) { // -1 to accomodate for nul + char c = line.charAt(idx++); + + if (c == '\r') { + c = line.charAt(idx++); + if (c == '\0') { + // macintosh end of line + break; + } + if (c == '\n') { + c = line.charAt(idx++); + if (c == '\0') { + // DOS end of line + break; + } + } + this.had_parse_error = true; + throw Error("newline inside string"); + } + if (c == '\n') { + c = line.charAt(idx++); + if (c == '\0') { + // unix end of line + break; + } + this.had_parse_error = true; + throw Error("newline inside string"); + } + parse_process_char(c); + } + parse_process_char('\n'); + + } while (this.state != START_RECORD); + + fields = this.fields; + this.fields = new PyList(); + + return fields; + } + + private void parse_process_char(char c) { + + Dialect dialect = this.dialect; + + switch (this.state) { + + case START_RECORD: + // start of record + if (c == '\n') { + // empty line - return [] + break; + } + // normal character - handle as START_FIELD + this.state = START_FIELD; + // *** fallthru *** + case START_FIELD: + // expecting field + if (c == '\n') { + // save empty field - return [fields] + parse_save_field(); + this.state = START_RECORD; + } else if (c == dialect.quotechar) { + // start quoted field + this.state = IN_QUOTED_FIELD; + } else if (c == dialect.escapechar) { + // possible escaped character + this.state = ESCAPED_CHAR; + } else if (c == ' ' && dialect.skipinitialspace) { + // ignore space at start of field + ; + } else if (c == dialect.delimiter) { + // save empty field + parse_save_field(); + } else { + // begin new unquoted field + parse_add_char(c); + this.state = IN_FIELD; + } + break; + + case ESCAPED_CHAR: + if (c != dialect.escapechar && c != dialect.delimiter && c != dialect.quotechar) { + parse_add_char(dialect.escapechar); + } + parse_add_char(c); + this.state = IN_FIELD; + break; + + case IN_FIELD: + // in unquoted field + if (c == '\n') { + // end of line - return [fields] + parse_save_field(); + this.state = START_RECORD; + } else if (c == dialect.escapechar) { + // possible escaped character + this.state = ESCAPED_CHAR; + } else if (c == dialect.delimiter) { + // save field - wait for new field + parse_save_field(); + this.state = START_FIELD; + } else { + // normal character - save in field + parse_add_char(c); + } + break; + + case IN_QUOTED_FIELD: + // in quoted field + if (c == '\n') { + // end of line - save '\n' in field + parse_add_char('\n'); + } else if (c == dialect.escapechar) { + // Possible escape character + this.state = ESCAPE_IN_QUOTED_FIELD; + } else if (c == dialect.quotechar) { + if (dialect.doublequote) { + // doublequote; " represented by "" + this.state = QUOTE_IN_QUOTED_FIELD; + } else { + // end of quote part of field + this.state = IN_FIELD; + } + } else { + // normal character - save in field + parse_add_char(c); + } + break; + + case ESCAPE_IN_QUOTED_FIELD: + if (c != dialect.escapechar && c != dialect.delimiter && c != dialect.quotechar) { + parse_add_char(dialect.escapechar); + } + parse_add_char(c); + this.state = IN_QUOTED_FIELD; + break; + + case QUOTE_IN_QUOTED_FIELD: + // doublequote - seen a quote in an quoted field + if (dialect.quoting != QUOTE_NONE && c == dialect.quotechar) { + // save "" as " + parse_add_char(c); + this.state = IN_QUOTED_FIELD; + } else if (c == dialect.delimiter) { + // save field - wait for new field + parse_save_field(); + this.state = START_FIELD; + } else if (c == '\n') { + // end of line - return [fields] + parse_save_field(); + this.state = START_RECORD; + } else if (!dialect.strict) { + parse_add_char(c); + this.state = IN_FIELD; + } else { + // illegal + this.had_parse_error = true; + throw Error("" + dialect.delimiter + " expected after " + + dialect.quotechar); + } + break; + } + } + + private void parse_save_field() { + PyObject field; + + field = new PyString(this.field.toString()); + if (field != null) { + this.fields.append(field); + } + + // fastest way to clear StringBuffer? + this.field = new StringBuffer(); + } + + private void parse_add_char(char c) { + this.field.append(c); + } + } + + // struct WriterObj (_csv.c) + public static class Writer extends PyObject { + // write output lines to this file + private PyObject writeline; + + // parsing dialect + public Dialect dialect; + + // buffer for parser.join + private StringBuffer rec; + + // length of record + private int rec_len; + + // number of fields in record + private int num_fields; + + // whether field should be quoted during a join. This is + // instead of passing around the quoted parameter in all the join + // methods in _csv.c + private boolean quoted = false; + + public Writer(PyObject[] args, String[] keywords) { + PyObject output_file; + + this.dialect = null; + this.writeline = null; + this.rec_len = 0; + this.num_fields = 0; + + if (args.length < 1) { + throw Py.TypeError("expected at least 1 argument, got 0"); + } + output_file = args[0]; + try { + this.writeline = output_file.__getattr__("write"); + if (this.writeline == null || !(this.writeline.isCallable())) { + throw Py.TypeError("argument 1 must be an instance with a write method"); + } + } catch(PyException ex) { + if(Py.matchException(ex, Py.AttributeError)) { + throw Py.TypeError("argument 1 must be an instance with a write method"); + } + } + + // Dialect is responsible for extracting the dialect argument + // and all the keyword parameters that make up "fmtparam". + this.dialect = new Dialect(args, keywords); + } + + public static PyString __doc__writerows = new PyString( + "writerows(sequence of sequences)\n" + + "\n" + + "Construct and write a series of sequences to a csv file. Non-string\n" + + "elements will be converted to string."); + + //csv_writerows (_csv.c) + public void writerows(PyObject seqseq) { + PyObject row_iter; + PyObject row_obj; + boolean result; + + row_iter = seqseq.__iter__(); + if (row_iter == null) { + throw Error("writerows() argument must be iterable"); + } + + while ((row_obj = row_iter.__iternext__()) != null) { + result = writerow(row_obj); + if (!result) { + break; + } + } + } + + public static PyString __doc__writerow = new PyString( + "writerow(sequence)\n" + + "\n" + + "Construct and write a CSV record from a sequence of fields. Non-string\n" + + "elements will be converted to string." + ); + + // csv_writerow (_csv.c) + public boolean writerow(PyObject seq) { + Dialect dialect = this.dialect; + int len, i; + + if (!seq.isSequenceType()) { + throw Error("sequence expected"); + } + + len = seq.__len__(); + if (len < 0) { + return false; + } + + // Join all fields in internal buffer. + join_reset(); + for (i = 0; i < len; i++) { + PyObject field; + boolean append_ok; + + quoted = false; + + field = seq.__getitem__(i); + if (field == null) { + return false; + } + + if (dialect.quoting == QUOTE_NONNUMERIC) { + + try { + field.__float__(); + } catch(PyException ex) { + quoted = true; + } + } + + if (field instanceof PyString) { + append_ok = join_append(field.toString(), len == 1); + } else if (field == Py.None) { + append_ok = join_append("", len == 1); + } else { + PyObject str; + + str = field.__str__(); + if (str == null) { + return false; + } + + append_ok = join_append(str.toString(), len == 1); + } + if (!append_ok) { + return false; + } + } + + // Add line terminator. + if (!join_append_lineterminator()) { + return false; + } + + this.writeline.__call__(new PyString(rec.toString())); + return true; + } + + private void join_reset() { + this.rec_len = 0; + this.num_fields = 0; + this.quoted = false; + this.rec = new StringBuffer(); + } + + private boolean join_append_lineterminator() { + this.rec.append(this.dialect.lineterminator.toString()); + return true; + } + + private boolean join_append(String field, boolean quote_empty) { + int rec_len; + + rec_len = join_append_data(field, quote_empty, false); + if (rec_len < 0) { + return false; + } + + this.rec_len = join_append_data(field, quote_empty, true); + this.num_fields++; + + return true; + } + + /** + * This method behaves differently depending on the value of copy_phase: + * if copy_phase is false, then the method determines the new record + * length. If copy_phase is true then the new field is appended to the + * record. + */ + private int join_append_data(String field, boolean quote_empty, boolean copy_phase) { + Dialect dialect = this.dialect; + int i, rec_len; + + rec_len = this.rec_len; + + // If this is not the first field we need a field separator. + if (this.num_fields > 0) { + if (copy_phase) { + this.rec.append(dialect.delimiter); + } + rec_len++; + } + + // Handle preceding quote. + switch (dialect.quoting) { + case QUOTE_ALL: + quoted = true; + if (copy_phase) { + this.rec.append(dialect.quotechar); + } + rec_len++; + break; + case QUOTE_MINIMAL: + case QUOTE_NONNUMERIC: + // We only know about quoted in the copy phase. + if (copy_phase && quoted) { + this.rec.append(dialect.quotechar); + rec_len++; + } + break; + case QUOTE_NONE: + break; + } + + // parsing below is based on _csv.c which + // expects all strings to be terminated with + // a nul byte. + field += '\0'; + + // Copy/count field data. + for (i = 0;; i++) { + char c = field.charAt(i); + + if (c == '\0') { + break; + } + // If in doublequote mode we escape quote chars with a quote. + if (dialect.quoting != QUOTE_NONE && c == dialect.quotechar + && dialect.doublequote) { + if (copy_phase) { + this.rec.append(dialect.quotechar); + } + quoted = true; + rec_len++; + } + + /* + * Some special characters need to be escaped. If we have a + * quote character switch to quoted field instead of escaping + * individual characters. + */ + if (!quoted && (c == dialect.delimiter || + c == dialect.escapechar || c == '\n' || c == '\r')) { + if (dialect.quoting != QUOTE_NONE) { + quoted = true; + } else if (dialect.escapechar != '\0') { + // Check _csv.c + if (copy_phase) { + this.rec.append(dialect.escapechar); + } + rec_len++; + } else { + throw Error("delimiter must be quoted or escaped"); + } + } + // Copy field character into record buffer. + if (copy_phase) { + this.rec.append(c); + } + rec_len++; + } + + // If field is empty check if it needs to be quoted. + if (i == 0 && quote_empty) { + if (dialect.quoting == QUOTE_NONE) { + throw Error("single empty field record must be quoted"); + + } else { + quoted = true; + } + } + + // Handle final quote character on field. + if (quoted) { + if (copy_phase) { + this.rec.append(dialect.quotechar); + } else { + // Didn't know about leading quote until we found it + // necessary in field data - compensate for it now. + rec_len++; + } + rec_len++; + } + + return rec_len; + } + + } + + public static PyObject writer(PyObject[] args, String[] keywords) { + return new Writer(args, keywords); + } + + public static PyObject reader(PyObject[] args, String[] keywords) { + return new Reader(args, keywords); + } + + public static PyObject list_dialects() { + return dialects.keys(); + } + + public static void register_dialect(PyObject name_obj, PyObject dialect_obj) { + + if (!(name_obj instanceof PyString)) { + throw Py.TypeError("dialect name must be a string or unicode"); + } + + // A class rather than an instance? Instantiate + if (dialect_obj instanceof PyClass) { + PyObject new_dia; + new_dia = dialect_obj.__call__(); + if (new_dia == null) { + throw Error("Error registering dialect - unable to create instace"); + } + dialect_obj = new_dia; + } + + // Make sure we finally have an instance + if (!(dialect_obj instanceof PyInstance)) { + throw Py.TypeError("dialect must be an instance"); + } + dialect_obj.__setattr__("_name", name_obj); + dialects.__setitem__(name_obj, dialect_obj); + } + + public static void unregister_dialect(PyObject name_obj) { + try { + dialects.__delitem__(name_obj); + } catch (PyException ex) { + if (Py.matchException(ex, Py.KeyError)) { + throw Error("unkown dialect: " + name_obj.toString()); + } + } + } + + public static PyObject get_dialect(PyObject name_obj) { + return get_dialect_from_registry(name_obj); + } + + private static PyObject get_dialect_from_registry(PyObject name_obj) { + PyObject dialect_obj = dialects.get(name_obj); + if (dialect_obj instanceof PyNone) { + throw Error("unknown dialect: \"" + name_obj + "\""); + } + return dialect_obj; + } + + private static PyException Error(String message) { + return new PyException(Error, message); + } + + public static PyString __doc__ = new PyString( + "CSV parsing and writing.\n" + + "\n" + + "This module provides classes that assist in the reading and writing\n" + + "of Comma Separated Value (CSV) files, and implements the interface\n" + + "described by PEP 305. Although many CSV files are simple to parse,\n" + + "the format is not formally defined by a stable specification and\n" + + "is subtle enough that parsing lines of a CSV file with something\n" + + "like line.split(\",\") is bound to fail. The module supports three\n" + + "basic APIs: reading, writing, and registration of dialects.\n" + + "\n" + + "\n" + + "DIALECT REGISTRATION:\n" + + "\n" + + "Readers and writers support a dialect argument, which is a convenient\n" + + "handle on a group of settings. When the dialect argument is a string,\n" + + "it identifies one of the dialects previously registered with the module.\n" + + "If it is a class or instance, the attributes of the argument are used as\n" + + "the settings for the reader or writer:\n" + + "\n" + + " class excel:\n" + + " delimiter = ','\n" + + " quotechar = '\"'\n" + + " escapechar = None\n" + + " doublequote = True\n" + + " skipinitialspace = False\n" + + " lineterminator = '\r\n'\n" + + " quoting = QUOTE_MINIMAL\n" + + "\n" + + "SETTINGS:\n" + + "\n" + + " * quotechar - specifies a one-character string to use as the \n" + + " quoting character. It defaults to '\"'.\n" + + " * delimiter - specifies a one-character string to use as the \n" + + " field separator. It defaults to ','.\n" + + " * skipinitialspace - specifies how to interpret whitespace which\n" + + " immediately follows a delimiter. It defaults to False, which\n" + + " means that whitespace immediately following a delimiter is part\n" + + " of the following field.\n" + + " * lineterminator - specifies the character sequence which should \n" + + " terminate rows.\n" + + " * quoting - controls when quotes should be generated by the writer.\n" + + " It can take on any of the following module constants:\n" + + "\n" + + " csv.QUOTE_MINIMAL means only when required, for example, when a\n" + + " field contains either the quotechar or the delimiter\n" + + " csv.QUOTE_ALL means that quotes are always placed around fields.\n" + + " csv.QUOTE_NONNUMERIC means that quotes are always placed around\n" + + " fields which do not parse as integers or floating point\n" + + " numbers.\n" + + " csv.QUOTE_NONE means that quotes are never placed around fields.\n" + + " * escapechar - specifies a one-character string used to escape \n" + + " the delimiter when quoting is set to QUOTE_NONE.\n" + + " * doublequote - controls the handling of quotes inside fields. When\n" + + " True, two consecutive quotes are interpreted as one during read,\n" + + " and when writing, each quote character embedded in the data is\n" + + " written as two quotes\n"); + + public static PyString __doc__reader = new PyString( + " csv_reader = reader(iterable [, dialect='excel']\n" + + " [optional keyword args])\n" + + " for row in csv_reader:\n" + + " process(row)\n" + + "\n" + + "The \"iterable\" argument can be any object that returns a line\n" + + "of input for each iteration, such as a file object or a list. The\n" + + "optional \"dialect\" parameter is discussed below. The function\n" + + "also accepts optional keyword arguments which override settings\n" + + "provided by the dialect.\n" + + "\n" + + "The returned object is an iterator. Each iteration returns a row\n" + + "of the CSV file (which can span multiple input lines):\n"); + + public static PyString __doc__writer = new PyString( + " csv_writer = csv.writer(fileobj [, dialect='excel']\n" + + " [optional keyword args])\n" + + " for row in csv_writer:\n" + + " csv_writer.writerow(row)\n" + + "\n" + + " [or]\n" + + "\n" + + " csv_writer = csv.writer(fileobj [, dialect='excel']\n" + + " [optional keyword args])\n" + + " csv_writer.writerows(rows)\n" + + "\n" + + "The \"fileobj\" argument can be any object that supports the file API.\n"); + + public static PyString __doc__list_dialects = new PyString( + "Return a list of all know dialect names.\n" + + " names = csv.list_dialects()"); + + public static PyString __doc__getdialect = new PyString( + "Return the dialect instance associated with name.\n" + + " dialect = csv.get_dialect(name)"); + + public static PyString __doc__register_dialect = new PyString( + "Create a mapping from a string name to a dialect class.\n" + + " dialect = csv.register_dialect(name, dialect)"); + + public static PyString __doc__unregister_dialect = new PyString( + "Delete the name/dialect mapping associated with a string name.\n" + + " csv.unregister_dialect(name)"); +} Index: Lib/test/test_csv.py =================================================================== --- Lib/test/test_csv.py (revision 0) +++ Lib/test/test_csv.py (revision 0) @@ -0,0 +1,717 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2001,2002 Python Software Foundation +# csv package unit tests + +import sys +import unittest +from StringIO import StringIO +import csv +#import gc +from test import test_support + +class Test_Csv(unittest.TestCase): + """ + Test the underlying C csv parser in ways that are not appropriate + from the high level interface. Further tests of this nature are done + in TestDialectRegistry. + """ + def test_reader_arg_valid(self): + self.assertRaises(TypeError, csv.reader) + self.assertRaises(TypeError, csv.reader, None) + self.assertRaises(AttributeError, csv.reader, [], bad_attr = 0) + self.assertRaises(csv.Error, csv.reader, [], 'foo') + class BadClass: + def __init__(self): + raise IOError + self.assertRaises(IOError, csv.reader, [], BadClass) + self.assertRaises(TypeError, csv.reader, [], None) + class BadDialect: + bad_attr = 0 + self.assertRaises(AttributeError, csv.reader, [], BadDialect) + + def test_writer_arg_valid(self): + self.assertRaises(TypeError, csv.writer) + self.assertRaises(TypeError, csv.writer, None) + self.assertRaises(AttributeError, csv.writer, StringIO(), bad_attr = 0) + + def _test_attrs(self, obj): + self.assertEqual(obj.dialect.delimiter, ',') + obj.dialect.delimiter = '\t' + self.assertEqual(obj.dialect.delimiter, '\t') + self.assertRaises(TypeError, delattr, obj.dialect, 'delimiter') + self.assertRaises(TypeError, setattr, obj.dialect, + 'lineterminator', None) + obj.dialect.escapechar = None + self.assertEqual(obj.dialect.escapechar, None) + self.assertRaises(TypeError, delattr, obj.dialect, 'quoting') + self.assertRaises(TypeError, setattr, obj.dialect, 'quoting', None) + obj.dialect.quoting = csv.QUOTE_MINIMAL + self.assertEqual(obj.dialect.quoting, csv.QUOTE_MINIMAL) + + def test_reader_attrs(self): + self._test_attrs(csv.reader([])) + + def test_writer_attrs(self): + self._test_attrs(csv.writer(StringIO())) + + def _write_test(self, fields, expect, **kwargs): + fileobj = StringIO() + writer = csv.writer(fileobj, **kwargs) + writer.writerow(fields) + self.assertEqual(fileobj.getvalue(), + expect + writer.dialect.lineterminator) + + 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_bigfield(self): + # This exercises the buffer realloc functionality + bigstring = 'X' * 50000 + self._write_test([bigstring,bigstring], '%s,%s' % \ + (bigstring, bigstring)) + + def test_write_quoting(self): + self._write_test(['a','1','p,q'], 'a,1,"p,q"') + self.assertRaises(csv.Error, + self._write_test, + ['a','1','p,q'], 'a,1,"p,q"', + quoting = csv.QUOTE_NONE) + self._write_test(['a','1','p,q'], 'a,1,"p,q"', + quoting = csv.QUOTE_MINIMAL) + self._write_test(['a','1','p,q'], '"a",1,"p,q"', + quoting = csv.QUOTE_NONNUMERIC) + self._write_test(['a','1','p,q'], '"a","1","p,q"', + quoting = csv.QUOTE_ALL) + + def test_write_escape(self): + self._write_test(['a','1','p,q'], 'a,1,"p,q"', + escapechar='\\') +# FAILED - needs to be fixed [am]: +# self._write_test(['a','1','p,"q"'], 'a,1,"p,\\"q\\"', +# escapechar='\\', doublequote = 0) + self._write_test(['a','1','p,q'], 'a,1,p\\,q', + escapechar='\\', quoting = csv.QUOTE_NONE) + + def test_writerows(self): + class BrokenFile: + def write(self, buf): + raise IOError + writer = csv.writer(BrokenFile()) + self.assertRaises(IOError, writer.writerows, [['a']]) + fileobj = StringIO() + writer = csv.writer(fileobj) + self.assertRaises(TypeError, writer.writerows, None) + writer.writerows([['a','b'],['c','d']]) + self.assertEqual(fileobj.getvalue(), "a,b\r\nc,d\r\n") + + def _read_test(self, input, expect, **kwargs): + reader = csv.reader(input, **kwargs) + result = list(reader) + self.assertEqual(result, expect) + + def test_read_oddinputs(self): + self._read_test([], []) + self._read_test([''], [[]]) + self.assertRaises(csv.Error, self._read_test, + ['"ab"c'], None, strict = 1) + # cannot handle null bytes for the moment + self.assertRaises(csv.Error, self._read_test, + ['ab\0c'], None, strict = 1) + self._read_test(['"ab"c'], [['abc']], doublequote = 0) + + def test_read_eol(self): + self._read_test(['a,b'], [['a','b']]) + self._read_test(['a,b\n'], [['a','b']]) + self._read_test(['a,b\r\n'], [['a','b']]) + self._read_test(['a,b\r'], [['a','b']]) + self.assertRaises(csv.Error, self._read_test, ['a,b\rc,d'], []) + self.assertRaises(csv.Error, self._read_test, ['a,b\nc,d'], []) + self.assertRaises(csv.Error, self._read_test, ['a,b\r\nc,d'], []) + + def test_read_escape(self): + self._read_test(['a,\\b,c'], [['a', '\\b', 'c']], escapechar='\\') + self._read_test(['a,b\\,c'], [['a', 'b,c']], escapechar='\\') + self._read_test(['a,"b\\,c"'], [['a', 'b,c']], escapechar='\\') + self._read_test(['a,"b,\\c"'], [['a', 'b,\\c']], escapechar='\\') + self._read_test(['a,"b,c\\""'], [['a', 'b,c"']], escapechar='\\') + self._read_test(['a,"b,c"\\'], [['a', 'b,c\\']], escapechar='\\') + + def test_read_bigfield(self): + # This exercises the buffer realloc functionality + bigstring = 'X' * 50000 + bigline = '%s,%s' % (bigstring, bigstring) + self._read_test([bigline], [[bigstring, bigstring]]) + +class TestDialectRegistry(unittest.TestCase): + 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", None) + class bogus: + def __init__(self): + raise KeyError + self.assertRaises(KeyError, csv.register_dialect, "nonesuch", bogus) + + def test_registry(self): + class myexceltsv(csv.excel): + delimiter = "\t" + name = "myexceltsv" + expected_dialects = csv.list_dialects() + [name] + expected_dialects.sort() + csv.register_dialect(name, myexceltsv) + try: + self.failUnless(isinstance(csv.get_dialect(name), myexceltsv)) + got_dialects = csv.list_dialects() + got_dialects.sort() + self.assertEqual(expected_dialects, got_dialects) + finally: + csv.unregister_dialect(name) + + def test_incomplete_dialect(self): + class myexceltsv(csv.Dialect): + delimiter = "\t" + self.assertRaises(csv.Error, myexceltsv) + + def test_space_dialect(self): + class space(csv.excel): + delimiter = " " + quoting = csv.QUOTE_NONE + escapechar = "\\" + + s = StringIO("abc def\nc1ccccc1 benzene\n") + rdr = csv.reader(s, dialect=space()) + self.assertEqual(rdr.next(), ["abc", "def"]) + self.assertEqual(rdr.next(), ["c1ccccc1", "benzene"]) + + def test_dialect_apply(self): + class testA(csv.excel): + delimiter = "\t" + class testB(csv.excel): + delimiter = ":" + class testC(csv.excel): + delimiter = "|" + + csv.register_dialect('testC', testC) + try: + fileobj = StringIO() + writer = csv.writer(fileobj) + writer.writerow([1,2,3]) + self.assertEqual(fileobj.getvalue(), "1,2,3\r\n") + + fileobj = StringIO() + writer = csv.writer(fileobj, testA) + writer.writerow([1,2,3]) + self.assertEqual(fileobj.getvalue(), "1\t2\t3\r\n") + + fileobj = StringIO() + writer = csv.writer(fileobj, dialect=testB()) + writer.writerow([1,2,3]) + self.assertEqual(fileobj.getvalue(), "1:2:3\r\n") + + fileobj = StringIO() + writer = csv.writer(fileobj, dialect='testC') + writer.writerow([1,2,3]) + self.assertEqual(fileobj.getvalue(), "1|2|3\r\n") + + fileobj = StringIO() + writer = csv.writer(fileobj, dialect=testA, delimiter=';') + writer.writerow([1,2,3]) + self.assertEqual(fileobj.getvalue(), "1;2;3\r\n") + finally: + csv.unregister_dialect('testC') + + def test_bad_dialect(self): + # Unknown parameter + self.assertRaises(AttributeError, csv.reader, [], bad_attr = 0) + # Bad values + self.assertRaises(TypeError, csv.reader, [], delimiter = None) + self.assertRaises(TypeError, csv.reader, [], quoting = -1) + self.assertRaises(TypeError, csv.reader, [], quoting = 100) + +class TestCsvBase(unittest.TestCase): + def readerAssertEqual(self, input, expected_result): + reader = csv.reader(StringIO(input), dialect = self.dialect) + fields = list(reader) + self.assertEqual(fields, expected_result) + + def writerAssertEqual(self, input, expected_result): + fileobj = StringIO() + writer = csv.writer(fileobj, dialect = self.dialect) + writer.writerows(input) + self.assertEqual(fileobj.getvalue(), expected_result) + +class TestDialectExcel(TestCsvBase): + dialect = 'excel' + + def test_single(self): + self.readerAssertEqual('abc', [['abc']]) + + def test_simple(self): + self.readerAssertEqual('1,2,3,4,5', [['1','2','3','4','5']]) + + def test_blankline(self): + self.readerAssertEqual('', []) + + def test_empty_fields(self): + self.readerAssertEqual(',', [['', '']]) + + def test_singlequoted(self): + self.readerAssertEqual('""', [['']]) + + def test_singlequoted_left_empty(self): + self.readerAssertEqual('"",', [['','']]) + + def test_singlequoted_right_empty(self): + self.readerAssertEqual(',""', [['','']]) + + def test_single_quoted_quote(self): + self.readerAssertEqual('""""', [['"']]) + + def test_quoted_quotes(self): + self.readerAssertEqual('""""""', [['""']]) + + def test_inline_quote(self): + self.readerAssertEqual('a""b', [['a""b']]) + + def test_inline_quotes(self): + self.readerAssertEqual('a"b"c', [['a"b"c']]) + + def test_quotes_and_more(self): + self.readerAssertEqual('"a"b', [['ab']]) + + def test_lone_quote(self): + self.readerAssertEqual('a"b', [['a"b']]) + + def test_quote_and_quote(self): + self.readerAssertEqual('"a" "b"', [['a "b"']]) + + def test_space_and_quote(self): + self.readerAssertEqual(' "a"', [[' "a"']]) + + def test_quoted(self): + self.readerAssertEqual('1,2,3,"I think, therefore I am",5,6', + [['1', '2', '3', + 'I think, therefore I am', + '5', '6']]) + + def test_quoted_quote(self): + self.readerAssertEqual('1,2,3,"""I see,"" said the blind man","as he picked up his hammer and saw"', + [['1', '2', '3', + '"I see," said the blind man', + 'as he picked up his hammer and saw']]) + + def test_quoted_nl(self): + input = '''\ +1,2,3,"""I see,"" +said the blind man","as he picked up his +hammer and saw" +9,8,7,6''' + self.readerAssertEqual(input, + [['1', '2', '3', + '"I see,"\nsaid the blind man', + 'as he picked up his\nhammer and saw'], + ['9','8','7','6']]) + + def test_dubious_quote(self): + self.readerAssertEqual('12,12,1",', [['12', '12', '1"', '']]) + + def test_null(self): + self.writerAssertEqual([], '') + + def test_single(self): + self.writerAssertEqual([['abc']], 'abc\r\n') + + def test_simple(self): + self.writerAssertEqual([[1, 2, 'abc', 3, 4]], '1,2,abc,3,4\r\n') + + def test_quotes(self): + self.writerAssertEqual([[1, 2, 'a"bc"', 3, 4]], '1,2,"a""bc""",3,4\r\n') + + def test_quote_fieldsep(self): + self.writerAssertEqual([['abc,def']], '"abc,def"\r\n') + + def test_newlines(self): + self.writerAssertEqual([[1, 2, 'a\nbc', 3, 4]], '1,2,"a\nbc",3,4\r\n') + +class EscapedExcel(csv.excel): + quoting = csv.QUOTE_NONE + escapechar = '\\' + +class TestEscapedExcel(TestCsvBase): + dialect = EscapedExcel() + + def test_escape_fieldsep(self): + self.writerAssertEqual([['abc,def']], 'abc\\,def\r\n') + + def test_read_escape_fieldsep(self): + self.readerAssertEqual('abc\\,def\r\n', [['abc,def']]) + +class QuotedEscapedExcel(csv.excel): + quoting = csv.QUOTE_NONNUMERIC + escapechar = '\\' + +class TestQuotedEscapedExcel(TestCsvBase): + dialect = QuotedEscapedExcel() + + def test_write_escape_fieldsep(self): + self.writerAssertEqual([['abc,def']], '"abc,def"\r\n') + + def test_read_escape_fieldsep(self): + self.readerAssertEqual('"abc\\,def"\r\n', [['abc,def']]) + +# Disabled, pending support in csv.utils module +class TestDictFields(unittest.TestCase): + ### "long" means the row is longer than the number of fieldnames + ### "short" means there are fewer elements in the row than fieldnames + def test_write_simple_dict(self): + fileobj = StringIO() + writer = csv.DictWriter(fileobj, fieldnames = ["f1", "f2", "f3"]) + writer.writerow({"f1": 10, "f3": "abc"}) + self.assertEqual(fileobj.getvalue(), "10,,abc\r\n") + + def test_write_no_fields(self): + fileobj = StringIO() + self.assertRaises(TypeError, csv.DictWriter, fileobj) + + def test_read_dict_fields(self): + reader = csv.DictReader(StringIO("1,2,abc\r\n"), + fieldnames=["f1", "f2", "f3"]) + self.assertEqual(reader.next(), {"f1": '1', "f2": '2', "f3": 'abc'}) + + def test_read_long(self): + reader = csv.DictReader(StringIO("1,2,abc,4,5,6\r\n"), + fieldnames=["f1", "f2"]) + self.assertEqual(reader.next(), {"f1": '1', "f2": '2', + None: ["abc", "4", "5", "6"]}) + + def test_read_long_with_rest(self): + reader = csv.DictReader(StringIO("1,2,abc,4,5,6\r\n"), + fieldnames=["f1", "f2"], restkey="_rest") + self.assertEqual(reader.next(), {"f1": '1', "f2": '2', + "_rest": ["abc", "4", "5", "6"]}) + + def test_read_short(self): + reader = csv.DictReader(["1,2,abc,4,5,6\r\n","1,2,abc\r\n"], + fieldnames="1 2 3 4 5 6".split(), + restval="DEFAULT") + self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc', + "4": '4', "5": '5', "6": '6'}) + self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc', + "4": 'DEFAULT', "5": 'DEFAULT', + "6": 'DEFAULT'}) + + def test_read_multi(self): + sample = [ + '2147483648,43.0e12,17,abc,def\r\n', + '147483648,43.0e2,17,abc,def\r\n', + '47483648,43.0,170,abc,def\r\n' + ] + + reader = csv.DictReader(sample, + fieldnames="i1 float i2 s1 s2".split()) + self.assertEqual(reader.next(), {"i1": '2147483648', + "float": '43.0e12', + "i2": '17', + "s1": 'abc', + "s2": 'def'}) + + def test_read_with_blanks(self): + reader = csv.DictReader(["1,2,abc,4,5,6\r\n","\r\n", + "1,2,abc,4,5,6\r\n"], + fieldnames="1 2 3 4 5 6".split()) + self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc', + "4": '4', "5": '5', "6": '6'}) + self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc', + "4": '4', "5": '5', "6": '6'}) + + def test_read_semi_sep(self): + reader = csv.DictReader(["1;2;abc;4;5;6\r\n"], + fieldnames="1 2 3 4 5 6".split(), + delimiter=';') + self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc', + "4": '4', "5": '5', "6": '6'}) + +class TestArrayWrites(unittest.TestCase): + def test_int_write(self): + import array + contents = [(20-i) for i in range(20)] + a = array.array('i', contents) + fileobj = StringIO() + writer = csv.writer(fileobj, dialect="excel") + writer.writerow(a) + expected = ",".join([str(i) for i in a])+"\r\n" + self.assertEqual(fileobj.getvalue(), expected) + + def test_double_write(self): + import array + contents = [(20-i)*0.1 for i in range(20)] + a = array.array('d', contents) + fileobj = StringIO() + writer = csv.writer(fileobj, dialect="excel") + writer.writerow(a) + expected = ",".join([str(i) for i in a])+"\r\n" + self.assertEqual(fileobj.getvalue(), expected) + + def test_float_write(self): + import array + contents = [(20-i)*0.1 for i in range(20)] + a = array.array('f', contents) + fileobj = StringIO() + writer = csv.writer(fileobj, dialect="excel") + writer.writerow(a) + expected = ",".join([str(i) for i in a])+"\r\n" + self.assertEqual(fileobj.getvalue(), expected) + + def test_char_write(self): + import array, string + a = array.array('c', string.letters) + fileobj = StringIO() + writer = csv.writer(fileobj, dialect="excel") + writer.writerow(a) + expected = ",".join(a)+"\r\n" + self.assertEqual(fileobj.getvalue(), expected) + +class TestDialectValidity(unittest.TestCase): + def test_quoting(self): + class mydialect(csv.Dialect): + delimiter = ";" + escapechar = '\\' + doublequote = False + skipinitialspace = True + lineterminator = '\r\n' + quoting = csv.QUOTE_NONE + d = mydialect() + + mydialect.quoting = None + self.assertRaises(csv.Error, mydialect) + + mydialect.quoting = csv.QUOTE_NONE + mydialect.escapechar = None + self.assertRaises(csv.Error, mydialect) + + mydialect.doublequote = True + mydialect.quoting = csv.QUOTE_ALL + mydialect.quotechar = '"' + d = mydialect() + + mydialect.quotechar = "''" + self.assertRaises(csv.Error, mydialect) + + mydialect.quotechar = 4 + self.assertRaises(csv.Error, mydialect) + + def test_delimiter(self): + class mydialect(csv.Dialect): + delimiter = ";" + escapechar = '\\' + doublequote = False + skipinitialspace = True + lineterminator = '\r\n' + quoting = csv.QUOTE_NONE + d = mydialect() + + mydialect.delimiter = ":::" + self.assertRaises(csv.Error, mydialect) + + mydialect.delimiter = 4 + self.assertRaises(csv.Error, mydialect) + + def test_lineterminator(self): + class mydialect(csv.Dialect): + delimiter = ";" + escapechar = '\\' + doublequote = False + skipinitialspace = True + lineterminator = '\r\n' + quoting = csv.QUOTE_NONE + d = mydialect() + + mydialect.lineterminator = ":::" + d = mydialect() + + mydialect.lineterminator = 4 + self.assertRaises(csv.Error, mydialect) + + +class TestSniffer(unittest.TestCase): + sample1 = """\ +Harry's, Arlington Heights, IL, 2/1/03, Kimi Hayes +Shark City, Glendale Heights, IL, 12/28/02, Prezence +Tommy's Place, Blue Island, IL, 12/28/02, Blue Sunday/White Crow +Stonecutters Seafood and Chop House, Lemont, IL, 12/19/02, Week Back +""" + sample2 = """\ +'Harry''s':'Arlington Heights':'IL':'2/1/03':'Kimi Hayes' +'Shark City':'Glendale Heights':'IL':'12/28/02':'Prezence' +'Tommy''s Place':'Blue Island':'IL':'12/28/02':'Blue Sunday/White Crow' +'Stonecutters Seafood and Chop House':'Lemont':'IL':'12/19/02':'Week Back' +""" + + header = '''\ +"venue","city","state","date","performers" +''' + sample3 = '''\ +05/05/03?05/05/03?05/05/03?05/05/03?05/05/03?05/05/03 +05/05/03?05/05/03?05/05/03?05/05/03?05/05/03?05/05/03 +05/05/03?05/05/03?05/05/03?05/05/03?05/05/03?05/05/03 +''' + + sample4 = '''\ +2147483648;43.0e12;17;abc;def +147483648;43.0e2;17;abc;def +47483648;43.0;170;abc;def +''' + + def test_has_header(self): + sniffer = csv.Sniffer() + self.assertEqual(sniffer.has_header(self.sample1), False) + self.assertEqual(sniffer.has_header(self.header+self.sample1), True) + + def test_sniff(self): + sniffer = csv.Sniffer() + dialect = sniffer.sniff(self.sample1) + self.assertEqual(dialect.delimiter, ",") + self.assertEqual(dialect.quotechar, '"') + self.assertEqual(dialect.skipinitialspace, True) + + dialect = sniffer.sniff(self.sample2) + self.assertEqual(dialect.delimiter, ":") + self.assertEqual(dialect.quotechar, "'") + self.assertEqual(dialect.skipinitialspace, False) + + def test_delimiters(self): + sniffer = csv.Sniffer() + dialect = sniffer.sniff(self.sample3) + self.assertEqual(dialect.delimiter, "0") + dialect = sniffer.sniff(self.sample3, delimiters="?,") + self.assertEqual(dialect.delimiter, "?") + dialect = sniffer.sniff(self.sample3, delimiters="/,") + self.assertEqual(dialect.delimiter, "/") + dialect = sniffer.sniff(self.sample4) + self.assertEqual(dialect.delimiter, ";") + +# commented out for now - jython csv module doesn't have gc module +if 0: + if not hasattr(sys, "gettotalrefcount"): + if test_support.verbose: print "*** skipping leakage tests ***" + else: + class NUL: + def write(s, *args): + pass + writelines = write + + class TestLeaks(unittest.TestCase): + def test_create_read(self): + delta = 0 + lastrc = sys.gettotalrefcount() + for i in xrange(20): + gc.collect() + self.assertEqual(gc.garbage, []) + rc = sys.gettotalrefcount() + csv.reader(["a,b,c\r\n"]) + csv.reader(["a,b,c\r\n"]) + csv.reader(["a,b,c\r\n"]) + delta = rc-lastrc + lastrc = rc + # if csv.reader() leaks, last delta should be 3 or more + self.assertEqual(delta < 3, True) + + def test_create_write(self): + delta = 0 + lastrc = sys.gettotalrefcount() + s = NUL() + for i in xrange(20): + gc.collect() + self.assertEqual(gc.garbage, []) + rc = sys.gettotalrefcount() + csv.writer(s) + csv.writer(s) + csv.writer(s) + delta = rc-lastrc + lastrc = rc + # if csv.writer() leaks, last delta should be 3 or more + self.assertEqual(delta < 3, True) + + def test_read(self): + delta = 0 + rows = ["a,b,c\r\n"]*5 + lastrc = sys.gettotalrefcount() + for i in xrange(20): + gc.collect() + self.assertEqual(gc.garbage, []) + rc = sys.gettotalrefcount() + rdr = csv.reader(rows) + for row in rdr: + pass + delta = rc-lastrc + lastrc = rc + # if reader leaks during read, delta should be 5 or more + self.assertEqual(delta < 5, True) + + def test_write(self): + delta = 0 + rows = [[1,2,3]]*5 + s = NUL() + lastrc = sys.gettotalrefcount() + for i in xrange(20): + gc.collect() + self.assertEqual(gc.garbage, []) + rc = sys.gettotalrefcount() + writer = csv.writer(s) + for row in rows: + writer.writerow(row) + delta = rc-lastrc + lastrc = rc + # if writer leaks during write, last delta should be 5 or more + self.assertEqual(delta < 5, True) + +# commented out for now - csv module doesn't yet support Unicode +if 0: + from StringIO import StringIO + import csv + + class TestUnicode(unittest.TestCase): + def test_unicode_read(self): + import codecs + f = codecs.EncodedFile(StringIO("Martin von Löwis," + "Marc André Lemburg," + "Guido van Rossum," + "François Pinard\r\n"), + data_encoding='iso-8859-1') + reader = csv.reader(f) + self.assertEqual(list(reader), [[u"Martin von Löwis", + u"Marc André Lemburg", + u"Guido van Rossum", + u"François Pinardn"]]) + +def test_main(): + mod = sys.modules[__name__] + test_support.run_unittest( + *[getattr(mod, name) for name in dir(mod) if name.startswith('Test')] + ) + +if __name__ == '__main__': + test_main()