aboutsummaryrefslogtreecommitdiffstats
path: root/tests/common/mod.rs
blob: 77737350c7ff721fe732bec713e0353461dd5ab8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
use hyper::{Body, Method, Request};
use std::io::BufRead;
use std::path::Path;

pub struct ExampleParts {
    pub method: String,
    pub path_and_query: String,
    pub body: Option<String>,
}

pub fn load_parts(path: &Path) -> ExampleParts {
    let file = std::fs::File::open(path).unwrap();
    let mut lines = std::io::BufReader::new(file).lines();
    let first_line: Vec<String> = lines
        .next()
        .unwrap()
        .unwrap()
        .split(" ")
        .map(|v| v.into())
        .collect();
    let body: Vec<String> = lines
        .map(|v| v.into())
        .collect::<Result<Vec<String>, _>>()
        .unwrap();
    let body: Option<String> = if body.len() == 0 {
        None
    } else {
        Some(body.join("\n"))
    };

    ExampleParts {
        method: first_line[0].clone(),
        path_and_query: first_line[1].clone(),
        body: body,
    }
}

pub fn load_request(path: &Path) -> Request<Body> {
    let parts = load_parts(path);
    Request::builder()
        .uri(parts.path_and_query)
        .method(
            Method::from_bytes(parts.method.as_bytes()).expect("valid method in example text file"),
        )
        .body(match parts.body {
            Some(data) => Body::from(data),
            None => Body::empty(),
        })
        .expect("constructing upstream request")
}