Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
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
30 changes: 29 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,35 @@ automatically [pip](https://pip.pypa.io/en/stable/) as well.

The `stage` can be `dev` or `prod`.
Remember to do it with Python 3.


- 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 what is the name of the SQL Driver installation.
Check it out with:

```bash
vim /usr/local/etc/odbcinst.ini
```

It may display something like

```.ini
[ODBC Driver 17 for SQL Server]
Description=Microsoft ODBC Driver 17 for SQL Server
Driver=/usr/local/lib/libmsodbcsql.17.dylib
UsageCount=2
```

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
```

To troubleshoot issues regarding this part please check out:
- [Install the Microsoft ODBC driver for SQL Server (macOS)](https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/install-microsoft-odbc-driver-sql-server-macos?view=sql-server-ver15).
- Github issue [odbcinst: SQLRemoveDriver failed with Unable to find component name](https://github.com/Microsoft/homebrew-mssql-preview/issues/2).
- Stack overflow solution to [Can't open lib 'ODBC Driver 13 for SQL Server'? Sym linking issue?](https://stackoverflow.com/questions/44527452/cant-open-lib-odbc-driver-13-for-sql-server-sym-linking-issue).

### How to use it
- Set the env var `FLASK_APP` to `time_tracker_api` and start the app:
Expand Down Expand Up @@ -122,7 +151,6 @@ the win.
[API import restrictions and known issues](https://docs.microsoft.com/en-us/azure/api-management/api-management-api-import-restrictions)
in Azure.


## License

Copyright 2020 ioet Inc. All Rights Reserved.
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
5 changes: 4 additions & 1 deletion requirements/dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,7 @@ pytest-mock==2.0.0
Faker==4.0.2

# Coverage
coverage==4.5.1
coverage==4.5.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
24 changes: 21 additions & 3 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,36 @@
import pytest
from _pytest.fixtures import FixtureRequest
from flask import Flask
from flask.testing import FlaskClient

from time_tracker_api import create_app

CONFIGURATIONS = ['AzureSQLDatabaseDevelopTestConfig']

@pytest.fixture(scope='session')
def app() -> Flask:

@pytest.fixture(scope='session', params=CONFIGURATIONS)
def app(request: FixtureRequest) -> Flask:
"""An instance of the app for tests"""
return create_app()
return create_app("time_tracker_api.config.%s" % request.param)


@pytest.fixture
def client(app: Flask) -> FlaskClient:
"""A test client for the app."""
with app.test_client() as c:
return c


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

seeder.fresh()

from time_tracker_api.sql_repository import SQLRepository
yield SQLRepository(PersonSQLModel)

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()
12 changes: 12 additions & 0 deletions tests/resources.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from time_tracker_api.sql_repository import db, SQLAuditedModel


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=False, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
age = db.Column(db.Integer, nullable=False)

def __repr__(self):
return '<Test Model %r>' % self.name
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
89 changes: 89 additions & 0 deletions tests/sql_repository_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
from faker import Faker

fake = Faker()

existing_elements_registry = []
last_deleted_element = None


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.

global sample_element
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)


def test_find(sql_repository):
"""Should find created element"""
existing_element = existing_elements_registry[0]

found_element = sql_repository.find(existing_element.id)

assert found_element is not None
assert found_element.id is not None


def test_update(sql_repository):
"""Updates an existing element"""
Copy link
Contributor

Choose a reason for hiding this comment

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

no need to have comments, please remove them and make test name consistent

Copy link
Contributor Author

Choose a reason for hiding this comment

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

In Java I would not have put comments, but this is Python. It is common here put comments even in modules. This is a test that tests the function called update. This is very simple.

existing_element = existing_elements_registry[0]

updated_element = sql_repository.update(existing_element.id,
dict(name="Jon Snow", age=34))

assert updated_element is not None
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):
"""Find all existing elements"""
existing_elements = sql_repository.find_all()

assert all(e in existing_elements_registry for e in existing_elements)


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)"""
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)

search_snow_result = sql_repository.find_all_contain_str('name', 'Snow')
assert len(search_snow_result) == 2

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', fake_name)
assert search_ram_result[0].name == new_element['name']


def test_delete_existing_element(sql_repository):
"""Should delete created element"""
existing_element = existing_elements_registry[0]

result = sql_repository.remove(existing_element.id)

assert result is None

global last_deleted_model
last_deleted_model = existing_elements_registry.pop()
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
Loading