Skip to main content

fixtures/
details.rs

1// Copyright (c) The cargo-guppy Contributors
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4use crate::{
5    dep_helpers::{
6        assert_all_links, assert_deps_internal, assert_topo_ids, assert_topo_metadatas,
7        assert_transitive_deps_internal,
8    },
9    package_id,
10};
11use ahash::AHashMap;
12use camino::Utf8PathBuf;
13use guppy::{
14    DependencyKind, PackageId, Version,
15    errors::FeatureGraphWarning,
16    graph::{
17        BuildTargetId, BuildTargetKind, DependencyDirection, EnabledStatus, PackageGraph,
18        PackageLink, PackageMetadata, PackageSource, Workspace,
19        feature::{FeatureLabel, StandardFeatures},
20    },
21    platform::{EnabledTernary, Platform, PlatformSpec},
22};
23use pretty_assertions::assert_eq;
24use std::collections::{BTreeMap, BTreeSet};
25
26/// This captures metadata fields that are relevant for tests. They are meant to be written out
27/// lazily as tests are filled out -- feel free to add more details as necessary!
28pub struct FixtureDetails {
29    workspace_members: Option<BTreeMap<Utf8PathBuf, PackageId>>,
30    hakari_package: Option<PackageId>,
31    package_details: AHashMap<PackageId, PackageDetails>,
32    link_details: AHashMap<(PackageId, PackageId), LinkDetails>,
33    feature_graph_warnings: Vec<FeatureGraphWarning>,
34    cycles: Vec<Vec<PackageId>>,
35}
36
37impl FixtureDetails {
38    pub fn new(package_details: AHashMap<PackageId, PackageDetails>) -> Self {
39        Self {
40            workspace_members: None,
41            hakari_package: None,
42            package_details,
43            link_details: AHashMap::new(),
44            feature_graph_warnings: vec![],
45            cycles: vec![],
46        }
47    }
48
49    pub fn with_workspace_members<'a>(
50        mut self,
51        workspace_members: impl IntoIterator<Item = (impl Into<Utf8PathBuf>, &'a str)>,
52    ) -> Self {
53        self.workspace_members = Some(
54            workspace_members
55                .into_iter()
56                .map(|(path, id)| (path.into(), package_id(id)))
57                .collect(),
58        );
59        self
60    }
61
62    /// Sets the hakari package for this fixture, if any.
63    ///
64    /// Some fixtures have a hakari package which can be used to test
65    /// hakari-specific behaviors.
66    pub fn with_hakari_package(mut self, id: &'static str) -> Self {
67        self.hakari_package = Some(package_id(id));
68        self
69    }
70
71    pub fn hakari_package(&self) -> Option<&PackageId> {
72        self.hakari_package.as_ref()
73    }
74
75    pub fn with_link_details(
76        mut self,
77        link_details: AHashMap<(PackageId, PackageId), LinkDetails>,
78    ) -> Self {
79        self.link_details = link_details;
80        self
81    }
82
83    pub fn with_feature_graph_warnings(mut self, mut warnings: Vec<FeatureGraphWarning>) -> Self {
84        warnings.sort();
85        self.feature_graph_warnings = warnings;
86        self
87    }
88
89    pub fn with_cycles(mut self, cycles: Vec<Vec<&'static str>>) -> Self {
90        let cycles: Vec<_> = cycles
91            .into_iter()
92            .map(|cycle| cycle.into_iter().map(package_id).collect())
93            .collect();
94        // Don't sort because the order returned by all_cycles (both the outer and inner vecs) is
95        // significant.
96        self.cycles = cycles;
97        self
98    }
99
100    pub fn known_ids(&self) -> impl Iterator<Item = &PackageId> {
101        self.package_details.keys()
102    }
103
104    pub fn assert_workspace(&self, workspace: Workspace) {
105        if let Some(expected_members) = &self.workspace_members {
106            let members: Vec<_> = workspace
107                .iter_by_path()
108                .map(|(path, metadata)| (path, metadata.id()))
109                .collect();
110            assert_eq!(
111                expected_members
112                    .iter()
113                    .map(|(path, id)| (path.as_path(), id))
114                    .collect::<Vec<_>>(),
115                members,
116                "workspace members should be correct"
117            );
118
119            assert_eq!(
120                workspace.iter_by_path().len(),
121                workspace.iter_by_name().len(),
122                "workspace.members() and members_by_name() return the same number of items"
123            );
124            for (name, metadata) in workspace.iter_by_name() {
125                assert_eq!(
126                    name,
127                    metadata.name(),
128                    "members_by_name returns consistent results"
129                );
130            }
131        }
132
133        if let Some(hakari_package) = &self.hakari_package {
134            assert!(
135                workspace.member_ids().any(|id| id == hakari_package),
136                "hakari package {hakari_package} should be a workspace member \
137                 (actual members: {})",
138                workspace
139                    .member_ids()
140                    .map(|id| id.to_string())
141                    .collect::<Vec<_>>()
142                    .join(", ")
143            );
144        }
145    }
146
147    pub fn assert_topo(&self, graph: &PackageGraph) {
148        assert_topo_ids(graph, DependencyDirection::Forward, "topo sort");
149        assert_topo_ids(graph, DependencyDirection::Reverse, "reverse topo sort");
150        assert_topo_metadatas(graph, DependencyDirection::Forward, "topo sort (metadatas)");
151        assert_topo_metadatas(
152            graph,
153            DependencyDirection::Reverse,
154            "reverse topo sort (metadatas)",
155        );
156        assert_all_links(graph, DependencyDirection::Forward, "all links");
157        assert_all_links(graph, DependencyDirection::Reverse, "all links reversed");
158    }
159
160    pub fn assert_metadata(&self, id: &PackageId, metadata: PackageMetadata<'_>, msg: &str) {
161        let details = &self.package_details[id];
162        details.assert_metadata(metadata, msg);
163    }
164
165    // ---
166    // Build targets
167    // ---
168
169    pub fn has_build_targets(&self, id: &PackageId) -> bool {
170        let details = &self.package_details[id];
171        details.build_targets.is_some()
172    }
173
174    pub fn assert_build_targets(&self, metadata: PackageMetadata<'_>, msg: &str) {
175        let build_targets = self.package_details[metadata.id()]
176            .build_targets
177            .as_ref()
178            .unwrap();
179
180        let mut actual: Vec<_> = metadata
181            .build_targets()
182            .map(|build_target| {
183                // Strip off the manifest path from the beginning.
184                let path = build_target
185                    .path()
186                    .strip_prefix(
187                        metadata
188                            .manifest_path()
189                            .parent()
190                            .expect("manifest path is a file"),
191                    )
192                    .expect("build target path is inside source dir")
193                    .to_path_buf();
194
195                (build_target.id(), build_target.kind().clone(), path)
196            })
197            .collect();
198        actual.sort();
199
200        assert_eq!(build_targets, &actual, "{}: build targets match", msg,);
201    }
202
203    // ---
204    // Direct dependencies
205    // ---
206
207    /// Returns true if the deps for this package are available to test against.
208    pub fn has_deps(&self, id: &PackageId) -> bool {
209        let details = &self.package_details[id];
210        details.deps.is_some()
211    }
212
213    pub fn assert_deps(&self, graph: &PackageGraph, id: &PackageId, msg: &str) {
214        let details = &self.package_details[id];
215        assert_deps_internal(graph, DependencyDirection::Forward, details, msg);
216    }
217
218    /// Returns true if the reverse deps for this package are available to test against.
219    pub fn has_reverse_deps(&self, id: &PackageId) -> bool {
220        let details = &self.package_details[id];
221        details.reverse_deps.is_some()
222    }
223
224    pub fn assert_reverse_deps(&self, graph: &PackageGraph, id: &PackageId, msg: &str) {
225        let details = &self.package_details[id];
226        assert_deps_internal(graph, DependencyDirection::Reverse, details, msg);
227    }
228
229    // ---
230    // Transitive dependencies
231    // ---
232
233    /// Returns true if the transitive deps for this package are available to test against.
234    pub fn has_transitive_deps(&self, id: &PackageId) -> bool {
235        let details = &self.package_details[id];
236        details.transitive_deps.is_some()
237    }
238
239    pub fn assert_transitive_deps(&self, graph: &PackageGraph, id: &PackageId, msg: &str) {
240        assert_transitive_deps_internal(
241            graph,
242            DependencyDirection::Forward,
243            &self.package_details[id],
244            msg,
245        )
246    }
247
248    /// Returns true if the transitive reverse deps for this package are available to test against.
249    pub fn has_transitive_reverse_deps(&self, id: &PackageId) -> bool {
250        let details = &self.package_details[id];
251        details.transitive_reverse_deps.is_some()
252    }
253
254    pub fn assert_transitive_reverse_deps(&self, graph: &PackageGraph, id: &PackageId, msg: &str) {
255        assert_transitive_deps_internal(
256            graph,
257            DependencyDirection::Reverse,
258            &self.package_details[id],
259            msg,
260        )
261    }
262
263    // ---
264    // Links
265    // ---
266
267    pub fn assert_link_details(&self, graph: &PackageGraph, msg: &str) {
268        for ((from, to), details) in &self.link_details {
269            let metadata = graph
270                .metadata(from)
271                .unwrap_or_else(|err| panic!("{msg}: {err}"));
272            let mut links: Vec<_> = metadata
273                .direct_links()
274                .filter(|link| link.to().id() == to)
275                .collect();
276            assert_eq!(
277                links.len(),
278                1,
279                "{}: exactly 1 link between '{}' and '{}'",
280                msg,
281                from,
282                to
283            );
284
285            let link = links.pop().unwrap();
286            let msg = format!("{msg}: {from} -> {to}");
287            details.assert_metadata(link, &msg);
288        }
289    }
290
291    // ---
292    // Features
293    // ---
294
295    pub fn has_named_features(&self, id: &PackageId) -> bool {
296        self.package_details[id].named_features.is_some()
297    }
298
299    pub fn assert_named_features(&self, graph: &PackageGraph, id: &PackageId, msg: &str) {
300        let mut actual: Vec<_> = graph
301            .metadata(id)
302            .expect("package id should be valid")
303            .named_features()
304            .collect();
305        actual.sort_unstable();
306        let expected = self.package_details[id].named_features.as_ref().unwrap();
307        assert_eq!(expected, &actual, "{}", msg);
308    }
309
310    pub fn assert_feature_graph_warnings(&self, graph: &PackageGraph, msg: &str) {
311        let mut actual: Vec<_> = graph.feature_graph().build_warnings().to_vec();
312        actual.sort();
313        assert_eq!(&self.feature_graph_warnings, &actual, "{}", msg);
314    }
315
316    /// Asserts invariants for `ConditionalLink::package_links`.
317    ///
318    /// * Every conditional link starts at its `from` feature's package.
319    /// * All of a conditional link's package links share one dependency name,
320    ///   and end at distinct packages.
321    /// * A link to `dep:name` has package links with the dependency name
322    ///   `name`.
323    /// * A cross-package one has exactly one package link, ending at its `to`
324    ///   feature's package.
325    pub fn assert_conditional_link_package_links(&self, graph: &PackageGraph, msg: &str) {
326        let feature_set = graph
327            .feature_graph()
328            .query_workspace(StandardFeatures::All)
329            .resolve();
330        for link in feature_set.conditional_links(DependencyDirection::Forward) {
331            let (from, to) = link.endpoints();
332            let package_links: Vec<_> = link.package_links().collect();
333            assert!(
334                !package_links.is_empty(),
335                "{msg}: {link:?} has at least one package link"
336            );
337            let dep_name = package_links[0].dep_name();
338            for package_link in &package_links {
339                assert_eq!(
340                    package_link.from().id(),
341                    from.package_id(),
342                    "{msg}: {link:?}: package link starts at the from package"
343                );
344                assert_eq!(
345                    package_link.dep_name(),
346                    dep_name,
347                    "{msg}: {link:?}: package links share one dependency name"
348                );
349            }
350            let to_ids: BTreeSet<_> = package_links
351                .iter()
352                .map(|package_link| package_link.to().id())
353                .collect();
354            assert_eq!(
355                to_ids.len(),
356                package_links.len(),
357                "{msg}: {link:?}: package links end at distinct packages"
358            );
359            match to.label() {
360                FeatureLabel::OptionalDependency(to_dep_name) => {
361                    assert_eq!(
362                        dep_name, to_dep_name,
363                        "{msg}: {link:?}: package links to dep:{to_dep_name} have that \
364                         dependency name"
365                    );
366                }
367                FeatureLabel::Base | FeatureLabel::Named(_) => {}
368            }
369
370            if from.package_id() != to.package_id() {
371                let [package_link] = package_links.as_slice() else {
372                    panic!("{msg}: {link:?}: cross-package link has exactly one package link");
373                };
374                assert_eq!(
375                    package_link.to().id(),
376                    to.package_id(),
377                    "{msg}: {link:?}: package link ends at the to package"
378                );
379            }
380        }
381    }
382
383    // ---
384    // Cycles
385    // ---
386
387    pub fn assert_cycles(&self, graph: &PackageGraph, msg: &str) {
388        let actual: Vec<_> = graph.cycles().all_cycles().collect();
389        // Don't sort because the order returned by all_cycles (both the outer and inner vecs) is
390        // significant.
391        assert_eq!(&self.cycles, &actual, "{}", msg);
392
393        let mut cache = graph.new_depends_cache();
394
395        for cycle in actual {
396            for &id1 in &cycle {
397                for &id2 in &cycle {
398                    assert!(
399                        graph.depends_on(id1, id2).expect("valid package IDs"),
400                        "{msg}: within cycle, {id1} depends on {id2}"
401                    );
402                    assert!(
403                        cache.depends_on(id1, id2).expect("valid package IDs"),
404                        "{msg}: within cycle, {id1} depends on {id2} (using cache)"
405                    )
406                }
407            }
408        }
409
410        // Just ensure that this doesn't crash for now -- we should add more checks later.
411        let _: Vec<_> = graph.feature_graph().cycles().all_cycles().collect();
412    }
413}
414
415pub struct PackageDetails {
416    id: PackageId,
417    name: &'static str,
418    version: Version,
419    authors: Vec<&'static str>,
420    description: Option<&'static str>,
421    license: Option<&'static str>,
422
423    source: Option<PackageSource<'static>>,
424    build_targets: Option<
425        Vec<(
426            BuildTargetId<'static>,
427            BuildTargetKind<'static>,
428            Utf8PathBuf,
429        )>,
430    >,
431    // The vector items are (name, package id).
432    // XXX add more details about dependency edges here?
433    deps: Option<Vec<(&'static str, PackageId)>>,
434    reverse_deps: Option<Vec<(&'static str, PackageId)>>,
435    transitive_deps: Option<Vec<PackageId>>,
436    transitive_reverse_deps: Option<Vec<PackageId>>,
437    named_features: Option<Vec<&'static str>>,
438}
439
440impl PackageDetails {
441    pub fn new(
442        id: &'static str,
443        name: &'static str,
444        version: &'static str,
445        authors: Vec<&'static str>,
446        description: Option<&'static str>,
447        license: Option<&'static str>,
448    ) -> Self {
449        Self {
450            id: package_id(id),
451            name,
452            version: Version::parse(version).expect("version should be valid"),
453            authors,
454            description,
455            license,
456            source: None,
457            build_targets: None,
458            deps: None,
459            reverse_deps: None,
460            transitive_deps: None,
461            transitive_reverse_deps: None,
462            named_features: None,
463        }
464    }
465
466    pub fn with_workspace_path(mut self, path: &'static str) -> Self {
467        self.source = Some(PackageSource::Workspace(path.into()));
468        self
469    }
470
471    pub fn with_local_path(mut self, path: &'static str) -> Self {
472        self.source = Some(PackageSource::Path(path.into()));
473        self
474    }
475
476    pub fn with_crates_io(self) -> Self {
477        self.with_external_source(PackageSource::CRATES_IO_REGISTRY)
478    }
479
480    pub fn with_external_source(mut self, source: &'static str) -> Self {
481        self.source = Some(PackageSource::External(source));
482        self
483    }
484
485    pub fn with_build_targets(
486        mut self,
487        mut build_targets: Vec<(
488            BuildTargetId<'static>,
489            BuildTargetKind<'static>,
490            &'static str,
491        )>,
492    ) -> Self {
493        build_targets.sort();
494        self.build_targets = Some(
495            build_targets
496                .into_iter()
497                .map(|(id, kind, path)| (id, kind, path.to_string().into()))
498                .collect(),
499        );
500        self
501    }
502
503    pub fn with_deps(mut self, mut deps: Vec<(&'static str, &'static str)>) -> Self {
504        deps.sort_unstable();
505        self.deps = Some(
506            deps.into_iter()
507                .map(|(name, id)| (name, package_id(id)))
508                .collect(),
509        );
510        self
511    }
512
513    pub fn with_reverse_deps(
514        mut self,
515        mut reverse_deps: Vec<(&'static str, &'static str)>,
516    ) -> Self {
517        reverse_deps.sort_unstable();
518        self.reverse_deps = Some(
519            reverse_deps
520                .into_iter()
521                .map(|(name, id)| (name, package_id(id)))
522                .collect(),
523        );
524        self
525    }
526
527    pub fn with_transitive_deps(mut self, mut transitive_deps: Vec<&'static str>) -> Self {
528        transitive_deps.sort_unstable();
529        self.transitive_deps = Some(transitive_deps.into_iter().map(package_id).collect());
530        self
531    }
532
533    pub fn with_transitive_reverse_deps(
534        mut self,
535        mut transitive_reverse_deps: Vec<&'static str>,
536    ) -> Self {
537        transitive_reverse_deps.sort_unstable();
538        self.transitive_reverse_deps = Some(
539            transitive_reverse_deps
540                .into_iter()
541                .map(package_id)
542                .collect(),
543        );
544        self
545    }
546
547    pub fn with_named_features(mut self, mut named_features: Vec<&'static str>) -> Self {
548        named_features.sort_unstable();
549        self.named_features = Some(named_features);
550        self
551    }
552
553    pub fn insert_into(self, map: &mut AHashMap<PackageId, PackageDetails>) {
554        map.insert(self.id.clone(), self);
555    }
556
557    pub fn id(&self) -> &PackageId {
558        &self.id
559    }
560
561    pub fn deps(&self, direction: DependencyDirection) -> Option<&[(&'static str, PackageId)]> {
562        match direction {
563            DependencyDirection::Forward => self.deps.as_deref(),
564            DependencyDirection::Reverse => self.reverse_deps.as_deref(),
565        }
566    }
567
568    pub fn transitive_deps(&self, direction: DependencyDirection) -> Option<&[PackageId]> {
569        match direction {
570            DependencyDirection::Forward => self.transitive_deps.as_deref(),
571            DependencyDirection::Reverse => self.transitive_reverse_deps.as_deref(),
572        }
573    }
574
575    pub fn assert_metadata(&self, metadata: PackageMetadata<'_>, msg: &str) {
576        assert_eq!(&self.id, metadata.id(), "{}: same package ID", msg);
577        assert_eq!(self.name, metadata.name(), "{}: same name", msg);
578        assert_eq!(&self.version, metadata.version(), "{}: same version", msg);
579        assert_eq!(
580            &self.authors,
581            &metadata
582                .authors()
583                .iter()
584                .map(|author| author.as_str())
585                .collect::<Vec<_>>(),
586            "{}: same authors",
587            msg
588        );
589        assert_eq!(
590            &self.description,
591            &metadata.description(),
592            "{}: same description",
593            msg
594        );
595        assert_eq!(&self.license, &metadata.license(), "{}: same license", msg);
596        if let Some(source) = &self.source {
597            assert_eq!(source, &metadata.source(), "{}: same source", msg);
598        }
599    }
600}
601
602#[derive(Clone, Debug)]
603pub struct LinkDetails {
604    from: PackageId,
605    to: PackageId,
606    platform_results: Vec<(DependencyKind, Platform, PlatformResults)>,
607    features: Vec<(DependencyKind, Vec<&'static str>)>,
608}
609
610impl LinkDetails {
611    pub fn new(from: PackageId, to: PackageId) -> Self {
612        Self {
613            from,
614            to,
615            platform_results: vec![],
616            features: vec![],
617        }
618    }
619
620    pub fn with_platform_status(
621        mut self,
622        dep_kind: DependencyKind,
623        platform: Platform,
624        status: PlatformResults,
625    ) -> Self {
626        self.platform_results.push((dep_kind, platform, status));
627        self
628    }
629
630    pub fn with_features(
631        mut self,
632        dep_kind: DependencyKind,
633        mut features: Vec<&'static str>,
634    ) -> Self {
635        features.sort_unstable();
636        self.features.push((dep_kind, features));
637        self
638    }
639
640    pub fn insert_into(self, map: &mut AHashMap<(PackageId, PackageId), Self>) {
641        map.insert((self.from.clone(), self.to.clone()), self);
642    }
643
644    pub fn assert_metadata(&self, link: PackageLink<'_>, msg: &str) {
645        let required_enabled = |status: EnabledStatus<'_>, platform_spec: &PlatformSpec| {
646            (
647                status.required_on(platform_spec),
648                status.enabled_on(platform_spec),
649            )
650        };
651
652        for (dep_kind, platform, results) in &self.platform_results {
653            let platform_spec = platform.clone().into();
654            let req = link.req_for_kind(*dep_kind);
655            assert_eq!(
656                required_enabled(req.status(), &platform_spec),
657                results.status,
658                "{}: for platform '{}', kind {}, status is correct",
659                msg,
660                platform.triple_str(),
661                dep_kind,
662            );
663            assert_eq!(
664                required_enabled(req.default_features(), &platform_spec),
665                results.default_features,
666                "{}: for platform '{}', kind {}, default features is correct",
667                msg,
668                platform.triple_str(),
669                dep_kind,
670            );
671            for (feature, status) in &results.feature_statuses {
672                assert_eq!(
673                    required_enabled(req.feature_status(feature), &platform_spec),
674                    *status,
675                    "{}: for platform '{}', kind {}, feature '{}' has correct status",
676                    msg,
677                    platform.triple_str(),
678                    dep_kind,
679                    feature
680                );
681            }
682        }
683
684        for (dep_kind, features) in &self.features {
685            let metadata = link.req_for_kind(*dep_kind);
686            let mut actual_features: Vec<_> = metadata.features().collect();
687            actual_features.sort_unstable();
688            assert_eq!(&actual_features, features, "{}: features is correct", msg);
689        }
690    }
691}
692
693#[derive(Clone, Debug)]
694pub struct PlatformResults {
695    // Each pair stands for (required on, enabled on).
696    status: (EnabledTernary, EnabledTernary),
697    default_features: (EnabledTernary, EnabledTernary),
698    feature_statuses: AHashMap<String, (EnabledTernary, EnabledTernary)>,
699}
700
701impl PlatformResults {
702    pub fn new(
703        status: (EnabledTernary, EnabledTernary),
704        default_features: (EnabledTernary, EnabledTernary),
705    ) -> Self {
706        Self {
707            status,
708            default_features,
709            feature_statuses: AHashMap::new(),
710        }
711    }
712
713    pub fn with_feature_status(
714        mut self,
715        feature: &str,
716        status: (EnabledTernary, EnabledTernary),
717    ) -> Self {
718        self.feature_statuses.insert(feature.to_string(), status);
719        self
720    }
721}