-
-
Notifications
You must be signed in to change notification settings - Fork 50
Migrate POST /setup/untag endpoint (#65) #246
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
39741dd
migration of /setup
d41b9ce
Add setups_test.py and refactor fetch_user to use fetch_user_or_raise
191d610
Merge branch 'main' into issue/65
PGijsbers b63794d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 78fb061
Update PR to use async, add docstrings, partial RFC updates
PGijsbers cea7333
Introduce RFC9457 responses, separate out test cases
PGijsbers c55f9e7
Preserve behavior of returning pre-existing tags
PGijsbers 3da8be3
Assert RFC9457 responses
PGijsbers 6b4073b
Avoid committing changes to the database
PGijsbers File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| """All database operations that directly operate on setups.""" | ||
|
|
||
| from sqlalchemy import text | ||
| from sqlalchemy.engine import Row | ||
| from sqlalchemy.ext.asyncio import AsyncConnection | ||
|
|
||
|
|
||
| async def get(setup_id: int, connection: AsyncConnection) -> Row | None: | ||
| """Get the setup with id `setup_id` from the database.""" | ||
| row = await connection.execute( | ||
| text( | ||
| """ | ||
| SELECT * | ||
| FROM algorithm_setup | ||
| WHERE sid = :setup_id | ||
| """, | ||
| ), | ||
| parameters={"setup_id": setup_id}, | ||
| ) | ||
| return row.first() | ||
|
|
||
|
|
||
| async def get_tags(setup_id: int, connection: AsyncConnection) -> list[Row]: | ||
| """Get all tags for setup with `setup_id` from the database.""" | ||
| rows = await connection.execute( | ||
| text( | ||
| """ | ||
| SELECT * | ||
| FROM setup_tag | ||
| WHERE id = :setup_id | ||
| """, | ||
| ), | ||
| parameters={"setup_id": setup_id}, | ||
| ) | ||
| return list(rows.all()) | ||
|
|
||
|
|
||
| async def untag(setup_id: int, tag: str, connection: AsyncConnection) -> None: | ||
| """Remove tag `tag` from setup with id `setup_id`.""" | ||
| await connection.execute( | ||
| text( | ||
| """ | ||
| DELETE FROM setup_tag | ||
| WHERE id = :setup_id AND tag = :tag | ||
| """, | ||
| ), | ||
| parameters={"setup_id": setup_id, "tag": tag}, | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| """All endpoints that relate to setups.""" | ||
|
|
||
| from typing import Annotated | ||
|
|
||
| from fastapi import APIRouter, Body, Depends | ||
| from sqlalchemy.ext.asyncio import AsyncConnection | ||
|
|
||
| import database.setups | ||
| from core.errors import SetupNotFoundError, TagNotFoundError, TagNotOwnedError | ||
| from database.users import User, UserGroup | ||
| from routers.dependencies import expdb_connection, fetch_user_or_raise | ||
| from routers.types import SystemString64 | ||
|
|
||
| router = APIRouter(prefix="/setup", tags=["setup"]) | ||
|
|
||
|
|
||
| @router.post(path="/untag") | ||
| async def untag_setup( | ||
| setup_id: Annotated[int, Body()], | ||
| tag: Annotated[str, SystemString64], | ||
| user: Annotated[User, Depends(fetch_user_or_raise)], | ||
| expdb_db: Annotated[AsyncConnection, Depends(expdb_connection)], | ||
| ) -> dict[str, dict[str, str | list[str]]]: | ||
| """Remove tag `tag` from setup with id `setup_id`.""" | ||
| if not await database.setups.get(setup_id, expdb_db): | ||
| msg = f"Setup {setup_id} not found." | ||
| raise SetupNotFoundError(msg) | ||
|
|
||
| setup_tags = await database.setups.get_tags(setup_id, expdb_db) | ||
| matched_tag_row = next((t for t in setup_tags if t.tag.casefold() == tag.casefold()), None) | ||
|
|
||
| if not matched_tag_row: | ||
| msg = f"Setup {setup_id} does not have tag {tag!r}." | ||
| raise TagNotFoundError(msg) | ||
|
|
||
| if matched_tag_row.uploader != user.user_id and UserGroup.ADMIN not in await user.get_groups(): | ||
| msg = ( | ||
| f"You may not remove tag {tag!r} of setup {setup_id} because it was not created by you." | ||
| ) | ||
| raise TagNotOwnedError(msg) | ||
|
|
||
| await database.setups.untag(setup_id, matched_tag_row.tag, expdb_db) | ||
| remaining_tags = [t.tag.casefold() for t in setup_tags if t != matched_tag_row] | ||
| return {"setup_untag": {"id": str(setup_id), "tag": remaining_tags}} | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
149 changes: 149 additions & 0 deletions
149
tests/routers/openml/migration/setups_migration_test.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,149 @@ | ||
| import contextlib | ||
| import re | ||
| from collections.abc import AsyncGenerator, Iterable | ||
| from http import HTTPStatus | ||
|
|
||
| import httpx | ||
| import pytest | ||
| from sqlalchemy import text | ||
| from sqlalchemy.ext.asyncio import AsyncConnection | ||
|
|
||
| from tests.users import OWNER_USER, ApiKey | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "api_key", | ||
| [ApiKey.ADMIN, ApiKey.SOME_USER, ApiKey.OWNER_USER], | ||
| ids=["Administrator", "non-owner", "tag owner"], | ||
| ) | ||
| @pytest.mark.parametrize( | ||
| "other_tags", | ||
| [[], ["some_other_tag"], ["foo_some_other_tag", "bar_some_other_tag"]], | ||
| ids=["none", "one tag", "two tags"], | ||
| ) | ||
| async def test_setup_untag_response_is_identical_when_tag_exists( | ||
| api_key: str, | ||
| other_tags: list[str], | ||
| py_api: httpx.AsyncClient, | ||
| php_api: httpx.AsyncClient, | ||
| expdb_test: AsyncConnection, | ||
| ) -> None: | ||
| setup_id = 1 | ||
| tag = "totally_new_tag_for_migration_testing" | ||
|
|
||
| @contextlib.asynccontextmanager | ||
| async def temporary_tags( | ||
| tags: Iterable[str], setup_id: int, *, persist: bool = False | ||
| ) -> AsyncGenerator[None]: | ||
| for tag in tags: | ||
| await expdb_test.execute( | ||
| text( | ||
| "INSERT INTO setup_tag(`id`,`tag`,`uploader`) VALUES (:setup_id, :tag, :user_id);" # noqa: E501 | ||
| ), | ||
| parameters={"setup_id": setup_id, "tag": tag, "user_id": OWNER_USER.user_id}, | ||
| ) | ||
| if persist: | ||
| await expdb_test.commit() | ||
| yield | ||
| for tag in tags: | ||
| await expdb_test.execute( | ||
| text("DELETE FROM setup_tag WHERE `id`=:setup_id AND `tag`=:tag"), | ||
| parameters={"setup_id": setup_id, "tag": tag}, | ||
| ) | ||
| if persist: | ||
| await expdb_test.commit() | ||
|
|
||
| all_tags = [tag, *other_tags] | ||
| async with temporary_tags(tags=all_tags, setup_id=setup_id, persist=True): | ||
| original = await php_api.post( | ||
| "/setup/untag", | ||
| data={"api_key": api_key, "tag": tag, "setup_id": setup_id}, | ||
| ) | ||
|
|
||
| # expdb_test transaction shared with Python API, | ||
| # no commit needed and rolled back at the end of the test | ||
| async with temporary_tags(tags=all_tags, setup_id=setup_id): | ||
| new = await py_api.post( | ||
| f"/setup/untag?api_key={api_key}", | ||
| json={"setup_id": setup_id, "tag": tag}, | ||
| ) | ||
|
|
||
| if new.status_code == HTTPStatus.OK: | ||
| assert original.status_code == new.status_code | ||
| original_untag = original.json()["setup_untag"] | ||
| new_untag = new.json()["setup_untag"] | ||
| assert original_untag["id"] == new_untag["id"] | ||
| if tags := original_untag.get("tag"): | ||
| if isinstance(tags, str): | ||
| assert tags == new_untag["tag"][0] | ||
| else: | ||
| assert tags == new_untag["tag"] | ||
| else: | ||
| assert new_untag["tag"] == [] | ||
| return | ||
|
|
||
| code, message = original.json()["error"].values() | ||
| assert original.status_code == HTTPStatus.PRECONDITION_FAILED | ||
| assert new.status_code == HTTPStatus.FORBIDDEN | ||
| assert code == new.json()["code"] | ||
| assert message == "Tag is not owned by you" | ||
PGijsbers marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| assert re.match( | ||
| r"You may not remove tag \S+ of setup \d+ because it was not created by you.", | ||
| new.json()["detail"], | ||
| ) | ||
|
|
||
|
|
||
| async def test_setup_untag_response_is_identical_setup_doesnt_exist( | ||
| py_api: httpx.AsyncClient, | ||
| php_api: httpx.AsyncClient, | ||
| ) -> None: | ||
| setup_id = 999999 | ||
| tag = "totally_new_tag_for_migration_testing" | ||
| api_key = ApiKey.SOME_USER | ||
|
|
||
| original = await php_api.post( | ||
| "/setup/untag", | ||
| data={"api_key": api_key, "tag": tag, "setup_id": setup_id}, | ||
| ) | ||
|
|
||
| new = await py_api.post( | ||
| f"/setup/untag?api_key={api_key}", | ||
| json={"setup_id": setup_id, "tag": tag}, | ||
| ) | ||
|
|
||
| assert original.status_code == HTTPStatus.PRECONDITION_FAILED | ||
| assert new.status_code == HTTPStatus.NOT_FOUND | ||
| assert original.json()["error"]["message"] == "Entity not found." | ||
| assert original.json()["error"]["code"] == new.json()["code"] | ||
| assert re.match( | ||
| r"Setup \d+ not found.", | ||
| new.json()["detail"], | ||
| ) | ||
|
|
||
|
|
||
| async def test_setup_untag_response_is_identical_tag_doesnt_exist( | ||
| py_api: httpx.AsyncClient, | ||
| php_api: httpx.AsyncClient, | ||
| ) -> None: | ||
| setup_id = 1 | ||
| tag = "totally_new_tag_for_migration_testing" | ||
| api_key = ApiKey.SOME_USER | ||
|
|
||
| original = await php_api.post( | ||
| "/setup/untag", | ||
| data={"api_key": api_key, "tag": tag, "setup_id": setup_id}, | ||
| ) | ||
|
|
||
| new = await py_api.post( | ||
| f"/setup/untag?api_key={api_key}", | ||
| json={"setup_id": setup_id, "tag": tag}, | ||
| ) | ||
|
|
||
| assert original.status_code == HTTPStatus.PRECONDITION_FAILED | ||
| assert new.status_code == HTTPStatus.NOT_FOUND | ||
| assert original.json()["error"]["code"] == new.json()["code"] | ||
| assert original.json()["error"]["message"] == "Tag not found." | ||
| assert re.match( | ||
| r"Setup \d+ does not have tag '\S+'.", | ||
| new.json()["detail"], | ||
| ) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.