Skip to content

Commit

Permalink
Add unit tests to availability module
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkusPettersson98 authored and dlon committed Sep 26, 2024
1 parent 0791526 commit 44c068c
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
4 changes: 4 additions & 0 deletions mullvad-api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }

Expand Down
36 changes: 36 additions & 0 deletions mullvad-api/src/availability.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
}
}

0 comments on commit 44c068c

Please sign in to comment.