-
Notifications
You must be signed in to change notification settings - Fork 6
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
Improve code coverage by adding more tests #9
Merged
Merged
Changes from all commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
8510179
Add tests for `get_id()` and `get_ids()`
pkhalaj c0dee66
Fix the bug: order of message and status
pkhalaj 2e8e025
Override the `caplog` fixture in pytest
pkhalaj ad4e143
Set `enqueue=False` in `conftest.py`
pkhalaj 3aba9e6
Fix the bug: store the `database_config` once the client is initialized
pkhalaj 79a67e6
Add `is_initialized()` method to the `MongoDB` class
pkhalaj 7161505
Change the name of `make_test_app_config_as_dict()` and update docstring
pkhalaj 742b84a
Add `@validate_call` to `MongoDB.initialize()`
pkhalaj 9c4687d
Add new tests for the `MongoDB.initialize()` method
pkhalaj a206fba
Fix the bug: Set `MongoDB.__client=None` once it is closed
pkhalaj fc74639
Add a test for testing `MongoDB.close()` without initialization
pkhalaj 7c93cda
Set `None` as default values for the args of `MongoDB.get_collection(…
pkhalaj f937d59
Add tests for `MongoDB.get_collection()` and `MongoDB().get_database()`
pkhalaj e8014ba
Remove unused `MongoDocument` model from `config.py`
pkhalaj 650f792
Add a specific error message to `config.id_must_be_valid()` when rais…
pkhalaj a6f136f
Add tests for `config.id_must_be_valid()`
pkhalaj 29f19a7
Extract the part which creates the FastAPI app into a separate module.
pkhalaj 8453356
Switch to `httpx.AsyncClient` for testing the API calls
pkhalaj 2f4e9fa
Change "/databases/" to "/databases"
pkhalaj ca5d3c3
Add a test for the `api.run_server()`
pkhalaj 27733f7
Add a test for `get_distinct_items_in_collection()`
pkhalaj aa8302c
Add more tests for `databases.document_by_id()`
pkhalaj 7f50198
Make `check_log()` a fixture
pkhalaj 583284d
Add a test for unknown messages sent to the recoder
pkhalaj e678756
Change `_aux()` to `check_log_message_at_level()`
pkhalaj 62974a4
Add a note to explain why we change error type in `id_must_be_valid()`
pkhalaj File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
"""The module which creates the main FastAPI app which will be used when running the API server.""" | ||
|
||
from fastapi import FastAPI, status | ||
from fastapi.responses import PlainTextResponse | ||
from loguru import logger | ||
from pydantic import ValidationError | ||
|
||
from trolldb.api.routes import api_router | ||
from trolldb.errors.errors import ResponseError | ||
|
||
API_INFO = dict( | ||
title="pytroll-db", | ||
summary="The database API of Pytroll", | ||
description= | ||
"The API allows you to perform CRUD operations as well as querying the database" | ||
"At the moment only MongoDB is supported. It is based on the following Python packages" | ||
"\n * **PyMongo** (https://github.com/mongodb/mongo-python-driver)" | ||
"\n * **motor** (https://github.com/mongodb/motor)", | ||
license_info=dict( | ||
name="The GNU General Public License v3.0", | ||
url="https://www.gnu.org/licenses/gpl-3.0.en.html" | ||
) | ||
) | ||
"""These will appear in the auto-generated documentation and are passed to the ``FastAPI`` class as keyword args.""" | ||
|
||
logger.info("Attempt to create the FastAPI app ...") | ||
fastapi_app = FastAPI() | ||
|
||
fastapi_app.include_router(api_router) | ||
|
||
|
||
@fastapi_app.exception_handler(ResponseError) | ||
async def auto_handler_response_errors(_, exc: ResponseError) -> PlainTextResponse: | ||
"""Catches all the exceptions raised as a ResponseError, e.g. accessing non-existing databases/collections.""" | ||
status_code, message = exc.get_error_details() | ||
info = dict( | ||
status_code=status_code if status_code else status.HTTP_500_INTERNAL_SERVER_ERROR, | ||
content=message if message else "Generic Error [This is not okay, check why we have the generic error!]", | ||
) | ||
logger.error(f"Response error caught by the API auto exception handler: {info}") | ||
return PlainTextResponse(**info) | ||
|
||
|
||
@fastapi_app.exception_handler(ValidationError) | ||
async def auto_handler_pydantic_validation_errors(_, exc: ValidationError) -> PlainTextResponse: | ||
"""Catches all the exceptions raised as a Pydantic ValidationError.""" | ||
logger.error(f"Response error caught by the API auto exception handler: {exc}") | ||
return PlainTextResponse(str(exc), status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) | ||
|
||
|
||
logger.info("FastAPI app created successfully.") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why change the type of error?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The reason is that as per the requirements of Pydantic, one can either raise a
ValueError
orAssertionError
in a custom validator. Here I have defined a custom validator for a MongoDB object ID. When it fails it raisesInvalidId
which is not a valid exception to signify validation failure in Pydantic, hence the need to catch the error and raise a different one.Please let me know if my understanding of this is correct.
Reference: https://docs.pydantic.dev/latest/concepts/validators/#handling-errors-in-validators
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I have added a note on this to the validator's docstring.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ok, all good then.