csv-validation 0.0.7__tar.gz → 0.0.8__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.7"
86
+ version = "0.0.8"
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.7"
3
+ version = "0.0.8"
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.7
3
+ Version: 0.0.8
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Classifier: Programming Language :: Python :: Implementation :: PyPy
@@ -98,7 +98,8 @@ columns:
98
98
  - Available formats:
99
99
  - `integer`: Validates any integer number (positive or negative)
100
100
  - `positive_integer`: Validates positive integer numbers
101
- - More formats will be added in next versions
101
+ - `non_empty`: Validates that field contains at least one character
102
+ - More formats will be added in next versions
102
103
 
103
104
  3. **Minimum Value** (`min`)
104
105
  - Check if numeric fields are greater than or equal to a specified value
@@ -109,6 +110,22 @@ columns:
109
110
  5. **Value Set** (`values`)
110
111
  - Ensure fields only contain values from a predefined set
111
112
 
113
+ ## Global Validations
114
+
115
+ ### empty_not_ok
116
+
117
+ Empty values (empty string '') are considered correct and accepted by default.
118
+ However, if your data must always have some content,
119
+ you can add a global `empty_not_ok` flag at the root level of your YAML definition to automatically
120
+ add the `format: non_empty` validation to all columns:
121
+
122
+ ```yaml
123
+ empty_not_ok: true
124
+ columns:
125
+ - name: Column1
126
+ # other validations...
127
+ ```
128
+
112
129
  ## Output
113
130
 
114
131
  The validation process provides detailed feedback including:
@@ -174,4 +191,4 @@ SOFTWARE.
174
191
 
175
192
  ## Contributing
176
193
 
177
- Contributions are welcome! Please feel free to submit a Pull Request.
194
+ Contributions are welcome! Please feel free to submit a Pull Request.
@@ -88,7 +88,8 @@ columns:
88
88
  - Available formats:
89
89
  - `integer`: Validates any integer number (positive or negative)
90
90
  - `positive_integer`: Validates positive integer numbers
91
- - More formats will be added in next versions
91
+ - `non_empty`: Validates that field contains at least one character
92
+ - More formats will be added in next versions
92
93
 
93
94
  3. **Minimum Value** (`min`)
94
95
  - Check if numeric fields are greater than or equal to a specified value
@@ -99,6 +100,22 @@ columns:
99
100
  5. **Value Set** (`values`)
100
101
  - Ensure fields only contain values from a predefined set
101
102
 
103
+ ## Global Validations
104
+
105
+ ### empty_not_ok
106
+
107
+ Empty values (empty string '') are considered correct and accepted by default.
108
+ However, if your data must always have some content,
109
+ you can add a global `empty_not_ok` flag at the root level of your YAML definition to automatically
110
+ add the `format: non_empty` validation to all columns:
111
+
112
+ ```yaml
113
+ empty_not_ok: true
114
+ columns:
115
+ - name: Column1
116
+ # other validations...
117
+ ```
118
+
102
119
  ## Output
103
120
 
104
121
  The validation process provides detailed feedback including:
@@ -164,4 +181,4 @@ SOFTWARE.
164
181
 
165
182
  ## Contributing
166
183
 
167
- Contributions are welcome! Please feel free to submit a Pull Request.
184
+ Contributions are welcome! Please feel free to submit a Pull Request.
@@ -26,6 +26,35 @@ enum Validation {
26
26
  None
27
27
  }
28
28
 
29
+ impl PartialEq for Validation {
30
+ fn eq(&self, other: &Self) -> bool {
31
+ match (self, other) {
32
+ // Compare RegularExpression enum values deeply
33
+ (
34
+ Validation::RegularExpression { expression: exp1, alias: alias1 },
35
+ Validation::RegularExpression { expression: exp2, alias: alias2 },
36
+ ) => exp1 == exp2 && alias1 == alias2,
37
+
38
+ // Compare Min and Max enums with `f64` values, using custom comparison
39
+ (Validation::Min(v1), Validation::Min(v2)) | (Validation::Max(v1), Validation::Max(v2)) => {
40
+ (v1 - v2).abs() < f64::EPSILON // Tolerates small differences in floats
41
+ },
42
+
43
+ // Compare Values variants by comparing the vectors
44
+ (Validation::Values(values1), Validation::Values(values2)) => {
45
+ values1 == values2
46
+ },
47
+
48
+ // Compare None variants (no associated data)
49
+ (Validation::None, Validation::None) => true,
50
+
51
+ // If enums don't match, they are not equal
52
+ _ => false,
53
+ }
54
+ }
55
+ }
56
+
57
+
29
58
  #[derive(Clone)]
30
59
  struct ColumnValidations {
31
60
  column_name: String,
@@ -88,7 +117,7 @@ fn apply_validation(value: &str, validation: &Validation, regex_map: &HashMap<St
88
117
  }
89
118
 
90
119
  fn get_regex_string_for_values(values: &Vec<String>) -> String {
91
- values.join("|")
120
+ format!("^$|^(?:{})$", values.join("|"))
92
121
  }
93
122
 
94
123
  /// Infers the file compression type and returns the corresponding buffered reader
@@ -207,13 +236,31 @@ fn get_validations(definition_string: &str) -> PyResult<Vec<ColumnValidations>>
207
236
  column_validations.push(new_validations);
208
237
  }
209
238
 
239
+ // If the global flag empty_not_ok is present, we automatically add an extra validation in each column to check that
240
+ // there are not empty values on that column
241
+ let empty_not_ok =
242
+ config[0]["empty_not_ok"].as_bool().map_or(false, |value| value);
243
+ if empty_not_ok {
244
+ let non_empty_validation = RegularExpression {
245
+ expression: String::from("^.+$"),
246
+ alias: String::from("non_empty")
247
+ };
248
+ for column_validations in column_validations.iter_mut() {
249
+ column_validations.validations.push(non_empty_validation.clone());
250
+ }
251
+ }
252
+
210
253
  Ok(column_validations)
211
254
  }
212
255
 
213
256
  fn get_regex_for_format(format: &str) -> PyResult<String> {
214
257
  match format {
215
- "integer" => Ok(String::from("^-?\\d+$")),
216
- "positive_integer" => Ok(String::from("^\\d+$")),
258
+ "integer" => Ok(String::from("^$|^-?\\d+$")),
259
+ "positive integer" => Ok(String::from("^$|^\\d+$")),
260
+ "decimal" => Ok(String::from("^$|^-?\\d+(\\.\\d+)?$")),
261
+ "positive decimal" => Ok(String::from("^$|^\\d+(\\.\\d+)?$")),
262
+ "decimal scientific" => Ok(String::from("^$|^-?\\d+(\\.\\d+)?([eE][-+]?\\d+)?$")),
263
+ "non_empty" => Ok(String::from("^.+$")),
217
264
  _ => Err(PyRuntimeError::new_err(format!("Unknown format: {format}")))
218
265
  }
219
266
  }
@@ -231,8 +278,8 @@ fn validate_column_names(reader: &mut Reader<Box<dyn Read>>, validations: &Vec<C
231
278
  if expected_column_names.len() != headers.len() {
232
279
  let expected_columns_set: HashSet<String> = expected_column_names.iter().cloned().collect();
233
280
  let headers_set: HashSet<String> = headers.iter().cloned().collect();
234
- debug!("File headers not in expected columns: {:?}", headers_set.difference(&expected_columns_set));
235
- debug!("Columns in expected columns not in file headers: {:?}", expected_columns_set.difference(&headers_set));
281
+ debug!("These column names in the CSV file were not expected: {:?}", headers_set.difference(&expected_columns_set));
282
+ debug!("These expected column names were missing in the CSV file: {:?}", expected_columns_set.difference(&headers_set));
236
283
  }
237
284
  else {
238
285
  for (expected_column, header) in zip(expected_column_names, headers) {
@@ -301,13 +348,14 @@ impl CSVValidator {
301
348
  info!("Columns names and order are correct");
302
349
  }
303
350
  else {
304
- error!("Expected columns != Real columns");
351
+ error!("Expected columns != CSV file columns. Cannot continue with the validations");
305
352
  return Ok(false);
306
353
  }
307
354
 
308
355
  // Second validation: If column names match, check if also the values match the validations
309
356
  let mut validation_summaries_map = build_validation_summaries_map(&self.validations);
310
357
  let mut is_valid_file = true;
358
+ let mut validated_rows = 0;
311
359
  for result in rdr.records() {
312
360
  let record = result.unwrap();
313
361
  for next_column in zip(record.iter(), self.validations.iter()) {
@@ -318,9 +366,10 @@ impl CSVValidator {
318
366
  if !valid {
319
367
  let validation_summary_list = validation_summaries_map.get_mut(_column_name).unwrap();
320
368
  let validation_summary = validation_summary_list
321
- .iter_mut()
322
- .find(|val_sum|
323
- std::mem::discriminant(&val_sum.validation) == std::mem::discriminant(validation)).unwrap();
369
+ .iter_mut()
370
+ .find(|val_sum| val_sum.validation == *validation)
371
+ .unwrap();
372
+
324
373
  validation_summary.wrong_rows += 1;
325
374
  if validation_summary.wrong_values_sample.len() < MAX_SAMPLE_SIZE as usize {
326
375
  validation_summary.wrong_values_sample.push(value.to_string());
@@ -329,6 +378,7 @@ impl CSVValidator {
329
378
  is_valid_file = is_valid_file && valid;
330
379
  }
331
380
  }
381
+ validated_rows = validated_rows + 1;
332
382
  }
333
383
 
334
384
  // Fill the ColumnValidationSummary for each column
@@ -346,17 +396,18 @@ impl CSVValidator {
346
396
  // TODO: Decide how to return the results of the validations
347
397
  let _validation_result_json = serde_json::to_string(&column_validation_summaries).unwrap();
348
398
 
349
- debug!("VALIDATIONS SUMMARY");
350
- debug!("==================================================================================");
399
+ info!("VALIDATIONS SUMMARY");
400
+ info!("==================================================================================");
401
+ info!("Rows: {} | Columns: {}", validated_rows, column_validation_summaries.len());
351
402
  for column_validation_summary in column_validation_summaries {
352
- debug!("Column: '{}'", column_validation_summary.column_name);
403
+ info!("Column: '{}'", column_validation_summary.column_name);
353
404
  for validation_summary in column_validation_summary.validation_summaries {
354
405
  let wrong_values_sample = if validation_summary.wrong_values_sample.len() > 0 {
355
406
  format!(" | Wrong Values Sample: {:?}", validation_summary.wrong_values_sample)
356
407
  } else {
357
408
  String::from("" )
358
409
  };
359
- debug!("\tValidation {:?} => Wrong Rows: {}{}", validation_summary.validation,
410
+ info!("\tValidation {:?} => Wrong Rows: {}{}", validation_summary.validation,
360
411
  validation_summary.wrong_rows, wrong_values_sample);
361
412
  }
362
413
  }
@@ -371,90 +422,35 @@ impl CSVValidator {
371
422
  }
372
423
  }
373
424
 
374
- // Keep the existing functions for backward compatibility
375
- #[pyfunction]
376
- fn validate_with_file(path: &str, definition_path: &str) -> PyResult<bool> {
377
- info!("Validating file {} against definition file {}", path, definition_path);
378
- let validator = CSVValidator::from_file(definition_path)?;
379
- validator.validate(path)
380
- }
381
-
382
- #[pyfunction]
383
- fn validate(path: &str, definition_string: String) -> PyResult<bool> {
384
- debug!("Validating file {} against definition:\n {}", path, definition_string);
385
- let validator = CSVValidator::from_string(&definition_string)?;
386
- validator.validate(path)
387
- }
388
-
389
425
  /// A Python module implemented in Rust.
390
426
  #[pymodule]
391
427
  fn csv_validation(m: &Bound<'_, PyModule>) -> PyResult<()> {
392
428
  pyo3_log::init();
393
429
  m.add_class::<CSVValidator>()?;
394
- m.add_function(wrap_pyfunction!(validate, m)?)?;
395
- m.add_function(wrap_pyfunction!(validate_with_file, m)?)?;
396
430
  Ok(())
397
431
  }
398
432
 
399
433
  #[cfg(test)]
400
434
  mod tests {
401
435
  use simple_logger::SimpleLogger;
402
- use crate::{validate, validate_with_file, CSVValidator};
436
+ use crate::CSVValidator;
403
437
 
404
438
  #[test]
405
439
  fn init_logger() {
406
440
  SimpleLogger::new().init().unwrap();
407
441
  }
408
442
 
409
- #[test]
410
- fn test_validate_csv_with_file() {
411
- assert!(validate_with_file("test/test_file.csv", "test/test_validations.yml").unwrap());
412
- }
413
-
414
- #[test]
415
- fn test_validate_csv_gz_with_file() {
416
- assert!(validate_with_file("test/test_file.csv.gz", "test/test_validations.yml").unwrap());
417
- }
418
-
419
443
  #[test]
420
444
  fn test_wrong_headers() {
421
445
  let definition = String::from("
422
446
  columns:
423
447
  - name: First Column
424
448
  - name: Second Column
425
- - name: Wrong Column
426
- - name: Expected Column Not In File
427
- ");
428
- assert!(!validate("test/test_file.csv", definition).unwrap());
429
- }
430
-
431
- #[test]
432
- fn test_format_validation() {
433
- let definition = String::from("
434
- columns:
435
- - name: First Column
436
- - name: Second Column
437
- - name: Third Column
438
- format: integer
439
- ");
440
- assert!(validate("test/test_file.csv", definition).unwrap());
441
- }
442
-
443
- #[test]
444
- fn test_validate_csv() {
445
- let definition = String::from("
446
- columns:
447
- - name: First Column
448
- regex: ^.+$
449
- - name: Second Column
450
- values: [one_value, or_another]
451
- - name: Third Column
452
- regex: ^-?[0-9]+$
453
- min: -23
454
- max: 2000
449
+ - name: Different Column name in file
450
+ - name: Missing Column Not In File
455
451
  ");
456
-
457
- assert!(validate("test/test_file.csv", definition).unwrap());
452
+ let validator = CSVValidator::from_string(&definition).unwrap();
453
+ assert!(!validator.validate("test/test_file.csv").unwrap());
458
454
  }
459
455
 
460
456
  #[test]
@@ -495,7 +491,7 @@ mod tests {
495
491
  - name: Name
496
492
  regex: ^[A-Za-z\\s]{2,50}$
497
493
  - name: Age
498
- format: positive_integer
494
+ format: positive integer
499
495
  min: 0
500
496
  max: 120
501
497
  - name: Status
@@ -506,6 +502,35 @@ mod tests {
506
502
  assert!(!validator.validate("test/test_file.csv").unwrap());
507
503
  }
508
504
 
505
+ #[test]
506
+ fn test_empty_ok_by_default() {
507
+ let definition_empty_ok = String::from("
508
+ columns:
509
+ - name: First Column
510
+ format: positive integer
511
+ - name: Second Column
512
+ values: ['A', 'B', 'C']
513
+ ");
514
+ let validator = CSVValidator::from_string(&definition_empty_ok).unwrap();
515
+ // This is OK as we didn't mention anything about empty values
516
+ assert!(validator.validate("test/empty_values.csv").unwrap());
517
+ }
518
+
519
+ #[test]
520
+ fn test_empty_not_ok() {
521
+ let definition_empty_ok = String::from("
522
+ empty_not_ok: true
523
+ columns:
524
+ - name: First Column
525
+ format: positive integer
526
+ - name: Second Column
527
+ values: ['A', 'B', 'C']
528
+ ");
529
+ let validator = CSVValidator::from_string(&definition_empty_ok).unwrap();
530
+ // Validation is not OK as the file contains empty values
531
+ assert!(!validator.validate("test/empty_values.csv").unwrap());
532
+ }
533
+
509
534
  #[test]
510
535
  fn test_csv_validator_invalid_format() {
511
536
  let definition = String::from("
@@ -537,4 +562,117 @@ mod tests {
537
562
  let definition = String::from("");
538
563
  assert!(CSVValidator::from_string(&definition).is_err());
539
564
  }
565
+
566
+ #[test]
567
+ fn test_format_integer() {
568
+ let test_cases = vec![
569
+ ("42", true),
570
+ ("-42", true),
571
+ ("0", true),
572
+ ("", true), // Empty values are allowed by default
573
+ ("3.14", false),
574
+ ("abc", false),
575
+ ("123abc", false),
576
+ ];
577
+
578
+ test_format_validation("integer", test_cases);
579
+ }
580
+
581
+ #[test]
582
+ fn test_format_positive_integer() {
583
+ let test_cases = vec![
584
+ ("42", true),
585
+ ("0", true),
586
+ ("", true), // Empty values are allowed by default
587
+ ("-42", false),
588
+ ("3.14", false),
589
+ ("abc", false),
590
+ ("123abc", false),
591
+ ];
592
+
593
+ test_format_validation("positive integer", test_cases);
594
+ }
595
+
596
+ #[test]
597
+ fn test_format_decimal() {
598
+ let test_cases = vec![
599
+ ("42", true),
600
+ ("42.0", true),
601
+ ("42.42", true),
602
+ ("-42.42", true),
603
+ ("0.0", true),
604
+ ("", true), // Empty values are allowed by default
605
+ ("abc", false),
606
+ ("12.34.56", false),
607
+ ("12e4", false),
608
+ ];
609
+
610
+ test_format_validation("decimal", test_cases);
611
+ }
612
+
613
+ #[test]
614
+ fn test_format_positive_decimal() {
615
+ let test_cases = vec![
616
+ ("42", true),
617
+ ("42.0", true),
618
+ ("42.42", true),
619
+ ("0.0", true),
620
+ ("", true), // Empty values are allowed by default
621
+ ("-42.42", false),
622
+ ("abc", false),
623
+ ("12.34.56", false),
624
+ ("12e4", false),
625
+ ];
626
+
627
+ test_format_validation("positive decimal", test_cases);
628
+ }
629
+
630
+ #[test]
631
+ fn test_format_decimal_scientific() {
632
+ let test_cases = vec![
633
+ ("42", true),
634
+ ("42.0", true),
635
+ ("42.42", true),
636
+ ("-42.42", true),
637
+ ("1.234e5", true),
638
+ ("1.234e+5", true),
639
+ ("1.234e-5", true),
640
+ ("1.234E5", true),
641
+ ("", true), // Empty values are allowed by default
642
+ ("abc", false),
643
+ ("12.34.56", false),
644
+ ("1.234e", false),
645
+ ("e5", false),
646
+ ("1.234e+", false),
647
+ ];
648
+
649
+ test_format_validation("decimal scientific", test_cases);
650
+ }
651
+
652
+ // Helper function to test format validations
653
+ fn test_format_validation(format: &str, test_cases: Vec<(&str, bool)>) {
654
+ let definition = format!("
655
+ columns:
656
+ - name: Test
657
+ format: {}
658
+ ", format);
659
+
660
+ let validator = CSVValidator::from_string(&definition).unwrap();
661
+
662
+ for (value, expected) in test_cases {
663
+ let test_csv = format!("Test\n{}", value);
664
+ let temp_file = format!("test/temp_format_test_{}.csv", format.replace(" ", "_"));
665
+ std::fs::write(&temp_file, test_csv).unwrap();
666
+
667
+ let result = validator.validate(&temp_file).unwrap();
668
+ assert_eq!(
669
+ result,
670
+ expected,
671
+ "Format '{}' validation failed for value '{}': expected {}, got {}",
672
+ format, value, expected, result
673
+ );
674
+
675
+ std::fs::remove_file(&temp_file).unwrap();
676
+ }
677
+ }
540
678
  }
@@ -0,0 +1,5 @@
1
+ First Column,Second Column
2
+ 123,A
3
+ ,B
4
+ 456,
5
+ 789,C
@@ -1,3 +1,4 @@
1
+ empty_not_ok: true
1
2
  columns:
2
3
  - name: First Column
3
4
  regex: ^.+$
File without changes
File without changes