Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 25.9 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Property tests on random small repositories: `diff` is canonical and
5//! `apply` inverts it, admission accepts what `commit` makes and rejects
6//! tampering, changes to unrelated paths land the same in either order, and
7//! merging two changesets agrees with landing one on the other. Plus
8//! properties of the three-way merge.
9//!
10//! Trees are built here from scratch with `build_directory`, independently of
11//! the engine, and serve as the oracle.
12
13use std::collections::{BTreeMap, BTreeSet};
14
15use braid_engine::{
16 ApplyProblem, Error, LandOutcome, MergeOutcome, MergeResult, admit, apply, commit, diff, land,
17 merge, merge3, read_changes, read_changeset,
18};
19use braid_format::{
20 Change, ChangeOp, Changes, Changeset, ChangesetError, ChangesetParts, Entry, EntryKind, GitId,
21 Kind, MemoryObjects, ObjectId, Objects, Signature, build_directory,
22};
23use proptest::prelude::*;
24use proptest::sample::Index;
25use proptest::test_runner::TestCaseError;
26
27/// What is at a path, before it is stored.
28#[derive(Clone, Debug, PartialEq, Eq)]
29enum Value {
30 File(Vec<u8>),
31 Exec(Vec<u8>),
32 Link(Vec<u8>),
33 Gitlink(u8),
34}
35
36impl Value {
37 fn kind(&self) -> EntryKind {
38 let blob = |content: &[u8]| ObjectId::hash(Kind::Blob, content);
39 match self {
40 Value::File(c) => EntryKind::File {
41 blob: blob(c),
42 size: c.len() as u64,
43 },
44 Value::Exec(c) => EntryKind::Executable {
45 blob: blob(c),
46 size: c.len() as u64,
47 },
48 Value::Link(c) => EntryKind::Symlink {
49 blob: blob(c),
50 size: c.len() as u64,
51 },
52 Value::Gitlink(byte) => EntryKind::Gitlink {
53 commit: GitId::Sha1([*byte; 20]),
54 },
55 }
56 }
57
58 fn op(&self) -> ChangeOp {
59 ChangeOp::from_entry(&self.kind()).expect("a value is never a directory")
60 }
61
62 fn store(&self, objects: &MemoryObjects) {
63 if let Value::File(c) | Value::Exec(c) | Value::Link(c) = self {
64 objects.put(Kind::Blob, c).unwrap();
65 }
66 }
67}
68
69/// A repository state: every file, by path. No path is inside another.
70type Files = BTreeMap<Vec<u8>, Value>;
71
72fn store_all(objects: &MemoryObjects, files: &Files) {
73 for value in files.values() {
74 value.store(objects);
75 }
76}
77
78/// Whether `prefix` is a directory that `path` is inside.
79fn inside(prefix: &[u8], path: &[u8]) -> bool {
80 path.len() > prefix.len() && path.starts_with(prefix) && path[prefix.len()] == b'/'
81}
82
83/// Whether two paths are the same, or one is inside the other.
84fn related(a: &[u8], b: &[u8]) -> bool {
85 a == b || inside(a, b) || inside(b, a)
86}
87
88/// The files that would stop `path` from being a file: files at its prefixes
89/// and files inside it.
90fn blockers(files: &Files, path: &[u8]) -> Vec<Vec<u8>> {
91 let mut found: Vec<Vec<u8>> = path
92 .iter()
93 .enumerate()
94 .filter(|(_, byte)| **byte == b'/')
95 .map(|(at, _)| &path[..at])
96 .filter(|prefix| files.contains_key(*prefix))
97 .map(<[u8]>::to_vec)
98 .collect();
99 let mut from = path.to_vec();
100 from.push(b'/');
101 let mut to = path.to_vec();
102 to.push(b'/' + 1);
103 found.extend(files.range(from..to).map(|(key, _)| key.clone()));
104 found
105}
106
107/// The canonical change list between two states, computed on the maps.
108fn changes(old: &Files, new: &Files) -> Vec<Change> {
109 let paths: BTreeSet<&Vec<u8>> = old.keys().chain(new.keys()).collect();
110 paths
111 .into_iter()
112 .filter_map(|path| {
113 let before = old.get(path).map(Value::kind);
114 let after = new.get(path);
115 (before != after.map(Value::kind)).then(|| Change {
116 path: path.clone(),
117 op: after.map_or(ChangeOp::Delete, Value::op),
118 })
119 })
120 .collect()
121}
122
123/// Builds and stores the tree of `files` from scratch.
124fn build(objects: &MemoryObjects, files: &Files) -> ObjectId {
125 store_all(objects, files);
126 let items: Vec<(&[u8], &Value)> = files.iter().map(|(p, v)| (p.as_slice(), v)).collect();
127 build_dir(objects, &items)
128}
129
130fn build_dir(objects: &MemoryObjects, items: &[(&[u8], &Value)]) -> ObjectId {
131 let mut entries = Vec::new();
132 let mut below: BTreeMap<&[u8], Vec<(&[u8], &Value)>> = BTreeMap::new();
133 for (path, value) in items {
134 match path.iter().position(|byte| *byte == b'/') {
135 None => entries.push(Entry {
136 name: path.to_vec(),
137 kind: value.kind(),
138 }),
139 Some(slash) => below
140 .entry(&path[..slash])
141 .or_default()
142 .push((&path[slash + 1..], *value)),
143 }
144 }
145 for (name, sub) in below {
146 entries.push(Entry {
147 name: name.to_vec(),
148 kind: EntryKind::Tree {
149 tree: build_dir(objects, &sub),
150 },
151 });
152 }
153 let directory = build_directory(entries).unwrap();
154 for (_, bytes) in &directory.nodes {
155 objects.put(Kind::Tree, bytes).unwrap();
156 }
157 directory.root()
158}
159
160fn signature() -> Signature {
161 Signature {
162 name: b"agent".to_vec(),
163 email: b"agent@example.org".to_vec(),
164 seconds: 1_700_000_000,
165 offset_minutes: 0,
166 }
167}
168
169fn commit_list(
170 objects: &MemoryObjects,
171 parents: Vec<ObjectId>,
172 list: Vec<Change>,
173) -> Result<ObjectId, Error> {
174 commit(
175 objects,
176 parents,
177 list,
178 signature(),
179 signature(),
180 b"change\n".to_vec(),
181 Vec::new(),
182 )
183}
184
185/// Short names, so that paths collide, nest and sort around `/`, with a few
186/// that differ only in case or normalisation.
187fn name() -> impl Strategy<Value = Vec<u8>> {
188 prop_oneof![
189 8 => "[a-d]".prop_map(String::into_bytes),
190 3 => "[a-c][a-c0-9-]{1,2}".prop_map(String::into_bytes),
191 1 => Just(b"A".to_vec()),
192 1 => Just(b"B".to_vec()),
193 1 => Just("caf\u{e9}".as_bytes().to_vec()),
194 1 => Just("cafe\u{301}".as_bytes().to_vec()),
195 ]
196}
197
198fn path() -> impl Strategy<Value = Vec<u8>> {
199 prop::collection::vec(name(), 1..=3).prop_map(|names| names.join(&b'/'))
200}
201
202fn content() -> impl Strategy<Value = Vec<u8>> {
203 prop_oneof![
204 Just(Vec::new()),
205 Just(b"same\n".to_vec()),
206 prop::collection::vec(
207 prop_oneof![Just(&b"x\n"[..]), Just(&b"y\n"[..]), Just(&b"z"[..])],
208 0..4
209 )
210 .prop_map(|parts| parts.concat()),
211 prop::collection::vec(any::<u8>(), 0..8),
212 ]
213}
214
215fn value() -> impl Strategy<Value = Value> {
216 prop_oneof![
217 6 => content().prop_map(Value::File),
218 2 => content().prop_map(Value::Exec),
219 1 => content().prop_map(Value::Link),
220 1 => (0u8..3).prop_map(Value::Gitlink),
221 ]
222}
223
224/// A random repository; one time in five with a directory of about a
225/// thousand files, on either side of the split limit.
226fn files() -> impl Strategy<Value = Files> {
227 (
228 prop::collection::vec((path(), value()), 0..20),
229 prop::option::weighted(0.2, (1016usize..1034, any::<u8>())),
230 )
231 .prop_map(|(list, wide)| {
232 let mut files = Files::new();
233 if let Some((count, salt)) = wide {
234 for i in 0..count {
235 files.insert(
236 format!("w/f{i:04}").into_bytes(),
237 Value::File(vec![salt, (i % 5) as u8]),
238 );
239 }
240 }
241 for (path, value) in list {
242 if blockers(&files, &path).is_empty() {
243 files.insert(path, value);
244 }
245 }
246 files
247 })
248}
249
250#[derive(Clone, Debug)]
251enum Edit {
252 Modify(Index, Value),
253 Delete(Index),
254 /// Adds a file, deleting whatever is in its way.
255 Add(Vec<u8>, Value),
256}
257
258fn edits() -> impl Strategy<Value = Vec<Edit>> {
259 prop::collection::vec(
260 prop_oneof![
261 3 => (any::<Index>(), value()).prop_map(|(i, v)| Edit::Modify(i, v)),
262 2 => any::<Index>().prop_map(Edit::Delete),
263 3 => (path(), value()).prop_map(|(p, v)| Edit::Add(p, v)),
264 1 => (1000u16..1060, value())
265 .prop_map(|(n, v)| Edit::Add(format!("w/f{n:04}").into_bytes(), v)),
266 ],
267 0..10,
268 )
269}
270
271fn edit(files: &Files, edits: &[Edit]) -> Files {
272 let mut out = files.clone();
273 for edit in edits {
274 match edit {
275 Edit::Modify(index, value) if !out.is_empty() => {
276 let key = out.keys().nth(index.index(out.len())).unwrap().clone();
277 out.insert(key, value.clone());
278 }
279 Edit::Delete(index) if !out.is_empty() => {
280 let key = out.keys().nth(index.index(out.len())).unwrap().clone();
281 out.remove(&key);
282 }
283 Edit::Add(path, value) => {
284 for blocker in blockers(&out, path) {
285 out.remove(&blocker);
286 }
287 out.insert(path.clone(), value.clone());
288 }
289 _ => {}
290 }
291 }
292 out
293}
294
295/// `target`, keeping only the changes to paths unrelated to `taken`, and
296/// only those that still make a valid state without the others.
297fn restrict(start: &Files, target: &Files, taken: &[Change]) -> Files {
298 let wanted: Vec<Change> = changes(start, target)
299 .into_iter()
300 .filter(|change| !taken.iter().any(|t| related(&t.path, &change.path)))
301 .collect();
302 let mut files = start.clone();
303 for change in &wanted {
304 if matches!(change.op, ChangeOp::Delete) {
305 files.remove(&change.path);
306 }
307 }
308 for change in &wanted {
309 if !matches!(change.op, ChangeOp::Delete) && blockers(&files, &change.path).is_empty() {
310 files.insert(change.path.clone(), target[&change.path].clone());
311 }
312 }
313 files
314}
315
316/// Lands `first` and then `second`, both built on `root`, and returns the
317/// final root tree, or `None` if the second landing conflicts.
318fn land_both(
319 objects: &MemoryObjects,
320 root: ObjectId,
321 first: ObjectId,
322 second: ObjectId,
323) -> Result<Option<ObjectId>, TestCaseError> {
324 let LandOutcome::FastForward(head) = land(objects, Some(root), first, signature())? else {
325 return Err(TestCaseError::fail(
326 "a change on the head must fast-forward",
327 ));
328 };
329 let head_root = read_changeset(objects, head)?.root;
330 match land(objects, Some(head), second, signature())? {
331 LandOutcome::Rebased { changeset, .. } => {
332 // What lands is admissible, and its list is the diff.
333 admit(objects, changeset, |id| *id == head)?;
334 let new = read_changeset(objects, changeset)?;
335 let list = read_changes(objects, changeset, &new)?.into_owned();
336 prop_assert_eq!(list, diff(objects, head_root, new.root)?);
337 Ok(Some(new.root))
338 }
339 LandOutcome::AlreadyApplied => Ok(Some(head_root)),
340 LandOutcome::Conflicts(_) => Ok(None),
341 LandOutcome::FastForward(_) => Err(TestCaseError::fail("cannot fast-forward twice")),
342 }
343}
344
345/// `diff` gives exactly the canonical list, and `apply` inverts it.
346fn check_round_trip(old: &Files, new: &Files) -> Result<(), TestCaseError> {
347 let objects = MemoryObjects::new();
348 let a = build(&objects, old);
349 let b = build(&objects, new);
350
351 prop_assert_eq!(diff(&objects, a, a)?, Vec::new());
352 prop_assert_eq!(diff(&objects, b, b)?, Vec::new());
353
354 // Exactly the files that differ, sorted by path, without repeats.
355 let forward = diff(&objects, a, b)?;
356 prop_assert!(forward.windows(2).all(|pair| pair[0].path < pair[1].path));
357 prop_assert_eq!(&forward, &changes(old, new));
358 prop_assert_eq!(apply(&objects, a, &forward)?, b);
359
360 let backward = diff(&objects, b, a)?;
361 prop_assert_eq!(&backward, &changes(new, old));
362 prop_assert_eq!(apply(&objects, b, &backward)?, a);
363 Ok(())
364}
365
366/// Two changes to unrelated paths, built on `start`, land the same in either
367/// order: both cleanly, with the same tree, or both with conflicts.
368fn check_commutation(
369 start: &Files,
370 x_files: &Files,
371 y_target: &Files,
372) -> Result<(), TestCaseError> {
373 let x_list = changes(start, x_files);
374 let y_files = restrict(start, y_target, &x_list);
375 let y_list = changes(start, &y_files);
376 for x in &x_list {
377 for y in &y_list {
378 prop_assert!(!related(&x.path, &y.path));
379 }
380 }
381
382 let objects = MemoryObjects::new();
383 store_all(&objects, start);
384 store_all(&objects, x_files);
385 store_all(&objects, &y_files);
386 let root = commit_list(&objects, Vec::new(), changes(&Files::new(), start))?;
387 let x = commit_list(&objects, vec![root], x_list)?;
388 let y = commit_list(&objects, vec![root], y_list.clone())?;
389
390 let x_then_y = land_both(&objects, root, x, y)?;
391 let y_then_x = land_both(&objects, root, y, x)?;
392 prop_assert_eq!(x_then_y.is_some(), y_then_x.is_some());
393 if let (Some(first), Some(second)) = (x_then_y, y_then_x) {
394 prop_assert_eq!(first, second);
395 let mut both = x_files.clone();
396 for change in &y_list {
397 match change.op {
398 ChangeOp::Delete => {
399 both.remove(&change.path);
400 }
401 _ => {
402 both.insert(change.path.clone(), y_files[&change.path].clone());
403 }
404 }
405 }
406 prop_assert_eq!(first, build(&MemoryObjects::new(), &both));
407 }
408 Ok(())
409}
410
411/// Two changesets built on one start, related or not: merging the second
412/// into the first gives what landing the second on the first gives, the same
413/// conflicts or the same tree, and a merge that is admissible, whose change
414/// list is the diff from the first.
415fn check_merge_agrees_with_land(
416 start: &Files,
417 x_files: &Files,
418 y_files: &Files,
419) -> Result<(), TestCaseError> {
420 let objects = MemoryObjects::new();
421 store_all(&objects, start);
422 store_all(&objects, x_files);
423 store_all(&objects, y_files);
424 let root = commit_list(&objects, Vec::new(), changes(&Files::new(), start))?;
425 let x = commit_list(&objects, vec![root], changes(start, x_files))?;
426 let y = commit(
427 &objects,
428 vec![root],
429 changes(start, y_files),
430 signature(),
431 signature(),
432 b"other change\n".to_vec(),
433 Vec::new(),
434 )?;
435 let landed = land(&objects, Some(x), y, signature())?;
436 let merged = merge(&objects, x, y, signature(), b"merge\n".to_vec(), Vec::new())?;
437 match (landed, merged) {
438 (LandOutcome::Conflicts(by_land), MergeOutcome::Conflicts(by_merge)) => {
439 prop_assert_eq!(by_land, by_merge);
440 }
441 (
442 landed @ (LandOutcome::Rebased { .. } | LandOutcome::AlreadyApplied),
443 MergeOutcome::Merged {
444 changeset,
445 merged_paths,
446 },
447 ) => {
448 let new = read_changeset(&objects, changeset)?;
449 prop_assert_eq!(&new.parents, &vec![x, y]);
450 admit(&objects, changeset, |id| *id == x || *id == y)?;
451 let x_root = read_changeset(&objects, x)?.root;
452 let list = read_changes(&objects, changeset, &new)?.into_owned();
453 prop_assert_eq!(list, diff(&objects, x_root, new.root)?);
454 match landed {
455 LandOutcome::Rebased {
456 changeset: rebased,
457 merged_paths: rebased_paths,
458 } => {
459 prop_assert_eq!(new.root, read_changeset(&objects, rebased)?.root);
460 prop_assert_eq!(merged_paths, rebased_paths);
461 }
462 _ => prop_assert_eq!(new.root, x_root),
463 }
464 }
465 (landed, merged) => {
466 return Err(TestCaseError::fail(format!(
467 "landing gave {landed:?}, merging gave {merged:?}"
468 )));
469 }
470 }
471 Ok(())
472}
473
474/// A directory of about a thousand files, on either side of the split
475/// limit, and a few other files.
476fn wide() -> impl Strategy<Value = Files> {
477 (
478 1000usize..1050,
479 any::<u8>(),
480 prop::collection::vec((path(), value()), 0..6),
481 )
482 .prop_map(|(count, salt, others)| {
483 let mut files = Files::new();
484 for i in 0..count {
485 files.insert(
486 format!("w/f{i:04}").into_bytes(),
487 Value::File(vec![salt, (i % 3) as u8]),
488 );
489 }
490 for (path, value) in others {
491 if blockers(&files, &path).is_empty() {
492 files.insert(path, value);
493 }
494 }
495 files
496 })
497}
498
499/// Enough edits, mostly in the wide directory, to move it across the limit.
500fn wide_edits() -> impl Strategy<Value = Vec<Edit>> {
501 prop::collection::vec(
502 prop_oneof![
503 2 => (any::<Index>(), value()).prop_map(|(i, v)| Edit::Modify(i, v)),
504 3 => any::<Index>().prop_map(Edit::Delete),
505 3 => (1000u16..1080, value())
506 .prop_map(|(n, v)| Edit::Add(format!("w/f{n:04}").into_bytes(), v)),
507 1 => (path(), value()).prop_map(|(p, v)| Edit::Add(p, v)),
508 ],
509 0..40,
510 )
511}
512
513proptest! {
514 #![proptest_config(ProptestConfig::with_cases(128))]
515
516 #[test]
517 fn diff_is_canonical_and_apply_inverts_it(old in files(), edits in edits()) {
518 check_round_trip(&old, &edit(&old, &edits))?;
519 }
520
521 #[test]
522 fn admission_accepts_commits_and_rejects_tampering(start in files(), edits in edits()) {
523 let objects = MemoryObjects::new();
524 // Oracle trees go to their own store, so they cannot stand in for a
525 // directory that `commit` failed to write.
526 let oracle = MemoryObjects::new();
527 let new = edit(&start, &edits);
528 store_all(&objects, &start);
529 store_all(&objects, &new);
530 let root = commit_list(&objects, Vec::new(), changes(&Files::new(), &start))?;
531 admit(&objects, root, |_| false)?;
532 let root_tree = read_changeset(&objects, root)?.root;
533 prop_assert_eq!(root_tree, build(&oracle, &start));
534
535 let list = changes(&start, &new);
536 let child = commit_list(&objects, vec![root], list.clone())?;
537 let good = read_changeset(&objects, child)?;
538 prop_assert_eq!(good.root, build(&oracle, &new));
539 let parent_only = |id: &ObjectId| *id == root;
540 admit(&objects, child, parent_only)?;
541 let not_admitted = admit(&objects, child, |_| false);
542 prop_assert!(
543 matches!(not_admitted, Err(Error::ParentNotAdmitted { .. })),
544 "{:?}", not_admitted
545 );
546
547 let forge = |changeset: &Changeset| {
548 objects.put(Kind::Changeset, &changeset.encode()).unwrap()
549 };
550
551 // A root the changes do not give.
552 let mut wrong_root = good.clone();
553 wrong_root.root = ObjectId::hash(Kind::Tree, b"another tree");
554 let result = admit(&objects, forge(&wrong_root), parent_only);
555 prop_assert!(matches!(result, Err(Error::RootMismatch { .. })), "{:?}", result);
556
557 // A blob that is not stored.
558 let mut missing = list.clone();
559 missing.push(Change {
560 path: b"zz-missing".to_vec(),
561 op: ChangeOp::File {
562 blob: ObjectId::hash(Kind::Blob, b"never stored"),
563 size: 12,
564 },
565 });
566 let id = commit_list(&objects, vec![root], missing)?;
567 let result = admit(&objects, id, parent_only);
568 prop_assert!(
569 matches!(result, Err(Error::Missing { kind: Kind::Blob, .. })),
570 "{:?}", result
571 );
572
573 // An unsorted list.
574 if list.len() >= 2 && matches!(good.changes, Changes::Inline(_)) {
575 let mut unsorted = good.clone();
576 let mut swapped = list.clone();
577 swapped.swap(0, 1);
578 unsorted.changes = Changes::Inline(swapped);
579 let result = admit(&objects, forge(&unsorted), parent_only);
580 prop_assert!(
581 matches!(
582 result,
583 Err(Error::Changeset { error: ChangesetError::Unsorted { .. }, .. })
584 ),
585 "{:?}", result
586 );
587 }
588
589 // A no-op change, with the root it would give.
590 if let Some((path, value)) = start.iter().next() {
591 let no_op = ChangesetParts {
592 parents: vec![root],
593 root: root_tree,
594 changes: vec![Change { path: path.clone(), op: value.op() }],
595 author: signature(),
596 committer: signature(),
597 message: Vec::new(),
598 extras: Vec::new(),
599 git_origin: None,
600 }
601 .assemble()
602 .unwrap();
603 objects.put(Kind::Changeset, &no_op.encoded).unwrap();
604 let result = admit(&objects, no_op.id, parent_only);
605 prop_assert!(
606 matches!(result, Err(Error::Apply { problem: ApplyProblem::NoOp, .. })),
607 "{:?}", result
608 );
609 }
610 }
611
612 #[test]
613 fn unrelated_changes_land_the_same_in_either_order(
614 start in files(),
615 x_edits in edits(),
616 y_edits in edits(),
617 ) {
618 check_commutation(&start, &edit(&start, &x_edits), &edit(&start, &y_edits))?;
619 }
620
621 #[test]
622 fn merging_agrees_with_landing(
623 start in files(),
624 x_edits in edits(),
625 y_edits in edits(),
626 ) {
627 check_merge_agrees_with_land(&start, &edit(&start, &x_edits), &edit(&start, &y_edits))?;
628 }
629}
630
631// Directories of about a thousand entries are slow to build and check in a
632// debug build, so these run fewer cases.
633proptest! {
634 #![proptest_config(ProptestConfig::with_cases(32))]
635
636 #[test]
637 fn split_directories_round_trip_across_the_limit(old in wide(), edits in wide_edits()) {
638 check_round_trip(&old, &edit(&old, &edits))?;
639 }
640
641 #[test]
642 fn unrelated_changes_to_a_split_directory_commute(
643 start in wide(),
644 x_edits in wide_edits(),
645 y_edits in wide_edits(),
646 ) {
647 check_commutation(&start, &edit(&start, &x_edits), &edit(&start, &y_edits))?;
648 }
649}
650
651/// Text made of a few distinct lines, so that random versions share lines.
652fn text() -> impl Strategy<Value = Vec<u8>> {
653 prop::collection::vec(
654 prop_oneof![
655 Just(&b"a\n"[..]),
656 Just(&b"b\n"[..]),
657 Just(&b"c\n"[..]),
658 Just(&b"\n"[..]),
659 Just(&b" d\n"[..]),
660 Just(&b"e"[..]),
661 ],
662 0..12,
663 )
664 .prop_map(|lines| lines.concat())
665}
666
667fn lines(text: &[u8]) -> Vec<&[u8]> {
668 text.split_inclusive(|byte| *byte == b'\n').collect()
669}
670
671proptest! {
672 #![proptest_config(ProptestConfig::with_cases(512))]
673
674 #[test]
675 fn merge_takes_the_side_that_changed(base in text(), other in text()) {
676 let clean = MergeResult::Clean(other.clone());
677 prop_assert_eq!(&merge3(&base, &base, &other), &clean);
678 prop_assert_eq!(&merge3(&base, &other, &base), &clean);
679 prop_assert_eq!(&merge3(&base, &other, &other), &clean);
680 }
681
682 #[test]
683 fn merge_is_symmetric_and_hunks_match_the_inputs(
684 base in text(),
685 ours in text(),
686 theirs in text(),
687 ) {
688 let forward = merge3(&base, &ours, &theirs);
689 let backward = merge3(&base, &theirs, &ours);
690 match (&forward, &backward) {
691 (MergeResult::Clean(a), MergeResult::Clean(b)) => prop_assert_eq!(a, b),
692 (MergeResult::Conflict { hunks: a }, MergeResult::Conflict { hunks: b }) => {
693 prop_assert_eq!(a.len(), b.len());
694 let (base_lines, ours_lines, theirs_lines) =
695 (lines(&base), lines(&ours), lines(&theirs));
696 for (hunk, mirror) in a.iter().zip(b) {
697 prop_assert_eq!(&hunk.base, &mirror.base);
698 prop_assert_eq!(&hunk.ours, &mirror.theirs);
699 prop_assert_eq!(&hunk.theirs, &mirror.ours);
700 prop_assert_eq!(&hunk.base.text, &base_lines[hunk.base.lines.clone()].concat());
701 prop_assert_eq!(&hunk.ours.text, &ours_lines[hunk.ours.lines.clone()].concat());
702 prop_assert_eq!(
703 &hunk.theirs.text,
704 &theirs_lines[hunk.theirs.lines.clone()].concat()
705 );
706 prop_assert!(hunk.ours.text != hunk.theirs.text);
707 }
708 }
709 _ => prop_assert!(false, "{:?} but {:?}", forward, backward),
710 }
711 }
712
713 #[test]
714 fn edits_with_a_line_between_them_merge(
715 prefix in 0usize..5,
716 ours_old in 0usize..4,
717 gap in 1usize..4,
718 theirs_old in 0usize..4,
719 suffix in 0usize..5,
720 ours_new in 0usize..3,
721 theirs_new in 0usize..3,
722 ) {
723 // Distinct base lines; ours replaces [a, b) and theirs [c, d), with at
724 // least one untouched line between b and c.
725 let a = prefix;
726 let b = a + ours_old;
727 let c = b + gap;
728 let d = c + theirs_old;
729 let count = d + suffix;
730 let base: Vec<Vec<u8>> = (0..count).map(|i| format!("line {i}\n").into_bytes()).collect();
731 let replace = |from: usize, to: usize, tag: &str, n: usize| -> Vec<u8> {
732 let mut out: Vec<u8> = base[..from].concat();
733 for i in 0..n {
734 out.extend(format!("{tag} {i}\n").into_bytes());
735 }
736 out.extend(base[to..].concat());
737 out
738 };
739 let ours = replace(a, b, "ours", ours_new);
740 let theirs = replace(c, d, "theirs", theirs_new);
741 let mut expected: Vec<u8> = base[..a].concat();
742 for i in 0..ours_new {
743 expected.extend(format!("ours {i}\n").into_bytes());
744 }
745 expected.extend(base[b..c].concat());
746 for i in 0..theirs_new {
747 expected.extend(format!("theirs {i}\n").into_bytes());
748 }
749 expected.extend(base[d..].concat());
750 let base: Vec<u8> = base.concat();
751 prop_assert_eq!(merge3(&base, &ours, &theirs), MergeResult::Clean(expected.clone()));
752 prop_assert_eq!(merge3(&base, &theirs, &ours), MergeResult::Clean(expected));
753 }
754}