csv-validation 0.0.3__tar.gz → 0.0.5__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {csv_validation-0.0.3 → csv_validation-0.0.5}/Cargo.lock +1 -1
- {csv_validation-0.0.3 → csv_validation-0.0.5}/Cargo.toml +1 -1
- {csv_validation-0.0.3 → csv_validation-0.0.5}/PKG-INFO +1 -1
- csv_validation-0.0.5/src/lib.rs +335 -0
- csv_validation-0.0.5/test/test_file.csv +5 -0
- csv_validation-0.0.3/src/lib.rs +0 -203
- csv_validation-0.0.3/test/test_file.csv +0 -5
- csv_validation-0.0.3/test/test_validations_wrong_headers.yml +0 -5
- {csv_validation-0.0.3 → csv_validation-0.0.5}/.github/workflows/CI.yml +0 -0
- {csv_validation-0.0.3 → csv_validation-0.0.5}/.gitignore +0 -0
- {csv_validation-0.0.3 → csv_validation-0.0.5}/build.sh +0 -0
- {csv_validation-0.0.3 → csv_validation-0.0.5}/pyproject.toml +0 -0
- {csv_validation-0.0.3 → csv_validation-0.0.5}/test/test_file.csv.gz +0 -0
- {csv_validation-0.0.3 → csv_validation-0.0.5}/test/test_validations.yml +0 -0
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
use crate::Validation::Values;
|
|
2
|
+
use std::collections::{HashMap, HashSet};
|
|
3
|
+
use std::fs;
|
|
4
|
+
use std::fs::File;
|
|
5
|
+
use std::io::{BufReader, Read};
|
|
6
|
+
use std::iter::zip;
|
|
7
|
+
use std::path::Path;
|
|
8
|
+
use csv::Reader;
|
|
9
|
+
use flate2::bufread::GzDecoder;
|
|
10
|
+
use log::{debug, error, info};
|
|
11
|
+
use pyo3::prelude::*;
|
|
12
|
+
use regex::Regex;
|
|
13
|
+
use yaml_rust2::YamlLoader;
|
|
14
|
+
use crate::Validation::{RegularExpression};
|
|
15
|
+
|
|
16
|
+
const MAX_SAMPLE_SIZE:u16 = 10;
|
|
17
|
+
|
|
18
|
+
#[derive(Debug, Clone)]
|
|
19
|
+
enum Validation {
|
|
20
|
+
RegularExpression(String),
|
|
21
|
+
Min(f64),
|
|
22
|
+
Max(f64),
|
|
23
|
+
Values(Vec<String>),
|
|
24
|
+
None
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
struct ColumnValidations {
|
|
28
|
+
column_name: String,
|
|
29
|
+
validations: Vec<Validation>
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
struct ValidationSummary {
|
|
33
|
+
validation: Validation,
|
|
34
|
+
wrong_rows: usize,
|
|
35
|
+
wrong_values_sample: Vec<String>
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
struct ColumnValidationsSummary {
|
|
39
|
+
column_name: String,
|
|
40
|
+
validation_summaries: Vec<ValidationSummary>
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
#[pyfunction]
|
|
44
|
+
fn validate_with_file(path: &str, definition_path: &str) -> PyResult<bool> {
|
|
45
|
+
info!("Validating file {} against definition file {}", path, definition_path);
|
|
46
|
+
let definition_string = fs::read_to_string(definition_path).unwrap();
|
|
47
|
+
validate(path, definition_string)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/// Validate that CSV file complies with a validations definition file
|
|
51
|
+
#[pyfunction]
|
|
52
|
+
fn validate(path: &str, definition_string: String) -> PyResult<bool> {
|
|
53
|
+
debug!("Validating file {} against definition:\n {}", path, definition_string);
|
|
54
|
+
let validations = get_validations(definition_string.as_str());
|
|
55
|
+
|
|
56
|
+
// Pre-Compile and save all Regex expressions to save time in execution
|
|
57
|
+
let mut regex_map = HashMap::new();
|
|
58
|
+
for column_validation in &validations {
|
|
59
|
+
for validation in &column_validation.validations {
|
|
60
|
+
match validation {
|
|
61
|
+
RegularExpression(regex) => {
|
|
62
|
+
regex_map.insert(regex.to_string(), Regex::new(regex.as_str()).unwrap());
|
|
63
|
+
},
|
|
64
|
+
Values(values) => {
|
|
65
|
+
let regex_str = get_regex_string_for_values(values);
|
|
66
|
+
regex_map.insert(regex_str.clone(), Regex::new(regex_str.as_str()).unwrap());
|
|
67
|
+
},
|
|
68
|
+
_ => continue
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Build the CSV reader
|
|
74
|
+
let mut rdr = get_reader_from(path);
|
|
75
|
+
|
|
76
|
+
// First validation: Ensure column names and order are exactly as expected
|
|
77
|
+
if validate_column_names(&mut rdr, &validations) {
|
|
78
|
+
info!("Columns names and order are correct");
|
|
79
|
+
}
|
|
80
|
+
else {
|
|
81
|
+
error!("Expected columns != Real columns");
|
|
82
|
+
return Ok(false);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Second validation: If column names match, check if also the values match the validations
|
|
86
|
+
let mut validation_summaries_map = build_validation_summaries_map(&validations);
|
|
87
|
+
let mut is_valid_file = true;
|
|
88
|
+
for result in rdr.records() {
|
|
89
|
+
let record = result.unwrap();
|
|
90
|
+
for next_column in zip(record.iter(), validations.iter()) {
|
|
91
|
+
let value = next_column.0;
|
|
92
|
+
let _column_name = &next_column.1.column_name;
|
|
93
|
+
for validation in &next_column.1.validations {
|
|
94
|
+
let valid = apply_validation(value, validation, ®ex_map);
|
|
95
|
+
if !valid {
|
|
96
|
+
let validation_summary_list = validation_summaries_map.get_mut(_column_name).unwrap();
|
|
97
|
+
let validation_summary = validation_summary_list
|
|
98
|
+
.iter_mut()
|
|
99
|
+
.find(|val_sum|
|
|
100
|
+
std::mem::discriminant(&val_sum.validation) == std::mem::discriminant(validation)).unwrap();
|
|
101
|
+
validation_summary.wrong_rows += 1;
|
|
102
|
+
if validation_summary.wrong_values_sample.len() < MAX_SAMPLE_SIZE as usize {
|
|
103
|
+
validation_summary.wrong_values_sample.push(value.to_string());
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
is_valid_file = is_valid_file && valid;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Fill the ColumnValidationSummary for each column
|
|
112
|
+
let mut column_validation_summaries = Vec::new();
|
|
113
|
+
for column_validation in &validations {
|
|
114
|
+
let validation_summary_for_column =
|
|
115
|
+
validation_summaries_map.remove(&column_validation.column_name).unwrap();
|
|
116
|
+
let column_validation_summary = ColumnValidationsSummary {
|
|
117
|
+
column_name: column_validation.column_name.clone(),
|
|
118
|
+
validation_summaries: validation_summary_for_column
|
|
119
|
+
};
|
|
120
|
+
column_validation_summaries.push(column_validation_summary);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
debug!("VALIDATIONS SUMMARY");
|
|
124
|
+
debug!("==================================================================================");
|
|
125
|
+
for column_validation_summary in column_validation_summaries {
|
|
126
|
+
debug!("Column: '{}'", column_validation_summary.column_name);
|
|
127
|
+
for validation_summary in column_validation_summary.validation_summaries {
|
|
128
|
+
debug!("\tValidation {:?} => Wrong Rows: {} | Wrong Values Sample: {:?}", &validation_summary.validation,
|
|
129
|
+
&validation_summary.wrong_rows, &validation_summary.wrong_values_sample);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if is_valid_file {
|
|
134
|
+
info!("OK: File matches the validations");
|
|
135
|
+
}
|
|
136
|
+
else {
|
|
137
|
+
info!("NO OK: File DOESN'T match validations");
|
|
138
|
+
}
|
|
139
|
+
Ok(is_valid_file)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
fn build_validation_summaries_map(validations: &Vec<ColumnValidations>) -> HashMap<String, Vec<ValidationSummary>> {
|
|
143
|
+
let mut validation_summaries_map = HashMap::new();
|
|
144
|
+
for validation in validations {
|
|
145
|
+
let mut validation_summaries = Vec::new();
|
|
146
|
+
for column_validation in &validation.validations {
|
|
147
|
+
let validation_summary =
|
|
148
|
+
ValidationSummary{validation: (*column_validation).clone(), wrong_rows: 0, wrong_values_sample: Vec::new()};
|
|
149
|
+
validation_summaries.push(validation_summary);
|
|
150
|
+
}
|
|
151
|
+
validation_summaries_map.insert(validation.column_name.clone(), validation_summaries);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
validation_summaries_map
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
fn apply_validation(value: &str, validation: &Validation, regex_map: &HashMap<String, Regex>) -> bool {
|
|
158
|
+
match validation {
|
|
159
|
+
RegularExpression(regex) => {
|
|
160
|
+
let regex = regex_map.get(regex).unwrap();
|
|
161
|
+
regex.is_match(value)
|
|
162
|
+
},
|
|
163
|
+
Validation::Min(min) => {
|
|
164
|
+
match value.parse::<f64>() {
|
|
165
|
+
Ok(value) => value >= *min,
|
|
166
|
+
Err(_) => false
|
|
167
|
+
}
|
|
168
|
+
},
|
|
169
|
+
Validation::Max(max) => {
|
|
170
|
+
match value.parse::<f64>() {
|
|
171
|
+
Ok(value) => value <= *max,
|
|
172
|
+
Err(_) => false
|
|
173
|
+
}
|
|
174
|
+
},
|
|
175
|
+
Validation::Values(values) => {
|
|
176
|
+
let regex_str = get_regex_string_for_values(values);
|
|
177
|
+
let regex = regex_map.get(®ex_str).unwrap();
|
|
178
|
+
regex.is_match(value)
|
|
179
|
+
}
|
|
180
|
+
Validation::None => panic!("Validation of type 'None' cannot be applied")
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
fn get_regex_string_for_values(values: &Vec<String>) -> String {
|
|
185
|
+
values.join("|")
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/// Infers the file compression type and returns the corresponding buffered reader
|
|
189
|
+
fn get_reader_from(path: &str) -> Reader<Box<dyn Read>> {
|
|
190
|
+
let buf_reader = BufReader::new(File::open(Path::new(path)).unwrap());
|
|
191
|
+
if is_gzip_file(path) {
|
|
192
|
+
debug!("File is gzipped");
|
|
193
|
+
let read_capacity = 10 * 1024_usize.pow(2);
|
|
194
|
+
let reader = BufReader::with_capacity(read_capacity, GzDecoder::new(buf_reader));
|
|
195
|
+
Reader::from_reader(Box::new(reader))
|
|
196
|
+
}
|
|
197
|
+
else {
|
|
198
|
+
Reader::from_reader(Box::new(buf_reader))
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
fn is_gzip_file(path: &str) -> bool {
|
|
203
|
+
let mut bytes = [0u8; 2];
|
|
204
|
+
File::open(Path::new(path)).unwrap().read_exact(&mut bytes).unwrap();
|
|
205
|
+
bytes[0] == 0x1f && bytes[1] == 0x8b
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
fn get_validations(definition_string: &str) -> Vec<ColumnValidations> {
|
|
209
|
+
// Read the YAML definition with the validations
|
|
210
|
+
let config = YamlLoader::load_from_str(definition_string).unwrap();
|
|
211
|
+
// Get the column names list and each associated validation
|
|
212
|
+
let columns = &config[0]["columns"];
|
|
213
|
+
let mut column_names = vec![];
|
|
214
|
+
let mut column_validations = vec![];
|
|
215
|
+
for column in columns.as_vec().unwrap() {
|
|
216
|
+
let column_def = column.as_hash().unwrap();
|
|
217
|
+
let mut name = "";
|
|
218
|
+
let mut validations = vec![];
|
|
219
|
+
for validation_definition in column_def.iter() {
|
|
220
|
+
let key = validation_definition.0.as_str().unwrap();
|
|
221
|
+
let value = validation_definition.1;
|
|
222
|
+
let mut validation: Validation = Validation::None;
|
|
223
|
+
match key {
|
|
224
|
+
"name" => { name = value.as_str().unwrap(); column_names.push(name); }
|
|
225
|
+
"regex" => { validation = Validation::RegularExpression(String::from(value.as_str().unwrap())); }
|
|
226
|
+
"min" => { validation = Validation::Min(value.as_i64().unwrap() as f64); }
|
|
227
|
+
"max" => { validation = Validation::Max(value.as_i64().unwrap() as f64); }
|
|
228
|
+
"values" => {
|
|
229
|
+
validation = Validation::Values(value.as_vec().unwrap()
|
|
230
|
+
.iter()
|
|
231
|
+
.map(|v| String::from(v.as_str().unwrap()))
|
|
232
|
+
.collect()
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
_ => panic!("Unknown validation: {key}")
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
if key != "name" {
|
|
239
|
+
validations.push(validation);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
}
|
|
243
|
+
let new_validations = ColumnValidations { column_name: name.to_string(), validations: validations };
|
|
244
|
+
column_validations.push(new_validations);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
column_validations
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
fn validate_column_names(reader: &mut Reader<Box<dyn Read>>, validations: &Vec<ColumnValidations>) -> bool {
|
|
251
|
+
let expected_column_names = validations.iter()
|
|
252
|
+
.map(|v| v.column_name.clone())
|
|
253
|
+
.collect::<Vec<String>>();
|
|
254
|
+
debug!("Expected Column Names: {:?}", expected_column_names);
|
|
255
|
+
|
|
256
|
+
let headers: Vec<String> = reader.headers().unwrap().iter().map(|s| String::from(s) ).collect();
|
|
257
|
+
debug!("Actual Column Names: {:?}", headers);
|
|
258
|
+
|
|
259
|
+
if expected_column_names != headers {
|
|
260
|
+
if expected_column_names.len() != headers.len() {
|
|
261
|
+
let expected_columns_set: HashSet<String> = expected_column_names.iter().cloned().collect();
|
|
262
|
+
let headers_set: HashSet<String> = headers.iter().cloned().collect();
|
|
263
|
+
debug!("File headers not in expected columns: {:?}", headers_set.difference(&expected_columns_set));
|
|
264
|
+
debug!("Columns in expected columns not in file headers: {:?}", expected_columns_set.difference(&headers_set));
|
|
265
|
+
}
|
|
266
|
+
else {
|
|
267
|
+
for (expected_column, header) in zip(expected_column_names, headers) {
|
|
268
|
+
if expected_column != header {
|
|
269
|
+
debug!("{:?} != {:?}", expected_column, header);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return false
|
|
274
|
+
}
|
|
275
|
+
true
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/// A Python module implemented in Rust.
|
|
279
|
+
#[pymodule]
|
|
280
|
+
fn csv_validation(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
|
281
|
+
pyo3_log::init();
|
|
282
|
+
m.add_function(wrap_pyfunction!(validate, m)?)?;
|
|
283
|
+
m.add_function(wrap_pyfunction!(validate_with_file, m)?)?;
|
|
284
|
+
Ok(())
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
#[cfg(test)]
|
|
288
|
+
mod tests {
|
|
289
|
+
use simple_logger::SimpleLogger;
|
|
290
|
+
use crate::{validate, validate_with_file};
|
|
291
|
+
|
|
292
|
+
#[test]
|
|
293
|
+
fn init_logger() {
|
|
294
|
+
SimpleLogger::new().init().unwrap();
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
#[test]
|
|
298
|
+
fn test_validate_csv_with_file() {
|
|
299
|
+
assert!(validate_with_file("test/test_file.csv", "test/test_validations.yml").unwrap());
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
#[test]
|
|
303
|
+
fn test_validate_csv_gz_with_file() {
|
|
304
|
+
assert!(validate_with_file("test/test_file.csv.gz", "test/test_validations.yml").unwrap());
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
#[test]
|
|
308
|
+
fn test_wrong_headers() {
|
|
309
|
+
let definition = String::from("
|
|
310
|
+
columns:
|
|
311
|
+
- name: First Column
|
|
312
|
+
- name: Second Column
|
|
313
|
+
- name: Wrong Column
|
|
314
|
+
- name: Expected Column Not In File
|
|
315
|
+
");
|
|
316
|
+
assert!(!validate("test/test_file.csv", definition).unwrap());
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
#[test]
|
|
320
|
+
fn test_validate_csv() {
|
|
321
|
+
let definition = String::from("
|
|
322
|
+
columns:
|
|
323
|
+
- name: First Column
|
|
324
|
+
regex: ^.+$
|
|
325
|
+
- name: Second Column
|
|
326
|
+
values: [one_value, or_another]
|
|
327
|
+
- name: Third Column
|
|
328
|
+
regex: ^-?[0-9]+$
|
|
329
|
+
min: -23
|
|
330
|
+
max: 2000
|
|
331
|
+
");
|
|
332
|
+
|
|
333
|
+
assert!(validate("test/test_file.csv", definition).unwrap());
|
|
334
|
+
}
|
|
335
|
+
}
|
csv_validation-0.0.3/src/lib.rs
DELETED
|
@@ -1,203 +0,0 @@
|
|
|
1
|
-
use std::collections::HashSet;
|
|
2
|
-
use std::fs;
|
|
3
|
-
use std::fs::File;
|
|
4
|
-
use std::io::{BufReader, Read};
|
|
5
|
-
use std::iter::zip;
|
|
6
|
-
use std::path::Path;
|
|
7
|
-
use csv::Reader;
|
|
8
|
-
use flate2::bufread::GzDecoder;
|
|
9
|
-
use log::{debug, error, info};
|
|
10
|
-
use pyo3::prelude::*;
|
|
11
|
-
use regex::Regex;
|
|
12
|
-
use yaml_rust2::YamlLoader;
|
|
13
|
-
use crate::Validation::{RegularExpression};
|
|
14
|
-
|
|
15
|
-
#[derive(Debug)]
|
|
16
|
-
enum Validation {
|
|
17
|
-
RegularExpression(Regex),
|
|
18
|
-
Min(f64),
|
|
19
|
-
Max(f64),
|
|
20
|
-
None
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
struct ColumnValidations {
|
|
24
|
-
column_name: String,
|
|
25
|
-
validations: Vec<Validation>
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
/// Validate that CSV file complies with validations definition
|
|
29
|
-
#[pyfunction]
|
|
30
|
-
fn validate(path: &str, definition_path: &str) -> PyResult<bool> {
|
|
31
|
-
info!("Validating file {} against definition {}", path, definition_path);
|
|
32
|
-
|
|
33
|
-
let validations = get_validations(definition_path);
|
|
34
|
-
|
|
35
|
-
// Build the CSV reader
|
|
36
|
-
let mut rdr = get_reader_from(path);
|
|
37
|
-
|
|
38
|
-
// First validation: Ensure column names and order are exactly as expected
|
|
39
|
-
if validate_column_names(&mut rdr, &validations) {
|
|
40
|
-
info!("Columns names and order are correct");
|
|
41
|
-
}
|
|
42
|
-
else {
|
|
43
|
-
error!("Expected columns != Real columns");
|
|
44
|
-
return Ok(false);
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
let mut is_valid_file = true;
|
|
48
|
-
for result in rdr.records() {
|
|
49
|
-
let record = result.unwrap();
|
|
50
|
-
for next_column in zip(record.iter(), validations.iter()) {
|
|
51
|
-
let value = next_column.0;
|
|
52
|
-
let _column_name = &next_column.1.column_name;
|
|
53
|
-
for validation in &next_column.1.validations {
|
|
54
|
-
let valid = apply_validation(value, validation);
|
|
55
|
-
if !valid {
|
|
56
|
-
debug!("Column {}: Value {} isn't valid for {:?}",
|
|
57
|
-
_column_name, value, validation);
|
|
58
|
-
}
|
|
59
|
-
is_valid_file = is_valid_file && valid;
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
info!("File matches the validations");
|
|
65
|
-
Ok(is_valid_file)
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
fn apply_validation(value: &str, validation: &Validation) -> bool {
|
|
69
|
-
match validation {
|
|
70
|
-
RegularExpression(regex) => regex.is_match(value),
|
|
71
|
-
Validation::Min(min) => {
|
|
72
|
-
match value.parse::<f64>() {
|
|
73
|
-
Ok(value) => value >= *min,
|
|
74
|
-
Err(_) => false
|
|
75
|
-
}
|
|
76
|
-
},
|
|
77
|
-
Validation::Max(max) => {
|
|
78
|
-
match value.parse::<f64>() {
|
|
79
|
-
Ok(value) => value <= *max,
|
|
80
|
-
Err(_) => false
|
|
81
|
-
}
|
|
82
|
-
},
|
|
83
|
-
Validation::None => panic!("None validation cannot be applied")
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/// Infers the file compression type and returns the corresponding buffered reader
|
|
88
|
-
fn get_reader_from(path: &str) -> Reader<Box<dyn Read>> {
|
|
89
|
-
let buf_reader = BufReader::new(File::open(Path::new(path)).unwrap());
|
|
90
|
-
if is_gzip_file(path) {
|
|
91
|
-
debug!("File is gzipped");
|
|
92
|
-
let read_capacity = 10 * 1024_usize.pow(2);
|
|
93
|
-
let reader = BufReader::with_capacity(read_capacity, GzDecoder::new(buf_reader));
|
|
94
|
-
Reader::from_reader(Box::new(reader))
|
|
95
|
-
}
|
|
96
|
-
else {
|
|
97
|
-
Reader::from_reader(Box::new(buf_reader))
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
fn is_gzip_file(path: &str) -> bool {
|
|
102
|
-
let mut bytes = [0u8; 2];
|
|
103
|
-
File::open(Path::new(path)).unwrap().read_exact(&mut bytes).unwrap();
|
|
104
|
-
bytes[0] == 0x1f && bytes[1] == 0x8b
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
fn get_validations(definition_path: &str) -> Vec<ColumnValidations> {
|
|
108
|
-
// Read the YAML definition with the validations
|
|
109
|
-
let config =
|
|
110
|
-
YamlLoader::load_from_str(fs::read_to_string(definition_path).unwrap().as_str()).unwrap();
|
|
111
|
-
// Get the column names list and each associated validation
|
|
112
|
-
let columns = &config[0]["columns"];
|
|
113
|
-
let mut column_names = vec![];
|
|
114
|
-
let mut column_validations = vec![];
|
|
115
|
-
for column in columns.as_vec().unwrap() {
|
|
116
|
-
let column_def = column.as_hash().unwrap();
|
|
117
|
-
let mut name = "";
|
|
118
|
-
let mut validations = vec![];
|
|
119
|
-
for validation_definition in column_def.iter() {
|
|
120
|
-
let key = validation_definition.0.as_str().unwrap();
|
|
121
|
-
let value = validation_definition.1;
|
|
122
|
-
let mut validation: Validation = Validation::None;
|
|
123
|
-
match key {
|
|
124
|
-
"name" => { name = value.as_str().unwrap(); column_names.push(name); }
|
|
125
|
-
"regex" => { validation = Validation::RegularExpression(Regex::new(&value.as_str().unwrap()).unwrap()); }
|
|
126
|
-
"min" => { validation = Validation::Min(value.as_i64().unwrap() as f64); }
|
|
127
|
-
"max" => { validation = Validation::Max(value.as_i64().unwrap() as f64); }
|
|
128
|
-
_ => panic!("Unknown validation: {key}")
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
if key != "name" {
|
|
132
|
-
validations.push(validation);
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
}
|
|
136
|
-
let new_validations = ColumnValidations { column_name: name.to_string(), validations: validations };
|
|
137
|
-
column_validations.push(new_validations);
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
column_validations
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
fn validate_column_names(reader: &mut Reader<Box<dyn Read>>, validations: &Vec<ColumnValidations>) -> bool {
|
|
144
|
-
let expected_column_names = validations.iter()
|
|
145
|
-
.map(|v| v.column_name.clone())
|
|
146
|
-
.collect::<Vec<String>>();
|
|
147
|
-
debug!("Expected Column Names: {:?}", expected_column_names);
|
|
148
|
-
|
|
149
|
-
let headers: Vec<String> = reader.headers().unwrap().iter().map(|s| String::from(s) ).collect();
|
|
150
|
-
debug!("Actual Column Names: {:?}", headers);
|
|
151
|
-
|
|
152
|
-
if expected_column_names != headers {
|
|
153
|
-
if expected_column_names.len() != headers.len() {
|
|
154
|
-
let expected_columns_set: HashSet<String> = expected_column_names.iter().cloned().collect();
|
|
155
|
-
let headers_set: HashSet<String> = headers.iter().cloned().collect();
|
|
156
|
-
debug!("File headers not in expected columns: {:?}", headers_set.difference(&expected_columns_set));
|
|
157
|
-
debug!("Columns in expected columns not in file headers: {:?}", expected_columns_set.difference(&headers_set));
|
|
158
|
-
}
|
|
159
|
-
else {
|
|
160
|
-
for (expected_column, header) in zip(expected_column_names, headers) {
|
|
161
|
-
if expected_column != header {
|
|
162
|
-
debug!("{:?} != {:?}", expected_column, header);
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
return false
|
|
167
|
-
}
|
|
168
|
-
true
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
/// A Python module implemented in Rust.
|
|
172
|
-
#[pymodule]
|
|
173
|
-
fn csv_validation(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
|
174
|
-
pyo3_log::init();
|
|
175
|
-
m.add_function(wrap_pyfunction!(validate, m)?)?;
|
|
176
|
-
Ok(())
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
#[cfg(test)]
|
|
180
|
-
mod tests {
|
|
181
|
-
use simple_logger::SimpleLogger;
|
|
182
|
-
use crate::validate;
|
|
183
|
-
|
|
184
|
-
#[test]
|
|
185
|
-
fn init_logger() {
|
|
186
|
-
SimpleLogger::new().init().unwrap();
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
#[test]
|
|
190
|
-
fn test_validate_csv() {
|
|
191
|
-
assert!(validate("test/test_file.csv", "test/test_validations.yml").unwrap());
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
#[test]
|
|
195
|
-
fn test_validate_csv_gz() {
|
|
196
|
-
assert!(validate("test/test_file.csv.gz", "test/test_validations.yml").unwrap());
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
#[test]
|
|
200
|
-
fn test_wrong_headers() {
|
|
201
|
-
assert!(!validate("test/test_file.csv", "test/test_validations_wrong_headers.yml").unwrap());
|
|
202
|
-
}
|
|
203
|
-
}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|