Support customizing portal in TestClient #1347
Closed
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.
Consider a situation where we would like to create a second instance of
TestClient
within a started app:Previously, in
starlette<0.15.0
, this worked fine. However, sincestarlette>=0.15.0
this causes mayhem when something attaches to the event loop on startup and then is used within a request. The specific reason this doesn't work is because two different event loops are created as described here in #1315. This PR adds a newportal
argument toTestClient
which allows sharing the sameBlockingPortal
instance from anyio and transitively sharing the same event loop.With this change, the example above just has to be slightly adapted as follows:
Feel free to suggest alternate solutions. I figured I'd create the PR for discussion (since the code change is simple enough).
Also, note that from what I understand of Trio, this problem wouldn't happen there because it doesn't have the concept of unscoped task creation like asyncio does.