Skip to content

Remove .unwrap(), even in Tests #487

Closed as not planned
Closed as not planned

Description

@DanGould

Rust API Guidelines recommend this. It makes for cleaner examples and demonstrates best practice in cases where people copy our code.

I propose all new PRs follow this guideline and we slowly pay back the tech debt of unwrap() in tests.

Activity

  1. DanGould commented on Jan 16, 2025

    @DanGould
    MemberAuthor

    Hmm I realized shortly after posting that the API Guidelines are talking about docstring examples or explicit examples, not tests. I still think it's a good idea, but maybe not critical? I also think bubbling up errors is usually not too tricky if the test's signature returns Result<_, Box<dyn std::error::Error>> unless the functions return some funkiness that's not std.

    What do you think @spacebear21 ?

  2. arminsabouri commented on Jan 16, 2025

    @arminsabouri
    Contributor

    Perhaps AnyHow Results could work better in test function signatures. If nothing else the code is more digestable as it replaces all expects(...) and unwraps() with ?.

  3. DanGould commented on Jan 16, 2025

    @DanGould
    MemberAuthor

    Anyhow does make error handling neat, which is why our payjoin-cli and payjoin-directory apps use them as reference.

    For the most fundamental docstring tests where Rust API guidelines suggest .unwrap() is inappropriate, I'm inclined to think anyhow suffers from another problem. Instead of being incomplete, like .unwrap(), the example stops being fundamental since it introduces an additional dependency.

    For this reason I'm sold on anyhow for our payjoin-cli and payjoin-directory tests and examples where our goal is to demonstrate a neat and sufficiently convenient reference, but I'm not convinced we want to introduce that dependency for our most fundamental tests. .map_err(|e| format!("An error happened in this context: {e}")? will propagate a Box<dyn Error> because both &str and String impl into() Box<std::error::Error + Send + Sync>, which seems more appropriate for those fundamental contexts.

  4. spacebear21 commented on Jan 16, 2025

    @spacebear21
    Collaborator

    If the goal is simply to make cleaner examples that can be copied from our tests, this approach sounds like the best:

    bubbling up errors is usually not too tricky if the test's signature returns Result<_, Box>

    We can also expose those generic Error/Result types in test_utils to use throughout the codebase and make it available for bindings.

  5. added this to the payjoin-0.23 milestone on Jan 20, 2025
  6. added
    good first issue
    on Jan 21, 2025
  7. spacebear21 commented on Mar 7, 2025

    @spacebear21
    Collaborator

    Can't believe I didn't notice this earlier, but @Anunayj brought up a good point in #556 (comment) that ? does not unwind the stack when tests fail (e.g. showing the exact line that error-ed).

    I prefer the readability of ? but this is a trade-off worth considering.

  8. nothingmuch commented on Mar 7, 2025

    @nothingmuch
    Contributor

    I prefer the readability of ? but this is a trade-off worth considering.

    Hmm, I assumed that was intentional, i.e. ? for boilerplate stuff that might be used as an example, and expect for test assertions or within helper functions whose type implies they are infallible.

    FWIW, only kind of related, I was always kind of surprised the norm for using assert! in tests was also without an explanatory message

  9. spacebear21 commented on Mar 7, 2025

    @spacebear21
    Collaborator

    ? for boilerplate stuff that might be used as an example, and expect for test assertions or within helper functions whose type implies they are infallible.

    This seems like the correct approach.

    I was always kind of surprised the norm for using assert! in tests was also without an explanatory message

    Yeah let's strive to correct this.

  10. benalleng commented on Mar 7, 2025

    @benalleng
    Collaborator

    i.e. ? for boilerplate stuff that might be used as an example

    Would it likely still be better to try and avoid using ? in favor of just creating an infallible helper in most cases since these are just boilerplate anyways?

    An example:

    let original_psbt = Psbt::from_str(ORIGINAL_PSBT)?;
    

    vs.

    // a suggestion from spacebear
    static PARSED_ORIGINAL_PSBT: Lazy<Psbt> =
            Lazy::new(|| Psbt::from_str(ORIGINAL_PSBT).expect("known psbt should parse"));
    
  11. Anunayj commented on Mar 7, 2025

    @Anunayj

    I'd also add that the rust book softly recommends to panic! in tests, and clearly the rust tests were designed with panicking in case of failure. assert! is designed to panic! for the same reason.

    I do understand sometimes people do use test cases as examples, and often verbatim copy and paste this in their code, I do not think that is the problem we should be solving (except in explicit examples). I think test cases primarily should enhance the developer experience, when one of the tests fail, I wanna know exactly why something failed in the stacktrace, instead of being given a opaque error.

  12. DanGould commented on Mar 8, 2025

    @DanGould
    MemberAuthor

    Some of our tests involve darn complicated setup and many potential sources of errors. I suppose my OP citing Rust API guidelines is somewhat short sighted in that the tests are not the public API.

    Where exactly is the suggestion to prefer to panic in tests in the rust book? I do read "If a method call fails in a test, you’d want the whole test to fail, even if that method isn’t the functionality under test. Because panic! is how a test is marked as a failure, calling unwrap or expect is exactly what should happen." but that's only the default when tests don't return a Result. The rust book also mentions first-class support for ? in tests for convenience, which I prefer in most of our cases.

    ? for boilerplate stuff that might be used as an example, and expect for test assertions or within helper functions whose type implies they are infallible.

    This approach seems like the right one to me. unwrap() is the worst of both worlds, it's ugly and provides no context. Where context is helpful, expect makes sense to me. Where we're dealing with boilerplate or helper functions, ? is less noisy.

    I'm very skeptical of using unwrap on boilerplate as suggested in this @Anunayj's comment because that seems less likely to fail than the behavior the test is trying to test.

    If we want to have even those errors propagated with ? panic to provide an unwind we can use a test-utils macro that gives us the best of both.

    edit: The following doesn't work, it's basically the same as current test behavior. Nothingmuch suggests you could use a proc macro to rewrite ? as unwrap(), but that'd be a mess and we should just be pragmatic

    #[proc_macro_attribute]
    pub fn test_panic_on_err(_attr: TokenStream, item: TokenStream) -> TokenStream {
        let input = parse_macro_input!(item as ItemFn);
        let fn_name = &input.sig.ident;
        let fn_body = &input.block;
    
        let output = quote! {
            #[test]
            fn #fn_name() {
                let result: Result<(), Box<dyn std::error::Error>> = (|| #fn_body)();
                if let Err(e) = result {
                    panic!("Test failed: {:?}", e); // Convert errors to panics
                }
            }
        };
    
        output.into()
    }

    which could then be used to wrap tests to both use the ? and panic as follows

    #[test_panic_on_err]
    fn my_test() -> Result<(), Box<dyn std::error::Error>> {
        let val: Option<i32> = None;
        let _ = val.ok_or("Expected Some but got None")?; // Will panic on failure
        Ok(())
    }
  13. DanGould commented on Mar 8, 2025

    @DanGould
    MemberAuthor

    That was all to ignore the critical aesthetic consideration that ? is more beautiful than .unwrap() everywhere.

  14. nothingmuch commented on Mar 17, 2025

    @nothingmuch
    Contributor

    Today I had another instance of when ? was more trouble than .unwrap(), v1_to_v2 was not fully up to date with new relay stuff, causing an error in the receiver's loop call to process_res (unexpected status). If it had .unwrap()ed at that point, i would have seen the error immediately, but instead it returned with ?. Since this loop runs in a separate task whose return value is only asserted later, the sender was meanwhile waiting for the response but as none was posted, eventually the directory's v1 compatibility responded with 503 service unavaiable, I was pretty confused until i roughly bisected the failure to the receiver's process by just adding panic!() and eventually realized what was going on and converted all ?'s in that block to .unwrap(), at which point the problem became apparent.

  15. DanGould commented on Mar 17, 2025

    @DanGould
    MemberAuthor

    Ok closing this because I have since learned the idea was misguided. .unwrap() is not necessarily tech debt.

    I do wonder to what extent the ?s we added to #512 would cause problems like the one above. Clearly ? everywhere can actually cause errors, and panics, though sometimes noisy, tend to be more appropriate in tests.

    Instead, let's follow some pragmatic practices:

    • use expect for test assertions or within helper functions whose type implies they are infallible.
    • use ? where it makes sense, in boilerplate that might be copied as an example where we wouldn't otherwise use assert!
    • prefer .expect() over .unwrap() in most cases, for context
    • don't rule out .unwrap() completely when .expect() is even noisier, prefer .unwrap() in nested tasks or otherwise deep callstacks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    good first issuetech debt

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions