Skip to content

Commit

Permalink
refactor(api): fix type errors in vscode
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastianvitterso committed Nov 11, 2022
1 parent 225a530 commit fd40ccb
Show file tree
Hide file tree
Showing 9 changed files with 37 additions and 48 deletions.
10 changes: 5 additions & 5 deletions api/src/common/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def __init__(
self,
message: str = "The requested operation failed",
debug: str = "An unknown and unhandled exception occurred in the API",
extra: dict = None,
extra: dict | None = None,
status: int = 500,
):
self.status = status
Expand All @@ -47,7 +47,7 @@ def __init__(
self,
message: str = "You do not have the required permissions",
debug: str = "Action denied because of insufficient permissions",
extra: dict = None,
extra: dict | None = None,
):
super().__init__(message, debug, extra, request_status.HTTP_403_FORBIDDEN)
self.type = self.__class__.__name__
Expand All @@ -58,7 +58,7 @@ def __init__(
self,
message: str = "The requested resource could not be found",
debug: str = "The requested resource could not be found",
extra: dict = None,
extra: dict | None = None,
):
super().__init__(message, debug, extra, request_status.HTTP_404_NOT_FOUND)
self.type = self.__class__.__name__
Expand All @@ -69,7 +69,7 @@ def __init__(
self,
message: str = "Invalid data for the operation",
debug: str = "Unable to complete the requested operation with the given input values.",
extra: dict = None,
extra: dict | None = None,
):
super().__init__(message, debug, extra, request_status.HTTP_400_BAD_REQUEST)
self.type = self.__class__.__name__
Expand All @@ -80,7 +80,7 @@ def __init__(
self,
message: str = "The received data is invalid",
debug: str = "Values are invalid for requested operation.",
extra: dict = None,
extra: dict | None = None,
):
super().__init__(message, debug, extra, request_status.HTTP_422_UNPROCESSABLE_ENTITY)
self.type = self.__class__.__name__
Expand Down
4 changes: 2 additions & 2 deletions api/src/common/responses.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import functools
import traceback
from inspect import iscoroutinefunction
from typing import Callable, Type, TypeVar
from typing import Any, Callable, Type, TypeVar

from requests import HTTPError
from starlette import status
Expand All @@ -17,7 +17,7 @@
)
from common.logger import logger

responses = {
responses: dict[int | str, dict[str, Any]] = {
400: {"model": ErrorResponse, "content": {"application/json": {"example": BadRequestException().dict()}}},
401: {
"model": ErrorResponse,
Expand Down
10 changes: 7 additions & 3 deletions api/src/data_providers/clients/ClientInterface.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,17 @@ def insert_many(self, instances: List[M]):
pass

@abstractmethod
def delete_many(self, query: Dict):
def delete_many(self, filter: Dict):
pass

@abstractmethod
def find(self, filters: Dict) -> M:
def find(self, filter: Dict) -> M:
pass

@abstractmethod
def find_one(self, filters: Dict) -> Optional[M]:
def find_one(self, filter: Dict) -> Optional[M]:
pass

@abstractmethod
def delete_collection(self):
pass
20 changes: 10 additions & 10 deletions api/src/data_providers/clients/mongodb/MongoDatabaseClient.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from typing import Dict, List, Optional

from pymongo import MongoClient
from pymongo.collection import Cursor
from pymongo.cursor import Cursor
from pymongo.database import Database
from pymongo.errors import DuplicateKeyError
from pymongo.mongo_client import MongoClient

from common.exceptions import NotFoundException, ValidationException
from data_providers.clients.ClientInterface import ClientInterface
Expand All @@ -24,8 +24,8 @@ def wipe_db(self):
for database_name in databases_to_delete:
self.database.client.drop_database(database_name)

def delete_collection(self, collection: str):
self.database[collection].drop()
def delete_collection(self):
self.collection.drop()

def create(self, document: Dict) -> Dict:
try:
Expand Down Expand Up @@ -54,14 +54,14 @@ def delete(self, uid: str) -> bool:
result = self.collection.delete_one(filter={"_id": uid})
return result.deleted_count > 0

def find(self, filters: Dict) -> Cursor:
return self.collection.find(filter=filters)
def find(self, filter: Dict) -> Cursor:
return self.collection.find(filter=filter)

def find_one(self, filters: Dict) -> Optional[Dict]:
return self.collection.find_one(filter=filters)
def find_one(self, filter: Dict) -> Optional[Dict]:
return self.collection.find_one(filter=filter)

def insert_many(self, items: List[Dict]):
return self.collection.insert_many(items)

def delete_many(self, query: Dict):
return self.collection.delete_many(query)
def delete_many(self, filter: Dict):
return self.collection.delete_many(filter)
2 changes: 1 addition & 1 deletion api/src/data_providers/get_repository.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from pymongo import MongoClient
from pymongo.mongo_client import MongoClient

from config import config
from data_providers.clients.mongodb.MongoDatabaseClient import MongoDatabaseClient
Expand Down
2 changes: 1 addition & 1 deletion api/src/data_providers/repositories/TodoRepository.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def delete(self, todo_item_id: str) -> None:
raise NotFoundException

def delete_all(self) -> None:
self.client.delete_collection(self.client.collection_name)
self.client.delete_collection()

def get(self, todo_item_id: str) -> TodoItem:
todo_item = self.client.get(todo_item_id)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class TestWhoami:
def test_whoami(self, test_app: TestClient):
config.AUTH_ENABLED = True
config.TEST_TOKEN = True
user = User(user_id=1, username="foo", roles=["a"])
user = User(user_id="1", email="foo@bar.baz", roles=["a"])
headers = {"Authorization": f"Bearer {generate_mock_token(user)}"}
response = test_app.get("/whoami", headers=headers)
data = response.json()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,7 @@ def test_find(self, test_client: MongoDatabaseClient):
{"_id": "81549300", "name": "hello"},
{"_id": "1a2b", "name": "pingvin"},
{"_id": "987321", "name": "alberto"},
{
"_id": "987456",
"name": "alberto",
},
{"_id": "987456", "name": "alberto"},
]
test_client.collection.insert_many(documents)
assert list(test_client.find({})) == documents
Expand All @@ -53,10 +50,7 @@ def test_list(self, test_client: MongoDatabaseClient):
{"_id": "81549300", "name": "hello"},
{"_id": "1a2b", "name": "pingvin"},
{"_id": "987321", "name": "alberto"},
{
"_id": "987456",
"name": "alberto",
},
{"_id": "987456", "name": "alberto"},
]
test_client.collection.insert_many(documents)
assert test_client.list() == documents
Expand Down Expand Up @@ -92,22 +86,18 @@ def test_delete_collection(self, test_client: MongoDatabaseClient):
{"_id": "81549300", "name": "hello"},
{"_id": "1a2b", "name": "pingvin"},
{"_id": "987321", "name": "alberto"},
{
"_id": "987456",
"name": "alberto",
},
{"_id": "987456", "name": "alberto"},
]
test_client.collection.insert_many(documents)
original_collection = test_client.collection_name
# add second collection to TestDB:
test_client.database.create_collection("peppers")
active_collections = test_client.database.list_collection_names()
number_of_entries_in_original_collection = test_client.database[original_collection].count_documents({})
number_of_entries_in_original_collection = test_client.collection.count_documents({})
assert number_of_entries_in_original_collection > 0
assert len(active_collections) == 2
test_client.delete_collection(original_collection)
test_client.delete_collection()
assert test_client.database.list_collection_names() == ["peppers"]
assert test_client.database[original_collection].count_documents({}) == 0
assert test_client.collection.count_documents({}) == 0

def test_create_in_empty_database(self, test_client: MongoDatabaseClient):
document = {"_id": "1a2b", "name": "pingvin"}
Expand All @@ -121,10 +111,7 @@ def test_wipe_db(self, test_client: MongoDatabaseClient):
{"_id": "81549300", "name": "hello"},
{"_id": "1a2b", "name": "pingvin"},
{"_id": "987321", "name": "alberto"},
{
"_id": "987456",
"name": "alberto",
},
{"_id": "987456", "name": "alberto"},
]
test_client.collection.insert_many(documents)
original_database = test_client.database.client.list_database_names()[0]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,13 @@
from common.exceptions import NotFoundException, ValidationException
from data_providers.clients.mongodb.MongoDatabaseClient import MongoDatabaseClient
from data_providers.repositories.TodoRepository import TodoRepository
from data_providers.repository_interfaces.TodoRepositoryInterface import (
TodoRepositoryInterface,
)
from entities.TodoItem import TodoItem


class TestTodoRepository:
@pytest.fixture(autouse=True)
def _setup_repository(self, test_client: MongoDatabaseClient):
self.repository: TodoRepositoryInterface = TodoRepository(client=test_client)
self.repository = TodoRepository(client=test_client)

def test_create(self):
todo_item = TodoItem(id="1234", title="todo 1", user_id="xyz")
Expand All @@ -34,7 +31,8 @@ def test_find_item_that_exist(self):
{"_id": "987456", "title": "todo 4", "user_id": "abc"},
]
self.repository.client.insert_many(documents)
assert self.repository.find_one({"title": "todo 2", "user_id": "xyz"}).id == "1a2b"
todo_item = self.repository.find_one({"title": "todo 2", "user_id": "xyz"})
assert todo_item is not None and todo_item.id == "1a2b"

def test_find_item_that_does_not_exist(self):
documents = [
Expand Down

0 comments on commit fd40ccb

Please sign in to comment.