phper_test/
utils.rs

1// Copyright (c) 2022 PHPER Framework Team
2// PHPER is licensed under Mulan PSL v2.
3// You can use this software according to the terms and conditions of the Mulan
4// PSL v2. You may obtain a copy of Mulan PSL v2 at:
5//          http://license.coscl.org.cn/MulanPSL2
6// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
7// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
8// NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
9// See the Mulan PSL v2 for more details.
10
11//! Utils for PHP test situation.
12
13use std::{
14    ffi::{OsStr, OsString},
15    fmt::Debug,
16    path::{Path, PathBuf},
17    process::Command,
18};
19
20pub(crate) fn execute_command<S: AsRef<OsStr> + Debug>(argv: &[S]) -> String {
21    let mut command = Command::new(&argv[0]);
22    command.args(&argv[1..]);
23    let output = command
24        .output()
25        .unwrap_or_else(|_| panic!("Execute command {:?} failed", &argv))
26        .stdout;
27    String::from_utf8(output).unwrap().trim().to_owned()
28}
29
30pub(crate) fn spawn_command<S: AsRef<OsStr> + Debug>(
31    argv: &[S], wait_time: Option<std::time::Duration>,
32) -> std::process::Child {
33    use std::{process::Stdio, thread};
34
35    let mut command = Command::new(&argv[0]);
36    let child = command
37        .args(&argv[1..])
38        .stdin(Stdio::null())
39        .stdout(Stdio::null())
40        .stderr(Stdio::null())
41        .spawn()
42        .unwrap_or_else(|_| panic!("Execute command {:?} failed", argv));
43
44    // Sleep to wait program running.
45    if let Some(wait_time) = wait_time {
46        thread::sleep(wait_time);
47    }
48
49    // Check process is running.
50    let id = child.id();
51    unsafe {
52        assert_eq!(
53            libc::kill(id.try_into().unwrap(), 0),
54            0,
55            "start process failed: {:?}",
56            argv
57        );
58    }
59
60    child
61}
62
63/// Get the dynamic link library path generated by `cargo build`.
64pub fn get_lib_path(target_path: impl AsRef<Path>, package_name: &str) -> PathBuf {
65    let target_path = target_path.as_ref();
66    let mut path = target_path.to_path_buf();
67    path.push(if cfg!(debug_assertions) {
68        "debug"
69    } else {
70        "release"
71    });
72    let mut ext_name = OsString::new();
73    ext_name.push("lib");
74    ext_name.push(package_name);
75    ext_name.push(if cfg!(target_os = "linux") {
76        ".so"
77    } else if cfg!(target_os = "macos") {
78        ".dylib"
79    } else if cfg!(target_os = "windows") {
80        ".dll"
81    } else {
82        ""
83    });
84    path.join(ext_name)
85}