Skip to content
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

fix(library): Set library.keywords as empty array (M2-6857) #1396

Merged
merged 5 commits into from
Jun 14, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions src/apps/library/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ async def get_all_library_count(self, query_params: QueryParams) -> int:
async def get_all_library_items(
self,
query_params: QueryParams,
) -> list[LibraryItem]:
) -> list[LibrarySchema]:
query: Query = select(
LibrarySchema.id,
LibrarySchema.keywords,
Expand All @@ -70,8 +70,7 @@ async def get_all_library_items(
query = paging(query, query_params.page, query_params.limit)

results = await self._execute(query)

return [LibraryItem.from_orm(result) for result in results.all()]
return results.all() # noqa

async def get_library_item_by_id(self, id_: uuid.UUID) -> LibraryItem:
query: Query = select(
Expand Down
4 changes: 2 additions & 2 deletions src/apps/library/db/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ class LibrarySchema(Base):
ForeignKey("applet_histories.id_version", ondelete="RESTRICT"),
nullable=False,
)
keywords = Column(ARRAY(String))
search_keywords = Column(ARRAY(String))
keywords = Column(ARRAY(String), nullable=False, server_default="{}")
search_keywords = Column(ARRAY(String), nullable=False, server_default="{}")


class CartSchema(Base):
Expand Down
14 changes: 9 additions & 5 deletions src/apps/library/domain.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import uuid

from pydantic import BaseModel, Field
from pydantic import BaseModel, Field, validator

from apps.activities.domain.response_type_config import PerformanceTaskType
from apps.shared.domain import InternalModel, PublicModel


class AppletLibrary(InternalModel):
applet_id_version: str
keywords: list[str] | None = None
keywords: list[str]


class AppletLibraryFull(AppletLibrary):
Expand All @@ -22,12 +22,16 @@ class AppletLibraryInfo(PublicModel):

class AppletLibraryCreate(InternalModel):
applet_id: uuid.UUID
keywords: list[str] | None = None
keywords: list[str] = Field(default_factory=list)
name: str

@validator("keywords", pre=True)
def validate_keywords(cls, keywords: list[str] | None):
return keywords if keywords is not None else []


class AppletLibraryUpdate(InternalModel):
keywords: list[str] | None = None
keywords: list[str] = []
iwankrshkin marked this conversation as resolved.
Show resolved Hide resolved
name: str


Expand Down Expand Up @@ -84,7 +88,7 @@ class _LibraryItem(BaseModel):
about: dict[str, str] | None = None
image: str = ""
theme_id: uuid.UUID | None = None
keywords: list[str] | None = None
keywords: list[str] = Field(default_factory=list)
activities: list[LibraryItemActivity] | None = None
activity_flows: list[LibraryItemFlow] | None = None

Expand Down
4 changes: 2 additions & 2 deletions src/apps/library/fixtures/libraries.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
"is_deleted": false,
"id": "68aadd6c-eb20-4666-85aa-fd6264825c01",
"applet_id_version": "92917a56-d586-4613-b7aa-991f2c4b15b2_1.1.0",
"keywords": null,
"search_keywords": null
"keywords": {},
"search_keywords": {}
}
}
]
3 changes: 2 additions & 1 deletion src/apps/library/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,8 @@ async def get_applets_count(self, query_param: QueryParams) -> int:
async def get_all_applets(self, query_params: QueryParams) -> list[PublicLibraryItem]:
"""Get all applets for library."""

library_items = await LibraryCRUD(self.session).get_all_library_items(query_params)
library_schemas = await LibraryCRUD(self.session).get_all_library_items(query_params)
library_items = parse_obj_as(list[LibraryItem], library_schemas)

for library_item in library_items:
library_item = await self._get_full_library_item(library_item)
Expand Down
23 changes: 23 additions & 0 deletions src/apps/library/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -461,3 +461,26 @@ async def test_library_get_url_applet_version_does_not_exists(
res = resp.json()["result"]
assert len(res) == 1
assert res[0]["message"] == AppletVersionDoesNotExistError.message

@pytest.mark.parametrize(
"kw, exp_kw, exp_status, include_kw",
(
(["test", "test2"], ["test", "test2"], http.HTTPStatus.CREATED, True),
([], [], http.HTTPStatus.CREATED, True),
(None, [], http.HTTPStatus.CREATED, False),
(None, [], http.HTTPStatus.CREATED, True),
),
)
async def test_library_share_with_empty_kw(
self, client: TestClient, applet_one: AppletFull, tom: User, kw, exp_kw, exp_status, include_kw
):
client.login(tom)
data = dict(applet_id=applet_one.id, name="PHQ2")
if include_kw:
data["keywords"] = kw

response = await client.post(self.library_url, data=data)
assert response.status_code == exp_status
if exp_status == http.HTTPStatus.CREATED:
result = response.json()["result"]
assert result["keywords"] == exp_kw
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"""Library default keywords

Revision ID: c587d336f28e
Revises: 01115b529336
Create Date: 2024-06-13 14:24:39.035015

"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = "c587d336f28e"
down_revision = "01115b529336"
branch_labels = None
depends_on = None


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.execute("UPDATE library SET keywords = '{}'::varchar[] WHERE keywords IS NULL")
op.execute("UPDATE library SET search_keywords = '{}'::varchar[] WHERE search_keywords IS NULL")
op.alter_column(
"library",
"keywords",
existing_type=postgresql.ARRAY(sa.VARCHAR()),
nullable=False,
server_default='{}'
)
op.alter_column(
"library",
"search_keywords",
existing_type=postgresql.ARRAY(sa.VARCHAR()),
nullable=False,
server_default='{}'
)
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column(
"library",
"search_keywords",
existing_type=postgresql.ARRAY(sa.VARCHAR()),
nullable=True,
)
op.alter_column(
"library",
"keywords",
existing_type=postgresql.ARRAY(sa.VARCHAR()),
nullable=True,
)
# ### end Alembic commands ###
Loading