Skip to main content

extract_json

Function extract_json 

Source
pub fn extract_json<T: DeserializeOwned>(response: Response) -> Result<T>
Expand description

Extract and deserialize JSON from a response

Returns the deserialized data or an error if deserialization fails.

§Examples

use reinhardt_testkit::http::{extract_json, create_request};
use reinhardt_http::Response;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct User {
    id: i64,
    name: String,
}

let user = User { id: 1, name: "Alice".to_string() };
let json = serde_json::to_string(&user).unwrap();
let response = Response::ok()
    .with_header("Content-Type", "application/json")
    .with_body(json);

let extracted: User = extract_json(response).unwrap();
assert_eq!(extracted.id, 1);
assert_eq!(extracted.name, "Alice");

§Invalid JSON

use reinhardt_testkit::http::extract_json;
use reinhardt_http::Response;
use serde::Deserialize;

#[derive(Deserialize)]
struct User {
    id: i64,
    name: String,
}

let response = Response::ok()
    .with_header("Content-Type", "application/json")
    .with_body("invalid json");

let result: Result<User, _> = extract_json(response);
assert!(result.is_err());