Skip to content

Commit c9e2871

Browse files
committed
Add #[starlang::test] attribute macro
Provides a test macro that automatically initializes the Starlang runtime, similar to how #[starlang::main] works for applications. Use as: #[starlang::test] async fn test_foo() { // starlang::init() already called }
1 parent 14516f6 commit c9e2871

2 files changed

Lines changed: 40 additions & 1 deletion

File tree

crates/starlang-macros/src/lib.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,3 +183,42 @@ pub fn main(_attr: TokenStream, item: TokenStream) -> TokenStream {
183183

184184
TokenStream::from(expanded)
185185
}
186+
187+
/// Test attribute macro that sets up the Starlang runtime for tests.
188+
///
189+
/// This macro wraps a test function with tokio's async runtime and
190+
/// initializes the global Starlang runtime before running the test body.
191+
///
192+
/// # Example
193+
///
194+
/// ```ignore
195+
/// use starlang::prelude::*;
196+
///
197+
/// #[starlang::test]
198+
/// async fn test_spawn_process() {
199+
/// let pid = starlang::spawn(|_ctx| async move {
200+
/// // Process logic
201+
/// });
202+
/// assert!(starlang::alive(pid));
203+
/// }
204+
/// ```
205+
#[proc_macro_attribute]
206+
pub fn test(_attr: TokenStream, item: TokenStream) -> TokenStream {
207+
let input = parse_macro_input!(item as ItemFn);
208+
209+
let fn_name = &input.sig.ident;
210+
let fn_block = &input.block;
211+
let fn_vis = &input.vis;
212+
let fn_attrs = &input.attrs;
213+
214+
let expanded = quote! {
215+
#[::tokio::test]
216+
#(#fn_attrs)*
217+
#fn_vis async fn #fn_name() {
218+
::starlang::init();
219+
#fn_block
220+
}
221+
};
222+
223+
TokenStream::from(expanded)
224+
}

crates/starlang/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ pub use process::{Runtime, RuntimeHandle};
195195
pub use runtime::Context;
196196

197197
// Re-export macros (from separate proc-macro crate)
198-
pub use starlang_macros::{GenServerImpl, main, self_pid, starlang_process};
198+
pub use starlang_macros::{GenServerImpl, main, self_pid, starlang_process, test};
199199

200200
/// Prelude module for convenient imports.
201201
///

0 commit comments

Comments
 (0)