在集成测试期间如何运行服务器(进程)?

时间:2020-07-10 22:55:16

标签: testing rust rust-tokio

我的问题是上次集成测试后服务器进程没有关闭。

integration.rs中,我有:

lazy_static! {
    static ref SERVER: Arc<Mutex<duct::ReaderHandle>> = {
        println!("Starting server");
        Arc::new(Mutex::new(
            cmd!("cargo", "run", "--", "13000")
                .reader()
                .expect("Valid server"),
        ))
    };
}

async fn wait_for_server() {
    lazy_static::initialize(&SERVER);
    // Code to wait
}

#[tokio::test]
async fn integration_test_query_amount() -> Result<()> {
    wait_for_server().await;
    let client = reqwest::Client::new();
    // Etc...
}

测试正常,但是在cargo test调用完成之后服务器保持运行。是否有一个不错的方法来启动并关闭这样的服务器?

1 个答案:

答案 0 :(得分:2)

您可以为进程创建Drop包装器,当其超出范围时将杀死该包装器。类似于:

struct KillOnDrop(std::process::Child);

impl Drop for KillOnDrop {
    fn drop(&mut self) {
        self.0.kill()
    }
}

或者,看起来您已经在使用tokio tokio::process supports this out of the box