דלג לתוכן
חזור

אוטומציית בדיקות - כיצד לבצע בדיקות נגישות אוטומטיות באמצעות Playwright Python ו-Axe

פורסם:

הקדמה

בנוף הדיגיטלי של ימינו, הבטחת נגישות אינטרנט היא לא רק חובה מוסרית אלא היבט חיוני באספקת חוויות מכילות למשתמשים עם צרכים מגוונים. Playwright, כלי אוטומציה רב עוצמה לדפדפנים, בשילוב עם ספריית בדיקות הנגישות Axe, מספק פתרון חזק לאוטומציה של בדיקות נגישות במהלך תהליך הבדיקות שלך. על ידי שילוב שני הכלים החזקים הללו, תוכל לזהות ולטפל בבעיות נגישות באופן יזום.

הפתרון המוצג במאמר זה מודגם בפרויקט הדוגמה שלי Playwright Python example project, שפותח בשיתוף עם אליאס שורוש.

יישום הפתרון

המחלקה AxeHelper מכילה את המתודה check_accessibility שמריצה את Axe על עמוד Playwright נתון, בודקת הפרות נגישות בהתבסס על המספר המרבי המותר של הפרות לכל רמת השפעה, ומספקת דיווח מפורט.

ניתן למצוא את קוד הפתרון כאן.

import json
from collections import Counter
from typing import Dict

import allure
from axe_playwright_python.sync_playwright import Axe
from playwright.sync_api import Page

class AxeHelper:

    def __init__(self, axe: Axe):
        self.axe = axe

    def check_accessibility(
        self, page: Page, maximum_allowed_violation_by_impact: Dict[str, int] = None
    ) -> None:
        """Checks accessibility of the page using playwright axe.

        :param page: Playwright Page object
        :param maximum_allowed_violations_by_impact: A dictionary
            specifying the maximum allowed violations for each impact
            level (e.g., {'minor': 2, 'moderate': 1, 'serious': 0, 'critical': 0}). If None, no violations will be allowed for
            any impact level.
        """
        if maximum_allowed_violation_by_impact is None:
            maximum_allowed_violation_by_impact = {
                "minor": 0,
                "moderate": 0,
                "serious": 0,
                "critical": 0,
            }
        results = self.axe.run(page)
        violations_count = dict(
            Counter(
                [violation["impact"] for violation in results.response["violations"]]
            )
        )
        if violations_exceeded := {
            impact_level: violation_count
            for impact_level, violation_count in violations_count.items()
            if violation_count
            > maximum_allowed_violation_by_impact.get(impact_level, 0)
        }:
            allure.attach(
                body=json.dumps(results.response["violations"], indent=4),
                name="Accessibility Violation Results",
                attachment_type=allure.attachment_type.JSON,
            )
            assert not violations_exceeded, (
                f"Found accessibility violations exceeding the maximum allowed: "
                f"{violations_exceeded}"
            )

קובץ ה-conftest מגדיר fixture של pytest שיוצר מופע של AxeHelper עם Axe מאותחל. ל-fixture זה יש scope של session, כלומר הוא נוצר פעם אחת לכל סשן בדיקות ומשותף בין כל הבדיקות.

import pytest
from axe_playwright_python.sync_playwright import Axe

from utilities.axe_helper import AxeHelper

@pytest.fixture(scope="session")
def axe_playwright():
    """Fixture to provide an instance of AxeHelper with Axe initialized.

    This fixture has a session scope, meaning it will be created once per test session
    and shared across all tests.

    Returns:
        AxeHelper: An instance of AxeHelper with Axe initialized.
    """
    yield AxeHelper(Axe())

שימוש בבדיקות

ניתן למצוא את השימוש בבדיקות כאן.

import allure

class TestAccessibility:

    @allure.title("Test Accessibility with Default Counts")
    def test_accessibility_default_counts(self, axe_playwright, page):
        axe_playwright.check_accessibility(page)

    @allure.title("Test Accessibility with Custom Counts")
    def test_accessibility_custom_counts(self, axe_playwright, page):
        axe_playwright.check_accessibility(
            page,
            maximum_allowed_violation_by_impact={
                "minor": 2,
                "moderate": 5,
                "serious": 0,
                "critical": 0,
            },
        )

הבדיקה הראשונה, test_accessibility_default_counts, מפעילה את המתודה check_accessibility של ה-fixture axe_playwright, שסורקת את העמוד הנתון אחר הפרות נגישות, ולא מאפשרת הפרות מכל רמת השפעה. הבדיקה השנייה, test_accessibility_custom_counts, מדגימה כיצד להתאים אישית את המספר המרבי המותר של הפרות לכל רמת השפעה באמצעות הפרמטר maximum_allowed_violations_by_impact.

לסיכום

שילוב Axe עם Playwright מעצים מהנדסי אוטומציה לשלב בדיקות נגישות בזרימות העבודה שלהם בצורה חלקה.

בדיקות מהנות!


הציעו שינויים

מוכנים לבנות את מפת הדרכים שלכם? נתחיל כאן


הפוסט הקודם
אוטומציית בדיקות - כיצד לעקוף התחברות מחדש עם Playwright Python ו-Pytest
הפוסט הבא
אוטומציית בדיקות - כיצד לקשר עקבות והקלטות וידאו של Playwright לדוח Allure באמצעות GitHub Actions