Featured image of post Supporting Multiple Users and Different Contexts with Playwright Fixtures

Supporting Multiple Users and Different Contexts with Playwright Fixtures

Introducing how to create a custom Fixture to handle multi-user interaction scenarios

In modern web development, applications often need to handle scenarios where multiple users interact simultaneously. Whether it is a real-time collaboration tool, a social media platform, or an e-commerce site, testing these multi-user interactions is essential to ensure stability and correctness.

However, by default, Playwright tests are designed for a single user, and each test runs in an isolated browser context.

In this article we will introduce how to create a custom Fixture to handle such multi-user interaction scenarios.

Limitations of Single-User Testing

When we write a standard Playwright test, we usually get a page object representing a single browser tab, and this tab belongs to an independent browserContext. This context is fully isolated, with its own cookies, local storage, and so on. This is a very useful feature for most scenarios that need testing.

But when we want to test scenarios like the following, the problem arises:

  • User A sends a friend request to user B.
  • User B accepts the friend request.
  • User A and user B can now see each other in their friend lists.

In a single test, it is impossible to act as both user A and user B at the same time, because there is only one page object. We might also manually create a new browser context to handle it separately, but that makes the test code verbose, repetitive, and hard to maintain.

Customizing a Multi-User Fixture

Playwright provides a powerful feature called “fixtures”, which allows customizing the test execution environment. We can use it to create a fixture that provides one or more fully independent user environments for each test.

Using Python’s pytest-playwright library, we implement this with the @pytest.fixture decorator.

Below we will create two fixtures: user_one and user_two. Each fixture is responsible for creating its own BrowserContext and Page, and automatically cleaning them up after the test ends.

Code Implementation

Here we will use the async API of pytest and playwright, because it is closer to real async scenarios.

First, make sure the necessary libraries are installed:

1
2
pip install pytest pytest-playwright
playwright install

Now, in the test file conftest.py, define the following fixtures:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# conftest.py
import pytest
from playwright.async_api import Page, BrowserContext, Browser, expect

@pytest.fixture
async def user_one(browser: Browser):
    """
    Provide an independent browser context and page for user one.
    """
    # create a brand-new, isolated browser context
    context = await browser.new_context()
    # create a new page in that context
    page = await context.new_page()
    
    # provide the context and page to the test function as a dict
    yield {"context": context, "page": page}
    
    # after the test ends, close the context to clean up resources
    await context.close()

@pytest.fixture
async def user_two(browser: Browser):
    """
    Provide an independent browser context and page for user two.
    """
    context = await browser.new_context()
    page = await context.new_page()
    
    yield {"context": context, "page": page}
    
    await context.close()

Code explanation:

  • Two async fixtures are defined: user_one and user_two.
  • Each fixture depends on the browser fixture automatically provided by pytest-playwright.
  • The yield keyword is the core of a pytest fixture. The code before yield is the setup part, the value of yield is passed to the test function, and the code after yield is the teardown part.
  • This way, each test using these fixtures gets two fully independent user environments.

Practical Usage

Now we can easily use the user_one and user_two fixtures in tests. Just add them as parameters to the test function.

Suppose we have a simple chat application and want to test whether user B can receive a message sent by user A.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# test_multi_user_chat.py
import pytest
from playwright.async_api import expect

# Note: the fixture definitions of user_one and user_two can be placed in conftest.py,
# and pytest will discover them automatically. Here, for convenience, we assume they are already available.

@pytest.mark.asyncio
async def test_chat_between_two_users(user_one, user_two):
    # get the page objects of the two users
    page_a = user_one['page']
    page_b = user_two['page']

    # user A enters the chat room
    await page_a.goto("https://your-chat-app.com/room/123")
    await page_a.get_by_label("Username").fill("UserA")
    await page_a.get_by_role("button", name="Join").click()

    # user B enters the same chat room
    await page_b.goto("https://your-chat-app.com/room/123")
    await page_b.get_by_label("Username").fill("UserB")
    await page_b.get_by_role("button", name="Join").click()

    # user A sends a message
    message_text = "Hello from User A!"
    await page_a.get_by_label("Message").fill(message_text)
    await page_a.get_by_role("button", name="Send").click()

    # user B verifies whether the message was received
    # we need to wait for the message to appear on user B's page
    await expect(page_b.get_by_text(message_text)).to_be_visible()

    # user B replies
    reply_text = "Hello from User B!"
    await page_b.get_by_label("Message").fill(reply_text)
    await page_b.get_by_role("button", name="Send").click()

    # user A verifies whether the reply was received
    await expect(page_a.get_by_text(reply_text)).to_be_visible()

Preserving Login State

In real testing, you usually want users to already be logged in before testing starts. This can be achieved with the storageState option. Simply load a JSON file containing authentication information when creating the context.

The code looks like:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import asyncio
from playwright.async_api import async_playwright, Browser

async def generate_user_state(
    browser: Browser,
    base_url: str,
    user_email: str,
    user_password: str,
    output_path: str = "user_one_state.json",
):
    """
    Generate a user authentication state file (e.g. user_one_state.json)
    
    :param browser: Playwright Browser instance
    :param base_url: Application base URL
    :param user_email: User email
    :param user_password: User password
    :param output_path: Output path of the state file
    """
    # 1. create a temporary browser context (stateless)
    context = await browser.new_context()
    page = await context.new_page()

    try:
        # 2. navigate to the login page and log in
        await page.goto(f"{base_url}/login")
        await page.fill("input[name='email']", user_email)
        await page.fill("input[name='password']", user_password)
        await page.click("button[type='submit']")
        
        # wait for login success (e.g. redirect to the dashboard)
        await page.wait_for_url(f"{base_url}/dashboard", timeout=10000)

        # 3. save the authentication state to a file
        await context.storage_state(path=output_path)
        print(f"✅ User state saved to: {output_path}")

    except Exception as e:
        print(f"❌ Login failed: {e}")
        raise
    finally:
        # 4. close the context
        await context.close()

# usage example
async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)  # can be set to False for debugging
        await generate_user_state(
            browser,
            base_url="https://your-app.com",
            user_email="user_one@example.com",
            user_password="your_password",
            output_path="user_one_state.json",
        )
        await browser.close()

if __name__ == "__main__":
    asyncio.run(main())

In the code above, we first create a temporary browser context, perform the login flow, then use storageState to save to a JSON file, and close the context to release resources.

The resulting JSON file looks like:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{
  "cookies": [
    {
      "name": "session_id",
      "value": "abc123",
      "domain": "your-app.com",
      "path": "/",
      "expires": -1,
      "httpOnly": true,
      "secure": true,
      "sameSite": "Lax"
    }
  ],
  "origins": [
    {
      "origin": "https://your-app.com",
      "localStorage": [
        {
          "name": "token",
          "value": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
        }
      ]
    }
  ]
}

Then we modify the corresponding user_one fixture:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# conftest.py (updated user_one fixture)

@pytest.fixture
async def user_one(browser: Browser):
    """
    Provide an independent, logged-in browser context and page for user one.
    """
    # assume we have generated 'user_one_state.json' via a separate script or test
    context = await browser.new_context(storage_state="user_one_state.json")
    page = await context.new_page()
    
    yield {"context": context, "page": page}
    
    await context.close()

This way, every test using the user_one fixture automatically gets an already-logged-in user environment, greatly simplifying the test setup process.

Conclusion

By creating custom multi-user fixtures, we can easily extend the capabilities of Playwright tests to handle complex multi-user interaction scenarios.

Built with Hugo
Theme Stack designed by Jimmy