Skip to content

Commit

Permalink
Extract is_api_request() and add unit tests
Browse files Browse the repository at this point in the history
Extract `is_api_request()` into a shared helper function (instead of a
private method) and add unit tests.

Future commits will add code in multiple places that call the new shared
helper function.

But even with only one caller for the function there are still benefits
to extracting it and unit-testing it directly: when writing the tests I
noticed that it was returning `None` instead of `False` and added a
`bool()` call to fix this.
  • Loading branch information
seanh committed Jul 18, 2024
1 parent 82fc4ff commit 05a240e
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 5 deletions.
7 changes: 2 additions & 5 deletions h/security/policy/combined.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from h.security.policy._identity_base import IdentityBasedPolicy
from h.security.policy._remote_user import RemoteUserPolicy
from h.security.policy.bearer_token import BearerTokenPolicy
from h.security.policy.helpers import is_api_request


@implementer(ISecurityPolicy)
Expand Down Expand Up @@ -69,7 +70,7 @@ def _call_sub_policies(self, method, request, *args, **kwargs):
:return: The response from the correct sub-policy
"""

if not self._is_api_request(request):
if not is_api_request(request):
# This is usually the cookie policy for UI things
return getattr(self._ui_policy, method)(request, *args, **kwargs)

Expand All @@ -84,7 +85,3 @@ def _call_sub_policies(self, method, request, *args, **kwargs):
)

return result

@staticmethod
def _is_api_request(request):
return request.matched_route and request.matched_route.name.startswith("api.")
3 changes: 3 additions & 0 deletions h/security/policy/helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
def is_api_request(request) -> bool:
"""Return True if `request` is an API request."""
return bool(request.matched_route and request.matched_route.name.startswith("api."))
22 changes: 22 additions & 0 deletions tests/unit/h/security/policy/helpers_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import pytest

from h.security.policy.helpers import is_api_request


@pytest.mark.parametrize(
"route_name,expected_result",
[
("anything", False),
("api.anything", True),
],
)
def test_is_api_request(pyramid_request, route_name, expected_result):
pyramid_request.matched_route.name = route_name

assert is_api_request(pyramid_request) == expected_result


def test_is_api_request_when_matched_route_is_None(pyramid_request):
pyramid_request.matched_route = None

assert is_api_request(pyramid_request) is False

0 comments on commit 05a240e

Please sign in to comment.