Skip to content

Commit

Permalink
PB-1108 Add delete user endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
msom committed Oct 30, 2024
1 parent 36b9a53 commit 2361672
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
20 changes: 20 additions & 0 deletions app/access/api.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from cognito.utils.user import delete_user
from ninja import Router
from ninja.errors import HttpError

from django.http import HttpRequest
from django.http import HttpResponse
from django.shortcuts import get_object_or_404

from .models import User
Expand Down Expand Up @@ -42,3 +45,20 @@ def users(request: HttpRequest) -> dict[str, list[UserSchema]]:
models = User.objects.all()
responses = [user_to_response(model) for model in models]
return {"items": responses}


@router.delete("users/{username}")
def delete(request: HttpRequest, username: str) -> HttpResponse:
"""
Delete the user with the given username.
Return HTTP status code
- 204 (No Content) if the user has been deleted
- 404 (Not Found) if there is no user with the given username
"""
model = get_object_or_404(User, username=username)
deleted = delete_user(model)
if not deleted:
raise HttpError(503, "Service Unavailable. Please retry later.")
model.delete()
return HttpResponse(status=204)
31 changes: 31 additions & 0 deletions app/access/tests/test_api.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from unittest.mock import patch

from access.api import router
from access.api import user_to_response
from access.models import User
Expand Down Expand Up @@ -108,3 +110,32 @@ def test_get_users_returns_users_ordered_by_id(self):
},
]
}

@patch('access.api.delete_user', return_value=True)
def test_delete_user_deletes_user(self, mock):
client = TestClient(router)
response = client.delete("users/dude")

assert response.status_code == 204
assert response.content == b''
assert User.objects.count() == 0

@patch('access.api.delete_user', return_value=False)
def test_delete_user_returns_404_if_nonexisting(self, mock):

client = TestClient(router)
response = client.delete("users/lebowski")

assert response.status_code == 404
assert response.data == {"detail": "Not Found"}
assert User.objects.count() == 1

@patch('access.api.delete_user', return_value=False)
def test_delete_user_returns_503_if_cognito_down(self, mock):

client = TestClient(router)
response = client.delete("users/dude")

assert response.status_code == 503
assert response.data == {'detail': 'Service Unavailable. Please retry later.'}
assert User.objects.count() == 1

0 comments on commit 2361672

Please sign in to comment.