File: test_reader.py

package info (click to toggle)
python-clevercsv 0.8.3%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,076 kB
  • sloc: python: 6,184; ansic: 870; makefile: 90
file content (222 lines) | stat: -rw-r--r-- 7,397 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# -*- coding: utf-8 -*-

"""
Unit tests for the CSV reader.

Author: Gertjan van den Burg

"""

import csv
import json
import unittest

from io import StringIO

from typing import Any
from typing import Iterable
from typing import Iterator
from typing import List

import clevercsv


class ReaderTestCase(unittest.TestCase):
    def _read_test(
        self, input: Iterable[str], expect: List[List[str]], **kwargs: Any
    ) -> None:
        reader = clevercsv.reader(input, **kwargs)
        result = list(reader)
        self.assertEqual(result, expect)

    def test_read_oddinputs(self) -> None:
        self._read_test([], [])
        self._read_test([""], [[]])
        self.assertRaises(
            clevercsv.Error, self._read_test, ['"ab"c'], None, strict=1
        )
        self.assertRaises(
            clevercsv.Error, self._read_test, ["ab\0c"], None, strict=1
        )
        # This commented test doesn't make sense for us, because we assert that
        # a field is only a quoted field if it begins *and* ends with a quote
        # character (except for the last field of a file, which only needs to
        # end in a quotechar if we're not strict).
        # self._read_test(['"ab"c'], [["abc"]], doublequote=0)
        self.assertRaises(clevercsv.Error, self._read_test, [b"ab\0c"], None)

    def test_read_eol(self) -> None:
        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"]])
        # these tests from CPython don't apply for now.
        self.assertRaises(clevercsv.Error, self._read_test, ["a,b\rc,d"], [])
        self.assertRaises(clevercsv.Error, self._read_test, ["a,b\rc,d"], [])
        self.assertRaises(clevercsv.Error, self._read_test, ["a,b\rc,d"], [])

    def test_read_eof(self) -> None:
        self._read_test(['a,"'], [["a", ""]])
        self._read_test(['"a'], [["a"]])
        # we're not using escape characters in the same way.
        # self._read_test("^", [["\n"]], escapechar="^")

    def test_read_escape(self) -> None:
        # we don't drop the escapechar if it serves no purpose
        # so instead of this:
        # self._read_test("a,\\b,c", [["a", "b", "c"]], escapechar="\\")
        # we do this:
        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="\\")
        # the next test also differs from Python
        self._read_test(['a,"b,c"\\'], [["a", "b,c"]], escapechar="\\")

    def test_read_bigfield(self) -> None:
        limit = clevercsv.field_size_limit()
        try:
            size = 500
            bigstring = "X" * size
            bigline = "%s,%s" % (bigstring, bigstring)
            self._read_test([bigline], [[bigstring, bigstring]])
            clevercsv.field_size_limit(size)
            self._read_test([bigline], [[bigstring, bigstring]])
            self.assertEqual(clevercsv.field_size_limit(), size)
            clevercsv.field_size_limit(size=-1)
            self.assertRaises(clevercsv.Error, self._read_test, [bigline], [])
            self.assertRaises(TypeError, clevercsv.field_size_limit, None)
            self.assertRaises(TypeError, clevercsv.field_size_limit, 1, None)
        finally:
            clevercsv.field_size_limit(limit)

    def test_read_linenum(self) -> None:
        r = clevercsv.reader(["line,1", "line,2", "line,3"])
        self.assertEqual(r.line_num, 0)
        self.assertEqual(next(r), ["line", "1"])
        self.assertEqual(r.line_num, 1)
        self.assertEqual(next(r), ["line", "2"])
        self.assertEqual(r.line_num, 2)
        self.assertEqual(next(r), ["line", "3"])
        self.assertEqual(r.line_num, 3)
        self.assertRaises(StopIteration, next, r)
        self.assertEqual(r.line_num, 3)

    def test_with_gen(self) -> None:
        def gen(x: Iterable[str]) -> Iterator[str]:
            for line in x:
                yield line

        r = clevercsv.reader(gen(["line,1", "line,2", "line,3"]))
        self.assertEqual(next(r), ["line", "1"])
        self.assertEqual(next(r), ["line", "2"])
        self.assertEqual(next(r), ["line", "3"])

    def test_simple(self) -> None:
        self._read_test(
            ["A,B,C,D,E"],
            [["A", "B", "C", "D", "E"]],
            delimiter=",",
            quotechar='"',
        )
        self._read_test(
            ["A,B,C,D,E"],
            [["A", "B", "C", "D", "E"]],
            delimiter=",",
            quotechar="",
        )
        self._read_test(["A,B,C,D,E"], [["A,B,C,D,E"]], delimiter="")
        self._read_test(
            ['A,"B",C,D,E'],
            [["A", "B", "C", "D", "E"]],
            delimiter=",",
            quotechar='"',
        )
        self._read_test(
            ['A,"B,C",D,E'],
            [["A", "B,C", "D", "E"]],
            delimiter=",",
            quotechar='"',
        )
        self._read_test(
            ['A,"B,C",D,E'],
            [["A", '"B', 'C"', "D", "E"]],
            delimiter=",",
            quotechar="",
        )
        self._read_test(
            ['"A","B","C",,,,'],
            [['"A"', '"B"', '"C"', "", "", "", ""]],
            delimiter=",",
            quotechar="",
        )

    def test_no_delim(self) -> None:
        self._read_test(
            ['A"B"C', 'A"B""C""D"'],
            [['A"B"C'], ['A"B""C""D"']],
            delimiter="",
            quotechar="",
        )
        self._read_test(
            ['A"B\r\nB"C', 'D"E"F', "G"],
            [['A"B\r\nB"C'], ['D"E"F'], ["G"]],
            delimiter="",
            quotechar='"',
        )
        self._read_test(
            ['A"B\nB"C', 'D"E"F', "G"],
            [['A"B\nB"C'], ['D"E"F'], ["G"]],
            delimiter="",
            quotechar='"',
        )
        self._read_test(
            ['A"B\nB\rB"C', 'D"E"F', "G"],
            [['A"B\nB\rB"C'], ['D"E"F'], ["G"]],
            delimiter="",
            quotechar='"',
        )

    def test_github_issue_130(self) -> None:
        # fmt: off
        data = """sku,features,attributes
22221,"[{""key"":""heel_height"",""value"":""Ulttra High (4\\""+)""}]","11,room"
"""
        # fmt: on

        # NOTE we set the escapechar to None to correctly carry over the `\`
        # escape character
        rows_csv = list(
            csv.reader(
                StringIO(data), delimiter=",", quotechar='"', escapechar=None
            )
        )
        expected = [
            [
                "sku",
                "features",
                "attributes",
            ],
            [
                "22221",
                '[{"key":"heel_height","value":"Ulttra High (4\\"+)"}]',
                "11,room",
            ],
        ]
        self.assertSequenceEqual(expected, rows_csv)

        rows_clevercsv = list(
            clevercsv.reader(
                StringIO(data), delimiter=",", quotechar='"', escapechar=""
            )
        )
        self.assertSequenceEqual(expected, rows_clevercsv)

        # Ensure we can parse the JSON as intended.
        cell = json.loads(expected[1][1])
        self.assertEqual(
            cell, [{"key": "heel_height", "value": 'Ulttra High (4"+)'}]
        )


if __name__ == "__main__":
    unittest.main()