25个版本

0.7.1 2024年4月18日
0.6.1 2023年4月21日
0.6.0 2023年2月17日
0.5.2 2022年12月20日
0.2.0 2021年7月6日

#64 in HTTP客户端

Download history 876/week @ 2024-04-30 1355/week @ 2024-05-07 848/week @ 2024-05-14 878/week @ 2024-05-21 367/week @ 2024-05-28 345/week @ 2024-06-04 503/week @ 2024-06-11 170/week @ 2024-06-18 863/week @ 2024-06-25 543/week @ 2024-07-02 136/week @ 2024-07-09 59/week @ 2024-07-16 435/week @ 2024-07-23 840/week @ 2024-07-30 519/week @ 2024-08-06 262/week @ 2024-08-13

2,060 每月下载量
3 个库 中使用

Apache-2.0

165KB
2K SLoC

asserhttp

流畅的HTTP响应断言


对许多HTTP客户端响应进行流畅断言的标准trait。目前支持 actix-webrocketreqwesthyperaxumawc(Actix Web客户端),surfureqisahc

入门

将其添加到您的 Cargo.toml

asserhttp = { version = "0.6.1", features = ["reqwest"] }
#                             or features = ["hyper"]
#                             or features = ["actix"]
#                             or features = ["axum"]
#                             or features = ["actix-web-client"]
#                             or features = ["rocket"]
#                             or features = ["surf"]
#                             or features = ["ureq"]
#                             or features = ["isahc"]

然后在测试中使用它,例如在 actix-web 上,

use actix_web::{App, HttpResponse, test::{call_service, init_service, TestRequest}, web};
use asserhttp::*;

#[actix_web::test]
async fn sample_test() {
    let app = App::new().route("/", web::get().to(|| async { HttpResponse::Ok().body(json!({"a": "b"})) }));
    call_service(&mut init_service(app).await, TestRequest::get().to_request()).await
        .expect_status_ok()
        .expect_content_type_json()
        .expect_body_json_eq(json!({"a": "b"}));
}

或者在 reqwest

use reqwest;
use asserhttp::*;

#[tokio::test]
async fn my_test() {
    reqwest::get("https://127.0.0.1").await
        .expect_status_ok()
        .expect_content_type_json()
        .expect_body_json_eq(json!({"name": "jdoe"}));
}

自定义

您不喜欢asserhttp的方法名称?没关系,您可以定义自己的。定义自己的trait并使用asserhttp方法来定义自己的!

就像这样简单

asserhttp::asserhttp_customize!(MyHttpDsl);

pub trait MyHttpDsl<T>: asserhttp::Asserhttp<T> {
    fn is_status_ok(&mut self) -> &mut T {
        self.expect_status_ok()
    }
    fn is_json(&mut self) -> &mut T {
        self.expect_content_type_json()
    }
    fn has_body(&mut self) -> &mut T { self.expect_body_present() }
}

gRPC

断言gRPC也支持tonic客户端。只需启用tonic特性,并像这样使用它:

use asserhttp::grpc::*;

#[tokio::main]
async fn main() {
    // success
    client.call_svc(tonic::Request::new(Payload)).await.expect_status_ok().expect_body(Payload);
    // error
    client.call_svc(tonic::Request::new(Payload)).await.expect_status_error(Code::NotFound);
}

依赖项

~8–46MB
~778K SLoC