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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
use ::anyhow::Context;
use ::hyper::body::Bytes;
use ::hyper::http::StatusCode;
use ::serde::Deserialize;
use ::std::convert::AsRef;
use ::std::fmt::Debug;
pub struct TestResponse {
request_url: String,
response_body: Bytes,
status_code: StatusCode,
}
impl TestResponse {
pub(crate) fn new(request_url: String, response_body: Bytes, status_code: StatusCode) -> Self {
Self {
request_url,
response_body,
status_code,
}
}
pub fn request_url<'a>(&'a self) -> &'a str {
&self.request_url
}
pub fn bytes<'a>(&'a self) -> &'a [u8] {
&self.response_body
}
pub fn text(&self) -> String {
String::from_utf8_lossy(&self.response_body).to_string()
}
pub fn status_code(&self) -> StatusCode {
self.status_code
}
pub fn json<T>(&self) -> T
where
for<'de> T: Deserialize<'de>,
{
serde_json::from_slice::<T>(&self.response_body)
.with_context(|| {
format!(
"Deserializing response from JSON for request {}",
self.request_url
)
})
.unwrap()
}
pub fn assert_text<C>(self, other: C) -> Self
where
C: AsRef<str>,
{
let other_contents = other.as_ref();
assert_eq!(&self.text(), other_contents);
self
}
pub fn assert_json<T>(self, other: &T) -> Self
where
for<'de> T: Deserialize<'de> + PartialEq<T> + Debug,
{
let own_json: T = self.json();
assert_eq!(own_json, *other);
self
}
pub fn assert_status_bad_request(self) -> Self {
self.assert_status(StatusCode::BAD_REQUEST)
}
pub fn assert_status_not_found(self) -> Self {
self.assert_status(StatusCode::NOT_FOUND)
}
pub fn assert_status_ok(self) -> Self {
self.assert_status(StatusCode::OK)
}
pub fn assert_status_not_ok(self) -> Self {
self.assert_not_status(StatusCode::OK)
}
pub fn assert_status(self, status_code: StatusCode) -> Self {
assert_eq!(self.status_code(), status_code);
self
}
pub fn assert_not_status(self, status_code: StatusCode) -> Self {
assert_ne!(self.status_code(), status_code);
self
}
}