1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-06-26 23:17:42 +02:00

add test runtime macro (#2409)

This commit is contained in:
Rob Ede
2021-10-19 17:30:32 +01:00
committed by GitHub
parent ad22cc4e7f
commit 591abc37c3
19 changed files with 94 additions and 43 deletions

View File

@ -59,6 +59,7 @@
#![recursion_limit = "512"]
use proc_macro::TokenStream;
use quote::quote;
mod route;
@ -157,24 +158,41 @@ method_macro! {
}
/// Marks async main function as the actix system entry-point.
///
/// # Actix Web Re-export
/// This macro can be applied with `#[actix_web::main]` when used in Actix Web applications.
///
/// # Examples
/// ```
/// #[actix_web_codegen::main]
/// #[actix_web::main]
/// async fn main() {
/// async { println!("Hello world"); }.await
/// }
/// ```
#[proc_macro_attribute]
pub fn main(_: TokenStream, item: TokenStream) -> TokenStream {
use quote::quote;
let input = syn::parse_macro_input!(item as syn::ItemFn);
(quote! {
#[actix_web::rt::main(system = "::actix_web::rt::System")]
#input
let mut output: TokenStream = (quote! {
#[::actix_web::rt::main(system = "::actix_web::rt::System")]
})
.into()
.into();
output.extend(item);
output
}
/// Marks async test functions to use the actix system entry-point.
///
/// # Examples
/// ```
/// #[actix_web::test]
/// async fn test() {
/// assert_eq!(async { "Hello world" }.await, "Hello world");
/// }
/// ```
#[proc_macro_attribute]
pub fn test(_: TokenStream, item: TokenStream) -> TokenStream {
let mut output: TokenStream = (quote! {
#[::actix_web::rt::test(system = "::actix_web::rt::System")]
})
.into();
output.extend(item);
output
}

View File

@ -220,7 +220,7 @@ fn guess_resource_type(typ: &syn::Type) -> ResourceType {
impl Route {
pub fn new(
args: AttributeArgs,
input: TokenStream,
ast: syn::ItemFn,
method: Option<MethodType>,
) -> syn::Result<Self> {
if args.is_empty() {
@ -234,14 +234,11 @@ impl Route {
),
));
}
let ast: syn::ItemFn = syn::parse(input)?;
let name = ast.sig.ident.clone();
// Try and pull out the doc comments so that we can reapply them to the
// generated struct.
//
// Note that multi line doc comments are converted to multiple doc
// attributes.
// Try and pull out the doc comments so that we can reapply them to the generated struct.
// Note that multi line doc comments are converted to multiple doc attributes.
let doc_attributes = ast
.attrs
.iter()
@ -349,9 +346,16 @@ pub(crate) fn with_method(
input: TokenStream,
) -> TokenStream {
let args = parse_macro_input!(args as syn::AttributeArgs);
match Route::new(args, input.clone(), method) {
let ast = match syn::parse::<syn::ItemFn>(input.clone()) {
Ok(ast) => ast,
// on parse error, make IDEs happy; see fn docs
Err(err) => return input_and_compile_error(input, err),
};
match Route::new(args, ast, method) {
Ok(route) => route.into_token_stream().into(),
// on parse err, make IDEs happy; see fn docs
// on macro related error, make IDEs happy; see fn docs
Err(err) => input_and_compile_error(input, err),
}
}