You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
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 ?.
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.
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.
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
? 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
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"));
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.
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
which could then be used to wrap tests to both use the ? and panic as follows
#[test_panic_on_err]fnmy_test() -> Result<(),Box<dyn std::error::Error>>{let val:Option<i32> = None;let _ = val.ok_or("Expected Some but got None")?;// Will panic on failureOk(())}
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.
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
Activity
DanGould commentedon Jan 16, 2025
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 ?
arminsabouri commentedon Jan 16, 2025
Perhaps AnyHow Results could work better in test function signatures. If nothing else the code is more digestable as it replaces all
expects(...)andunwraps()with?.DanGould commentedon Jan 16, 2025
Anyhow does make error handling neat, which is why our
payjoin-cliandpayjoin-directoryapps use them as reference.For the most fundamental docstring tests where Rust API guidelines suggest
.unwrap()is inappropriate, I'm inclined to thinkanyhowsuffers 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
anyhowfor ourpayjoin-cliandpayjoin-directorytests 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 aBox<dyn Error>because both&strandStringimplinto()Box<std::error::Error + Send + Sync>, which seems more appropriate for those fundamental contexts.spacebear21 commentedon Jan 16, 2025
If the goal is simply to make cleaner examples that can be copied from our tests, this approach sounds like the best:
We can also expose those generic Error/Result types in test_utils to use throughout the codebase and make it available for bindings.
Remove unwrap() in integration/e2e tests (#512)
feat: removed `unwrap` from v2 of send and recieve (#544)
spacebear21 commentedon Mar 7, 2025
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.nothingmuch commentedon Mar 7, 2025
Hmm, I assumed that was intentional, i.e.
?for boilerplate stuff that might be used as an example, andexpectfor 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 messagespacebear21 commentedon Mar 7, 2025
This seems like the correct approach.
Yeah let's strive to correct this.
benalleng commentedon Mar 7, 2025
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:
vs.
Anunayj commentedon Mar 7, 2025
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 topanic!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.
DanGould commentedon Mar 8, 2025
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.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,expectmakes 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
?asunwrap(), but that'd be a mess and we should just be pragmaticwhich could then be used to wrap tests to both use the
?and panic as followsDanGould commentedon Mar 8, 2025
That was all to ignore the critical aesthetic consideration that
?is more beautiful than.unwrap()everywhere.Add additional tests for v2 send module (#554)
Add additional tests for v1 send module (#556)
nothingmuch commentedon Mar 17, 2025
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.
DanGould commentedon Mar 17, 2025
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:
assert!Remove unwrap() in integration/e2e tests (#512)