async def test_login_xsrf_initial_cookies(app, browser, case, username):
    """Test that login works with various initial states for xsrf tokens

    Page will be reloaded with correct values
    """
    hub_root = public_host(app)
    hub_url = url_path_join(public_host(app), app.hub.base_url)
    hub_parent = hub_url.rstrip("/").rsplit("/", 1)[0] + "/"
    login_url = url_path_join(
        hub_url, url_concat("login", {"next": url_path_join(app.base_url, "/hub/home")})
    )
    # start with all cookies cleared
    await browser.context.clear_cookies()
    if case == "invalid":
        await browser.context.add_cookies(
            [{"name": "_xsrf", "value": "invalid-hub-prefix", "url": hub_url}]
        )
    elif case.startswith("valid-prefix"):
        if "invalid-root" in case:
            invalid_url = hub_root
        else:
            invalid_url = hub_parent
        await browser.goto(login_url)
        # first visit sets valid xsrf cookie
        cookies = await browser.context.cookies()
        assert len(cookies) == 1
        # second visit is also made with invalid xsrf on `/`
        # handling of this behavior is undefined in HTTP itself!
        # _either_ the invalid cookie on / is ignored
        # _or_ both will be cleared
        # currently, this test assumes the observed behavior,
        # which is that the invalid cookie on `/` has _higher_ priority
        await browser.context.add_cookies(
            [{"name": "_xsrf", "value": "invalid-root", "url": invalid_url}]
        )
        cookies = await browser.context.cookies()
        assert len(cookies) == 2

    # after visiting page, cookies get re-established
    await browser.goto(login_url)
    cookies = await browser.context.cookies()
    print(cookies)
    cookie = cookies[0]
    assert cookie['name'] == '_xsrf'
    assert cookie["path"] == app.hub.base_url

    # next page visit, cookies don't change
    await browser.goto(login_url)
    cookies_2 = await browser.context.cookies()
    assert cookies == cookies_2
    # login is successful
    await login(browser, username, username)
Test that login works with various initial states for xsrf tokens

Page will be reloaded with correct values
jupyterhub/tests/browser/test_browser.py