|
| 1 | +use std::io::{Cursor, Read, Write}; |
| 2 | +use std::path::Path; |
| 3 | +use zip::read::ZipFile; |
| 4 | +use zip::write::SimpleFileOptions; |
| 5 | +use zip::{ZipArchive, ZipWriter}; |
| 6 | + |
| 7 | +const DIRECTORY_NAME: &str = "test_directory"; |
| 8 | +const FILE_NAME: &str = "hello_world.txt"; |
| 9 | +const LOREM_IPSUM: &[u8] = b"Lorem ipsum dolor sit amet, consectetur adipiscing elit."; |
| 10 | + |
| 11 | +#[test] |
| 12 | +fn by_path() { |
| 13 | + let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); |
| 14 | + let mut archive = create_archive(options); |
| 15 | + let path = Path::new(DIRECTORY_NAME).join(FILE_NAME); |
| 16 | + let file = archive.by_path(path).unwrap(); |
| 17 | + validate_file(file); |
| 18 | +} |
| 19 | + |
| 20 | +#[test] |
| 21 | +#[cfg(feature = "aes-crypto")] |
| 22 | +fn by_path_decrypt() { |
| 23 | + use zip::AesMode; |
| 24 | + |
| 25 | + const PASSWORD: &str = "helloworld"; |
| 26 | + |
| 27 | + let options = SimpleFileOptions::default() |
| 28 | + .compression_method(zip::CompressionMethod::Stored) |
| 29 | + .with_aes_encryption(AesMode::Aes128, PASSWORD); |
| 30 | + let mut archive = create_archive(options); |
| 31 | + let path = Path::new(DIRECTORY_NAME).join(FILE_NAME); |
| 32 | + let file = archive.by_path_decrypt(path, PASSWORD.as_bytes()).unwrap(); |
| 33 | + validate_file(file); |
| 34 | +} |
| 35 | + |
| 36 | +fn create_archive(options: SimpleFileOptions) -> ZipArchive<Cursor<Vec<u8>>> { |
| 37 | + let mut buf = Vec::new(); |
| 38 | + let mut zip = ZipWriter::new(Cursor::new(&mut buf)); |
| 39 | + zip.add_directory(DIRECTORY_NAME, options).unwrap(); |
| 40 | + zip.start_file(format!("{DIRECTORY_NAME}/{FILE_NAME}"), options) |
| 41 | + .unwrap(); |
| 42 | + zip.write_all(LOREM_IPSUM).unwrap(); |
| 43 | + zip.finish().unwrap(); |
| 44 | + ZipArchive::new(Cursor::new(buf)).unwrap() |
| 45 | +} |
| 46 | + |
| 47 | +fn validate_file<T>(mut file: ZipFile<T>) |
| 48 | +where |
| 49 | + T: Read, |
| 50 | +{ |
| 51 | + let mut file_buf = Vec::new(); |
| 52 | + file.read_to_end(&mut file_buf).unwrap(); |
| 53 | + assert_eq!(LOREM_IPSUM, file_buf); |
| 54 | +} |
0 commit comments