Debian Codegraph @

third_party/rust/uniffi_bindgen/src/bindings/python/test.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 crate::bindings::RunScriptOptions;
6 use crate::cargo_metadata::CrateConfigSupplier;
7 use crate::library_mode::generate_bindings;
8 use anyhow::{Context, Result};
9 use camino::Utf8Path;
10 use std::env;
11 use std::ffi::OsString;
12 use std::process::Command;
13 use uniffi_testing::UniFFITestHelper;
14
15 /// Run Python tests for a UniFFI test fixture
16 pub fn run_test(tmp_dir: &str, fixture_name: &str, script_file: &str) -> Result<()> {
17 run_script(
18 tmp_dir,
19 fixture_name,
20 script_file,
21 vec![],
22 &RunScriptOptions::default(),
23 )
24 }
25
26 /// Run a Python script
27 ///
28 /// This function will set things up so that the script can import the UniFFI bindings for a crate
29 pub fn run_script(
30 tmp_dir: &str,
31 crate_name: &str,
32 script_file: &str,
33 args: Vec<String>,
34 _options: &RunScriptOptions,
35 ) -> Result<()> {
36 let script_path = Utf8Path::new(script_file).canonicalize_utf8()?;
37 let test_helper = UniFFITestHelper::new(crate_name)?;
38 let out_dir = test_helper.create_out_dir(tmp_dir, &script_path)?;
39 let cdylib_path = test_helper.copy_cdylib_to_out_dir(&out_dir)?;
40 generate_bindings(
41 &cdylib_path,
42 None,
43 &super::PythonBindingGenerator,
44 &CrateConfigSupplier::from(test_helper.cargo_metadata()),
45 None,
46 &out_dir,
47 false,
48 )?;
49
50 let pythonpath = env::var_os("PYTHONPATH").unwrap_or_else(|| OsString::from(""));
51 let pythonpath = env::join_paths(
52 env::split_paths(&pythonpath).chain(vec![out_dir.to_path_buf().into_std_path_buf()]),
53 )?;
54
55 let mut command = Command::new("python3");
56 command
57 .current_dir(out_dir)
58 .env("PYTHONPATH", pythonpath)
59 .arg(script_path)
60 .args(args);
61 let status = command
62 .spawn()
63 .context("Failed to spawn `python3` when running script")?
64 .wait()
65 .context("Failed to wait for `python3` when running script")?;
66 if !status.success() {
67 anyhow::bail!("running `python3` failed");
68 }
69 Ok(())
70 }