This commit is contained in:
Maxime Alves LIRMM 2022-08-08 16:42:31 +02:00
parent 6bb6abcbd4
commit b2084bf8c3
6 changed files with 66 additions and 36 deletions

View File

@ -1,5 +1,5 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
__version__ = '0.6.21-rc0' __version__ = '0.6.21-rc1'
def version(): def version():
return f'HalfAPI version:{__version__}' return f'HalfAPI version:{__version__}'

View File

@ -73,6 +73,15 @@ class HalfDomain(Starlette):
package, package_module.__version__, specifier package, package_module.__version__, specifier
)) ))
logger.debug('HalfDomain init %s', {
'domain': {
'name': self.name,
'id': self.id,
'version': self.version,
'halfapi_version': self.halfapi_version,
'config': self.config
}
})
super().__init__( super().__init__(
routes=self.gen_domain_routes(), routes=self.gen_domain_routes(),
@ -83,7 +92,7 @@ class HalfDomain(Starlette):
'id': self.id, 'id': self.id,
'version': self.version, 'version': self.version,
'halfapi_version': self.halfapi_version, 'halfapi_version': self.halfapi_version,
'config': self.config.get('domain', {}).get(self.name, {}).get('config', {}) 'config': self.config['domain'][self.name]
} }
}) })
] ]

View File

@ -22,37 +22,35 @@ class DomainMiddleware(BaseHTTPMiddleware):
""" """
logger.info('DomainMiddleware app:%s domain:%s', app, domain) logger.info('DomainMiddleware app:%s domain:%s', app, domain)
super().__init__(app) super().__init__(app)
self.domain = domain self.domain = domain.copy()
self.name = domain['name']
self.request = None self.request = None
@property
def config(self):
return { **self.domain['config'] }
async def dispatch(self, request: Request, async def dispatch(self, request: Request,
call_next: RequestResponseEndpoint) -> Response: call_next: RequestResponseEndpoint) -> Response:
""" """
Call of the route fonction (decorated or not) Call of the route fonction (decorated or not)
""" """
logger.debug('DomainMiddleware dispatch:%s !!! %s', self.config, request.app.config)
request.scope['domain'] = self.domain['name'] request.scope['domain'] = self.domain['name']
"""
if hasattr(request.app, 'config') \ if hasattr(request.app, 'config') \
and isinstance(request.app.config, dict): and isinstance(request.app.config, dict):
# Set the config scope to the domain's config # Set the config scope to the domain's config
request.scope['config'] = request.app.config.get( """
'domain', {} request.scope['config'] = self.config
).get(
self.domain['name'], {}
).copy()
# TODO: Remove in 0.7.0 # TODO: Remove in 0.7.0
config = request.scope['config'].copy()
request.scope['config']['domain'] = {} request.scope['config']['domain'] = {}
request.scope['config']['domain'][self.domain['name']] = {} request.scope['config']['domain'][self.name] = {
request.scope['config']['domain'][self.domain['name']]['config'] = config 'config': self.config
}
else:
logger.debug('%s', request.app)
logger.debug('%s', getattr(request.app, 'config', None))
response = await call_next(request) response = await call_next(request)

View File

@ -14,14 +14,27 @@ from pprint import pprint
import tempfile import tempfile
class TestDomain(TestCase): class TestDomain(TestCase):
@property
def domain_name(self):
return getattr(self, 'DOMAIN')
@property @property
def module_name(self): def module_name(self):
return getattr(self, 'MODULE', self.DOMAIN) return getattr(self, 'MODULE', self.domain_name)
@property
def acl_path(self):
return getattr(self, 'ACL', '.acl')
@property
def router_path(self):
return getattr(self, 'ROUTERS', '.routers')
@property @property
def router_module(self): def router_module(self):
return '.'.join((self.module_name, self.ROUTERS)) return '.'.join((self.module_name, self.ROUTERS))
def setUp(self): def setUp(self):
# CLI # CLI
class_ = CliRunner class_ = CliRunner
@ -54,16 +67,14 @@ class TestDomain(TestCase):
'domain': {} 'domain': {}
} }
self.halfapi_conf['domain'][self.DOMAIN] = { self.halfapi_conf['domain'][self.domain_name] = {
'name': self.DOMAIN, 'name': self.domain_name,
'router': self.ROUTERS, 'router': self.router_path,
'acl': self.ACL, 'acl': self.acl_path,
'module': self.module_name, 'module': self.module_name,
'prefix': False, 'prefix': False,
'enabled': True, 'enabled': True,
'config': { 'config': getattr(self, 'CONFIG', {})
'test': True
}
} }
_, self.config_file = tempfile.mkstemp() _, self.config_file = tempfile.mkstemp()
@ -87,7 +98,7 @@ class TestDomain(TestCase):
try: try:
result = self.runner.invoke(cli, '--version') result = self.runner.invoke(cli, '--version')
self.assertEqual(result.exit_code, 0) self.assertEqual(result.exit_code, 0)
result = self.runner.invoke(cli, ['domain', self.DOMAIN, self.config_file]) result = self.runner.invoke(cli, ['domain', self.domain_name, self.config_file])
self.assertEqual(result.exit_code, 0) self.assertEqual(result.exit_code, 0)
result_d = json.loads(result.stdout) result_d = json.loads(result.stdout)
result = self.runner.invoke(cli, ['run', '--help']) result = self.runner.invoke(cli, ['run', '--help'])
@ -121,14 +132,16 @@ class TestDomain(TestCase):
assert 'domain' in schema assert 'domain' in schema
r = self.client.get('/halfapi/acls') r = self.client.get('/halfapi/acls')
"""
assert r.status_code == 200 assert r.status_code == 200
d_r = r.json() d_r = r.json()
assert isinstance(d_r, dict) assert isinstance(d_r, dict)
assert self.DOMAIN in d_r.keys() assert self.domain_name in d_r.keys()
ACLS = HalfDomain.acls(self.module, self.ACL) ACLS = HalfDomain.acls(self.module, self.acl_path)
assert len(ACLS) == len(d_r[self.DOMAIN]) assert len(ACLS) == len(d_r[self.domain_name])
for acl_name in ACLS: for acl_name in ACLS:
assert acl_name[0] in d_r[self.DOMAIN] assert acl_name[0] in d_r[self.domain_name]
"""

View File

@ -5,8 +5,7 @@ class TestDummyDomain(TestDomain):
from .dummy_domain import __name__, __routers__ from .dummy_domain import __name__, __routers__
DOMAIN = __name__ DOMAIN = __name__
ROUTERS = __routers__ CONFIG = {'test': True}
ACL = '.acl'
def test_domain(self): def test_domain(self):
self.check_domain() self.check_domain()

View File

@ -2,12 +2,23 @@ from starlette.testclient import TestClient
from starlette.middleware.base import BaseHTTPMiddleware from starlette.middleware.base import BaseHTTPMiddleware
from unittest.mock import patch from unittest.mock import patch
from halfapi.lib.domain_middleware import DomainMiddleware from halfapi.lib.domain_middleware import DomainMiddleware
from halfapi import __version__
def test_init(): def test_init():
with patch('starlette.middleware.base.BaseHTTPMiddleware.__init__') as init: with patch('starlette.middleware.base.BaseHTTPMiddleware.__init__') as init:
mw = DomainMiddleware('app', 'domain') mw = DomainMiddleware('app', {
'name': 'test',
'id': 'randomid',
'version': '0.0.0',
'halfapi_version': __version__,
'config': {}
})
init.assert_called_once_with('app') init.assert_called_once_with('app')
assert mw.domain == 'domain' assert isinstance(mw.domain, dict)
assert isinstance(mw.name, str)
assert mw.name == 'test'
assert isinstance(mw.config, dict)
assert len(mw.config) == 0
assert mw.request == None assert mw.request == None
def test_call(application_debug): def test_call(application_debug):