[tests] update tests for 0.5.3

This commit is contained in:
Maxime Alves LIRMM@home 2021-06-17 18:52:18 +02:00
parent 6181592692
commit 4d50363c9b
12 changed files with 160 additions and 46 deletions

View File

@ -11,6 +11,7 @@ from uuid import uuid1, uuid4, UUID
import click import click
from click.testing import CliRunner from click.testing import CliRunner
import jwt import jwt
import sys
from unittest.mock import patch from unittest.mock import patch
import pytest import pytest
from starlette.applications import Starlette from starlette.applications import Starlette
@ -251,6 +252,7 @@ def create_route():
@pytest.fixture @pytest.fixture
def dummy_project(): def dummy_project():
sys.path.insert(0, './tests')
halfapi_config = tempfile.mktemp() halfapi_config = tempfile.mktemp()
halfapi_secret = tempfile.mktemp() halfapi_secret = tempfile.mktemp()
domain = 'dummy_domain' domain = 'dummy_domain'
@ -271,3 +273,31 @@ def dummy_project():
f.write('turlututu') f.write('turlututu')
return (halfapi_config, 'dummy_domain', 'routers') return (halfapi_config, 'dummy_domain', 'routers')
@pytest.fixture
def routers():
sys.path.insert(0, './tests')
from dummy_domain import routers
return routers
@pytest.fixture
def application_debug():
from halfapi.app import HalfAPI
return HalfAPI({
'SECRET':'turlututu',
'PRODUCTION':False
}).application
@pytest.fixture
def application_domain(routers):
from halfapi.app import HalfAPI
return HalfAPI({
'SECRET':'turlututu',
'PRODUCTION':True,
'DOMAINS':{'dummy_domain':routers}
}).application

View File

@ -1,5 +1,5 @@
from starlette.responses import PlainTextResponse from starlette.responses import PlainTextResponse
from dummy_domain import acl from halfapi.lib import acl
ACLS = { ACLS = {
'GET': [{'acl':acl.public}] 'GET': [{'acl':acl.public}]

View File

@ -1,6 +1,6 @@
from halfapi.lib import acl from halfapi.lib import acl
ACLS = { ACLS = {
'GET' : [{acl.public}] 'GET' : [{'acl':acl.public}]
} }
def get(): def get():
raise NotImplementedError raise NotImplementedError

View File

@ -2,31 +2,21 @@
import pytest import pytest
from starlette.authentication import UnauthenticatedUser from starlette.authentication import UnauthenticatedUser
from starlette.testclient import TestClient from starlette.testclient import TestClient
from halfapi.app import application
import json import json
def test_get_api_routes():
c = TestClient(application)
r = c.get('/')
d_r = r.json()
assert isinstance(d_r, dict)
def test_current_user(project_runner, application_debug):
def test_current_user(project_runner): c = TestClient(application_debug)
"""
Missing HALFAPI_SECRET to give current user route
"""
c = TestClient(application)
r = c.get('/halfapi/current_user') r = c.get('/halfapi/current_user')
assert r.status_code == 200 assert r.status_code == 200
def test_log(): def test_log(application_debug):
c = TestClient(application) c = TestClient(application_debug)
r = c.get('/halfapi/log') r = c.get('/halfapi/log')
assert r.status_code == 200 assert r.status_code == 200
def test_error(): def test_error(application_debug):
c = TestClient(application) c = TestClient(application_debug)
r = c.get('/halfapi/error/400') r = c.get('/halfapi/error/400')
assert r.status_code == 400 assert r.status_code == 400
r = c.get('/halfapi/error/404') r = c.get('/halfapi/error/404')
@ -34,8 +24,8 @@ def test_error():
r = c.get('/halfapi/error/500') r = c.get('/halfapi/error/500')
assert r.status_code == 500 assert r.status_code == 500
def test_exception(): def test_exception(application_debug):
c = TestClient(application) c = TestClient(application_debug)
try: try:
r = c.get('/halfapi/exception') r = c.get('/halfapi/exception')
assert r.status_code == 500 assert r.status_code == 500

View File

@ -7,17 +7,35 @@ import pytest
from starlette.routing import Route from starlette.routing import Route
from starlette.testclient import TestClient from starlette.testclient import TestClient
from halfapi.lib.routes import gen_starlette_routes from halfapi.lib.domain import gen_router_routes
def test_get_route(dummy_project): def test_get_route(dummy_project, application_domain, routers):
from halfapi.app import application c = TestClient(application_domain)
os.environ['HALFAPI_CONFIG'] = dummy_project[0] path = verb = params = None
c = TestClient(application) for path, verb, _, params in gen_router_routes(routers, []):
print(f'/{dummy_project[1]}/alphabet') if len(params):
r = c.get(f'/{dummy_project[1]}/alphabet') route_path = '/dummy_domain/{}'.format(path)
try: try:
assert r.status_code == 200 if verb.lower() == 'get':
r = c.get(route_path)
elif verb.lower() == 'post':
r = c.post(route_path)
elif verb.lower() == 'patch':
r = c.patch(route_path)
elif verb.lower() == 'put':
r = c.put(route_path)
elif verb.lower() == 'delete':
r = c.delete(route_path)
else:
raise Exception(verb)
try:
assert r.status_code in [200, 501]
except AssertionError as exc: except AssertionError as exc:
print('.'.join((dummy_project[1], 'routers'))) print('{} [{}] {}'.format(str(r.status_code), verb, route_path))
raise exc
except NotImplementedError:
pass
if not path:
raise Exception('No route generated')

View File

@ -1,18 +1,36 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import importlib import importlib
from halfapi.lib.domain import VERBS, gen_router_routes from halfapi.lib.domain import VERBS, gen_routes, gen_router_routes, MissingAclError
from types import FunctionType
def test_gen_router_routes(): def test_gen_router_routes():
from .dummy_domain import routers from .dummy_domain import routers
for path, d_route in gen_router_routes(routers, ['dummy_domain']): for path, verb, fct, params in gen_router_routes(routers, ['dummy_domain']):
assert isinstance(path, str) assert isinstance(path, str)
for verb in VERBS: assert verb in VERBS
if verb not in d_route.keys(): assert len(params) > 0
continue assert hasattr(fct, '__call__')
route = d_route[verb]
print(f'[{verb}] {path} {route["fct"]}') def test_gen_routes():
assert len(route['params']) > 0 from .dummy_domain.routers.abc.alphabet import TEST_uuid
assert hasattr(route['fct'], '__call__') try:
if 'fqtn' in route: gen_routes(
assert isinstance(route['fqtn'], str) TEST_uuid,
'get',
['abc', 'alphabet', 'TEST_uuid', ''],
[])
except MissingAclError:
assert True
fct, params = gen_routes(
TEST_uuid,
'get',
['abc', 'alphabet', 'TEST_uuid', ''],
TEST_uuid.ACLS['GET'])
assert isinstance(fct, FunctionType)
assert isinstance(params, list)
assert len(TEST_uuid.ACLS['GET']) == len(params)

44
tests/test_lib_router.py Normal file
View File

@ -0,0 +1,44 @@
import os
from halfapi.lib.router import read_router
def test_read_router_routers():
from .dummy_domain import routers
router_d = read_router(routers)
assert '' in router_d
assert 'SUBROUTES' in router_d['']
assert isinstance(router_d['']['SUBROUTES'], list)
for elt in os.scandir(routers.__path__[0]):
if elt.is_dir():
assert elt.name in router_d['']['SUBROUTES']
def test_read_router_abc():
from .dummy_domain.routers import abc
router_d = read_router(abc)
assert '' in router_d
assert 'SUBROUTES' in router_d['']
assert isinstance(router_d['']['SUBROUTES'], list)
def test_read_router_alphabet():
from .dummy_domain.routers.abc import alphabet
router_d = read_router(alphabet)
assert '' in router_d
assert 'SUBROUTES' in router_d['']
assert isinstance(router_d['']['SUBROUTES'], list)
def test_read_router_TEST():
from .dummy_domain.routers.abc.alphabet import TEST_uuid
router_d = read_router(TEST_uuid)
print(router_d)
assert '' in router_d
assert 'SUBROUTES' in router_d['']
assert isinstance(router_d['']['GET'], list)
assert isinstance(router_d['']['POST'], list)
assert isinstance(router_d['']['PATCH'], list)
assert isinstance(router_d['']['PUT'], list)

View File

@ -5,7 +5,6 @@ from starlette.authentication import (
AuthenticationBackend, AuthenticationError, BaseUser, AuthCredentials, AuthenticationBackend, AuthenticationError, BaseUser, AuthCredentials,
UnauthenticatedUser) UnauthenticatedUser)
from halfapi.app import application
from halfapi.lib.schemas import schema_dict_dom from halfapi.lib.schemas import schema_dict_dom
def test_schemas_dict_dom(): def test_schemas_dict_dom():
@ -15,8 +14,23 @@ def test_schemas_dict_dom():
assert isinstance(schema, dict) assert isinstance(schema, dict)
def test_get_api_routes(project_runner): def test_get_api_routes(project_runner, application_debug):
c = TestClient(application) c = TestClient(application_debug)
r = c.get('/') r = c.get('/')
d_r = r.json() d_r = r.json()
assert isinstance(d_r, dict) assert isinstance(d_r, dict)
def test_get_api_dummy_domain_routes(application_domain, routers):
c = TestClient(application_domain)
r = c.get('/dummy_domain')
assert r.status_code == 200
d_r = r.json()
assert isinstance(d_r, dict)
print(d_r)
assert 'abc/alphabet' in d_r
assert 'GET' in d_r['abc/alphabet']
assert len(d_r['abc/alphabet']['GET']) > 0
assert 'acl' in d_r['abc/alphabet']['GET'][0]