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
use crate::cmd::{cfg_spinner, run_stage};
use crate::install::Tools;
use crate::parse::{Opts, ServeOpts, TestOpts};
use crate::thread::spawn_thread;
use crate::{errors::*, serve};
use console::{style, Emoji};
use indicatif::{MultiProgress, ProgressBar};
use std::path::PathBuf;
use std::process::{Command, Stdio};

// Emoji for stages
static TESTING: Emoji<'_, '_> = Emoji("🧪", "");

/// Returns the exit code if it's non-zero.
macro_rules! handle_exit_code {
    ($code:expr) => {
        let (_, _, code) = $code;
        if code != 0 {
            return ::std::result::Result::Ok(code);
        }
    };
}

/// Tests the user's app by creating a testing server and running `cargo test`
/// against it, which will presumably use a WebDriver of some kind.
pub fn test(
    dir: PathBuf,
    test_opts: &TestOpts,
    tools: &Tools,
    global_opts: &Opts,
) -> Result<i32, ExecutionError> {
    // We need to own this for the threads
    let tools = tools.clone();
    let Opts {
        cargo_engine_path,
        cargo_engine_args,
        verbose,
        ..
    } = global_opts.clone();

    let serve_opts = ServeOpts {
        // We want to run the binary while we run `cargo test` at the same time
        no_run: true,
        no_build: test_opts.no_build,
        release: false,
        standalone: false,
        watch: test_opts.watch,
        custom_watch: test_opts.custom_watch.clone(),
        host: test_opts.host.clone(),
        port: test_opts.port,
    };
    let num_steps: u8 = if test_opts.no_build { 2 } else { 4 };
    // This will do all sorts of things with spinners etc., but we've told it we're
    // testing, so things will be neater
    let spinners = MultiProgress::new();
    let (exit_code, server_path) = serve(
        dir.clone(),
        &serve_opts,
        &tools,
        global_opts,
        &spinners,
        true,
    )?;
    if exit_code != 0 {
        return Ok(exit_code);
    }
    if let Some(server_path) = server_path {
        // Building is complete and we have a path to run the server, so we'll now do
        // that with a child process (doesn't need to be in a separate thread, since
        // it's long-running)
        let mut server = Command::new(&server_path)
            .envs([
                ("PERSEUS_ENGINE_OPERATION", "serve"),
                ("PERSEUS_TESTING", "true"),
            ])
            .current_dir(&dir)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .map_err(|err| ExecutionError::CmdExecFailed {
                cmd: server_path,
                source: err,
            })?;

        // Now run the Cargo tests against that
        let test_msg = format!(
            "{} {} Running tests",
            style(format!("[{}/{}]", num_steps, num_steps)).bold().dim(),
            TESTING,
        );
        let test_spinner = spinners.insert(num_steps.into(), ProgressBar::new_spinner());
        let test_spinner = cfg_spinner(test_spinner, &test_msg);
        let test_dir = dir;
        let headless = !test_opts.show_browser;
        let test_thread = spawn_thread(
            move || {
                handle_exit_code!(run_stage(
                    vec![&format!(
                        // We use single-threaded testing, because most webdrivers don't support
                        // multithreaded testing yet
                        "{} test {} -- --test-threads 1",
                        cargo_engine_path, cargo_engine_args
                    )],
                    &test_dir,
                    &test_spinner,
                    &test_msg,
                    if headless {
                        vec![
                            ("CARGO_TARGET_DIR", "dist/target_engine"),
                            ("RUSTFLAGS", "--cfg=engine"),
                            ("CARGO_TERM_COLOR", "always"),
                            ("PERSEUS_RUN_WASM_TESTS", "true"),
                            ("PERSEUS_RUN_WASM_TESTS_HEADLESS", "true"),
                        ]
                    } else {
                        vec![
                            ("CARGO_TARGET_DIR", "dist/target_engine"),
                            ("RUSTFLAGS", "--cfg=engine"),
                            ("CARGO_TERM_COLOR", "always"),
                            ("PERSEUS_RUN_WASM_TESTS", "true"),
                        ]
                    },
                    verbose,
                )?);

                Ok(0)
            },
            // See above
            false,
        );

        let test_res = test_thread
            .join()
            .map_err(|_| ExecutionError::ThreadWaitFailed)??;

        // If the server has already terminated, it had an error, and that would be
        // reflected in the tests
        let _ = server.kill();

        if test_res != 0 {
            return Ok(test_res);
        }

        // We've handled errors in the component threads, so the exit code is now zero
        Ok(0)
    } else {
        Err(ExecutionError::GetServerExecutableFailedSimple.into())
    }
}