-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsv_test.py
More file actions
246 lines (205 loc) · 6.84 KB
/
csv_test.py
File metadata and controls
246 lines (205 loc) · 6.84 KB
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
"""The `csv` module."""
import csv
from datetime import datetime
from pathlib import Path
from typing import Dict, List, NamedTuple
def test_read_csv_default() -> None:
"""Read a CSV file in the default (Excel) dialect."""
csv_sample_path = Path(__file__).parent.joinpath("csv_sample1.csv")
with open(csv_sample_path, newline="") as csvfile:
csv_reader = csv.reader(csvfile)
csv_rows: List[List[str]] = list(csv_reader)
assert csv_rows == [
["Item Type", "Order Priority", "Order Date", "Order ID"],
["Office Supplies", "L", "5/2/2014", "1"],
["Cereal", "H", "4/18/2014", "2"],
]
def test_write_csv_default(tmp_path: Path) -> None:
"""Write a CSV file in the default (Excel) dialect.
Write all rows, then append a single row to an existing CSV file.
"""
csv_rows = [
["Item Type", "Order Priority", "Order Date", "Order ID"],
["Office Supplies", "L", "5/2/2014", "1"],
]
csv_row = ["Cereal", "H", "4/18/2014", "2"]
tmp_csv_path = tmp_path.joinpath("csv_sample.csv")
with open(tmp_csv_path, "w", newline="") as csvfile:
csv_writer = csv.writer(csvfile)
csv_writer.writerows(csv_rows)
with open(tmp_csv_path, "a", newline="") as csvfile:
csv_writer = csv.writer(csvfile)
csv_writer.writerow(csv_row)
with open(tmp_csv_path) as csv_sample:
data = csv_sample.read()
assert (
data
== """\
Item Type,Order Priority,Order Date,Order ID
Office Supplies,L,5/2/2014,1
Cereal,H,4/18/2014,2
"""
)
def test_read_csv_dict() -> None:
"""Read a CSV file into a `dict`."""
csv_sample_path = Path(__file__).parent.joinpath("csv_sample1.csv")
with open(csv_sample_path, newline="") as csvfile:
csv_reader = csv.DictReader(csvfile)
assert csv_reader.fieldnames == [
"Item Type",
"Order Priority",
"Order Date",
"Order ID",
]
csv_rows: List[Dict[str, str]] = list(csv_reader)
assert csv_rows == [
{
"Item Type": "Office Supplies",
"Order Priority": "L",
"Order Date": "5/2/2014",
"Order ID": "1",
},
{
"Item Type": "Cereal",
"Order Priority": "H",
"Order Date": "4/18/2014",
"Order ID": "2",
},
]
def test_write_csv_dict(tmp_path: Path) -> None:
"""Write a CSV file from a `dict`."""
fieldnames = [
"Item Type",
"Order Priority",
"Order Date",
"Order ID",
]
csv_rows = [
{
"Item Type": "Office Supplies",
"Order Priority": "L",
"Order Date": "5/2/2014",
"Order ID": "1",
},
{
"Item Type": "Cereal",
"Order Priority": "H",
"Order Date": "4/18/2014",
"Order ID": "2",
},
]
tmp_csv_path = tmp_path.joinpath("csv_sample.csv")
with open(tmp_csv_path, "w", newline="") as csvfile:
csv_writer = csv.DictWriter(csvfile, fieldnames)
csv_writer.writeheader()
csv_writer.writerows(csv_rows)
with open(tmp_csv_path) as csv_sample:
data = csv_sample.read()
assert (
data
== """\
Item Type,Order Priority,Order Date,Order ID
Office Supplies,L,5/2/2014,1
Cereal,H,4/18/2014,2
"""
)
def test_read_dialect() -> None:
"""Read a CSV file in the 'unixpasswd' dialect.
Uses a subclass of `Dialect`.
"""
class UnixPasswdDialect(csv.Dialect):
"""Dialect for Unix `passwd` files."""
# Specify all attributes because the `Dialect` class defaults all to None!
delimiter = ":"
quotechar = '"'
escapechar = None
doublequote = True
skipinitialspace = False
lineterminator = "\r\n"
quoting = csv.QUOTE_NONE
csv.register_dialect("unixpasswd", UnixPasswdDialect)
fieldnames = [
"Login Name",
"Encrypted Password",
"User ID",
"Group ID",
"User Name or Comment",
"Home Directory",
"Command Interpreter",
]
csv_passwd_path = Path(__file__).parent.joinpath("csv_passwd")
with open(csv_passwd_path, newline="") as passwd_file:
passwd_reader = csv.DictReader(
passwd_file, fieldnames=fieldnames, dialect="unixpasswd"
)
passwd_rows = list(passwd_reader)
csv.unregister_dialect("unixpasswd")
assert passwd_rows == [
{
"Login Name": "bin",
"Encrypted Password": "x",
"User ID": "2",
"Group ID": "2",
"User Name or Comment": "bin",
"Home Directory": "/bin",
"Command Interpreter": "/usr/sbin/nologin",
},
{
"Login Name": "hplip",
"Encrypted Password": "x",
"User ID": "117",
"Group ID": "7",
"User Name or Comment": "HPLIP system user,,,",
"Home Directory": "/var/run/hplip",
"Command Interpreter": "/bin/false",
},
]
def test_write_dialect(tmp_path: Path) -> None:
"""Write a CSV file in the 'unixpasswd' dialect."""
passwd_rows = [
["bin", "x", "2", "2", "bin", "/bin", "/usr/sbin/nologin"],
["hplip", "x", "117", "7", "HPLIP user,,,", "/var/run/hplip", "/bin/false",],
]
csv.register_dialect("unixpasswd", delimiter=":", quoting=csv.QUOTE_NONE)
tmp_passwd_path = tmp_path.joinpath("csv_passwd")
with open(tmp_passwd_path, "w", newline="") as passwd_file:
csv_writer = csv.writer(passwd_file, "unixpasswd")
csv_writer.writerows(passwd_rows)
csv.unregister_dialect("unixpasswd")
with open(tmp_passwd_path) as passwd_sample:
data = passwd_sample.read()
assert (
data
== """\
bin:x:2:2:bin:/bin:/usr/sbin/nologin
hplip:x:117:7:HPLIP user,,,:/var/run/hplip:/bin/false
"""
)
def test_read_csv_object() -> None:
"""Read a CSV file into named tuple objects."""
class Order(NamedTuple):
"""Represents a row in a CSV file."""
item_type: str
priority: str
date: datetime
id: int
csv_sample_path = Path(__file__).parent.joinpath("csv_sample1.csv")
with open(csv_sample_path, newline="") as csvfile:
csv_reader = csv.reader(csvfile)
next(csv_reader) # Skip header row
orders: List[Order] = [
Order(
item_type=row[0],
priority=row[1],
date=datetime.strptime(row[2], "%m/%d/%Y"),
id=int(row[3]),
)
for row in csv_reader
]
assert len(orders) == 2
assert orders[0] == Order(
item_type="Office Supplies", priority="L", date=datetime(2014, 5, 2), id=1
)
assert orders[1] == Order(
item_type="Cereal", priority="H", date=datetime(2014, 4, 18), id=2
)