Create containers per test or as a static global?
Closed this issue · 3 comments
Kind of related to my previous issue here #727 (comment)
When I use testcontainers
and create a new container for every tests, I often run into some issue where some of the containers aren't successfully created (maybe a race condition). So then my instinct told me to create a static global container with something like this for the test module:
// Static variables for Redis container and URL
static REDIS_CONTAINER: OnceCell<ContainerAsync<GenericImage>> = OnceCell::const_new();
static REDIS_URL: OnceCell<String> = OnceCell::const_new();
// Function to initialize and get the Redis container
async fn get_redis() -> &'static ContainerAsync<GenericImage> {
REDIS_CONTAINER
.get_or_init(|| async {
GenericImage::new("redis", "7.4")
.with_exposed_port(6379.tcp())
.start()
.await
.expect("Redis test container failed to start")
})
.await
}
// Function to get the Redis URL
async fn get_redis_url() -> &'static str {
REDIS_URL
.get_or_init(|| async {
let container = get_redis().await;
let host_port = container
.get_host_port_ipv4(6379)
.await
.expect("Failed to get host port");
format!("redis://127.0.0.1:{}", host_port)
})
.await
}
This worked for a while but I soon realized that the clean up of these containers often fail. That is, I'm often left with something like this after a bit of development:
So far I have the watchdog
feature enabled but this is still happening. I guess my question is, what's the recommended approach here? Is there one or is this a current limitation?
Hi there 👋
Sorry, but this is duplicate of #707 (and proper solution requires #577).
In #707 you can find some workaround how to achieve this even right now, for example: #707 (comment)
Closing due to this
@DDtKey Maybe I should rename the issue, but I dont think the suggested workaround in #707 (comment) is any different from what I have above?
I guess I'm not asking for "how to create a single global container", the problem I'm experiencing is that the containers still aren't shut down properly...? I have the watchdog
feature enabled.
but I dont think the suggested workaround in #707 (comment) is any different from what I have above?
They are different, take a look at the Weak
+ Arc
usage there
Anyway, that's a workaround and the issue itself is duplicate - ability to use static containers without tricks.
And issue of shutdown/clean-up is main one, please check the conversations there.
That's how Rust's drop works. It's not called for static variables. So the trick with Weak works if you have parallel tests
watchdog
in general only monitors OS signals