csv-validation 0.0.5__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.5"
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.5"
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.5
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
@@ -8,16 +8,18 @@ use std::path::Path;
8
8
  use csv::Reader;
9
9
  use flate2::bufread::GzDecoder;
10
10
  use log::{debug, error, info};
11
+ use pyo3::exceptions::{PyRuntimeError};
11
12
  use pyo3::prelude::*;
12
13
  use regex::Regex;
13
14
  use yaml_rust2::YamlLoader;
15
+ use serde::{Deserialize, Serialize};
14
16
  use crate::Validation::{RegularExpression};
15
17
 
16
18
  const MAX_SAMPLE_SIZE:u16 = 10;
17
19
 
18
- #[derive(Debug, Clone)]
20
+ #[derive(Debug, Clone, Serialize, Deserialize)]
19
21
  enum Validation {
20
- RegularExpression(String),
22
+ RegularExpression { expression: String, alias: String },
21
23
  Min(f64),
22
24
  Max(f64),
23
25
  Values(Vec<String>),
@@ -29,12 +31,14 @@ struct ColumnValidations {
29
31
  validations: Vec<Validation>
30
32
  }
31
33
 
34
+ #[derive(Serialize, Deserialize)]
32
35
  struct ValidationSummary {
33
36
  validation: Validation,
34
37
  wrong_rows: usize,
35
38
  wrong_values_sample: Vec<String>
36
39
  }
37
40
 
41
+ #[derive(Serialize, Deserialize)]
38
42
  struct ColumnValidationsSummary {
39
43
  column_name: String,
40
44
  validation_summaries: Vec<ValidationSummary>
@@ -43,7 +47,7 @@ struct ColumnValidationsSummary {
43
47
  #[pyfunction]
44
48
  fn validate_with_file(path: &str, definition_path: &str) -> PyResult<bool> {
45
49
  info!("Validating file {} against definition file {}", path, definition_path);
46
- let definition_string = fs::read_to_string(definition_path).unwrap();
50
+ let definition_string = fs::read_to_string(definition_path)?;
47
51
  validate(path, definition_string)
48
52
  }
49
53
 
@@ -51,15 +55,15 @@ fn validate_with_file(path: &str, definition_path: &str) -> PyResult<bool> {
51
55
  #[pyfunction]
52
56
  fn validate(path: &str, definition_string: String) -> PyResult<bool> {
53
57
  debug!("Validating file {} against definition:\n {}", path, definition_string);
54
- let validations = get_validations(definition_string.as_str());
58
+ let validations = get_validations(definition_string.as_str())?;
55
59
 
56
60
  // Pre-Compile and save all Regex expressions to save time in execution
57
61
  let mut regex_map = HashMap::new();
58
62
  for column_validation in &validations {
59
63
  for validation in &column_validation.validations {
60
64
  match validation {
61
- RegularExpression(regex) => {
62
- regex_map.insert(regex.to_string(), Regex::new(regex.as_str()).unwrap());
65
+ RegularExpression { expression, alias: _ } => {
66
+ regex_map.insert(expression.to_string(), Regex::new(expression.as_str()).unwrap());
63
67
  },
64
68
  Values(values) => {
65
69
  let regex_str = get_regex_string_for_values(values);
@@ -71,10 +75,10 @@ fn validate(path: &str, definition_string: String) -> PyResult<bool> {
71
75
  }
72
76
 
73
77
  // Build the CSV reader
74
- let mut rdr = get_reader_from(path);
78
+ let mut rdr = get_reader_from(path)?;
75
79
 
76
80
  // First validation: Ensure column names and order are exactly as expected
77
- if validate_column_names(&mut rdr, &validations) {
81
+ if validate_column_names(&mut rdr, &validations)? {
78
82
  info!("Columns names and order are correct");
79
83
  }
80
84
  else {
@@ -91,7 +95,7 @@ fn validate(path: &str, definition_string: String) -> PyResult<bool> {
91
95
  let value = next_column.0;
92
96
  let _column_name = &next_column.1.column_name;
93
97
  for validation in &next_column.1.validations {
94
- let valid = apply_validation(value, validation, &regex_map);
98
+ let valid = apply_validation(value, validation, &regex_map)?;
95
99
  if !valid {
96
100
  let validation_summary_list = validation_summaries_map.get_mut(_column_name).unwrap();
97
101
  let validation_summary = validation_summary_list
@@ -120,13 +124,20 @@ fn validate(path: &str, definition_string: String) -> PyResult<bool> {
120
124
  column_validation_summaries.push(column_validation_summary);
121
125
  }
122
126
 
127
+ let validation_result_json = serde_json::to_string(&column_validation_summaries).unwrap();
128
+
123
129
  debug!("VALIDATIONS SUMMARY");
124
130
  debug!("==================================================================================");
125
131
  for column_validation_summary in column_validation_summaries {
126
132
  debug!("Column: '{}'", column_validation_summary.column_name);
127
133
  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);
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);
130
141
  }
131
142
  }
132
143
 
@@ -154,30 +165,30 @@ fn build_validation_summaries_map(validations: &Vec<ColumnValidations>) -> HashM
154
165
  validation_summaries_map
155
166
  }
156
167
 
157
- 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> {
158
169
  match validation {
159
- RegularExpression(regex) => {
160
- let regex = regex_map.get(regex).unwrap();
161
- regex.is_match(value)
170
+ RegularExpression { expression: exp, alias: _ } => {
171
+ let regex = regex_map.get(exp).unwrap();
172
+ Ok(regex.is_match(value))
162
173
  },
163
174
  Validation::Min(min) => {
164
175
  match value.parse::<f64>() {
165
- Ok(value) => value >= *min,
166
- Err(_) => false
176
+ Ok(value) => Ok(value >= *min),
177
+ Err(_) => Ok(false)
167
178
  }
168
179
  },
169
180
  Validation::Max(max) => {
170
181
  match value.parse::<f64>() {
171
- Ok(value) => value <= *max,
172
- Err(_) => false
182
+ Ok(value) => Ok(value <= *max),
183
+ Err(_) => Ok(false)
173
184
  }
174
185
  },
175
186
  Validation::Values(values) => {
176
187
  let regex_str = get_regex_string_for_values(values);
177
188
  let regex = regex_map.get(&regex_str).unwrap();
178
- regex.is_match(value)
189
+ Ok(regex.is_match(value))
179
190
  }
180
- Validation::None => panic!("Validation of type 'None' cannot be applied")
191
+ Validation::None => Err(PyRuntimeError::new_err("'None' validation has no implementation"))
181
192
  }
182
193
  }
183
194
 
@@ -186,26 +197,26 @@ fn get_regex_string_for_values(values: &Vec<String>) -> String {
186
197
  }
187
198
 
188
199
  /// 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) {
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)? {
192
203
  debug!("File is gzipped");
193
204
  let read_capacity = 10 * 1024_usize.pow(2);
194
205
  let reader = BufReader::with_capacity(read_capacity, GzDecoder::new(buf_reader));
195
- Reader::from_reader(Box::new(reader))
206
+ Ok(Reader::from_reader(Box::new(reader)))
196
207
  }
197
208
  else {
198
- Reader::from_reader(Box::new(buf_reader))
209
+ Ok(Reader::from_reader(Box::new(buf_reader)))
199
210
  }
200
211
  }
201
212
 
202
- fn is_gzip_file(path: &str) -> bool {
213
+ fn is_gzip_file(path: &str) -> PyResult<bool> {
203
214
  let mut bytes = [0u8; 2];
204
- File::open(Path::new(path)).unwrap().read_exact(&mut bytes).unwrap();
205
- bytes[0] == 0x1f && bytes[1] == 0x8b
215
+ File::open(Path::new(path))?.read_exact(&mut bytes)?;
216
+ Ok(bytes[0] == 0x1f && bytes[1] == 0x8b)
206
217
  }
207
218
 
208
- fn get_validations(definition_string: &str) -> Vec<ColumnValidations> {
219
+ fn get_validations(definition_string: &str) -> PyResult<Vec<ColumnValidations>> {
209
220
  // Read the YAML definition with the validations
210
221
  let config = YamlLoader::load_from_str(definition_string).unwrap();
211
222
  // Get the column names list and each associated validation
@@ -214,40 +225,56 @@ fn get_validations(definition_string: &str) -> Vec<ColumnValidations> {
214
225
  let mut column_validations = vec![];
215
226
  for column in columns.as_vec().unwrap() {
216
227
  let column_def = column.as_hash().unwrap();
217
- let mut name = "";
228
+ let mut column_name = "";
218
229
  let mut validations = vec![];
219
230
  for validation_definition in column_def.iter() {
220
231
  let key = validation_definition.0.as_str().unwrap();
221
232
  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
- }
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
+ }?;
237
256
 
238
257
  if key != "name" {
239
258
  validations.push(validation);
240
259
  }
241
260
 
242
261
  }
243
- let new_validations = ColumnValidations { column_name: name.to_string(), validations: validations };
262
+ let new_validations = ColumnValidations { column_name: column_name.to_string(), validations: validations };
244
263
  column_validations.push(new_validations);
245
264
  }
246
265
 
247
- column_validations
266
+ Ok(column_validations)
248
267
  }
249
268
 
250
- 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> {
251
278
  let expected_column_names = validations.iter()
252
279
  .map(|v| v.column_name.clone())
253
280
  .collect::<Vec<String>>();
@@ -270,9 +297,9 @@ fn validate_column_names(reader: &mut Reader<Box<dyn Read>>, validations: &Vec<C
270
297
  }
271
298
  }
272
299
  }
273
- return false
300
+ return Ok(false)
274
301
  }
275
- true
302
+ Ok(true)
276
303
  }
277
304
 
278
305
  /// A Python module implemented in Rust.
@@ -316,6 +343,18 @@ mod tests {
316
343
  assert!(!validate("test/test_file.csv", definition).unwrap());
317
344
  }
318
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
+
319
358
  #[test]
320
359
  fn test_validate_csv() {
321
360
  let definition = String::from("
File without changes