3
3
4
4
from dataclass_csv import DataclassReader , CsvValueError
5
5
6
- from .mocks import User , UserWithOptionalAge , DataclassWithBooleanValue , DataclassWithBooleanValueNoneDefault
6
+ from .mocks import (
7
+ User ,
8
+ UserWithOptionalAge ,
9
+ DataclassWithBooleanValue ,
10
+ DataclassWithBooleanValueNoneDefault ,
11
+ UserWithInitFalse ,
12
+ UserWithInitFalseAndDefaultValue ,
13
+ )
7
14
8
15
9
16
def test_reader_with_non_dataclass (create_csv ):
@@ -114,16 +121,12 @@ def test_parse_bool_value_false(create_csv):
114
121
def test_parse_bool_value_invalid (create_csv ):
115
122
csv_file = create_csv ({'boolValue' : 'notValidBoolean' })
116
123
with csv_file .open () as f :
117
- try :
124
+ with pytest . raises ( CsvValueError ) :
118
125
reader = DataclassReader (f , DataclassWithBooleanValue )
119
126
list (reader )
120
- assert False # Should not be able to successfully parse
121
- except CsvValueError :
122
- pass
123
127
124
128
125
129
def test_parse_bool_value_none_default (create_csv ):
126
- """Verify that blank/null values are parsed as None for optional fields"""
127
130
csv_file = create_csv ({'boolValue' : '' })
128
131
with csv_file .open () as f :
129
132
reader = DataclassReader (f , DataclassWithBooleanValueNoneDefault )
@@ -132,11 +135,35 @@ def test_parse_bool_value_none_default(create_csv):
132
135
assert dataclass_instance .boolValue is None
133
136
134
137
138
+ def test_skip_dataclass_field_when_init_is_false (create_csv ):
139
+ csv_file = create_csv ({'firstname' : 'User1' , 'lastname' : 'TestUser' })
140
+ with csv_file .open () as f :
141
+ reader = DataclassReader (f , UserWithInitFalse )
142
+ items = list (reader )
143
+
144
+
145
+ def test_try_to_access_not_initialized_prop_raise_attr_error (create_csv ):
146
+ csv_file = create_csv ({'firstname' : 'User1' , 'lastname' : 'TestUser' })
147
+ with csv_file .open () as f :
148
+ reader = DataclassReader (f , UserWithInitFalse )
149
+ items = list (reader )
150
+ with pytest .raises (AttributeError ):
151
+ user = items [0 ]
152
+ user_age = user .age
153
+
154
+
155
+ def test_try_to_access_not_initialized_prop_with_default_value (create_csv ):
156
+ csv_file = create_csv ({'firstname' : 'User1' , 'lastname' : 'TestUser' })
157
+ with csv_file .open () as f :
158
+ reader = DataclassReader (f , UserWithInitFalseAndDefaultValue )
159
+ items = list (reader )
160
+ user = items [0 ]
161
+ assert user .age == 0
162
+
163
+
135
164
def test_reader_with_optional_types (create_csv ):
136
165
csv_file = create_csv ({'name' : 'User' , 'age' : 40 })
137
166
138
167
with csv_file .open () as f :
139
168
reader = DataclassReader (f , UserWithOptionalAge )
140
169
list (reader )
141
-
142
-
0 commit comments