Debian Codegraph @

third_party/rust/uniffi_testing/src/lib.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 use anyhow::{bail, Result};
6 use camino::{Utf8Path, Utf8PathBuf};
7 use cargo_metadata::{CrateType, Message, Metadata, MetadataCommand, Package, Target};
8 use fs_err as fs;
9 use once_cell::sync::Lazy;
10 use std::{
11 collections::hash_map::DefaultHasher,
12 env,
13 env::consts::DLL_EXTENSION,
14 hash::{Hash, Hasher},
15 process::{Command, Stdio},
16 };
17
18 // A source to compile for a test
19 #[derive(Debug)]
20 pub struct CompileSource {
21 pub udl_path: Utf8PathBuf,
22 pub config_path: Option<Utf8PathBuf>,
23 }
24
25 // Store Cargo output to in a static to avoid calling it more than once.
26
27 static CARGO_METADATA: Lazy<Metadata> = Lazy::new(get_cargo_metadata);
28 static CARGO_BUILD_MESSAGES: Lazy<Vec<Message>> = Lazy::new(get_cargo_build_messages);
29
30 /// Struct for running fixture and example tests for bindings generators
31 ///
32 /// Expectations:
33 /// - Used from a integration test (a `.rs` file in the tests/ directory)
34 /// - The working directory is the project root for the bindings crate. This is the normal case
35 /// for test code, just make sure you don't cd somewhere else.
36 /// - The bindings crate has a dev-dependency on the fixture crate
37 /// - The fixture crate produces a cdylib library
38 /// - The fixture crate, and any external-crates, has 1 UDL file in it's src/ directory
39 pub struct UniFFITestHelper {
40 crate_name: String,
41 cdylib: Utf8PathBuf,
42 }
43
44 impl UniFFITestHelper {
45 pub fn new(package_name: &str) -> Result<Self> {
46 let package = Self::find_package(package_name)?;
47 let (crate_name, cdylib) = Self::find_name_and_cdylib_path(&package)?;
48 Ok(Self { crate_name, cdylib })
49 }
50
51 fn find_package(name: &str) -> Result<Package> {
52 let matching: Vec<&Package> = CARGO_METADATA
53 .packages
54 .iter()
55 .filter(|p| p.name == name)
56 .collect();
57 match matching.len() {
58 1 => Ok(matching[0].clone()),
59 n => bail!("cargo metadata return {n} packages named {name}"),
60 }
61 }
62
63 fn find_name_and_cdylib_path(package: &Package) -> Result<(String, Utf8PathBuf)> {
64 let cdylib_targets: Vec<&Target> = package
65 .targets
66 .iter()
67 .filter(|t| t.crate_types.iter().any(|t| *t == CrateType::CDyLib))
68 .collect();
69 let target = match cdylib_targets.len() {
70 1 => cdylib_targets[0],
71 n => bail!("Found {n} cdylib targets for {}", package.name),
72 };
73 let target_name = target.name.replace('-', "_");
74
75 let artifacts = CARGO_BUILD_MESSAGES
76 .iter()
77 .filter_map(|message| match message {
78 Message::CompilerArtifact(artifact) => {
79 if artifact.target == *target {
80 Some(artifact.clone())
81 } else {
82 None
83 }
84 }
85 _ => None,
86 });
87 let cdylib_files: Vec<Utf8PathBuf> = artifacts
88 .into_iter()
89 .flat_map(|artifact| {
90 artifact
91 .filenames
92 .into_iter()
93 .filter(|nm| matches!(nm.extension(), Some(DLL_EXTENSION)))
94 .collect::<Vec<Utf8PathBuf>>()
95 })
96 .collect();
97
98 match cdylib_files.len() {
99 1 => Ok((target_name, cdylib_files[0].to_owned())),
100 n => bail!("Found {n} cdylib files for {}", package.name),
101 }
102 }
103
104 /// Create at `out_dir` for testing
105 ///
106 /// This directory can be used for:
107 /// - Generated bindings files (usually via the `--out-dir` param)
108 /// - cdylib libraries that the bindings depend on
109 /// - Anything else that's useful for testing
110 ///
111 /// This directory typically created as a subdirectory of `CARGO_TARGET_TMPDIR` when running an
112 /// integration test.
113 ///
114 /// We use the script path to create a hash included in the outpuit directory. This avoids
115 /// path collutions when 2 scripts run against the same fixture.
116 pub fn create_out_dir(
117 &self,
118 temp_dir: impl AsRef<Utf8Path>,
119 script_path: impl AsRef<Utf8Path>,
120 ) -> Result<Utf8PathBuf> {
121 let dirname = format!("{}-{}", self.crate_name, hash_path(script_path.as_ref()));
122 let out_dir = temp_dir.as_ref().join(dirname);
123 if out_dir.exists() {
124 // Clean out any files from previous runs
125 fs::remove_dir_all(&out_dir)?;
126 }
127 fs::create_dir(&out_dir)?;
128 println!("Creating testing out_dir: {out_dir}");
129 Ok(out_dir)
130 }
131
132 /// Copy the `cdylib` for a fixture into the out_dir
133 ///
134 /// This is typically needed for the bindings to open it when running the tests
135 ///
136 /// Returns the path to the copied library
137 pub fn copy_cdylib_to_out_dir(&self, out_dir: impl AsRef<Utf8Path>) -> Result<Utf8PathBuf> {
138 let path = self.cdylib_path()?;
139 let dest = out_dir.as_ref().join(path.file_name().unwrap());
140 fs::copy(&path, &dest)?;
141 Ok(dest)
142 }
143
144 /// Get the path to the cdylib file for this package
145 pub fn cdylib_path(&self) -> Result<Utf8PathBuf> {
146 Ok(self.cdylib.clone())
147 }
148
149 pub fn crate_name(&self) -> &str {
150 &self.crate_name
151 }
152
153 pub fn cargo_metadata(&self) -> Metadata {
154 CARGO_METADATA.clone()
155 }
156 }
157
158 fn get_cargo_metadata() -> Metadata {
159 MetadataCommand::new()
160 .exec()
161 .expect("error running cargo metadata")
162 }
163
164 fn get_cargo_build_messages() -> Vec<Message> {
165 #[cfg(feature = "ffi-trace")]
166 let features_arg = "--features=ffi-trace";
167
168 #[cfg(not(feature = "ffi-trace"))]
169 let features_arg = "--features=";
170
171 let mut child = Command::new(env!("CARGO"))
172 .arg("test")
173 .arg(features_arg)
174 .arg("--no-run")
175 .arg("--message-format=json")
176 .stdout(Stdio::piped())
177 .spawn()
178 .expect("Error running cargo build");
179 let output = std::io::BufReader::new(child.stdout.take().unwrap());
180 let result = Message::parse_stream(output)
181 .map(|m| m.expect("Error parsing cargo build messages"))
182 .collect();
183 child.wait().expect("failed to wait for child");
184 result
185 }
186
187 fn hash_path(path: &Utf8Path) -> String {
188 let mut hasher = DefaultHasher::new();
189 path.hash(&mut hasher);
190 format!("{:x}", hasher.finish())
191 }