csv-validation 0.0.1__tar.gz → 0.0.2__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.1"
86
+ version = "0.0.2"
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.1"
3
+ version = "0.0.2"
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.1
3
+ Version: 0.0.2
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Classifier: Programming Language :: Python :: Implementation :: PyPy
@@ -5,14 +5,23 @@ use std::iter::zip;
5
5
  use std::path::Path;
6
6
  use csv::Reader;
7
7
  use flate2::bufread::GzDecoder;
8
- use log::info;
8
+ use log::{debug, error, info};
9
9
  use pyo3::prelude::*;
10
10
  use regex::Regex;
11
11
  use yaml_rust2::YamlLoader;
12
+ use crate::Validation::{RegularExpression};
13
+
14
+ #[derive(Debug)]
15
+ enum Validation {
16
+ RegularExpression(Regex),
17
+ Min(f64),
18
+ Max(f64),
19
+ None
20
+ }
12
21
 
13
- struct ColumnValidation {
22
+ struct ColumnValidations {
14
23
  column_name: String,
15
- validation: Regex
24
+ validations: Vec<Validation>
16
25
  }
17
26
 
18
27
  /// Validate that CSV file complies with validations definition
@@ -30,32 +39,55 @@ fn validate(path: &str, definition_path: &str) -> PyResult<bool> {
30
39
  info!("Columns names and order are correct");
31
40
  }
32
41
  else {
33
- info!("Expected columns != Real columns");
42
+ error!("Expected columns != Real columns");
34
43
  return Ok(false);
35
44
  }
36
45
 
46
+ let mut is_valid_file = true;
37
47
  for result in rdr.records() {
38
48
  let record = result.unwrap();
39
49
  for next_column in zip(record.iter(), validations.iter()) {
40
50
  let value = next_column.0;
41
- let column_name = &next_column.1.column_name;
42
- let re = &next_column.1.validation;
43
- if !re.is_match(value) {
44
- info!("Column [{}] => Value {:?} doesn't match regex {:?}", column_name, value, re);
45
- return Ok(false);
51
+ let _column_name = &next_column.1.column_name;
52
+ for validation in &next_column.1.validations {
53
+ let valid = apply_validation(value, validation);
54
+ if !valid {
55
+ debug!("Column {}: Value {} isn't valid for {:?}",
56
+ _column_name, value, validation);
57
+ }
58
+ is_valid_file = is_valid_file && valid;
46
59
  }
47
60
  }
48
61
  }
49
62
 
50
63
  info!("File matches the validations");
51
- Ok(true)
64
+ Ok(is_valid_file)
65
+ }
66
+
67
+ fn apply_validation(value: &str, validation: &Validation) -> bool {
68
+ match validation {
69
+ RegularExpression(regex) => regex.is_match(value),
70
+ Validation::Min(min) => {
71
+ match value.parse::<f64>() {
72
+ Ok(value) => value >= *min,
73
+ Err(_) => false
74
+ }
75
+ },
76
+ Validation::Max(max) => {
77
+ match value.parse::<f64>() {
78
+ Ok(value) => value <= *max,
79
+ Err(_) => false
80
+ }
81
+ },
82
+ Validation::None => panic!("None validation cannot be applied")
83
+ }
52
84
  }
53
85
 
54
86
  /// Infers the file compression type and returns the corresponding buffered reader
55
87
  fn get_reader_from(path: &str) -> Reader<Box<dyn Read>> {
56
88
  let buf_reader = BufReader::new(File::open(Path::new(path)).unwrap());
57
89
  if is_gzip_file(path) {
58
- info!("File is gzipped");
90
+ debug!("File is gzipped");
59
91
  let read_capacity = 10 * 1024_usize.pow(2);
60
92
  let reader = BufReader::with_capacity(read_capacity, GzDecoder::new(buf_reader));
61
93
  Reader::from_reader(Box::new(reader))
@@ -71,48 +103,54 @@ fn is_gzip_file(path: &str) -> bool {
71
103
  bytes[0] == 0x1f && bytes[1] == 0x8b
72
104
  }
73
105
 
74
- fn get_validations(definition_path: &str) -> Vec<ColumnValidation> {
106
+ fn get_validations(definition_path: &str) -> Vec<ColumnValidations> {
75
107
  // Read the YAML definition with the validations
76
108
  let config =
77
109
  YamlLoader::load_from_str(fs::read_to_string(definition_path).unwrap().as_str()).unwrap();
78
110
  // Get the column names list and each associated validation
79
111
  let columns = &config[0]["columns"];
80
112
  let mut column_names = vec![];
81
- let mut validations = vec![];
113
+ let mut column_validations = vec![];
82
114
  for column in columns.as_vec().unwrap() {
83
115
  let column_def = column.as_hash().unwrap();
84
116
  let mut name = "";
85
- let mut regex = "";
86
- for validation in column_def.iter() {
87
- let key = validation.0.as_str().unwrap();
88
- let value = validation.1.as_str().unwrap();
89
-
90
- if key == "name" {
91
- name = value;
92
- column_names.push(name);
117
+ let mut validations = vec![];
118
+ for validation_definition in column_def.iter() {
119
+ let key = validation_definition.0.as_str().unwrap();
120
+ let value = validation_definition.1;
121
+ let mut validation: Validation = Validation::None;
122
+ match key {
123
+ "name" => { name = value.as_str().unwrap(); column_names.push(name); }
124
+ "regex" => { validation = Validation::RegularExpression(Regex::new(&value.as_str().unwrap()).unwrap()); }
125
+ "min" => { validation = Validation::Min(value.as_i64().unwrap() as f64); }
126
+ "max" => { validation = Validation::Max(value.as_i64().unwrap() as f64); }
127
+ _ => panic!("Unknown validation: {key}")
93
128
  }
94
- if key == "regex" {
95
- regex = value;
129
+
130
+ if key != "name" {
131
+ validations.push(validation);
96
132
  }
133
+
97
134
  }
98
- let new_validation = ColumnValidation { column_name: name.to_string(), validation: Regex::new(&regex).unwrap() };
99
- validations.push(new_validation);
135
+ let new_validations = ColumnValidations { column_name: name.to_string(), validations: validations };
136
+ column_validations.push(new_validations);
100
137
  }
101
138
 
102
- validations
139
+ column_validations
103
140
  }
104
141
 
105
- fn validate_column_names(reader: &mut Reader<Box<dyn Read>>, validations: &Vec<ColumnValidation>) -> bool {
142
+ fn validate_column_names(reader: &mut Reader<Box<dyn Read>>, validations: &Vec<ColumnValidations>) -> bool {
106
143
  let column_names = validations.iter()
107
144
  .map(|v| v.column_name.clone())
108
145
  .collect::<Vec<String>>();
109
- info!("Expected Column Names: {:?}", column_names);
146
+ debug!("Expected Column Names: {:?}", column_names);
110
147
 
111
148
  let headers: Vec<&str> = reader.headers().unwrap().iter().collect();
112
- info!("Actual Column Names: {:?}", headers);
149
+ debug!("Actual Column Names: {:?}", headers);
113
150
 
114
151
  column_names == headers
115
152
  }
153
+
116
154
  /// A Python module implemented in Rust.
117
155
  #[pymodule]
118
156
  fn csv_validation(m: &Bound<'_, PyModule>) -> PyResult<()> {
@@ -121,15 +159,18 @@ fn csv_validation(m: &Bound<'_, PyModule>) -> PyResult<()> {
121
159
  Ok(())
122
160
  }
123
161
 
124
-
125
162
  #[cfg(test)]
126
163
  mod tests {
127
164
  use simple_logger::SimpleLogger;
128
165
  use crate::validate;
129
166
 
130
167
  #[test]
131
- fn test_validate_csv() {
168
+ fn init_logger() {
132
169
  SimpleLogger::new().init().unwrap();
170
+ }
171
+
172
+ #[test]
173
+ fn test_validate_csv() {
133
174
  assert!(validate("test/test_file.csv", "test/test_validations.yml").unwrap());
134
175
  }
135
176
 
@@ -0,0 +1,5 @@
1
+ First Column,Second Column,Third Column
2
+ first_val,other_value,67
3
+ second_val,other second,1
4
+ third_val,and_third,1978
5
+ fourth_val,new ole,-23
@@ -4,4 +4,6 @@ columns:
4
4
  - name: Second Column
5
5
  regex: ^.+$
6
6
  - name: Third Column
7
- regex: ^[0-9]+$
7
+ regex: ^-?[0-9]+$
8
+ min: -23
9
+ max: 2000
@@ -1,4 +0,0 @@
1
- First Column,Second Column,Third Column
2
- first_val,other_value,67
3
- second_val,other_second,1
4
- third_val,and_third,1978
File without changes