bdrck 0.22.5

Generic common foundational utilities.
Documentation
// Copyright 2015 Axel Rasmussen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::http::recording::*;
use crate::http::types::{HeaderMap, HttpData, ResponseMetadata};
use crate::testing::temp;
use reqwest::{Method, Request, Url};
use std::collections::HashMap;
use std::collections::VecDeque;

#[test]
fn test_recording_default_is_empty() {
    crate::init().unwrap();

    let r = Recording::default();
    assert!(r.0.is_empty());
}

#[test]
fn test_recording_flush_round_trip() {
    crate::init().unwrap();

    // Build a Recording in memory, flush it to disk, then reload and compare.
    let mut headers = HashMap::new();
    headers.insert(
        "x-custom".to_owned(),
        vec![HttpData::Text("value".to_owned())],
    );
    let entry = RecordingEntry {
        req: RecordedRequest {
            method: "GET".to_owned(),
            url: "http://example.com/".to_owned(),
            headers,
            body: None,
        },
        res: RecordedResponse {
            metadata: ResponseMetadata {
                status: 200,
                headers: HeaderMap::new(),
            },
            body: HttpData::Text("hello".to_owned()),
        },
    };
    let mut entries = VecDeque::new();
    entries.push_back(entry);
    let recording = Recording(entries);

    let f = temp::File::new_file().unwrap();
    recording.flush(f.path()).unwrap();

    let bytes = std::fs::read(f.path()).unwrap();
    let reloaded: Recording = serde_json::from_slice(&bytes).unwrap();

    assert_eq!(1, reloaded.0.len());
    let first = reloaded.0.front().unwrap();
    assert_eq!("GET", first.req.method);
    assert_eq!("http://example.com/", first.req.url);
    assert_eq!(None, first.req.body);
    assert_eq!(200, first.res.metadata.status);
}

#[test]
fn test_recorded_request_from_reqwest_request() {
    crate::init().unwrap();

    let url: Url = "http://example.com/path".parse().unwrap();
    let mut req = Request::new(Method::POST, url.clone());
    req.headers_mut().insert(
        "x-custom",
        reqwest::header::HeaderValue::from_static("value"),
    );
    *req.body_mut() = Some(b"hello".to_vec().into());

    let recorded = RecordedRequest::from(&req);
    assert_eq!("POST", recorded.method);
    assert_eq!(url.as_str(), recorded.url);
    assert_eq!(
        &vec![HttpData::Text("value".to_owned())],
        recorded.headers.get("x-custom").unwrap()
    );
    // The body is recorded via Debug, which starts with "Some(".
    let body = recorded.body.expect("expected recorded body");
    assert!(body.starts_with("Body"), "got {:?}", body);
}

#[test]
fn test_recorded_response_from_tuple() {
    crate::init().unwrap();

    let metadata = ResponseMetadata {
        status: 204,
        headers: HeaderMap::new(),
    };
    let body: Vec<u8> = b"hello".to_vec();
    let recorded = RecordedResponse::from(&(metadata, body));
    assert_eq!(204, recorded.metadata.status);
    match recorded.body {
        HttpData::Text(s) => assert_eq!("hello", s),
        HttpData::Binary(_) => panic!("expected Text for UTF-8 body"),
    }
}