Browse Source

Merge branch 'rename_source' into 'development'

Rename source

See merge request warricksothr/Corvus!2
development
Drew Short 5 years ago
parent
commit
1561b92163
  1. 2
      server/.env
  2. 22
      server/Dockerfile
  3. 4
      server/corvus/api/__init__.py
  4. 2
      server/corvus/model/__init__.py
  5. 1
      server/corvus/utility/__init__.py
  6. 4
      server/dev-run.sh
  7. 8
      server/documentation/api/authentication.rst
  8. 2
      server/documentation/api/index.rst
  9. 30
      server/documentation/api/user.rst
  10. 8
      server/documentation/conf.py
  11. 12
      server/documentation/introduction.rst
  12. 4
      server/entrypoint.sh
  13. 14
      server/manage.py
  14. 10
      server/run_tests.bat
  15. 12
      server/run_tests.sh
  16. 42
      server/server/__init__.py
  17. 4
      server/server/api/__init__.py
  18. 16
      server/server/api/authentication_api.py
  19. 2
      server/server/api/decorators.py
  20. 4
      server/server/api/health_api.py
  21. 2
      server/server/api/model.py
  22. 20
      server/server/api/user_api.py
  23. 0
      server/server/db.py
  24. 2
      server/server/default_settings.py
  25. 20
      server/server/errors.py
  26. 0
      server/server/middleware/__init__.py
  27. 8
      server/server/middleware/authentication_middleware.py
  28. 2
      server/server/model/__init__.py
  29. 4
      server/server/model/user_model.py
  30. 0
      server/server/service/__init__.py
  31. 6
      server/server/service/authentication_service.py
  32. 10
      server/server/service/patch_service.py
  33. 2
      server/server/service/role_service.py
  34. 4
      server/server/service/transformation_service.py
  35. 16
      server/server/service/user_service.py
  36. 8
      server/server/service/user_token_service.py
  37. 8
      server/server/service/validation_service.py
  38. 1
      server/server/utility/__init__.py
  39. 0
      server/server/utility/authentication_utility.py
  40. 8
      server/server/utility/json_utility.py
  41. 2
      server/server/utility/pagination_utility.py
  42. 0
      server/server/utility/session_utility.py
  43. 4
      server/setup.py
  44. 4
      server/tests/api/test_decorators.py
  45. 2
      server/tests/api/test_user_api.py
  46. 26
      server/tests/conftest.py
  47. 4
      server/tests/middleware/test_authentication_middleware.py
  48. 4
      server/tests/service/test_authentication_service.py
  49. 6
      server/tests/service/test_patch_service.py
  50. 2
      server/tests/service/test_role_service.py
  51. 8
      server/tests/service/test_transformation_service.py
  52. 4
      server/tests/service/test_validation_service.py

2
server/.env

@ -1 +1 @@
FLASK_APP=corvus:corvus
FLASK_APP=server:server

22
server/Dockerfile

@ -1,25 +1,25 @@
FROM python:3.7-slim-stretch
MAINTAINER Drew Short <warrick@sothr.com>
ENV CORVUS_APP_DIRECTORY /opt/corvus
ENV CORVUS_CONFIG_DIRECTORY /srv/corvus/config
ENV CORVUS_DATA_DIRECTORY /srv/corvus/data
ENV SERVER_APP_DIRECTORY /opt/server
ENV SERVER_CONFIG_DIRECTORY /srv/server/config
ENV SERVER_DATA_DIRECTORY /srv/server/data
RUN mkdir -p ${CORVUS_APP_DIRECTORY} \
&& mkdir -p ${CORVUS_CONFIG_DIRECTORY} \
&& mkdir -p ${CORVUS_DATA_DIRECTORY} \
RUN mkdir -p ${SERVER_APP_DIRECTORY} \
&& mkdir -p ${SERVER_CONFIG_DIRECTORY} \
&& mkdir -p ${SERVER_DATA_DIRECTORY} \
&& pip install pipenv gunicorn
VOLUME ${CORVUS_CONFIG_DIRECTORY}
VOLUME ${CORVUS_DATA_DIRECTORY}
VOLUME ${SERVER_CONFIG_DIRECTORY}
VOLUME ${SERVER_DATA_DIRECTORY}
COPY ./ ${CORVUS_APP_DIRECTORY}/
COPY ./ ${SERVER_APP_DIRECTORY}/
RUN cd ${CORVUS_APP_DIRECTORY} \
RUN cd ${SERVER_APP_DIRECTORY} \
&& pipenv install --system --deploy --ignore-pipfile
EXPOSE 8080
WORKDIR ${CORVUS_APP_DIRECTORY}
WORKDIR ${SERVER_APP_DIRECTORY}
CMD ./entrypoint.sh

4
server/corvus/api/__init__.py

@ -1,4 +0,0 @@
"""API blueprint exports."""
from corvus.api.authentication_api import AUTH_BLUEPRINT
from corvus.api.user_api import USER_BLUEPRINT
from corvus.api.health_api import HEALTH_BLUEPRINT

2
server/corvus/model/__init__.py

@ -1,2 +0,0 @@
"""Expose models to be used in Corvus."""
from corvus.model.user_model import User, UserToken

1
server/corvus/utility/__init__.py

@ -1 +0,0 @@
"""Utilities for Corvus."""

4
server/dev-run.sh

@ -1,5 +1,5 @@
#!/usr/bin/env bash
FLASK_APP=corvus:corvus flask db upgrade
FLASK_APP=server:server flask db upgrade
python manage.py user register-admin
FLASK_APP=corvus:corvus flask run
FLASK_APP=server:server flask run

8
server/documentation/api/authentication.rst

@ -51,7 +51,7 @@ Authentication API
POST /auth/bump HTTP/1.1
Host: example.tld
Accept: application/json
Authorization: Token <Base64(user:userToken)>
X-Auth-Token: <Base64(user:userToken)>
**Example response**:
@ -66,7 +66,7 @@ Authentication API
}
:<header Accept: Response content type depends on :mailheader:`Accept` header
:<header Authorization: Encoded token authorization
:<header X-Auth-Token: Encoded token authorization
:>header Content-Type: Depends on :mailheader:`Accept` header of request
:>json datetime lastLoginTime: Updated lastLoginTime for the user
:statuscode 200: User last_login_time successfully bumped
@ -83,7 +83,7 @@ Authentication API
POST /auth/logout HTTP/1.1
Host: example.tld
Accept: application/json
Authorization: Token <Base64(user:userToken)>
X-Auth-Token: <Base64(user:userToken)>
**Example response**:
@ -98,7 +98,7 @@ Authentication API
}
:<header Accept: Response content type depends on :mailheader:`Accept` header
:<header Authorization: Rncoded token authorization
:<header X-Auth-Token: Encoded token authorization
:>header Content-Type: Depends on :mailheader:`Accept` header of request
:>json boolean success: Whether the logout was successful
:statuscode 200: User successfully logged out

2
server/documentation/api/index.rst

@ -7,3 +7,5 @@ Corvus API documentation
authentication
user
API documentation for the modules

30
server/documentation/api/user.rst

@ -12,7 +12,7 @@ User API
GET /user HTTP/1.1
Host: example.tld
Accept: application/json
Authorization: Token <Base64(user:userToken)>
X-Auth-Token: <Base64(user:userToken)>
**Example response**:
@ -31,7 +31,7 @@ User API
{
"creationTime": "2018-07-29T11:58:17-05:00",
"lastLoginTime": "2018-07-29T12:43:27-05:00",
"name": "corvus_administrator",
"name": "server_administrator",
"role": "ADMIN",
"version": 0
}
@ -41,7 +41,7 @@ User API
:query int page: User page to retrieve
:query int perPage: Number of records to retrieve per page (max 100)
:<header Accept: Response content type depends on :mailheader:`Accept` header
:<header Authorization: The encoded basic authorization
:<header X-Auth-Token: Encoded token authorization
:>header Content-Type: Depends on :mailheader:`Accept` header of request
:>json int page: Page retrieved
:>json int count: Number of items returned
@ -62,10 +62,10 @@ User API
.. sourcecode:: http
GET /user/corvus_administrator HTTP/1.1
GET /user/server_administrator HTTP/1.1
Host: example.tld
Accept: application/json
Authorization: Token <Base64(user:userToken)>
X-Auth-Token: <Base64(user:userToken)>
**Example response**:
@ -78,14 +78,14 @@ User API
{
"creationTime": "2018-07-29T11:58:17-05:00",
"lastLoginTime": "2018-07-29T12:43:27-05:00",
"name": "corvus_administrator",
"name": "server_administrator",
"role": "ADMIN",
"version": 0
}
:param string user_name: Name of the user to retrieve information about
:<header Accept: Response content type depends on :mailheader:`Accept` header
:<header Authorization: The encoded basic authorization
:<header X-Auth-Token: Encoded token authorization
:>header Content-Type: Depends on :mailheader:`Accept` header of request
:>json datetime creationTime: Creation time for the user
:>json datetime lastLoginTime: When the user last logged in, or was last bumped
@ -104,10 +104,10 @@ User API
.. sourcecode:: http
PATCH /user/corvus_administrator HTTP/1.1
PATCH /user/server_administrator HTTP/1.1
Host: example.tld
Accept: application/json
Authorization: Token <Base64(user:userToken)>
X-Auth-Token: <Base64(user:userToken)>
Content-Type: application/json
{
@ -126,14 +126,14 @@ User API
{
"creationTime": "2018-07-29T11:58:17-05:00",
"lastLoginTime": "2019-07-29T12:43:27-05:00",
"name": "corvus_administrator",
"name": "server_administrator",
"role": "ADMIN",
"version": 1
}
:param string user_name: Name of the user to update
:<header Accept: Response content type depends on :mailheader:`Accept` header
:<header Authorization: Encoded token authorization
:<header X-Auth-Token: Encoded token authorization
:<header Content-Type: application/json
:<json datetime createDateTime: Update createDateTime (Administrator Only)
:<json datetime lastLoginTime: Update lastLoginTime
@ -162,7 +162,7 @@ User API
POST /user HTTP/1.1
Host: example.tld
Accept: application/json
Authorization: Token <Base64(user:userToken)>
X-Auth-Token: <Base64(user:userToken)>
Content-Type: application/json
{
@ -187,7 +187,7 @@ User API
}
:<header Accept: Response content type depends on :mailheader:`Accept` header
:<header Authorization: Encoded token authorization
:<header X-Auth-Token: Encoded token authorization
:<header Content-Type: application/json
:<json string name: Name of the user
:<json string password: Password to use
@ -212,7 +212,7 @@ User API
DELETE /user/test_user HTTP/1.1
Host: example.tld
Accept: application/json
Authorization: Token <Base64(user:userToken)>
X-Auth-Token: <Base64(user:userToken)>
**Example response**:
@ -229,7 +229,7 @@ User API
:param string user_name: Name of the user to delete
:<header Accept: Response content type depends on :mailheader:`Accept` header
:<header Authorization: Encoded token authorization
:<header X-Auth-Token: Encoded token authorization
:>header Content-Type: Depends on :mailheader:`Accept` header of request
:>json string message: Success or failure message
:>json boolean success: Action status indicator

8
server/documentation/conf.py

@ -20,13 +20,13 @@
# -- Project information -----------------------------------------------------
project = 'Corvus'
copyright = '2018, Drew Short'
copyright = '2019, Drew Short'
author = 'Drew Short'
# The short X.Y version
version = '2018.8'
version = '2019.10'
# The full version, including alpha/beta/rc tags
release = '2018.8.1'
release = '2019.10.1'
# -- General configuration ---------------------------------------------------
@ -140,7 +140,7 @@ latex_documents = [
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'corvus', 'Corvus Documentation',
(master_doc, 'server', 'Corvus Documentation',
[author], 1)
]

12
server/documentation/introduction.rst

@ -1,4 +1,14 @@
Introduction To Corvus
========================
TODO
Corvus is the scaffolding for python web services. Among the things it offers are the following:
* Management CLI for working with users
* Prebuilt auth framework with roles and tokens
* Hierarchical role models
* Stong testing foundation
* Strong code formatting testing foundation
* PipEnv scaffold for ensuring reproducable builds
* Prebuilt docker environments for runtime
* Pythonenv integration
* Lightweight Flask backend

4
server/entrypoint.sh

@ -1,10 +1,10 @@
#!/usr/bin/env bash
# Migrate the Database
FLASK_APP=corvus:corvus flask db upgrade
FLASK_APP=server:server flask db upgrade
# Make sure an administrator is registered
python manage.py user register-admin
# Start the application
gunicorn -b 0.0.0.0:8080 corvus:corvus
gunicorn -b 0.0.0.0:8080 server:server

14
server/manage.py

@ -8,10 +8,10 @@ from typing import Optional
import click
from click import Context
from corvus import corvus
from corvus.model import User
from corvus.service import user_service
from corvus.service.role_service import ROLE_LIST
from server import server
from server.model import User
from server.service import user_service
from server.service.role_service import ROLE_LIST
logging.basicConfig()
@ -85,7 +85,7 @@ def register_user(
def register_admin_user(ctx: Context):
admin_users = User.query.filter_by(role=User.ROLE_ADMIN).all()
if len(admin_users) == 0:
name = 'corvus_administrator'
name = 'server_administrator'
password = ''.join(
random.choices(string.ascii_letters + string.digits, k=32))
ctx.invoke(
@ -150,6 +150,6 @@ user_command_group.add_command(reset_user_password)
user_command_group.add_command(list_users)
if __name__ == '__main__':
logging.debug('Managing: %s', corvus.name)
with corvus.app_context():
logging.debug('Managing: %s', server.name)
with server.app_context():
main()

10
server/run_tests.bat

@ -11,20 +11,20 @@ pipenv run pytest --version
pipenv run pycodestyle --version
pipenv run pydocstyle --version
pipenv run pylint corvus
pipenv run pylint server
if %errorlevel% neq 0 exit /b %errorlevel%
pipenv run mypy corvus tests
pipenv run mypy server tests
if %errorlevel% neq 0 exit /b %errorlevel%
pipenv run coverage run --source corvus -m pytest
pipenv run coverage run --source server -m pytest
if %errorlevel% neq 0 exit /b %errorlevel%
pipenv run coverage report --fail-under=85 -m --skip-covered
if %errorlevel% neq 0 exit /b %errorlevel%
pipenv run pycodestyle corvus tests
pipenv run pycodestyle server tests
if %errorlevel% neq 0 exit /b %errorlevel%
pipenv run pydocstyle corvus
pipenv run pydocstyle server
if %errorlevel% neq 0 exit /b %errorlevel%

12
server/run_tests.sh

@ -4,7 +4,7 @@ set -e
set -x
# shellcheck disable=SC2034
PIPENV_VERBOSITY=-1
export PIPENV_VERBOSITY=-1
pipenv run python3 --version
pipenv run python3 -m pip --version
@ -16,9 +16,9 @@ pipenv run pytest --version
pipenv run pycodestyle --version
pipenv run pydocstyle --version
pipenv run pylint corvus
pipenv run mypy corvus tests
PYTHONPATH=$(pwd) pipenv run coverage run --source corvus -m pytest
pipenv run pylint server
pipenv run mypy server tests
PYTHONPATH=$(pwd) pipenv run coverage run --source server -m pytest
pipenv run coverage report --fail-under=85 -m --skip-covered
pipenv run pycodestyle corvus tests
pipenv run pydocstyle corvus
pipenv run pycodestyle server tests
pipenv run pydocstyle server

42
server/corvus/__init__.py → server/server/__init__.py

@ -1,14 +1,14 @@
"""Corvus Flask Application."""
"""Flask Application."""
import os
from logging.config import dictConfig
from flask import Flask
from flask_migrate import Migrate
from corvus.db import db
from corvus.errors import BaseError, handle_corvus_base_error, \
handle_corvus_404_error
from corvus.utility import json_utility, session_utility
from server.db import db
from server.errors import BaseError, handle_base_error, \
handle_404_error
from server.utility import json_utility, session_utility
dictConfig({
'version': 1,
@ -29,18 +29,18 @@ dictConfig({
def create_app(test_config: dict = None) -> Flask:
"""
Create an instance of Corvus.
Create a server instance.
:param test_config:
:return:
"""
app = Flask(__name__, instance_relative_config=True)
app.logger.debug('Creating Corvus Server')
app.logger.debug('Creating Server')
data_directory = os.getenv('CORVUS_DATA_DIRECTORY', '/tmp')
app.logger.debug('Corvus Data Directory: %s', data_directory)
data_directory = os.getenv('SERVER_DATA_DIRECTORY', '/tmp')
app.logger.debug('Server Data Directory: %s', data_directory)
default_database_uri = 'sqlite:///{}/corvus.db'.format(data_directory)
default_database_uri = 'sqlite:///{}/server.db'.format(data_directory)
app.config.from_mapping(
SECRET_KEY='dev',
SQLALCHEMY_DATABASE_URI=default_database_uri,
@ -50,10 +50,10 @@ def create_app(test_config: dict = None) -> Flask:
if test_config is None:
app.logger.debug('Loading configurations')
app.config.from_object('corvus.default_settings')
app.config.from_object('server.default_settings')
app.config.from_pyfile('config.py', silent=True)
if os.getenv('CORVUS_SETTINGS', None):
app.config.from_envvar('CORVUS_SETTINGS')
if os.getenv('SERVER_SETTINGS', None):
app.config.from_envvar('SERVER_SETTINGS')
else:
app.logger.debug('Loading test configuration')
app.config.from_mapping(test_config)
@ -81,7 +81,7 @@ def register_blueprints(app: Flask) -> None:
:param app:
:return:
"""
from corvus.api import AUTH_BLUEPRINT, USER_BLUEPRINT, HEALTH_BLUEPRINT
from server.api import AUTH_BLUEPRINT, USER_BLUEPRINT, HEALTH_BLUEPRINT
app.register_blueprint(AUTH_BLUEPRINT)
app.register_blueprint(USER_BLUEPRINT)
app.register_blueprint(HEALTH_BLUEPRINT)
@ -94,15 +94,15 @@ def register_error_handlers(app: Flask) -> None:
:param app:
:return:
"""
app.register_error_handler(404, handle_corvus_404_error)
app.register_error_handler(BaseError, handle_corvus_base_error)
app.register_error_handler(404, handle_404_error)
app.register_error_handler(BaseError, handle_base_error)
corvus = create_app() # pylint: disable=C0103
register_blueprints(corvus)
register_error_handlers(corvus)
server = create_app() # pylint: disable=C0103
register_blueprints(server)
register_error_handlers(server)
logger = corvus.logger # pylint: disable=C0103
logger = server.logger # pylint: disable=C0103
if __name__ == "__main__":
corvus.run()
server.run()

4
server/server/api/__init__.py

@ -0,0 +1,4 @@
"""API blueprint exports."""
from server.api.authentication_api import AUTH_BLUEPRINT
from server.api.user_api import USER_BLUEPRINT
from server.api.health_api import HEALTH_BLUEPRINT

16
server/corvus/api/authentication_api.py → server/server/api/authentication_api.py

@ -1,19 +1,19 @@
"""Authentication API blueprint and endpoint definitions."""
from flask import Blueprint, g, abort, request
from corvus.api.decorators import return_json
from corvus.api.model import APIMessage, APIResponse, APIPage
from corvus.middleware import authentication_middleware
from corvus.service import (
from server.api.decorators import return_json
from server.api.model import APIMessage, APIResponse, APIPage
from server.middleware import authentication_middleware
from server.service import (
user_token_service,
authentication_service,
user_service,
transformation_service
)
from corvus.middleware.authentication_middleware import Auth
from corvus.service.role_service import Role
from corvus.model import UserToken
from corvus.utility.pagination_utility import get_pagination_params
from server.middleware.authentication_middleware import Auth
from server.service.role_service import Role
from server.model import UserToken
from server.utility.pagination_utility import get_pagination_params
AUTH_BLUEPRINT = Blueprint(
name='auth', import_name=__name__, url_prefix='/auth')

2
server/corvus/api/decorators.py → server/server/api/decorators.py

@ -4,7 +4,7 @@ from typing import Callable, Any
from flask import jsonify, Response
from corvus.api.model import APIResponse
from server.api.model import APIResponse
def return_json(func: Callable) -> Callable:

4
server/corvus/api/health_api.py → server/server/api/health_api.py

@ -1,8 +1,8 @@
"""Endpoint to expose the health of the application."""
from flask import Blueprint
from corvus.api.decorators import return_json
from corvus.api.model import APIResponse, APIMessage
from server.api.decorators import return_json
from server.api.model import APIResponse, APIMessage
HEALTH_BLUEPRINT = Blueprint(
name='health', import_name=__name__, url_prefix='/health')

2
server/corvus/api/model.py → server/server/api/model.py

@ -3,7 +3,7 @@ from typing import Any, List, Optional, Dict
from flask_sqlalchemy import Pagination
from corvus.db import db_model
from server.db import db_model
# pylint: disable=too-few-public-methods

20
server/corvus/api/user_api.py → server/server/api/user_api.py

@ -2,20 +2,20 @@
from flask import Blueprint, abort, request, g
from corvus.api.decorators import return_json
from corvus.api.model import APIResponse, APIMessage, APIPage
from corvus.middleware import authentication_middleware
from corvus.middleware.authentication_middleware import Auth
from corvus.model import User
from corvus.service import (
from server.api.decorators import return_json
from server.api.model import APIResponse, APIMessage, APIPage
from server.middleware import authentication_middleware
from server.middleware.authentication_middleware import Auth
from server.model import User
from server.service import (
patch_service,
transformation_service,
user_service
)
from corvus.service.patch_service import get_patch_fields
from corvus.service.role_service import Role
from corvus.utility.pagination_utility import get_pagination_params
from corvus.service.role_service import ROLE_LIST
from server.service.patch_service import get_patch_fields
from server.service.role_service import Role
from server.utility.pagination_utility import get_pagination_params
from server.service.role_service import ROLE_LIST
USER_BLUEPRINT = Blueprint(
name='user', import_name=__name__, url_prefix='/user')

0
server/corvus/db.py → server/server/db.py

2
server/corvus/default_settings.py → server/server/default_settings.py

@ -1,4 +1,4 @@
"""Default settings for corvus."""
"""Default settings for server."""
DEBUG = False
SECRET_KEY = b'\xb4\x89\x0f\x0f\xe5\x88\x97\xfe\x8d<\x0b@d\xe9\xa5\x87%' \

20
server/corvus/errors.py → server/server/errors.py

@ -1,14 +1,14 @@
"""Error definitions for Corvus."""
"""Error definitions."""
from typing import Dict
from werkzeug.exceptions import HTTPException
from corvus.api.decorators import return_json
from corvus.api.model import APIResponse, APIMessage
from server.api.decorators import return_json
from server.api.model import APIResponse, APIMessage
class BaseError(Exception):
"""Corvus Base Error Class (5xx errors)."""
"""Base Error Class (5xx errors)."""
def __init__(
self,
@ -30,7 +30,7 @@ class BaseError(Exception):
class ClientError(BaseError):
"""Corvus errors where the client is wrong (4xx errors)."""
"""Errors where the client is wrong (4xx errors)."""
def __init__(self,
message: str = 'Unknown client error',
@ -41,18 +41,18 @@ class ClientError(BaseError):
class ValidationError(ClientError):
"""Corvus Validation Error."""
"""Validation Error."""
@return_json
def handle_corvus_404_error(exception: HTTPException) -> APIResponse:
"""Error handler for 404 Corvus errors."""
def handle_404_error(exception: HTTPException) -> APIResponse:
"""Error handler for 404 errors."""
return APIResponse(
payload=APIMessage(False, 'Not Found'),
status=exception.code if exception.code is not None else 404)
@return_json
def handle_corvus_base_error(error: BaseError) -> APIResponse:
"""Error handler for basic Corvus raised errors."""
def handle_base_error(error: BaseError) -> APIResponse:
"""Error handler for basic raised errors."""
return APIResponse(payload=error, status=error.status_code)

0
server/corvus/middleware/__init__.py → server/server/middleware/__init__.py

8
server/corvus/middleware/authentication_middleware.py → server/server/middleware/authentication_middleware.py

@ -9,14 +9,14 @@ from flask import request, Response, g, json
from werkzeug.datastructures import Authorization
from werkzeug.http import bytes_to_wsgi, wsgi_to_bytes
from corvus.api.model import APIMessage
from corvus.service import (
from server.api.model import APIMessage
from server.service import (
authentication_service,
user_service,
user_token_service
)
from corvus.service.role_service import ROLES, Role
from corvus.service import transformation_service
from server.service.role_service import ROLES, Role
from server.service import transformation_service
class Auth(Enum):

2
server/server/model/__init__.py

@ -0,0 +1,2 @@
"""Expose models to be used."""
from server.model.user_model import User, UserToken

4
server/corvus/model/user_model.py → server/server/model/user_model.py

@ -1,8 +1,8 @@
"""User related SQLALchemy models."""
from sqlalchemy import Enum
from corvus.db import db
from corvus.service.role_service import Role
from server.db import db
from server.service.role_service import Role
class User(db.Model): # pylint: disable=too-few-public-methods

0
server/corvus/service/__init__.py → server/server/service/__init__.py

6
server/corvus/service/authentication_service.py → server/server/service/authentication_service.py

@ -5,9 +5,9 @@ from typing import Optional
from nacl import pwhash
from nacl.exceptions import InvalidkeyError
from corvus import errors
from corvus.model import User, UserToken
from corvus.service import user_token_service
from server import errors
from server.model import User, UserToken
from server.service import user_token_service
def validate_password_strength(proposed_password: str) -> str:

10
server/corvus/service/patch_service.py → server/server/service/patch_service.py

@ -1,11 +1,11 @@
"""Patching support for db.Model objects."""
from typing import Set, Optional, Any, Dict
from corvus import errors
from corvus.db import db_model
from corvus.model import User
from corvus.service import transformation_service
from corvus.service import validation_service
from server import errors
from server.db import db_model
from server.model import User
from server.service import transformation_service
from server.service import validation_service
def get_patch_fields(patch_json: Dict[str, Any]) -> Set[str]:

2
server/corvus/service/role_service.py → server/server/service/role_service.py

@ -1,4 +1,4 @@
"""Role service for Corvus."""
"""Role service."""
from collections import defaultdict
from enum import Enum
from typing import Optional, List, Set, Dict

4
server/corvus/service/transformation_service.py → server/server/service/transformation_service.py

@ -3,8 +3,8 @@ import logging
import re
from typing import Dict, Callable, Any, List, Optional, Type
from corvus import errors
from corvus.db import db_model
from server import errors
from server.db import db_model
LOGGER = logging.getLogger(__name__)

16
server/corvus/service/user_service.py → server/server/service/user_service.py

@ -8,20 +8,20 @@ from typing import Optional, Dict, Callable, Any, Tuple
from flask_sqlalchemy import Pagination
from iso8601 import iso8601
from corvus import errors
from corvus.db import db
from corvus.model import User
from corvus.service import role_service
from corvus.service.authentication_service import validate_password_strength
from corvus.service.transformation_service import (
from server import errors
from server.db import db
from server.model import User
from server.service import role_service
from server.service.authentication_service import validate_password_strength
from server.service.transformation_service import (
BaseTransformer,
register_transformer
)
from corvus.service.validation_service import (
from server.service.validation_service import (
BaseValidator,
register_validator
)
from corvus.utility import authentication_utility
from server.utility import authentication_utility
LOGGER = logging.getLogger(__name__)

8
server/corvus/service/user_token_service.py → server/server/service/user_token_service.py

@ -6,13 +6,13 @@ from typing import Optional, Dict, Callable, Any
from flask_sqlalchemy import Pagination
from iso8601 import iso8601, ParseError
from corvus.db import db
from corvus.model import User, UserToken
from corvus.service.transformation_service import (
from server.db import db
from server.model import User, UserToken
from server.service.transformation_service import (
BaseTransformer,
register_transformer
)
from corvus import errors
from server import errors
@register_transformer

8
server/corvus/service/validation_service.py → server/server/service/validation_service.py

@ -1,12 +1,12 @@
"""Validation service for Corvus models."""
"""Validation service for models."""
from typing import Type, Dict, Callable, Any, Set, Optional, Tuple
from sqlalchemy import orm
from corvus import errors
from corvus.db import db_model
from corvus.model import User
from server import errors
from server.db import db_model
from server.model import User
_changable_attribute_names: Dict[str, Set[str]] = {}

1
server/server/utility/__init__.py

@ -0,0 +1 @@
"""Utilities."""

0
server/corvus/utility/authentication_utility.py → server/server/utility/authentication_utility.py

8
server/corvus/utility/json_utility.py → server/server/utility/json_utility.py

@ -5,10 +5,10 @@ from typing import Any
import rfc3339
from flask.json import JSONEncoder
from corvus.api.model import APIResponse, BaseAPIMessage
from corvus.db import db
from corvus.errors import BaseError
from corvus.service.transformation_service import serialize_model
from server.api.model import APIResponse, BaseAPIMessage
from server.db import db
from server.errors import BaseError
from server.service.transformation_service import serialize_model
class CustomJSONEncoder(JSONEncoder):

2
server/corvus/utility/pagination_utility.py → server/server/utility/pagination_utility.py

@ -3,7 +3,7 @@ from typing import Tuple
from werkzeug.datastructures import MultiDict
from corvus import errors
from server import errors
def get_pagination_params(request_args: MultiDict) -> Tuple[int, int]:

0
server/corvus/utility/session_utility.py → server/server/utility/session_utility.py

4
server/setup.py

@ -1,8 +1,8 @@
from setuptools import setup
setup(
name='corvus',
packages=['corvus'],
name='server',
packages=['server'],
include_package_data=True,
install_requires=[
'flask',

4
server/tests/api/test_decorators.py

@ -2,8 +2,8 @@ from typing import Any
from flask import Response, Flask
from corvus.api.decorators import return_json
from corvus.api.model import APIResponse
from server.api.decorators import return_json
from server.api.model import APIResponse
@return_json

2
server/tests/api/test_user_api.py

@ -6,7 +6,7 @@ from flask.testing import FlaskClient
from tests.conftest import AuthActions
from corvus.service.role_service import ROLE_LIST
from server.service.role_service import ROLE_LIST
def test_get_users_happy_path(auth: AuthActions, client: FlaskClient):

26
server/tests/conftest.py

@ -10,10 +10,10 @@ from flask import Flask
from flask.testing import FlaskClient, FlaskCliRunner
from werkzeug.test import Client
from corvus import create_app, register_blueprints, register_error_handlers
from corvus.db import init_db
from corvus.model import User
from corvus.service import user_service
from server import create_app, register_blueprints, register_error_handlers
from server.db import init_db
from server.model import User
from server.service import user_service
def add_test_user() -> Tuple[str, str]:
@ -27,27 +27,27 @@ def add_test_user() -> Tuple[str, str]:
@pytest.fixture
def app() -> Generator[Flask, Any, Any]:
"""Create and configure a new corvus_app instance for each test."""
"""Create and configure a new server_app instance for each test."""
# create a temporary file to isolate the database for each test
db_fd, db_path = tempfile.mkstemp(suffix='.db')
test_database_uri = 'sqlite:///{}'.format(db_path)
# create the corvus_app with common test config
corvus_app = create_app({
# create the server_app with common test config
server_app = create_app({
'TESTING': True,
'SQLALCHEMY_DATABASE_URI': test_database_uri,
})
register_blueprints(corvus_app)
register_error_handlers(corvus_app)
register_blueprints(server_app)
register_error_handlers(server_app)
# create the database and load test data
with corvus_app.app_context():
with server_app.app_context():
init_db()
test_username, test_password = add_test_user()
corvus_app.config['test_username'] = test_username
corvus_app.config['test_password'] = test_password
server_app.config['test_username'] = test_username
server_app.config['test_password'] = test_password
# get_db().executescript(_data_sql)
yield corvus_app
yield server_app
# close and remove the temporary database
os.close(db_fd)

4
server/tests/middleware/test_authentication_middleware.py

@ -1,9 +1,9 @@
from mock import patch, MagicMock, Mock
from corvus.middleware.authentication_middleware import \
from server.middleware.authentication_middleware import \
authenticate_with_password, authenticate_with_token
middleware_module = 'corvus.middleware.authentication_middleware'
middleware_module = 'server.middleware.authentication_middleware'
@patch(middleware_module + '.g')

4
server/tests/service/test_authentication_service.py

@ -1,7 +1,7 @@
import pytest
from corvus import errors
from corvus.service import authentication_service
from server import errors
from server.service import authentication_service
def test_validate_password_strength_good_password():

6
server/tests/service/test_patch_service.py

@ -3,9 +3,9 @@ from datetime import datetime, timedelta
import pytest
from mock import MagicMock, patch
from corvus import errors
from corvus.model import UserToken, User
from corvus.service import patch_service, role_service
from server import errors
from server.model import UserToken, User
from server.service import patch_service, role_service
def test_patch_models():

2
server/tests/service/test_role_service.py

@ -1,4 +1,4 @@
from corvus.service.role_service import ROLES, Role
from server.service.role_service import ROLES, Role
def test_role_tree_find_roles_in_hierarchy():

8
server/tests/service/test_transformation_service.py

@ -2,14 +2,14 @@ from typing import Dict, Callable, Any
import pytest
from corvus import db
from corvus.model import UserToken
from corvus.service.transformation_service import (
from server import db
from server.model import UserToken
from server.service.transformation_service import (
BaseTransformer,
deserialize_model,
register_transformer,
serialize_model)
from corvus.service.user_token_service import UserTokenTransformer
from server.service.user_token_service import UserTokenTransformer
def test_serialize_model():

4
server/tests/service/test_validation_service.py

@ -1,5 +1,5 @@
from corvus.model import User
from corvus.service import role_service, validation_service
from server.model import User
from server.service import role_service, validation_service
def test_successful_validation():

Loading…
Cancel
Save