Skip to content

Commit

Permalink
QA: Register API test cases
Browse files Browse the repository at this point in the history
  • Loading branch information
mtreacy002 committed Jun 24, 2020
1 parent f3bb484 commit 9c0621a
Show file tree
Hide file tree
Showing 10 changed files with 252 additions and 78 deletions.
12 changes: 8 additions & 4 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,14 @@ env:
global:
- PGPORT=5432
before_script:
- psql -c 'create database bit_schema_test;' -U postgres
- psql -c 'create schema bitschema;' -U postgres
- psql -c 'create schema test_schema;' -U postgres
- psql -c 'create schema test_schema_2;' -U postgres
- psql -c 'CREATE DATABASE bit_schema_test;' -U postgres
- psql -c 'CREATE SCHEMA bitschema;' -U postgres -d bit_schema_test
- psql -c 'CREATE SCHEMA test_schema;' -U postgres -d bit_schema_test
- psql -c 'create SCHEMA test_schema_2;' -U postgres -d bit_schema_test
- psql -c '\dn;' -U postgres -d bit_schema_test
- psql -c 'show search_path;' -U postgres -d bit_schema_test
- psql -c "ALTER DATABASE bit_schema_test SET search_path TO bitschema,public;" -U postgres -d bit_schema_test
- psql -c 'show search_path;' -U postgres -d bit_schema_test
install:
- pip3 install -r requirements.txt
script:
Expand Down
1 change: 0 additions & 1 deletion app/api/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
def add_models_to_namespace(api_namespace):
api_namespace.models[register_user_api_model.name] = register_user_api_model


register_user_api_model = Model(
"User registration model",
{
Expand Down
33 changes: 19 additions & 14 deletions app/api/ms_api_utils.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
import logging
import requests
from http import HTTPStatus
from flask import json
import requests
from app import messages

# from requests.exceptions import HTTPError
from flask import json
# from urllib3.exceptions import HTTPError
# from werkzeug.exceptions import HTTPException

# set base url

Expand All @@ -22,18 +19,26 @@

# create instance
def post_request(request_url, data):

try:

response = requests.post(
request_url, json=data, headers={"Accept": "application/json"}
)
response.raise_for_status()
except requests.ConnectionError as e:
return f"{e.response.json()}", HTTPStatus.INTERNAL_SERVER_ERROR
except requests.HTTPError as e:
return f"{e.response.json()}", e.response.status_code
response_message = response.json()
response_code = response.status_code
except requests.exceptions.ConnectionError as e:
response_message = messages.INTERNAL_SERVER_ERROR
response_code = json.dumps(HTTPStatus.INTERNAL_SERVER_ERROR)
logging.fatal(f"{e}")
except requests.exceptions.HTTPError as e:
response_message = e.response.json()
response_code = e.response.status_code
except Exception as e:
return f"{e.response.json()}", e.response.status_code
else:
logging.warning(f"{response}")
return f"{response.json()}", response.status_code
response_message = messages.INTERNAL_SERVER_ERROR
response_code = json.dumps(HTTPStatus.INTERNAL_SERVER_ERROR)
logging.fatal(f"{e}")
finally:
logging.fatal(f"{response_message}")
return response_message, response_code

13 changes: 9 additions & 4 deletions app/api/resources/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
from app.api.ms_api_utils import post_request, BASE_MS_API_URL
from app import messages
from app.api.models.user import *
from app.api.validations.user import *


users_ns = Namespace("Users", description="Operations related to users")
add_models_to_namespace(users_ns)
Expand Down Expand Up @@ -47,13 +49,16 @@ def post(cls):

data = request.json

# send POST /register request to MS API and return response

is_valid = validate_user_registration_request_data(data)

if is_valid != {}:
return is_valid, HTTPStatus.BAD_REQUEST

result = post_request(f"{BASE_MS_API_URL}/register", data)

if result[1] == HTTPStatus.OK:
return f"{messages.USER_WAS_CREATED_SUCCESSFULLY}", HTTPStatus.CREATED
return messages.USER_WAS_CREATED_SUCCESSFULLY, HTTPStatus.CREATED
elif result[1] == HTTPStatus.INTERNAL_SERVER_ERROR:
return f"{messages.INTERNAL_SERVER_ERROR}", HTTPStatus.INTERNAL_SERVER_ERROR
return messages.INTERNAL_SERVER_ERROR, HTTPStatus.INTERNAL_SERVER_ERROR
else:
return result
45 changes: 27 additions & 18 deletions config.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,23 +49,32 @@ class BaseConfig(object):
# mail accounts
MAIL_DEFAULT_SENDER = os.getenv("MAIL_DEFAULT_SENDER")

DB_TYPE = os.getenv("DB_TYPE"),
DB_USERNAME = os.getenv("DB_USERNAME"),
DB_PASSWORD = os.getenv("DB_PASSWORD"),
DB_ENDPOINT = os.getenv("DB_ENDPOINT"),
DB_NAME = os.getenv("DB_NAME")
DB_TEST_NAME = os.getenv("DB_TEST_NAME")

@staticmethod
def build_db_uri(
db_type_arg=os.getenv("DB_TYPE"),
db_user_arg=os.getenv("DB_USERNAME"),
db_password_arg=os.getenv("DB_PASSWORD"),
db_endpoint_arg=os.getenv("DB_ENDPOINT"),
db_name_arg=os.getenv("DB_NAME"),
db_type_arg = os.getenv("DB_TYPE"),
db_user_arg = os.getenv("DB_USERNAME"),
db_password_arg = os.getenv("DB_PASSWORD"),
db_endpoint_arg = os.getenv("DB_ENDPOINT"),
db_name_arg = os.getenv("DB_NAME"),
):
"""Build remote database uri using specific environment variables."""

return "{db_type}://{db_user}:{db_password}@{db_endpoint}/{db_name}".format(
db_type=db_type_arg,
db_user=db_user_arg,
db_password=db_password_arg,
db_endpoint=db_endpoint_arg,
db_name=db_name_arg,
)
return f"{db_type_arg}://{db_user_arg}:{db_password_arg}@{db_endpoint_arg}/{db_name_arg}"

@staticmethod
def build_db_test_uri(
db_type_arg = os.getenv("DB_TYPE"),
db_user_arg = os.getenv("DB_USERNAME"),
db_password_arg = os.getenv("DB_PASSWORD"),
db_endpoint_arg = os.getenv("DB_ENDPOINT"),
db_name_arg = os.getenv("DB_TEST_NAME"),
):
return f"{db_type_arg}://{db_user_arg}:{db_password_arg}@{db_endpoint_arg}/{db_name_arg}"

class LocalConfig(BaseConfig):
"""Local configuration."""
Expand All @@ -74,6 +83,7 @@ class LocalConfig(BaseConfig):

# Using a local postgre database
SQLALCHEMY_DATABASE_URI = "postgresql:///bit_schema"

# SQLALCHEMY_DATABASE_URI = BaseConfig.build_db_uri()

class DevelopmentConfig(BaseConfig):
Expand All @@ -89,19 +99,18 @@ class TestingConfig(BaseConfig):

# Using a local postgre database
SQLALCHEMY_DATABASE_URI = "postgresql:///bit_schema_test"

# SQLALCHEMY_DATABASE_URI = BaseConfig.build_db_test_uri()

class StagingConfig(BaseConfig):
"""Staging configuration."""

DEBUG = True
# SQLALCHEMY_DATABASE_URI = BaseConfig.build_db_uri()
SQLALCHEMY_DATABASE_URI = "postgresql:///bit_schema"
SQLALCHEMY_DATABASE_URI = BaseConfig.build_db_uri()


class ProductionConfig(BaseConfig):
# SQLALCHEMY_DATABASE_URI = BaseConfig.build_db_uri()
SQLALCHEMY_DATABASE_URI = "postgresql:///bit_schema"
SQLALCHEMY_DATABASE_URI = BaseConfig.build_db_uri()


def get_env_config() -> str:
Expand Down
7 changes: 7 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,13 @@ lazy-object-proxy==1.4.3
Mako==1.1.2
MarkupSafe==1.1.1
mccabe==0.6.1
more-itertools==8.4.0
packaging==20.4
paramiko==2.7.1
pathspec==0.8.0
pluggy==0.13.1
psycopg2-binary==2.8.3
py==1.8.2
pycodestyle==2.6.0
pycparser==2.18
pyflakes==2.2.0
Expand All @@ -60,7 +64,10 @@ pylint-flask==0.6
pylint-plugin-utils==0.6
PyMySQL==0.9.2
PyNaCl==1.3.0
pyparsing==2.4.7
pyrsistent==0.16.0
pytest==5.4.3
pytest-cov==2.10.0
python-dateutil==2.7.3
python-dotenv==0.8.2
python-editor==1.0.4
Expand Down
19 changes: 1 addition & 18 deletions run.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import os
from flask import Flask, jsonify

# from flask_restx import Resource, Api
from config import get_env_config
from flask_migrate import Migrate, MigrateCommand
from flask_cors import CORS
from config import get_env_config

cors = CORS()

Expand Down Expand Up @@ -64,10 +62,6 @@ def create_tables():

from app.database.sqlalchemy_extension import db

# to clear mock data
# !!! WARNING!!! Uncomment the line below ONLY when you want to clear all data in the database to start fresh
# db.drop_all()

from app.database.models.ms_schema.user import UserModel
from app.database.models.ms_schema.mentorship_relation import (
MentorshipRelationModel,
Expand All @@ -84,17 +78,8 @@ def create_tables():
MentorshipRelationExtensionModel,
)

# uncomment the line below if no dummy data needed on INITIAL setup!
# !!! Warning !!! Do not uncomment if this is not your INITIAL setup to database!
db.create_all()

# uncomment lines below if you want to add dummy data on INITIAL setup!
# !!! Warning!!! Treat this with caution as it will mess up your db!!
# Warning !!! Do not uncomment if this is not your INITIAL setup to database!

# from app.database.db_add_mock import add_mock_data # uncomment here
# add_mock_data()

@application.shell_context_processor
def make_shell_context():
return {
Expand All @@ -110,7 +95,5 @@ def make_shell_context():
"MentorshipRelationExtensionModel": MentorshipRelationExtensionModel,
}

# test

if __name__ == "__main__":
application.run(port=5000)
19 changes: 2 additions & 17 deletions tests/base_test_case.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,24 +21,9 @@ def setUp(self):

db.create_all()

# register first user which is admin user



# self.admin_user = UserModel(
# name=test_admin_user["name"],
# email=test_admin_user["email"],
# username=test_admin_user["username"],
# password=test_admin_user["password"],
# terms_and_conditions_checked=test_admin_user[
# "terms_and_conditions_checked"
# ],
# )
# db.session.add(self.admin_user)
# db.session.commit()
# self.admin_user.is_email_verified = True

@classmethod
def tearDown(cls):
db.session.remove()
db.drop_all()
db.drop_all()

3 changes: 1 addition & 2 deletions tests/test_app_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,8 @@ def test_app_production_config(self):
self.assertFalse(application.config["DEBUG"])
self.assertFalse(application.config["TESTING"])
self.assertFalse(application.config["SQLALCHEMY_TRACK_MODIFICATIONS"])
# self.assertEqual('mysql_something', application.config['SQLALCHEMY_DATABASE_URI'])
self.assertIsNotNone(current_app)


if __name__ == "__main__":
unittest.main()
unittest.main()
Loading

0 comments on commit 9c0621a

Please sign in to comment.