Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
google
GitHub Repository: google/crosvm
Path: blob/main/devices/src/mock.rs
5392 views
1
// Copyright 2025 The ChromiumOS Authors
2
// Use of this source code is governed by a BSD-style license that can be
3
// found in the LICENSE file.
4
5
//! Centralized mock device implementations, for unit-tests.
6
7
use std::cmp::PartialEq;
8
use std::default::Default;
9
10
use anyhow::Context;
11
use serde::Deserialize;
12
use serde::Serialize;
13
use snapshot::AnySnapshot;
14
use vm_control::DeviceId;
15
use vm_control::PlatformDeviceId;
16
17
use crate::BusDevice;
18
use crate::Suspendable;
19
20
/// A mock device, for unit-tests.
21
#[derive(Copy, Clone, Serialize, Deserialize, Eq, PartialEq, Debug)]
22
pub struct MockDevice {
23
suspendable_switch: bool,
24
}
25
26
impl MockDevice {
27
/// Create a basic mock device with methods that succeed but do nothing.
28
pub fn new() -> Self {
29
Self {
30
suspendable_switch: false,
31
}
32
}
33
34
/// Changes the state of the device in a way that affects its snapshots.
35
pub fn toggle_suspendable_switch(&mut self) {
36
self.suspendable_switch ^= true
37
}
38
}
39
40
impl Default for MockDevice {
41
fn default() -> Self {
42
Self::new()
43
}
44
}
45
46
impl BusDevice for MockDevice {
47
fn device_id(&self) -> DeviceId {
48
PlatformDeviceId::Mock.into()
49
}
50
51
fn debug_label(&self) -> String {
52
"mock device".to_owned()
53
}
54
}
55
56
impl Suspendable for MockDevice {
57
fn snapshot(&mut self) -> anyhow::Result<AnySnapshot> {
58
AnySnapshot::to_any(self).context("error serializing")
59
}
60
61
fn restore(&mut self, data: AnySnapshot) -> anyhow::Result<()> {
62
*self = AnySnapshot::from_any(data).context("error deserializing")?;
63
Ok(())
64
}
65
66
fn sleep(&mut self) -> anyhow::Result<()> {
67
Ok(())
68
}
69
70
fn wake(&mut self) -> anyhow::Result<()> {
71
Ok(())
72
}
73
}
74
75
#[cfg(test)]
76
mod tests {
77
use super::*;
78
use crate::suspendable_tests;
79
80
suspendable_tests!(
81
mock_device,
82
MockDevice::new(),
83
MockDevice::toggle_suspendable_switch
84
);
85
}
86
87