python-dependency-injector/tests/unit/ext/test_aiohttp_py35.py

94 lines
2.6 KiB
Python
Raw Normal View History

"""Dependency injector Aiohttp extension unit tests."""
from aiohttp import web
from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop
from dependency_injector import containers, providers
from dependency_injector.ext import aiohttp
async def index(_):
2021-10-01 03:09:42 +03:00
return web.Response(text="Hello World!")
async def test(_):
2021-10-01 03:09:42 +03:00
return web.Response(text="Test!")
class Test(web.View):
async def get(self):
2021-10-01 03:09:42 +03:00
return web.Response(text="Test class-based!")
@web.middleware
async def middleware(request, handler):
resp = await handler(request)
2021-10-01 03:09:42 +03:00
resp.text = resp.text + " wink1"
return resp
def middleware_factory(text):
@web.middleware
async def sample_middleware(request, handler):
resp = await handler(request)
resp.text = resp.text + text
return resp
return sample_middleware
class ApplicationContainer(containers.DeclarativeContainer):
app = aiohttp.Application(
web.Application,
middlewares=providers.List(
aiohttp.Middleware(middleware),
2021-10-01 03:09:42 +03:00
aiohttp.MiddlewareFactory(middleware_factory, text=" wink2"),
),
)
index_view = aiohttp.View(index)
test_view = aiohttp.View(test)
test_class_view = aiohttp.ClassBasedView(Test)
class ApplicationTests(AioHTTPTestCase):
async def get_application(self):
"""
Override the get_app method to return your application.
"""
container = ApplicationContainer()
app = container.app()
app.container = container
app.add_routes([
2021-10-01 03:09:42 +03:00
web.get("/", container.index_view.as_view()),
web.get("/test", container.test_view.as_view(), name="test"),
web.get("/test-class", container.test_class_view.as_view()),
])
return app
@unittest_run_loop
async def test_index(self):
2021-10-01 03:09:42 +03:00
response = await self.client.get("/")
self.assertEqual(response.status, 200)
2021-10-01 03:09:42 +03:00
self.assertEqual(await response.text(), "Hello World! wink2 wink1")
@unittest_run_loop
async def test_test(self):
2021-10-01 03:09:42 +03:00
response = await self.client.get("/test")
self.assertEqual(response.status, 200)
2021-10-01 03:09:42 +03:00
self.assertEqual(await response.text(), "Test! wink2 wink1")
@unittest_run_loop
async def test_test_class_based(self):
2021-10-01 03:09:42 +03:00
response = await self.client.get("/test-class")
self.assertEqual(response.status, 200)
2021-10-01 03:09:42 +03:00
self.assertEqual(await response.text(), "Test class-based! wink2 wink1")
@unittest_run_loop
async def test_endpoints(self):
2021-10-01 03:09:42 +03:00
self.assertEqual(str(self.app.router["test"].url_for()), "/test")