Container data-race when using concurrent tests #223
Replies: 1 comment 2 replies
-
Bug or design flaw? Depends on how you look at it I guess. Using shared containers in app works, primarily because the registrations occur at launch and remain stable while the app resolves its dependencies. Switching to concurrent testing is at odds with the behavior of the application itself, which means that swapping out shared resources no longer works. This also breaks the various property wrappers that depend on the shared containers. The only mitigation is running the tests serially, or rearchitecting the application to pass the container along as needed. That would allow you to construct and pass a correctly configured container to each concurrent instance under test. |
Beta Was this translation helpful? Give feedback.
-
We're using Swift-Testing which by default runs tests concurrently, our tests are also async meaning code under test can be suspended.
As an example, we have this dependency and mock version:
And a sut:
With the following swift-tests:
One of the two tests (random) will always fail:
The reason for failure is that the tests run in a single process, when the tests are executed concurrently one of the tests will register a dependency, and the other test will start concurrently and override this registration while the other test's await call is suspended. This leads to a data-race when registering and consuming the container.
I've included the example SPM package, you'll need Xcode 16 beta to be able to run the tests, and you'll also need to run the entire test case, they will pass when run individually.
test.zip
Is this a bug, or design flaw or is there a way to mitigate this without having to make the tests run serially?
Beta Was this translation helpful? Give feedback.
All reactions