1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
//! [![crates.io version](https://img.shields.io/crates/v/safina-async-test.svg)](https://crates.io/crates/safina-async-test)
//! [![license: Apache 2.0](https://gitlab.com/leonhard-llc/safina-rs/-/raw/main/license-apache-2.0.svg)](http://www.apache.org/licenses/LICENSE-2.0)
//! [![unsafe forbidden](https://gitlab.com/leonhard-llc/safina-rs/-/raw/main/unsafe-forbidden-success.svg)](https://github.com/rust-secure-code/safety-dance/)
//! [![pipeline status](https://gitlab.com/leonhard-llc/safina-rs/badges/main/pipeline.svg)](https://gitlab.com/leonhard-llc/safina-rs/-/pipelines)
//!
//! A macro for running `async fn` tests.
//!
//! It is part of [`safina`](https://crates.io/crates/safina), a safe async runtime.
//!
//! Runs tests with [`safina_executor::block_on`](https://docs.rs/safina-executor/latest/safina_executor/fn.block_on.html).
//!
//! # Features
//! - `forbid(unsafe_code)`
//! - Straightforward implementation
//!
//! # Limitations
//! - Requires Rust `nightly` because safina-executor does
//!
//! # Examples
//! ```rust
//! use safina_async_test::async_test;
//! # async fn an_async_fn() -> Result<(), std::io::Error> { Ok(()) }
//! #[async_test]
//! async fn test1() {
//!     an_async_fn().await.unwrap();
//! }
//! ```
//!
//! ```rust
//! use safina_async_test::async_test;
//! # async fn background_task() {}
//! # async fn do_request() -> Result<u8, std::io::Error> { Ok(42) }
//! #[async_test]
//! async fn test2() {
//!     safina_executor::increase_threads_to(1);
//!     safina_executor::spawn(background_task());
//!     assert_eq!(42, do_request().await.unwrap());
//! }
//! ```
//!
//! # Documentation
//! https://docs.rs/safina-async-test
//!
//! # Alternatives
//! - [`async_std::test`](https://docs.rs/async-std/latest/async_std/attr.test.html)
//! - [`futures_await_test::async_test`](https://docs.rs/futures-await-test/0.3.0/futures_await_test/)
//! - [`tokio::test`](https://docs.rs/tokio/latest/tokio/attr.test.html)
//!
//! # Changelog
//! - v0.1.4 - Upgrade to new safina-executor version which removes need for `Box::pin`.
//! - v0.1.3 - Add badges to readme.  Rename `safina` package to `safina-executor`.
//! - v0.1.2 - Update docs
//! - v0.1.1 - First published version
//!
//! # TO DO
//! - DONE - Implement as declarative macro.  UX is bad.
//! - DONE - Implement as procedural macro.
//! - DONE - Report errors nicely
//! - DONE - Publish on crates.io
//! - Let users depend only on safina-async-test:
//!   1. Move proc macro to its own crate.
//!   1. Make safina_async_test re-export the macro and safina_executor::block_on.
//!   1. Change the macro to call safina_async_test::block_on.
//!
//! # Release Process
//! 1. Edit `Cargo.toml` and bump version number.
//! 1. Run `./release.sh`
#![forbid(unsafe_code)]

use proc_macro;
use proc_macro2::{Ident, TokenStream, TokenTree};
use quote::quote_spanned;
//pub use safina_executor::block_on;

#[proc_macro_attribute]
pub fn async_test(
    attr: proc_macro::TokenStream,
    item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
    let mut result = proc_macro::TokenStream::from(impl_async_test(
        proc_macro2::TokenStream::from(attr.clone()),
        proc_macro2::TokenStream::from(item.clone()),
    ));
    result.extend(item);

    // let mut token_stream_string = String::new();
    // for tree in result {
    //     token_stream_string.push_str(format!("tree: {:?}\n", tree).as_str());
    // }
    // panic!("TokenStream:\n{}", token_stream_string);

    result
}

fn impl_async_test(attr: TokenStream, item: TokenStream) -> TokenStream {
    for tree in attr {
        return quote_spanned!(tree.span()=>compile_error!("parameters not allowed"););
    }
    // Ident { ident: "async", span: #0 bytes(50..55) }
    // Ident { ident: "fn", span: #0 bytes(56..58) }
    // Ident { ident: "should_run_async_fn", span: #0 bytes(59..78) }
    // Group { delimiter: Parenthesis, stream: TokenStream [], span: ...
    // Group { delimiter: Brace, stream: TokenStream [Ident { ident: "println",...
    let mut iter = item.into_iter();
    let first = iter.next();
    if let (
        Some(TokenTree::Ident(ref ident_async)),
        Some(TokenTree::Ident(ref ident_fn)),
        Some(TokenTree::Ident(ref ident_name)),
    ) = (&first, iter.next(), iter.next())
    {
        if ident_async.to_string() == "async" && ident_fn.to_string() == "fn" {
            let async_name = ident_name.to_string() + "_";
            let ident_async_name = Ident::new(&async_name, ident_name.span());
            return quote_spanned!(ident_name.span()=>
                #[test]
                pub fn #ident_async_name () {
                    safina_executor::block_on( #ident_name ())
                }
            );
        }
    }
    if let Some(tree) = first {
        return quote_spanned!(tree.span()=>compile_error!("expected async fn"););
    } else {
        panic!("expected async fn");
    }
}

// The version below has two drawbacks:
// 1. IDEs don't know that the stuff inside `async_test! { async fn test1() { ... } }` is a
//    function, so they don't provide formatting, auto-complete, or other useful editor functions.
//    This is a fatal flaw.
// 2. It puts the test in a module with the same name as the test function,
//    and a test function named `async_test`.
//    So for `async_test! { async fn test1() {...} }` below, it makes
//    `mod test1 { #[test] fn async_test() {...} }`.
//    This makes IDE test output more verbose.  Each test appears as its own category.
//
// macro_rules! async_test {
//     (async fn $name:ident () $body:block) => {
//         async fn $name() $body
//
//         mod $name {
//             #[test]
//             fn async_test () {
//                 safina_executor::block_on(super::$name())
//             }
//         }
//     }
// }
//
// async_test! {
// async fn test1() {
//     println!("test1");
// }
// }

// The version below requires the user to keep the two names in sync.
// Also, the error messages are not great.
//
// macro_rules! async_test {
//     ($name:ident) => {
//         mod $name {
//             #[test]
//             fn async_test () {
//                 safina_executor::block_on(super::$name())
//             }
//         }
//     }
// }
//
// async_test!(test1);
// async fn test1() {
//     println!("test1");
// }
//
// async_test!(test1); // error[E0428]: the name `test1` is defined multiple times
// async fn test2() {
//     println!("test2");
// }
//
// async_test!(test3); // error[E0423]: expected function, found module `super::test3`
// async fn test4() {
//     println!("test4");
// }