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
|
// yt - A fully featured command line YouTube client
//
// Copyright (C) 2025 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// SPDX-License-Identifier: GPL-3.0-or-later
//
// This file is part of Yt.
//
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.
use std::{
env,
ffi::OsStr,
fmt::Write,
fs,
io::{self, BufRead, BufReader},
mem,
path::{Path, PathBuf},
process::{self, Stdio},
};
use rocie_client::{
apis::{api_set_no_auth_user_api::provision, configuration::Configuration},
models::UserStub,
};
use crate::{
_testenv::{Paths, log::request},
testenv::TestEnv,
};
macro_rules! function_name {
() => {{
fn f() {}
fn type_name_of<T>(_: T) -> &'static str {
std::any::type_name::<T>()
}
let name = type_name_of(f);
name.strip_suffix("::{{closure}}::f").unwrap()
}};
}
pub(crate) use function_name;
fn target_dir() -> PathBuf {
// Tests exe is in target/debug/deps, the *rocie-server* exe is in target/debug
env::current_exe()
.expect("./target/debug/deps/rocie-server-*")
.parent()
.expect("./target/debug/deps")
.parent()
.expect("./target/debug")
.parent()
.expect("./target")
.to_path_buf()
}
fn test_dir(name: &'static str) -> PathBuf {
target_dir().join("tests").join(name)
}
fn prepare_files_and_dirs(test_dir: &Path) -> io::Result<Paths> {
fs::create_dir_all(test_dir)?;
let db_path = test_dir.join("database.sqlite");
{
// Remove all files, so that the test run stays pure
for entry in fs::read_dir(test_dir).unwrap() {
let entry = entry.unwrap();
let entry_ft = entry.file_type().unwrap();
if entry_ft.is_dir() {
fs::remove_dir_all(entry.path())?;
} else if entry_ft.is_file() {
fs::remove_file(entry.path())?;
} else {
panic!("Unknown file: {} ({entry_ft:#?})", entry.path().display());
}
}
}
Ok(Paths {
db: db_path,
test_dir: test_dir.to_owned(),
})
}
fn find_server_exe() -> PathBuf {
let target = target_dir().join("debug");
let exe_name = if cfg!(windows) {
"rocie-server.exe"
} else {
"rocie-server"
};
target.join(exe_name)
}
fn rocie_base_path(port: &str) -> String {
format!("http://127.0.0.1:{port}")
}
fn rocie_server_args(paths: &Paths) -> [&OsStr; 4] {
[
OsStr::new("serve"),
OsStr::new("--db-path"),
paths.db.as_os_str(),
OsStr::new("--print-port"),
]
}
impl TestEnv {
pub(crate) async fn new(name: &'static str) -> TestEnv {
let env = Self::new_no_login(name);
request!(
env,
provision(UserStub {
description: Some("Test user, used during test runs".to_string()),
name: "rocie".to_string(),
password: "server".to_string()
})
);
env
}
pub(crate) fn new_no_login(name: &'static str) -> TestEnv {
let test_dir = test_dir(name);
let paths = prepare_files_and_dirs(&test_dir)
.inspect_err(|err| panic!("Error during test dir preparation: {err}"))
.unwrap();
let (server_process, port) = {
let server_exe = find_server_exe();
let mut cmd = process::Command::new(&server_exe);
cmd.current_dir(&paths.test_dir);
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
cmd.args(rocie_server_args(&paths));
let mut child = cmd.spawn().expect("server spawn");
let port: u16 = {
let mut stdout = BufReader::new(child.stdout.as_mut().expect("Was captured"));
let mut port = String::new();
assert_ne!(stdout.read_line(&mut port).expect("Works"), 0);
port.trim_end()
.parse()
.expect("The server should reply with a u16 port number")
};
(child, port)
};
let config = {
let mut inner = Configuration::new();
inner.base_path = rocie_base_path(port.to_string().as_str());
inner.user_agent = Some(String::from("Rocie test driver"));
inner
};
let me = TestEnv {
name,
test_dir,
paths,
server_process: Some(server_process),
config,
port: port.to_string(),
};
me.log(format!("Starting test `{name}` on port `{port}`"));
me
}
}
impl Drop for TestEnv {
fn drop(&mut self) {
/// Format an error message for when the server did not exit successfully.
fn format_exit(args: &[&OsStr], output: &process::Output) -> String {
let mut base = String::new();
{
let args = args
.iter()
.map(|s| s.to_str().unwrap())
.collect::<Vec<_>>()
.join(" ");
if output.status.success() {
writeln!(base, "`rocie-server {args}` did exit successfully.")
.expect("In-memory");
} else {
writeln!(base, "`rocie-server {args}` did not exit successfully.")
.expect("In-memory");
}
}
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
if !stdout.is_empty() {
writeln!(base, "Stdout:\n---\n{stdout}\n---").expect("In-memory");
}
if !stderr.is_empty() {
writeln!(base, "Stderr:\n---\n{stderr}\n---").expect("In-memory");
}
base
}
{
// Stop the server process via SIGTERM.
let mut kill = process::Command::new("kill")
.args([
"-s",
"TERM",
&self.server_process.as_ref().unwrap().id().to_string(),
])
.spawn()
.unwrap();
eprintln!("Killing the server process");
kill.wait().unwrap();
}
let output = mem::take(&mut self.server_process)
.expect("Is some at this point")
.wait_with_output()
.expect("server exit output");
eprintln!(
"{}",
format_exit(rocie_server_args(&self.paths).as_slice(), &output)
);
}
}
|