async_std_test/lib.rs
1/*
2 * lib.rs
3 *
4 * async-std-test - Alternate implementation of the async-std test macro
5 * Copyright (c) 2022 Ammon Smith
6 *
7 * async-std-test is available free of charge under the terms of the MIT
8 * License. You are free to redistribute and/or modify it under those
9 * terms. It is distributed in the hopes that it will be useful, but
10 * WITHOUT ANY WARRANTY. See the LICENSE file for more details.
11 *
12 */
13
14#![forbid(unsafe_code, future_incompatible)]
15#![deny(missing_debug_implementations, nonstandard_style)]
16
17//! An alternate method of running `async fn` tests. Meant for use with [`async-std`].
18//!
19//! The only export in this crate is a procedural macro, [`async_test`].
20//! It can be invoked as follows:
21//!
22//! ```ignore
23//! #[async_test]
24//! async fn my_test() -> std::io::Result<()> {
25//! assert_eq!(2 * 2, 4);
26//! Ok(())
27//! }
28//! ```
29//!
30//! [`async-std`]: https://docs.rs/async-std
31//! [`async_test`]: ./attr.async_test.html
32
33use proc_macro::TokenStream;
34use quote::{quote, quote_spanned};
35use syn::spanned::Spanned;
36
37/// Enables this test to be run in an `async fn`.
38///
39/// Requires that the test return [`Result`] with the error
40/// type implementing [`Display`].
41///
42/// # Examples
43///
44/// ```ignore
45/// #[async_test]
46/// async fn my_test() -> std::io::Result<()> {
47/// assert_eq!(2 * 2, 4);
48/// Ok(())
49/// }
50/// ```
51///
52/// [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
53/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
54#[proc_macro_attribute]
55pub fn async_test(_attr: TokenStream, item: TokenStream) -> TokenStream {
56 let input = syn::parse_macro_input!(item as syn::ItemFn);
57
58 let ret = &input.sig.output;
59 let name = &input.sig.ident;
60 let body = &input.block;
61 let attrs = &input.attrs;
62 let vis = &input.vis;
63
64 if input.sig.asyncness.is_none() {
65 return TokenStream::from(quote_spanned! { input.span() =>
66 compile_error!("the async keyword is missing from the function declaration"),
67 });
68 }
69
70 let result = quote! {
71 #[::core::prelude::v1::test]
72 #(#attrs)*
73 #vis fn #name() {
74 async fn test_inner() #ret {
75 #body
76 }
77
78 async_std::task::block_on(async {
79 if let Err(error) = test_inner().await {
80 panic!("Error in test: {}", error);
81 }
82 })
83 }
84 };
85
86 result.into()
87}