Skip to content

Commit

Permalink
test(bootstrap): increase coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
lennartkloock committed Jan 7, 2025
1 parent d9601ad commit 91fd95e
Show file tree
Hide file tree
Showing 6 changed files with 155 additions and 9 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions crates/bootstrap/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ documentation = "https://docs.rs/scuffle-bootstrap"
license = "MIT OR Apache-2.0"
keywords = ["bootstrap", "binary", "cli", "config"]

[lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(coverage_nightly)'] }

[dependencies]
anyhow = "1.0"
tokio = { version = "1", features = ["full"] }
Expand All @@ -19,3 +22,6 @@ pin-project-lite = "0.2"
scuffle-context.workspace = true
scuffle-bootstrap-derive.workspace = true
scuffle-workspace-hack.workspace = true

[dev-dependencies]
scuffle-future-ext.workspace = true
16 changes: 16 additions & 0 deletions crates/bootstrap/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,19 @@ impl ConfigParser for EmptyConfig {
std::future::ready(Ok(EmptyConfig))
}
}

#[cfg(test)]
#[cfg_attr(all(test, coverage_nightly), coverage(off))]
mod tests {
use super::{ConfigParser, EmptyConfig};

#[tokio::test]
async fn unit_config() {
assert!(matches!(<()>::parse().await, Ok(())));
}

#[tokio::test]
async fn empty_config() {
assert!(matches!(EmptyConfig::parse().await, Ok(EmptyConfig)));
}
}
80 changes: 72 additions & 8 deletions crates/bootstrap/src/global.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::sync::Arc;

use crate::config::{ConfigParser, EmptyConfig};

fn default_runtime() -> tokio::runtime::Runtime {
fn default_runtime_builder() -> tokio::runtime::Builder {
let worker_threads = std::env::var("TOKIO_WORKER_THREADS")
.unwrap_or_default()
.parse::<usize>()
Expand Down Expand Up @@ -66,7 +66,7 @@ fn default_runtime() -> tokio::runtime::Runtime {
builder.max_io_events_per_tick(max_io_events_per_tick);
}

builder.build().expect("runtime build")
builder
}

pub trait Global: Send + Sync + 'static {
Expand All @@ -75,7 +75,7 @@ pub trait Global: Send + Sync + 'static {
/// Builds the tokio runtime for the application.
#[inline(always)]
fn tokio_runtime() -> tokio::runtime::Runtime {
default_runtime()
default_runtime_builder().build().expect("runtime build")
}

/// Called before loading the config.
Expand Down Expand Up @@ -118,7 +118,7 @@ pub trait Global: Send + Sync + 'static {
pub trait GlobalWithoutConfig: Send + Sync + 'static {
#[inline(always)]
fn tokio_runtime() -> tokio::runtime::Runtime {
default_runtime()
default_runtime_builder().build().expect("runtime build")
}

/// Initialize the global.
Expand Down Expand Up @@ -157,10 +157,7 @@ impl<T: GlobalWithoutConfig> Global for T {

#[inline(always)]
fn tokio_runtime() -> tokio::runtime::Runtime {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.expect("runtime build")
<T as GlobalWithoutConfig>::tokio_runtime()
}

#[inline(always)]
Expand Down Expand Up @@ -190,3 +187,70 @@ impl<T: GlobalWithoutConfig> Global for T {
<T as GlobalWithoutConfig>::on_exit(self, result)
}
}

#[cfg(test)]
#[cfg_attr(all(test, coverage_nightly), coverage(off))]
mod tests {
use std::sync::Arc;
use std::thread;

use super::{Global, GlobalWithoutConfig};
use crate::EmptyConfig;

struct TestGlobal;

impl Global for TestGlobal {
type Config = ();

async fn init(_config: Self::Config) -> anyhow::Result<std::sync::Arc<Self>> {
Ok(Arc::new(Self))
}
}

#[tokio::test]
async fn default_global() {
thread::spawn(|| {
// To get the coverage
TestGlobal::tokio_runtime();
});

assert!(matches!(TestGlobal::pre_init(), Ok(())));
let global = TestGlobal::init(()).await.unwrap();
assert!(matches!(global.on_services_start().await, Ok(())));

assert!(matches!(global.on_exit(Ok(())).await, Ok(())));
assert!(global.on_exit(Err(anyhow::anyhow!("error"))).await.is_err());

assert!(matches!(global.on_service_exit("test", Ok(())).await, Ok(())));
assert!(global.on_service_exit("test", Err(anyhow::anyhow!("error"))).await.is_err());
}

struct TestGlobalWithoutConfig;

impl GlobalWithoutConfig for TestGlobalWithoutConfig {
async fn init() -> anyhow::Result<std::sync::Arc<Self>> {
Ok(Arc::new(Self))
}
}

#[tokio::test]
async fn default_global_no_config() {
thread::spawn(|| {
// To get the coverage
<TestGlobalWithoutConfig as Global>::tokio_runtime();
});

assert!(matches!(TestGlobalWithoutConfig::pre_init(), Ok(())));
<TestGlobalWithoutConfig as Global>::init(EmptyConfig).await.unwrap();
let global = <TestGlobalWithoutConfig as GlobalWithoutConfig>::init().await.unwrap();
assert!(matches!(Global::on_services_start(&global).await, Ok(())));

assert!(matches!(Global::on_exit(&global, Ok(())).await, Ok(())));
assert!(Global::on_exit(&global, Err(anyhow::anyhow!("error"))).await.is_err());

assert!(matches!(Global::on_service_exit(&global, "test", Ok(())).await, Ok(())));
assert!(Global::on_service_exit(&global, "test", Err(anyhow::anyhow!("error")))
.await
.is_err());
}
}
2 changes: 2 additions & 0 deletions crates/bootstrap/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![cfg_attr(all(coverage_nightly, test), feature(coverage_attribute))]

pub mod config;
pub mod global;
pub mod service;
Expand Down
59 changes: 58 additions & 1 deletion crates/bootstrap/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ pub trait Service<Global>: Send + Sync + 'static + Sized {
None
}

/// Initialize the service
/// Initialize the service and return `Ok(true)` if the service should be
/// run.
fn enabled(&self, global: &Arc<Global>) -> impl std::future::Future<Output = anyhow::Result<bool>> + Send {
let _ = global;
std::future::ready(Ok(true))
Expand Down Expand Up @@ -67,3 +68,59 @@ where
Poll::Ready((this.name, res))
}
}

#[cfg(test)]
#[cfg_attr(all(test, coverage_nightly), coverage(off))]
mod tests {
use std::sync::Arc;

use scuffle_future_ext::FutureExt;

use super::{NamedFuture, Service};

struct DefaultService;

impl Service<()> for DefaultService {}

#[tokio::test]
async fn defaukt_service() {
let svc = DefaultService;
let global = Arc::new(());
let (ctx, handler) = scuffle_context::Context::new();

assert_eq!(svc.name(), None);
assert!(svc.enabled(&global).await.unwrap());

handler.cancel();

assert!(matches!(svc.run(global, ctx).await, Ok(())));

assert!(handler
.shutdown()
.with_timeout(tokio::time::Duration::from_millis(200))
.await
.is_ok());
}

#[tokio::test]
async fn future_service() {
let (ctx, handler) = scuffle_context::Context::new();
let global = Arc::new(());

let fut_fn = |_global: Arc<()>, _ctx: scuffle_context::Context| async { anyhow::Result::<()>::Ok(()) };
assert!(fut_fn.run(global, ctx).await.is_ok());

handler.cancel();
assert!(handler
.shutdown()
.with_timeout(tokio::time::Duration::from_millis(200))
.await
.is_ok());
}

#[tokio::test]
async fn named_future() {
let named_fut = NamedFuture::new("test", async { 42 });
assert_eq!(named_fut.await, ("test", 42));
}
}

0 comments on commit 91fd95e

Please sign in to comment.