summaryrefslogtreecommitdiffhomepage
path: root/test/test-manager/src/run_tests.rs
blob: f0ff402034041162581525f465272382d44d1275 (plain)
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
use crate::summary::{self, maybe_log_test_result};
use crate::tests::TestContext;
use crate::{
    logging::{panic_as_string, TestOutput},
    mullvad_daemon, tests,
    tests::Error,
    vm,
};
use anyhow::{Context, Result};
use futures::FutureExt;
use mullvad_management_interface::ManagementServiceClient;
use std::future::Future;
use std::panic;
use std::time::Duration;
use test_rpc::logging::Output;
use test_rpc::{mullvad_daemon::MullvadClientVersion, ServiceClient};

const BAUD: u32 = 115200;

pub async fn run(
    config: tests::config::TestConfig,
    instance: &dyn vm::VmInstance,
    test_filters: &[String],
    skip_wait: bool,
    print_failed_tests_only: bool,
    mut summary_logger: Option<summary::SummaryLogger>,
) -> Result<()> {
    log::trace!("Setting test constants");
    tests::config::TEST_CONFIG.init(config);

    let pty_path = instance.get_pty();

    log::info!("Connecting to {pty_path}");

    let serial_stream =
        tokio_serial::SerialStream::open(&tokio_serial::new(pty_path, BAUD)).unwrap();
    let (runner_transport, mullvad_daemon_transport, mut connection_handle, completion_handle) =
        test_rpc::transport::create_client_transports(serial_stream).await?;

    if !skip_wait {
        connection_handle.wait_for_server().await?;
    }

    log::info!("Running client");

    let client = ServiceClient::new(connection_handle.clone(), runner_transport);
    let mullvad_client =
        mullvad_daemon::new_rpc_client(connection_handle, mullvad_daemon_transport).await;

    let mut tests: Vec<_> = inventory::iter::<tests::TestMetadata>().collect();
    tests.sort_by_key(|test| test.priority.unwrap_or(0));

    if !test_filters.is_empty() {
        tests.retain(|test| {
            if test.always_run {
                return true;
            }
            for command in test_filters {
                let command = command.to_lowercase();
                if test.command.to_lowercase().contains(&command) {
                    return true;
                }
            }
            false
        });
    }

    let mut final_result = Ok(());

    let test_context = TestContext {
        rpc_provider: mullvad_client,
    };

    let mut successful_tests = vec![];
    let mut failed_tests = vec![];

    let logger = super::logging::Logger::get_or_init();

    for test in tests {
        let mut mclient = test_context
            .rpc_provider
            .as_type(test.mullvad_client_version)
            .await;

        if let Some(client) = mclient.downcast_mut::<ManagementServiceClient>() {
            crate::tests::init_default_settings(client).await;
        }

        log::info!("Running {}", test.name);

        if print_failed_tests_only {
            // Stop live record
            logger.store_records(true);
        }

        let test_result = run_test(
            client.clone(),
            mclient,
            &test.func,
            test.name,
            test_context.clone(),
        )
        .await;

        if test.mullvad_client_version == MullvadClientVersion::New {
            // Try to reset the daemon state if the test failed OR if the test doesn't explicitly
            // disabled cleanup.
            if test.cleanup || matches!(test_result.result, Err(_) | Ok(Err(_))) {
                let mut client = test_context.rpc_provider.new_client().await;
                crate::tests::cleanup_after_test(&mut client).await?;
            }
        }

        if print_failed_tests_only {
            // Print results of failed test
            if matches!(test_result.result, Err(_) | Ok(Err(_))) {
                logger.print_stored_records();
            } else {
                logger.flush_records();
            }
            logger.store_records(false);
        }

        test_result.print();

        let test_succeeded = matches!(test_result.result, Ok(Ok(_)));

        maybe_log_test_result(
            summary_logger.as_mut(),
            test.name,
            if test_succeeded {
                summary::TestResult::Pass
            } else {
                summary::TestResult::Fail
            },
        )
        .await
        .context("Failed to log test result")?;

        match test_result.result {
            Err(panic) => {
                failed_tests.push(test.name);
                final_result = Err(panic).context("test panicked");
                if test.must_succeed {
                    break;
                }
            }
            Ok(Err(failure)) => {
                failed_tests.push(test.name);
                final_result = Err(failure).context("test failed");
                if test.must_succeed {
                    break;
                }
            }
            Ok(Ok(result)) => {
                successful_tests.push(test.name);
                final_result = final_result.and(Ok(result));
            }
        }
    }

    log::info!("TESTS THAT SUCCEEDED:");
    for test in successful_tests {
        log::info!("{test}");
    }

    log::info!("TESTS THAT FAILED:");
    for test in failed_tests {
        log::info!("{test}");
    }

    // wait for cleanup
    drop(test_context);
    let _ = tokio::time::timeout(Duration::from_secs(5), completion_handle).await;

    final_result
}

pub async fn run_test<F, R, MullvadClient>(
    runner_rpc: ServiceClient,
    mullvad_rpc: MullvadClient,
    test: &F,
    test_name: &'static str,
    test_context: super::tests::TestContext,
) -> TestOutput
where
    F: Fn(super::tests::TestContext, ServiceClient, MullvadClient) -> R,
    R: Future<Output = Result<(), Error>>,
{
    let _flushed = runner_rpc.try_poll_output().await;

    // Assert that the test is unwind safe, this is the same assertion that cargo tests do. This
    // assertion being incorrect can not lead to memory unsafety however it could theoretically
    // lead to logic bugs. The problem of forcing the test to be unwind safe is that it causes a
    // large amount of unergonomic design.
    let result = panic::AssertUnwindSafe(test(test_context, runner_rpc.clone(), mullvad_rpc))
        .catch_unwind()
        .await
        .map_err(panic_as_string);

    let mut output = vec![];
    if matches!(result, Ok(Err(_)) | Err(_)) {
        let output_after_test = runner_rpc.try_poll_output().await;
        match output_after_test {
            Ok(mut output_after_test) => {
                output.append(&mut output_after_test);
            }
            Err(e) => {
                output.push(Output::Other(format!("could not get logs: {:?}", e)));
            }
        }
    }

    let log_output = runner_rpc.get_mullvad_app_logs().await.ok();

    TestOutput {
        log_output,
        test_name,
        error_messages: output,
        result,
    }
}