csv-validation 0.0.10__tar.gz → 0.0.11__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.10"
86
+ version = "0.0.11"
87
87
  dependencies = [
88
88
  "csv",
89
89
  "flate2",
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "csv_validation"
3
- version = "0.0.10"
3
+ version = "0.0.11"
4
4
  edition = "2021"
5
5
 
6
6
  # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: csv_validation
3
- Version: 0.0.10
3
+ Version: 0.0.11
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Classifier: Programming Language :: Python :: Implementation :: PyPy
@@ -11,12 +11,13 @@ use log::{debug, error, info};
11
11
  use pyo3::exceptions::{PyRuntimeError};
12
12
  use pyo3::prelude::*;
13
13
  use regex::Regex;
14
- use yaml_rust2::YamlLoader;
14
+ use yaml_rust2::{Yaml, YamlLoader};
15
15
  use serde::{Deserialize, Serialize};
16
16
  use crate::Validation::{RegularExpression};
17
17
 
18
18
  const MAX_SAMPLE_SIZE:u16 = 10;
19
19
  const DEFAULT_COLUMN_SEPARATOR:u8 = b',';
20
+ const DEFAULT_DECIMAL_SEPARATOR:char = '.';
20
21
 
21
22
  #[derive(Debug, Clone, Serialize, Deserialize)]
22
23
  enum Validation {
@@ -90,45 +91,20 @@ fn build_validation_summaries_map(validations: &Vec<ColumnValidations>) -> HashM
90
91
  validation_summaries_map
91
92
  }
92
93
 
93
- fn apply_validation(value: &str, validation: &Validation, regex_map: &HashMap<String, Regex>) -> PyResult<bool> {
94
- match validation {
95
- RegularExpression { expression: exp, alias: _ } => {
96
- let regex = regex_map.get(exp).unwrap();
97
- Ok(regex.is_match(value))
98
- },
99
- Validation::Min(min) => {
100
- if value.is_empty() {
101
- Ok(true)
102
- }
103
- else {
104
- match value.parse::<f64>() {
105
- Ok(value) => Ok(value >= *min),
106
- Err(_) => Ok(false)
107
- }
108
- }
109
- },
110
- Validation::Max(max) => {
111
- if value.is_empty() {
112
- Ok(true)
113
- }
114
- else {
115
- match value.parse::<f64>() {
116
- Ok(value) => Ok(value <= *max),
117
- Err(_) => Ok(false)
118
- }
119
- }
120
- },
121
- Validation::Values(values) => {
122
- let regex_str = get_regex_string_for_values(values);
123
- let regex = regex_map.get(&regex_str).unwrap();
124
- Ok(regex.is_match(value))
125
- }
126
- Validation::None => Err(PyRuntimeError::new_err("'None' validation has no implementation"))
127
- }
94
+ fn get_regex_string_for_values(values: &Vec<String>) -> String {
95
+ format!("^$|^(?:{})$", values.iter().map(|s| regex_escape(s)).collect::<Vec<_>>().join("|"))
128
96
  }
129
97
 
130
- fn get_regex_string_for_values(values: &Vec<String>) -> String {
131
- format!("^$|^(?:{})$", values.join("|"))
98
+ fn regex_escape(text: &str) -> String {
99
+ let metacharacters = r"\.^$|()?*+[]{}";
100
+ let mut escaped = String::with_capacity(text.len());
101
+ for ch in text.chars() {
102
+ if metacharacters.contains(ch) {
103
+ escaped.push('\\');
104
+ }
105
+ escaped.push(ch);
106
+ }
107
+ escaped
132
108
  }
133
109
 
134
110
  /// Infers the file compression type and returns the corresponding buffered reader
@@ -207,14 +183,14 @@ fn get_validations(definition_string: &str) -> PyResult<Vec<ColumnValidations>>
207
183
  })
208
184
  }
209
185
  "min" => {
210
- let num = value.as_i64()
211
- .ok_or_else(|| PyRuntimeError::new_err("Min value must be a number"))?;
212
- Ok(Validation::Min(num as f64))
186
+ let num = yaml_value_as_f64(value)
187
+ .ok_or_else(|| PyRuntimeError::new_err(format!("Min value {:?} is not a number", value)))?;
188
+ Ok(Validation::Min(num))
213
189
  }
214
190
  "max" => {
215
- let num = value.as_i64()
216
- .ok_or_else(|| PyRuntimeError::new_err("Max value must be a number"))?;
217
- Ok(Validation::Max(num as f64))
191
+ let num = yaml_value_as_f64(value)
192
+ .ok_or_else(|| PyRuntimeError::new_err(format!("Max value {:?} is not a number", value)))?;
193
+ Ok(Validation::Max(num))
218
194
  }
219
195
  "values" => {
220
196
  let values = value.as_vec()
@@ -268,6 +244,14 @@ fn get_validations(definition_string: &str) -> PyResult<Vec<ColumnValidations>>
268
244
  Ok(column_validations)
269
245
  }
270
246
 
247
+ fn yaml_value_as_f64(val: &Yaml) -> Option<f64> {
248
+ match val {
249
+ Yaml::Real(s) => s.parse().ok(),
250
+ Yaml::Integer(i) => Some(*i as f64),
251
+ _ => None,
252
+ }
253
+ }
254
+
271
255
  fn get_regex_for_format(format: &str) -> PyResult<String> {
272
256
  match format {
273
257
  "integer" => Ok(String::from("^$|^-?\\d+$")),
@@ -315,9 +299,11 @@ fn validate_column_names(reader: &mut Reader<Box<dyn Read>>, validations: &Vec<C
315
299
  struct CSVValidator {
316
300
  validations: Vec<ColumnValidations>,
317
301
  regex_map: HashMap<String, Regex>,
318
- separator: u8
302
+ separator: u8,
303
+ decimal_separator: char
319
304
  }
320
305
 
306
+ // Methods Exposed to Python
321
307
  #[pymethods]
322
308
  impl CSVValidator {
323
309
  #[new]
@@ -325,7 +311,8 @@ impl CSVValidator {
325
311
  CSVValidator {
326
312
  validations: Vec::new(),
327
313
  regex_map: HashMap::new(),
328
- separator: DEFAULT_COLUMN_SEPARATOR
314
+ separator: DEFAULT_COLUMN_SEPARATOR,
315
+ decimal_separator: DEFAULT_DECIMAL_SEPARATOR
329
316
  }
330
317
  }
331
318
 
@@ -356,7 +343,7 @@ impl CSVValidator {
356
343
  }
357
344
  }
358
345
 
359
- Ok(CSVValidator { validations, regex_map, separator: DEFAULT_COLUMN_SEPARATOR })
346
+ Ok(CSVValidator { validations, regex_map, separator: DEFAULT_COLUMN_SEPARATOR, decimal_separator: DEFAULT_DECIMAL_SEPARATOR })
360
347
  }
361
348
 
362
349
  fn set_separator(&mut self, separator: String) -> PyResult<()> {
@@ -369,6 +356,16 @@ impl CSVValidator {
369
356
  }
370
357
  }
371
358
 
359
+ fn set_decimal_separator(&mut self, decimal_separator: String) -> PyResult<()> {
360
+ if decimal_separator.len() == 1 {
361
+ self.decimal_separator = decimal_separator.chars().next().unwrap();
362
+ Ok(())
363
+ }
364
+ else {
365
+ Err(PyRuntimeError::new_err(format!("Wrong decimal separator {decimal_separator}. It can only have one character")))
366
+ }
367
+ }
368
+
372
369
  fn validate(&self, file_path: &str) -> PyResult<bool> {
373
370
  // Build the CSV reader
374
371
  let mut rdr = get_reader_from(file_path, self.separator)?;
@@ -392,7 +389,7 @@ impl CSVValidator {
392
389
  let value = next_column.0;
393
390
  let _column_name = &next_column.1.column_name;
394
391
  for validation in &next_column.1.validations {
395
- let valid = apply_validation(value, validation, &self.regex_map)?;
392
+ let valid = self.apply_validation(value, validation, &self.regex_map)?;
396
393
  if !valid {
397
394
  let validation_summary_list = validation_summaries_map.get_mut(_column_name).unwrap();
398
395
  let validation_summary = validation_summary_list
@@ -466,6 +463,48 @@ impl CSVValidator {
466
463
  }
467
464
  }
468
465
 
466
+ // Internal methods that are NOT Exposed in Python
467
+ impl CSVValidator {
468
+ fn apply_validation(&self, value: &str, validation: &Validation, regex_map: &HashMap<String, Regex>) -> PyResult<bool> {
469
+ match validation {
470
+ RegularExpression { expression: exp, alias: _ } => {
471
+ let regex = regex_map.get(exp).unwrap();
472
+ Ok(regex.is_match(value))
473
+ },
474
+ Validation::Min(min) => {
475
+ if value.is_empty() {
476
+ Ok(true)
477
+ }
478
+ else {
479
+ let normalized_value = value.replace(self.decimal_separator, ".");
480
+ match normalized_value.parse::<f64>() {
481
+ Ok(value) => Ok(value >= *min),
482
+ Err(_) => Ok(false)
483
+ }
484
+ }
485
+ },
486
+ Validation::Max(max) => {
487
+ if value.is_empty() {
488
+ Ok(true)
489
+ }
490
+ else {
491
+ let normalized_value = value.replace(self.decimal_separator, ".");
492
+ match normalized_value.parse::<f64>() {
493
+ Ok(value) => Ok(value <= *max),
494
+ Err(_) => Ok(false)
495
+ }
496
+ }
497
+ },
498
+ Validation::Values(values) => {
499
+ let regex_str = get_regex_string_for_values(values);
500
+ let regex = regex_map.get(&regex_str).unwrap();
501
+ Ok(regex.is_match(value))
502
+ }
503
+ Validation::None => Err(PyRuntimeError::new_err("'None' validation has no implementation"))
504
+ }
505
+ }
506
+ }
507
+
469
508
  /// A Python module implemented in Rust.
470
509
  #[pymodule]
471
510
  fn csv_validation(m: &Bound<'_, PyModule>) -> PyResult<()> {
@@ -634,6 +673,43 @@ mod tests {
634
673
  assert!(validator.validate("test/empty_values.csv").unwrap());
635
674
  }
636
675
 
676
+ #[test]
677
+ fn test_list_of_values_with_special_characters() {
678
+ let definition = String::from("
679
+ columns:
680
+ - name: ColumnA
681
+ values: ['A+', '[B]', 'C$']
682
+ ");
683
+
684
+ let path_of_file_to_validate = "test/test_file_with_special_characters.csv";
685
+ let file_content = "ColumnA\nA+\n[B]\nC$";
686
+ std::fs::write(path_of_file_to_validate, file_content).unwrap();
687
+
688
+ let validator = CSVValidator::from_string(&definition).unwrap();
689
+ assert!(validator.validate(path_of_file_to_validate).unwrap());
690
+ std::fs::remove_file(path_of_file_to_validate).unwrap();
691
+ }
692
+
693
+ #[test]
694
+ fn test_min_max_with_custom_decimal_separator() {
695
+ let definition = String::from("
696
+ columns:
697
+ - name: ColumnA
698
+ min: -5
699
+ max: 27.8
700
+ ");
701
+
702
+ let path_of_file_to_validate = "test/test_file_with_custom_decimals.csv";
703
+ let file_content = "ColumnA\n0\n4,3\n27,8";
704
+ std::fs::write(path_of_file_to_validate, file_content).unwrap();
705
+
706
+ let mut validator = CSVValidator::from_string(&definition).unwrap();
707
+ validator.set_separator(String::from(";")).unwrap();
708
+ validator.set_decimal_separator(String::from(",")).unwrap();
709
+ assert!(validator.validate(path_of_file_to_validate).unwrap());
710
+ std::fs::remove_file(path_of_file_to_validate).unwrap();
711
+ }
712
+
637
713
  #[test]
638
714
  fn test_format_integer() {
639
715
  let test_cases = vec![
File without changes