Skip to content

Commit

Permalink
black
Browse files Browse the repository at this point in the history
  • Loading branch information
grillazz committed Apr 17, 2024
1 parent 6ee787e commit 3a2a3e4
Show file tree
Hide file tree
Showing 9 changed files with 62 additions and 33 deletions.
4 changes: 2 additions & 2 deletions greens/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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,
)


Expand Down
8 changes: 6 additions & 2 deletions greens/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions greens/routers/v1/vegs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ?
19 changes: 14 additions & 5 deletions greens/services/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -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=}")
Expand All @@ -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
Expand All @@ -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,
}
10 changes: 8 additions & 2 deletions greens/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 8 additions & 4 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
24 changes: 12 additions & 12 deletions tests/test_routers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
},
}
)
9 changes: 7 additions & 2 deletions tests/test_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -32,14 +33,16 @@ 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
# Assuming edge cases would be related to the boundaries of ObjectId creation and representation
# 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",
Expand All @@ -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."
8 changes: 4 additions & 4 deletions tests/test_vegs_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 3a2a3e4

Please sign in to comment.