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.
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.