From 44c068cbba1735f212a7a05f547889669fc82470 Mon Sep 17 00:00:00 2001 From: Markus Pettersson Date: Thu, 26 Sep 2024 10:55:27 +0200 Subject: [PATCH] Add unit tests to `availability` module --- mullvad-api/Cargo.toml | 4 ++++ mullvad-api/src/availability.rs | 36 +++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/mullvad-api/Cargo.toml b/mullvad-api/Cargo.toml index c181694a4bae..fe2998106970 100644 --- a/mullvad-api/Cargo.toml +++ b/mullvad-api/Cargo.toml @@ -37,6 +37,10 @@ talpid-time = { path = "../talpid-time" } shadowsocks = { workspace = true, features = [ "stream-cipher" ] } +[dev-dependencies] +talpid-time = { path = "../talpid-time", features = ["test"] } +tokio = { workspace = true, features = ["test-util", "time"] } + [build-dependencies] cbindgen = { version = "0.24.3", default-features = false } diff --git a/mullvad-api/src/availability.rs b/mullvad-api/src/availability.rs index 976b03820245..0857a7812b59 100644 --- a/mullvad-api/src/availability.rs +++ b/mullvad-api/src/availability.rs @@ -268,3 +268,39 @@ impl Drop for ApiAvailabilityState { self.stop_inactivity_timer(); } } + +#[cfg(test)] +mod test { + use super::*; + /// Use mockable time for tests + pub use tokio::time::Duration; + + // Note that all of these tests needs a tokio runtime. Creating an instance of [`ApiAvailability`] will implicitly + // spawn a tokio task. + + /// Test that the inactivity timer starts in an expected state. + #[tokio::test(start_paused = true)] + async fn test_initially_active() { + // Start a new timer. It should *not* start as paused. + let timer = ApiAvailability::default(); + assert!( + !timer.get_state().is_background_paused(), + "Inactivity timer should be active" + ) + } + + /// Test that the inactivity timer kicks in after [`INACTIVITY_TIME`] of inactivity. + #[tokio::test(start_paused = true)] + async fn test_inactivity() { + // Start a new timer. It should be marked as 'active'. + let timer = ApiAvailability::default(); + // Elapse INACTIVITY_TIME (+ some slack because clocks) + const SLACK: Duration = Duration::from_secs(1); + talpid_time::sleep(INACTIVITY_TIME + SLACK).await; + // Check that the timer is now marked as 'inactive' + assert!( + timer.get_state().is_background_paused(), + "Inactivity timer should be inactive because 'INACTIVITY_TIME' has passed" + ) + } +}