c176a67ca67c22e018e9a2cd0170cee0a6580bbb
[nit.git] / lib / csv / test_csv.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # This file is free software, which comes along with NIT. This software is
4 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
5 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
6 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
7 # is kept unaltered, and a notification of the changes is added.
8 # You are allowed to redistribute it and sell it, alone or is a part of
9 # another product.
10
11 # Tests for `csv`.
12 module test_csv is test_suite
13
14 import test_suite
15 import csv
16
17 class TestCsvWriter
18 super TestSuite
19
20 # The custom CSV format used in the tests.
21 private var custom_format = new CsvFormat('/', ':', "#")
22
23 # Expect to write `row` as `expected_rfc4180` and as `expected_custom`.
24 #
25 # Parameters:
26 #
27 # * `always_escape`: value of the `always_escape` option.
28 # * `row`: row to write.
29 # * `expected_rfc4180`: expected result in RFC 4180.
30 # * `expected_custom`: expected result in the custom CSV format.
31 private fun expect(always_escape: Bool, row: SequenceRead[String],
32 expected_rfc4180: String,
33 expected_custom: String) do
34 var out = new StringOStream
35 var writer = new CsvWriter(out)
36
37 writer.always_escape = always_escape
38 writer.write_sequence(row)
39 assert out.to_s == expected_rfc4180 else
40 sys.stderr.write "\nFormat: RFC 4180\n"
41 sys.stderr.write "Expecting: \"{expected_rfc4180.escape_to_nit}\"\n"
42 sys.stderr.write "Got: \"{out.to_s.escape_to_nit}\"\n"
43 end
44 writer.close
45
46 out = new StringOStream
47 writer = new CsvWriter.with_format(out, custom_format)
48 writer.always_escape = always_escape
49 writer.write_sequence(row)
50 assert out.to_s == expected_custom else
51 sys.stderr.write "\nFormat: {custom_format.delimiter}"
52 sys.stderr.write " {custom_format.separator}"
53 sys.stderr.write " {custom_format.eol.escape_to_nit}\n"
54 sys.stderr.write "Expecting: \"{expected_custom.escape_to_nit}\"\n"
55 sys.stderr.write "Got: \"{out.to_s.escape_to_nit}\"\n"
56 end
57 writer.close
58 end
59
60 fun test_empty do expect(true, new Array[String], "\r\n", "#")
61
62 fun test_one_cell do expect(true, ["foo/\"\r\n,"],
63 "\"foo/\"\"\r\n,\"\r\n",
64 "/foo//\"\r\n,/#")
65
66 fun test_optimize_size_escaped do expect(false, ["foo/\"\r\n,"],
67 "\"foo/\"\"\r\n,\"\r\n",
68 "/foo//\"\r\n,/#")
69
70 fun test_optimize_size_eol do expect(false, ["foo\r#\n"],
71 "\"foo\r#\n\"\r\n",
72 "/foo\r#\n/#")
73
74 fun test_optimize_size_unescaped do expect(false, ["foo"],
75 "foo\r\n",
76 "foo#")
77
78 fun test_multiple_cells do expect(true, ["1", "", "/"],
79 "\"1\",,\"/\"\r\n",
80 "/1/::////#")
81
82 fun test_multiple_cells_optimize_size do expect(false, ["1", "", "/"],
83 "1,,/\r\n",
84 "1::////#")
85 end