Fix race condition in init config tests #261
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
In the
init::config::testsmodule, the usage ofstd::env::set_varandstd::env::remove_varcan cause a race condition which can occasionally fail thecargo testinvocation.This happens when 2 tests using the
EnvManagertype are running in parallel in different threads of the test binary.You can verify that on any Linux system by running (e.g.):
cargo test test_get_multi_exporter_config_datadog_ -- --test-threads 3By selecting those 3 datadog tests that use the
EnvManagerand ensuring parallelism on 3 threads, you should be able to reproduce the race condition 100% of the time. Note that without the--test-threads 3argument, you should also run multi-threaded unless you have a single core. Also note that even when simply runningcargo testto run all tests, the race condition will happen occasionally out of bad luck (that's how I found the problem).Solution
I introduced a static
Mutex<()>in theEnvManager. When callingEnvManager::new(), the Mutex guard becomes part of the EnvManager struct, ensuring only one EnvManager can exist at a time among the threads of the test binary. Essentially, it guarantees that tests using theEnvManagerare run sequentially and do not interfere with each other.