Can I write tests for invalid lifetimes?

I am writing Rust code that manipulates raw pointers. These source pointers are then exposed to users through structures that use ContravariantLifetime to associate the lifetime of the structure with my object.

I would like to write tests that confirm that user-oriented structures cannot live longer than my object. I have code like:

fn element_cannot_outlive_parts() { let mut z = { let p = Package::new(); p.create() // returns an object that cannot live longer than p }; } 

This does not compile, which is what I want. However, I would like to have an automatic check that this behavior is true even after any refactoring that I do with the code.

My best idea at the moment is to write one-time Rust files with this code and tweak the bash scripts to try to compile them and find specific error messages that all look pretty hacky.

+5
source share
2 answers

The Rust project has a special set of tests called compile-fail that do exactly what you want.

compiletest crate is an extraction of this idea that allows other libraries to do the same:

 fn main() { let x: (u64, bool) = (true, 42u64); //~^ ERROR mismatched types //~^^ ERROR mismatched types } 

One of the ideas that appears halfway is to use the Cargo features.

Define tests using the function flag:

 #[test] #[cfg(feature = "compile_failure")] fn bogus_test() {} 

Add this to Cargo.toml:

 [features] compile_failure = [] 

And run the tests like

 cargo test --features compile_failure 

The obvious thing missing from this is the automatic check "if it was a correct mistake." If nothing else, this allows me to have tests that half live in my code base.

+1
source

You can annotate the test, the expected failure.

 #[should_fail] 

So you can write a test that tries to break the lifetime it should have, and thus fail, which would actually be a pass.

An example of a test for an "index beyond borders" see below (pulled from the Rust guide )

 #[test] #[should_fail] fn test_out_of_bounds_failure() { let v: &[int] = []; v[0]; } 

I believe that this example would be a compilation error, so it would be reasonable that the error of your compilation violation of the lifespan would also be caught by this.

-2
source

Source: https://habr.com/ru/post/1205904/


All Articles