Skip to content

Commit

Permalink
fix tests, merge main
Browse files Browse the repository at this point in the history
  • Loading branch information
jefer94 committed Jan 24, 2025
1 parent d2e2953 commit 6c17075
Show file tree
Hide file tree
Showing 7 changed files with 175 additions and 184 deletions.
61 changes: 3 additions & 58 deletions breathecode/authenticate/tests/urls/tests_academy_google.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@

import pytest
from capyc import pytest as capy
from django import shortcuts
from django.http import JsonResponse
from django.urls.base import reverse_lazy
from django.utils import timezone
from rest_framework import status
Expand All @@ -21,64 +19,11 @@
callback = str(base64.urlsafe_b64encode(b"https://potato.io"), "utf-8")


@pytest.fixture(autouse=True)
def redirect_url(monkeypatch: pytest.MonkeyPatch):
def redirect_url(*args, **kwargs):

if args:
args = args[1:]

if args:
try:
kwargs["_template"] = args[0]
except:
...

try:
kwargs["context"] = args[1]
except:
...

try:
if args[2]:
kwargs["content_type"] = args[2]
except:
...

try:
if args[3]:
kwargs["status"] = args[3]
except:
...

try:
if args[4]:
kwargs["using"] = args[4]
except:
...

if "context" in kwargs:
kwargs.update(kwargs["context"])
del kwargs["context"]

if "academy" in kwargs:
kwargs["academy"] = kwargs["academy"].id

return JsonResponse(kwargs, status=kwargs["status"])

monkeypatch.setattr(
shortcuts,
"render",
MagicMock(side_effect=redirect_url),
)
yield


b = os.urandom(16)


@pytest.fixture(autouse=True)
def setup(monkeypatch: pytest.MonkeyPatch, db):
def setup(monkeypatch: pytest.MonkeyPatch, db, patch_render):

monkeypatch.setattr("os.urandom", lambda _: b)
monkeypatch.setattr("breathecode.authenticate.tasks.create_user_from_invite.delay", MagicMock())
Expand Down Expand Up @@ -164,7 +109,6 @@ def test_no_callback_url(database: capy.Database, client: APIClient, format: cap

def test_redirect_to_google(database: capy.Database, client: APIClient, format: capy.Format, utc_now: datetime):
model = database.create(token=1, user=1)
print(utc_now)
url = reverse_lazy("authenticate:academy_google") + f"?token={model.token.key}&url={callback}"
response = client.get(url, headers={"Academy": 1})

Expand Down Expand Up @@ -194,13 +138,14 @@ def test_no_capability_with_academy_settings(
database: capy.Database, client: APIClient, format: capy.Format, utc_now: datetime, academy_settings: str
):
model = database.create(token=1, user=1)
print(utc_now)
url = (
reverse_lazy("authenticate:academy_google")
+ f"?token={model.token.key}&url={callback}&academysettings={academy_settings}"
)
response = client.get(url, headers={"Academy": 1})

print(response.content)

assert response.status_code == status.HTTP_403_FORBIDDEN
json = response.json()
assert json == {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,8 @@

@pytest.fixture(autouse=True)
def setup(db, fake, monkeypatch: pytest.MonkeyPatch):
# def is_enabled(feature, context, default):
# if feature == "payments.can_access":
# return True

# return False

# m = MagicMock(side_effect=is_enabled)

monkeypatch.setenv("APP_URL", fake.url())
# monkeypatch.setattr(feature, "is_enabled", m)

yield

Expand All @@ -56,9 +48,6 @@ def __init__(self, monkeypatch: pytest.MonkeyPatch):
self.can_access = True
self.bypass_consumption = False

# def __call__(self, feature, context, default):
# ...

def setup(self):
def is_enabled(feature, context, default):
if feature == "payments.can_access":
Expand Down Expand Up @@ -3201,8 +3190,6 @@ def test_with_mentor_profile__redirect_to_session__saas__bypass_consumption_fals
for x in ["ACTIVE", "UNLISTED"]
]

print(1, feature.is_enabled)

id = 0
for mentor_profile in mentor_profile_cases:
id += 1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,7 @@ def test_subscription_process_to_charge(self):
"status": "RENEWAL",
"user_id": 1,
"was_delivered": True,
"chosen_period": "MONTH",
}
),
],
Expand Down
61 changes: 33 additions & 28 deletions breathecode/utils/tests/views/tests_private_view.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,24 @@
import json
from unittest.mock import MagicMock, call, patch
from rest_framework.test import APIRequestFactory
import breathecode.utils.views as views
from rest_framework import status
from django.contrib.sessions.backends.db import SessionStore

import pytest
from django.contrib import messages
from django.contrib.sessions.backends.db import SessionStore
from django.http import JsonResponse
from rest_framework import status
from rest_framework.test import APIRequestFactory

import breathecode.utils.views as views

from ..mixins import UtilsTestCase

PERMISSION = "can_kill_kenny"


@pytest.fixture(autouse=True)
def setup(db, patch_render): ...


def build_view(*args, **kwargs):

@views.private_view(*args, **kwargs)
Expand Down Expand Up @@ -147,21 +154,20 @@ def test_with_token__passing_permission(self):
request.session = session

view = build_view("can_kill_kenny")

response = view(request, id=1)

url_hash = self.bc.format.to_base64(f"/they-killed-kenny?token={model.token}")
content = self.bc.format.from_bytes(response.content, "utf-8")

self.assertEqual(content, "")
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
self.assertEqual(response.url, f"/v1/auth/view/login?attempt=1&url={url_hash}")
self.bc.check.calls(
messages.add_message.call_args_list,
[
call(request, messages.ERROR, "You don't have permission can_kill_kenny to access this view"),
],
self.assertEqual(
json.loads(response.content),
{
"status": 403,
"_template": "message.html",
"MESSAGE": "You don't have permission can_kill_kenny to access this view",
"BUTTON": None,
"BUTTON_TARGET": "_blank",
"LINK": None,
},
)
self.bc.check.calls(messages.add_message.call_args_list, [])

# Given: 1 Token
# When: with token, auth url and no permission
Expand All @@ -177,21 +183,20 @@ def test_with_token__passing_permission__auth_url(self):

url = self.bc.fake.url()
view = build_view("can_kill_kenny", url)

response = view(request, id=1)

url_hash = self.bc.format.to_base64(f"/they-killed-kenny?token={model.token}")
content = self.bc.format.from_bytes(response.content, "utf-8")

self.assertEqual(content, "")
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
self.assertEqual(response.url, f"{url}?attempt=1&url={url_hash}")
self.bc.check.calls(
messages.add_message.call_args_list,
[
call(request, messages.ERROR, "You don't have permission can_kill_kenny to access this view"),
],
self.assertEqual(
json.loads(response.content),
{
"status": 403,
"_template": "message.html",
"MESSAGE": "You don't have permission can_kill_kenny to access this view",
"BUTTON": None,
"BUTTON_TARGET": "_blank",
"LINK": None,
},
)
self.bc.check.calls(messages.add_message.call_args_list, [])

# Given: 1 Token
# When: with token and not auth url
Expand Down
55 changes: 55 additions & 0 deletions conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
import pytest
from capyc.pytest.core.fixtures import Random
from capyc.pytest.django.fixtures.signals import Signals
from django import shortcuts
from django.core.cache import cache
from django.http import JsonResponse
from django.utils import timezone
from linked_services.django import actions
from rest_framework.test import APIClient
Expand Down Expand Up @@ -341,3 +343,56 @@ def wrapper() -> dict[str, Any]:
}

yield wrapper


@pytest.fixture
def patch_render(monkeypatch: pytest.MonkeyPatch):
def redirect_url(*args, **kwargs):

if args:
args = args[1:]

if args:
try:
kwargs["_template"] = args[0]
except Exception:
...

try:
kwargs["context"] = args[1]
except Exception:
...

try:
if args[2]:
kwargs["content_type"] = args[2]
except Exception:
...

try:
if args[3]:
kwargs["status"] = args[3]
except Exception:
...

try:
if args[4]:
kwargs["using"] = args[4]
except Exception:
...

if "context" in kwargs:
kwargs.update(kwargs["context"])
del kwargs["context"]

if "academy" in kwargs:
kwargs["academy"] = kwargs["academy"].id

return JsonResponse(kwargs, status=kwargs["status"])

monkeypatch.setattr(
shortcuts,
"render",
MagicMock(side_effect=redirect_url),
)
yield
Loading

0 comments on commit 6c17075

Please sign in to comment.