From 3a2a3e456b0268c4ce758e47e24e19e3719fc4b0 Mon Sep 17 00:00:00 2001 From: Jakub Miazek Date: Wed, 17 Apr 2024 10:38:54 +0200 Subject: [PATCH] black --- greens/config.py | 4 ++-- greens/main.py | 8 ++++++-- greens/routers/v1/vegs.py | 1 + greens/services/repository.py | 19 ++++++++++++++----- greens/utils.py | 10 ++++++++-- tests/conftest.py | 12 ++++++++---- tests/test_routers.py | 24 ++++++++++++------------ tests/test_schemas.py | 9 +++++++-- tests/test_vegs_api.py | 8 ++++---- 9 files changed, 62 insertions(+), 33 deletions(-) diff --git a/greens/config.py b/greens/config.py index 30152b3..d7f9e8f 100644 --- a/greens/config.py +++ b/greens/config.py @@ -7,6 +7,7 @@ class Settings(BaseSettings): """Settings for the application""" + environment: str = os.getenv("ENVIRONMENT", "local") testing: str = os.getenv("TESTING", "0") up: str = os.getenv("UP", "up") @@ -33,8 +34,7 @@ def mongodb_url(self) -> MongoDsn: port=self.MONGODB_PORT, username=self.MONGODB_USER, password=self.MONGODB_PASSWORD, - - path=self.MONGODB_PARAMS + path=self.MONGODB_PARAMS, ) diff --git a/greens/main.py b/greens/main.py index a09ea7f..22363e2 100644 --- a/greens/main.py +++ b/greens/main.py @@ -15,8 +15,12 @@ async def lifespan(app: FastAPI): app.state.logger = get_logger(__name__) app.state.logger.info("Starting greens on your farmland...mmm") - app.state.mongo_client, app.state.mongo_db, app.state.mongo_collection = await init_mongo( - global_settings.mongodb_database, global_settings.mongodb_url, global_settings.mongodb_collection + app.state.mongo_client, app.state.mongo_db, app.state.mongo_collection = ( + await init_mongo( + global_settings.mongodb_database, + global_settings.mongodb_url, + global_settings.mongodb_collection, + ) ) try: yield diff --git a/greens/routers/v1/vegs.py b/greens/routers/v1/vegs.py index 0abe7dc..3842eb1 100644 --- a/greens/routers/v1/vegs.py +++ b/greens/routers/v1/vegs.py @@ -47,4 +47,5 @@ async def get_document(object_id: ObjectIdField): except (ValueError, TypeError) as exception: raise NotFoundHTTPException(msg=str(exception)) from exception + # TODO: PUT for replace aka set PATCH for update ? diff --git a/greens/services/repository.py b/greens/services/repository.py index 592f2c0..58d2108 100644 --- a/greens/services/repository.py +++ b/greens/services/repository.py @@ -19,7 +19,9 @@ async def retrieve_document(document_id: str, collection: str) -> dict: :return: """ document_filter = {"_id": ObjectId(document_id)} - if document := await greens.app.state.mongo_collection[collection].find_one(document_filter): + if document := await greens.app.state.mongo_collection[collection].find_one( + document_filter + ): return await document_id_helper(document) else: raise ValueError(f"No document found for {document_id=} in {collection=}") @@ -33,8 +35,9 @@ async def create_document(document, collection: str) -> InsertOneResult: :return: """ try: - document: InsertOneResult = await greens.app.state.mongo_collection[collection].insert_one( - document.model_dump()) + document: InsertOneResult = await greens.app.state.mongo_collection[ + collection + ].insert_one(document.model_dump()) return document except WriteError as e: # TODO: this not make sense as id from mongo will be always unique if we not pass it @@ -45,6 +48,12 @@ async def get_mongo_meta() -> dict: list_databases = await greens.app.state.mongo_client.list_database_names() list_of_collections = {} for db in list_databases: - list_of_collections[db] = await greens.app.state.mongo_client[db].list_collection_names() + list_of_collections[db] = await greens.app.state.mongo_client[ + db + ].list_collection_names() mongo_meta = await greens.app.state.mongo_client.server_info() - return {"version": mongo_meta["version"], "databases": list_databases, "collections": list_of_collections} + return { + "version": mongo_meta["version"], + "databases": list_databases, + "collections": list_of_collections, + } diff --git a/greens/utils.py b/greens/utils.py index 7a846c7..e2f3aab 100644 --- a/greens/utils.py +++ b/greens/utils.py @@ -19,8 +19,14 @@ def get_logger(module_name): """ logger = logging.getLogger(module_name) - handler = RichHandler(rich_tracebacks=True, console=console, tracebacks_show_locals=True) - handler.setFormatter(logging.Formatter("%(name)s - [ %(threadName)s:%(funcName)s:%(lineno)d ] - %(message)s")) + handler = RichHandler( + rich_tracebacks=True, console=console, tracebacks_show_locals=True + ) + handler.setFormatter( + logging.Formatter( + "%(name)s - [ %(threadName)s:%(funcName)s:%(lineno)d ] - %(message)s" + ) + ) logger.addHandler(handler) logger.setLevel(logging.DEBUG) return logger diff --git a/tests/conftest.py b/tests/conftest.py index 41b4dee..a08b4ec 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -20,11 +20,15 @@ def anyio_backend(request): @pytest.fixture async def client() -> AsyncGenerator: async with AsyncClient( - app=app, - base_url="http://testserver", + app=app, + base_url="http://testserver", ) as client: app.state.logger = get_logger(__name__) - app.state.mongo_client, app.state.mongo_db, app.state.mongo_collection = await init_mongo( - global_settings.mongodb_test, global_settings.db_url, global_settings.mongodb_collection + app.state.mongo_client, app.state.mongo_db, app.state.mongo_collection = ( + await init_mongo( + global_settings.mongodb_test, + global_settings.db_url, + global_settings.mongodb_collection, + ) ) yield client diff --git a/tests/test_routers.py b/tests/test_routers.py index 8ff034c..25d03c7 100644 --- a/tests/test_routers.py +++ b/tests/test_routers.py @@ -15,15 +15,15 @@ async def test_health_check(client: AsyncClient): async def test_health_check_snapshot(client: AsyncClient): response = await client.get("/health-check") assert response.status_code == status.HTTP_200_OK - assert response.json() == snapshot({ - "version": "7.0.8", - "databases": ["admin", "config", "farmland", "local"], - "collections": { - "admin": ["system.users", "system.version"], - "config": ["system.sessions"], - "farmland": ["greens"], - "local": ["startup_log"], - }, -}) - - + assert response.json() == snapshot( + { + "version": "7.0.8", + "databases": ["admin", "config", "farmland", "local"], + "collections": { + "admin": ["system.users", "system.version"], + "config": ["system.sessions"], + "farmland": ["greens"], + "local": ["startup_log"], + }, + } + ) diff --git a/tests/test_schemas.py b/tests/test_schemas.py index aefb085..b6c5552 100644 --- a/tests/test_schemas.py +++ b/tests/test_schemas.py @@ -8,6 +8,7 @@ # that should accept BSON ObjectId instances. We'll need to mock or construct valid and # invalid ObjectId instances for testing. + # Helper function to create a valid ObjectId instance def create_valid_objectid(): return ObjectId() @@ -32,7 +33,8 @@ def test_document_response_with_valid_id(test_id, object_id): # Assert assert document_response.id == str( - object_id), f"Test case {test_id} failed: The id field did not match the input ObjectId." + object_id + ), f"Test case {test_id} failed: The id field did not match the input ObjectId." # Edge cases @@ -40,6 +42,7 @@ def test_document_response_with_valid_id(test_id, object_id): # Since ObjectId is a specific BSON type, edge cases might not be as relevant here, # but we can still test for unusual but valid ObjectIds + # Error cases @pytest.mark.parametrize( "test_id, object_id, expected_exception", @@ -55,4 +58,6 @@ def test_document_response_with_invalid_id(test_id, object_id, expected_exceptio with pytest.raises(expected_exception) as exc_info: DocumentResponse(id=object_id) - assert str(exc_info.value), f"Test case {test_id} failed: Expected exception {expected_exception} was not raised." + assert str( + exc_info.value + ), f"Test case {test_id} failed: Expected exception {expected_exception} was not raised." diff --git a/tests/test_vegs_api.py b/tests/test_vegs_api.py index 90a097b..a7eecfd 100644 --- a/tests/test_vegs_api.py +++ b/tests/test_vegs_api.py @@ -9,10 +9,10 @@ @pytest.mark.parametrize( "payload, status_code", ( - ( - {"name": "Corn", "desc": "Corn on the cob"}, - status.HTTP_201_CREATED, - ), + ( + {"name": "Corn", "desc": "Corn on the cob"}, + status.HTTP_201_CREATED, + ), ), ) # Test document create endpoint