diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5c102c3c..e1af1d8f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,9 +34,20 @@ jobs: - name: Run mypy run: mypy . + - name: Install Chromium + run: python -m playwright install --with-deps chromium + - name: Run tests run: pytest --cov-report=xml + - name: Upload accessibility reports + if: always() + uses: actions/upload-artifact@v6 + with: + name: accessibility-reports + path: axe-reports/ + if-no-files-found: ignore + - name: Upload coverage to Codecov if: github.event.pull_request.user.login != 'dependabot[bot]' && github.event.pull_request.user.login != 'pre-commit-ci[bot]' && github.ref_type != 'tag' uses: codecov/codecov-action@v7 diff --git a/.gitignore b/.gitignore index 185b8c6b..7a8e850d 100644 --- a/.gitignore +++ b/.gitignore @@ -50,6 +50,7 @@ coverage.xml *.py,cover .hypothesis/ .pytest_cache/ +axe-reports/ # Translations *.mo diff --git a/README.md b/README.md index 815a5d68..0a645014 100644 --- a/README.md +++ b/README.md @@ -98,9 +98,16 @@ To get started: 7. Run the tests: ```bash + python -m playwright install --with-deps chromium pytest ``` + To run the accessibility tests without a headless browser you can run the following command: + + ```bash + PWDEBUG=1 python -m pytest tests/test_accessibility.py --no-cov + ``` + 8. Create an admin account to access admin backend: ```bash diff --git a/dev-requirements.txt b/dev-requirements.txt index 107fd94e..85d63be9 100644 --- a/dev-requirements.txt +++ b/dev-requirements.txt @@ -80,6 +80,8 @@ filelock==4.2.4 # via # python-discovery # virtualenv +greenlet==3.5.6 + # via playwright gunicorn==26.2.0 # via direct-webapp (pyproject.toml) identify==2.6.20 @@ -124,6 +126,10 @@ pip-tools==7.6.2 # via direct-webapp (pyproject.toml) platformdirs==4.14.0 # via virtualenv +playwright==1.65.2 + # via + # direct-webapp (pyproject.toml) + # pytest-playwright pluggy==1.7.0 # via # pytest @@ -139,17 +145,29 @@ pyproject-hooks==1.3.3 pytest==9.2.0 # via # direct-webapp (pyproject.toml) + # pytest-base-url # pytest-cov # pytest-django # pytest-mock + # pytest-playwright +pytest-base-url==2.1.0 + # via pytest-playwright pytest-cov==7.1.0 # via direct-webapp (pyproject.toml) pytest-django==4.14.0 # via direct-webapp (pyproject.toml) pytest-mock==3.17.0 # via direct-webapp (pyproject.toml) +pytest-playwright==0.10.0 + # via + # direct-webapp (pyproject.toml) + # pytest-playwright-axe +pytest-playwright-axe==4.14.0 + # via direct-webapp (pyproject.toml) python-discovery==1.6.7 # via virtualenv +python-slugify==9.2.0 + # via pytest-playwright pyyaml==6.0.3 # via # djlint @@ -157,7 +175,9 @@ pyyaml==6.0.3 regex==2026.9.29 # via djlint requests==2.34.2 - # via direct-webapp (pyproject.toml) + # via + # direct-webapp (pyproject.toml) + # pytest-base-url ruff==0.17.3 # via direct-webapp (pyproject.toml) setuptools==84.2.1 @@ -168,6 +188,8 @@ sqlparse==0.6.0 # via django tablib==3.10.0 # via django-import-export +text-unidecode==1.3 + # via python-slugify types-django-import-export==4.4.0.20260813 # via direct-webapp (pyproject.toml) types-markdown==3.11.2.20261029 diff --git a/main/templates/main/pages/events.html b/main/templates/main/pages/events.html index 856c133d..88c07de1 100644 --- a/main/templates/main/pages/events.html +++ b/main/templates/main/pages/events.html @@ -35,7 +35,7 @@

{{ yea
- Event image diff --git a/pyproject.toml b/pyproject.toml index 6f856881..27fca6ef 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,6 +41,10 @@ dev = [ "types-Markdown", "types-requests", "beautifulsoup4", + "playwright", + "pytest-playwright", + "pytest-playwright-axe", + ] prod = [ "mysqlclient", @@ -100,6 +104,11 @@ ignore_missing_imports = true module = ["django_filters.*"] ignore_missing_imports = true +# Not installed in the pre-commit mypy env: playwright exceeds pre-commit.ci's size limit. +[[tool.mypy.overrides]] +module = ["playwright.*", "pytest_playwright_axe.*"] +ignore_missing_imports = true + [[tool.mypy.overrides]] module = ["main.io_resources"] disallow_any_generics = false diff --git a/tests/conftest.py b/tests/conftest.py index 77bd8749..bbcfbc2d 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,7 +1,13 @@ """Pytest configuration file.""" +import os + import pytest +# This allows using playwright in tests. See: +# https://github.com/microsoft/playwright-pytest/issues/29#issuecomment-731515676 +os.environ.setdefault("DJANGO_ALLOW_ASYNC_UNSAFE", "true") + @pytest.fixture def user(django_user_model): diff --git a/tests/test_accessibility.py b/tests/test_accessibility.py new file mode 100644 index 00000000..355a4df8 --- /dev/null +++ b/tests/test_accessibility.py @@ -0,0 +1,231 @@ +"""Scan the application's HTML pages with Playwright and axe-core.""" + +from collections.abc import Iterable, Iterator +from json import dumps +from pprint import pformat +from urllib.parse import urlencode + +import pytest +from django.conf import settings +from django.contrib.auth.mixins import AccessMixin +from django.core.management import call_command +from django.test import Client +from django.urls import URLPattern, URLResolver, get_resolver, reverse +from playwright.sync_api import Page, expect +from pytest_playwright_axe import Axe + +from main.models import Event, Provider, Skill, SkillLevel, SkillProfile +from main.team_services import create_team, generate_invitation_token + +pytestmark = pytest.mark.django_db(transaction=True) + + +class AccessibilityViolation(AssertionError): + """Distinguish axe violations from navigation, setup, and scanner errors.""" + + +known_violations = pytest.mark.xfail( + reason="Known axe violations see report", + raises=AccessibilityViolation, + strict=True, +) + +# Argument-free routes that are not scanned by the discovered-page tests. +EXCLUDED_URL_NAMES = { + # Non-HTML responses or POST-only endpoints. + "logout", + "framework_json", + "framework_csv", + "download-csv-data-link", + "download-json-data-link", + # Redirects to self_assess or skills_profile. + "account-overview", + # Scanned with representative query data in test_shared_skill_profile. + "view_skill_profile", +} + +# Django auth views protected by the login_required decorator, not AccessMixin. +LOGIN_REQUIRED_URL_NAMES = {"password_change", "password_change_done"} + + +def _url_patterns( + patterns: Iterable[URLPattern | URLResolver], +) -> Iterator[URLPattern]: + """Yield non-namespaced URL patterns, skipping namespaced apps like admin.""" + for pattern in patterns: + if isinstance(pattern, URLResolver): + if not pattern.namespace: + yield from _url_patterns(pattern.url_patterns) + elif isinstance(pattern, URLPattern): + yield pattern + + +def _discover_page_names() -> tuple[list[str], list[str]]: + """Split named, argument-free routes into public and login-required pages.""" + public: set[str] = set() + login_required: set[str] = set() + for pattern in _url_patterns(get_resolver().url_patterns): + if ( + not pattern.name + or pattern.name in EXCLUDED_URL_NAMES + or pattern.pattern.regex.groups + ): + continue + view_class = getattr(pattern.callback, "view_class", None) + requires_login = pattern.name in LOGIN_REQUIRED_URL_NAMES or ( + view_class is not None and issubclass(view_class, AccessMixin) + ) + (login_required if requires_login else public).add(pattern.name) + return sorted(public), sorted(login_required) + + +PUBLIC_PAGES, ACCOUNT_PAGES = _discover_page_names() + + +@pytest.fixture +def login(live_server, context): + """Log a user into the browser using a server-side Django session.""" + + def _login(user): + client = Client() + client.force_login(user) + context.add_cookies( + [ + { + "name": settings.SESSION_COOKIE_NAME, + "value": client.cookies[settings.SESSION_COOKIE_NAME].value, + "url": live_server.url, + } + ] + ) + + return _login + + +@pytest.fixture(autouse=True) +def accessibility_data(mocker): + """Populate framework content and isolate remote policy Markdown requests.""" + call_command( + "loaddata", + settings.BASE_DIR / "direct_webapp/fixtures/framework-2-0.json", + verbosity=0, + ) + Event.objects.create( + title="Framework workshop", + start_date="2026-04-01", + description="A workshop about the framework.", + location="Manchester", + event_link="https://example.com/event", + blog="https://example.com/blog", + contributors="Test Contributor", + ) + for view in ("GovernancePageView", "LicensingPageView"): + mocker.patch( + f"main.views.page_views.{view}.get_markdown_content", + return_value="

Policy details

Example policy content.

", + ) + + +def check_accessibility(page: Page, url: str, filename: str) -> None: + """Check the intended, fully loaded page and report any axe violations.""" + response = page.goto(url) + assert response is not None and response.status == 200 + expect(page).to_have_url(url) + expect(page.locator(".page-loading")).not_to_be_visible() + assert page.evaluate( + """() => [...document.styleSheets].some( + sheet => sheet.href?.endsWith('/assets/css/theme.min.css') + && sheet.cssRules.length > 0 + )""" + ), "The theme stylesheet must load before scanning." + violations = Axe().run( + page, + filename=filename, + report_on_violation_only=True, + json_report_generated=False, + )["violations"] + if violations: + raise AccessibilityViolation( + f"Accessibility violations on {url}:\n{pformat(violations)}" + ) + + +@known_violations +@pytest.mark.parametrize("page_url", PUBLIC_PAGES) +def test_public_pages(live_server, page: Page, page_url): + """Scan public pages discovered from the URL configuration.""" + check_accessibility(page, live_server.url + reverse(page_url), page_url) + + +@known_violations +@pytest.mark.parametrize("page_url", ACCOUNT_PAGES) +def test_account_pages(live_server, page: Page, login, user, page_url): + """Scan account forms, a populated skill profile, and team memberships.""" + SkillProfile.objects.create( + profile=user.profile, + skill=Skill.objects.order_by("pk")[0], + skill_level=SkillLevel.objects.get(level=1), + ) + create_team(user=user, name="Research team", description="A research team") + login(user) + check_accessibility(page, live_server.url + reverse(page_url), page_url) + + +@known_violations +@pytest.mark.parametrize( + ("page_url", "model"), + [("skill_detail", Skill), ("learning_provider_detail", Provider)], +) +def test_detail_pages(live_server, page: Page, page_url, model): + """Scan populated skill and provider detail pages.""" + url = reverse(page_url, kwargs={"slug": model.objects.order_by("pk")[0].slug}) + check_accessibility(page, live_server.url + url, page_url) + + +@known_violations +def test_shared_skill_profile(live_server, page: Page): + """Scan a shared competency wheel with representative profile data.""" + skill = Skill.objects.select_related("competency__competency_domain").first() + assert skill is not None + query = urlencode( + { + "chart_data": dumps( + [ + { + "user_id": "root", + "skill_profile_data": [ + { + "skill": skill.name, + "category": skill.competency.competency_domain.name, + "subcategory": skill.competency.name, + "skill_level": 1, + } + ], + } + ] + ), + "skill_levels": dumps(list(SkillLevel.objects.values("level", "name"))), + } + ) + url = live_server.url + reverse("view_skill_profile") + "?" + query + check_accessibility(page, url, "view_skill_profile") + + +@known_violations +@pytest.mark.parametrize("page_url", ["team-invitation-link", "team-invitation-accept"]) +def test_team_invitation_pages( + live_server, page: Page, login, user, admin_user, page_url +): + """Scan manager link generation and a non-member's invitation form.""" + team = create_team( + user=admin_user, name="Research team", description="A research team" + ) + kwargs = {"team_slug": team.slug} + if page_url == "team-invitation-accept": + kwargs["token"] = generate_invitation_token(team=team, invited_by=admin_user) + login(user) + else: + login(admin_user) + check_accessibility( + page, live_server.url + reverse(page_url, kwargs=kwargs), page_url + )