Skip to content

Commit

Permalink
fiddle with unit tests, fix redirects for webapp oauth app to include…
Browse files Browse the repository at this point in the history
… all hostnames from ALLOWED_HOSTS
  • Loading branch information
tykling committed Nov 9, 2024
1 parent 93735d5 commit 52b26fd
Show file tree
Hide file tree
Showing 6 changed files with 45 additions and 50 deletions.
13 changes: 3 additions & 10 deletions src/albums/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,11 @@

from bs4 import BeautifulSoup
from django.urls import reverse
from oauth2_provider.models import get_access_token_model
from oauth2_provider.models import get_application_model
from oauth2_provider.models import get_grant_model

from utils.tests import ApiTestBase
from utils.tests import BmaTestBase

Application = get_application_model()
AccessToken = get_access_token_model()
Grant = get_grant_model()


class TestAlbumsApi(ApiTestBase):
class TestAlbumsApi(BmaTestBase):
"""Test for API endpoints in the albums API."""

def test_album_create_api(
Expand Down Expand Up @@ -169,7 +162,7 @@ def test_album_list_api(self) -> None:
assert response.json()["bma_response"][0]["title"] == "album5", "Did not get the expected offset"


class TestAlbumViews(ApiTestBase):
class TestAlbumViews(BmaTestBase):
"""Unit tests for regular django Album views."""

def create_albums(self) -> None:
Expand Down
19 changes: 6 additions & 13 deletions src/files/tests.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,17 @@
"""Tests for the files API."""
"""Tests for the files API, admin and HTML views."""

from pathlib import Path

from bs4 import BeautifulSoup
from django.conf import settings
from django.urls import reverse
from oauth2_provider.models import get_access_token_model
from oauth2_provider.models import get_application_model
from oauth2_provider.models import get_grant_model

from utils.tests import ApiTestBase
from utils.tests import BmaTestBase

from .models import BaseFile

Application = get_application_model()
AccessToken = get_access_token_model()
Grant = get_grant_model()


class TestFilesApi(ApiTestBase):
class TestFilesApi(BmaTestBase):
"""Test for methods in the files API."""

def test_api_auth_bearer_token(self) -> None:
Expand All @@ -33,7 +26,7 @@ def test_api_auth_get_refresh_token(self) -> None:
"/o/token/",
{
"grant_type": "refresh_token",
"client_id": f"client_id_{self.creator2.username}",
"client_id": self.creator2.webapp_oauth_client_id,
"refresh_token": self.creator2.tokeninfo["refresh_token"],
},
)
Expand Down Expand Up @@ -779,7 +772,7 @@ def test_file_missing_on_disk(self) -> None:
self.assertEqual(response.json()["bma_response"]["size_bytes"], 0)


class TestFileAdmin(ApiTestBase):
class TestFileAdmin(BmaTestBase):
"""Tests for the FileAdmin."""

def test_file_list_status_code(self) -> None:
Expand Down Expand Up @@ -927,7 +920,7 @@ def test_file_list(self) -> None:
)


class TestFileViews(ApiTestBase):
class TestFileViews(BmaTestBase):
"""Unit tests for regular django views."""

@classmethod
Expand Down
11 changes: 2 additions & 9 deletions src/tags/tests.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,11 @@
"""Tests for the files API."""

from django.urls import reverse
from oauth2_provider.models import get_access_token_model
from oauth2_provider.models import get_application_model
from oauth2_provider.models import get_grant_model

from utils.tests import ApiTestBase
from utils.tests import BmaTestBase

Application = get_application_model()
AccessToken = get_access_token_model()
Grant = get_grant_model()


class TestTagsApi(ApiTestBase):
class TestTagsApi(BmaTestBase):
"""Test tag stuff in the API."""

def test_tag_api(self) -> None:
Expand Down
4 changes: 3 additions & 1 deletion src/users/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from typing import TYPE_CHECKING
from typing import Any

from django.conf import settings
from oauth2_provider.generators import generate_client_id
from oauth2_provider.generators import generate_client_secret
from oauth2_provider.models import Application
Expand All @@ -17,9 +18,10 @@
def create_webapp_oauth_app(*, sender: str, instance: "User", created: bool, **kwargs: dict[Any, Any]) -> None:
"""Create the oauth app for the BMA webapp."""
if created:
redirect_uris = [f"https://{hostname}/api/csrf/" for hostname in settings.ALLOWED_HOSTS]
app, app_created = Application.objects.get_or_create(
user=instance,
redirect_uris="https://redirect.invalid/redirect",
redirect_uris=" ".join(redirect_uris),
client_type="public",
authorization_grant_type="authorization-code",
name="autocreated-bma-webapp-client",
Expand Down
23 changes: 23 additions & 0 deletions src/users/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"""Tests for the users app."""

from django.conf import settings
from oauth2_provider.models import get_application_model

from utils.tests import BmaTestBase

Application = get_application_model()


class TestUserOauthApplication(BmaTestBase):
"""Tests for oauth stuff."""

def test_user_oauth_app_for_webapp(self) -> None:
"""Make sure the webapp oauth app has been created correctly for all users."""
redirect_uris = [f"https://{hostname}/api/csrf/" for hostname in settings.ALLOWED_HOSTS]
for user in self.users:
app = Application.objects.get(name="autocreated-bma-webapp-client", user=user)
assert app.redirect_uris == " ".join(redirect_uris)
assert app.client_type == "public"
assert app.authorization_grant_type == "authorization-code"
assert app.skip_authorization
assert hasattr(self.user0, "webapp_oauth_client_id")
25 changes: 8 additions & 17 deletions src/utils/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@
Grant = get_grant_model()


class ApiTestBase(TestCase):
"""The base class used by all api tests."""
class BmaTestBase(TestCase):
"""The base class used by all BMA tests."""

@classmethod
def setUpTestData(cls) -> None:
Expand All @@ -37,6 +37,7 @@ def setUpTestData(cls) -> None:
cls.client = Client(enforce_csrf_checks=False)

# create 2 regular users, 2 creators, 2 moderators, 2 curators, and 1 superuser
cls.users = []
for i in range(9):
kwargs = {}
if i in [0, 1]:
Expand All @@ -56,17 +57,7 @@ def setUpTestData(cls) -> None:
user.set_password("secret")
user.save()
setattr(cls, user.username, user)
# create oauth application
cls.application = Application.objects.create(
name="Test Application",
redirect_uris="https://example.com/noexist/callback/",
user=user,
client_type=Application.CLIENT_PUBLIC,
authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
client_id=f"client_id_{user.username}",
client_secret="client_secret",
skip_authorization=True,
)
cls.users.append(user)
user.auth = cls.get_access_token(user)
user.save()
cls.client.logout()
Expand Down Expand Up @@ -95,9 +86,9 @@ def get_access_token(cls, user) -> str: # noqa: ANN001

# get the authorization code
data = {
"client_id": f"client_id_{user.username}",
"client_id": user.webapp_oauth_client_id,
"state": "something",
"redirect_uri": "https://example.com/noexist/callback/",
"redirect_uri": "https://localhost/api/csrf/",
"response_type": "code",
"allow": True,
"code_challenge": code_challenge_base64,
Expand All @@ -119,8 +110,8 @@ def get_access_token(cls, user) -> str: # noqa: ANN001
{
"grant_type": "authorization_code",
"code": qs["code"],
"redirect_uri": "https://example.com/noexist/callback/",
"client_id": f"client_id_{user.username}",
"redirect_uri": "https://localhost/api/csrf/",
"client_id": user.webapp_oauth_client_id,
"code_verifier": code_verifier_base64.decode("utf-8"),
},
)
Expand Down

0 comments on commit 52b26fd

Please sign in to comment.