From 32e822391b5fc086c64eff36c17510c3668f3ae0 Mon Sep 17 00:00:00 2001 From: Sahil Raja Date: Wed, 25 Nov 2026 12:47:42 +0000 Subject: [PATCH 1/9] add playwright dependencies --- .gitignore | 2 ++ .pre-commit-config.yaml | 2 ++ dev-requirements.txt | 24 +++++++++++++++++++++++- pyproject.toml | 4 ++++ 4 files changed, 31 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 185b8c6b..9d5c3a6b 100644 --- a/.gitignore +++ b/.gitignore @@ -50,6 +50,8 @@ coverage.xml *.py,cover .hypothesis/ .pytest_cache/ +axe-reports/ +test-results/ # Translations *.mo diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 86240087..b61072bf 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -47,6 +47,8 @@ repos: - django-tables2 - django-filter - django-guardian + - playwright + - pytest-playwright-axe - repo: https://github.com/igorshubovych/markdownlint-cli rev: v0.50.1 hooks: 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/pyproject.toml b/pyproject.toml index 6f856881..6d38cc0f 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", From a9bb65bf006e6b4111ed6f02b08db3015a06bbbb Mon Sep 17 00:00:00 2001 From: Sahil Raja Date: Wed, 25 Nov 2026 12:51:04 +0000 Subject: [PATCH 2/9] fix events page image error --- main/templates/main/pages/events.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From 542571ced279b30319c717bf378276b4374cd03c Mon Sep 17 00:00:00 2001 From: Sahil Raja Date: Wed, 25 Nov 2026 12:59:29 +0000 Subject: [PATCH 3/9] add accessability test file with xfail enabled to flag issues --- .gitignore | 1 - tests/conftest.py | 6 ++ tests/test_accessibility.py | 205 ++++++++++++++++++++++++++++++++++++ 3 files changed, 211 insertions(+), 1 deletion(-) create mode 100644 tests/test_accessibility.py diff --git a/.gitignore b/.gitignore index 9d5c3a6b..7a8e850d 100644 --- a/.gitignore +++ b/.gitignore @@ -51,7 +51,6 @@ coverage.xml .hypothesis/ .pytest_cache/ axe-reports/ -test-results/ # Translations *.mo 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..8e923348 --- /dev/null +++ b/tests/test_accessibility.py @@ -0,0 +1,205 @@ +"""Scan the application's HTML pages with Playwright and axe-core.""" + +from json import dumps +from pprint import pformat +from urllib.parse import urlencode + +import pytest +from django.conf import settings +from django.core.management import call_command +from django.test import Client +from django.urls import 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, +) + + +@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", + [ + "index", + "about", + "framework", + "framework_overview", + "skills_and_competencies", + "skill_levels", + "learning_providers", + "learning_resources", + "tools_languages_methodologies", + "roles", + "privacy", + "terms", + "governance", + "licensing", + "our_team", + "get_involved", + "events", + "django_registration_register", + "login", + "password_reset", + ], +) +def test_public_pages(live_server, page: Page, page_url): + """Scan public pages, including the custom registration form.""" + check_accessibility(page, live_server.url + reverse(page_url), page_url) + + +@known_violations +@pytest.mark.parametrize( + "page_url", + ["self_assess", "skills_profile", "profile", "terms_acceptance", "my_teams"], +) +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 + ) From 3ddbe679073ae2f5129f48ff3fa7e24d94437efc Mon Sep 17 00:00:00 2001 From: Sahil Raja Date: Wed, 25 Nov 2026 12:59:46 +0000 Subject: [PATCH 4/9] update readme --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 815a5d68..63171010 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,7 @@ To get started: 7. Run the tests: ```bash + python -m playwright install --with-deps chromium pytest ``` From f374bc12ee8fb5098e498bb06dc1a08116194365 Mon Sep 17 00:00:00 2001 From: Sahil Raja Date: Wed, 25 Nov 2026 13:01:35 +0000 Subject: [PATCH 5/9] install playwright in CI and make reports avaialble for download --- .github/workflows/ci.yml | 11 +++++++++++ 1 file changed, 11 insertions(+) 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 From 24cc00bc29ec685bf012bc1430c230978355e09d Mon Sep 17 00:00:00 2001 From: Sahil Raja Date: Thu, 26 Nov 2026 15:04:01 +0000 Subject: [PATCH 6/9] remove pre-commit hooks --- .pre-commit-config.yaml | 2 -- pyproject.toml | 5 +++++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index b61072bf..86240087 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -47,8 +47,6 @@ repos: - django-tables2 - django-filter - django-guardian - - playwright - - pytest-playwright-axe - repo: https://github.com/igorshubovych/markdownlint-cli rev: v0.50.1 hooks: diff --git a/pyproject.toml b/pyproject.toml index 6d38cc0f..27fca6ef 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -104,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 From 2bf3f77f4970a1a819233a8e6605007ed4dbfa89 Mon Sep 17 00:00:00 2001 From: Sahil Raja Date: Fri, 27 Nov 2026 15:48:42 +0000 Subject: [PATCH 7/9] dynamicaly get the urls for the tests --- tests/test_accessibility.py | 88 ++++++++++++++++++++++++------------- 1 file changed, 57 insertions(+), 31 deletions(-) diff --git a/tests/test_accessibility.py b/tests/test_accessibility.py index 8e923348..355a4df8 100644 --- a/tests/test_accessibility.py +++ b/tests/test_accessibility.py @@ -1,14 +1,16 @@ """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 reverse +from django.urls import URLPattern, URLResolver, get_resolver, reverse from playwright.sync_api import Page, expect from pytest_playwright_axe import Axe @@ -28,6 +30,57 @@ class AccessibilityViolation(AssertionError): 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): @@ -98,41 +151,14 @@ def check_accessibility(page: Page, url: str, filename: str) -> None: @known_violations -@pytest.mark.parametrize( - "page_url", - [ - "index", - "about", - "framework", - "framework_overview", - "skills_and_competencies", - "skill_levels", - "learning_providers", - "learning_resources", - "tools_languages_methodologies", - "roles", - "privacy", - "terms", - "governance", - "licensing", - "our_team", - "get_involved", - "events", - "django_registration_register", - "login", - "password_reset", - ], -) +@pytest.mark.parametrize("page_url", PUBLIC_PAGES) def test_public_pages(live_server, page: Page, page_url): - """Scan public pages, including the custom registration form.""" + """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", - ["self_assess", "skills_profile", "profile", "terms_acceptance", "my_teams"], -) +@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( From 69ed854d961b7da78eba77cf55d7091f2de6e49b Mon Sep 17 00:00:00 2001 From: Sahil Raja Date: Fri, 27 Nov 2026 16:57:12 +0000 Subject: [PATCH 8/9] add command in readme to allow the tests to run without a headless browser --- README.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 63171010..a8668de9 100644 --- a/README.md +++ b/README.md @@ -102,13 +102,19 @@ To get started: pytest ``` -8. Create an admin account to access admin backend: +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 +``` + +1. Create an admin account to access admin backend: ```bash python manage.py createsuperuser ``` -9. Populate the database using a snapshot of v2.0 of the framework (this is not necessarily the latest live version, so this is only used for development). +2. Populate the database using a snapshot of v2.0 of the framework (this is not necessarily the latest live version, so this is only used for development). ```bash python manage.py loaddata direct_webapp/fixtures/framework-2-0.json From 54bb890c31e62ef1085243b9169ad59db3a81c23 Mon Sep 17 00:00:00 2001 From: Sahil Raja Date: Fri, 27 Nov 2026 17:06:21 +0000 Subject: [PATCH 9/9] fix numbering --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index a8668de9..0a645014 100644 --- a/README.md +++ b/README.md @@ -102,19 +102,19 @@ To get started: pytest ``` -To run the accessibility tests without a headless browser you can run the following command: + 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 -``` + ```bash + PWDEBUG=1 python -m pytest tests/test_accessibility.py --no-cov + ``` -1. Create an admin account to access admin backend: +8. Create an admin account to access admin backend: ```bash python manage.py createsuperuser ``` -2. Populate the database using a snapshot of v2.0 of the framework (this is not necessarily the latest live version, so this is only used for development). +9. Populate the database using a snapshot of v2.0 of the framework (this is not necessarily the latest live version, so this is only used for development). ```bash python manage.py loaddata direct_webapp/fixtures/framework-2-0.json