Add simple FastAPI example
This commit is contained in:
parent
ee965f9782
commit
8092421727
|
@ -7,6 +7,10 @@ that were made in every particular version.
|
|||
From version 0.7.6 *Dependency Injector* framework strictly
|
||||
follows `Semantic versioning`_
|
||||
|
||||
Develop
|
||||
-------
|
||||
- Add simple ``FastAPI`` example.
|
||||
|
||||
4.4.1
|
||||
-----
|
||||
- Improve ``FastAPI`` integration: handle ``Depends(Provide[...])``.
|
||||
|
|
|
@ -0,0 +1,29 @@
|
|||
import sys
|
||||
|
||||
from fastapi import FastAPI, Depends
|
||||
from dependency_injector import containers, providers
|
||||
from dependency_injector.wiring import inject, Provide
|
||||
|
||||
|
||||
class Service:
|
||||
async def process(self) -> str:
|
||||
return 'Ok'
|
||||
|
||||
|
||||
class Container(containers.DeclarativeContainer):
|
||||
|
||||
service = providers.Factory(Service)
|
||||
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
@app.api_route('/')
|
||||
@inject
|
||||
async def index(service: Service = Depends(Provide[Container.service])):
|
||||
result = await service.process()
|
||||
return {'result': result}
|
||||
|
||||
|
||||
container = Container()
|
||||
container.wire(modules=[sys.modules[__name__]])
|
|
@ -0,0 +1,25 @@
|
|||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from fastapi_di_example import app, container, Service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(event_loop):
|
||||
client = AsyncClient(app=app, base_url='http://test')
|
||||
yield client
|
||||
event_loop.run_until_complete(client.aclose())
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_index(client):
|
||||
service_mock = mock.AsyncMock(spec=Service)
|
||||
service_mock.process.return_value = 'Foo'
|
||||
|
||||
with container.service.override(service_mock):
|
||||
response = await client.get('/')
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {'result': 'Foo'}
|
Loading…
Reference in New Issue