我正在尝试测试一个简单的 ntex 服务器。 这是测试中的完整代码:
use ntex::{web, web::test};
use shopp::config;
#[ntex::test]
async fn health_check_works() {
let app = test::init_service(web::App::new().configure(config)).await;
let req = test::TestRequest::get()
.uri("/health_check")
.header("content-type", "text/plain")
.to_request();
let resp = test::call_service(&app, req).await;
assert!(resp.status().is_success());
}
#[ntex::test]
async fn spawn_server_works() {
spawn_server();
let output = std::process::Command::new("curl")
.arg("-vvv")
.arg("http://127.0.0.1:8000/health_check")
.spawn()
.expect("Failed to execute command.");
}
fn spawn_server() {
let server = shopp::run().expect("Failed to start server.");
let _ = async_std::task::spawn(server);
}
结果都是绿色的,2/2 工作。然而!详细卷曲的输出是
* Trying 127.0.0.1:8000...
* connect to 127.0.0.1 port 8000 failed: Connection refused
* Failed to connect to 127.0.0.1 port 8000 after 0 ms: Couldn't connect to server
* Closing connection 0
curl: (7) Failed to connect to 127.0.0.1 port 8000 after 0 ms: Couldn't connect to server
但是当我在spawn_server_works函数中插入一些睡眠并开始测试时,我切换到另一个shell并且可以成功curl:
* Trying 127.0.0.1:8000...
* Connected to 127.0.0.1 (127.0.0.1) port 8000 (#0)
> GET /health_check HTTP/1.1
> Host: 127.0.0.1:8000
> User-Agent: curl/7.88.1
> Accept: */*
>
< HTTP/1.1 200 OK
< content-length: 0
< date: Thu, 22 Feb 2024 21:02:27 GMT
<
* Connection #0 to host 127.0.0.1 left intact
因此,同时,来自货物测试内部的curl失败,而来自外部货物测试会话的curl按预期工作。
有什么想法吗?
服务器的完整代码:
# lib.rs
use ntex::server::Server;
use ntex::web;
#[web::get("/health_check")]
async fn health_check() -> impl web::Responder {
web::HttpResponse::Ok()
}
pub fn config(cfg: &mut web::ServiceConfig) {
cfg.service(health_check);
}
pub fn run() -> Result<Server, std::io::Error> {
let server = web::HttpServer::new(|| web::App::new().configure(config))
.bind(("127.0.0.1", 8000))?
.run();
Ok(server)
}
# main.rs
use ntex::server::Server;
use ntex::web;
#[web::get("/health_check")]
async fn health_check() -> impl web::Responder {
web::HttpResponse::Ok()
}
pub fn config(cfg: &mut web::ServiceConfig) {
cfg.service(health_check);
}
pub fn run() -> Result<Server, std::io::Error> {
let server = web::HttpServer::new(|| web::App::new().configure(config))
.bind(("127.0.0.1", 8000))?
.run();
Ok(server)
}
编辑:此行为以某种方式记录在此处https://doc.rust-lang.org/rust-by-example/std_misc/process/wait.html
显然,std::process::Command 生成了一个子进程。该子项需要在curl 情况下调用wait() 方法。对此一无所知,文档中没有任何地方。所以最终的工作代码是:
#[ntex::test]
async fn spawn_server_works() {
spawn_server();
let _ = std::process::Command::new("curl")
.arg("http://127.0.0.1:8000/health_check")
.arg("-vvv")
.spawn()
.expect("Failed to execute command.")
.wait()
.expect("Failed to wait");
}
希望对未来的人有所帮助!