Rust: Need way to run some code before any of unit tests

Created on 17 Aug 2016  路  5Comments  路  Source: rust-lang/rust

The details can be found logging while running cargo test.

The problem is in usage of rust log library,
to get it work you need call "initialization" code that provide implementation of log::Log trait
to logging macros.

So to get output from your code that tested by "cargo test" you need somehow call "logging_init" function, but as can I see at now there is no way to tell "cargo" run something before any tests.

Previously reported as cargo bug

A-libtest C-feature-request T-libs

Most helpful comment

I agree that setup and teardown for tests would be useful. This is going to need an RFC so let's track it under https://github.com/rust-lang/rfcs/issues/1664.

All 5 comments

You can call let _ = env_logger::init(); (it's safe to call this function multiple times, only the first call will count) at the top of each test but this is far from perfect.

Another workaround is to put the initialization code in a lazy static, and make sure to access said static at the beginning of every test (a macro can help). Then it will really only run once.

@durka If you're going to do that, you might as well just use sync::Once.

A similar, and even more difficult issue, is if you want to run teardown after all the tests have run.

I agree that setup and teardown for tests would be useful. This is going to need an RFC so let's track it under https://github.com/rust-lang/rfcs/issues/1664.

Was this page helpful?
0 / 5 - 0 ratings