This repository has been archived by the owner on Apr 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
helper.rs
132 lines (111 loc) · 3.4 KB
/
helper.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
use actix_web::{
dev::MessageBody,
error::PayloadError,
web::{Bytes, BytesMut},
Error, HttpResponse,
};
use futures::{
future::ready,
stream::{Stream, StreamExt},
};
pub use rand::random;
use rand::{self, distributions::Alphanumeric, Rng};
use std::{fs::File, io::Read};
/// Generates a random string with given size.
pub fn random_string(size: usize) -> String {
rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(size)
.map(char::from)
.collect::<String>()
}
/// Reads file content into string result.
pub fn read_file(file: &str) -> Result<String, Error> {
let mut file = File::open(file)?;
let mut content = String::new();
let _ = file.read_to_string(&mut content);
Ok(content)
}
/// Loads bytes from (Request) stream
pub async fn load_body<S>(stream: S) -> Result<BytesMut, PayloadError>
where
S: Stream<Item = Result<Bytes, PayloadError>>,
{
let body = stream
.map(|res| match res {
Ok(chunk) => chunk,
_ => panic!(),
})
.fold(BytesMut::new(), move |mut body, chunk| {
body.extend_from_slice(&chunk);
ready(body)
})
.await;
Ok(body)
}
/// Reads bytes from HttpResponse.
pub async fn read_body<B>(mut res: HttpResponse<B>) -> Result<Bytes, Error>
where
B: MessageBody + Unpin,
{
let mut body = res.take_body();
let mut bytes = BytesMut::new();
while let Some(item) = body.next().await {
bytes.extend_from_slice(&item?);
}
Ok(bytes.freeze())
}
#[cfg(test)]
mod tests {
use super::*;
use actix_web::{
rt as actix_rt,
test::{call_service, init_service, TestRequest},
web, App, HttpResponse,
};
use futures::{future::ok, stream};
#[test]
fn random_string_has_given_size() {
let size: u8 = random();
let string = random_string(size as usize);
assert_eq!(string.len(), size as usize);
}
#[test]
fn random_strings_are_different() {
let size: u8 = std::cmp::max(1, random());
let first_string = random_string(size as usize);
let second_string = random_string(size as usize);
assert!(first_string != second_string);
}
#[test]
fn read_file_returns_error_if_file_not_exists() {
let not_exist = read_file("a");
assert!(not_exist.is_err());
}
#[test]
fn read_file_returns_content() {
let content = read_file("tests/read_file_test");
assert!(content.is_ok());
assert_eq!(&content.unwrap(), "a1b2c3");
}
#[actix_rt::test]
async fn read_request_body() {
let content = &random_string(20);
let content_bytes = Box::leak(content.clone().into_boxed_str()).as_bytes();
let payload = Bytes::from(content_bytes);
let stream = stream::once(ok(payload));
assert_eq!(load_body(stream).await.unwrap(), Bytes::from(content_bytes));
}
#[actix_rt::test]
async fn read_response_body() {
let payload = random_string(20);
let payload_bytes = Bytes::from(payload.clone());
let app = init_service(
App::new().default_service(web::to(move || HttpResponse::Ok().body(payload.clone()))),
)
.await;
let req = TestRequest::default().to_request();
let res = call_service(&app, req).await;
assert_eq!(read_body(res.into()).await.unwrap(), payload_bytes);
}
}