Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ coverage.xml
*.py,cover
.hypothesis/
.pytest_cache/
axe-reports/

# Translations
*.mo
Expand Down
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,16 @@ To get started:
7. Run the tests:

```bash
python -m playwright install --with-deps chromium

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you maybe add the instructions of how to run this with seeing the browser version also? Not in this line but as an extra fyi

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
Expand Down
24 changes: 23 additions & 1 deletion dev-requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -139,25 +145,39 @@ 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
# pre-commit
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
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion main/templates/main/pages/events.html
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ <h2 class="h4 text-uppercase text-body-secondary pb-2 border-bottom mb-4">{{ yea
<div class="card card-hover card-lifted shadow-sm h-100">
<div class="row g-0">
<div class="col-md-3">
<img src="{% static event.image|default:'assets/app-icons/logo.svg' %}"
<img src="{% static 'assets/app-icons/logo.svg' %}"
alt="Event image"
class="rounded-start w-100 h-100"
style="object-fit: cover">
Expand Down
9 changes: 9 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ dev = [
"types-Markdown",
"types-requests",
"beautifulsoup4",
"playwright",
"pytest-playwright",
"pytest-playwright-axe",

]
prod = [
"mysqlclient",
Expand Down Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -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):
Expand Down
231 changes: 231 additions & 0 deletions tests/test_accessibility.py
Original file line number Diff line number Diff line change
@@ -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="<h2>Policy details</h2><p>Example policy content.</p>",
)


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
)