]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Increase coverage on the error paths. (#214)
authorNicolas Patry <patry.nicolas@protonmail.com>
Tue, 28 Mar 2023 12:13:38 +0000 (14:13 +0200)
committerGitHub <noreply@github.com>
Tue, 28 Mar 2023 12:13:38 +0000 (14:13 +0200)
safetensors/src/tensor.rs

index 452d5602c0ff2cc0d3ad3fb5ccaf90e811582d2d..cb5a057729bd28e72ae08e2560ee998c3952cc3a 100644 (file)
@@ -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"),
+        }
+    }
 }