Skip to content

Commit

Permalink
refactored to remove unnecessary commands
Browse files Browse the repository at this point in the history
  • Loading branch information
proafxin committed Jun 16, 2024
1 parent 3930489 commit ec42985
Show file tree
Hide file tree
Showing 12 changed files with 53 additions and 70 deletions.
4 changes: 2 additions & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@

from tracker.db.session import get_db
from tracker.models.base import Base
from tracker.views.bug import router as bug_router
from tracker.views.story import router as story_router
from tracker.routers.bug import router as bug_router
from tracker.routers.story import router as story_router

SQLALCHEMY_DATABASE_URL = "sqlite+aiosqlite:///./test_db.db"

Expand Down
21 changes: 16 additions & 5 deletions tests/test_bug.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import pytest
from fastapi import status
from httpx import AsyncClient

from tests.common import detail_not_found


class TestStory:
class TestBug:
async def __test_bug(self, bug: dict):
assert isinstance(bug, dict)
assert "id" in bug
Expand All @@ -22,14 +23,24 @@ async def test_create(self, client: AsyncClient) -> None:
"story_id": 1,
}
response = await client.post(url="/bugs/", json=json)
assert response.status_code == 200
assert response.status_code == status.HTTP_200_OK
bug = response.json()
await self.__test_bug(bug=bug)

@pytest.mark.asyncio
async def test_create_exception(self, client: AsyncClient) -> None:
json = {
"title": "Test Bug",
"description": "Description of Test Bug",
"story_id": 100,
}
response = await client.post(url="/bugs/", json=json)
assert response.status_code == status.HTTP_404_NOT_FOUND

@pytest.mark.asyncio
async def test_get(self, client: AsyncClient) -> None:
response = await client.get(url="/bugs/")
assert response.status_code == 200
assert response.status_code == status.HTTP_200_OK

bugs = response.json()
assert isinstance(bugs, list)
Expand All @@ -39,13 +50,13 @@ async def test_get(self, client: AsyncClient) -> None:
@pytest.mark.asyncio
async def test_get_by_id(self, client: AsyncClient) -> None:
response = await client.get(url="/bugs/1")
assert response.status_code == 200
assert response.status_code == status.HTTP_200_OK
bug = response.json()
await self.__test_bug(bug=bug)

@pytest.mark.asyncio
async def test_get_not_found(self, client: AsyncClient) -> None:
response = await client.get(url="/bugs/2")
assert response.status_code == 404
assert response.status_code == status.HTTP_404_NOT_FOUND
error = response.json()
detail_not_found(error=error)
9 changes: 5 additions & 4 deletions tests/test_story.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import pytest
from fastapi import status
from httpx import AsyncClient

from tests.common import detail_not_found
Expand All @@ -15,14 +16,14 @@ async def __test_story(self, story: dict):
async def test_create(self, client: AsyncClient) -> None:
json = {"name": "Test Story"}
response = await client.post(url="/stories/", json=json)
assert response.status_code == 200
assert response.status_code == status.HTTP_200_OK
story = response.json()
await self.__test_story(story=story)

@pytest.mark.asyncio
async def test_get(self, client: AsyncClient) -> None:
response = await client.get(url="/stories/")
assert response.status_code == 200
assert response.status_code == status.HTTP_200_OK

data = response.json()
assert isinstance(data, list)
Expand All @@ -32,13 +33,13 @@ async def test_get(self, client: AsyncClient) -> None:
@pytest.mark.asyncio
async def test_get_by_id(self, client: AsyncClient) -> None:
response = await client.get(url="/stories/1")
assert response.status_code == 200
assert response.status_code == status.HTTP_200_OK
story = response.json()
await self.__test_story(story=story)

@pytest.mark.asyncio
async def test_get_not_found(self, client: AsyncClient) -> None:
response = await client.get(url="/stories/2")
assert response.status_code == 404
assert response.status_code == status.HTTP_404_NOT_FOUND
error = response.json()
detail_not_found(error=error)
4 changes: 2 additions & 2 deletions tracker/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
from fastapi import FastAPI

from tracker.db.session import engine
from tracker.views.bug import router as bug_router
from tracker.views.story import router as story_router
from tracker.routers.bug import router as bug_router
from tracker.routers.story import router as story_router


async def configure_router():
Expand Down
3 changes: 0 additions & 3 deletions tracker/models/bug.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,3 @@ class Bug(Base):

class Config:
orm_mode = True

def __repr__(self) -> str:
return f"{self.title}, {self.story_id}"
File renamed without changes.
4 changes: 2 additions & 2 deletions tracker/serializers/bug.py → tracker/responses/bug.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

from pydantic import ConfigDict

from tracker.serializers.base import Base
from tracker.serializers.story import StoryOutput
from tracker.responses.base import Base
from tracker.responses.story import StoryOutput


class BugBase(Base):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from pydantic import ConfigDict

from tracker.serializers.base import Base
from tracker.responses.base import Base


class StoryInput(Base):
Expand Down
12 changes: 4 additions & 8 deletions tracker/views/bug.py → tracker/routers/bug.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from sqlalchemy.ext.asyncio import AsyncSession

from tracker.db.session import get_db
from tracker.serializers.bug import BugInput, BugOutput
from tracker.responses.bug import BugInput, BugOutput
from tracker.services.bug import bug_by_id, bugs
from tracker.services.bug import create as create_bug

Expand All @@ -13,9 +13,7 @@

@router.post("/bugs/", response_model=BugOutput)
async def create(bug: BugInput, db: Annotated[AsyncSession, Depends(get_db)]):
obj = await create_bug(db=db, bug=bug)

return obj
return BugOutput.model_validate(await create_bug(db=db, bug=bug))


@router.get("/bugs/", response_model=list[BugOutput])
Expand All @@ -26,7 +24,5 @@ async def get(


@router.get("/bugs/{id}", response_model=BugOutput)
async def get_bug(id: int, db: Annotated[AsyncSession, Depends(get_db)]):
obj = await bug_by_id(db=db, id=id)

return obj
async def get_by_id(id: int, db: Annotated[AsyncSession, Depends(get_db)]):
return BugOutput.model_validate(await bug_by_id(db=db, id=id))
10 changes: 3 additions & 7 deletions tracker/views/story.py → tracker/routers/story.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from sqlalchemy.ext.asyncio import AsyncSession

from tracker.db.session import get_db
from tracker.serializers.story import StoryInput, StoryOutput
from tracker.responses.story import StoryInput, StoryOutput
from tracker.services.story import create as create_story
from tracker.services.story import stories, story_by_id

Expand All @@ -13,9 +13,7 @@

@router.post("/stories/", response_model=StoryOutput)
async def create(story: StoryInput, db: Annotated[AsyncSession, Depends(get_db)]):
obj = await create_story(db=db, story=story)

return obj
return await create_story(db=db, story=story)


@router.get("/stories/", response_model=list[StoryOutput])
Expand All @@ -27,6 +25,4 @@ async def get_stories(

@router.get("/stories/{id}", response_model=StoryOutput)
async def get_story(id: int, db: Annotated[AsyncSession, Depends(get_db)]):
obj = await story_by_id(db=db, id=id)

return obj
return StoryOutput.model_validate(await story_by_id(db=db, id=id))
43 changes: 13 additions & 30 deletions tracker/services/bug.py
Original file line number Diff line number Diff line change
@@ -1,54 +1,37 @@
from http import HTTPStatus
from typing import Sequence

from fastapi import HTTPException
from fastapi.encoders import jsonable_encoder
from fastapi import HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select

from tracker.models.bug import Bug
from tracker.serializers.bug import BugInput, BugOutput
from tracker.responses.bug import BugInput, BugOutput
from tracker.services.story import story_by_id


async def bug_by_id(db: AsyncSession, id: int) -> BugOutput | HTTPException:
async def bug_by_id(db: AsyncSession, id: int) -> Bug:
query = await db.execute(select(Bug).filter(Bug.id == id))
res = query.scalars().all()

if len(res) > 0:
return res[0]

raise HTTPException(status_code=HTTPStatus.NOT_FOUND)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)


def bug_output(bug: Bug) -> BugOutput:
story = jsonable_encoder(obj=bug.story)
bug_output = BugOutput(
id=int(bug.id),
title=bug.title,
description=bug.description,
story=story,
story_id=bug.story_id,
created_at=bug.created_at,
updated_at=bug.updated_at,
)
async def bugs(db: AsyncSession, skip: int = 0, limit: int = 10) -> Sequence[BugOutput]:
query = await db.execute(select(Bug).offset(skip).limit(limit=limit))

return bug_output


async def bugs(db: AsyncSession, skip: int = 0, limit: int = 10) -> list[BugOutput]:
bugs = await db.scalars(select(Bug).offset(offset=skip).limit(limit=limit))
output = []

for bug in bugs:
output.append(bug_output(bug=bug))

return output
return query.scalars().all()


async def create(db: AsyncSession, bug: BugInput) -> BugOutput:
story = await story_by_id(db=db, id=bug.story_id)
response = await story_by_id(db=db, id=bug.story_id)

if isinstance(response, HTTPException):
raise response

obj = Bug(**bug.model_dump(), story=story)
obj = Bug(**bug.model_dump(), story=response)

db.add(obj)
await db.commit()
Expand Down
11 changes: 5 additions & 6 deletions tracker/services/story.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
from http import HTTPStatus
from typing import Sequence

from fastapi import HTTPException
from fastapi import HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select

from tracker.models.story import Story
from tracker.serializers.story import StoryInput, StoryOutput
from tracker.responses.story import StoryInput, StoryOutput


async def stories(
Expand All @@ -17,14 +16,14 @@ async def stories(
return query.scalars().all()


async def story_by_id(db: AsyncSession, id: int) -> StoryOutput | HTTPException:
async def story_by_id(db: AsyncSession, id: int) -> Story:
query = await db.execute(select(Story).where(Story.id == id))
stories = query.scalars().all()

if len(stories) > 0:
return stories[0]

raise HTTPException(status_code=HTTPStatus.NOT_FOUND)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)


async def create(db: AsyncSession, story: StoryInput) -> StoryOutput:
Expand All @@ -34,4 +33,4 @@ async def create(db: AsyncSession, story: StoryInput) -> StoryOutput:
await db.commit()
await db.refresh(story_new)

return story_new
return StoryOutput.model_validate(story_new)

0 comments on commit ec42985

Please sign in to comment.