csv-validation 0.0.7__tar.gz → 0.0.9__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.9"
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.9"
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.9
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Classifier: Programming Language :: Python :: Implementation :: PyPy
@@ -8,7 +8,7 @@ License-File: LICENSE
8
8
  Requires-Python: >=3.8
9
9
  Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
10
10
 
11
- # CSV Validation
11
+ # CSV Validation Library
12
12
 
13
13
  Blazing fast format validations for your CSV files
14
14
 
@@ -59,6 +59,10 @@ columns:
59
59
  """
60
60
 
61
61
  validator = CSVValidator.from_string(validation_rules)
62
+ # Optionally set a custom column separator
63
+ validator.set_separator(";") # Default is comma (,)
64
+
65
+ # Validate a CSV file
62
66
  is_valid = validator.validate("data.csv")
63
67
  ```
64
68
 
@@ -98,7 +102,8 @@ columns:
98
102
  - Available formats:
99
103
  - `integer`: Validates any integer number (positive or negative)
100
104
  - `positive_integer`: Validates positive integer numbers
101
- - More formats will be added in next versions
105
+ - `non_empty`: Validates that field contains at least one character
106
+ - More formats will be added in next versions
102
107
 
103
108
  3. **Minimum Value** (`min`)
104
109
  - Check if numeric fields are greater than or equal to a specified value
@@ -109,13 +114,49 @@ columns:
109
114
  5. **Value Set** (`values`)
110
115
  - Ensure fields only contain values from a predefined set
111
116
 
112
- ## Output
117
+ ## Global Validations
118
+
119
+ ### empty_not_ok
120
+
121
+ Empty values (empty string '') are considered correct and accepted by default.
122
+ However, if your data must always have some content,
123
+ you can add a global `empty_not_ok` flag at the root level of your YAML definition to automatically
124
+ add the `format: non_empty` validation to all columns:
125
+
126
+ ```yaml
127
+ empty_not_ok: true
128
+ columns:
129
+ - name: Column1
130
+ # other validations...
131
+ ```
132
+
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
144
+
145
+ By default, the library uses comma (,) as the column separator. You can change this using the `set_separator` method:
146
+
147
+ ```python
148
+ validator = CSVValidator.from_file("rules.yml")
149
+ validator.set_separator(";") # Use semicolon as separator
150
+ validator.set_separator("\t") # Use tab as separator
151
+ ```
152
+
153
+ ## Error Handling
113
154
 
114
- The validation process provides detailed feedback including:
115
- - Overall validation status (true/false)
116
- - Number of invalid rows per validation rule
117
- - Sample of invalid values for debugging
118
- - Detailed logging for troubleshooting
155
+ The library provides detailed validation reports through Python's logging system. When a validation fails, you'll get information about:
156
+ - Which columns failed validation
157
+ - What type of validation failed
158
+ - Sample of invalid values
159
+ - Number of rows that failed each validation
119
160
 
120
161
  ## Development
121
162
 
@@ -125,7 +166,7 @@ The validation process provides detailed feedback including:
125
166
  - Python 3.6+ (for Python bindings)
126
167
  - Cargo and standard Rust tooling
127
168
 
128
- ### Building from Source
169
+ ### Building from Source (Rust version)
129
170
 
130
171
  ```bash
131
172
  # Clone the repository
@@ -174,4 +215,4 @@ SOFTWARE.
174
215
 
175
216
  ## Contributing
176
217
 
177
- Contributions are welcome! Please feel free to submit a Pull Request.
218
+ Contributions are welcome! Please feel free to submit a Pull Request.
@@ -1,4 +1,4 @@
1
- # CSV Validation
1
+ # CSV Validation Library
2
2
 
3
3
  Blazing fast format validations for your CSV files
4
4
 
@@ -49,6 +49,10 @@ columns:
49
49
  """
50
50
 
51
51
  validator = CSVValidator.from_string(validation_rules)
52
+ # Optionally set a custom column separator
53
+ validator.set_separator(";") # Default is comma (,)
54
+
55
+ # Validate a CSV file
52
56
  is_valid = validator.validate("data.csv")
53
57
  ```
54
58
 
@@ -88,7 +92,8 @@ columns:
88
92
  - Available formats:
89
93
  - `integer`: Validates any integer number (positive or negative)
90
94
  - `positive_integer`: Validates positive integer numbers
91
- - More formats will be added in next versions
95
+ - `non_empty`: Validates that field contains at least one character
96
+ - More formats will be added in next versions
92
97
 
93
98
  3. **Minimum Value** (`min`)
94
99
  - Check if numeric fields are greater than or equal to a specified value
@@ -99,13 +104,49 @@ columns:
99
104
  5. **Value Set** (`values`)
100
105
  - Ensure fields only contain values from a predefined set
101
106
 
102
- ## Output
107
+ ## Global Validations
108
+
109
+ ### empty_not_ok
110
+
111
+ Empty values (empty string '') are considered correct and accepted by default.
112
+ However, if your data must always have some content,
113
+ you can add a global `empty_not_ok` flag at the root level of your YAML definition to automatically
114
+ add the `format: non_empty` validation to all columns:
115
+
116
+ ```yaml
117
+ empty_not_ok: true
118
+ columns:
119
+ - name: Column1
120
+ # other validations...
121
+ ```
122
+
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
134
+
135
+ By default, the library uses comma (,) as the column separator. You can change this using the `set_separator` method:
136
+
137
+ ```python
138
+ validator = CSVValidator.from_file("rules.yml")
139
+ validator.set_separator(";") # Use semicolon as separator
140
+ validator.set_separator("\t") # Use tab as separator
141
+ ```
142
+
143
+ ## Error Handling
103
144
 
104
- The validation process provides detailed feedback including:
105
- - Overall validation status (true/false)
106
- - Number of invalid rows per validation rule
107
- - Sample of invalid values for debugging
108
- - Detailed logging for troubleshooting
145
+ The library provides detailed validation reports through Python's logging system. When a validation fails, you'll get information about:
146
+ - Which columns failed validation
147
+ - What type of validation failed
148
+ - Sample of invalid values
149
+ - Number of rows that failed each validation
109
150
 
110
151
  ## Development
111
152
 
@@ -115,7 +156,7 @@ The validation process provides detailed feedback including:
115
156
  - Python 3.6+ (for Python bindings)
116
157
  - Cargo and standard Rust tooling
117
158
 
118
- ### Building from Source
159
+ ### Building from Source (Rust version)
119
160
 
120
161
  ```bash
121
162
  # Clone the repository
@@ -164,4 +205,4 @@ SOFTWARE.
164
205
 
165
206
  ## Contributing
166
207
 
167
- Contributions are welcome! Please feel free to submit a Pull Request.
208
+ Contributions are welcome! Please feel free to submit a Pull Request.
@@ -5,7 +5,7 @@ use std::fs::File;
5
5
  use std::io::{BufReader, Read};
6
6
  use std::iter::zip;
7
7
  use std::path::Path;
8
- use csv::Reader;
8
+ use csv::{Reader, ReaderBuilder};
9
9
  use flate2::bufread::GzDecoder;
10
10
  use log::{debug, error, info};
11
11
  use pyo3::exceptions::{PyRuntimeError};
@@ -16,6 +16,7 @@ use serde::{Deserialize, Serialize};
16
16
  use crate::Validation::{RegularExpression};
17
17
 
18
18
  const MAX_SAMPLE_SIZE:u16 = 10;
19
+ const DEFAULT_COLUMN_SEPARATOR:u8 = b',';
19
20
 
20
21
  #[derive(Debug, Clone, Serialize, Deserialize)]
21
22
  enum Validation {
@@ -26,6 +27,35 @@ enum Validation {
26
27
  None
27
28
  }
28
29
 
30
+ impl PartialEq for Validation {
31
+ fn eq(&self, other: &Self) -> bool {
32
+ match (self, other) {
33
+ // Compare RegularExpression enum values deeply
34
+ (
35
+ Validation::RegularExpression { expression: exp1, alias: alias1 },
36
+ Validation::RegularExpression { expression: exp2, alias: alias2 },
37
+ ) => exp1 == exp2 && alias1 == alias2,
38
+
39
+ // Compare Min and Max enums with `f64` values, using custom comparison
40
+ (Validation::Min(v1), Validation::Min(v2)) | (Validation::Max(v1), Validation::Max(v2)) => {
41
+ (v1 - v2).abs() < f64::EPSILON // Tolerates small differences in floats
42
+ },
43
+
44
+ // Compare Values variants by comparing the vectors
45
+ (Validation::Values(values1), Validation::Values(values2)) => {
46
+ values1 == values2
47
+ },
48
+
49
+ // Compare None variants (no associated data)
50
+ (Validation::None, Validation::None) => true,
51
+
52
+ // If enums don't match, they are not equal
53
+ _ => false,
54
+ }
55
+ }
56
+ }
57
+
58
+
29
59
  #[derive(Clone)]
30
60
  struct ColumnValidations {
31
61
  column_name: String,
@@ -88,20 +118,24 @@ fn apply_validation(value: &str, validation: &Validation, regex_map: &HashMap<St
88
118
  }
89
119
 
90
120
  fn get_regex_string_for_values(values: &Vec<String>) -> String {
91
- values.join("|")
121
+ format!("^$|^(?:{})$", values.join("|"))
92
122
  }
93
123
 
94
124
  /// Infers the file compression type and returns the corresponding buffered reader
95
- fn get_reader_from(path: &str) -> PyResult<Reader<Box<dyn Read>>> {
125
+ fn get_reader_from(path: &str, separator: u8) -> PyResult<Reader<Box<dyn Read>>> {
96
126
  let buf_reader = BufReader::new(File::open(Path::new(path))?);
97
127
  if is_gzip_file(path)? {
98
128
  debug!("File is gzipped");
99
129
  let read_capacity = 10 * 1024_usize.pow(2);
100
130
  let reader = BufReader::with_capacity(read_capacity, GzDecoder::new(buf_reader));
101
- Ok(Reader::from_reader(Box::new(reader)))
131
+ Ok(ReaderBuilder::new()
132
+ .delimiter(separator)
133
+ .from_reader(Box::new(reader)))
102
134
  }
103
135
  else {
104
- Ok(Reader::from_reader(Box::new(buf_reader)))
136
+ Ok(ReaderBuilder::new()
137
+ .delimiter(separator)
138
+ .from_reader(Box::new(buf_reader)))
105
139
  }
106
140
  }
107
141
 
@@ -207,13 +241,32 @@ fn get_validations(definition_string: &str) -> PyResult<Vec<ColumnValidations>>
207
241
  column_validations.push(new_validations);
208
242
  }
209
243
 
244
+ // If the global flag empty_not_ok is present, we automatically add an extra validation in each column to check that
245
+ // there are not empty values on that column
246
+ let empty_not_ok =
247
+ config[0]["empty_not_ok"].as_bool().map_or(false, |value| value);
248
+ if empty_not_ok {
249
+ let non_empty_validation = RegularExpression {
250
+ expression: String::from("^.+$"),
251
+ alias: String::from("non_empty")
252
+ };
253
+ for column_validations in column_validations.iter_mut() {
254
+ column_validations.validations.push(non_empty_validation.clone());
255
+ }
256
+ }
257
+
210
258
  Ok(column_validations)
211
259
  }
212
260
 
213
261
  fn get_regex_for_format(format: &str) -> PyResult<String> {
214
262
  match format {
215
- "integer" => Ok(String::from("^-?\\d+$")),
216
- "positive_integer" => Ok(String::from("^\\d+$")),
263
+ "integer" => Ok(String::from("^$|^-?\\d+$")),
264
+ "positive integer" => Ok(String::from("^$|^\\d+$")),
265
+ "decimal" => Ok(String::from("^$|^-?\\d+(\\.\\d+)?$")),
266
+ "positive decimal point" | "positive decimal" => Ok(String::from("^$|^\\d+(\\.\\d+)?$")),
267
+ "positive decimal comma" => Ok(String::from("^$|^\\d+(,\\d+)?$")),
268
+ "decimal scientific" => Ok(String::from("^$|^-?\\d+(\\.\\d+)?([eE][-+]?\\d+)?$")),
269
+ "non_empty" => Ok(String::from("^.+$")),
217
270
  _ => Err(PyRuntimeError::new_err(format!("Unknown format: {format}")))
218
271
  }
219
272
  }
@@ -229,15 +282,17 @@ fn validate_column_names(reader: &mut Reader<Box<dyn Read>>, validations: &Vec<C
229
282
 
230
283
  if expected_column_names != headers {
231
284
  if expected_column_names.len() != headers.len() {
285
+ info!("The number of columns in the CSV file doesn't match the validations:");
232
286
  let expected_columns_set: HashSet<String> = expected_column_names.iter().cloned().collect();
233
287
  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));
288
+ info!("These column names in the CSV file were not expected: {:?}", headers_set.difference(&expected_columns_set));
289
+ info!("These expected column names were missing in the CSV file: {:?}", expected_columns_set.difference(&headers_set));
236
290
  }
237
291
  else {
292
+ info!("The CSV file has the same number of columns than the validations but some names are different:");
238
293
  for (expected_column, header) in zip(expected_column_names, headers) {
239
294
  if expected_column != header {
240
- debug!("{:?} != {:?}", expected_column, header);
295
+ info!("{:?} != {:?}", expected_column, header);
241
296
  }
242
297
  }
243
298
  }
@@ -249,7 +304,8 @@ fn validate_column_names(reader: &mut Reader<Box<dyn Read>>, validations: &Vec<C
249
304
  #[pyclass]
250
305
  struct CSVValidator {
251
306
  validations: Vec<ColumnValidations>,
252
- regex_map: HashMap<String, Regex>
307
+ regex_map: HashMap<String, Regex>,
308
+ separator: u8
253
309
  }
254
310
 
255
311
  #[pymethods]
@@ -258,7 +314,8 @@ impl CSVValidator {
258
314
  fn new() -> Self {
259
315
  CSVValidator {
260
316
  validations: Vec::new(),
261
- regex_map: HashMap::new()
317
+ regex_map: HashMap::new(),
318
+ separator: DEFAULT_COLUMN_SEPARATOR
262
319
  }
263
320
  }
264
321
 
@@ -289,25 +346,36 @@ impl CSVValidator {
289
346
  }
290
347
  }
291
348
 
292
- Ok(CSVValidator { validations, regex_map })
349
+ Ok(CSVValidator { validations, regex_map, separator: DEFAULT_COLUMN_SEPARATOR })
350
+ }
351
+
352
+ fn set_separator(&mut self, separator: String) -> PyResult<()> {
353
+ if separator.len() == 1 {
354
+ self.separator = separator.chars().next().unwrap() as u8;
355
+ Ok(())
356
+ }
357
+ else {
358
+ Err(PyRuntimeError::new_err(format!("Wrong separator {separator}. It can only have one character")))
359
+ }
293
360
  }
294
361
 
295
362
  fn validate(&self, file_path: &str) -> PyResult<bool> {
296
363
  // Build the CSV reader
297
- let mut rdr = get_reader_from(file_path)?;
364
+ let mut rdr = get_reader_from(file_path, self.separator)?;
298
365
 
299
366
  // First validation: Ensure column names and order are exactly as expected
300
367
  if validate_column_names(&mut rdr, &self.validations)? {
301
368
  info!("Columns names and order are correct");
302
369
  }
303
370
  else {
304
- error!("Expected columns != Real columns");
371
+ error!("Expected columns != CSV file columns. Cannot continue with the validations");
305
372
  return Ok(false);
306
373
  }
307
374
 
308
375
  // Second validation: If column names match, check if also the values match the validations
309
376
  let mut validation_summaries_map = build_validation_summaries_map(&self.validations);
310
377
  let mut is_valid_file = true;
378
+ let mut validated_rows = 0;
311
379
  for result in rdr.records() {
312
380
  let record = result.unwrap();
313
381
  for next_column in zip(record.iter(), self.validations.iter()) {
@@ -318,9 +386,10 @@ impl CSVValidator {
318
386
  if !valid {
319
387
  let validation_summary_list = validation_summaries_map.get_mut(_column_name).unwrap();
320
388
  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();
389
+ .iter_mut()
390
+ .find(|val_sum| val_sum.validation == *validation)
391
+ .unwrap();
392
+
324
393
  validation_summary.wrong_rows += 1;
325
394
  if validation_summary.wrong_values_sample.len() < MAX_SAMPLE_SIZE as usize {
326
395
  validation_summary.wrong_values_sample.push(value.to_string());
@@ -329,6 +398,7 @@ impl CSVValidator {
329
398
  is_valid_file = is_valid_file && valid;
330
399
  }
331
400
  }
401
+ validated_rows = validated_rows + 1;
332
402
  }
333
403
 
334
404
  // Fill the ColumnValidationSummary for each column
@@ -346,18 +416,27 @@ impl CSVValidator {
346
416
  // TODO: Decide how to return the results of the validations
347
417
  let _validation_result_json = serde_json::to_string(&column_validation_summaries).unwrap();
348
418
 
349
- debug!("VALIDATIONS SUMMARY");
350
- debug!("==================================================================================");
419
+ let mut failed_columns = HashMap::new();
420
+ info!("VALIDATIONS SUMMARY");
421
+ info!("==================================================================================");
422
+ info!("Rows: {} | Columns: {}", validated_rows, column_validation_summaries.len());
351
423
  for column_validation_summary in column_validation_summaries {
352
- debug!("Column: '{}'", column_validation_summary.column_name);
424
+ info!("Column: '{}'", column_validation_summary.column_name);
353
425
  for validation_summary in column_validation_summary.validation_summaries {
354
426
  let wrong_values_sample = if validation_summary.wrong_values_sample.len() > 0 {
355
427
  format!(" | Wrong Values Sample: {:?}", validation_summary.wrong_values_sample)
356
428
  } else {
357
429
  String::from("" )
358
430
  };
359
- debug!("\tValidation {:?} => Wrong Rows: {}{}", validation_summary.validation,
431
+ info!("\tValidation {:?} => Wrong Rows: {}{}", validation_summary.validation,
360
432
  validation_summary.wrong_rows, wrong_values_sample);
433
+ if validation_summary.wrong_rows > 0 {
434
+ let column_name = &column_validation_summary.column_name;
435
+ if !failed_columns.contains_key(column_name) {
436
+ failed_columns.insert(column_name.clone(), vec!());
437
+ }
438
+ failed_columns.get_mut(column_name).unwrap().push(validation_summary);
439
+ }
361
440
  }
362
441
  }
363
442
 
@@ -365,96 +444,47 @@ impl CSVValidator {
365
444
  info!("OK: File matches the validations");
366
445
  }
367
446
  else {
368
- info!("NO OK: File DOESN'T match validations");
447
+ info!("NO OK: File DOESN'T match validations. Failed Validations:");
448
+ for (column_name, failed_validations) in failed_columns.into_iter() {
449
+ info!("COLUMN '{}' :", column_name);
450
+ for validation_summary in failed_validations {
451
+ info!("\tValidation {:?} => Wrong Rows: {}", validation_summary.validation, validation_summary.wrong_rows)
452
+ }
453
+ }
369
454
  }
370
455
  Ok(is_valid_file)
371
456
  }
372
457
  }
373
458
 
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
459
  /// A Python module implemented in Rust.
390
460
  #[pymodule]
391
461
  fn csv_validation(m: &Bound<'_, PyModule>) -> PyResult<()> {
392
462
  pyo3_log::init();
393
463
  m.add_class::<CSVValidator>()?;
394
- m.add_function(wrap_pyfunction!(validate, m)?)?;
395
- m.add_function(wrap_pyfunction!(validate_with_file, m)?)?;
396
464
  Ok(())
397
465
  }
398
466
 
399
467
  #[cfg(test)]
400
468
  mod tests {
401
469
  use simple_logger::SimpleLogger;
402
- use crate::{validate, validate_with_file, CSVValidator};
470
+ use crate::CSVValidator;
403
471
 
404
472
  #[test]
405
473
  fn init_logger() {
406
474
  SimpleLogger::new().init().unwrap();
407
475
  }
408
476
 
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
477
  #[test]
420
478
  fn test_wrong_headers() {
421
479
  let definition = String::from("
422
480
  columns:
423
481
  - name: First Column
424
482
  - 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
483
+ - name: Different Column name in file
484
+ - name: Missing Column Not In File
455
485
  ");
456
-
457
- assert!(validate("test/test_file.csv", definition).unwrap());
486
+ let validator = CSVValidator::from_string(&definition).unwrap();
487
+ assert!(!validator.validate("test/test_file.csv").unwrap());
458
488
  }
459
489
 
460
490
  #[test]
@@ -495,7 +525,7 @@ mod tests {
495
525
  - name: Name
496
526
  regex: ^[A-Za-z\\s]{2,50}$
497
527
  - name: Age
498
- format: positive_integer
528
+ format: positive integer
499
529
  min: 0
500
530
  max: 120
501
531
  - name: Status
@@ -506,6 +536,35 @@ mod tests {
506
536
  assert!(!validator.validate("test/test_file.csv").unwrap());
507
537
  }
508
538
 
539
+ #[test]
540
+ fn test_empty_ok_by_default() {
541
+ let definition_empty_ok = String::from("
542
+ columns:
543
+ - name: First Column
544
+ format: positive integer
545
+ - name: Second Column
546
+ values: ['A', 'B', 'C']
547
+ ");
548
+ let validator = CSVValidator::from_string(&definition_empty_ok).unwrap();
549
+ // This is OK as we didn't mention anything about empty values
550
+ assert!(validator.validate("test/empty_values.csv").unwrap());
551
+ }
552
+
553
+ #[test]
554
+ fn test_empty_not_ok() {
555
+ let definition_empty_ok = String::from("
556
+ empty_not_ok: true
557
+ columns:
558
+ - name: First Column
559
+ format: positive integer
560
+ - name: Second Column
561
+ values: ['A', 'B', 'C']
562
+ ");
563
+ let validator = CSVValidator::from_string(&definition_empty_ok).unwrap();
564
+ // Validation is not OK as the file contains empty values
565
+ assert!(!validator.validate("test/empty_values.csv").unwrap());
566
+ }
567
+
509
568
  #[test]
510
569
  fn test_csv_validator_invalid_format() {
511
570
  let definition = String::from("
@@ -537,4 +596,117 @@ mod tests {
537
596
  let definition = String::from("");
538
597
  assert!(CSVValidator::from_string(&definition).is_err());
539
598
  }
599
+
600
+ #[test]
601
+ fn test_format_integer() {
602
+ let test_cases = vec![
603
+ ("42", true),
604
+ ("-42", true),
605
+ ("0", true),
606
+ ("", true), // Empty values are allowed by default
607
+ ("3.14", false),
608
+ ("abc", false),
609
+ ("123abc", false),
610
+ ];
611
+
612
+ test_format_validation("integer", test_cases);
613
+ }
614
+
615
+ #[test]
616
+ fn test_format_positive_integer() {
617
+ let test_cases = vec![
618
+ ("42", true),
619
+ ("0", true),
620
+ ("", true), // Empty values are allowed by default
621
+ ("-42", false),
622
+ ("3.14", false),
623
+ ("abc", false),
624
+ ("123abc", false),
625
+ ];
626
+
627
+ test_format_validation("positive integer", test_cases);
628
+ }
629
+
630
+ #[test]
631
+ fn test_format_decimal() {
632
+ let test_cases = vec![
633
+ ("42", true),
634
+ ("42.0", true),
635
+ ("42.42", true),
636
+ ("-42.42", true),
637
+ ("0.0", true),
638
+ ("", true), // Empty values are allowed by default
639
+ ("abc", false),
640
+ ("12.34.56", false),
641
+ ("12e4", false),
642
+ ];
643
+
644
+ test_format_validation("decimal", test_cases);
645
+ }
646
+
647
+ #[test]
648
+ fn test_format_positive_decimal() {
649
+ let test_cases = vec![
650
+ ("42", true),
651
+ ("42.0", true),
652
+ ("42.42", true),
653
+ ("0.0", true),
654
+ ("", true), // Empty values are allowed by default
655
+ ("-42.42", false),
656
+ ("abc", false),
657
+ ("12.34.56", false),
658
+ ("12e4", false),
659
+ ];
660
+
661
+ test_format_validation("positive decimal", test_cases);
662
+ }
663
+
664
+ #[test]
665
+ fn test_format_decimal_scientific() {
666
+ let test_cases = vec![
667
+ ("42", true),
668
+ ("42.0", true),
669
+ ("42.42", true),
670
+ ("-42.42", true),
671
+ ("1.234e5", true),
672
+ ("1.234e+5", true),
673
+ ("1.234e-5", true),
674
+ ("1.234E5", true),
675
+ ("", true), // Empty values are allowed by default
676
+ ("abc", false),
677
+ ("12.34.56", false),
678
+ ("1.234e", false),
679
+ ("e5", false),
680
+ ("1.234e+", false),
681
+ ];
682
+
683
+ test_format_validation("decimal scientific", test_cases);
684
+ }
685
+
686
+ // Helper function to test format validations
687
+ fn test_format_validation(format: &str, test_cases: Vec<(&str, bool)>) {
688
+ let definition = format!("
689
+ columns:
690
+ - name: Test
691
+ format: {}
692
+ ", format);
693
+
694
+ let validator = CSVValidator::from_string(&definition).unwrap();
695
+
696
+ for (value, expected) in test_cases {
697
+ let test_csv = format!("Test\n{}", value);
698
+ let temp_file = format!("test/temp_format_test_{}.csv", format.replace(" ", "_"));
699
+ std::fs::write(&temp_file, test_csv).unwrap();
700
+
701
+ let result = validator.validate(&temp_file).unwrap();
702
+ assert_eq!(
703
+ result,
704
+ expected,
705
+ "Format '{}' validation failed for value '{}': expected {}, got {}",
706
+ format, value, expected, result
707
+ );
708
+
709
+ std::fs::remove_file(&temp_file).unwrap();
710
+ }
711
+ }
540
712
  }
@@ -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