csv-validation 0.0.10__tar.gz → 0.0.12__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.12"
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.12"
4
4
  edition = "2021"
5
5
 
6
6
  # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -0,0 +1 @@
1
+ include csv_validation.pyi
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: csv_validation
3
- Version: 0.0.10
3
+ Version: 0.0.12
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Classifier: Programming Language :: Python :: Implementation :: PyPy
@@ -12,17 +12,18 @@ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
12
12
 
13
13
  Blazing fast format validations for your CSV files
14
14
 
15
- This is a Python lib with a Rust core that will allow you to validate huge CSV files (GBs) in seconds (or in few minutes for really huge files) using a minimal amount of memory.
15
+ This is a Python lib with a Rust core that will allow you to validate huge CSV files (GBs) in seconds (or in a few minutes for really huge files) using a minimal amount of memory.
16
16
 
17
17
  ## Features
18
18
 
19
19
  - ✨ Validate both plain and gzipped CSV files
20
20
  - 🔍 Multiple validation types supported:
21
+ - Correct column name and order
21
22
  - Regular expressions
22
- - Minimum/Maximum value checks
23
+ - Well-known formats (integer, decimal, etc.)
24
+ - Minimum/Maximum numerical value checks
23
25
  - Value set validation (allowed values)
24
- - Column name and order validation
25
- - 🐍 Python bindings included
26
+ - 🦀 + 🐍 Rust lib with Python bindings included
26
27
  - 📝 Detailed validation summaries with sample invalid values
27
28
  - 🚀 High performance with optimizations like regex pre-compilation
28
29
  - 📊 Support for large CSV files
@@ -68,7 +69,7 @@ is_valid = validator.validate("data.csv")
68
69
 
69
70
  ### Validation Definition Format
70
71
 
71
- Create a small, easy to read YAML file with your validation rules. Example:
72
+ Create a small, easy-to-read YAML file with your validation rules. Example:
72
73
 
73
74
  ```yaml
74
75
  columns:
@@ -98,12 +99,17 @@ columns:
98
99
  - Validate fields against custom regex patterns
99
100
 
100
101
  2. **Format** (`format`)
101
- - Predefined formats for common validations
102
+ - Predefined formats for common validations (This is the recommended way to validate numeric fields)
103
+ - In the background, the library uses regex patterns to validate formats.
102
104
  - Available formats:
103
105
  - `integer`: Validates any integer number (positive or negative)
104
- - `positive_integer`: Validates positive integer numbers
106
+ - `positive integer`: Validates positive integer numbers
107
+ - `decimal`: Validates any decimal number (positive or negative) using point as decimal separator
108
+ - `positive decimal point/positive decimal`: Validates positive decimal numbers using point as decimal separator
109
+ - `positive decimal comma`: Validates positive decimal numbers using comma as decimal separator
110
+ - `decimal scientific`: Validates decimal numbers in scientific notation (e.g. 23.02e-12)
105
111
  - `non_empty`: Validates that field contains at least one character
106
- - More formats will be added in next versions
112
+ - More formats will be added in upcoming versions
107
113
 
108
114
  3. **Minimum Value** (`min`)
109
115
  - Check if numeric fields are greater than or equal to a specified value
@@ -114,6 +120,9 @@ columns:
114
120
  5. **Value Set** (`values`)
115
121
  - Ensure fields only contain values from a predefined set
116
122
 
123
+ You can add as many validations as you want for the same column, but take into account that the
124
+ column only will be considered correct if all the validations are OK.
125
+
117
126
  ## Global Validations
118
127
 
119
128
  ### empty_not_ok
@@ -130,17 +139,7 @@ columns:
130
139
  # other validations...
131
140
  ```
132
141
 
133
- ### Supported Formats
134
-
135
- - `integer`: Any integer number (positive or negative)
136
- - `positive integer`: Any positive integer number
137
- - `decimal`: Any decimal number (positive or negative)
138
- - `positive decimal point`: Any positive decimal number using point as decimal separator
139
- - `positive decimal comma`: Any positive decimal number using comma as decimal separator
140
- - `decimal scientific`: Any decimal number in scientific notation
141
- - `non_empty`: Any non-empty value
142
-
143
- ### Column Separators
142
+ ### Column Separator
144
143
 
145
144
  By default, the library uses comma (,) as the column separator. You can change this using the `set_separator` method:
146
145
 
@@ -150,6 +149,15 @@ validator.set_separator(";") # Use semicolon as separator
150
149
  validator.set_separator("\t") # Use tab as separator
151
150
  ```
152
151
 
152
+ ### Decimal Separator
153
+
154
+ By default, the library uses point (.) as the decimal separator. You can change this using the `set_decimal_separator` method:
155
+
156
+ ```python
157
+ validator = CSVValidator.from_file("rules.yml")
158
+ validator.set_decimal_separator(",") # Use comma
159
+ ```
160
+
153
161
  ## Error Handling
154
162
 
155
163
  The library provides detailed validation reports through Python's logging system. When a validation fails, you'll get information about:
@@ -2,17 +2,18 @@
2
2
 
3
3
  Blazing fast format validations for your CSV files
4
4
 
5
- This is a Python lib with a Rust core that will allow you to validate huge CSV files (GBs) in seconds (or in few minutes for really huge files) using a minimal amount of memory.
5
+ This is a Python lib with a Rust core that will allow you to validate huge CSV files (GBs) in seconds (or in a few minutes for really huge files) using a minimal amount of memory.
6
6
 
7
7
  ## Features
8
8
 
9
9
  - ✨ Validate both plain and gzipped CSV files
10
10
  - 🔍 Multiple validation types supported:
11
+ - Correct column name and order
11
12
  - Regular expressions
12
- - Minimum/Maximum value checks
13
+ - Well-known formats (integer, decimal, etc.)
14
+ - Minimum/Maximum numerical value checks
13
15
  - Value set validation (allowed values)
14
- - Column name and order validation
15
- - 🐍 Python bindings included
16
+ - 🦀 + 🐍 Rust lib with Python bindings included
16
17
  - 📝 Detailed validation summaries with sample invalid values
17
18
  - 🚀 High performance with optimizations like regex pre-compilation
18
19
  - 📊 Support for large CSV files
@@ -58,7 +59,7 @@ is_valid = validator.validate("data.csv")
58
59
 
59
60
  ### Validation Definition Format
60
61
 
61
- Create a small, easy to read YAML file with your validation rules. Example:
62
+ Create a small, easy-to-read YAML file with your validation rules. Example:
62
63
 
63
64
  ```yaml
64
65
  columns:
@@ -88,12 +89,17 @@ columns:
88
89
  - Validate fields against custom regex patterns
89
90
 
90
91
  2. **Format** (`format`)
91
- - Predefined formats for common validations
92
+ - Predefined formats for common validations (This is the recommended way to validate numeric fields)
93
+ - In the background, the library uses regex patterns to validate formats.
92
94
  - Available formats:
93
95
  - `integer`: Validates any integer number (positive or negative)
94
- - `positive_integer`: Validates positive integer numbers
96
+ - `positive integer`: Validates positive integer numbers
97
+ - `decimal`: Validates any decimal number (positive or negative) using point as decimal separator
98
+ - `positive decimal point/positive decimal`: Validates positive decimal numbers using point as decimal separator
99
+ - `positive decimal comma`: Validates positive decimal numbers using comma as decimal separator
100
+ - `decimal scientific`: Validates decimal numbers in scientific notation (e.g. 23.02e-12)
95
101
  - `non_empty`: Validates that field contains at least one character
96
- - More formats will be added in next versions
102
+ - More formats will be added in upcoming versions
97
103
 
98
104
  3. **Minimum Value** (`min`)
99
105
  - Check if numeric fields are greater than or equal to a specified value
@@ -104,6 +110,9 @@ columns:
104
110
  5. **Value Set** (`values`)
105
111
  - Ensure fields only contain values from a predefined set
106
112
 
113
+ You can add as many validations as you want for the same column, but take into account that the
114
+ column only will be considered correct if all the validations are OK.
115
+
107
116
  ## Global Validations
108
117
 
109
118
  ### empty_not_ok
@@ -120,17 +129,7 @@ columns:
120
129
  # other validations...
121
130
  ```
122
131
 
123
- ### Supported Formats
124
-
125
- - `integer`: Any integer number (positive or negative)
126
- - `positive integer`: Any positive integer number
127
- - `decimal`: Any decimal number (positive or negative)
128
- - `positive decimal point`: Any positive decimal number using point as decimal separator
129
- - `positive decimal comma`: Any positive decimal number using comma as decimal separator
130
- - `decimal scientific`: Any decimal number in scientific notation
131
- - `non_empty`: Any non-empty value
132
-
133
- ### Column Separators
132
+ ### Column Separator
134
133
 
135
134
  By default, the library uses comma (,) as the column separator. You can change this using the `set_separator` method:
136
135
 
@@ -140,6 +139,15 @@ validator.set_separator(";") # Use semicolon as separator
140
139
  validator.set_separator("\t") # Use tab as separator
141
140
  ```
142
141
 
142
+ ### Decimal Separator
143
+
144
+ By default, the library uses point (.) as the decimal separator. You can change this using the `set_decimal_separator` method:
145
+
146
+ ```python
147
+ validator = CSVValidator.from_file("rules.yml")
148
+ validator.set_decimal_separator(",") # Use comma
149
+ ```
150
+
143
151
  ## Error Handling
144
152
 
145
153
  The library provides detailed validation reports through Python's logging system. When a validation fails, you'll get information about:
@@ -0,0 +1,13 @@
1
+ class CSVValidator:
2
+
3
+ @staticmethod
4
+ def from_file(definition_path: str) -> CSVValidator: ...
5
+
6
+ @staticmethod
7
+ def from_string(definition_string: str) -> CSVValidator: ...
8
+
9
+ def set_separator(self, separator: str): ...
10
+
11
+ def set_decimal_separator(self, decimal_separator: str): ...
12
+
13
+ def validate(self, file_path: str) -> bool: ...
@@ -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 {
@@ -75,6 +76,26 @@ struct ColumnValidationsSummary {
75
76
  validation_summaries: Vec<ValidationSummary>
76
77
  }
77
78
 
79
+ #[derive(Serialize, Deserialize)]
80
+ struct FileValidationSummary {
81
+ file_path: String,
82
+ total_rows: usize,
83
+ total_columns: usize,
84
+ correct_columns: Vec<ColumnValidationsSummary>,
85
+ wrong_columns: Vec<ColumnValidationsSummary>
86
+ }
87
+
88
+ impl ValidationSummary {
89
+ fn get_wrong_values_details(&self) -> String {
90
+ let wrong_samples = &self.wrong_values_sample
91
+ .iter()
92
+ .map(|s| format!("'{}'", s))
93
+ .collect::<Vec<String>>()
94
+ .join(",");
95
+ format!("Wrong Rows: {} | Sample: {}", self.wrong_rows, wrong_samples)
96
+ }
97
+ }
98
+
78
99
  fn build_validation_summaries_map(validations: &Vec<ColumnValidations>) -> HashMap<String, Vec<ValidationSummary>> {
79
100
  let mut validation_summaries_map = HashMap::new();
80
101
  for validation in validations {
@@ -90,48 +111,23 @@ fn build_validation_summaries_map(validations: &Vec<ColumnValidations>) -> HashM
90
111
  validation_summaries_map
91
112
  }
92
113
 
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
- }
114
+ fn get_regex_string_for_values(values: &Vec<String>) -> String {
115
+ format!("^$|^(?:{})$", values.iter().map(|s| regex_escape(s)).collect::<Vec<_>>().join("|"))
128
116
  }
129
117
 
130
- fn get_regex_string_for_values(values: &Vec<String>) -> String {
131
- format!("^$|^(?:{})$", values.join("|"))
118
+ fn regex_escape(text: &str) -> String {
119
+ let metacharacters = r"\.^$|()?*+[]{}";
120
+ let mut escaped = String::with_capacity(text.len());
121
+ for ch in text.chars() {
122
+ if metacharacters.contains(ch) {
123
+ escaped.push('\\');
124
+ }
125
+ escaped.push(ch);
126
+ }
127
+ escaped
132
128
  }
133
129
 
134
- /// Infers the file compression type and returns the corresponding buffered reader
130
+ /// Infers the file compression status and returns the corresponding buffered reader
135
131
  fn get_reader_from(path: &str, separator: u8) -> PyResult<Reader<Box<dyn Read>>> {
136
132
  let buf_reader = BufReader::new(File::open(Path::new(path))?);
137
133
  if is_gzip_file(path)? {
@@ -207,14 +203,14 @@ fn get_validations(definition_string: &str) -> PyResult<Vec<ColumnValidations>>
207
203
  })
208
204
  }
209
205
  "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))
206
+ let num = yaml_value_as_f64(value)
207
+ .ok_or_else(|| PyRuntimeError::new_err(format!("Min value {:?} is not a number", value)))?;
208
+ Ok(Validation::Min(num))
213
209
  }
214
210
  "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))
211
+ let num = yaml_value_as_f64(value)
212
+ .ok_or_else(|| PyRuntimeError::new_err(format!("Max value {:?} is not a number", value)))?;
213
+ Ok(Validation::Max(num))
218
214
  }
219
215
  "values" => {
220
216
  let values = value.as_vec()
@@ -268,6 +264,14 @@ fn get_validations(definition_string: &str) -> PyResult<Vec<ColumnValidations>>
268
264
  Ok(column_validations)
269
265
  }
270
266
 
267
+ fn yaml_value_as_f64(val: &Yaml) -> Option<f64> {
268
+ match val {
269
+ Yaml::Real(s) => s.parse().ok(),
270
+ Yaml::Integer(i) => Some(*i as f64),
271
+ _ => None,
272
+ }
273
+ }
274
+
271
275
  fn get_regex_for_format(format: &str) -> PyResult<String> {
272
276
  match format {
273
277
  "integer" => Ok(String::from("^$|^-?\\d+$")),
@@ -282,6 +286,7 @@ fn get_regex_for_format(format: &str) -> PyResult<String> {
282
286
  }
283
287
 
284
288
  fn validate_column_names(reader: &mut Reader<Box<dyn Read>>, validations: &Vec<ColumnValidations>) -> PyResult<bool> {
289
+ info!("Validating column names and order...");
285
290
  let expected_column_names = validations.iter()
286
291
  .map(|v| v.column_name.clone())
287
292
  .collect::<Vec<String>>();
@@ -315,9 +320,11 @@ fn validate_column_names(reader: &mut Reader<Box<dyn Read>>, validations: &Vec<C
315
320
  struct CSVValidator {
316
321
  validations: Vec<ColumnValidations>,
317
322
  regex_map: HashMap<String, Regex>,
318
- separator: u8
323
+ separator: u8,
324
+ decimal_separator: char
319
325
  }
320
326
 
327
+ // Methods Exposed to Python
321
328
  #[pymethods]
322
329
  impl CSVValidator {
323
330
  #[new]
@@ -325,17 +332,34 @@ impl CSVValidator {
325
332
  CSVValidator {
326
333
  validations: Vec::new(),
327
334
  regex_map: HashMap::new(),
328
- separator: DEFAULT_COLUMN_SEPARATOR
335
+ separator: DEFAULT_COLUMN_SEPARATOR,
336
+ decimal_separator: DEFAULT_DECIMAL_SEPARATOR
329
337
  }
330
338
  }
331
339
 
332
340
  #[staticmethod]
341
+ #[pyo3(text_signature = "(definition_path)")]
342
+ /// Create a new CSVValidator from a YAML file with the validation definition.
343
+ ///
344
+ /// Args:
345
+ /// definition_path (str): The path to the YAML file with the validation definition.
346
+ ///
347
+ /// Returns:
348
+ /// a CSVValidation instance
333
349
  fn from_file(definition_path: &str) -> PyResult<Self> {
334
350
  let definition_string = fs::read_to_string(definition_path)?;
335
351
  Self::from_string(&definition_string)
336
352
  }
337
353
 
338
354
  #[staticmethod]
355
+ #[pyo3(text_signature = "(definition_string)")]
356
+ /// Create a new CSVValidator from a YAML string with the validation definition.
357
+ ///
358
+ /// Args:
359
+ /// definition_string (str): A string with the YAML validations definition.
360
+ ///
361
+ /// Returns:
362
+ /// a CSVValidation instance
339
363
  fn from_string(definition_string: &str) -> PyResult<Self> {
340
364
  let validations = get_validations(definition_string)?;
341
365
  let mut regex_map = HashMap::new();
@@ -356,9 +380,16 @@ impl CSVValidator {
356
380
  }
357
381
  }
358
382
 
359
- Ok(CSVValidator { validations, regex_map, separator: DEFAULT_COLUMN_SEPARATOR })
383
+ Ok(CSVValidator { validations, regex_map, separator: DEFAULT_COLUMN_SEPARATOR, decimal_separator: DEFAULT_DECIMAL_SEPARATOR })
360
384
  }
361
385
 
386
+ #[pyo3(text_signature = "(self, separator)")]
387
+ /// Set the CSV separator (also known as delimiter):
388
+ ///
389
+ /// The separator is ',' by default. If your file has a different one, you can modify it here.
390
+ ///
391
+ /// Args:
392
+ /// separator (str): A string with only one character that is the CSV file separator.
362
393
  fn set_separator(&mut self, separator: String) -> PyResult<()> {
363
394
  if separator.len() == 1 {
364
395
  self.separator = separator.chars().next().unwrap() as u8;
@@ -369,6 +400,33 @@ impl CSVValidator {
369
400
  }
370
401
  }
371
402
 
403
+ #[pyo3(text_signature = "(self, decimal_separator)")]
404
+ /// Set the decimal number separator
405
+ ///
406
+ /// The default decimals separator for float numbers is '.'.
407
+ /// If your file uses a different one, you can modify it here.
408
+ ///
409
+ /// Args:
410
+ /// decimal_separator (str): A string with only one character that is the decimal separator.
411
+ fn set_decimal_separator(&mut self, decimal_separator: String) -> PyResult<()> {
412
+ if decimal_separator.len() == 1 {
413
+ self.decimal_separator = decimal_separator.chars().next().unwrap();
414
+ Ok(())
415
+ }
416
+ else {
417
+ Err(PyRuntimeError::new_err(format!("Wrong decimal separator {decimal_separator}. It can only have one character")))
418
+ }
419
+ }
420
+
421
+ #[pyo3(text_signature = "(self, file_path)")]
422
+ /// Validates the CSV file against the validations defined in this CSVValidator.
423
+ /// When finished, it will log a comprehensive summary with the details of the Validation.
424
+ ///
425
+ /// Args:
426
+ /// file_path (str): The path with the CSV file to validate.
427
+ ///
428
+ /// Returns:
429
+ /// bool: True if the file fully complies with all the validations, False otherwise
372
430
  fn validate(&self, file_path: &str) -> PyResult<bool> {
373
431
  // Build the CSV reader
374
432
  let mut rdr = get_reader_from(file_path, self.separator)?;
@@ -378,7 +436,7 @@ impl CSVValidator {
378
436
  info!("Columns names and order are correct");
379
437
  }
380
438
  else {
381
- error!("Expected columns != CSV file columns. Cannot continue with the validations");
439
+ error!("Expected columns != File columns. Cannot continue with rest of the validations");
382
440
  return Ok(false);
383
441
  }
384
442
 
@@ -386,13 +444,15 @@ impl CSVValidator {
386
444
  let mut validation_summaries_map = build_validation_summaries_map(&self.validations);
387
445
  let mut is_valid_file = true;
388
446
  let mut validated_rows = 0;
447
+
448
+ // Iterate over the CSV file and validate each row
389
449
  for result in rdr.records() {
390
450
  let record = result.unwrap();
391
451
  for next_column in zip(record.iter(), self.validations.iter()) {
392
452
  let value = next_column.0;
393
453
  let _column_name = &next_column.1.column_name;
394
454
  for validation in &next_column.1.validations {
395
- let valid = apply_validation(value, validation, &self.regex_map)?;
455
+ let valid = self.apply_validation(value, validation, &self.regex_map)?;
396
456
  if !valid {
397
457
  let validation_summary_list = validation_summaries_map.get_mut(_column_name).unwrap();
398
458
  let validation_summary = validation_summary_list
@@ -423,46 +483,134 @@ impl CSVValidator {
423
483
  column_validation_summaries.push(column_validation_summary);
424
484
  }
425
485
 
426
- // TODO: Decide how to return the results of the validations
427
- let _validation_result_json = serde_json::to_string(&column_validation_summaries).unwrap();
486
+ let validation_process_summary =
487
+ &self.create_validation_process_summary(column_validation_summaries, validated_rows, file_path);
488
+
489
+ // TODO: Decide how to return the results of the validations in JSON
490
+ //let _validation_result_json = serde_json::to_string(&validation_process_summary).unwrap();
428
491
 
429
- let mut failed_columns = HashMap::new();
492
+ info!("");
430
493
  info!("VALIDATIONS SUMMARY");
431
- info!("==================================================================================");
432
- info!("Rows: {} | Columns: {}", validated_rows, column_validation_summaries.len());
433
- for column_validation_summary in column_validation_summaries {
434
- info!("Column: '{}'", column_validation_summary.column_name);
435
- for validation_summary in column_validation_summary.validation_summaries {
436
- let wrong_values_sample = if validation_summary.wrong_values_sample.len() > 0 {
437
- format!(" | Wrong Values Sample: {:?}", validation_summary.wrong_values_sample)
438
- } else {
439
- String::from("" )
440
- };
441
- info!("\tValidation {:?} => Wrong Rows: {}{}", validation_summary.validation,
442
- validation_summary.wrong_rows, wrong_values_sample);
494
+ info!("==================================================");
495
+ info!("FILE: {}", file_path);
496
+ info!("Rows: {} | Columns: {}", validation_process_summary.total_rows, validation_process_summary.total_columns);
497
+
498
+ let correct_columns = validation_process_summary.correct_columns.len();
499
+ let wrong_columns = validation_process_summary.wrong_columns.len();
500
+
501
+ info!("");
502
+ info!("CORRECT COLUMNS: {}/{}", correct_columns, validation_process_summary.total_columns);
503
+ info!("--------------------------------------------------");
504
+ for column_validation_summary in &validation_process_summary.correct_columns {
505
+ info!(" - {}: [✔] OK", column_validation_summary.column_name);
506
+ for validation_summary in column_validation_summary.validation_summaries.iter() {
507
+ info!(" ✔ - {:?}", validation_summary.validation);
508
+ }
509
+ }
510
+
511
+ info!("");
512
+ info!("WRONG COLUMNS: {}/{}", wrong_columns, validation_process_summary.total_columns);
513
+ info!("--------------------------------------------------");
514
+ for column_validation_summary in &validation_process_summary.wrong_columns {
515
+ info!(" - {}: [✖] FAIL", column_validation_summary.column_name);
516
+ for validation_summary in column_validation_summary.validation_summaries.iter() {
443
517
  if validation_summary.wrong_rows > 0 {
444
- let column_name = &column_validation_summary.column_name;
445
- if !failed_columns.contains_key(column_name) {
446
- failed_columns.insert(column_name.clone(), vec!());
447
- }
448
- failed_columns.get_mut(column_name).unwrap().push(validation_summary);
518
+ info!(" ✖ - {:?}", validation_summary.validation);
519
+ info!(" {:?}", validation_summary.get_wrong_values_details());
520
+ }
521
+ else {
522
+ info!(" ✔ - {:?}", validation_summary.validation);
449
523
  }
450
524
  }
451
525
  }
452
526
 
527
+ info!("");
528
+ info!("VALIDATION RESULT");
529
+ info!("--------------------------------------------------");
453
530
  if is_valid_file {
454
- info!("OK: File matches the validations");
531
+ info!("[✔] OK - File matches the validations");
455
532
  }
456
533
  else {
457
- info!("NO OK: File DOESN'T match validations. Failed Validations:");
458
- for (column_name, failed_validations) in failed_columns.into_iter() {
459
- info!("COLUMN '{}' :", column_name);
460
- for validation_summary in failed_validations {
461
- info!("\tValidation {:?} => Wrong Rows: {}", validation_summary.validation, validation_summary.wrong_rows)
534
+ info!("[✖] FAIL: File DOESN'T match all validations");
535
+ }
536
+ info!("");
537
+ Ok(is_valid_file)
538
+ }
539
+ }
540
+
541
+ // Internal methods that are NOT Exposed in Python
542
+ impl CSVValidator {
543
+ fn apply_validation(&self, value: &str, validation: &Validation, regex_map: &HashMap<String, Regex>) -> PyResult<bool> {
544
+ match validation {
545
+ RegularExpression { expression: exp, alias: _ } => {
546
+ let regex = regex_map.get(exp).unwrap();
547
+ Ok(regex.is_match(value))
548
+ },
549
+ Validation::Min(min) => {
550
+ if value.is_empty() {
551
+ Ok(true)
552
+ }
553
+ else {
554
+ let normalized_value = value.replace(self.decimal_separator, ".");
555
+ match normalized_value.parse::<f64>() {
556
+ Ok(value) => Ok(value >= *min),
557
+ Err(_) => Ok(false)
558
+ }
462
559
  }
560
+ },
561
+ Validation::Max(max) => {
562
+ if value.is_empty() {
563
+ Ok(true)
564
+ }
565
+ else {
566
+ let normalized_value = value.replace(self.decimal_separator, ".");
567
+ match normalized_value.parse::<f64>() {
568
+ Ok(value) => Ok(value <= *max),
569
+ Err(_) => Ok(false)
570
+ }
571
+ }
572
+ },
573
+ Validation::Values(values) => {
574
+ let regex_str = get_regex_string_for_values(values);
575
+ let regex = regex_map.get(&regex_str).unwrap();
576
+ Ok(regex.is_match(value))
463
577
  }
578
+ Validation::None => Err(PyRuntimeError::new_err("'None' validation has no implementation"))
579
+ }
580
+ }
581
+
582
+ fn create_validation_process_summary(&self, column_validation_summaries: Vec<ColumnValidationsSummary>, validated_rows: usize, file_path: &str) -> FileValidationSummary {
583
+ let total_rows = validated_rows;
584
+ let total_columns = column_validation_summaries.len();
585
+
586
+ let mut failed_columns = HashSet::new();
587
+ let mut correct_columns = vec![];
588
+ let mut wrong_columns = vec![];
589
+ for column_validation_summary in column_validation_summaries {
590
+ for validation_summary in &column_validation_summary.validation_summaries {
591
+ if validation_summary.wrong_rows > 0 {
592
+ let column_name = &column_validation_summary.column_name;
593
+ if !failed_columns.contains(column_name) {
594
+ failed_columns.insert(column_name.clone());
595
+ }
596
+ }
597
+ }
598
+
599
+ if failed_columns.contains(&column_validation_summary.column_name) {
600
+ wrong_columns.push(column_validation_summary);
601
+ }
602
+ else {
603
+ correct_columns.push(column_validation_summary);
604
+ }
605
+ }
606
+
607
+ FileValidationSummary {
608
+ file_path: file_path.parse().unwrap(),
609
+ total_rows,
610
+ total_columns,
611
+ correct_columns,
612
+ wrong_columns
464
613
  }
465
- Ok(is_valid_file)
466
614
  }
467
615
  }
468
616
 
@@ -634,6 +782,43 @@ mod tests {
634
782
  assert!(validator.validate("test/empty_values.csv").unwrap());
635
783
  }
636
784
 
785
+ #[test]
786
+ fn test_list_of_values_with_special_characters() {
787
+ let definition = String::from("
788
+ columns:
789
+ - name: ColumnA
790
+ values: ['A+', '[B]', 'C$']
791
+ ");
792
+
793
+ let path_of_file_to_validate = "test/test_file_with_special_characters.csv";
794
+ let file_content = "ColumnA\nA+\n[B]\nC$";
795
+ std::fs::write(path_of_file_to_validate, file_content).unwrap();
796
+
797
+ let validator = CSVValidator::from_string(&definition).unwrap();
798
+ assert!(validator.validate(path_of_file_to_validate).unwrap());
799
+ std::fs::remove_file(path_of_file_to_validate).unwrap();
800
+ }
801
+
802
+ #[test]
803
+ fn test_min_max_with_custom_decimal_separator() {
804
+ let definition = String::from("
805
+ columns:
806
+ - name: ColumnA
807
+ min: -5
808
+ max: 27.8
809
+ ");
810
+
811
+ let path_of_file_to_validate = "test/test_file_with_custom_decimals.csv";
812
+ let file_content = "ColumnA\n0\n4,3\n27,8";
813
+ std::fs::write(path_of_file_to_validate, file_content).unwrap();
814
+
815
+ let mut validator = CSVValidator::from_string(&definition).unwrap();
816
+ validator.set_separator(String::from(";")).unwrap();
817
+ validator.set_decimal_separator(String::from(",")).unwrap();
818
+ assert!(validator.validate(path_of_file_to_validate).unwrap());
819
+ std::fs::remove_file(path_of_file_to_validate).unwrap();
820
+ }
821
+
637
822
  #[test]
638
823
  fn test_format_integer() {
639
824
  let test_cases = vec![
File without changes