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

How to run a server (a process) for the duration of integration tests?

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

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 调用完成后保持 运行。是否有启动 和关闭 这样的服务器的好方法?

您可以为一个进程制作一个 Drop 包装器,当它超出范围时将终止它。大致如下:

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

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

或者,您似乎已经在使用 tokiotokio::process supports this out of the box