csv-validation 0.0.4__tar.gz → 0.0.6__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.
@@ -83,7 +83,7 @@ dependencies = [
83
83
 
84
84
  [[package]]
85
85
  name = "csv_validation"
86
- version = "0.0.4"
86
+ version = "0.0.6"
87
87
  dependencies = [
88
88
  "csv",
89
89
  "flate2",
@@ -91,6 +91,8 @@ dependencies = [
91
91
  "pyo3",
92
92
  "pyo3-log",
93
93
  "regex",
94
+ "serde",
95
+ "serde_json",
94
96
  "simple_logger",
95
97
  "yaml-rust2",
96
98
  ]
@@ -387,6 +389,18 @@ dependencies = [
387
389
  "syn",
388
390
  ]
389
391
 
392
+ [[package]]
393
+ name = "serde_json"
394
+ version = "1.0.140"
395
+ source = "registry+https://github.com/rust-lang/crates.io-index"
396
+ checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373"
397
+ dependencies = [
398
+ "itoa",
399
+ "memchr",
400
+ "ryu",
401
+ "serde",
402
+ ]
403
+
390
404
  [[package]]
391
405
  name = "simple_logger"
392
406
  version = "5.0.0"
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "csv_validation"
3
- version = "0.0.4"
3
+ version = "0.0.6"
4
4
  edition = "2021"
5
5
 
6
6
  # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -15,5 +15,7 @@ log = "0.4.26"
15
15
  pyo3 = "0.23.3"
16
16
  pyo3-log = "0.12.1"
17
17
  regex = "1.11.1"
18
+ serde_json = "1.0.140"
18
19
  simple_logger = "5.0.0"
19
20
  yaml-rust2 = "0.10.0"
21
+ serde = { version = "1.0.218", features = ["derive"] }
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: csv_validation
3
- Version: 0.0.4
3
+ Version: 0.0.6
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Classifier: Programming Language :: Python :: Implementation :: PyPy
@@ -1,3 +1,4 @@
1
+ use crate::Validation::Values;
1
2
  use std::collections::{HashMap, HashSet};
2
3
  use std::fs;
3
4
  use std::fs::File;
@@ -7,18 +8,21 @@ use std::path::Path;
7
8
  use csv::Reader;
8
9
  use flate2::bufread::GzDecoder;
9
10
  use log::{debug, error, info};
11
+ use pyo3::exceptions::{PyRuntimeError};
10
12
  use pyo3::prelude::*;
11
13
  use regex::Regex;
12
14
  use yaml_rust2::YamlLoader;
15
+ use serde::{Deserialize, Serialize};
13
16
  use crate::Validation::{RegularExpression};
14
17
 
15
18
  const MAX_SAMPLE_SIZE:u16 = 10;
16
19
 
17
- #[derive(Debug, Clone)]
20
+ #[derive(Debug, Clone, Serialize, Deserialize)]
18
21
  enum Validation {
19
- RegularExpression(String),
22
+ RegularExpression { expression: String, alias: String },
20
23
  Min(f64),
21
24
  Max(f64),
25
+ Values(Vec<String>),
22
26
  None
23
27
  }
24
28
 
@@ -27,31 +31,43 @@ struct ColumnValidations {
27
31
  validations: Vec<Validation>
28
32
  }
29
33
 
34
+ #[derive(Serialize, Deserialize)]
30
35
  struct ValidationSummary {
31
36
  validation: Validation,
32
37
  wrong_rows: usize,
33
38
  wrong_values_sample: Vec<String>
34
39
  }
35
40
 
41
+ #[derive(Serialize, Deserialize)]
36
42
  struct ColumnValidationsSummary {
37
43
  column_name: String,
38
44
  validation_summaries: Vec<ValidationSummary>
39
45
  }
40
46
 
41
- /// Validate that CSV file complies with validations definition
42
47
  #[pyfunction]
43
- fn validate(path: &str, definition_path: &str) -> PyResult<bool> {
44
- info!("Validating file {} against definition {}", path, definition_path);
48
+ fn validate_with_file(path: &str, definition_path: &str) -> PyResult<bool> {
49
+ info!("Validating file {} against definition file {}", path, definition_path);
50
+ let definition_string = fs::read_to_string(definition_path)?;
51
+ validate(path, definition_string)
52
+ }
45
53
 
46
- let validations = get_validations(definition_path);
54
+ /// Validate that CSV file complies with a validations definition file
55
+ #[pyfunction]
56
+ fn validate(path: &str, definition_string: String) -> PyResult<bool> {
57
+ debug!("Validating file {} against definition:\n {}", path, definition_string);
58
+ let validations = get_validations(definition_string.as_str())?;
47
59
 
48
60
  // Pre-Compile and save all Regex expressions to save time in execution
49
61
  let mut regex_map = HashMap::new();
50
62
  for column_validation in &validations {
51
63
  for validation in &column_validation.validations {
52
64
  match validation {
53
- RegularExpression(regex) => {
54
- regex_map.insert(regex, Regex::new(regex.as_str()).unwrap());
65
+ RegularExpression { expression, alias: _ } => {
66
+ regex_map.insert(expression.to_string(), Regex::new(expression.as_str()).unwrap());
67
+ },
68
+ Values(values) => {
69
+ let regex_str = get_regex_string_for_values(values);
70
+ regex_map.insert(regex_str.clone(), Regex::new(regex_str.as_str()).unwrap());
55
71
  },
56
72
  _ => continue
57
73
  }
@@ -59,10 +75,10 @@ fn validate(path: &str, definition_path: &str) -> PyResult<bool> {
59
75
  }
60
76
 
61
77
  // Build the CSV reader
62
- let mut rdr = get_reader_from(path);
78
+ let mut rdr = get_reader_from(path)?;
63
79
 
64
80
  // First validation: Ensure column names and order are exactly as expected
65
- if validate_column_names(&mut rdr, &validations) {
81
+ if validate_column_names(&mut rdr, &validations)? {
66
82
  info!("Columns names and order are correct");
67
83
  }
68
84
  else {
@@ -79,7 +95,7 @@ fn validate(path: &str, definition_path: &str) -> PyResult<bool> {
79
95
  let value = next_column.0;
80
96
  let _column_name = &next_column.1.column_name;
81
97
  for validation in &next_column.1.validations {
82
- let valid = apply_validation(value, validation, &regex_map);
98
+ let valid = apply_validation(value, validation, &regex_map)?;
83
99
  if !valid {
84
100
  let validation_summary_list = validation_summaries_map.get_mut(_column_name).unwrap();
85
101
  let validation_summary = validation_summary_list
@@ -108,13 +124,20 @@ fn validate(path: &str, definition_path: &str) -> PyResult<bool> {
108
124
  column_validation_summaries.push(column_validation_summary);
109
125
  }
110
126
 
127
+ let validation_result_json = serde_json::to_string(&column_validation_summaries).unwrap();
128
+
111
129
  debug!("VALIDATIONS SUMMARY");
112
130
  debug!("==================================================================================");
113
131
  for column_validation_summary in column_validation_summaries {
114
132
  debug!("Column: '{}'", column_validation_summary.column_name);
115
133
  for validation_summary in column_validation_summary.validation_summaries {
116
- debug!("\tValidation {:?} => Wrong Rows: {} | Wrong Values Sample: {:?}", &validation_summary.validation,
117
- &validation_summary.wrong_rows, &validation_summary.wrong_values_sample);
134
+ let wrong_values_sample = if validation_summary.wrong_values_sample.len() > 0 {
135
+ format!(" | Wrong Values Sample: {:?}", validation_summary.wrong_values_sample)
136
+ } else {
137
+ String::from("" )
138
+ };
139
+ debug!("\tValidation {:?} => Wrong Rows: {}{}", validation_summary.validation,
140
+ validation_summary.wrong_rows, wrong_values_sample);
118
141
  }
119
142
  }
120
143
 
@@ -142,85 +165,116 @@ fn build_validation_summaries_map(validations: &Vec<ColumnValidations>) -> HashM
142
165
  validation_summaries_map
143
166
  }
144
167
 
145
- fn apply_validation(value: &str, validation: &Validation, regex_map: &HashMap<&String, Regex>) -> bool {
168
+ fn apply_validation(value: &str, validation: &Validation, regex_map: &HashMap<String, Regex>) -> PyResult<bool> {
146
169
  match validation {
147
- RegularExpression(regex) => {
148
- let regex = regex_map.get(regex).unwrap();
149
- regex.is_match(value)
170
+ RegularExpression { expression: exp, alias: _ } => {
171
+ let regex = regex_map.get(exp).unwrap();
172
+ Ok(regex.is_match(value))
150
173
  },
151
174
  Validation::Min(min) => {
152
175
  match value.parse::<f64>() {
153
- Ok(value) => value >= *min,
154
- Err(_) => false
176
+ Ok(value) => Ok(value >= *min),
177
+ Err(_) => Ok(false)
155
178
  }
156
179
  },
157
180
  Validation::Max(max) => {
158
181
  match value.parse::<f64>() {
159
- Ok(value) => value <= *max,
160
- Err(_) => false
182
+ Ok(value) => Ok(value <= *max),
183
+ Err(_) => Ok(false)
161
184
  }
162
185
  },
163
- Validation::None => panic!("None validation cannot be applied")
186
+ Validation::Values(values) => {
187
+ let regex_str = get_regex_string_for_values(values);
188
+ let regex = regex_map.get(&regex_str).unwrap();
189
+ Ok(regex.is_match(value))
190
+ }
191
+ Validation::None => Err(PyRuntimeError::new_err("'None' validation has no implementation"))
164
192
  }
165
193
  }
166
194
 
195
+ fn get_regex_string_for_values(values: &Vec<String>) -> String {
196
+ values.join("|")
197
+ }
198
+
167
199
  /// Infers the file compression type and returns the corresponding buffered reader
168
- fn get_reader_from(path: &str) -> Reader<Box<dyn Read>> {
169
- let buf_reader = BufReader::new(File::open(Path::new(path)).unwrap());
170
- if is_gzip_file(path) {
200
+ fn get_reader_from(path: &str) -> PyResult<Reader<Box<dyn Read>>> {
201
+ let buf_reader = BufReader::new(File::open(Path::new(path))?);
202
+ if is_gzip_file(path)? {
171
203
  debug!("File is gzipped");
172
204
  let read_capacity = 10 * 1024_usize.pow(2);
173
205
  let reader = BufReader::with_capacity(read_capacity, GzDecoder::new(buf_reader));
174
- Reader::from_reader(Box::new(reader))
206
+ Ok(Reader::from_reader(Box::new(reader)))
175
207
  }
176
208
  else {
177
- Reader::from_reader(Box::new(buf_reader))
209
+ Ok(Reader::from_reader(Box::new(buf_reader)))
178
210
  }
179
211
  }
180
212
 
181
- fn is_gzip_file(path: &str) -> bool {
213
+ fn is_gzip_file(path: &str) -> PyResult<bool> {
182
214
  let mut bytes = [0u8; 2];
183
- File::open(Path::new(path)).unwrap().read_exact(&mut bytes).unwrap();
184
- bytes[0] == 0x1f && bytes[1] == 0x8b
215
+ File::open(Path::new(path))?.read_exact(&mut bytes)?;
216
+ Ok(bytes[0] == 0x1f && bytes[1] == 0x8b)
185
217
  }
186
218
 
187
- fn get_validations(definition_path: &str) -> Vec<ColumnValidations> {
219
+ fn get_validations(definition_string: &str) -> PyResult<Vec<ColumnValidations>> {
188
220
  // Read the YAML definition with the validations
189
- let config =
190
- YamlLoader::load_from_str(fs::read_to_string(definition_path).unwrap().as_str()).unwrap();
221
+ let config = YamlLoader::load_from_str(definition_string).unwrap();
191
222
  // Get the column names list and each associated validation
192
223
  let columns = &config[0]["columns"];
193
224
  let mut column_names = vec![];
194
225
  let mut column_validations = vec![];
195
226
  for column in columns.as_vec().unwrap() {
196
227
  let column_def = column.as_hash().unwrap();
197
- let mut name = "";
228
+ let mut column_name = "";
198
229
  let mut validations = vec![];
199
230
  for validation_definition in column_def.iter() {
200
231
  let key = validation_definition.0.as_str().unwrap();
201
232
  let value = validation_definition.1;
202
- let mut validation: Validation = Validation::None;
203
- match key {
204
- "name" => { name = value.as_str().unwrap(); column_names.push(name); }
205
- "regex" => { validation = Validation::RegularExpression(String::from(value.as_str().unwrap())); }
206
- "min" => { validation = Validation::Min(value.as_i64().unwrap() as f64); }
207
- "max" => { validation = Validation::Max(value.as_i64().unwrap() as f64); }
208
- _ => panic!("Unknown validation: {key}")
209
- }
233
+ let validation = match key {
234
+ "name" => {
235
+ column_name = value.as_str().unwrap();
236
+ column_names.push(column_name);
237
+ Ok(Validation::None)
238
+ }
239
+ "regex" => { Ok(Validation::RegularExpression { expression: String::from(value.as_str().unwrap()), alias: String::from("regex") }) }
240
+ "min" => { Ok(Validation::Min(value.as_i64().unwrap() as f64)) }
241
+ "max" => { Ok(Validation::Max(value.as_i64().unwrap() as f64)) }
242
+ "values" => {
243
+ Ok(Validation::Values(value.as_vec().unwrap()
244
+ .iter()
245
+ .map(|v| String::from(v.as_str().unwrap()))
246
+ .collect()
247
+ ))
248
+ }
249
+ "format" => {
250
+ let format = value.as_str().unwrap();
251
+ let regex_for_format = get_regex_for_format(format)?;
252
+ Ok(Validation::RegularExpression { expression: regex_for_format, alias: format.to_string() })
253
+ }
254
+ _ => Err(PyRuntimeError::new_err(format!("Unknown validation: {key}")))
255
+ }?;
210
256
 
211
257
  if key != "name" {
212
258
  validations.push(validation);
213
259
  }
214
260
 
215
261
  }
216
- let new_validations = ColumnValidations { column_name: name.to_string(), validations: validations };
262
+ let new_validations = ColumnValidations { column_name: column_name.to_string(), validations: validations };
217
263
  column_validations.push(new_validations);
218
264
  }
219
265
 
220
- column_validations
266
+ Ok(column_validations)
221
267
  }
222
268
 
223
- fn validate_column_names(reader: &mut Reader<Box<dyn Read>>, validations: &Vec<ColumnValidations>) -> bool {
269
+ fn get_regex_for_format(format: &str) -> PyResult<String> {
270
+ match format {
271
+ "integer" => Ok(String::from("^-?\\d+$")),
272
+ "positive integer" => Ok(String::from("^\\d+$")),
273
+ _ => Err(PyRuntimeError::new_err(format!("Unknown format: {format}")))
274
+ }
275
+ }
276
+
277
+ fn validate_column_names(reader: &mut Reader<Box<dyn Read>>, validations: &Vec<ColumnValidations>) -> PyResult<bool> {
224
278
  let expected_column_names = validations.iter()
225
279
  .map(|v| v.column_name.clone())
226
280
  .collect::<Vec<String>>();
@@ -243,9 +297,9 @@ fn validate_column_names(reader: &mut Reader<Box<dyn Read>>, validations: &Vec<C
243
297
  }
244
298
  }
245
299
  }
246
- return false
300
+ return Ok(false)
247
301
  }
248
- true
302
+ Ok(true)
249
303
  }
250
304
 
251
305
  /// A Python module implemented in Rust.
@@ -253,13 +307,14 @@ fn validate_column_names(reader: &mut Reader<Box<dyn Read>>, validations: &Vec<C
253
307
  fn csv_validation(m: &Bound<'_, PyModule>) -> PyResult<()> {
254
308
  pyo3_log::init();
255
309
  m.add_function(wrap_pyfunction!(validate, m)?)?;
310
+ m.add_function(wrap_pyfunction!(validate_with_file, m)?)?;
256
311
  Ok(())
257
312
  }
258
313
 
259
314
  #[cfg(test)]
260
315
  mod tests {
261
316
  use simple_logger::SimpleLogger;
262
- use crate::validate;
317
+ use crate::{validate, validate_with_file};
263
318
 
264
319
  #[test]
265
320
  fn init_logger() {
@@ -267,17 +322,53 @@ mod tests {
267
322
  }
268
323
 
269
324
  #[test]
270
- fn test_validate_csv() {
271
- assert!(validate("test/test_file.csv", "test/test_validations.yml").unwrap());
325
+ fn test_validate_csv_with_file() {
326
+ assert!(validate_with_file("test/test_file.csv", "test/test_validations.yml").unwrap());
272
327
  }
273
328
 
274
329
  #[test]
275
- fn test_validate_csv_gz() {
276
- assert!(validate("test/test_file.csv.gz", "test/test_validations.yml").unwrap());
330
+ fn test_validate_csv_gz_with_file() {
331
+ assert!(validate_with_file("test/test_file.csv.gz", "test/test_validations.yml").unwrap());
277
332
  }
278
333
 
279
334
  #[test]
280
335
  fn test_wrong_headers() {
281
- assert!(!validate("test/test_file.csv", "test/test_validations_wrong_headers.yml").unwrap());
336
+ let definition = String::from("
337
+ columns:
338
+ - name: First Column
339
+ - name: Second Column
340
+ - name: Wrong Column
341
+ - name: Expected Column Not In File
342
+ ");
343
+ assert!(!validate("test/test_file.csv", definition).unwrap());
344
+ }
345
+
346
+ #[test]
347
+ fn test_format_validation() {
348
+ let definition = String::from("
349
+ columns:
350
+ - name: First Column
351
+ - name: Second Column
352
+ - name: Third Column
353
+ format: integer
354
+ ");
355
+ assert!(validate("test/test_file.csv", definition).unwrap());
356
+ }
357
+
358
+ #[test]
359
+ fn test_validate_csv() {
360
+ let definition = String::from("
361
+ columns:
362
+ - name: First Column
363
+ regex: ^.+$
364
+ - name: Second Column
365
+ values: [one_value, or_another]
366
+ - name: Third Column
367
+ regex: ^-?[0-9]+$
368
+ min: -23
369
+ max: 2000
370
+ ");
371
+
372
+ assert!(validate("test/test_file.csv", definition).unwrap());
282
373
  }
283
374
  }
@@ -0,0 +1,5 @@
1
+ First Column,Second Column,Third Column
2
+ first_val,one_value,67
3
+ second_val,or_another,1
4
+ third_val,or_another,1978
5
+ fourth_val,one_value,-23
@@ -1,5 +0,0 @@
1
- First Column,Second Column,Third Column
2
- first_val,other_value,67
3
- second_val,other second,1
4
- third_val,and_third,1978
5
- fourth_val,new ole,-23
@@ -1,5 +0,0 @@
1
- columns:
2
- - name: First Column
3
- - name: Second Column
4
- - name: Wrong Column
5
- - name: Expected Column Not In File
File without changes