From 7a5ea266109c094453a34cb2ead6520f4dbdace0 Mon Sep 17 00:00:00 2001 From: Oksamies Date: Fri, 8 Dec 2023 20:29:26 +0200 Subject: [PATCH] Add tests to UserDeleteView endpoint --- .../api/cyberstorm/tests/test_user.py | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 django/thunderstore/api/cyberstorm/tests/test_user.py diff --git a/django/thunderstore/api/cyberstorm/tests/test_user.py b/django/thunderstore/api/cyberstorm/tests/test_user.py new file mode 100644 index 000000000..e40ee0f78 --- /dev/null +++ b/django/thunderstore/api/cyberstorm/tests/test_user.py @@ -0,0 +1,67 @@ +import json + +import pytest +from django.contrib.auth import get_user_model +from rest_framework.test import APIClient + +from thunderstore.core.types import UserType +from thunderstore.repository.factories import UserFactory + +User = get_user_model() + + +@pytest.mark.django_db +def test_user_delete__when_deleting_own_account__succeeds( + api_client: APIClient, + user: UserType, +): + api_client.force_authenticate(user) + response = api_client.post( + f"/api/cyberstorm/user/{user.username}/delete/", + json.dumps({"verification": user.username}), + content_type="application/json", + ) + + assert response.status_code == 200 + response_json = response.json() + assert response_json["username"] == user.username + + with pytest.raises(User.DoesNotExist) as e: + User.objects.get(pk=user.pk) + assert "User matching query does not exist." in str(e.value) + + +@pytest.mark.django_db +def test_user_delete__when_deleting_others_account__fails( + api_client: APIClient, + user: UserType, +): + user2 = UserFactory() + api_client.force_authenticate(user2) + response = api_client.post( + f"/api/cyberstorm/user/{user.username}/delete/", + json.dumps({"verification": user.username}), + content_type="application/json", + ) + + assert response.status_code == 403 + assert response.json()["detail"] == "You can only delete your own account" + assert User.objects.filter(pk=user.pk).count() == 1 + + +@pytest.mark.django_db +def test_user_delete__when_missing_verification_parameter__fails( + api_client: APIClient, + user: UserType, +): + api_client.force_authenticate(user) + response = api_client.post( + f"/api/cyberstorm/user/{user.username}/delete/", + json.dumps({"verification": "TotallyNotCorrectUsername"}), + content_type="application/json", + ) + + assert response.status_code == 400 + response_json = response.json() + assert "Invalid verification" in response_json["verification"] + assert User.objects.filter(pk=user.pk).count() == 1