-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Validate DelimFile headers #17
base: main
Are you sure you want to change the base?
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -171,8 +171,16 @@ impl<D: DeserializeOwned> DelimFileReader<D> { | |
.has_headers(true) | ||
.quoting(quote) | ||
.from_reader(reader); | ||
assert!(csv_reader.has_headers(), "Expected input file to have a header row"); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I removed this assert. It wasn't actually checking for a header line but instead just checks that the reader is configured to read a header. |
||
|
||
// NB: csv_reader.has_header() does not actually check for existence of a header, but only | ||
// checks that the reader is configured to read a header. | ||
|
||
// If the header is not empty (try to parse it) | ||
let header = csv_reader.headers().map_err(FgError::ConversionError)?.to_owned(); | ||
if !header.is_empty() { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Empty files return empty headers, so we validate headers for only non-empty TSVs. |
||
Self::validate_header(&header, delimiter)? | ||
} | ||
|
||
let record_iter = csv_reader.into_deserialize(); | ||
Ok(Self { record_iter, header }) | ||
} | ||
|
@@ -186,6 +194,25 @@ impl<D: DeserializeOwned> DelimFileReader<D> { | |
pub fn read(&mut self) -> Option<Result<D>> { | ||
self.record_iter.next().map(|result| result.map_err(FgError::ConversionError)) | ||
} | ||
|
||
fn validate_header(header: &StringRecord, delimiter: u8) -> Result<()> { | ||
let delim = String::from_utf8(vec![delimiter]).unwrap(); | ||
let found_header_parts: Vec<&str> = header.iter().collect(); | ||
theJasonFan marked this conversation as resolved.
Show resolved
Hide resolved
|
||
let expected_header_parts = serde_aux::prelude::serde_introspect::<D>(); | ||
|
||
// Expected header fields must be a _subset_ of found header fields | ||
let ok = expected_header_parts.iter().all(|field| found_header_parts.contains(field)); | ||
|
||
if !ok { | ||
let expected = expected_header_parts.join(&delim); | ||
return Err(FgError::DelimFileHeaderError { | ||
expected, | ||
found: header.as_slice().to_owned(), | ||
theJasonFan marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}); | ||
} | ||
|
||
Ok(()) | ||
} | ||
} | ||
|
||
impl<D: DeserializeOwned> Iterator for DelimFileReader<D> { | ||
|
@@ -342,6 +369,7 @@ impl DelimFile { | |
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
use crate::io::{DelimFile, Io}; | ||
use serde::{Deserialize, Serialize}; | ||
use tempfile::TempDir; | ||
|
@@ -355,6 +383,25 @@ mod tests { | |
o: Option<f64>, | ||
} | ||
|
||
// Trickier record types in which fields are skipped in de/serialization | ||
#[derive(Debug, Serialize, Deserialize, PartialEq)] | ||
struct RecWithSkipDe { | ||
s: String, | ||
i: usize, | ||
b: bool, | ||
#[serde(skip_deserializing)] | ||
o: Option<f64>, | ||
} | ||
|
||
#[derive(Debug, Serialize, Deserialize, PartialEq)] | ||
struct RecWithSkipSe { | ||
s: String, | ||
i: usize, | ||
b: bool, | ||
#[serde(skip_serializing)] | ||
o: Option<f64>, | ||
} | ||
|
||
#[test] | ||
fn test_reading_and_writing_lines_to_file() { | ||
let lines = vec!["foo", "bar,splat,whee", "baz\twhoopsie"]; | ||
|
@@ -431,4 +478,47 @@ mod tests { | |
assert_eq!(from_csv, recs); | ||
assert_eq!(from_tsv, recs); | ||
} | ||
|
||
#[test] | ||
fn test_header_error() { | ||
let recs = vec![ | ||
RecWithSkipDe { s: "Hello".to_string(), i: 123, b: true, o: None }, | ||
RecWithSkipDe { s: "A,B,C".to_string(), i: 456, b: false, o: Some(123.45) }, | ||
]; | ||
let tmp = TempDir::new().unwrap(); | ||
let csv = tmp.path().join("recs.csv"); | ||
let df = DelimFile::default(); | ||
df.write_csv(&csv, recs).unwrap(); | ||
|
||
let result: Result<Vec<RecWithSkipDe>> = df.read_tsv(&csv); | ||
let err = result.unwrap_err(); | ||
|
||
// Serialized CSV should contain all fields, deserializing should skip "o" | ||
if let FgError::DelimFileHeaderError { expected, found } = err { | ||
assert_eq!(expected, "s\ti\tb"); | ||
assert_eq!(found, "s,i,b,o"); | ||
} else { | ||
panic!() | ||
} | ||
|
||
let recs = vec![ | ||
RecWithSkipSe { s: "Hello".to_string(), i: 123, b: true, o: None }, | ||
RecWithSkipSe { s: "A,B,C".to_string(), i: 456, b: false, o: Some(123.45) }, | ||
]; | ||
let tmp = TempDir::new().unwrap(); | ||
let csv = tmp.path().join("recs.csv"); | ||
let df = DelimFile::default(); | ||
df.write_csv(&csv, recs).unwrap(); | ||
|
||
let result: Result<Vec<RecWithSkipSe>> = df.read_tsv(&csv); | ||
let err = result.unwrap_err(); | ||
|
||
// Serialized CSV should contain should skip "o", deserailize should expect all fields | ||
if let FgError::DelimFileHeaderError { expected, found } = err { | ||
assert_eq!(expected, "s\ti\tb\to"); | ||
assert_eq!(found, "s,i,b"); | ||
} else { | ||
panic!() | ||
} | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Used for serde / field name introspection.
fqtk
uses the same crate.