5

Is there a way, apart from manual code review, to guarantee assert!() and panic!() calls intended for test code not accidentally gets built for the chain runtime.

4 Answers 4

6

And yeah debug_assert! might also be worth keeping in mind. However, you can also do something like:

macro_rules! test_only_assert {
    ($cond:expr $(,)?) => {{
        #[cfg(test)]
        assert!($cond)
    }};
}

// Now you can do like:
fn runtime_function() {
    test_only_assert!(..)
}

And similar for panic too. It will make sure that test will be run even when running with release profile. Eg: cargo test --all --release and wont be included if binary is in debug but not in test.

2

Besides the mentioned debug_assert! there is nothing provided by Rust out of the box. However, you could write your own maybe-assert crate or whatever you want to call it.

You would by default export a macro maybe_assert! with the same semantics as assert!, aka you just forward all the arguments to assert!. The trick would be to introduce some feature do-not-assert or something similar to your maybe_assert crate. Then you would enable this do-not-assert feature for your runtime when you build a release that should be put on chain.

2

One way of achieving what you ask for is to enclose every assert! statement in a #cfg[test]

#cfg[test]
assert!(...)
2
  • because the code will be less readable and the programmers will forget.
    – Simson
    Jul 26, 2022 at 8:57
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Jul 26, 2022 at 10:56
1

I think you are looking for debug_assert!(). It is built into debug builds but not release builds

May not directly answer your question, but could be useful

1
  • Could be, it should assert when we run cargo test but not break the runtime
    – Simson
    Jul 25, 2022 at 0:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.