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
extern crate tempfile;
use serde_json::Value;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::fs::File;
use std::io::prelude::*;
use std::io::SeekFrom;
use std::io::Write;
use std::process;
use std::process::{Command, Stdio};
use std::str;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use tempfile::tempdir;
use warp::{self, Buf, Filter};
pub struct TestCommand {
command: String,
args: Vec<&'static str>,
child_handle: RefCell<Box<Option<process::Child>>>,
}
impl TestCommand {
pub fn new(command: &str, args: Vec<&'static str>) -> TestCommand {
TestCommand {
command: String::from(command),
args,
child_handle: RefCell::new(Box::new(None)),
}
}
pub fn spawn(&self) {
let child = Command::new(self.command.to_owned())
.args(&self.args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("Failed to start");
let mut child_handle = self.child_handle.borrow_mut();
*child_handle = Box::new(Some(child));
}
}
pub struct TestService {
config_path: String,
_config_file: File,
_tmp_dir: tempfile::TempDir,
name: String,
child_handle: RefCell<Box<Option<process::Child>>>,
}
impl TestService {
pub fn new(name: &str, ip: &str, port: u16) -> TestService {
let mut config = Vec::new();
writeln!(&mut config, "[{}.addr]", name).unwrap();
writeln!(&mut config, "ip = \"{}\"", ip).unwrap();
writeln!(&mut config, "port = {}", port).unwrap();
let config_str = String::from_utf8(config).unwrap();
let dir = tempdir().unwrap();
let config_path = dir.path().join("config.toml");
let mut config_file = File::create(config_path.clone()).unwrap();
writeln!(config_file, "{}", config_str).unwrap();
TestService {
config_path: config_path.to_str().unwrap().to_owned(),
_config_file: config_file,
_tmp_dir: dir,
name: String::from(name),
child_handle: RefCell::new(Box::new(None)),
}
}
pub fn config(&mut self, config_data: &str) {
self._config_file.seek(SeekFrom::End(0)).unwrap();
self._config_file.write_all(config_data.as_bytes()).unwrap();
}
pub fn build(&self) {
Command::new("cargo")
.arg("build")
.arg("--package")
.arg(self.name.to_owned())
.output()
.expect("Failed to build service");
}
pub fn spawn(&self) {
let child = Command::new("cargo")
.arg("run")
.arg("--package")
.arg(self.name.clone())
.arg("--")
.arg("-c")
.arg(self.config_path.clone())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("Failed to start");
let mut child_handle = self.child_handle.borrow_mut();
*child_handle = Box::new(Some(child));
}
pub fn kill(&self) {
let mut borrowed_child = self.child_handle.borrow_mut();
if let Some(mut handle) = borrowed_child.take() {
handle.kill().unwrap();
}
}
}
impl Drop for TestService {
fn drop(&mut self) {
let mut borrowed_child = self.child_handle.borrow_mut();
if let Some(mut handle) = borrowed_child.take() {
handle.kill().unwrap();
}
}
}
pub fn service_query(query: &str, ip: &str, port: u16) -> Value {
let client = reqwest::Client::builder()
.timeout(Duration::from_millis(100))
.build()
.unwrap();
let mut map = ::std::collections::HashMap::new();
map.insert("query", query);
for _ in 0..5 {
if let Ok(mut result) = client
.post(&format!("http://{}:{}", ip, port))
.json(&map)
.send()
{
return serde_json::from_str(&result.text().unwrap()).unwrap();
}
thread::sleep(Duration::from_millis(100));
}
panic!("Service query failed - {}:{}", ip, port);
}
pub struct ServiceListener {
requests: Arc<Mutex<VecDeque<String>>>,
}
impl ServiceListener {
pub fn spawn(_ip: &str, port: u16) -> ServiceListener {
let requests = Arc::new(Mutex::new(VecDeque::<String>::new()));
let req_handle = requests.clone();
let listener = warp::post2()
.and(warp::any())
.and(warp::body::concat().and_then(|body: warp::body::FullBody| {
std::str::from_utf8(body.bytes())
.map(String::from)
.map_err(warp::reject::custom)
}))
.map(move |body: String| {
req_handle.lock().unwrap().push_back(body.to_owned());
"hi"
});
thread::spawn(move || warp::serve(listener).run(([127, 0, 0, 1], port)));
ServiceListener {
requests: requests.clone(),
}
}
pub fn get_request(&self) -> Option<String> {
self.requests.lock().unwrap().pop_front()
}
}