Skip to content

Instantly share code, notes, and snippets.

@mgaitan
Created May 29, 2024 23:43
Show Gist options
  • Save mgaitan/652d39a7df5076e38239d2ae3f6862ed to your computer and use it in GitHub Desktop.
Save mgaitan/652d39a7df5076e38239d2ae3f6862ed to your computer and use it in GitHub Desktop.
Playwright-pytest login just once per session (sharing storage state)

Simplest way to use Playwright sharing the "state" among tests.

The first test won't have the storage file so it will get a new empty page with no context and set it up / login.

Further tests will get a Page instance injected that has the same context as the first one, reusing the signed-in state.

Check https://playwright.dev/python/docs/auth#reusing-signed-in-state

import pytest
@pytest.fixture(scope="session")
def storage(tmp_path_factory):
return tmp_path_factory.mktemp("session") / "state.json"
@pytest.fixture
def page(new_context, storage):
if storage.exists():
yield new_context(storage_state=storage).new_page()
else:
context = new_context()
page = context.new_page()
page.goto("https://httpbin.dev/cookies/set?login=foo&pass=bar")
yield page
context.storage_state(path=storage)
def test_basic_cookie(page):
def handle_response(response):
assert response.json() == {"login": "foo", "pass": "bar"}
page.on('response', handle_response)
page.goto("https://httpbin.dev/cookies")
def test_cookies_2(page):
def handle_response(response):
assert response.json() == {"login": "foo", "pass": "bar", "something_else": "baz"}
page.on('response', handle_response)
page.goto("https://httpbin.dev/cookies/set?something_else=baz")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment