nextest-runner 0.114.0

Core runner logic for cargo nextest.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
// Copyright (c) The nextest Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

use crate::{
    errors::{FromMessagesError, RustBuildMetaParseError, WriteTestListError},
    helpers::convert_rel_path_to_forward_slash,
    list::{BinaryListState, OutputFormat, RustBuildMeta, Styles},
    platform::BuildPlatforms,
    write_str::WriteStr,
};
use camino::{Utf8Path, Utf8PathBuf};
use cargo_metadata::{Artifact, BuildScript, Message, PackageId, TargetKind};
use guppy::graph::PackageGraph;
use nextest_metadata::{
    BinaryListSummary, BuildPlatform, RustBinaryId, RustNonTestBinaryKind,
    RustNonTestBinarySummary, RustTestBinaryKind, RustTestBinarySummary,
};
use owo_colors::OwoColorize;
use serde::Deserialize;
use std::{
    collections::{BTreeMap, HashSet},
    io,
};
use tracing::{debug, warn};

/// A Rust test binary built by Cargo.
#[derive(Clone, Debug)]
pub struct RustTestBinary {
    /// A unique ID.
    pub id: RustBinaryId,
    /// The path to the binary artifact.
    pub path: Utf8PathBuf,
    /// The package this artifact belongs to.
    pub package_id: String,
    /// The kind of Rust test binary this is.
    pub kind: RustTestBinaryKind,
    /// The unique binary name defined in `Cargo.toml` or inferred by the filename.
    pub name: String,
    /// Platform for which this binary was built.
    /// (Proc-macro tests are built for the host.)
    pub build_platform: BuildPlatform,
}

/// The list of Rust test binaries built by Cargo.
#[derive(Clone, Debug)]
pub struct BinaryList {
    /// Rust-related metadata.
    pub rust_build_meta: RustBuildMeta<BinaryListState>,

    /// The list of test binaries.
    pub rust_binaries: Vec<RustTestBinary>,
}

impl BinaryList {
    /// Parses Cargo messages from the given `BufRead` and returns a list of test binaries.
    pub fn from_messages(
        reader: impl io::BufRead,
        graph: &PackageGraph,
        build_platforms: BuildPlatforms,
    ) -> Result<Self, FromMessagesError> {
        let mut builder = BinaryListBuilder::new(graph, build_platforms);

        for message in Message::parse_stream(reader) {
            let message = message.map_err(FromMessagesError::ReadMessages)?;
            builder.process_message(message)?;
        }

        Ok(builder.finish())
    }

    /// Constructs the list from its summary format
    pub fn from_summary(summary: BinaryListSummary) -> Result<Self, RustBuildMetaParseError> {
        let rust_binaries = summary
            .rust_binaries
            .into_values()
            .map(|bin| RustTestBinary {
                name: bin.binary_name,
                path: bin.binary_path,
                package_id: bin.package_id,
                kind: bin.kind,
                id: bin.binary_id,
                build_platform: bin.build_platform,
            })
            .collect();
        Ok(Self {
            rust_build_meta: RustBuildMeta::from_summary(summary.rust_build_meta)?,
            rust_binaries,
        })
    }

    /// Outputs this list to the given writer.
    pub fn write(
        &self,
        output_format: OutputFormat,
        writer: &mut dyn WriteStr,
        colorize: bool,
    ) -> Result<(), WriteTestListError> {
        match output_format {
            OutputFormat::Human { verbose } => self
                .write_human(writer, verbose, colorize)
                .map_err(WriteTestListError::Io),
            OutputFormat::Oneline { verbose } => self
                .write_oneline(writer, verbose, colorize)
                .map_err(WriteTestListError::Io),
            OutputFormat::Serializable(format) => format.to_writer(&self.to_summary(), writer),
        }
    }

    fn to_summary(&self) -> BinaryListSummary {
        BinaryListSummary {
            rust_build_meta: self.rust_build_meta.to_summary(),
            rust_binaries: self.binary_summaries(),
        }
    }

    /// Produces a summary suitable for archive metadata.
    ///
    /// * `build_directory` is omitted so it defaults to `target_directory` on
    ///   extraction.
    /// * Binary paths under `build_directory` are remapped to `target_directory`
    ///   so the `PathMapper` can remap them correctly on extraction.
    pub(crate) fn to_archive_summary(&self) -> BinaryListSummary {
        let target_dir = &self.rust_build_meta.target_directory;
        let build_directory = &self.rust_build_meta.build_directory;

        let rust_binaries = self
            .rust_binaries
            .iter()
            .map(|bin| {
                // In the archive, test binaries are stored under target/.
                // Remap paths from build_directory to target_directory so the PathMapper
                // can relocate them on extraction.
                let binary_path = target_dir.join(
                    bin.path
                        .strip_prefix(build_directory)
                        .expect("test binary paths must be within the build directory"),
                );
                let summary = RustTestBinarySummary {
                    binary_name: bin.name.clone(),
                    package_id: bin.package_id.clone(),
                    kind: bin.kind.clone(),
                    binary_path,
                    binary_id: bin.id.clone(),
                    build_platform: bin.build_platform,
                };
                (bin.id.clone(), summary)
            })
            .collect();

        BinaryListSummary {
            rust_build_meta: self.rust_build_meta.to_archive_summary(),
            rust_binaries,
        }
    }

    fn binary_summaries(&self) -> BTreeMap<RustBinaryId, RustTestBinarySummary> {
        self.rust_binaries
            .iter()
            .map(|bin| {
                let summary = RustTestBinarySummary {
                    binary_name: bin.name.clone(),
                    package_id: bin.package_id.clone(),
                    kind: bin.kind.clone(),
                    binary_path: bin.path.clone(),
                    binary_id: bin.id.clone(),
                    build_platform: bin.build_platform,
                };
                (bin.id.clone(), summary)
            })
            .collect()
    }

    fn write_human(
        &self,
        writer: &mut dyn WriteStr,
        verbose: bool,
        colorize: bool,
    ) -> io::Result<()> {
        let mut styles = Styles::default();
        if colorize {
            styles.colorize();
        }
        for bin in &self.rust_binaries {
            if verbose {
                writeln!(writer, "{}:", bin.id.style(styles.binary_id))?;
                writeln!(writer, "  {} {}", "bin:".style(styles.field), bin.path)?;
                writeln!(
                    writer,
                    "  {} {}",
                    "build platform:".style(styles.field),
                    bin.build_platform,
                )?;
            } else {
                writeln!(writer, "{}", bin.id.style(styles.binary_id))?;
            }
        }
        Ok(())
    }

    fn write_oneline(
        &self,
        writer: &mut dyn WriteStr,
        verbose: bool,
        colorize: bool,
    ) -> io::Result<()> {
        let mut styles = Styles::default();
        if colorize {
            styles.colorize();
        }
        for bin in &self.rust_binaries {
            write!(writer, "{}", bin.id.style(styles.binary_id))?;
            if verbose {
                write!(
                    writer,
                    " [{}{}] [{}{}]",
                    "bin: ".style(styles.field),
                    bin.path,
                    "build platform: ".style(styles.field),
                    bin.build_platform,
                )?;
            }
            writeln!(writer)?;
        }
        Ok(())
    }

    /// Outputs this list as a string with the given format.
    pub fn to_string(&self, output_format: OutputFormat) -> Result<String, WriteTestListError> {
        let mut s = String::with_capacity(1024);
        self.write(output_format, &mut s, false)?;
        Ok(s)
    }
}

/// Incrementally builds a [`BinaryList`] from Cargo messages.
#[derive(Debug)]
pub struct BinaryListBuilder<'g> {
    state: BinaryListBuildState<'g>,
}

impl<'g> BinaryListBuilder<'g> {
    /// Creates a new builder for Cargo messages.
    pub fn new(graph: &'g PackageGraph, build_platforms: BuildPlatforms) -> Self {
        Self {
            state: BinaryListBuildState::new(graph, build_platforms),
        }
    }

    /// Processes a single Cargo message.
    pub fn process_message(&mut self, message: Message) -> Result<(), FromMessagesError> {
        self.state.process_message(message)
    }

    /// Processes a single line of Cargo output.
    ///
    /// This uses the same single-line parsing behavior as
    /// [`cargo_metadata::Message::parse_stream`].
    pub fn process_message_line(&mut self, line: &str) -> Result<(), FromMessagesError> {
        self.process_message(parse_message_line(line))
    }

    /// Finishes building the binary list.
    pub fn finish(self) -> BinaryList {
        self.state.finish()
    }
}

// Adapted from cargo_metadata::MessageIter::next (cargo_metadata 0.23.1).
fn parse_message_line(line: &str) -> Message {
    let mut deserializer = serde_json::Deserializer::from_str(line);
    deserializer.disable_recursion_limit();
    Message::deserialize(&mut deserializer).unwrap_or_else(|_| Message::TextLine(line.to_owned()))
}

#[derive(Debug)]
struct BinaryListBuildState<'g> {
    graph: &'g PackageGraph,
    rust_binaries: Vec<RustTestBinary>,
    rust_build_meta: RustBuildMeta<BinaryListState>,
    alt_target_dir: Option<Utf8PathBuf>,
}

impl<'g> BinaryListBuildState<'g> {
    fn new(graph: &'g PackageGraph, build_platforms: BuildPlatforms) -> Self {
        let rust_target_dir = graph.workspace().target_directory().to_path_buf();
        // Use the build directory if on Cargo 1.91 or newer. Fall back to
        // the target directory for older Cargo versions.
        let build_directory = graph
            .workspace()
            .build_directory()
            .unwrap_or_else(|| graph.workspace().target_directory())
            .to_path_buf();
        // For testing only, not part of the public API.
        let alt_target_dir = std::env::var("__NEXTEST_ALT_TARGET_DIR")
            .ok()
            .map(Utf8PathBuf::from);

        Self {
            graph,
            rust_binaries: vec![],
            rust_build_meta: RustBuildMeta::new(rust_target_dir, build_directory, build_platforms),
            alt_target_dir,
        }
    }

    fn process_message(&mut self, message: Message) -> Result<(), FromMessagesError> {
        match message {
            Message::CompilerArtifact(artifact) => {
                self.process_artifact(artifact)?;
            }
            Message::BuildScriptExecuted(build_script) => {
                self.process_build_script(build_script)?;
            }
            _ => {
                // Ignore all other messages.
            }
        }

        Ok(())
    }

    fn process_artifact(&mut self, artifact: Artifact) -> Result<(), FromMessagesError> {
        if let Some(path) = artifact.executable {
            self.detect_base_output_dir(&path);

            if artifact.profile.test {
                let package_id = artifact.package_id.repr;

                // Look up the executable by package ID.

                let name = artifact.target.name;

                let package = self
                    .graph
                    .metadata(&guppy::PackageId::new(package_id.clone()))
                    .map_err(FromMessagesError::PackageGraph)?;

                let kind = artifact.target.kind;
                if kind.is_empty() {
                    return Err(FromMessagesError::MissingTargetKind {
                        package_name: package.name().to_owned(),
                        binary_name: name.clone(),
                    });
                }

                let (computed_kind, platform) = if kind.iter().any(|k| {
                    // https://doc.rust-lang.org/nightly/cargo/reference/cargo-targets.html#the-crate-type-field
                    matches!(
                        k,
                        TargetKind::Lib
                            | TargetKind::RLib
                            | TargetKind::DyLib
                            | TargetKind::CDyLib
                            | TargetKind::StaticLib
                    )
                }) {
                    (RustTestBinaryKind::LIB, BuildPlatform::Target)
                } else if let Some(TargetKind::ProcMacro) = kind.first() {
                    (RustTestBinaryKind::PROC_MACRO, BuildPlatform::Host)
                } else {
                    // Non-lib kinds should always have just one element. Grab the first one.
                    (
                        RustTestBinaryKind::new(
                            kind.into_iter()
                                .next()
                                .expect("already checked that kind is non-empty")
                                .to_string(),
                        ),
                        BuildPlatform::Target,
                    )
                };

                // Construct the binary ID from the package and build target.
                let id = RustBinaryId::from_parts(package.name(), &computed_kind, &name);

                self.rust_binaries.push(RustTestBinary {
                    path,
                    package_id,
                    kind: computed_kind,
                    name,
                    id,
                    build_platform: platform,
                });
            } else if artifact
                .target
                .kind
                .iter()
                .any(|x| matches!(x, TargetKind::Bin))
            {
                // This is a non-test binary -- add it to the map.
                // Error case here implies that the returned path wasn't in the target directory -- ignore it
                // since it shouldn't happen in normal use.
                if let Ok(rel_path) = path.strip_prefix(&self.rust_build_meta.target_directory) {
                    let non_test_binary = RustNonTestBinarySummary {
                        name: artifact.target.name,
                        kind: RustNonTestBinaryKind::BIN_EXE,
                        path: convert_rel_path_to_forward_slash(rel_path),
                    };

                    self.rust_build_meta
                        .non_test_binaries
                        .entry(artifact.package_id.repr)
                        .or_default()
                        .insert(non_test_binary);
                };
            }
        } else if artifact
            .target
            .kind
            .iter()
            .any(|x| matches!(x, TargetKind::DyLib | TargetKind::CDyLib))
        {
            // Also look for and grab dynamic libraries to store in archives.
            for filename in artifact.filenames {
                if let Ok(rel_path) = filename.strip_prefix(&self.rust_build_meta.target_directory)
                {
                    let non_test_binary = RustNonTestBinarySummary {
                        name: artifact.target.name.clone(),
                        kind: RustNonTestBinaryKind::DYLIB,
                        path: convert_rel_path_to_forward_slash(rel_path),
                    };
                    self.rust_build_meta
                        .non_test_binaries
                        .entry(artifact.package_id.repr.clone())
                        .or_default()
                        .insert(non_test_binary);
                }
            }
        }

        Ok(())
    }

    /// Look for paths that contain "deps" in their second-to-last component,
    /// and are descendants of the target directory.
    /// The paths without "deps" are base output directories.
    ///
    /// e.g. path/to/repo/target/debug/deps/test-binary => add "debug"
    /// to base output dirs.
    ///
    /// Note that test binaries are always present in "deps", so we should always
    /// have a match.
    ///
    /// The `Option` in the return value is to let ? work.
    fn detect_base_output_dir(&mut self, artifact_path: &Utf8Path) -> Option<()> {
        // Artifact paths must be relative to the build directory (which
        // equals the target directory unless Cargo's build.build-dir is
        // configured).
        let rel_path = match artifact_path.strip_prefix(&self.rust_build_meta.build_directory) {
            Ok(rel) => rel,
            Err(_) => {
                debug!(
                    target: "nextest-runner::list",
                    "artifact path `{}` is not within the build directory `{}`, \
                     skipping base output directory detection",
                    artifact_path, self.rust_build_meta.build_directory,
                );
                return None;
            }
        };
        let parent = rel_path.parent()?;
        if parent.file_name() == Some("deps") {
            let base = parent.parent()?;
            if !self.rust_build_meta.base_output_directories.contains(base) {
                self.rust_build_meta
                    .base_output_directories
                    .insert(convert_rel_path_to_forward_slash(base));
            }
        }
        Some(())
    }

    fn process_build_script(&mut self, build_script: BuildScript) -> Result<(), FromMessagesError> {
        for path in build_script.linked_paths {
            self.detect_linked_path(&build_script.package_id, &path);
        }

        // We only care about build scripts for workspace packages.
        let package_id = guppy::PackageId::new(build_script.package_id.repr);
        let in_workspace = self.graph.metadata(&package_id).map_or_else(
            |_| {
                // Warn about processing a package that isn't in the package graph.
                warn!(
                    target: "nextest-runner::list",
                    "warning: saw package ID `{}` which wasn't produced by cargo metadata",
                    package_id
                );
                false
            },
            |p| p.in_workspace(),
        );
        if in_workspace {
            // Build script out_dirs are relative to the build directory.
            match build_script
                .out_dir
                .strip_prefix(&self.rust_build_meta.build_directory)
            {
                Ok(rel_out_dir) => {
                    self.rust_build_meta.build_script_out_dirs.insert(
                        package_id.repr().to_owned(),
                        convert_rel_path_to_forward_slash(rel_out_dir),
                    );
                }
                Err(_) => {
                    debug!(
                        target: "nextest-runner::list",
                        "build script out_dir `{}` for package `{}` is not within \
                         the build directory `{}`, skipping",
                        build_script.out_dir, package_id,
                        self.rust_build_meta.build_directory,
                    );
                }
            }

            // Capture build script environment variables from the structured
            // cargo message, avoiding the need to parse the raw output file.
            if !build_script.env.is_empty() {
                self.rust_build_meta
                    .build_script_info
                    .get_or_insert_with(BTreeMap::new)
                    .entry(package_id.repr().to_owned())
                    .or_default()
                    .envs = build_script.env.into_iter().collect();
            }
        }

        Ok(())
    }

    /// The `Option` in the return value is to let ? work.
    fn detect_linked_path(&mut self, package_id: &PackageId, path: &Utf8Path) -> Option<()> {
        // Remove anything up to the first "=" (e.g. "native=").
        let actual_path = match path.as_str().split_once('=') {
            Some((_, p)) => p.into(),
            None => path,
        };

        let rel_path = match actual_path.strip_prefix(&self.rust_build_meta.build_directory) {
            Ok(rel) => rel,
            Err(_) => {
                // For a seeded build (like in our test suite), Cargo will
                // return:
                //
                // * the new path if the linked path exists
                // * the original path if the linked path does not exist
                //
                // Linked paths not existing is not an ordinary condition, but
                // we want to test it within nextest. We filter out paths if
                // they're not a subdirectory of the target directory. With
                // __NEXTEST_ALT_TARGET_DIR, we can simulate that for an
                // alternate target directory.
                if let Some(alt_target_dir) = &self.alt_target_dir {
                    actual_path.strip_prefix(alt_target_dir).ok()?
                } else {
                    return None;
                }
            }
        };

        self.rust_build_meta
            .linked_paths
            .entry(convert_rel_path_to_forward_slash(rel_path))
            .or_default()
            .insert(package_id.repr.clone());

        Some(())
    }

    fn finish(mut self) -> BinaryList {
        self.rust_binaries.sort_by(|b1, b2| b1.id.cmp(&b2.id));

        // Clean out any build script output directories for which there's no corresponding binary.
        let relevant_package_ids = self
            .rust_binaries
            .iter()
            .map(|bin| bin.package_id.clone())
            .collect::<HashSet<_>>();

        self.rust_build_meta
            .build_script_out_dirs
            .retain(|package_id, _| relevant_package_ids.contains(package_id));
        if let Some(info) = &mut self.rust_build_meta.build_script_info {
            info.retain(|package_id, _| relevant_package_ids.contains(package_id));
        }

        BinaryList {
            rust_build_meta: self.rust_build_meta,
            rust_binaries: self.rust_binaries,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        cargo_config::{TargetDefinitionLocation, TargetTriple, TargetTripleSource},
        list::{
            SerializableFormat,
            test_helpers::{PACKAGE_GRAPH_FIXTURE, PACKAGE_METADATA_ID, package_metadata},
        },
        platform::{HostPlatform, PlatformLibdir, TargetPlatform},
    };
    use indoc::indoc;
    use maplit::btreeset;
    use nextest_metadata::PlatformLibdirUnavailable;
    use pretty_assertions::assert_eq;
    use serde_json::json;
    use target_spec::{Platform, TargetFeatures};

    #[test]
    fn test_parse_binary_list() {
        let fake_bin_test = RustTestBinary {
            id: "fake-package::bin/fake-binary".into(),
            path: "/fake/binary".into(),
            package_id: "fake-package 0.1.0 (path+file:///Users/fakeuser/project/fake-package)"
                .to_owned(),
            kind: RustTestBinaryKind::LIB,
            name: "fake-binary".to_owned(),
            build_platform: BuildPlatform::Target,
        };
        let fake_macro_test = RustTestBinary {
            id: "fake-macro::proc-macro/fake-macro".into(),
            path: "/fake/macro".into(),
            package_id: "fake-macro 0.1.0 (path+file:///Users/fakeuser/project/fake-macro)"
                .to_owned(),
            kind: RustTestBinaryKind::PROC_MACRO,
            name: "fake-macro".to_owned(),
            build_platform: BuildPlatform::Host,
        };

        let fake_triple = TargetTriple {
            platform: Platform::new("aarch64-unknown-linux-gnu", TargetFeatures::Unknown).unwrap(),
            source: TargetTripleSource::CliOption,
            location: TargetDefinitionLocation::Builtin,
        };
        let fake_host_libdir = "/home/fake/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-unknown-linux-gnu/lib";
        let build_platforms = BuildPlatforms {
            host: HostPlatform {
                platform: TargetTriple::x86_64_unknown_linux_gnu().platform,
                libdir: PlatformLibdir::Available(Utf8PathBuf::from(fake_host_libdir)),
            },
            target: Some(TargetPlatform {
                triple: fake_triple,
                // Test out the error case for unavailable libdirs.
                libdir: PlatformLibdir::Unavailable(PlatformLibdirUnavailable::RUSTC_OUTPUT_ERROR),
            }),
        };

        let mut rust_build_meta =
            RustBuildMeta::new("/fake/target", "/fake/target", build_platforms);
        rust_build_meta
            .base_output_directories
            .insert("my-profile".into());
        rust_build_meta.non_test_binaries.insert(
            "my-package-id".into(),
            btreeset! {
                RustNonTestBinarySummary {
                    name: "my-name".into(),
                    kind: RustNonTestBinaryKind::BIN_EXE,
                    path: "my-profile/my-name".into(),
                },
                RustNonTestBinarySummary {
                    name: "your-name".into(),
                    kind: RustNonTestBinaryKind::DYLIB,
                    path: "my-profile/your-name.dll".into(),
                },
                RustNonTestBinarySummary {
                    name: "your-name".into(),
                    kind: RustNonTestBinaryKind::DYLIB,
                    path: "my-profile/your-name.exp".into(),
                },
            },
        );

        let binary_list = BinaryList {
            rust_build_meta,
            rust_binaries: vec![fake_bin_test, fake_macro_test],
        };

        // Check that the expected outputs are valid.
        static EXPECTED_HUMAN: &str = indoc! {"
        fake-package::bin/fake-binary
        fake-macro::proc-macro/fake-macro
        "};
        static EXPECTED_HUMAN_VERBOSE: &str = indoc! {r"
        fake-package::bin/fake-binary:
          bin: /fake/binary
          build platform: target
        fake-macro::proc-macro/fake-macro:
          bin: /fake/macro
          build platform: host
        "};
        static EXPECTED_JSON_PRETTY: &str = indoc! {r#"
        {
          "rust-build-meta": {
            "target-directory": "/fake/target",
            "build-directory": "/fake/target",
            "base-output-directories": [
              "my-profile"
            ],
            "non-test-binaries": {
              "my-package-id": [
                {
                  "name": "my-name",
                  "kind": "bin-exe",
                  "path": "my-profile/my-name"
                },
                {
                  "name": "your-name",
                  "kind": "dylib",
                  "path": "my-profile/your-name.dll"
                },
                {
                  "name": "your-name",
                  "kind": "dylib",
                  "path": "my-profile/your-name.exp"
                }
              ]
            },
            "build-script-out-dirs": {},
            "build-script-info": {},
            "linked-paths": [],
            "platforms": {
              "host": {
                "platform": {
                  "triple": "x86_64-unknown-linux-gnu",
                  "target-features": "unknown"
                },
                "libdir": {
                  "status": "available",
                  "path": "/home/fake/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-unknown-linux-gnu/lib"
                }
              },
              "targets": [
                {
                  "platform": {
                    "triple": "aarch64-unknown-linux-gnu",
                    "target-features": "unknown"
                  },
                  "libdir": {
                    "status": "unavailable",
                    "reason": "rustc-output-error"
                  }
                }
              ]
            },
            "target-platforms": [
              {
                "triple": "aarch64-unknown-linux-gnu",
                "target-features": "unknown"
              }
            ],
            "target-platform": "aarch64-unknown-linux-gnu"
          },
          "rust-binaries": {
            "fake-macro::proc-macro/fake-macro": {
              "binary-id": "fake-macro::proc-macro/fake-macro",
              "binary-name": "fake-macro",
              "package-id": "fake-macro 0.1.0 (path+file:///Users/fakeuser/project/fake-macro)",
              "kind": "proc-macro",
              "binary-path": "/fake/macro",
              "build-platform": "host"
            },
            "fake-package::bin/fake-binary": {
              "binary-id": "fake-package::bin/fake-binary",
              "binary-name": "fake-binary",
              "package-id": "fake-package 0.1.0 (path+file:///Users/fakeuser/project/fake-package)",
              "kind": "lib",
              "binary-path": "/fake/binary",
              "build-platform": "target"
            }
          }
        }"#};
        // Non-verbose oneline is the same as non-verbose human.
        static EXPECTED_ONELINE: &str = indoc! {"
            fake-package::bin/fake-binary
            fake-macro::proc-macro/fake-macro
        "};
        static EXPECTED_ONELINE_VERBOSE: &str = indoc! {r"
            fake-package::bin/fake-binary [bin: /fake/binary] [build platform: target]
            fake-macro::proc-macro/fake-macro [bin: /fake/macro] [build platform: host]
        "};

        assert_eq!(
            binary_list
                .to_string(OutputFormat::Human { verbose: false })
                .expect("human succeeded"),
            EXPECTED_HUMAN
        );
        assert_eq!(
            binary_list
                .to_string(OutputFormat::Human { verbose: true })
                .expect("human succeeded"),
            EXPECTED_HUMAN_VERBOSE
        );
        assert_eq!(
            binary_list
                .to_string(OutputFormat::Serializable(SerializableFormat::JsonPretty))
                .expect("json-pretty succeeded"),
            EXPECTED_JSON_PRETTY
        );
        assert_eq!(
            binary_list
                .to_string(OutputFormat::Oneline { verbose: false })
                .expect("oneline succeeded"),
            EXPECTED_ONELINE
        );
        assert_eq!(
            binary_list
                .to_string(OutputFormat::Oneline { verbose: true })
                .expect("oneline verbose succeeded"),
            EXPECTED_ONELINE_VERBOSE
        );
    }

    #[test]
    fn test_parse_binary_list_from_message_lines() {
        let build_platforms = BuildPlatforms {
            host: HostPlatform {
                platform: TargetTriple::x86_64_unknown_linux_gnu().platform,
                libdir: PlatformLibdir::Available("/fake/libdir".into()),
            },
            target: None,
        };
        let package = package_metadata();
        let artifact_path = PACKAGE_GRAPH_FIXTURE
            .workspace()
            .target_directory()
            .join("debug/deps/metadata_helper-test");
        let src_path = package
            .manifest_path()
            .parent()
            .expect("manifest path has a parent")
            .join("src/lib.rs");

        let compiler_artifact = json!({
            "reason": "compiler-artifact",
            "package_id": PACKAGE_METADATA_ID,
            "manifest_path": package.manifest_path(),
            "target": {
                "name": package.name(),
                "kind": ["lib"],
                "crate_types": ["lib"],
                "required-features": [],
                "src_path": src_path,
                "edition": "2021",
                "doctest": true,
                "test": true,
                "doc": true
            },
            "profile": {
                "opt_level": "0",
                "debuginfo": 0,
                "debug_assertions": true,
                "overflow_checks": true,
                "test": true
            },
            "features": [],
            "filenames": [artifact_path],
            "executable": artifact_path,
            "fresh": false
        });
        let input = format!("this is not JSON\n{}\n\n", compiler_artifact);

        let from_messages = BinaryList::from_messages(
            input.as_bytes(),
            &PACKAGE_GRAPH_FIXTURE,
            build_platforms.clone(),
        )
        .expect("parsing from messages succeeds");

        let mut builder = BinaryListBuilder::new(&PACKAGE_GRAPH_FIXTURE, build_platforms);
        for line in input.lines() {
            builder
                .process_message_line(line)
                .expect("processing line succeeds");
        }
        let from_lines = builder.finish();

        assert_eq!(
            from_lines
                .to_string(OutputFormat::Serializable(SerializableFormat::JsonPretty))
                .expect("json-pretty succeeds"),
            from_messages
                .to_string(OutputFormat::Serializable(SerializableFormat::JsonPretty))
                .expect("json-pretty succeeds")
        );
    }
}