Location>code7788 >text

Playwright+Python] Tutorial Series (VIII) Authentication Authentication Use

Popularity:502 ℃/2024-08-08 23:05:02

write sth. upfront

There's still a bit of a rambling feeling that the official translation and certain bloggers writing that play flute are basically the product of a direct translation from the software.

It reads raw, not to mention that there are times when it doesn't even mean what it says, which is really really not complimentary.

What the hell does that mean?

That is, you have already logged in once, in the case of Session, Cookie has not been invalidated, after logging in once, the next time you do not have to go through the process of logging in again, thus shortening the script execution time and improving the efficiency of the test.

Did I make myself clear?

Got it, thanks!

You don't ask for anything you can do yourself, hahaha!

Use of Authentication

1. Core concepts

This is the necessary configuration given officially, so I'll post it directly as follows:

mkdir -p playwright/.auth
echo $'\nplaywright/.auth' >> .gitignore

Note: With all due respect, adding it or not doesn't affect anything and can be ignored!

2. Core ideas

Before running the script each time, you need to run a login process.

As we were used to before, surely we should also abstract the login and put it into a public method right, but what we're going to do here is an enhancement.

What it means is that you log in once and the next time you execute the test directly without logging in.

3. Practical scenarios

Scene:Now I'm going to log in to Ink Drop and click on Write Article.

Core:Reusing logged-in status

3.1. Use of cookies for storage

Playwright allows the reuse of the logged-in state in tests via the() method extracts cookies and locally stored authentication state to avoid duplicate logins in multiple tests.
Sample code:

# -*- coding: utf-8 -*-
# @Time : 2024/08/08 20:03
# @Author :
# @FileName: test_authentication.py
# @Software: PyCharm
# @Cnblogs : /longronglang
# @Motto: You just work hard and leave the rest to providence.
import pytest
from playwright.sync_api import expect, Page

# Create a global variable to hold the storage state
storage = None


def test_login(page: Page): # Create a global variable to hold the storage state.
    global storage
    ("/")
    page.get_by_text("Login / Register").click()
    page.get_by_text("Email Login >").click()
    # Interact with login form
    page.get_by_placeholder("Email address, e.g. example@").fill("username@")
    page.get_by_placeholder("Please enter a password").fill("password")
    page.get_by_text("I'm logging in!") .click()
    page.wait_for_timeout(1000)
    # Assert that the page title is Baidu.
    expect(page.get_by_text('Community daily posts receive benefits')).to_have_text("Community daily posts receive benefits")
    # Save storage state into the file.
    storage = .storage_state(path="")


# In other tests, create a new context and use the previously saved storage state
def test_write_article(page: Page) -> None.
    global storage
    """
    Method 1
    Create a new context and use the previously stored state file
    new_context = .new_context(storage_state=storage)
    new_page = new_context.new_page()
    """

    """
    Method 2
    Create a new page directly, using the previously stored state file
    """
    new_page = .new_page(storage_state=storage)
    new_page.goto("/")
    new_page.get_by_text("write article").click()


if __name__ == '__main__'.
    (['-vs', 'test_authentication.py'])

Effect:

On both of these, although the use case can be executed successfully, several new browser windows are opened

3.2. Using Session Storage

Cookies and locally stored authentication state can be used cross-browser, but session storage is not persistent, and Playwright does not provide an API for it, so you need to save and load it manually.

Sample code:

# -*- coding: utf-8 -*-
# @Time : 2024/08/08 21:30
# @Author :
# @FileName: test_session
# @Software: PyCharm
# @Cnblogs :/longronglang
# @Motto:You just try.,The rest is up to God..
#
import os

import pytest
from playwright.sync_api import Page


# Define global login
@(scope="function", autouse=True)
def page(page: Page):
    ("/")
    page.get_by_text("log in / enrollment").click()
    page.get_by_text("邮箱log in >").click()
    # Interact with login form
    page.get_by_placeholder("E-mail address,for example:example@").fill("username@")
    page.get_by_placeholder("Please enter your password").fill("password")
    page.get_by_text("我要log in啦!").click()
    page.wait_for_timeout(1000)
    # Assert that the page title is Baidu,You'll see.
    expect(page.get_by_text('Community Daily Posts Receive Benefits')).to_have_text("Community Daily Posts Receive Benefits")
    # Get the session store for the current page
    session_storage = ("() => (sessionStorage)")
    # Storing the session store as an environment variable
    ["SESSION_STORAGE"] = session_storage
    session_storage = ["SESSION_STORAGE"]
    new_context =
    new_context.add_init_script("""(storage => {
      if ( === '') {
        const entries = (storage)
        for (const [key, value] of (entries)) {
          (key, value)
        }
      }
    })('""" + session_storage + "')")
    new_page = new_context.new_page()
    yield new_page


# test_demo.py
from playwright.sync_api import Page, expect


def test_write_article(page: Page) -> None:
    ("/")
    page.get_by_text("write an article").click()
    page.wait_for_timeout(1000)


if __name__ == '__main__':
    (['-vs', 'test_authentication.py'])

Effect:

Written this way, it's more elegant, at least it doesn't open multiple browsers at the same time, but it's still an extra tab, not a big problem overall.

put at the end

I read a post written by a blogger the day before yesterday and it really blew me away, super detailed and vicarious.

I was struck by the fact that good technical writing, too, has a soul.

So the question is, what if you were to write technical articles?

What should you write?