Rust – Is `Lazy::new` guaranteed to be called only once even when running tests in parallel?

Issue

This Content is from Stack Overflow. Question asked by cameron1024

I am testing some code that expects a postgres database with a particular set of data in the tables. I have a function that will connect to a database, ensure the data is correct, then return a connection. Once this data is set up, all the queries are read-only, so I’m not worrying about synchronizing the rest of the tests.

I’m worried about potential race conditions if this “ensure the database is correct” step is called twice at the same time.

I’ve wrapped this setup function in a once_cell::sync::Lazy, to try to guarantee that it is called only once per cargo test invocation, but I’m not sure this is actually guaranteeing what I think it is.

Note, this also includes doctests, which I understand are run with an entirely different model to regular unit tests. Does my use of Lazy still guarantee that the function is only run once, even in these circumstances?

This feels like a relatively common problem, but I’ve had trouble finding better solutions on the internet so far.



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?