From 73aba47ccff227f77e6fb7ef8f9d857f3b0a5676 Mon Sep 17 00:00:00 2001 From: Nicolas Patry Date: Tue, 28 Mar 2023 14:13:38 +0200 Subject: [PATCH] Increase coverage on the error paths. (#214) --- safetensors/src/tensor.rs | 52 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/safetensors/src/tensor.rs b/safetensors/src/tensor.rs index 452d560..cb5a057 100644 --- a/safetensors/src/tensor.rs +++ b/safetensors/src/tensor.rs @@ -781,12 +781,16 @@ mod tests { offset += n; } - let filename = format!("./out_{model_id}.bin"); + let filename = format!("./out_{model_id}.safetensors"); let out = serialize(&metadata, &None).unwrap(); - std::fs::write(&filename, out).unwrap(); + let raw = std::fs::read(&filename).unwrap(); + let _deserialized = SafeTensors::deserialize(&raw).unwrap(); + std::fs::remove_file(&filename).unwrap(); + // File api + serialize_to_file(&metadata, &None, Path::new(&filename)).unwrap(); let raw = std::fs::read(&filename).unwrap(); let _deserialized = SafeTensors::deserialize(&raw).unwrap(); std::fs::remove_file(&filename).unwrap(); @@ -860,4 +864,48 @@ mod tests { _ => panic!("This should not be able to be deserialized"), } } + + #[test] + fn test_header_too_small() { + let serialized = b""; + match SafeTensors::deserialize(serialized) { + Err(SafeTensorError::HeaderTooSmall) => { + // Yes we have the correct error + } + _ => panic!("This should not be able to be deserialized"), + } + } + + #[test] + fn test_invalid_header_length() { + let serialized = b"<\x00\x00\x00\x00\x00\x00\x00"; + match SafeTensors::deserialize(serialized) { + Err(SafeTensorError::InvalidHeaderLength) => { + // Yes we have the correct error + } + _ => panic!("This should not be able to be deserialized"), + } + } + + #[test] + fn test_invalid_header_non_utf8() { + let serialized = b"\x01\x00\x00\x00\x00\x00\x00\x00\xff"; + match SafeTensors::deserialize(serialized) { + Err(SafeTensorError::InvalidHeader) => { + // Yes we have the correct error + } + _ => panic!("This should not be able to be deserialized"), + } + } + + #[test] + fn test_invalid_header_not_json() { + let serialized = b"\x01\x00\x00\x00\x00\x00\x00\x00{"; + match SafeTensors::deserialize(serialized) { + Err(SafeTensorError::InvalidHeaderDeserialization) => { + // Yes we have the correct error + } + _ => panic!("This should not be able to be deserialized"), + } + } } -- 2.43.0