pytest-playwright basic tutorial (1) - installation and simple use
Structure of this article
1. How to install Playwright
2. How to run the test case
3. Brief introduction of fixture
a brief introdction
This tutorial is mainly a translated official website tutorial
Attach the official document link: Installation | Playwright Python
How to install Playwright
Enter in the pycharm terminal
pip install pytest-playwright
Just wait for the installation
After the installation is complete, enter in the terminal
playwright install
Install the browser driver that comes with playwright
How to run the test case
Create a file test_my_application.py
named and enter the following content
import re
from playwright.sync_api import Page, expect
def test_homepage_has_Playwright_in_title_and_get_started_link_linking_to_the_intro_page(page: Page):
page.goto("https://playwright.dev/")
# 查找是否存在标题 为"Playwright".
expect(page).to_have_title(re.compile("Playwright"))
# 创建一个定位器实例
get_started = page.get_by_role("link", name="Get started")
# 严格查找一个值"/docs/intro".
expect(get_started).to_have_attribute("href", "/docs/intro")
# 点击 get_started 按钮.
get_started.click()
# 判断该链接中是否包含"intro".
expect(page).to_have_url(re.compile(".*intro"))
Type in terminal
pytest
run test case
By default, the chromium kernel will be used to run the test case, and the default is headless mode, that is, the page will not be displayed. The final result will be displayed in the terminal
The role of the expect()
function is: wait until the expected condition is met
Using pytest's test fixture
import pytest
from playwright.sync_api import Page
@pytest.fixture(scope="function", autouse=True)
def before_each_after_each(page: Page):
print("beforeEach")
# Go to the starting url before each test.
page.goto("https://playwright.dev/")
yield
print("afterEach")
def test_main_navigation(page: Page):
# Assertions use the expect API.
expect(page).to_have_url("https://playwright.dev/")
@pytest.fixture(scope="function",autouse=True)
The role of it is to allow each test case to use the function decorated by this decorator to achieve code reuse
Parameter introduction:
scope = "function"
The function of means that the use of this fixture is when each test function is executed
autouse = True
Indicates that this fixture automatically finds qualified test cases, executes them automatically, and does not need to call this function again
Among them, the yield
previous code is executed before the test case, yield
and the subsequent code is executed after the test case
The execution effect is as follows
Summarize
This article introduces how to start using playwright+pytest for simple tests, and also introduces the use of fixtures in pytest, hoping to help everyone (●'◡'●)