team-ljyzipelo

공개
347줄12 KB
1// 분할 7z 만들기: 볼륨 이름/크기, 분할 읽기 왕복, 이름 충돌·취소·게시 실패 되돌리기.
2use super::*;
3
4const MIB: u64 = 1024 * 1024;
5
6fn noise(length: usize, mut state: u32) -> Vec<u8> {
7 (0..length)
8 .map(|_| {
9 state ^= state << 13;
10 state ^= state >> 17;
11 state ^= state << 5;
12 state as u8
13 })
14 .collect()
15}
16fn split_request(c: &Case, names: &[&str], output: &str, size: u64) -> Start {
17 let mut start = c.request(names);
18 if let Action::CreateSevenZip {
19 output_file,
20 volume_size,
21 ..
22 } = &mut start.action
23 {
24 *output_file = NativePath::from_path(&c.0.join(output));
25 *volume_size = Some(size);
26 }
27 start
28}
29fn volume_files(dir: &std::path::Path, prefix: &str) -> Vec<String> {
30 let mut names = fs::read_dir(dir)
31 .unwrap()
32 .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
33 .filter(|name| name.starts_with(prefix))
34 .collect::<Vec<_>>();
35 names.sort();
36 names
37}
38fn created(events: &[Message]) -> Vec<String> {
39 events
40 .iter()
41 .filter_map(|event| match event {
42 Message::Output {
43 entry_id: None,
44 relative_name,
45 disposition: Disposition::Created,
46 } => Some(relative_name.clone()),
47 _ => None,
48 })
49 .collect()
50}
51fn no_temporaries(dir: &std::path::Path) {
52 assert!(!tree(dir).keys().any(|name| name.contains(".zipelo-")));
53}
54
55#[test]
56fn split_volumes_have_requested_sizes_and_round_trip_through_the_split_reader() {
57 for parent in ["", "source"] {
58 let c = Case::new();
59 private_dir(&c.0.join("source"));
60 private_dir(&c.0.join("source/빈 폴더"));
61 fs::write(
62 c.0.join("source/noise.bin"),
63 noise(2 * MIB as usize + 300_000, 7),
64 )
65 .unwrap();
66 fs::write(c.0.join("source/한글.txt"), "분할 압축\n".repeat(2000)).unwrap();
67 fs::write(c.0.join("source/empty"), b"").unwrap();
68 let expected = tree(&c.0.join("source"));
69 let output = if parent.is_empty() {
70 "result.7z".to_owned()
71 } else {
72 format!("{parent}/result.7z")
73 };
74 let events = c.run(Message::Start(split_request(&c, &["source"], &output, MIB)));
75 let t = terminal(&events);
76 assert_eq!(t.outcome, Outcome::Completed, "{events:?}");
77 assert_eq!(t.publication, Publication::Complete);
78 assert_eq!(t.created_count, 3);
79 assert_eq!(t.cleanup, Cleanup::Complete);
80 assert_eq!(t.retained_partial_count, 0);
81 assert_eq!(
82 created(&events),
83 ["result.7z.001", "result.7z.002", "result.7z.003"]
84 );
85 let dir = c.0.join(parent);
86 assert!(!dir.join("result.7z").exists());
87 assert_eq!(
88 volume_files(&dir, "result.7z"),
89 ["result.7z.001", "result.7z.002", "result.7z.003"]
90 );
91 let sizes = ["001", "002", "003"].map(|n| {
92 fs::metadata(dir.join(format!("result.7z.{n}")))
93 .unwrap()
94 .len()
95 });
96 assert_eq!(sizes[0], MIB);
97 assert_eq!(sizes[1], MIB);
98 assert!(sizes[2] > 0 && sizes[2] <= MIB, "{sizes:?}");
99 // 볼륨을 이어 붙이면 그대로 하나의 7z임.
100 let mut joined = Vec::new();
101 for n in ["001", "002", "003"] {
102 joined.extend(fs::read(dir.join(format!("result.7z.{n}"))).unwrap());
103 }
104 assert_eq!(&joined[..6], b"7z\xbc\xaf\x27\x1c");
105 no_temporaries(&c.0);
106
107 let first = NativePath::from_path(&dir.join("result.7z.001"));
108 let listed = c.run(Message::Start(Start {
109 action: Action::List {
110 archive: first.clone(),
111 },
112 limits: Limits::default(),
113 }));
114 assert_eq!(terminal(&listed).outcome, Outcome::Completed, "{listed:?}");
115 assert!(listed.iter().any(|event| matches!(
116 event,
117 Message::ListEnd {
118 list_id: ListId {
119 source_object: SourceObject::SplitSevenZip { .. },
120 ..
121 },
122 ..
123 }
124 )));
125 private_dir(&c.0.join("decoded"));
126 let extracted = c.run(Message::Start(Start {
127 action: Action::Extract {
128 archive: first,
129 destination: c.path("decoded"),
130 selection: Selection::All,
131 list_id: None,
132 gzip_output_name: None,
133 },
134 limits: Limits::default(),
135 }));
136 assert_eq!(
137 terminal(&extracted).outcome,
138 Outcome::Completed,
139 "{extracted:?}"
140 );
141 assert_eq!(tree(&c.0.join("decoded/source")), expected);
142 if let Some(tool) = std::env::var_os("ZIPELO_TEST_7ZIP") {
143 let output = Command::new(&tool)
144 .arg("t")
145 .arg(dir.join("result.7z.001"))
146 .output()
147 .unwrap();
148 assert!(output.status.success(), "{output:?}");
149 let output = Command::new(tool)
150 .args(["x", "-y"])
151 .arg(dir.join("result.7z.001"))
152 .arg(format!("-o{}", c.0.join("independent").display()))
153 .output()
154 .unwrap();
155 assert!(output.status.success(), "{output:?}");
156 assert_eq!(tree(&c.0.join("independent/source")), expected);
157 }
158 }
159}
160
161#[test]
162fn small_archives_still_use_a_single_first_volume_name() {
163 let c = Case::new();
164 fs::write(c.0.join("source"), b"small payload").unwrap();
165 let events = c.run(Message::Start(split_request(
166 &c,
167 &["source"],
168 "작은.7z",
169 4 * MIB,
170 )));
171 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
172 assert_eq!(terminal(&events).created_count, 1);
173 assert_eq!(created(&events), ["작은.7z.001"]);
174 assert_eq!(volume_files(&c.0, "작은.7z"), ["작은.7z.001"]);
175 let listed = c.run(Message::Start(Start {
176 action: Action::List {
177 archive: c.path("작은.7z.001"),
178 },
179 limits: Limits::default(),
180 }));
181 assert_eq!(terminal(&listed).outcome, Outcome::Completed, "{listed:?}");
182}
183
184#[test]
185fn invalid_sizes_names_and_existing_volume_names_are_rejected() {
186 let c = Case::new();
187 fs::write(c.0.join("source"), b"abcdef").unwrap();
188 for size in [0, 1, MIB - 1] {
189 failure(
190 &c.run(Message::Start(split_request(
191 &c,
192 &["source"],
193 "result.7z",
194 size,
195 ))),
196 ErrorCode::InvalidRequest,
197 );
198 }
199 failure(
200 &c.run(Message::Start(split_request(
201 &c,
202 &["source"],
203 "result.zip",
204 MIB,
205 ))),
206 ErrorCode::InvalidRequest,
207 );
208 // 분할 읽기는 자릿수와 관계없이 같은 접두사의 숫자 이름을 한 묶음으로 보므로 모두 거부함.
209 for existing in [
210 "result.7z.001",
211 "result.7z.002",
212 "result.7z.0001",
213 "result.7z.5",
214 ] {
215 fs::write(c.0.join(existing), b"preserve").unwrap();
216 failure(
217 &c.run(Message::Start(split_request(
218 &c,
219 &["source"],
220 "result.7z",
221 MIB,
222 ))),
223 ErrorCode::Conflict,
224 );
225 assert_eq!(fs::read(c.0.join(existing)).unwrap(), b"preserve");
226 assert_eq!(volume_files(&c.0, "result.7z"), [existing]);
227 fs::remove_file(c.0.join(existing)).unwrap();
228 }
229 // 숫자가 아닌 비슷한 이름과 분할하지 않은 같은 이름은 그대로 두고 만듦.
230 fs::write(c.0.join("result.7z"), b"single").unwrap();
231 fs::write(c.0.join("result.7z.bak"), b"backup").unwrap();
232 let events = c.run(Message::Start(split_request(
233 &c,
234 &["source"],
235 "result.7z",
236 MIB,
237 )));
238 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
239 assert_eq!(fs::read(c.0.join("result.7z")).unwrap(), b"single");
240 assert!(c.0.join("result.7z.001").is_file());
241 no_temporaries(&c.0);
242}
243
244#[test]
245fn cancel_while_writing_volumes_publishes_nothing() {
246 let c = Case::new();
247 fs::write(c.0.join("source"), noise(3 * MIB as usize, 11)).unwrap();
248 let mut sent = false;
249 let events = c.run_with(
250 &mut c.command(),
251 Message::Start(split_request(&c, &["source"], "result.7z", MIB)),
252 |event| {
253 // 볼륨 게시 단계의 첫 쓰기 진행(전체 길이가 있는 Write)에서 취소함.
254 if !sent
255 && matches!(
256 event,
257 Message::Progress {
258 stage: Stage::Write,
259 total_bytes: Some(_),
260 ..
261 }
262 )
263 {
264 sent = true;
265 vec![Message::Cancel]
266 } else {
267 Vec::new()
268 }
269 },
270 );
271 assert!(sent);
272 failure(&events, ErrorCode::None);
273 assert!(volume_files(&c.0, "result.7z").is_empty());
274 no_temporaries(&c.0);
275}
276
277#[cfg(target_os = "linux")]
278#[test]
279fn a_volume_name_taken_during_publication_rolls_back_every_volume() {
280 for operation in ["second", "source", "cancel"] {
281 let c = Case::new();
282 fs::write(c.0.join("source"), noise(2 * MIB as usize + 1000, 3)).unwrap();
283 let marker = c.0.join("marker");
284 let release = c.0.join("release");
285 let mut command = c.command();
286 command
287 .env("LD_PRELOAD", shim(&c, "io_fault.c"))
288 .env("ZIPELO_TEST_FAULT", "pause")
289 .env("ZIPELO_TEST_MARKER", &marker)
290 .env("ZIPELO_TEST_RELEASE", &release);
291 let mut changed = false;
292 let events = c.run_with(
293 &mut command,
294 Message::Start(split_request(&c, &["source"], "result.7z", MIB)),
295 |event| {
296 if !changed
297 && matches!(
298 event,
299 Message::Progress {
300 stage: Stage::Write,
301 total_bytes: Some(_),
302 ..
303 }
304 )
305 {
306 let until = std::time::Instant::now() + Duration::from_secs(5);
307 while !marker.exists() {
308 assert!(std::time::Instant::now() < until);
309 std::thread::sleep(Duration::from_millis(2));
310 }
311 match operation {
312 // 첫 볼륨은 게시할 수 있지만 둘째 이름이 막혀 첫 볼륨도 되돌려야 함.
313 "second" => fs::write(c.0.join("result.7z.002"), b"user data").unwrap(),
314 "source" => fs::write(c.0.join("source"), b"changed").unwrap(),
315 _ => {}
316 }
317 changed = true;
318 let replies = if operation == "cancel" {
319 vec![Message::Cancel]
320 } else {
321 Vec::new()
322 };
323 fs::write(&release, b"resume").unwrap();
324 replies
325 } else {
326 Vec::new()
327 }
328 },
329 );
330 assert!(changed);
331 failure(
332 &events,
333 match operation {
334 "second" => ErrorCode::Conflict,
335 "source" => ErrorCode::SourceChanged,
336 _ => ErrorCode::None,
337 },
338 );
339 if operation == "second" {
340 assert_eq!(volume_files(&c.0, "result.7z"), ["result.7z.002"]);
341 assert_eq!(fs::read(c.0.join("result.7z.002")).unwrap(), b"user data");
342 } else {
343 assert!(volume_files(&c.0, "result.7z").is_empty());
344 }
345 no_temporaries(&c.0);
346 }
347}