smol-rs / smol-macros

Macros for using smol-rs
Apache License 2.0
7 stars 2 forks source link

Support tests that return `Result<T, E>` #6

Open ThatGeoGuy opened 7 months ago

ThatGeoGuy commented 7 months ago

First off: thanks for the crate, it makes getting started writing tests pretty easy to work with.

In regular (standard, not async) Rust we can do:

#[cfg(test)]
mod tests {
    use super::*;
    use std::error::Error;

    #[test]
    fn it_works() -> Result<(), Box<dyn Error>> {
        let _ = f32::try_from(20usize)?;
        Ok(())
    }
}

However, the test! macro doesn't support this form at all, and assumes that all tests return ().

This means that we can't write:

#[cfg(test)]
mod tests {
    use super::*;
    macro_rules_attribute::apply;
    use std::error::Error;

    #[apply(smol_macros::test!]
    async fn it_works(_ex: &Executor<'_>) -> Result<(), Box<dyn Error>> {
        let _ = f32::try_from(20usize)?;
        Ok(())
    }
}

The current workaround to this is to just .unwrap or .expect all Result types in the function. Materially, they don't really change the logic of the test (since a panic means failure), but it is often nice to be able to write the code with ? and FromResidual only because the tests can often serve as an example for how code should be written in practice.

Thoughts? Would the current macro be able to be reworked so that the return type for a test can be set as well?

notgull commented 1 day ago

I would accept a PR for this.

notgull commented 1 day ago

I submitted #6 to test this issue. However, it looks like tests that return Result already work?

#[apply(test!)]
async fn it_works(_ex: &Executor<'_>) -> Result<(), Box<dyn std::error::Error>> {
    let _ = u32::try_from(20usize)?;
    Ok(())
}