Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a test assuring a compilation error?

I want to prove that my API statically prevents an invalid usage by failing to compile.

There is tooling for assuring that code panics at run-time (#[should_panic]), but I couldn't find anything for compilation failure. The doc tests seem most promising, because every snippet is a separate compilation unit, but panic check is all there seems to be.

like image 505
CodeSandwich Avatar asked Mar 24 '19 18:03

CodeSandwich


People also ask

How do you handle compilation errors?

Logic errors are best handled by meticulous program debugging. Compile-time errors rise at compile-time, before the execution of the program. Syntax error or missing file reference that prevents the program from successfully compiling is an example of this.

What is a compile test?

As an additional effort to measure the performance impact of the introduction of interception ability, we have measured the execution time for the Java compiler to translate the test program to Java bytecodes. The averaged execution times are presented in Table 5.

How do you identify a compilation error?

When you look at an error, the compiler or IDE shows you the line where it detects the error. But the error is not always on that line. For example, if you have omitted a semicolon on line 12 then the compiler might detect an error at line 13.


1 Answers

There isn't currently a way of indicating that a regular test should not compile. And by the look of related issues (#521 and #1994 ) something like #[compile_fail] is unlikely to become available any time soon.

However, there are two other ways to write these tests.

Doctests

Since Rust 1.22, you can make doc tests which are supposed to fail to compile, by labeling the code snippet with compile_fail:

/// Foos a bar.
/// 
/// # Example
///
/// ```compile_fail
/// foo(3); // 3 is not a bar
/// ```
fn foo(bar: Bar) {
}

Compile-test toolkit

The compile-test tools used internally by the Rust project were extracted into the dedicated crate compiletest_rs.

With the boilerplate suggested in the documentation, one can write compile-fail tests in the tests/compile-fail folder:

fn main() {
   let x: bool = 0;
}

See also:

  • Can I write tests for invalid lifetimes?

These tests should be written with care, nevertheless. Quoting from the announcement of the compile_fail feature:

Please note that these kinds of tests can be more fragile than others, as additions to Rust may cause code to compile when it previously would not.

like image 167
E_net4 stands with Ukraine Avatar answered Oct 28 '22 06:10

E_net4 stands with Ukraine