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