|
| 1 | +"""Tests for DELETE /users/{user_id}.""" |
| 2 | + |
| 3 | +import uuid |
| 4 | +from http import HTTPStatus |
| 5 | +from typing import NamedTuple |
| 6 | + |
| 7 | +import httpx # noqa: TC002 used at runtime by pytest fixtures |
| 8 | +import pytest |
| 9 | +import pytest_mock # noqa: TC002 used at runtime by pytest fixtures |
| 10 | +from sqlalchemy import text |
| 11 | +from sqlalchemy.exc import IntegrityError |
| 12 | +from sqlalchemy.ext.asyncio import AsyncConnection # noqa: TC002 used at runtime by pytest fixtures |
| 13 | + |
| 14 | +from core.errors import AccountHasResourcesError, ForbiddenError, UserNotFoundError |
| 15 | +from database.users import UserGroup |
| 16 | +from routers.openml.users import delete_user_account |
| 17 | +from tests.users import ADMIN_USER, OWNER_USER, SOME_USER, ApiKey |
| 18 | + |
| 19 | + |
| 20 | +async def test_delete_user_missing_auth(py_api: httpx.AsyncClient) -> None: |
| 21 | + response = await py_api.delete("/users/1") |
| 22 | + assert response.status_code == HTTPStatus.UNAUTHORIZED |
| 23 | + body = response.json() |
| 24 | + assert body["code"] == "103" |
| 25 | + assert body["detail"] == "No API key provided." |
| 26 | + |
| 27 | + |
| 28 | +class DisposableUser(NamedTuple): |
| 29 | + user_id: int |
| 30 | + api_key: str |
| 31 | + |
| 32 | + |
| 33 | +@pytest.fixture |
| 34 | +async def disposable_user(user_test: AsyncConnection) -> DisposableUser: |
| 35 | + api_key = uuid.uuid4().hex |
| 36 | + suffix = uuid.uuid4().hex[:10] |
| 37 | + username = f"tmp_user_{suffix}" |
| 38 | + email = f"{suffix}@openml-delete.test" |
| 39 | + |
| 40 | + await user_test.execute( |
| 41 | + text( |
| 42 | + """ |
| 43 | + INSERT INTO users ( |
| 44 | + ip_address, username, password, email, created_on, |
| 45 | + company, country, bio, session_hash |
| 46 | + ) VALUES ( |
| 47 | + '127.0.0.1', :username, 'x', :email, UNIX_TIMESTAMP(), |
| 48 | + '', '', '', :api_key |
| 49 | + ) |
| 50 | + """, |
| 51 | + ), |
| 52 | + parameters={"username": username, "email": email, "api_key": api_key}, |
| 53 | + ) |
| 54 | + uid_row = await user_test.execute(text("SELECT LAST_INSERT_ID() AS id")) |
| 55 | + (new_id,) = uid_row.one() |
| 56 | + await user_test.execute( |
| 57 | + text("INSERT INTO users_groups (user_id, group_id) VALUES (:uid, :gid)"), |
| 58 | + parameters={"uid": new_id, "gid": UserGroup.READ_WRITE.value}, |
| 59 | + ) |
| 60 | + return DisposableUser(user_id=new_id, api_key=api_key) |
| 61 | + # No explicit teardown: the ``user_test`` fixture rolls back at the end |
| 62 | + # of the test, which removes the rows inserted above. |
| 63 | + |
| 64 | + |
| 65 | +@pytest.mark.mut |
| 66 | +async def test_delete_user_api_success_self_delete( |
| 67 | + py_api: httpx.AsyncClient, |
| 68 | + user_test: AsyncConnection, |
| 69 | + disposable_user: DisposableUser, |
| 70 | + mocker: pytest_mock.MockerFixture, |
| 71 | +) -> None: |
| 72 | + log_info = mocker.patch("routers.openml.users.logger.info") |
| 73 | + |
| 74 | + response = await py_api.delete( |
| 75 | + f"/users/{disposable_user.user_id}", |
| 76 | + params={"api_key": disposable_user.api_key}, |
| 77 | + ) |
| 78 | + assert response.status_code == HTTPStatus.NO_CONTENT |
| 79 | + assert response.content == b"" |
| 80 | + |
| 81 | + exists = await user_test.execute( |
| 82 | + text("SELECT 1 FROM users WHERE id = :id LIMIT 1"), |
| 83 | + parameters={"id": disposable_user.user_id}, |
| 84 | + ) |
| 85 | + assert exists.one_or_none() is None |
| 86 | + |
| 87 | + log_info.assert_any_call( |
| 88 | + "User account {user_id} was removed.", |
| 89 | + user_id=disposable_user.user_id, |
| 90 | + ) |
| 91 | + |
| 92 | + |
| 93 | +@pytest.mark.mut |
| 94 | +async def test_delete_user_api_success_admin_deletes_disposable_user( |
| 95 | + py_api: httpx.AsyncClient, |
| 96 | + user_test: AsyncConnection, |
| 97 | + disposable_user: DisposableUser, |
| 98 | +) -> None: |
| 99 | + response = await py_api.delete( |
| 100 | + f"/users/{disposable_user.user_id}", |
| 101 | + params={"api_key": ApiKey.ADMIN}, |
| 102 | + ) |
| 103 | + assert response.status_code == HTTPStatus.NO_CONTENT |
| 104 | + assert response.content == b"" |
| 105 | + |
| 106 | + exists = await user_test.execute( |
| 107 | + text("SELECT 1 FROM users WHERE id = :id LIMIT 1"), |
| 108 | + parameters={"id": disposable_user.user_id}, |
| 109 | + ) |
| 110 | + assert exists.one_or_none() is None |
| 111 | + |
| 112 | + |
| 113 | +# ── Direct handler tests ── |
| 114 | + |
| 115 | + |
| 116 | +async def test_delete_user_direct_not_found( |
| 117 | + user_test: AsyncConnection, |
| 118 | + expdb_test: AsyncConnection, |
| 119 | +) -> None: |
| 120 | + with pytest.raises(UserNotFoundError, match=r"User 888888888 not found\.") as exc_info: |
| 121 | + await delete_user_account( |
| 122 | + user_id=888888888, |
| 123 | + current_user=ADMIN_USER, |
| 124 | + expdb=expdb_test, |
| 125 | + userdb=user_test, |
| 126 | + ) |
| 127 | + assert exc_info.value.status_code == HTTPStatus.NOT_FOUND |
| 128 | + assert exc_info.value.uri == UserNotFoundError.uri |
| 129 | + |
| 130 | + |
| 131 | +async def test_delete_user_direct_forbidden( |
| 132 | + user_test: AsyncConnection, |
| 133 | + expdb_test: AsyncConnection, |
| 134 | +) -> None: |
| 135 | + with pytest.raises( |
| 136 | + ForbiddenError, match=r"You may only delete your own user account\." |
| 137 | + ) as exc_info: |
| 138 | + await delete_user_account( |
| 139 | + user_id=ADMIN_USER.user_id, |
| 140 | + current_user=SOME_USER, |
| 141 | + expdb=expdb_test, |
| 142 | + userdb=user_test, |
| 143 | + ) |
| 144 | + assert exc_info.value.status_code == HTTPStatus.FORBIDDEN |
| 145 | + assert exc_info.value.uri == ForbiddenError.uri |
| 146 | + |
| 147 | + admin_row = await user_test.execute( |
| 148 | + text("SELECT 1 FROM users WHERE id = :id LIMIT 1"), |
| 149 | + parameters={"id": ADMIN_USER.user_id}, |
| 150 | + ) |
| 151 | + assert admin_row.one_or_none() is not None |
| 152 | + |
| 153 | + |
| 154 | +async def test_delete_user_direct_conflict_has_resources( |
| 155 | + user_test: AsyncConnection, |
| 156 | + expdb_test: AsyncConnection, |
| 157 | +) -> None: |
| 158 | + with pytest.raises(AccountHasResourcesError, match="Cannot delete this account") as exc_info: |
| 159 | + await delete_user_account( |
| 160 | + user_id=OWNER_USER.user_id, |
| 161 | + current_user=ADMIN_USER, |
| 162 | + expdb=expdb_test, |
| 163 | + userdb=user_test, |
| 164 | + ) |
| 165 | + assert exc_info.value.status_code == HTTPStatus.CONFLICT |
| 166 | + assert exc_info.value.uri == AccountHasResourcesError.uri |
| 167 | + |
| 168 | + owner_row = await user_test.execute( |
| 169 | + text("SELECT 1 FROM users WHERE id = :id LIMIT 1"), |
| 170 | + parameters={"id": OWNER_USER.user_id}, |
| 171 | + ) |
| 172 | + assert owner_row.one_or_none() is not None |
| 173 | + |
| 174 | + |
| 175 | +@pytest.mark.mut |
| 176 | +async def test_delete_user_integrity_error_logs_and_raises_conflict( |
| 177 | + user_test: AsyncConnection, |
| 178 | + expdb_test: AsyncConnection, |
| 179 | + disposable_user: DisposableUser, |
| 180 | + mocker: pytest_mock.MockerFixture, |
| 181 | +) -> None: |
| 182 | + mocker.patch( |
| 183 | + "database.users.delete_user_rows", |
| 184 | + side_effect=IntegrityError( |
| 185 | + "DELETE FROM users", {"user_id": disposable_user.user_id}, Exception("fk") |
| 186 | + ), |
| 187 | + ) |
| 188 | + log_error = mocker.patch("routers.openml.users.logger.error") |
| 189 | + |
| 190 | + with pytest.raises(AccountHasResourcesError, match="Cannot delete this account") as exc_info: |
| 191 | + await delete_user_account( |
| 192 | + user_id=disposable_user.user_id, |
| 193 | + current_user=ADMIN_USER, |
| 194 | + expdb=expdb_test, |
| 195 | + userdb=user_test, |
| 196 | + ) |
| 197 | + |
| 198 | + assert exc_info.value.status_code == HTTPStatus.CONFLICT |
| 199 | + log_error.assert_called_once_with( |
| 200 | + "Delete of user {user_id} failed with integrity error after pre-check.", |
| 201 | + user_id=disposable_user.user_id, |
| 202 | + ) |
0 commit comments