about summary refs log tree commit diff stats
path: root/crates/rocie-server/tests/_testenv/init.rs
blob: 5309fea6a28c8ec49f2849455150e90ff60caf6f (plain) (blame)
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
// 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, mem,
    path::{Path, PathBuf},
    process::{self, Stdio},
    thread::sleep,
    time::Duration,
};

use rocie_client::apis::configuration::Configuration;

use crate::{_testenv::Paths, testenv::TestEnv};

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, port: u32) -> PathBuf {
    target_dir().join("tests").join(name).join(port.to_string())
}

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<'a>(paths: &'a Paths, port: &'a str) -> [&'a OsStr; 5] {
    [
        OsStr::new("serve"),
        OsStr::new("--db-path"),
        paths.db.as_os_str(),
        OsStr::new("--port"),
        OsStr::new(port),
    ]
}

impl TestEnv {
    pub(crate) fn new(name: &'static str, port: u32) -> TestEnv {
        let test_dir = test_dir(name, port);

        let paths = prepare_files_and_dirs(&test_dir)
            .inspect_err(|err| panic!("Error during test dir preparation: {err}"))
            .unwrap();

        let server_process = {
            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, port.to_string().as_str()));

            let child = cmd.spawn().expect("server spawn");

            // Give the server time to start.
            // TODO(@bpeetz): Use a better synchronization primitive <2025-09-11>
            sleep(Duration::from_millis(240));

            child
        };

        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, &self.port).as_slice(),
                &output
            )
        );
    }
}