diff --git a/tests/conftest.py b/tests/conftest.py index 1614e75..06f7d6f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -6,20 +6,59 @@ import os import subprocess import importlib import tempfile -import click -from unittest.mock import patch from typing import Dict, Tuple +from uuid import uuid1, uuid4, UUID +import click +import jwt +from unittest.mock import patch import pytest -from uuid import uuid1 -from click.testing import CliRunner +from starlette.applications import Starlette +from starlette.responses import PlainTextResponse +from starlette.middleware.authentication import AuthenticationMiddleware +from starlette.testclient import TestClient from halfapi import __version__ from halfapi.cli.cli import cli from halfapi.cli.init import init, format_halfapi_etc from halfapi.cli.domain import domain, create_domain +from halfapi.lib.responses import ORJSONResponse +from halfapi.lib.jwt_middleware import JWTAuthenticationBackend logger = logging.getLogger('halfapitest') PROJNAME = os.environ.get('PROJ','tmp_api') +os.environ['HALFAPI_SECRET'] = 'dummysecret' +SECRET = 'dummysecret' + +from halfapi.lib.jwt_middleware import ( + JWTUser, JWTAuthenticationBackend, + JWTWebSocketAuthenticationBackend) + +@pytest.fixture +def token_builder(): + yield jwt.encode({ + 'name':'xxx', + 'user_id': str(uuid4())}, + key=SECRET + ) + +@pytest.fixture +def token_debug_false_builder(): + yield jwt.encode({ + 'name':'xxx', + 'user_id': str(uuid4()), + 'debug': False}, + key=SECRET + ) + + +@pytest.fixture +def token_debug_true_builder(): + yield jwt.encode({ + 'name':'xxx', + 'user_id': str(uuid4()), + 'debug': True}, + key=SECRET + ) @pytest.fixture def runner(): @@ -161,3 +200,30 @@ def project_runner(runner, halfapicli, halfapi_conf_dir): ### yield halfapicli + +@pytest.fixture +def dummy_app(): + app = Starlette() + app.add_route('/', + lambda request, *args, **kwargs: PlainTextResponse('Hello test!')) + app.add_middleware( + AuthenticationMiddleware, + backend=JWTAuthenticationBackend(secret_key='dummysecret') + ) + return app +@pytest.fixture + +def dummy_debug_app(): + app = Starlette(debug=True) + app.add_route('/', + lambda request, *args, **kwargs: PlainTextResponse('Hello test!')) + app.add_middleware( + AuthenticationMiddleware, + backend=JWTAuthenticationBackend(secret_key='dummysecret') + ) + return app + + +@pytest.fixture +def test_client(dummy_app): + return TestClient(dummy_app) diff --git a/tests/test_jwt_middleware.py b/tests/test_jwt_middleware.py index 08bf44d..eee24d5 100644 --- a/tests/test_jwt_middleware.py +++ b/tests/test_jwt_middleware.py @@ -14,92 +14,12 @@ from starlette.testclient import TestClient from starlette.authentication import ( AuthenticationBackend, AuthenticationError, BaseUser, AuthCredentials, UnauthenticatedUser) +from starlette.responses import PlainTextResponse - -#from halfapi.app import app -#os.environ['HALFAPI_PROD'] = 'True' -os.environ['HALFAPI_SECRET'] = 'randomsecret' - -from halfapi.lib.jwt_middleware import (PRODUCTION, SECRET, +from halfapi.lib.jwt_middleware import ( JWTUser, JWTAuthenticationBackend, JWTWebSocketAuthenticationBackend) -def test_constants(): - assert isinstance(PRODUCTION, bool) - assert isinstance(SECRET, str) - -@pytest.fixture -def token(): - # This fixture needs to have a running auth-lirmm on 127.0.0.1:3000 - # Sets a valid token - - r = requests.post('http://127.0.0.1:3000/', - data={'email':'maizi', 'password':'a'}) - - if len(r.text) <= 0: - raise Exception('No result in token retrieval') - - try: - res = json.loads(r.text) - except JSONDecodeError: - raise Exception('Malformed response from token retrieval') - - if 'token' not in res.keys(): - raise Exception('Missing token in token request') - - return res['token'] - - -@pytest.fixture -def token_builder(): - yield jwt.encode({ - 'name':'xxx', - 'user_id': str(uuid4())}, - key=SECRET - ) - -@pytest.fixture -def token_debug_false_builder(): - yield jwt.encode({ - 'name':'xxx', - 'user_id': str(uuid4()), - 'debug': False}, - key=SECRET - ) - - -@pytest.fixture -def token_debug_true_builder(): - yield jwt.encode({ - 'name':'xxx', - 'user_id': str(uuid4()), - 'debug': True}, - key=SECRET - ) - - - - -@pytest.fixture -def token_dirser(): - # This fixture needs to have a running auth-lirmm on 127.0.0.1:3000 - # Sets a valid token - - r = requests.post('http://127.0.0.1:3000/', - data={'email':'dhenaut', 'password':'a'}) - - if len(r.text) <= 0: - raise Exception('No result in token retrieval') - - try: - res = json.loads(r.text) - except JSONDecodeError: - raise Exception('Malformed response from token retrieval') - - if 'token' not in res.keys(): - raise Exception('Missing token in token request') - - return res['token'] def test_JWTUser(): uid = uuid4()