vmtest 0.18.0

Helps run your tests in virtual machines
Documentation
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::Path;
use std::sync::mpsc::channel;

use tempfile::{tempdir, tempdir_in};
use test_log::test;

use vmtest::output::Output;
use vmtest::ui::Ui;
use vmtest::Mount;
use vmtest::{Config, Target, VMConfig};

mod helpers;
use helpers::*;

// Expect that we can run the entire matrix successfully
#[test]
fn test_run() {
    let config = Config {
        target: vec![
            Target {
                name: "uefi image boots with uefi flag".to_string(),
                image: Some(asset("image-uefi.raw-efi")),
                uefi: true,
                command: "/mnt/vmtest/main.sh nixos".to_string(),
                ..Default::default()
            },
            Target {
                name: "not uefi image boots without uefi flag".to_string(),
                image: Some(asset("image-not-uefi.raw")),
                uefi: false,
                command: "/mnt/vmtest/main.sh nixos".to_string(),
                ..Default::default()
            },
        ],
    };
    let (vmtest, _dir) = setup(config, &["main.sh"]);
    let ui = Ui::new(vmtest);
    let failed = ui.run(false);
    assert_eq!(failed, 0);
}

// Expect that when we run multiple targets, we get the correct number of failures.
#[test]
fn test_run_multiple_return_number_failures() {
    let config = Config {
        target: vec![
            Target {
                name: "uefi image boots with uefi flag".to_string(),
                image: Some(asset("image-uefi.raw-efi")),
                uefi: true,
                command: "exit 1".to_string(),
                ..Default::default()
            },
            Target {
                name: "uefi image boots with uefi flag 2".to_string(),
                image: Some(asset("image-uefi.raw-efi")),
                uefi: true,
                command: "exit 1".to_string(),
                ..Default::default()
            },
            Target {
                name: "not uefi image boots without uefi flag".to_string(),
                image: Some(asset("image-not-uefi.raw")),
                uefi: false,
                command: "/mnt/vmtest/main.sh nixos".to_string(),
                ..Default::default()
            },
        ],
    };
    let (vmtest, _dir) = setup(config, &["main.sh"]);
    let ui = Ui::new(vmtest);
    let failed = ui.run(false);
    assert_eq!(failed, 2);
}

// Expect that when we run a single target, we return the return code of the command.
#[test]
fn test_run_single_return_number_return_code() {
    let config = Config {
        target: vec![Target {
            name: "not uefi image boots without uefi flag".to_string(),
            image: Some(asset("image-not-uefi.raw")),
            uefi: false,
            command: "exit 12".to_string(),
            ..Default::default()
        }],
    };
    let (vmtest, _dir) = setup(config, &["main.sh"]);
    let ui = Ui::new(vmtest);
    let failed = ui.run(false);
    assert_eq!(failed, 12);
}

// Expect that when we fail to start the vm, we return 69 (EX_UNAVAILABLE).
#[test]
fn test_vmtest_infra_error() {
    let config = Config {
        target: vec![Target {
            name: "not an actual image, should return EX_UNAVAILABLE".to_string(),
            image: Some(asset("not_an_actual_image")),
            uefi: false,
            command: "exit 12".to_string(),
            ..Default::default()
        }],
    };
    let (vmtest, _dir) = setup(config, &["main.sh"]);
    let ui = Ui::new(vmtest);
    let failed = ui.run(false);
    assert_eq!(failed, 69);
}

// Expect we can run each target one by one, sucessfully
#[test]
fn test_run_one() {
    let uefi_image = create_new_image(asset("image-uefi.raw-efi"));
    let non_uefi_image = create_new_image(asset("image-not-uefi.raw"));

    let config = Config {
        target: vec![
            Target {
                name: "uefi image boots with uefi flag".to_string(),
                image: Some(uefi_image.as_pathbuf()),
                uefi: true,
                command: "/mnt/vmtest/main.sh nixos".to_string(),
                ..Default::default()
            },
            Target {
                name: "not uefi image boots without uefi flag".to_string(),
                image: Some(non_uefi_image.as_pathbuf()),
                uefi: false,
                command: "/mnt/vmtest/main.sh nixos".to_string(),
                ..Default::default()
            },
        ],
    };
    let (vmtest, _dir) = setup(config, &["main.sh"]);
    for i in 0..2 {
        let (send, recv) = channel();
        vmtest.run_one(i, send);
        assert_no_err!(recv);
    }
}

// Expect that we have bounds checks
#[test]
fn test_run_out_of_bounds() {
    let uefi_image = create_new_image(asset("image-uefi.raw-efi"));
    let non_uefi_image = create_new_image(asset("image-not-uefi.raw"));

    let config = Config {
        target: vec![
            Target {
                name: "uefi image boots with uefi flag".to_string(),
                image: Some(uefi_image.as_pathbuf()),
                uefi: true,
                command: "/mnt/vmtest/main.sh nixos".to_string(),
                ..Default::default()
            },
            Target {
                name: "not uefi image boots without uefi flag".to_string(),
                image: Some(non_uefi_image.as_pathbuf()),
                uefi: false,
                command: "/mnt/vmtest/main.sh nixos".to_string(),
                ..Default::default()
            },
        ],
    };
    let (vmtest, _dir) = setup(config, &["main.sh"]);
    let (send, recv) = channel();
    vmtest.run_one(2, send);
    assert_err!(recv, Output::BootEnd);
}

// Try running a uefi image without uefi flag. It should fail to boot.
#[test]
fn test_not_uefi() {
    let uefi_image = create_new_image(asset("image-uefi.raw-efi"));

    let config = Config {
        target: vec![Target {
            name: "uefi image does not boot without uefi flag".to_string(),
            image: Some(uefi_image.as_pathbuf()),
            uefi: false,
            command: "echo unreachable".to_string(),
            ..Default::default()
        }],
    };
    let (vmtest, _dir) = setup(config, &["main.sh"]);
    let (send, recv) = channel();
    vmtest.run_one(0, send);
    assert_err!(recv, Output::BootEnd);
}

#[test]
fn test_command_runs_in_shell() {
    let config = Config {
        target: vec![Target {
            name: "command is run in shell".to_string(),
            kernel: Some(asset("bzImage-v5.15-default")),
            // `$0` is a portable way of getting the name of the shell without relying
            // on env vars which may be propagated from the host into the guest.
            command: "if true; then echo -n $0 > /mnt/vmtest/result; fi".to_string(),
            ..Default::default()
        }],
    };
    let (vmtest, dir) = setup(config, &[]);
    let (send, recv) = channel();
    vmtest.run_one(0, send);
    assert_no_err!(recv);

    // Check that output file contains the shell
    let result_path = dir.path().join("result");
    let result = fs::read_to_string(result_path).expect("Failed to read result");
    assert_eq!(result, "bash");
}

// Validate that we can run an interactive shell when passing `-` as the command.
// We need to sleep a bit before sending our command as it takes a bit of time
// for the shared directory to be mounted by QGA.
#[test]
fn test_interactive_shell() {
    let dir = tempdir().expect("Failed to create tempdir");
    assert!(env::set_current_dir(dir.path()).is_ok());
    let vmtest_bin_path = Path::new(env!("CARGO_BIN_EXE_vmtest"));
    let command = format!(
        "{} --kernel {} -",
        vmtest_bin_path
            .to_str()
            .expect("Failed to convert vmtest path to str"),
        asset("bzImage-v5.15-default").to_str().unwrap(),
    );
    let mut p = rexpect::spawn(&command, Some(30000)).expect("Failed to spawn vmtest");
    p.exp_regex(".*root@.*#.*")
        .expect("Did not get shell prompt");
    // sleep 10 seconds to give a chance to set up shared directory with qga.
    p.send_line("sleep 10")
        .expect("Failed to send sleep command");

    p.send_line("echo \"hello world\" > /mnt/vmtest/result")
        .expect("Failed to send echo command");
    p.exp_regex(".*root@.*#.*")
        .expect("Did not get shell prompt after sending command.");
    p.send_line("exit").expect("Failed to send exit command.");
    p.exp_eof().expect("vmtest did not return EOF");

    // Check that output file contains "hello world"
    let result_path = dir.path().join("result");
    let result = fs::read_to_string(result_path).expect("Failed to read result");
    assert_eq!(result, "hello world\n");
}

// Tests that for kernel targets, environment variables from the host are propagated
// into the guest.
#[test]
fn test_kernel_target_env_var_propagation() {
    let config = Config {
        target: vec![Target {
            name: "host env vars are propagated into guest".to_string(),
            kernel: Some(asset("bzImage-v5.15-default")),
            command: "echo -n $TEST_ENV_VAR > /mnt/vmtest/result".to_string(),
            ..Default::default()
        }],
    };

    // Set test env var
    env::set_var("TEST_ENV_VAR", "test value");

    let (vmtest, dir) = setup(config, &[]);
    let (send, recv) = channel();
    vmtest.run_one(0, send);
    assert_no_err!(recv);

    // Check that output file contains the shell
    let result_path = dir.path().join("result");
    let result = fs::read_to_string(result_path).expect("Failed to read result");
    assert_eq!(result, "test value");
}

// Tests that for kernel targets, current working directory is preserved in the guest
#[test]
fn test_kernel_target_cwd_preserved() {
    let config = Config {
        target: vec![Target {
            name: "host cwd preserved in guest".to_string(),
            kernel: Some(asset("bzImage-v5.15-default")),
            command: "cat text_file.txt".to_string(),
            ..Default::default()
        }],
    };

    // Calculate source fixture directory and pass it in as the base path
    // to `Vmtest`. The base path is what controls the working directory.
    //
    // Note the base path is used for other stuff too like resolving relative
    // paths in the config, but since we are careful to use absolute paths
    // in the config we can decouple that behavior for this test.
    let root = Path::new(env!("CARGO_MANIFEST_DIR"));
    let fixtures = root.join("tests/fixtures");
    let vmtest = vmtest::Vmtest::new(fixtures, config).expect("Failed to construct vmtest");

    let (send, recv) = channel();
    vmtest.run_one(0, send);
    assert_no_err!(recv);
}

#[test]
fn test_command_process_substitution() {
    let config = Config {
        target: vec![Target {
            name: "command can run process substitution".to_string(),
            kernel: Some(asset("bzImage-v5.15-default")),
            // `$0` is a portable way of getting the name of the shell without relying
            // on env vars which may be propagated from the host into the guest.
            command: "cat <(echo -n $0) > /mnt/vmtest/result".to_string(),
            ..Default::default()
        }],
    };
    let (vmtest, dir) = setup(config, &[]);
    let (send, recv) = channel();
    vmtest.run_one(0, send);
    assert_no_err!(recv);

    // Check that output file contains the shell
    let result_path = dir.path().join("result");
    let result = fs::read_to_string(result_path).expect("Failed to read result");
    assert_eq!(result, "bash");
}

#[test]
fn test_qemu_error_shown() {
    let config = Config {
        target: vec![Target {
            name: "invalid kernel path".to_string(),
            kernel: Some(asset("doesn't exist")),
            command: "true".to_string(),
            ..Default::default()
        }],
    };
    let (vmtest, _dir) = setup(config, &[]);
    let (send, recv) = channel();
    vmtest.run_one(0, send);

    let err = assert_get_err!(recv, Output::BootEnd);
    let msg = err.to_string();
    assert!(msg.contains("qemu: could not open kernel file"));
}

// Test that host FS cannot be written to if `ro` flag is passed to guest kernel args
#[test]
fn test_kernel_ro_flag() {
    // Cannot place this dir in tmpfs b/c vmtest will mount over host /tmp with a new tmpfs
    let root = Path::new(env!("CARGO_MANIFEST_DIR"));
    let touch_dir = tempdir_in(root).expect("Failed to create tempdir");

    let config = Config {
        target: vec![Target {
            name: "cannot touch host rootfs with ro".to_string(),
            kernel: Some(asset("bzImage-v5.15-default")),
            kernel_args: Some("ro".to_string()),
            command: format!("touch {}/file", touch_dir.path().display()),
            ..Default::default()
        }],
    };
    let (vmtest, _dir) = setup(config, &[]);
    let (send, recv) = channel();
    vmtest.run_one(0, send);
    assert_err!(recv, Output::CommandEnd, i64);
}

#[test]
fn test_run_custom_resources() {
    let uefi_image_t1 = create_new_image(asset("image-uefi.raw-efi"));
    let uefi_image_t2 = create_new_image(asset("image-uefi.raw-efi"));

    let config = Config {
        target: vec![
            Target {
                name: "Custom number of CPUs".to_string(),
                image: Some(uefi_image_t1.as_pathbuf()),
                uefi: true,
                command: r#"bash -xc "[[ "$(nproc)" == "1" ]]""#.into(),
                vm: VMConfig {
                    num_cpus: 1,
                    ..Default::default()
                },
                ..Default::default()
            },
            Target {
                name: "Custom amount of RAM".to_string(),
                image: Some(uefi_image_t2.as_pathbuf()),
                uefi: true,
                // Should be in the 200 thousands, but it's variable.
                command: r#"bash -xc "cat /proc/meminfo | grep 'MemTotal:         2..... kB'""#
                    .into(),
                vm: VMConfig {
                    memory: "256M".into(),
                    ..Default::default()
                },
                ..Default::default()
            },
        ],
    };
    let (vmtest, _dir) = setup(config, &["main.sh"]);
    for i in 0..2 {
        let (send, recv) = channel();
        vmtest.run_one(i, send);
        assert_no_err!(recv);
    }
}

#[test]
fn test_run_custom_mounts() {
    let uefi_image = create_new_image(asset("image-uefi.raw-efi"));

    let config = Config {
        target: vec![
            Target {
                name: "mount".to_string(),
                image: Some(uefi_image.as_pathbuf()),
                uefi: true,
                command: r#"bash -xc "[[ -e /tmp/mount/README.md ]]""#.into(),
                vm: VMConfig {
                    mounts: HashMap::from([(
                        "/tmp/mount".into(),
                        Mount {
                            host_path: Path::new(env!("CARGO_MANIFEST_DIR")).into(),
                            writable: true,
                        },
                    )]),
                    ..Default::default()
                },
                ..Default::default()
            },
            Target {
                name: "RO mount".to_string(),
                image: Some(uefi_image.as_pathbuf()),
                uefi: true,
                command: r#"bash -xc "(touch /tmp/ro/hi && exit -1) || true""#.into(),
                vm: VMConfig {
                    mounts: HashMap::from([(
                        "/tmp/ro".into(),
                        Mount {
                            host_path: Path::new(env!("CARGO_MANIFEST_DIR")).into(),
                            writable: false,
                        },
                    )]),
                    ..Default::default()
                },
                ..Default::default()
            },
        ],
    };
    let (vmtest, _dir) = setup(config, &["main.sh"]);
    for i in 0..2 {
        let (send, recv) = channel();
        vmtest.run_one(i, send);
        assert_no_err!(recv);
    }
}