rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
97.01k stars 12.54k forks source link

Missing documentation/feature - changing global_allocator in cargo test #81953

Open Firstyear opened 3 years ago

Firstyear commented 3 years ago

Hi,

From https://github.com/rust-lang/rust/blob/master/library/core/src/alloc/global.rs#L5 this mentions how to use a different global allocator in the main of a binary. It would be beneficial to be able to use the same allocator in tests of that binary, or associated libraries and modules.

Can this documentation be extended to demonstrate how cargo test can use an alternate allocator? Alternately if this isn't possible today, can this be a feature request to allow the allocator to be changed with cargo test?

Thanks,

ghost commented 3 years ago

Yeah I was also looking for the actual same thing.

ehuss commented 3 years ago

Can you clarify why it doesn't seem the allocator is not used in your test? If you place a #[test] function in main.rs, and run cargo test, that test should use the global allocator defined in main.rs.

If you have a lib.rs, then you can move the #[global_allocator] to the lib.rs, and all Cargo tests (and binaries) should inherit that. The allocator needs to be defined once (and only once) somewhere in the dependency graph, and where it goes depends on what you are doing.

Generally the std docs don't discuss Cargo directly, since the docs are somewhat agnostic to the build tool (and generally that level of detail belongs to guide-style material).

Firstyear commented 3 years ago

@ehuss I think what I'm asking is that that behaviour should be explicitly documented in the global allocator trait page as today it's ambiguous to how you use a custom allocator in tests. Alternately, it could be added to https://doc.rust-lang.org/edition-guide/rust-2018/platform-and-target-support/global-allocators.html