Skip to main content

targeted_mutation/
output_fixture.rs

1//! Runtime assets declared relative to the workspace and isolated Cargo output.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::fs::{self, File, OpenOptions};
5use std::io::{self, ErrorKind};
6use std::path::{Component, Path, PathBuf};
7
8use anyhow::{Context, Result, bail};
9use serde::{Deserialize, Serialize};
10
11const OWNERSHIP: &str = ".tmt-output-fixtures.json";
12const OWNERSHIP_TEMP: &str = ".tmt-output-fixtures-new";
13const STAGING: &str = ".tmt-output-fixture-stage";
14
15/// A workspace input and its destination inside TMT's isolated Cargo output.
16#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
17pub struct Fixture {
18    pub from: PathBuf,
19    pub to: PathBuf,
20}
21
22impl std::str::FromStr for Fixture {
23    type Err = anyhow::Error;
24
25    fn from_str(text: &str) -> Result<Self> {
26        let (from, to) = text
27            .split_once('=')
28            .context("expected a fixture mapping FROM=TO")?;
29        Ok(Self {
30            from: relative(Path::new(from))?,
31            to: relative(Path::new(to))?,
32        })
33    }
34}
35
36fn relative(path: &Path) -> Result<PathBuf> {
37    let mut clean = PathBuf::new();
38    for part in path.components() {
39        match part {
40            Component::Normal(name) => clean.push(name),
41            Component::CurDir => {}
42            _ => bail!(
43                "output fixture path must be relative and confined: {}",
44                path.display()
45            ),
46        }
47    }
48    if clean.as_os_str().is_empty() {
49        bail!("output fixture path must name a file or directory");
50    }
51    Ok(clean)
52}
53
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55enum Kind {
56    File,
57    Directory,
58}
59
60enum Planned {
61    File(PathBuf),
62    Directory { shared: bool },
63}
64
65impl Planned {
66    fn kind(&self) -> Kind {
67        match self {
68            Self::File(_) => Kind::File,
69            Self::Directory { .. } => Kind::Directory,
70        }
71    }
72}
73
74#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
75struct Stamp {
76    length: u64,
77    modified: std::time::SystemTime,
78    #[cfg(unix)]
79    device_and_inode: (u64, u64),
80}
81
82impl Stamp {
83    fn from_metadata(metadata: &fs::Metadata) -> Result<Self> {
84        #[cfg(unix)]
85        use std::os::unix::fs::MetadataExt as _;
86        Ok(Self {
87            length: metadata.len(),
88            modified: metadata.modified()?,
89            #[cfg(unix)]
90            device_and_inode: (metadata.dev(), metadata.ino()),
91        })
92    }
93}
94
95#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
96#[serde(rename_all = "snake_case")]
97enum Owned {
98    File(Vec<Stamp>),
99    Directory,
100}
101
102impl Owned {
103    fn check(&self, metadata: &fs::Metadata) -> Result<Option<Self>> {
104        Ok(match self {
105            // tmt:ignore the stamp of anything else has another inode and so does not match; the guard is for platforms whose stamp has none
106            Self::File(stamps) if metadata.is_file() => {
107                let current = Stamp::from_metadata(metadata)?;
108                stamps.contains(&current).then(|| Self::File(vec![current]))
109            }
110            Self::Directory if metadata.is_dir() => Some(Self::Directory),
111            _ => None,
112        })
113    }
114
115    fn kind(&self) -> Kind {
116        match self {
117            Self::File(_) => Kind::File,
118            Self::Directory => Kind::Directory,
119        }
120    }
121}
122
123type Ownership = BTreeMap<PathBuf, Owned>;
124
125/// The caller holds the work-directory lock and invokes staging before running tests.
126pub(crate) fn stage(
127    workspace: &Path,
128    work: &Path,
129    target_dir: &Path,
130    fixtures: &[Fixture],
131) -> Result<()> {
132    let work = work.canonicalize()?;
133    let target = target_dir.canonicalize()?;
134    if target == work || !target.starts_with(&work) || !fs::symlink_metadata(target_dir)?.is_dir() {
135        bail!("the output fixture target must be a directory inside the TMT work directory");
136    }
137
138    let recorded = read_ownership(&work.join(OWNERSHIP))?;
139    if fixtures.is_empty() && recorded.is_empty() {
140        return Ok(());
141    }
142    let workspace = workspace.canonicalize()?;
143    let mut plan = BTreeMap::new();
144    for fixture in fixtures {
145        let from = relative(&fixture.from)?;
146        let to = relative(&fixture.to)?;
147        // A mapped destination or a shared parent already in the plan overlaps
148        // at this path. Above it, only shared parents can be reused.
149        let mut overlapping = plan.contains_key(&to);
150        for parent in to
151            .ancestors()
152            .skip(1)
153            .filter(|parent| !parent.as_os_str().is_empty())
154        {
155            let entry = plan
156                .entry(parent.to_path_buf())
157                .or_insert(Planned::Directory { shared: true });
158            overlapping |= !matches!(entry, Planned::Directory { shared: true });
159        }
160        if overlapping {
161            bail!("overlapping output fixture destination: {}", to.display());
162        }
163        plan_source(
164            &workspace.join(from),
165            &to,
166            &workspace,
167            &work,
168            &mut plan,
169            &mut BTreeSet::new(),
170        )?;
171    }
172
173    // Two names that differ only in the case of their letters are one file on a file
174    // system that does not tell case apart (the usual one on macOS and Windows): the
175    // second would replace the first, and both would be taken for ours. They are
176    // refused everywhere, so that a plan means the same wherever it is run.
177    let mut folded: BTreeMap<String, &PathBuf> = BTreeMap::new();
178    for path in plan.keys() {
179        let key = path.to_string_lossy().to_lowercase();
180        if let Some(other) = folded.insert(key, path) {
181            bail!(
182                "output fixture destinations differ only by case: {} and {}",
183                other.display(),
184                path.display()
185            );
186        }
187    }
188
189    // A replaced file is no longer ours. Cargo can choose a different output
190    // path in a later build, and tests may create files of their own.
191    let mut previous = Ownership::new();
192    let mut previous_meta: BTreeMap<PathBuf, fs::Metadata> = BTreeMap::new();
193    let mut previous_folded: BTreeMap<String, Vec<PathBuf>> = BTreeMap::new();
194    for (path, receipt) in &recorded {
195        // What is no longer a file or a directory of ours, or is now behind something
196        // that is not a directory, was replaced by somebody else: it is theirs.
197        if let Place::Found(metadata) = output_place(&target, path)?
198            && let Some(current) = receipt.check(&metadata)?
199        {
200            previous_folded
201                .entry(path.to_string_lossy().to_lowercase())
202                .or_default()
203                .push(path.clone());
204            previous_meta.insert(path.clone(), metadata);
205            previous.insert(path.clone(), current);
206        }
207    }
208
209    // Validate the whole plan before modifying Cargo output.
210    let mut shared = BTreeSet::new();
211    for (path, entry) in &plan {
212        if let Some(metadata) = output_metadata(&target, path)? {
213            let shared_directory = matches!(entry, Planned::Directory { shared: true });
214            let kind_matches = match entry.kind() {
215                Kind::File => metadata.is_file(),
216                Kind::Directory => metadata.is_dir(),
217            };
218            let exact_owned = previous.contains_key(path);
219            // On a case-insensitive filesystem, renaming a previously owned fixture to a
220            // different case (`debug/Data` -> `debug/data`) resolves to the old owned entry.
221            let mut case_owned = false;
222            if !exact_owned
223                && let Some(aliases) = previous_folded.get(&path.to_string_lossy().to_lowercase())
224            {
225                for old in aliases {
226                    if !plan.contains_key(old)
227                        && let Some(old_meta) = previous_meta.get(old)
228                        && same_directory_entry(&target, old, old_meta, path, &metadata)?
229                    {
230                        case_owned = true;
231                        break;
232                    }
233                }
234            }
235            let owned = exact_owned || case_owned;
236            if !kind_matches || (!shared_directory && !owned) {
237                bail!(
238                    "output fixture destination already exists: {}",
239                    path.display()
240                );
241            }
242            // Only a shared directory gets here without being ours: it was there before us.
243            // A case-renamed owned directory is re-created with its new spelling instead.
244            if !owned {
245                shared.insert(path.clone());
246            }
247        }
248    }
249
250    // Prepare complete files privately. The ownership journal can describe both
251    // sides of each rename, even if the next run starts after an interruption.
252    let staging = Staging::new(work.join(STAGING))?;
253    let mut wanted = Ownership::new();
254    let mut prepared = BTreeMap::new();
255    for (index, (path, entry)) in plan.iter().enumerate() {
256        let receipt = match entry {
257            Planned::Directory { .. } if shared.contains(path) => continue,
258            Planned::Directory { .. } => Owned::Directory,
259            Planned::File(from) => {
260                let temporary = staging.0.join(index.to_string());
261                copy_file(from, &temporary)?;
262                let stamp = Stamp::from_metadata(&fs::metadata(&temporary)?)?;
263                prepared.insert(path.clone(), temporary);
264                Owned::File(vec![stamp])
265            }
266        };
267        wanted.insert(path.clone(), receipt);
268    }
269
270    let mut pending = previous.clone();
271    for (path, receipt) in &wanted {
272        match (pending.get_mut(path), receipt) {
273            (Some(Owned::File(old)), Owned::File(fresh)) => old.extend(fresh.iter().cloned()),
274            _ => {
275                pending.insert(path.clone(), receipt.clone());
276            }
277        }
278    }
279    if pending != recorded {
280        write_ownership(&work, &pending)?;
281    }
282
283    for (path, receipt) in previous.iter().rev() {
284        if !wanted.contains_key(path) {
285            remove_owned(&target.join(path), receipt.kind())?;
286        }
287    }
288    for (path, entry) in plan {
289        let output = target.join(&path);
290        match entry {
291            Planned::Directory { .. } if !output.exists() => {
292                fs::create_dir(&output).with_context(|| {
293                    format!("creating output fixture directory {}", output.display())
294                })?
295            }
296            Planned::Directory { .. } => {}
297            Planned::File(_) => {
298                fs::rename(&prepared[&path], &output)
299                    .with_context(|| format!("installing output fixture {}", output.display()))?;
300            }
301        }
302    }
303    if pending != wanted {
304        write_ownership(&work, &wanted)?;
305    }
306
307    Ok(())
308}
309
310fn plan_source(
311    from: &Path,
312    to: &Path,
313    workspace: &Path,
314    work: &Path,
315    plan: &mut BTreeMap<PathBuf, Planned>,
316    visiting: &mut BTreeSet<PathBuf>,
317) -> Result<()> {
318    let resolved = from
319        .canonicalize()
320        .with_context(|| format!("resolving output fixture source {}", from.display()))?;
321    let allowed = |path: &Path| {
322        path.strip_prefix(workspace).is_ok_and(|relative| {
323            // tmt:ignore the tests give every part but the first a case of its own; a link to the workspace root is refused without the first too, as a cycle, because the root contains the link
324            !relative.as_os_str().is_empty()
325                && !path.starts_with(work)
326                && !relative.starts_with("target")
327                && !relative.components().any(|part| part.as_os_str() == ".git")
328        })
329    };
330    if !allowed(from) || !allowed(&resolved) {
331        bail!(
332            "output fixture source {} resolves outside the allowed workspace inputs: {}",
333            from.display(),
334            resolved.display()
335        );
336    }
337    let metadata = fs::metadata(&resolved)?;
338    if metadata.is_file() {
339        plan.insert(to.to_path_buf(), Planned::File(resolved));
340    // tmt:ignore what is neither a file nor a directory cannot be listed, so it is refused without this test too; this gives the reason
341    } else if metadata.is_dir() && visiting.insert(resolved.clone()) {
342        plan.insert(to.to_path_buf(), Planned::Directory { shared: false });
343        for child in fs::read_dir(&resolved)? {
344            let child = child?;
345            plan_source(
346                &child.path(),
347                &to.join(child.file_name()),
348                workspace,
349                work,
350                plan,
351                visiting,
352            )?;
353        }
354        visiting.remove(&resolved);
355    } else {
356        bail!(
357            "output fixture source {} is a cycle or has an unsupported file type",
358            from.display()
359        );
360    }
361    Ok(())
362}
363
364/// What is at a path below the target directory, looked at without following links.
365enum Place {
366    Found(fs::Metadata),
367    Missing,
368    /// The path itself, or a part of it, is neither a file nor a directory where it has
369    /// to be one (a symbolic link, for example).
370    Unsafe(PathBuf),
371}
372
373fn output_place(target: &Path, relative: &Path) -> Result<Place> {
374    let mut parts = relative.components().peekable();
375    let mut current = target.to_path_buf();
376    while let Some(part) = parts.next() {
377        current.push(part);
378        let Some(metadata) = inspect(&current)? else {
379            return Ok(Place::Missing);
380        };
381        if parts.peek().is_none() && (metadata.is_dir() || metadata.is_file()) {
382            return Ok(Place::Found(metadata));
383        }
384        if !metadata.is_dir() {
385            return Ok(Place::Unsafe(current));
386        }
387    }
388    unreachable!("relative output fixture paths are nonempty")
389}
390
391/// A destination that is about to be written: nothing is written through an unsafe path.
392fn output_metadata(target: &Path, relative: &Path) -> Result<Option<fs::Metadata>> {
393    match output_place(target, relative)? {
394        Place::Found(metadata) => Ok(Some(metadata)),
395        Place::Missing => Ok(None),
396        Place::Unsafe(path) => bail!(
397            "output fixture destination crosses an unsafe path: {}",
398            path.display()
399        ),
400    }
401}
402
403fn same_directory_entry(
404    target: &Path,
405    old: &Path,
406    old_meta: &fs::Metadata,
407    new: &Path,
408    new_meta: &fs::Metadata,
409) -> Result<bool> {
410    if !same_entry(&target.join(old), old_meta, &target.join(new), new_meta) {
411        return Ok(false);
412    }
413    // A hard link on a case-sensitive filesystem shares the same inode as the owned
414    // entry, but appears as a distinct directory entry in its parent directory.
415    let old_parts: Vec<_> = old.components().collect();
416    let new_parts: Vec<_> = new.components().collect();
417    if old_parts.len() != new_parts.len() {
418        return Ok(false);
419    }
420    let mut parent = target.to_path_buf();
421    for (old_part, new_part) in old_parts.into_iter().zip(new_parts) {
422        if old_part != new_part {
423            let old_name = old_part.as_os_str();
424            let new_name = new_part.as_os_str();
425            let mut has_old = false;
426            let mut has_new = false;
427            for entry in fs::read_dir(&parent)
428                .with_context(|| format!("reading directory {}", parent.display()))?
429            {
430                let name = entry?.file_name();
431                if name == old_name {
432                    has_old = true;
433                } else if name == new_name {
434                    has_new = true;
435                }
436                if has_old && has_new {
437                    return Ok(false);
438                }
439            }
440        }
441        parent.push(old_part);
442    }
443    Ok(true)
444}
445
446fn same_entry(a_path: &Path, a: &fs::Metadata, b_path: &Path, b: &fs::Metadata) -> bool {
447    #[cfg(unix)]
448    {
449        let _ = (a_path, b_path);
450        use std::os::unix::fs::MetadataExt as _;
451        (a.dev(), a.ino()) == (b.dev(), b.ino())
452    }
453    #[cfg(not(unix))]
454    {
455        a.is_file() == b.is_file()
456            && a.is_dir() == b.is_dir()
457            && a_path
458                .canonicalize()
459                .ok()
460                .zip(b_path.canonicalize().ok())
461                .is_some_and(|(a_real, b_real)| a_real == b_real)
462    }
463}
464
465fn inspect(path: &Path) -> Result<Option<fs::Metadata>> {
466    match fs::symlink_metadata(path) {
467        Ok(metadata) => Ok(Some(metadata)),
468        Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
469        Err(error) => Err(error).with_context(|| format!("inspecting {}", path.display())),
470    }
471}
472
473fn remove_owned(path: &Path, kind: Kind) -> Result<()> {
474    let result = match kind {
475        Kind::File => fs::remove_file(path),
476        Kind::Directory => fs::remove_dir(path),
477    };
478    match result {
479        Ok(()) => Ok(()),
480        // tmt:ignore only what was just seen in place is removed, so nothing is missing unless it is removed concurrently; the tests pin that other errors are reported
481        Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),
482        // Tests or Cargo may have created their own files under a former fixture.
483        // tmt:ignore removing a file never reports a directory that is not empty, so the kind only states the intent; the tests pin that other errors of a directory are reported
484        Err(error) if kind == Kind::Directory && error.kind() == ErrorKind::DirectoryNotEmpty => {
485            Ok(())
486        }
487        Err(error) => {
488            Err(error).with_context(|| format!("removing old output fixture {}", path.display()))
489        }
490    }
491}
492
493struct Staging(PathBuf);
494
495impl Staging {
496    fn new(path: PathBuf) -> Result<Self> {
497        if let Some(existing) = inspect(&path)? {
498            if !existing.is_dir() {
499                bail!(
500                    "output fixture staging path is not a directory: {}",
501                    path.display()
502                );
503            }
504            fs::remove_dir_all(&path)?;
505        }
506        fs::create_dir(&path)?;
507        Ok(Self(path))
508    }
509}
510
511impl Drop for Staging {
512    fn drop(&mut self) {
513        let _ = fs::remove_dir_all(&self.0);
514    }
515}
516
517fn copy_file(from: &Path, to: &Path) -> Result<()> {
518    let copy = || -> io::Result<()> {
519        let mut input = File::open(from)?;
520        let mut output = OpenOptions::new().write(true).create_new(true).open(to)?;
521        io::copy(&mut input, &mut output)?;
522        output.set_permissions(input.metadata()?.permissions())?;
523        Ok(())
524    };
525    copy().with_context(|| {
526        format!(
527            "copying output fixture {} to {}",
528            from.display(),
529            to.display()
530        )
531    })
532}
533
534fn read_ownership(path: &Path) -> Result<Ownership> {
535    let Some(metadata) = inspect(path)? else {
536        return Ok(Ownership::new());
537    };
538    if !metadata.is_file() {
539        bail!(
540            "output fixture ownership is not a regular file: {}",
541            path.display()
542        );
543    }
544    let owned: Ownership = serde_json::from_reader(io::BufReader::new(File::open(path)?))
545        .with_context(|| format!("reading output fixture ownership {}", path.display()))?;
546    for entry in owned.keys() {
547        if relative(entry)? != *entry {
548            bail!("invalid output fixture ownership path: {}", entry.display());
549        }
550    }
551    Ok(owned)
552}
553
554fn write_ownership(work: &Path, owned: &Ownership) -> Result<()> {
555    let temporary = work.join(OWNERSHIP_TEMP);
556    if let Some(existing) = inspect(&temporary)? {
557        if !existing.is_file() {
558            bail!(
559                "output fixture ownership staging path is not a regular file: {}",
560                temporary.display()
561            );
562        }
563        fs::remove_file(&temporary)?;
564    }
565    let file = OpenOptions::new()
566        .write(true)
567        .create_new(true)
568        .open(&temporary)?;
569    serde_json::to_writer(&file, owned)?;
570    // tmt:ignore durability across a power loss, which a test cannot observe
571    file.sync_all()?;
572    // tmt:ignore Windows does not rename a file that is open; elsewhere closing it first changes nothing
573    drop(file);
574    fs::rename(temporary, work.join(OWNERSHIP)).context("committing output fixture ownership")
575}
576
577#[cfg(test)]
578mod tests {
579    use super::*;
580    use std::fs;
581    use std::sync::atomic::{AtomicUsize, Ordering};
582
583    struct Tree {
584        workspace: PathBuf,
585        work: PathBuf,
586        target: PathBuf,
587    }
588
589    impl Tree {
590        fn new() -> Self {
591            static NEXT: AtomicUsize = AtomicUsize::new(0);
592            let root = std::env::temp_dir().join(format!(
593                "tmt-output-fixture-{}-{}",
594                std::process::id(),
595                NEXT.fetch_add(1, Ordering::Relaxed)
596            ));
597            fs::create_dir(&root).unwrap();
598            let work = root.join("work");
599            let target = work.join("target");
600            fs::create_dir(&work).unwrap();
601            fs::create_dir(&target).unwrap();
602            Self {
603                workspace: root.canonicalize().unwrap(),
604                work,
605                target,
606            }
607        }
608
609        fn stage(&self, fixtures: &[Fixture]) -> Result<()> {
610            stage(&self.workspace, &self.work, &self.target, fixtures)
611        }
612    }
613
614    impl Drop for Tree {
615        fn drop(&mut self) {
616            fs::remove_dir_all(&self.workspace).unwrap();
617        }
618    }
619
620    fn mapping(from: &str, to: &str) -> Fixture {
621        Fixture {
622            from: from.into(),
623            to: to.into(),
624        }
625    }
626
627    #[test]
628    fn paths_must_remain_relative_to_their_roots() {
629        let fixture: Fixture = "./runtime/app.mjs=debug/runtime/app.mjs".parse().unwrap();
630        assert_eq!(fixture, mapping("runtime/app.mjs", "debug/runtime/app.mjs"));
631        for text in [
632            "missing-separator",
633            "=debug/asset",
634            "runtime=",
635            "/tmp/asset=debug",
636            "runtime=../output",
637            "runtime/../escape=debug",
638            "runtime=.",
639            "runtime=/tmp/asset",
640        ] {
641            assert!(text.parse::<Fixture>().is_err(), "{text}");
642        }
643        assert_eq!(
644            serde_json::to_value(fixture).unwrap(),
645            serde_json::json!({"from": "runtime/app.mjs", "to": "debug/runtime/app.mjs"})
646        );
647    }
648
649    #[test]
650    fn updates_owned_assets_and_preserves_unowned_outputs() {
651        let tree = Tree::new();
652        let input = tree.workspace.join("runtime");
653        fs::create_dir(&input).unwrap();
654        fs::write(input.join("old.mjs"), "first").unwrap();
655        fs::write(input.join("always.mjs"), "first").unwrap();
656        fs::create_dir(tree.target.join("debug")).unwrap();
657        fs::write(tree.target.join("debug/cargo-output"), "cargo").unwrap();
658        let asset = mapping("runtime", "debug/runtime");
659        tree.stage(std::slice::from_ref(&asset)).unwrap();
660        assert_eq!(
661            fs::read_to_string(tree.target.join("debug/runtime/old.mjs")).unwrap(),
662            "first"
663        );
664
665        fs::remove_file(input.join("old.mjs")).unwrap();
666        fs::write(input.join("new.mjs"), "second").unwrap();
667        fs::write(input.join("always.mjs"), "updated").unwrap();
668        fs::write(tree.target.join("debug/runtime/test-output"), "keep").unwrap();
669        tree.stage(&[asset]).unwrap();
670
671        assert!(!tree.target.join("debug/runtime/old.mjs").exists());
672        assert_eq!(
673            fs::read_to_string(tree.target.join("debug/runtime/new.mjs")).unwrap(),
674            "second"
675        );
676        assert_eq!(
677            fs::read_to_string(tree.target.join("debug/runtime/always.mjs")).unwrap(),
678            "updated"
679        );
680        tree.stage(&[]).unwrap();
681        assert!(!tree.target.join("debug/runtime/new.mjs").exists());
682        assert!(!tree.target.join("debug/runtime/always.mjs").exists());
683        assert_eq!(
684            fs::read_to_string(tree.target.join("debug/runtime/test-output")).unwrap(),
685            "keep"
686        );
687        assert_eq!(
688            fs::read_to_string(tree.target.join("debug/cargo-output")).unwrap(),
689            "cargo"
690        );
691        assert!(tree.stage(&[mapping("runtime", "debug/runtime")]).is_err());
692    }
693
694    #[test]
695    fn does_not_replace_a_new_file_at_a_previously_owned_path() {
696        let tree = Tree::new();
697        fs::write(tree.workspace.join("asset"), "fixture data").unwrap();
698        let asset = mapping("asset", "debug/asset");
699        tree.stage(std::slice::from_ref(&asset)).unwrap();
700        let output = tree.target.join("debug/asset");
701        let new_artifact = tree.target.join("replacement");
702        fs::write(&new_artifact, "an artifact Cargo just created").unwrap();
703        fs::rename(&new_artifact, &output).unwrap();
704
705        assert!(tree.stage(std::slice::from_ref(&asset)).is_err());
706        assert_eq!(
707            fs::read_to_string(&output).unwrap(),
708            "an artifact Cargo just created"
709        );
710        tree.stage(&[]).unwrap();
711        assert_eq!(
712            fs::read_to_string(output).unwrap(),
713            "an artifact Cargo just created"
714        );
715    }
716
717    #[test]
718    fn validates_all_destinations_before_copying() {
719        let tree = Tree::new();
720        fs::write(tree.workspace.join("asset"), "content").unwrap();
721        fs::write(tree.target.join("cargo-output"), "build artifact").unwrap();
722        assert!(
723            tree.stage(&[mapping("asset", "new"), mapping("asset", "cargo-output")])
724                .is_err()
725        );
726        assert!(!tree.target.join("new").exists());
727        assert_eq!(
728            fs::read_to_string(tree.target.join("cargo-output")).unwrap(),
729            "build artifact"
730        );
731        assert!(
732            tree.stage(&[mapping("asset", "nested"), mapping("asset", "nested/entry")])
733                .is_err()
734        );
735        assert!(!tree.target.join("nested").exists());
736    }
737
738    #[test]
739    fn destinations_that_differ_only_by_case_are_one_destination() {
740        let tree = Tree::new();
741        fs::write(tree.workspace.join("asset"), "content").unwrap();
742        fs::write(tree.workspace.join("other"), "other").unwrap();
743        // Where case is not told apart the second would replace the first.
744        for (first, second) in [
745            ("debug/Data", "debug/data"),
746            ("debug/a/file", "debug/A/other"),
747            ("É/x", "é/y"),
748        ] {
749            let error = tree
750                .stage(&[mapping("asset", first), mapping("other", second)])
751                .unwrap_err();
752            assert!(
753                format!("{error:#}").contains("differ only by case"),
754                "{first} and {second}: {error:#}"
755            );
756            assert!(!tree.target.join(first).exists(), "{first}");
757            assert!(!tree.target.join(second).exists(), "{second}");
758        }
759        // Names that differ in more than that are two.
760        tree.stage(&[
761            mapping("asset", "debug/Data"),
762            mapping("other", "debug/data2"),
763        ])
764        .unwrap();
765        assert_eq!(
766            fs::read_to_string(tree.target.join("debug/Data")).unwrap(),
767            "content"
768        );
769        assert_eq!(
770            fs::read_to_string(tree.target.join("debug/data2")).unwrap(),
771            "other"
772        );
773    }
774
775    #[test]
776    fn checks_output_destination_relationships() {
777        // formal/pict/output-destinations.pict, with its seed rows.
778        let data = include_str!("../tests/data/output-destinations.pict.tsv");
779        for row in data.lines().skip(1) {
780            let values: Vec<_> = row.split_whitespace().collect();
781            let [relation, source, spelling] = values[..] else {
782                panic!("unexpected model row: {row}");
783            };
784            let tree = Tree::new();
785            let first_source = tree.workspace.join("first");
786            if source == "Directory" {
787                fs::create_dir(&first_source).unwrap();
788                fs::write(first_source.join("file"), "first").unwrap();
789            } else {
790                fs::write(first_source, "first").unwrap();
791            }
792            fs::write(tree.workspace.join("second"), "second").unwrap();
793            let first = "debug/nested/model";
794            let second = match relation {
795                "Same" => first,
796                "Ancestor" => "debug/nested",
797                "Descendant" => "debug/nested/model/data",
798                "Sibling" => "debug/nested/other",
799                "NamePrefix" => "debug/nested/models",
800                "DifferentRoot" => "release/nested/model",
801                _ => panic!("unexpected relation: {row}"),
802            };
803            let spelled = if spelling == "Normalized" {
804                format!("./{}", second.replace('/', "//./"))
805            } else {
806                second.to_owned()
807            };
808            let result = tree.stage(&[mapping("first", first), mapping("second", &spelled)]);
809            if matches!(relation, "Same" | "Ancestor" | "Descendant") {
810                assert_eq!(
811                    result.unwrap_err().to_string(),
812                    format!("overlapping output fixture destination: {second}"),
813                    "{row}"
814                );
815                assert!(!tree.target.join("debug").exists(), "{row}");
816                assert!(!tree.work.join(OWNERSHIP).exists(), "{row}");
817            } else {
818                result.unwrap();
819                let mut first_output = tree.target.join(first);
820                if source == "Directory" {
821                    first_output.push("file");
822                }
823                assert_eq!(fs::read_to_string(first_output).unwrap(), "first", "{row}");
824                assert_eq!(
825                    fs::read_to_string(tree.target.join(second)).unwrap(),
826                    "second",
827                    "{row}"
828                );
829            }
830        }
831    }
832
833    #[cfg(unix)]
834    #[test]
835    fn output_fixture_replays_pict_table() {
836        use std::os::unix::fs::symlink;
837        // formal/pict/output-fixture.pict, with its seed rows.
838        let data = include_str!("../tests/data/output-fixture.pict.tsv");
839        for row in data.lines().skip(1) {
840            let values: Vec<_> = row.trim().split('\t').collect();
841            let [source, destination, parent] = values[..] else {
842                panic!("unexpected model row: {row}");
843            };
844            let tree = Tree::new();
845            let input = tree.workspace.join("asset");
846            let ordinary = tree.workspace.join("ordinary");
847            fs::write(&ordinary, "value").unwrap();
848            match source {
849                "File" => fs::write(&input, "value").unwrap(),
850                "Directory" => {
851                    fs::create_dir(&input).unwrap();
852                    fs::write(input.join("entry"), "value").unwrap();
853                }
854                "LocalLink" => symlink(&ordinary, &input).unwrap(),
855                "OutsideLink" => symlink("/dev/null", &input).unwrap(),
856                "DanglingLink" => symlink("missing", &input).unwrap(),
857                _ => panic!("{row}"),
858            }
859            let output = tree.target.join("debug/asset");
860            if parent == "Present" {
861                fs::create_dir(output.parent().unwrap()).unwrap();
862            }
863            match destination {
864                "Vacant" => {}
865                "Occupied" => fs::write(&output, "unowned").unwrap(),
866                "Link" => symlink(&ordinary, &output).unwrap(),
867                _ => panic!("{row}"),
868            }
869            let accepted =
870                matches!(source, "File" | "Directory" | "LocalLink") && destination == "Vacant";
871            let result = tree.stage(&[mapping("asset", "debug/asset")]);
872            assert_eq!(result.is_ok(), accepted, "{row}: {result:?}");
873            if accepted {
874                let file = if source == "Directory" {
875                    output.join("entry")
876                } else {
877                    output
878                };
879                assert_eq!(fs::read_to_string(file).unwrap(), "value", "{row}");
880            } else if destination == "Occupied" {
881                assert_eq!(fs::read_to_string(output).unwrap(), "unowned", "{row}");
882            } else if destination == "Link" {
883                assert_eq!(fs::read_link(output).unwrap(), ordinary, "{row}");
884            } else {
885                assert!(!output.exists(), "{row}");
886            }
887            assert_eq!(fs::read_to_string(ordinary).unwrap(), "value", "{row}");
888        }
889    }
890
891    #[cfg(unix)]
892    #[test]
893    fn refuses_ancestor_links_and_source_cycles() {
894        use std::os::unix::fs::symlink;
895        let tree = Tree::new();
896        fs::write(tree.workspace.join("asset"), "content").unwrap();
897        let outside = tree.workspace.join("outside-target");
898        fs::create_dir(&outside).unwrap();
899        symlink(&outside, tree.target.join("linked")).unwrap();
900        assert!(tree.stage(&[mapping("asset", "linked/written")]).is_err());
901        assert!(!outside.join("written").exists());
902
903        let cyclic = tree.workspace.join("cycle");
904        fs::create_dir(&cyclic).unwrap();
905        symlink(&cyclic, cyclic.join("again")).unwrap();
906        assert!(tree.stage(&[mapping("cycle", "debug/cycle")]).is_err());
907        assert!(!tree.target.join("debug/cycle").exists());
908    }
909
910    #[test]
911    fn the_target_must_be_a_real_directory_inside_the_work_directory() {
912        let tree = Tree::new();
913        let refused = |target: &Path| {
914            let error = stage(&tree.workspace, &tree.work, target, &[]).unwrap_err();
915            assert!(
916                error.to_string().contains("inside the TMT work directory"),
917                "{}: {error:#}",
918                target.display()
919            );
920        };
921        refused(&tree.work);
922        refused(&tree.workspace);
923        #[cfg(unix)]
924        {
925            let link = tree.work.join("link");
926            std::os::unix::fs::symlink(&tree.target, &link).unwrap();
927            refused(&link);
928        }
929        tree.stage(&[]).unwrap();
930    }
931
932    #[test]
933    fn forgets_an_owned_directory_that_became_a_file() {
934        let tree = Tree::new();
935        fs::create_dir(tree.workspace.join("empty")).unwrap();
936        tree.stage(&[mapping("empty", "debug/dir")]).unwrap();
937        let output = tree.target.join("debug/dir");
938        fs::remove_dir(&output).unwrap();
939        fs::write(&output, "an artifact Cargo just created").unwrap();
940
941        tree.stage(&[]).unwrap();
942        assert_eq!(
943            fs::read_to_string(&output).unwrap(),
944            "an artifact Cargo just created"
945        );
946        assert!(tree.stage(&[mapping("empty", "debug/dir")]).is_err());
947    }
948
949    #[cfg(unix)]
950    #[test]
951    fn forgets_what_was_replaced_by_something_that_is_not_ours() {
952        // A file of ours replaced by a link: the link stays and nothing is written through it.
953        let tree = Tree::new();
954        fs::write(tree.workspace.join("asset"), "value").unwrap();
955        let asset = mapping("asset", "debug/asset");
956        tree.stage(std::slice::from_ref(&asset)).unwrap();
957        let output = tree.target.join("debug/asset");
958        fs::remove_file(&output).unwrap();
959        let elsewhere = tree.workspace.join("elsewhere");
960        fs::write(&elsewhere, "not ours").unwrap();
961        std::os::unix::fs::symlink(&elsewhere, &output).unwrap();
962
963        tree.stage(&[]).unwrap();
964        assert!(fs::symlink_metadata(&output).unwrap().is_symlink());
965        let error = tree.stage(std::slice::from_ref(&asset)).unwrap_err();
966        assert!(
967            error.to_string().contains("crosses an unsafe path"),
968            "{error:#}"
969        );
970        assert_eq!(fs::read_to_string(&elsewhere).unwrap(), "not ours");
971
972        // A directory of ours replaced by a file: what was in the directory is behind it.
973        let tree = Tree::new();
974        let input = tree.workspace.join("asset");
975        fs::create_dir(&input).unwrap();
976        fs::write(input.join("entry"), "value").unwrap();
977        tree.stage(std::slice::from_ref(&asset)).unwrap();
978        let output = tree.target.join("debug/asset");
979        fs::remove_dir_all(&output).unwrap();
980        fs::write(&output, "an artifact Cargo just created").unwrap();
981
982        tree.stage(&[]).unwrap();
983        assert_eq!(
984            fs::read_to_string(&output).unwrap(),
985            "an artifact Cargo just created"
986        );
987        assert!(tree.stage(std::slice::from_ref(&asset)).is_err());
988    }
989
990    #[test]
991    fn a_destination_of_another_kind_is_refused_before_anything_is_removed() {
992        let tree = Tree::new();
993        let input = tree.workspace.join("asset");
994        fs::create_dir(&input).unwrap();
995        fs::write(input.join("entry"), "value").unwrap();
996        let asset = mapping("asset", "debug/asset");
997        tree.stage(std::slice::from_ref(&asset)).unwrap();
998
999        // The source is now a file, and the directory that is ours is in its place.
1000        fs::remove_dir_all(&input).unwrap();
1001        fs::write(&input, "a file").unwrap();
1002        let error = tree.stage(std::slice::from_ref(&asset)).unwrap_err();
1003        assert!(
1004            error.to_string().contains("already exists: debug/asset"),
1005            "{error:#}"
1006        );
1007        assert_eq!(
1008            fs::read_to_string(tree.target.join("debug/asset/entry")).unwrap(),
1009            "value"
1010        );
1011        // Withdrawing the fixture first makes room for the file.
1012        tree.stage(&[]).unwrap();
1013        tree.stage(&[asset]).unwrap();
1014        assert_eq!(
1015            fs::read_to_string(tree.target.join("debug/asset")).unwrap(),
1016            "a file"
1017        );
1018    }
1019
1020    #[test]
1021    fn removes_the_parent_directories_it_created_and_no_others() {
1022        for existed in [true, false] {
1023            let tree = Tree::new();
1024            fs::write(tree.workspace.join("asset"), "value").unwrap();
1025            let parent = tree.target.join("debug");
1026            if existed {
1027                fs::create_dir(&parent).unwrap();
1028            }
1029            let asset = mapping("asset", "debug/nested/asset");
1030            // The second run finds the directories of the first in place.
1031            tree.stage(std::slice::from_ref(&asset)).unwrap();
1032            tree.stage(std::slice::from_ref(&asset)).unwrap();
1033            assert_eq!(
1034                fs::read_to_string(parent.join("nested/asset")).unwrap(),
1035                "value"
1036            );
1037            tree.stage(&[]).unwrap();
1038            assert!(!parent.join("nested").exists(), "existed: {existed}");
1039            assert_eq!(parent.is_dir(), existed);
1040        }
1041    }
1042
1043    /// Takes away the right to change the entries of a directory, and gives what
1044    /// restores it. Gives `None` where that holds nobody back (a privileged user),
1045    /// so that the caller can skip.
1046    #[cfg(unix)]
1047    fn deny_changes(dir: &Path) -> Option<impl FnOnce() + use<>> {
1048        use std::os::unix::fs::PermissionsExt;
1049        let set = |dir: &Path, mode| {
1050            fs::set_permissions(dir, fs::Permissions::from_mode(mode)).unwrap();
1051        };
1052        set(dir, 0o555);
1053        let probe = dir.join("probe");
1054        if fs::write(&probe, "").is_ok() {
1055            fs::remove_file(probe).unwrap();
1056            set(dir, 0o755);
1057            return None;
1058        }
1059        let dir = dir.to_path_buf();
1060        Some(move || set(&dir, 0o755))
1061    }
1062
1063    #[cfg(unix)]
1064    #[test]
1065    fn the_next_run_completes_an_install_that_was_interrupted() {
1066        let tree = Tree::new();
1067        let input = tree.workspace.join("asset");
1068        fs::write(&input, "first").unwrap();
1069        tree.stage(&[mapping("asset", "held/kept")]).unwrap();
1070
1071        // The second run installs one file and is stopped at the next.
1072        fs::write(&input, "second").unwrap();
1073        let both = [mapping("asset", "early/new"), mapping("asset", "held/kept")];
1074        let Some(allow) = deny_changes(&tree.target.join("held")) else {
1075            return;
1076        };
1077        let stopped = tree.stage(&both);
1078        allow();
1079        let error = stopped.unwrap_err();
1080        assert!(
1081            error.to_string().contains("installing output fixture"),
1082            "{error:#}"
1083        );
1084        let read = |path: &str| fs::read_to_string(tree.target.join(path)).unwrap();
1085        assert_eq!(read("early/new"), "second");
1086        assert_eq!(read("held/kept"), "first");
1087
1088        // Both files are still known as ours: the one installed and the one not yet.
1089        tree.stage(&both).unwrap();
1090        assert_eq!(read("early/new"), "second");
1091        assert_eq!(read("held/kept"), "second");
1092        tree.stage(&[]).unwrap();
1093        assert!(!tree.target.join("early").exists());
1094        assert!(!tree.target.join("held").exists());
1095    }
1096
1097    #[cfg(unix)]
1098    #[test]
1099    fn reports_an_old_fixture_that_cannot_be_removed() {
1100        for source in ["file", "directory"] {
1101            let tree = Tree::new();
1102            fs::write(tree.workspace.join("file"), "value").unwrap();
1103            fs::create_dir(tree.workspace.join("directory")).unwrap();
1104            tree.stage(&[mapping(source, "held/old")]).unwrap();
1105            let Some(allow) = deny_changes(&tree.target.join("held")) else {
1106                return;
1107            };
1108            let stopped = tree.stage(&[]);
1109            allow();
1110            let error = stopped.unwrap_err();
1111            assert!(
1112                error.to_string().contains("removing old output fixture"),
1113                "{source}: {error:#}"
1114            );
1115            assert!(tree.target.join("held/old").exists(), "{source}");
1116            tree.stage(&[]).unwrap();
1117            assert!(!tree.target.join("held").exists(), "{source}");
1118        }
1119    }
1120
1121    #[test]
1122    fn sources_are_not_taken_from_the_work_directory_build_output_or_git_data() {
1123        let tree = Tree::new();
1124        let write = |path: &str| {
1125            let path = tree.workspace.join(path);
1126            fs::create_dir_all(path.parent().unwrap()).unwrap();
1127            fs::write(path, "value").unwrap();
1128        };
1129        let refused = |from: &str| {
1130            let error = tree.stage(&[mapping(from, "debug/out")]).unwrap_err();
1131            assert!(
1132                error
1133                    .to_string()
1134                    .contains("outside the allowed workspace inputs"),
1135                "{from}: {error:#}"
1136            );
1137            assert!(!tree.target.join("debug").exists(), "{from}");
1138        };
1139        for path in [
1140            "work/secret",
1141            "target/built",
1142            ".git/config",
1143            "sub/.git/config",
1144            "sub/data",
1145            "plain/data",
1146            "targets/data",
1147            ".gitignore",
1148            "ordinary",
1149        ] {
1150            write(path);
1151        }
1152        for from in [
1153            "work/secret",
1154            "target/built",
1155            ".git/config",
1156            "sub/.git/config",
1157        ] {
1158            refused(from);
1159        }
1160        // A directory is refused for what it contains.
1161        refused("sub");
1162        #[cfg(unix)]
1163        {
1164            use std::os::unix::fs::symlink;
1165            // A link is judged by where it is and by what it names.
1166            let ordinary = tree.workspace.join("ordinary");
1167            symlink(&ordinary, tree.workspace.join("target/link")).unwrap();
1168            refused("target/link");
1169            for (name, hidden) in [
1170                ("to-git", ".git/config"),
1171                ("to-target", "target/built"),
1172                ("to-work", "work/secret"),
1173            ] {
1174                symlink(tree.workspace.join(hidden), tree.workspace.join(name)).unwrap();
1175                refused(name);
1176            }
1177        }
1178        // Names that only resemble the refused ones are ordinary inputs.
1179        for (index, from) in ["plain/data", "targets/data", ".gitignore", "ordinary"]
1180            .into_iter()
1181            .enumerate()
1182        {
1183            let to = format!("debug/{index}");
1184            tree.stage(&[mapping(from, &to)]).unwrap();
1185            assert_eq!(
1186                fs::read_to_string(tree.target.join(to)).unwrap(),
1187                "value",
1188                "{from}"
1189            );
1190        }
1191    }
1192
1193    #[cfg(unix)]
1194    #[test]
1195    fn copies_a_directory_that_two_links_name() {
1196        use std::os::unix::fs::symlink;
1197        let tree = Tree::new();
1198        let common = tree.workspace.join("common");
1199        let source = tree.workspace.join("source");
1200        fs::create_dir(&common).unwrap();
1201        fs::create_dir(&source).unwrap();
1202        fs::write(common.join("file"), "value").unwrap();
1203        symlink(&common, source.join("one")).unwrap();
1204        symlink(&common, source.join("two")).unwrap();
1205        // Seen twice, but not inside itself: this is no cycle.
1206        tree.stage(&[mapping("source", "debug/source")]).unwrap();
1207        for name in ["one", "two"] {
1208            assert_eq!(
1209                fs::read_to_string(tree.target.join("debug/source").join(name).join("file"))
1210                    .unwrap(),
1211                "value"
1212            );
1213        }
1214    }
1215
1216    #[cfg(unix)]
1217    #[test]
1218    fn a_destination_that_cannot_be_inspected_is_refused_before_copying() {
1219        let tree = Tree::new();
1220        fs::write(tree.workspace.join("asset"), "value").unwrap();
1221        // Longer than any name a file system holds.
1222        let unusable = "z".repeat(300);
1223        let error = tree
1224            .stage(&[mapping("asset", "first"), mapping("asset", &unusable)])
1225            .unwrap_err();
1226        assert!(error.to_string().contains("inspecting"), "{error:#}");
1227        assert!(!tree.target.join("first").exists());
1228        assert!(!tree.work.join(OWNERSHIP).exists());
1229    }
1230
1231    #[test]
1232    fn leaves_no_staging_directory_behind() {
1233        let tree = Tree::new();
1234        fs::write(tree.workspace.join("asset"), "value").unwrap();
1235        let staging = tree.work.join(STAGING);
1236        // What an interrupted run left is replaced.
1237        fs::create_dir(&staging).unwrap();
1238        fs::write(staging.join("0"), "stale").unwrap();
1239        tree.stage(&[mapping("asset", "debug/asset")]).unwrap();
1240        assert_eq!(
1241            fs::read_to_string(tree.target.join("debug/asset")).unwrap(),
1242            "value"
1243        );
1244        assert!(!staging.exists());
1245        assert!(!tree.work.join(OWNERSHIP_TEMP).exists());
1246    }
1247
1248    #[cfg(unix)]
1249    #[test]
1250    fn a_staged_file_keeps_the_permissions_of_its_source() {
1251        use std::os::unix::fs::PermissionsExt;
1252        let tree = Tree::new();
1253        // Whatever the umask is, it does not give both of these to a new file.
1254        for (name, mode) in [("tool", 0o750), ("data", 0o640)] {
1255            let input = tree.workspace.join(name);
1256            fs::write(&input, "value").unwrap();
1257            fs::set_permissions(&input, fs::Permissions::from_mode(mode)).unwrap();
1258        }
1259        tree.stage(&[mapping("tool", "debug/tool"), mapping("data", "debug/data")])
1260            .unwrap();
1261        for (name, mode) in [("tool", 0o750), ("data", 0o640)] {
1262            let staged = fs::metadata(tree.target.join("debug").join(name)).unwrap();
1263            assert_eq!(staged.permissions().mode() & 0o777, mode, "{name}");
1264        }
1265    }
1266
1267    #[test]
1268    fn refuses_an_ownership_record_whose_paths_are_not_confined_and_plain() {
1269        let tree = Tree::new();
1270        let record = tree.work.join(OWNERSHIP);
1271        for path in ["./debug/asset", "../outside", "/outside"] {
1272            let text = serde_json::json!({ path: "directory" }).to_string();
1273            fs::write(&record, &text).unwrap();
1274            assert!(tree.stage(&[]).is_err(), "{path}");
1275            assert_eq!(fs::read_to_string(&record).unwrap(), text, "{path}");
1276        }
1277        fs::write(&record, r#"{"debug/asset":"directory"}"#).unwrap();
1278        tree.stage(&[]).unwrap();
1279    }
1280
1281    #[test]
1282    fn replacing_owned_fixture_with_different_case_succeeds() {
1283        let tree = Tree::new();
1284        fs::write(tree.workspace.join("asset"), "first").unwrap();
1285        tree.stage(&[mapping("asset", "debug/Data")]).unwrap();
1286        assert_eq!(
1287            fs::read_to_string(tree.target.join("debug/Data")).unwrap(),
1288            "first"
1289        );
1290
1291        fs::write(tree.workspace.join("asset"), "second").unwrap();
1292        tree.stage(&[mapping("asset", "debug/data")]).unwrap();
1293        assert_eq!(
1294            fs::read_to_string(tree.target.join("debug/data")).unwrap(),
1295            "second"
1296        );
1297    }
1298
1299    #[test]
1300    fn hard_link_is_not_treated_as_same_directory_entry() {
1301        let tree = Tree::new();
1302        fs::write(tree.workspace.join("asset"), "first").unwrap();
1303        tree.stage(&[mapping("asset", "debug/Data")]).unwrap();
1304        let owned = tree.target.join("debug/Data");
1305        let sibling_link = tree.target.join("debug/alias");
1306        fs::hard_link(&owned, &sibling_link).unwrap();
1307        assert!(
1308            !same_directory_entry(
1309                &tree.target,
1310                Path::new("debug/Data"),
1311                &fs::symlink_metadata(&owned).unwrap(),
1312                Path::new("debug/alias"),
1313                &fs::symlink_metadata(&sibling_link).unwrap(),
1314            )
1315            .unwrap()
1316        );
1317
1318        // On case-sensitive filesystems, an unowned hard link with a case-differing name
1319        // must be rejected as an existing destination and preserved.
1320        let lower = tree.target.join("debug/data");
1321        if fs::hard_link(&owned, &lower).is_ok() {
1322            fs::write(tree.workspace.join("asset"), "second").unwrap();
1323            let err = tree.stage(&[mapping("asset", "debug/data")]).unwrap_err();
1324            assert!(
1325                format!("{err:#}").contains("already exists"),
1326                "unexpected error: {err:#}"
1327            );
1328            assert_eq!(fs::read_to_string(&owned).unwrap(), "first");
1329            assert_eq!(fs::read_to_string(&lower).unwrap(), "first");
1330        }
1331    }
1332}