Skip to content

Commit b350d49

Browse files
committed
Refactored the testsuite for persistent local services
1 parent c723975 commit b350d49

File tree

12 files changed

+230
-120
lines changed

12 files changed

+230
-120
lines changed

mrmat_python_api_flask/__init__.py

Lines changed: 13 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -25,43 +25,31 @@
2525

2626
import sys
2727
import os
28+
import logging
2829
import importlib.metadata
29-
from logging.config import dictConfig
30+
31+
from rich.console import Console
32+
from rich.logging import RichHandler
3033

3134
from flask import Flask
3235
from flask_sqlalchemy import SQLAlchemy
3336
from flask_migrate import Migrate
3437
from flask_marshmallow import Marshmallow
3538
from flask_oidc import OpenIDConnect
3639

40+
logging.basicConfig(level='INFO',
41+
handlers=[RichHandler(rich_tracebacks=True,
42+
show_path=False,
43+
omit_repeated_times=False)])
44+
log = logging.getLogger(__name__)
45+
console = Console()
46+
3747
__version__ = importlib.metadata.version('mrmat-python-api-flask')
3848
db = SQLAlchemy()
3949
ma = Marshmallow()
4050
migrate = Migrate()
4151
oidc = OpenIDConnect()
4252

43-
dictConfig({
44-
'version': 1,
45-
'formatters': {'default': {
46-
'format': '[%(asctime)s] %(levelname)s: %(message)s',
47-
}},
48-
'handlers': {
49-
'wsgi': {
50-
'class': 'logging.StreamHandler',
51-
'stream': 'ext://flask.logging.wsgi_errors_stream',
52-
'formatter': 'default'
53-
}
54-
},
55-
'root': {
56-
'level': 'INFO',
57-
'handlers': ['wsgi']
58-
},
59-
'mrmat_python_api_flask': {
60-
'level': 'INFO',
61-
'handlers': ['wsgi']
62-
}
63-
})
64-
6553

6654
def create_app(config_override=None, instance_path=None):
6755
"""Factory method to create a Flask app.
@@ -82,7 +70,8 @@ def create_app(config_override=None, instance_path=None):
8270
#
8371
# Set configuration defaults. If a config file is present then load it. If we have overrides, apply them
8472

85-
app.config.setdefault('SECRET_KEY', os.urandom(16))
73+
# TODO
74+
#app.config.setdefault('SECRET_KEY', 'JFg4K1l5vVmusHmI0cNAFg')
8675
app.config.setdefault('SQLALCHEMY_DATABASE_URI',
8776
'sqlite+pysqlite:///' + os.path.join(app.instance_path, 'mrmat-python-api-flask.sqlite'))
8877
app.config.setdefault('SQLALCHEMY_TRACK_MODIFICATIONS', False)

mrmat_python_api_flask/apis/resource/v1/api.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,11 @@
3838

3939
def _extract_identity() -> Tuple:
4040
return g.oidc_token_info['client_id'], \
41-
g.oidc_token_info['preferred_username']
41+
g.oidc_token_info['username']
4242

4343

4444
@bp.route('/', methods=['GET'])
45-
@oidc.accept_token(require_token=True, scopes_required=['mrmat-python-api-flask-resource-read'])
45+
@oidc.accept_token(require_token=True, scopes_required=['mpaf-read'])
4646
def get_all():
4747
identity = _extract_identity()
4848
logger.info(f'Called by {identity[1]} ({identity[0]}')
@@ -51,7 +51,7 @@ def get_all():
5151

5252

5353
@bp.route('/<i>', methods=['GET'])
54-
@oidc.accept_token(require_token=True, scopes_required=['mrmat-python-api-flask-resource-read'])
54+
@oidc.accept_token(require_token=True, scopes_required=['mpaf-read'])
5555
def get_one(i: int):
5656
identity = _extract_identity()
5757
logger.info(f'Called by {identity[1]} ({identity[0]}')
@@ -62,7 +62,7 @@ def get_one(i: int):
6262

6363

6464
@bp.route('/', methods=['POST'])
65-
@oidc.accept_token(require_token=True, scopes_required=['mrmat-python-api-flask-resource-write'])
65+
@oidc.accept_token(require_token=True, scopes_required=['mpaf-write'])
6666
def create():
6767
(client_id, name) = _extract_identity()
6868
logger.info(f'Called by {name} ({client_id}')
@@ -99,7 +99,7 @@ def create():
9999

100100

101101
@bp.route('/<i>', methods=['PUT'])
102-
@oidc.accept_token(require_token=True, scopes_required=['mrmat-python-api-flask-resource-write'])
102+
@oidc.accept_token(require_token=True, scopes_required=['mpaf-write'])
103103
def modify(i: int):
104104
(client_id, name) = _extract_identity()
105105
logger.info(f'Called by {name} ({client_id}')
@@ -118,7 +118,7 @@ def modify(i: int):
118118

119119

120120
@bp.route('/<i>', methods=['DELETE'])
121-
@oidc.accept_token(require_token=True, scopes_required=['mrmat-python-api-flask-resource-write'])
121+
@oidc.accept_token(require_token=True, scopes_required=['mpaf-write'])
122122
def remove(i: int):
123123
(client_id, name) = _extract_identity()
124124
logger.info(f'Called by {name} ({client_id}')

mrmat_python_api_flask/client.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,9 @@
2929
from time import sleep
3030
from argparse import ArgumentParser, Namespace
3131
from typing import List, Optional, Dict
32-
import cli_ui
33-
from halo import Halo
3432
import requests
3533

36-
from mrmat_python_api_flask import __version__
34+
from mrmat_python_api_flask import __version__, log
3735

3836

3937
class ClientException(Exception):
@@ -76,7 +74,6 @@ def oidc_device_auth(config: Dict, discovery: Dict) -> Dict:
7674
return data
7775

7876

79-
@Halo(text='Checking authentication')
8077
def oidc_check_auth(config: Dict, discovery: Dict, device_auth: Dict):
8178
wait = 5
8279
stop = False
@@ -159,7 +156,6 @@ def main(argv=None) -> int:
159156
args = parse_args(argv if argv is not None else sys.argv[1:])
160157
if args is None:
161158
return 0
162-
cli_ui.setup(verbose=args.debug, quiet=args.quiet, timestamp=False)
163159

164160
#
165161
# Read from the config file by default, but allow overrides via the CLI
@@ -191,23 +187,23 @@ def main(argv=None) -> int:
191187
raise ClientException(msg='No expires_in in device_auth')
192188

193189
# Adding the user code to the URL is convenient, but not as secure as it could be
194-
cli_ui.info(f'Please visit {device_auth["verification_uri"]} within {device_auth["expires_in"]} seconds and '
190+
log.info(f'Please visit {device_auth["verification_uri"]} within {device_auth["expires_in"]} seconds and '
195191
f'enter code {device_auth["user_code"]}. Or just visit {device_auth["verification_uri_complete"]}')
196192

197193
auth = oidc_check_auth(config, discovery, device_auth)
198-
cli_ui.info('Authenticated')
194+
log.info('Authenticated')
199195

200196
#
201197
# We're using requests directly here because requests_oauthlib doesn't support device code flow directly
202198

203199
resp = requests.get('http://127.0.0.1:5000/api/greeting/v3/',
204200
headers={'Authorization': f'Bearer {auth["id_token"]}'})
205-
cli_ui.info(f'Status Code: {resp.status_code}')
206-
cli_ui.info(resp.content)
201+
log.info(f'Status Code: {resp.status_code}')
202+
log.info(resp.content)
207203

208204
return 0
209205
except ClientException as ce:
210-
cli_ui.error(ce.msg)
206+
log.error(ce.msg)
211207
return ce.exit_code
212208

213209

pytest.ini

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
[pytest]
66
testpaths = tests
7-
addopts = --cov=mrmat_python_api_flask --cov-report=term --cov-report=xml:build/coverage.xml --junit-xml=build/junit.xml
7+
#addopts = --cov=mrmat_python_api_flask --cov-report=term --cov-report=xml:build/coverage.xml --junit-xml=build/junit.xml
88
junit_family = xunit2
99
log_cli = 1
1010
log_cli_level = INFO

0 commit comments

Comments
 (0)