Skip to content

Commit 0b93440

Browse files
authored
Fix: correctly parse hyphen in agency paths (#3983)
2 parents 9789d4b + d429edd commit 0b93440

2 files changed

Lines changed: 48 additions & 1 deletion

File tree

benefits/core/urls.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ class TransitAgencyPathConverter:
2626
"""Path converter to parse valid TransitAgency objects from URL paths."""
2727

2828
# used to test the url fragment, determines if this PathConverter is used
29-
regex = "[a-zA-Z]{3,}"
29+
regex = "[a-zA-Z-]{3,}"
3030

3131
def to_python(self, value):
3232
"""Determine if the matched fragment corresponds to an active Agency."""

tests/pytest/core/test_urls.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"""
2+
h/t to this blog post for the inspiration for these tests
3+
https://adamj.eu/tech/2025/08/01/django-custom-url-converter-string/
4+
"""
5+
6+
import pytest
7+
from django.urls import path, reverse
8+
9+
# Import forces registration
10+
from benefits.core.urls import TransitAgencyPathConverter # noqa: F401
11+
12+
urlpatterns = [
13+
path(
14+
"<agency:agency>",
15+
lambda *args, **kwargs: None, # dummy view
16+
name="sample",
17+
)
18+
]
19+
sample_path = urlpatterns[0]
20+
21+
22+
@pytest.mark.django_db
23+
class TestTransitAgencyPathConverter:
24+
def test_active_agency(self, model_TransitAgency):
25+
result = sample_path.resolve(model_TransitAgency.slug)
26+
assert result.kwargs["agency"] == model_TransitAgency
27+
28+
result = reverse("sample", urlconf=__name__, kwargs={"agency": model_TransitAgency})
29+
assert result == f"/{model_TransitAgency.slug}"
30+
31+
def test_active_agency__hyphen_slug(self, model_TransitAgency):
32+
model_TransitAgency.slug = "c-s-t"
33+
model_TransitAgency.save()
34+
35+
result = sample_path.resolve(model_TransitAgency.slug)
36+
assert result.kwargs["agency"] == model_TransitAgency
37+
38+
result = reverse("sample", urlconf=__name__, kwargs={"agency": model_TransitAgency})
39+
assert result == f"/{model_TransitAgency.slug}"
40+
41+
def test_inactive_agency(self, model_TransitAgency_inactive):
42+
result = sample_path.resolve(model_TransitAgency_inactive.slug)
43+
assert result is None
44+
45+
def test_unknown_agency(self):
46+
result = sample_path.resolve("unknown")
47+
assert result is None

0 commit comments

Comments
 (0)