pytest-dev / pytest-dev/pytest-django

How to test parallel requests (race conditions)

Open
#611 2 comments 5 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

documentation
Dominant language
Python
Stars
1.5k
Forks
367
PR merge metrics
No merged PRs in 30d

Description

I wonder what is the best way to test race conditions with parallel web requests, where each request runs in its own transaction typically, but if both would insert the same data it would trigger an IntegrityError.

I've came up with using live_server and asyncio/aiohttp for it:

def test_user_ephemeralkey_race(active_requests_mock, drf_renter, renter, org,
                                live_server, event_loop, mock_stripe_customer):
    import asyncio

    import aiohttp
    import rest_framework_jwt

    # …

    url = '%s%s' % (live_server.url, reverse('app:name'))

    event_loop.set_debug(True)

    async def get_url():
        async with aiohttp.ClientSession(headers={
            'Accept': 'application/json; version=1.0',
        }) as client:
            async with client.get(url) as resp:
                text = await resp.text()
                assert resp.status == 200, text
                assert json.loads(text) == expected_response

    coros = asyncio.gather(
        get_url(),
        get_url(),
        loop=event_loop,
    )
    event_loop.run_until_complete(coros)

It works for me, but I wonder if there's a lighter solution that would not
involve using transactional_db (via live_server) in particular.

If this makes sense we might want to add it to the documentation probably?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No file or test is named in the issue. Review the existing pytest-django documentation and the live_server and transactional_db entry points, then determine whether a lighter race-condition testing approach can be documented. Done means the recommended approach and its limitations are clearly described.

Written by the indexing model from the issue text.

Assessment

Tech stack
django, python
Domain
documentation, testing
Issue type
Documentation
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.