Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Refactor codebase to use solution of #25
  • Loading branch information
EliuX committed Mar 20, 2020
commit bafb867f7a33362636cf7036fdef1b785caf2076
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ automatically [pip](https://pip.pypa.io/en/stable/) as well.


- Install the [Microsoft ODBC Driver for SQL Server](https://docs.microsoft.com/en-us/sql/connect/odbc/microsoft-odbc-driver-for-sql-server?view=sql-server-ver15)
in your operative system. Then you have to check out how is called the SQL Driver installation.
in your operative system. Then you have to check out what is the name of the SQL Driver installation.
Check it out with:

```bash
Expand All @@ -55,7 +55,7 @@ Driver=/usr/local/lib/libmsodbcsql.17.dylib
UsageCount=2
```

Then when you specify the driver name, e.g. _DBC Driver 17 for SQL Server_ in the `DATABASE_URI`. E.g.
Then specify the driver name, in this case _DBC Driver 17 for SQL Server_ in the `DATABASE_URI`, e.g.:

```.dotenv
DATABASE_URI=mssql+pyodbc://<user>:<password>@time-tracker-srv.database.windows.net/<database>?driver\=ODBC Driver 17 for SQL Server
Expand Down
21 changes: 20 additions & 1 deletion cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@
from flask_script import Manager

from time_tracker_api import create_app

app = create_app('time_tracker_api.config.CLIConfig')

from time_tracker_api.api import api

app = create_app()
cli_manager = Manager(app)


Expand Down Expand Up @@ -44,6 +46,23 @@ def gen_postman_collection(filename='timetracker-api-postman-collection.json',
save_data(parsed_json, filename)


@cli_manager.command
def seed():
from time_tracker_api.database import seeder as seed
seed()


@cli_manager.command
def re_create_db():
print('This is going to drop all tables and seed again the database')
confirm_answer = input('Do you confirm (Y) you want to remove all your data?\n')
if confirm_answer.upper() == 'Y':
from time_tracker_api.database import seeder
seeder.fresh()
else:
print('\nThis action was cancelled!')


def save_data(data: str, filename: str) -> None:
""" Save text content to a file """
if filename:
Expand Down
4 changes: 2 additions & 2 deletions requirements/dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@ Faker==4.0.2
# Coverage
coverage==4.5.1

# SQL database (MS SQL)
flask_sqlalchemy==2.4.1
# The Debug Toolbar
Flask-DebugToolbar==0.11.0
10 changes: 8 additions & 2 deletions requirements/prod.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,13 @@ Jinja2==2.11.1
gunicorn==20.0.4

#Swagger support for Restful API
flask-restplus==0.13.0
flask-restplus==0.12.1

#CLI support
Flask-Script==2.0.6
Flask-Script==2.0.6

# SQL database (MS SQL)
flask_sqlalchemy==2.4.1

# Handling requests
requests==2.23.0
19 changes: 9 additions & 10 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,15 @@ def client(app: Flask) -> FlaskClient:


@pytest.fixture(scope="module")
def sql_repository(app: Flask):
with app.app_context():
from .resources import TestModel
from time_tracker_api.sql_repository import db
def sql_repository():
from .resources import PersonSQLModel
from time_tracker_api.database import seeder
from time_tracker_api.sql_repository import db

db.create_all()
print("Models for test created!")
seeder.fresh()

from time_tracker_api.sql_repository import SQLRepository
yield SQLRepository(TestModel)
from time_tracker_api.sql_repository import SQLRepository
yield SQLRepository(PersonSQLModel)

print("Models for test removed!")
db.drop_all()
db.drop_all()
print("Models for test removed!")
10 changes: 8 additions & 2 deletions tests/projects/projects_namespace_test.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
from flask import json
from flask.testing import FlaskClient
from pytest_mock import MockFixture


def test_list_should_return_nothing(client):
"""Should return an empty array"""
def test_list_all_elements(client: FlaskClient, mocker: MockFixture):
"""Should return all elements in a list"""
from time_tracker_api.projects.projects_namespace import project_dao
repository_find_all_mock = mocker.patch.object(project_dao.repository, 'find_all', return_value=[])

response = client.get("/projects", follow_redirects=True)

assert 200 == response.status_code

json_data = json.loads(response.data)
assert [] == json_data
repository_find_all_mock.assert_called_once()
7 changes: 4 additions & 3 deletions tests/resources.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from time_tracker_api.sql_repository import db
from time_tracker_api.sql_repository import db, SQLAuditedModel


class TestModel(db.Model):
class PersonSQLModel(db.Model, SQLAuditedModel):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the reason to have SQL as part of the class name?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because this is the SQLAlchemy model, not a generic one

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it extremelly necessat to include SQL as part of the name?

Copy link
Contributor Author

@EliuX EliuX Mar 20, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, because this model is specific to the SQL implementation. As well as I have the SQL prefix in the repository and other resources related to this particular technology, which has its own characteristics: specific library, handling of commits, rollbacks, the concept of tables, columns and so forth, which is not the same as, for instance, an In-memory implementation, a Mongo Implementation, etc.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just by looking it has the SQL prefix you know that this has SQL-specific logic.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We are not going to add support for Mongo, in-memory or so. We should not pollute code with implementation details.

__tablename__ = 'tests'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True, nullable=False)
name = db.Column(db.String(80), unique=False, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
age = db.Column(db.Integer, nullable=False)

Expand Down
1 change: 0 additions & 1 deletion tests/smoke_test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

def test_app_exists(app):
"""Does app exists"""
assert app is not None
26 changes: 16 additions & 10 deletions tests/sql_repository_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,19 @@

def test_create(sql_repository):
"""Should create a new Entry"""
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not naming the function/method name as

test_creates_a_new_entry

Then you can get rid of comments

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function just tests the function create of the repository, this is a simple and unique name. As I explained before the comment in the function is providing a verbose description of the test.

from .resources import TestModel
global sample_element
sample_element = TestModel(name=fake.name(),
email=fake.safe_email(),
age=fake.pyint(min_value=10, max_value=80))
sample_element = dict(name=fake.name(),
email=fake.safe_email(),
age=fake.pyint(min_value=10, max_value=80))

result = sql_repository.create(sample_element)

assert result is not None
assert result.id is not None
assert result.created_at is not None
assert result.created_by is not None
assert result.updated_at is None
assert result.updated_by is None

existing_elements_registry.append(result)

Expand All @@ -43,6 +46,9 @@ def test_update(sql_repository):
assert updated_element.id == existing_element.id
assert updated_element.name == "Jon Snow"
assert updated_element.age == 34
assert updated_element.updated_at is not None
assert updated_element.updated_at > updated_element.created_at
assert updated_element.updated_by is not None


def test_find_all(sql_repository):
Expand All @@ -54,10 +60,10 @@ def test_find_all(sql_repository):

def test_find_all_that_contains_property_with_string(sql_repository):
"""Find all elements that have a property that partially contains a string (case-insensitive)"""
from .resources import TestModel
new_element = TestModel(name='Ramsay Snow',
email=fake.safe_email(),
age=fake.pyint(min_value=10, max_value=80))
fake_name = fake.name()
new_element = dict(name="%s Snow" % fake_name,
email=fake.safe_email(),
age=fake.pyint(min_value=10, max_value=80))
sql_repository.create(new_element)
existing_elements_registry.append(new_element)

Expand All @@ -67,8 +73,8 @@ def test_find_all_that_contains_property_with_string(sql_repository):
search_jon_result = sql_repository.find_all_contain_str('name', 'Jon')
assert len(search_jon_result) == 1

search_ram_result = sql_repository.find_all_contain_str('name', 'RAM')
assert search_ram_result[0] is new_element
search_ram_result = sql_repository.find_all_contain_str('name', fake_name)
assert search_ram_result[0].name == new_element['name']


def test_delete_existing_element(sql_repository):
Expand Down
Empty file removed tests/time_entries/__init__.py
Empty file.
17 changes: 0 additions & 17 deletions tests/time_entries/time_entries_namespace_test.py

This file was deleted.

24 changes: 24 additions & 0 deletions time_tracker_api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@

from flask import Flask

flask_app: Flask = None


def create_app(config_path='time_tracker_api.config.DefaultConfig',
config_data=None):
global flask_app
flask_app = Flask(__name__)

init_app_config(flask_app, config_path, config_data)
Expand Down Expand Up @@ -36,3 +39,24 @@ def init_app(app: Flask):

from .api import api
api.init_app(app)

if app.config.get('DEBUG'):
add_debug_toolbar(app)


def add_debug_toolbar(app):
app.config['DEBUG_TB_PANELS'] = (
'flask_debugtoolbar.panels.versions.VersionDebugPanel',
'flask_debugtoolbar.panels.timer.TimerDebugPanel',
'flask_debugtoolbar.panels.headers.HeaderDebugPanel',
'flask_debugtoolbar.panels.request_vars.RequestVarsDebugPanel',
'flask_debugtoolbar.panels.config_vars.ConfigVarsDebugPanel',
'flask_debugtoolbar.panels.template.TemplateDebugPanel',
'flask_debugtoolbar.panels.logger.LoggingPanel',
'flask_debugtoolbar.panels.route_list.RouteListDebugPanel',
'flask_debugtoolbar.panels.profiler.ProfilerDebugPanel'
)

from flask_debugtoolbar import DebugToolbarExtension
toolbar = DebugToolbarExtension()
toolbar.init_app(app)
3 changes: 2 additions & 1 deletion time_tracker_api/activities/activities_namespace.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from faker import Faker
from flask_restplus import fields, Resource, Namespace

from time_tracker_api.api import audit_fields
from faker import Faker

faker = Faker()

Expand Down
71 changes: 63 additions & 8 deletions time_tracker_api/api.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
from flask_restplus import Api, fields
import pyodbc

import sqlalchemy
from faker import Faker
from flask import current_app as app
from flask_restplus import Api, fields

faker = Faker()

api = Api(version='1.0.1', title="TimeTracker API",
api = Api(version='1.0.1',
title="TimeTracker API",
description="API for the TimeTracker project")

# Common models structure
Expand All @@ -14,31 +19,81 @@
description='Date of creation',
example=faker.iso8601(end_datetime=None),
),
'tenant_id': fields.String(
'updated_at': fields.Date(
readOnly=True,
title='Tenant',
max_length=64,
description='The tenant this belongs to',
example=faker.random_int(1, 9999),
title='Updated',
description='Date of update',
example=faker.iso8601(end_datetime=None),
),
# TODO Activate it when the tenants model is implemented
# 'tenant_id': fields.String(
# readOnly=True,
# title='Tenant',
# max_length=64,
# description='The tenant this belongs to',
# example=faker.random_int(1, 9999),
# ),
'created_by': fields.String(
readOnly=True,
title='Creator',
max_length=64,
description='User that created it',
example=faker.random_int(1, 9999),
example='anonymous',
),
'updated_by': fields.String(
readOnly=True,
title='Updater',
max_length=64,
description='User that updated it',
example='anonymous',
),
}

# APIs
from time_tracker_api.projects import projects_namespace

api.add_namespace(projects_namespace.ns)

from time_tracker_api.activities import activities_namespace

api.add_namespace(activities_namespace.ns)

from time_tracker_api.technologies import technologies_namespace

api.add_namespace(technologies_namespace.ns)

from time_tracker_api.time_entries import time_entries_namespace

api.add_namespace(time_entries_namespace.ns)

"""
Error handlers
"""


@api.errorhandler(sqlalchemy.exc.IntegrityError)
def handle_db_integrity_error(e):
"""Handles errors related to data consistency"""
if e.code == 'gkpj':
return {'message': 'It already exists.'}, 409
else:
return {'message': 'Data integrity issues.'}, 409


@api.errorhandler(sqlalchemy.exc.DataError)
def handle_invalid_data_error(e):
"""Return a 422 because the user entered data of an invalid type"""
return {'message': 'The processed data was invalid. Please correct it.'}, 422


@api.errorhandler(pyodbc.OperationalError)
def handle_connection_error(e):
"""Return a 500 due to a issue in the connection to a 3rd party service"""
return {'message': 'Connection issues. Please try again in a few minutes.'}, 500


@api.errorhandler
def generic_exception_handler(e):
if not app.config.get("FLASK_DEBUG", False):
app.logger.error(e)
return {'message': 'An unhandled exception occurred.'}, 500
Loading