forked from actix/actix-web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.rs
385 lines (350 loc) · 11.8 KB
/
test.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
//! Various helpers for Actix applications to use during testing.
use std::cell::RefCell;
use std::rc::Rc;
use actix_http::http::header::{Header, HeaderName, IntoHeaderValue};
use actix_http::http::{HttpTryFrom, Method, StatusCode, Version};
use actix_http::test::TestRequest as HttpTestRequest;
use actix_http::{Extensions, PayloadStream, Request};
use actix_router::{Path, ResourceDef, Url};
use actix_rt::Runtime;
use actix_server_config::ServerConfig;
use actix_service::{FnService, IntoNewService, NewService, Service};
use bytes::Bytes;
#[cfg(feature = "cookies")]
use cookie::Cookie;
use futures::future::{lazy, Future};
use crate::config::{AppConfig, AppConfigInner};
use crate::data::RouteData;
use crate::dev::Body;
use crate::rmap::ResourceMap;
use crate::service::{ServiceFromRequest, ServiceRequest, ServiceResponse};
use crate::{Error, HttpRequest, HttpResponse};
thread_local! {
static RT: RefCell<Runtime> = {
RefCell::new(Runtime::new().unwrap())
};
}
/// Runs the provided future, blocking the current thread until the future
/// completes.
///
/// This function can be used to synchronously block the current thread
/// until the provided `future` has resolved either successfully or with an
/// error. The result of the future is then returned from this function
/// call.
///
/// Note that this function is intended to be used only for testing purpose.
/// This function panics on nested call.
pub fn block_on<F>(f: F) -> Result<F::Item, F::Error>
where
F: Future,
{
RT.with(move |rt| rt.borrow_mut().block_on(f))
}
/// Runs the provided function, with runtime enabled.
///
/// Note that this function is intended to be used only for testing purpose.
/// This function panics on nested call.
pub fn run_on<F, I, E>(f: F) -> Result<I, E>
where
F: Fn() -> Result<I, E>,
{
RT.with(move |rt| rt.borrow_mut().block_on(lazy(f)))
}
pub fn ok_service() -> impl Service<
Request = ServiceRequest<PayloadStream>,
Response = ServiceResponse<Body>,
Error = Error,
> {
default_service(StatusCode::OK)
}
pub fn default_service(
status_code: StatusCode,
) -> impl Service<
Request = ServiceRequest<PayloadStream>,
Response = ServiceResponse<Body>,
Error = Error,
> {
FnService::new(move |req: ServiceRequest<PayloadStream>| {
req.into_response(HttpResponse::build(status_code).finish())
})
}
/// This method accepts application builder instance, and constructs
/// service.
///
/// ```rust,ignore
/// use actix_service::Service;
/// use actix_web::{test, web, App, HttpResponse, http::StatusCode};
///
/// fn main() {
/// let mut app = test::init_service(
/// App::new()
/// .service(web::resource("/test").to(|| HttpResponse::Ok()))
/// );
///
/// // Create request object
/// let req = test::TestRequest::with_uri("/test").to_request();
///
/// // Execute application
/// let resp = test::block_on(app.call(req)).unwrap();
/// assert_eq!(resp.status(), StatusCode::OK);
/// }
/// ```
pub fn init_service<R, S, B, E>(
app: R,
) -> impl Service<Request = Request, Response = ServiceResponse<B>, Error = E>
where
R: IntoNewService<S, ServerConfig>,
S: NewService<
ServerConfig,
Request = Request,
Response = ServiceResponse<B>,
Error = E,
>,
S::InitError: std::fmt::Debug,
{
let cfg = ServerConfig::new("127.0.0.1:8080".parse().unwrap());
block_on(app.into_new_service().new_service(&cfg)).unwrap()
}
/// Calls service and waits for response future completion.
///
/// ```rust,ignore
/// use actix_web::{test, App, HttpResponse, http::StatusCode};
/// use actix_service::Service;
///
/// fn main() {
/// let mut app = test::init_service(
/// App::new()
/// .service(web::resource("/test").to(|| HttpResponse::Ok()))
/// );
///
/// // Create request object
/// let req = test::TestRequest::with_uri("/test").to_request();
///
/// // Call application
/// let resp = test::call_succ_service(&mut app, req);
/// assert_eq!(resp.status(), StatusCode::OK);
/// }
/// ```
pub fn call_success<S, R, B, E>(app: &mut S, req: R) -> S::Response
where
S: Service<Request = R, Response = ServiceResponse<B>, Error = E>,
E: std::fmt::Debug,
{
block_on(app.call(req)).unwrap()
}
/// Test `Request` builder.
///
/// For unit testing, actix provides a request builder type and a simple handler runner. TestRequest implements a builder-like pattern.
/// You can generate various types of request via TestRequest's methods:
/// * `TestRequest::to_request` creates `actix_http::Request` instance.
/// * `TestRequest::to_service` creates `ServiceRequest` instance, which is used for testing middlewares and chain adapters.
/// * `TestRequest::to_from` creates `ServiceFromRequest` instance, which is used for testing extractors.
/// * `TestRequest::to_http_request` creates `HttpRequest` instance, which is used for testing handlers.
///
/// ```rust,ignore
/// # use futures::IntoFuture;
/// use actix_web::{test, HttpRequest, HttpResponse, HttpMessage};
/// use actix_web::http::{header, StatusCode};
///
/// fn index(req: HttpRequest) -> HttpResponse {
/// if let Some(hdr) = req.headers().get(header::CONTENT_TYPE) {
/// HttpResponse::Ok().into()
/// } else {
/// HttpResponse::BadRequest().into()
/// }
/// }
///
/// fn main() {
/// let req = test::TestRequest::with_header("content-type", "text/plain")
/// .to_http_request();
///
/// let resp = test::block_on(index(req).into_future()).unwrap();
/// assert_eq!(resp.status(), StatusCode::OK);
///
/// let req = test::TestRequest::default().to_http_request();
/// let resp = test::block_on(index(req).into_future()).unwrap();
/// assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
/// }
/// ```
pub struct TestRequest {
req: HttpTestRequest,
rmap: ResourceMap,
config: AppConfigInner,
route_data: Extensions,
}
impl Default for TestRequest {
fn default() -> TestRequest {
TestRequest {
req: HttpTestRequest::default(),
rmap: ResourceMap::new(ResourceDef::new("")),
config: AppConfigInner::default(),
route_data: Extensions::new(),
}
}
}
#[allow(clippy::wrong_self_convention)]
impl TestRequest {
/// Create TestRequest and set request uri
pub fn with_uri(path: &str) -> TestRequest {
TestRequest {
req: HttpTestRequest::default().uri(path).take(),
rmap: ResourceMap::new(ResourceDef::new("")),
config: AppConfigInner::default(),
route_data: Extensions::new(),
}
}
/// Create TestRequest and set header
pub fn with_hdr<H: Header>(hdr: H) -> TestRequest {
TestRequest {
req: HttpTestRequest::default().set(hdr).take(),
config: AppConfigInner::default(),
rmap: ResourceMap::new(ResourceDef::new("")),
route_data: Extensions::new(),
}
}
/// Create TestRequest and set header
pub fn with_header<K, V>(key: K, value: V) -> TestRequest
where
HeaderName: HttpTryFrom<K>,
V: IntoHeaderValue,
{
TestRequest {
req: HttpTestRequest::default().header(key, value).take(),
config: AppConfigInner::default(),
rmap: ResourceMap::new(ResourceDef::new("")),
route_data: Extensions::new(),
}
}
/// Create TestRequest and set method to `Method::GET`
pub fn get() -> TestRequest {
TestRequest {
req: HttpTestRequest::default().method(Method::GET).take(),
config: AppConfigInner::default(),
rmap: ResourceMap::new(ResourceDef::new("")),
route_data: Extensions::new(),
}
}
/// Create TestRequest and set method to `Method::POST`
pub fn post() -> TestRequest {
TestRequest {
req: HttpTestRequest::default().method(Method::POST).take(),
config: AppConfigInner::default(),
rmap: ResourceMap::new(ResourceDef::new("")),
route_data: Extensions::new(),
}
}
/// Set HTTP version of this request
pub fn version(mut self, ver: Version) -> Self {
self.req.version(ver);
self
}
/// Set HTTP method of this request
pub fn method(mut self, meth: Method) -> Self {
self.req.method(meth);
self
}
/// Set HTTP Uri of this request
pub fn uri(mut self, path: &str) -> Self {
self.req.uri(path);
self
}
/// Set a header
pub fn set<H: Header>(mut self, hdr: H) -> Self {
self.req.set(hdr);
self
}
/// Set a header
pub fn header<K, V>(mut self, key: K, value: V) -> Self
where
HeaderName: HttpTryFrom<K>,
V: IntoHeaderValue,
{
self.req.header(key, value);
self
}
#[cfg(feature = "cookies")]
/// Set cookie for this request
pub fn cookie(mut self, cookie: Cookie) -> Self {
self.req.cookie(cookie);
self
}
/// Set request payload
pub fn set_payload<B: Into<Bytes>>(mut self, data: B) -> Self {
self.req.set_payload(data);
self
}
/// Set application data. This is equivalent of `App::data()` method
/// for testing purpose.
pub fn app_data<T: 'static>(self, data: T) -> Self {
self.config.extensions.borrow_mut().insert(data);
self
}
/// Set route data. This is equivalent of `Route::data()` method
/// for testing purpose.
pub fn route_data<T: 'static>(mut self, data: T) -> Self {
self.route_data.insert(RouteData::new(data));
self
}
#[cfg(test)]
/// Set request config
pub(crate) fn rmap(mut self, rmap: ResourceMap) -> Self {
self.rmap = rmap;
self
}
/// Complete request creation and generate `ServiceRequest` instance
pub fn to_service(mut self) -> ServiceRequest<PayloadStream> {
let req = self.req.finish();
ServiceRequest::new(
Path::new(Url::new(req.uri().clone())),
req,
Rc::new(self.rmap),
AppConfig::new(self.config),
)
}
/// Complete request creation and generate `Request` instance
pub fn to_request(mut self) -> Request<PayloadStream> {
self.req.finish()
}
/// Complete request creation and generate `ServiceResponse` instance
pub fn to_response<B>(self, res: HttpResponse<B>) -> ServiceResponse<B> {
self.to_service().into_response(res)
}
/// Complete request creation and generate `HttpRequest` instance
pub fn to_http_request(mut self) -> HttpRequest {
let req = self.req.finish();
ServiceRequest::new(
Path::new(Url::new(req.uri().clone())),
req,
Rc::new(self.rmap),
AppConfig::new(self.config),
)
.into_request()
}
/// Complete request creation and generate `ServiceFromRequest` instance
pub fn to_from(mut self) -> ServiceFromRequest<PayloadStream> {
let req = self.req.finish();
let req = ServiceRequest::new(
Path::new(Url::new(req.uri().clone())),
req,
Rc::new(self.rmap),
AppConfig::new(self.config),
);
ServiceFromRequest::new(req, Some(Rc::new(self.route_data)))
}
/// Runs the provided future, blocking the current thread until the future
/// completes.
///
/// This function can be used to synchronously block the current thread
/// until the provided `future` has resolved either successfully or with an
/// error. The result of the future is then returned from this function
/// call.
///
/// Note that this function is intended to be used only for testing purpose.
/// This function panics on nested call.
pub fn block_on<F>(f: F) -> Result<F::Item, F::Error>
where
F: Future,
{
block_on(f)
}
}