forked from jmgilman/rustify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.rs
102 lines (91 loc) · 2.49 KB
/
common.rs
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
use httpmock::prelude::*;
#[cfg(feature = "blocking")]
use rustify::blocking::clients::reqwest::Client as ReqwestBlocking;
use rustify::{
clients::reqwest::Client as Reqwest,
endpoint::{Endpoint, MiddleWare, Wrapper},
errors::ClientError,
};
use serde::{de::DeserializeOwned, Deserialize};
use serde_json::Value;
pub struct TestServer {
pub server: MockServer,
pub client: Reqwest,
}
#[cfg(feature = "blocking")]
pub struct TestServerBlocking {
pub server: MockServer,
pub client: ReqwestBlocking,
}
impl TestServer {
#[allow(dead_code)]
pub fn with_client(mut client: Reqwest) -> TestServer {
let server = MockServer::start();
let url = server.base_url();
client.base = url;
TestServer { server, client }
}
}
impl Default for TestServer {
fn default() -> Self {
let server = MockServer::start();
let url = server.base_url();
TestServer {
server,
client: Reqwest::default(url.as_str()),
}
}
}
#[cfg(feature = "blocking")]
impl Default for TestServerBlocking {
fn default() -> Self {
let server = MockServer::start();
let url = server.base_url();
TestServerBlocking {
server,
client: ReqwestBlocking::default(url.as_str()),
}
}
}
#[derive(Debug, Deserialize)]
pub struct TestResponse {
pub age: u8,
}
#[derive(Debug, Deserialize)]
pub struct TestWrapper {
pub result: Value,
}
#[derive(Debug, Deserialize)]
pub struct TestGenericWrapper<T> {
pub result: T,
}
impl<T: DeserializeOwned + Send + Sync> Wrapper for TestGenericWrapper<T> {
type Value = T;
}
pub struct Middle {}
impl MiddleWare for Middle {
fn request<E: Endpoint>(
&self,
_: &E,
req: &mut http::Request<Vec<u8>>,
) -> Result<(), ClientError> {
req.headers_mut()
.append("X-API-Token", http::HeaderValue::from_static("mytoken"));
Ok(())
}
fn response<E: Endpoint>(
&self,
_: &E,
resp: &mut http::Response<Vec<u8>>,
) -> Result<(), ClientError> {
let resp_body = resp.body().clone();
let wrapper: TestWrapper =
serde_json::from_slice(&resp_body).map_err(|e| ClientError::ResponseParseError {
source: e.into(),
content: String::from_utf8(resp_body.to_vec()).ok(),
})?;
let data = wrapper.result.to_string();
*resp.body_mut() = data.as_bytes().to_vec();
Ok(())
}
}