Exemplo n.º 1
0
    def __init__(self):
        """Creates application instances for all parliaments."""
        self.instances = {}
#        with open(os.path.join(os.path.dirname(__file__), 'parliaments.json'), 'r') as f:
#            parliaments = json.load(f)
#        for parl, conf in parliaments.items():
#            self.instances[parl] = create_app(parl, conf)
        self.instances['ovolby'] = create_app({})
Exemplo n.º 2
0
	def __init__(self):
		"""Creates application instances for all parliaments."""
		self.instances = {}
		with open(os.path.join(os.path.dirname(__file__), 'conf', 'parliaments.json'), 'r') as f:
			parliaments = json.load(f)
		for c, cp in parliaments.items():
			for p in cp:
				pfx = c + '/' + p['code']
				self.instances[pfx] = create_app(c, p)
Exemplo n.º 3
0
 def setUp(self):
     self.app = shaservice.create_app().test_client()
     self.json_data = {
         "empty": json.dumps({}),
         "valid": json.dumps({"foo": "bar", "bar": "baz"})
     }
     self.hashes = {
         "empty": "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a",
         "valid": "e8e02f85df24c0220e706521f44c42a5c25d91ae366c7c892304023b226cbcb1"
     }
Exemplo n.º 4
0
def test_collection_items():
    conn = MongoClient()
    db = conn.mypropertydb
    data_table = db.properties
    items = 0
    for item in data_table.find():
        items += 1

    app = run.create_app()
    clint = app.test_client()
    res = clint.get('api/properties')
    data = res.get_json()

    assert items == len(data['result'])
Exemplo n.º 5
0
    def setUp(self, settings_file=None, url_converters=None):

        self.this_directory = os.path.dirname(os.path.realpath(__file__))

        if settings_file is None:
            settings_file = SETTINGS_PATH

        self.connection = None
        self.setupDB()

        self.settings_file = settings_file
        self.app = create_app(SETTINGS_PATH)
        self.app.testing = True

        self.test_client = self.app.test_client()

        self.domain = self.app.config['DOMAIN']
    def setUpClass(cls):
        app = create_app("test_config")
        app.testing = True
        app.app_context().push()
        cls.test = app.test_client()
        #create local database
        db = SQLAlchemy(app)
        with app.app_context():
            Doctor.__table__.create(bind=db.engine)
            Patient.__table__.create(bind=db.engine)
            Nurse.__table__.create(bind=db.engine)
        with open('sampleData.json') as data_file:
            test_DataBaseFacade.data = json.load(data_file)
        #db.session.add_all([testdoctor, testnurse, testpatient])
        db.session.commit()

        test_DataBaseFacade.database_facade = DatabaseFacade.getInstance(db)
Exemplo n.º 7
0
def app():
    """Set up and tear down the test app."""
    from run import create_app, db

    app = create_app('testing')

    app.config['TESTING'] = True

    app_context = app.app_context()
    app_context.push()

    db.create_all()

    yield app

    db.session.remove()
    db.drop_all()
    app_context.pop()
Exemplo n.º 8
0
def client():
    """Exposes a test client for the app with a temporary database that can be
    used for unit testing

    Notes
    -----
    In order for a unit test to have access to this test client, the fixture
    must be listed as a parameter in the test definition
    """
    app = create_app()
    app.config["DEBUG"] = True

    # create test client and database
    with app.test_client() as client:
        with app.app_context():
            db.drop_all()
            db.create_all()  # Create sql tables for our data models
            populate()
            yield client
 def setUpClass(cls):
     app = create_app("test_config")
     app.testing = True
     cls.test = app.test_client()
     db = SQLAlchemy(app)
     with app.app_context():
         Doctor.__table__.create(bind=db.engine)
         Patient.__table__.create(bind=db.engine)
         Nurse.__table__.create(bind=db.engine)
     with open('sampleData.json') as data_file:
         FacadeLoginTests.data = json.load(data_file)
     testdoctor = AccountAdapter.createFromJSON(
         'Doctor', FacadeLoginTests.data["json_doc"])
     testpatient = AccountAdapter.createFromJSON(
         'Patient', FacadeLoginTests.data["json_pat_case"])
     testnurse = AccountAdapter.createFromJSON(
         'Nurse', FacadeLoginTests.data["json_nur"])
     #correction to date
     testpatient.birth_day = date(1997, 9, 16)
     db.session.add_all([testdoctor, testnurse, testpatient])
     db.session.commit()
Exemplo n.º 10
0
def test_page_items_with_ratio():
    app = run.create_app()
    clint = app.test_client()
    res = clint.get(
        'api/properties?page=1&feed_ratio=[{%22feed%22:%2011,%22ratio%22:%2024},{%22feed%22:%2012,%22ratio%22:%2012},{%22feed%22:%2016,%22ratio%22:%2012}]'
    )
    data = res.get_json()
    len_11 = 0
    len_12 = 0
    len_16 = 0
    for i in data['result']:
        for key, value in i.items():
            if key == 'Feed':
                if value == '11':
                    len_11 += 1

                elif value == '12':
                    len_12 += 1

                else:
                    len_16 += 1

    assert len(data['result']
               ) == 48 and len_11 == 24 and len_12 == 12 and len_16 == 12
Exemplo n.º 11
0
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from data.models import db
from run import create_app

app = create_app('dev')

migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)


if __name__ == '__main__':
    manager.run()


# Run migrations initialization
# python migrate.py db init

# Run the migration
# python migrate.py db migrate

# Then apply the migration to the database
# python migrate.py db upgrade
 def create_app():
     return create_app("TestingConfig")
Exemplo n.º 13
0
 def setUp(self):
     self.app = create_app("config")
     ctx = self.app.app_context()
     ctx.push()
Exemplo n.º 14
0
 def setUpClass(self):
     print('### Setting up flask server ###')
     app = create_app("config")
     app.config['TESTING'] = True
     self.app = app.test_client()
Exemplo n.º 15
0
    def setUp(self):
        """Define test variables and initialize app."""

        self.app = create_app(config_name="testing")
        self.app.testing = True
        self.client = self.app.test_client()
 def setUp(self):
     self.app = create_app("TestingConfig")
Exemplo n.º 17
0
 def create_app():
     app = create_app("tests.config.TestConfig")
     initialise_db(app)
     return app
Exemplo n.º 18
0
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from flask_script import Manager

from run import create_app


app = create_app()
manager = Manager(app)

if __name__ == '__main__':
    manager.run()
Exemplo n.º 19
0
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
#from Model import db
from Models.Client import db
from run import create_app

app = create_app('config')

migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()
Exemplo n.º 20
0
def test_empty_page():
    app = run.create_app()
    clint = app.test_client()
    res = clint.get('api/properties?page=6')
    data = res.get_json()
    assert len(data['result']) == 0
Exemplo n.º 21
0
def app():
    return create_app()
 def setUp(self):
     self.app = create_app("config")
     ctx = self.app.app_context()
     ctx.push()
     self.reseller_repository = ResellerRepository()
     self.purchase_repository = PurchaseRepository()
Exemplo n.º 23
0
def app() -> Flask:
    return create_app()
Exemplo n.º 24
0
class TestDB(unittest.TestCase):
    """ Test case for the CRUD methods."""
    app = create_app('config.TestingConfig')

    @classmethod
    def setUpClass(cls) -> None:
        """ Method runs once for the entire test class before tests.
        Creating connection to database. """
        with cls.app.app_context():
            db.drop_all()
            db.create_all()

    @classmethod
    def tearDownClass(cls) -> None:
        """ Method runs once for the entire test class after tests.
        Destroying connection to database. """
        with cls.app.app_context():
            db.session.remove()
            db.drop_all()

    def setUp(self) -> None:
        """ Method runs before every test. Filling database with data. """
        with self.app.app_context():
            id_ = ds.add(name='HR', email='*****@*****.**')
            es.add(name='Mary', birthday=date(2000, 9, 22), department=id_,
                   working_since=date(2020, 1, 13), salary=30000.0)

    def tearDown(self) -> None:
        """ Method runs after every test. Remove data from database. """
        with self.app.app_context():
            db.drop_all()
            db.create_all()

    def test_get_all_departments(self):
        """ Test getting the list of all departments in database. """
        with self.app.app_context():
            self.assertNotEqual(ds.get_all(), [])

    def test_add_department(self):
        """ Test adding new department to database. """
        with self.app.app_context():
            ds.add(name='IT')
            self.assertEqual(len(ds.get_all()), 2)

    def test_get_existing_department(self):
        """ Test getting existing department from database. """
        with self.app.app_context():
            self.assertTrue(ds.get_by_name('HR'))

    def test_get_non_existing_department(self):
        """ Test getting non-existing department from database. """
        with self.app.app_context():
            with self.assertRaises(Exception):
                ds.get_by_name('ITIT')

    def test_update_department(self):
        """ Test updating existing department in database. """
        with self.app.app_context():
            department = ds.get_by_name('HR')
            ds.update(id_=department.id,
                      name=department.name)
            self.assertNotEqual(department.email, '*****@*****.**')

    def test_get_all_employees(self):
        """ Test getting the list of all employees in database. """
        with self.app.app_context():
            self.assertNotEqual(es.get_all(), [])

    def test_add_employee(self):
        """ Test adding new employee to database. """
        with self.app.app_context():
            id_ = ds.get_by_name('HR').id
            es.add(name='Mary', birthday=date(2000, 9, 22), department=id_,
                   working_since=date(2020, 1, 13), salary=30000.0)
            self.assertEqual(len(es.get_all()), 2)

    def test_get_existing_employee(self):
        """ Test getting existing employee from database. """
        with self.app.app_context():
            self.assertTrue(es.get_by_name('Mary'))

    def test_get_non_existing_employee(self):
        """ Test getting non-existing employee from database. """
        with self.app.app_context():
            self.assertIsNone(es.get_by_name('Polina'))

    def test_update_employee(self):
        """ Test updating existing employee in database. """
        with self.app.app_context():
            mary = es.get_by_name('Mary')
            es.update(id_=mary.id,
                      name=mary.name,
                      birthday=mary.birthday,
                      working_since=mary.working_since,
                      salary=333333,
                      department=ds.get_by_name('HR').id)
            self.assertNotEqual(mary.salary, 30000.0)

    def test_delete_data_from_tables(self):
        """ Test deleting all data from employee and department tables."""
        with self.app.app_context():
            es.delete_all()
            ds.delete_all()
            self.assertEqual(ds.get_all(), [])
            self.assertEqual(es.get_all(), [])

    def test_delete_certain_department(self):
        """ Test deleting certain department by id. """
        with self.app.app_context():
            id_ = ds.add('IT')
            with self.assertRaises(Exception):
                ds.delete(id_)
                self.assertIsNone(ds.get_by_name('IT'))

    def test_delete_certain_employee(self):
        """ Test deleting certain employee by id. """
        with self.app.app_context():
            employee_id = es.get_by_name('Mary').id
            es.delete(employee_id)
            self.assertIsNone(es.get_by_name('Mary'))

    def test_find_by_birthday(self):
        """ Test finding all employees with birthday between received dates."""
        with self.app.app_context():
            employees = es.find_by_birthday(date(2000, 9, 1), date(2000, 9, 23))
            self.assertEqual(1, len(employees))
            employees = es.find_by_birthday(date(1990, 9, 1), date(1990, 9, 23))
            self.assertEqual(0, len(employees))

    def test_get_employee_error(self):
        """ Test getting IntegrityError passing invalid id for employee."""
        with self.app.app_context():
            with self.assertRaises(Exception) as context:
                es.get(1111)

            self.assertEqual("Can't get employee with id 1111",
                             str(context.exception))

    def test_manipulate_department_error(self):
        """ Test getting IntegrityError passing invalid id for department in
        different functions."""
        with self.app.app_context():
            with self.assertRaises(Exception) as context:
                ds.get(1111)

            self.assertEqual("Can't get department with id 1111",
                             str(context.exception))

            with self.assertRaises(Exception) as context:
                ds.delete(1111)

            self.assertEqual("Can't delete department with id 1111",
                             str(context.exception))

            with self.assertRaises(Exception) as context:
                ds.update(1111, 'name', 'email')

            self.assertEqual("Can't update department with id 1111",
                             str(context.exception))

    def test_show_employees_by_birthday(self):
        """ Test getting list of employees with birthday between certain
        dates."""
        with self.app.app_context():
            employees = es.find_by_birthday(
                start=date(2000, 9, 20),
                end=date(2000, 9, 23))
            self.assertEqual(len(employees), 1)
            employees = es.find_by_birthday(
                start=date(2010, 9, 20),
                end=date(2010, 9, 23))
            self.assertEqual(len(employees), 0)
Exemplo n.º 25
0
# -*- coding: UTF-8 -*-
__author__ = 'Joynice'

from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from run import create_app
from exts import db
from front.models import Images
app = create_app()

manager = Manager(app)
Migrate(app, db)
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()
Exemplo n.º 26
0
import os
import unittest
import tempfile
import pytest
import run

app = run.create_app()


def test_get_data():
    with app.test_client() as test_url:
        url = test_url.get("http://127.0.0.1:5000/api/pagination")
        assert url.status_code == 200


def test_without_ratio():
    with app.test_client() as test_url:
        url = test_url.get("http://127.0.0.1:5000/api/pagination?page=1")
        assert url.status_code == 200


def test_get_req_without_api():
    with app.test_client() as test_url:
        url = test_url.get("http://127.0.0.1:5000")
        assert url.status_code == 404


def test_less_ratio():
    with app.test_client() as test_url:
        url = test_url.get(
            "http://127.0.0.1:5000/api/pagination?feed_ratio=[{'feed':12,'ratio':16}, {'feed':16,'ratio':16}]&page=1"
 def create_app():
     return create_app('TestingConfig')
Exemplo n.º 28
0
def add_dummy_data(environment):
    ''' Create dummy data for the given environment'''

    try:
        flask_app = create_app(environment)
        flask_app.app_context().push()

        # Create some useful dummy data for demos
        user = User(name="Chris Ellis",
                    username="******",
                    email="*****@*****.**",
                    password="******")
        db.session.add(user)
        db.session.commit()
        print("Added:", user)

        # # Audio engineering
        # pitch = Pitch(name = "Amazing new speaker technology", user_id = user.id)
        # db.session.add(pitch)
        # db.session.commit()
        # print("Added:", pitch)

        # pitch_try = PitchTry(pitch_id=pitch.id, transcription="Hey there I am doing research for new audio technologies are you interested in hearing more", duration=8)
        # db.session.add(pitch_try)
        # db.session.commit()
        # print("Added:", pitch_try)

        # pitch_try = PitchTry(pitch_id=pitch.id, transcription="Hey i am interested in audio engineering how about you there are some cool things we can do with it", duration=12)
        # db.session.add(pitch_try)
        # db.session.commit()
        # print("Added:", pitch_try)

        # pitch_try = PitchTry(pitch_id=pitch.id, transcription="My name is Chris and I work with audio technologies we have new research that is paving the way for some exciting breakthroughs that will push the boundaries of audio engineering as we know it today", duration=20)
        # db.session.add(pitch_try)
        # db.session.commit()
        # print("Added:", pitch_try)

        # Pet sitting service
        # pitch = Pitch(name = "Pet sitting service", user_id = user.id)
        # db.session.add(pitch)
        # db.session.commit()
        # print("Added:", pitch)

        # pitch_try = PitchTry(pitch_id=pitch.id, transcription="Hey I run a pet sitting service. If you have a dog or cat i can pet sit it", duration=8)
        # db.session.add(pitch_try)
        # db.session.commit()
        # print("Added:", pitch_try)

        # pitch_try = PitchTry(pitch_id=pitch.id, transcription="I am a pet sitter. Call me if you need anyone to watch your pets! My number is 123 456 7829", duration=10)
        # db.session.add(pitch_try)
        # db.session.commit()
        # print("Added:", pitch_try)

        # pitch_try = PitchTry(pitch_id=pitch.id, transcription="I am a highly-rated pet sitter. I love watching pets and treat them like family. You can count on me if you ever are in need of a pet-sitter. my email is [email protected]", duration=13)
        # db.session.add(pitch_try)
        # db.session.commit()
        # print("Added:", pitch_try)

        ### User: Dummy Data
        ##############################################
        # print("Adding user data.")
        # with open(os.path.join(DUMMY_DATA_PATH, 'user.csv'), newline='') as csvfile:
        #     reader = csv.DictReader(csvfile)
        #     for row in reader:
        #         user = User(name = row['name'], email = row['email'], password="******")
        #         db.session.add(user)

        # db.session.commit()

    except Exception as e:
        print(e)
        print("[!] An error occurred while trying to add dummy data. Exiting.")
        exit()
import logging
import structlog

from retrying import RetryError
from run import create_app, configure_structlogger, initialise_db

# This is a duplicate of run.py, with minor modifications to support gunicorn execution.

logger = structlog.wrap_logger(logging.getLogger(__name__))

config_path = "config.Config"

app = create_app(config_path)

configure_structlogger(app.config)

try:
    initialise_db(app)
except RetryError:
    logger.exception('Failed to initialise database')
    exit(1)
 def setUp(self):
     self.app = create_app("config")
     ctx = self.app.app_context()
     ctx.push()
     self.reseller_service = ResellerService()
import unittest
import json
from run import create_app

from Model import db
from classes.DatabaseFacade import DatabaseFacade


app = create_app("config")
app.app_context().push()


class test_DataBaseFacade(unittest.TestCase):


    def test_registerDoctor(self):
        with open('sampleData.json') as data_file:
            data = json.load(data_file)
        database_facade = DatabaseFacade.getInstance(db)
        database_facade.registerDoctor(data['json_doc'])
        doctor = database_facade.getDoctorsByPermitNumber("56765")
        assert doctor.last_name == "Nickel"
        database_facade.removeDoctor(data['json_doc'])

    def test_registerNurse(self):
        with open('sampleData.json') as data_file:
            data = json.load(data_file)
        database_facade = DatabaseFacade.getInstance(db)
        database_facade.registerNurse(data['json_nur'])
        nurse = database_facade.getNursesByAccessId("3434")
        assert nurse.last_name == "YOLO"
Exemplo n.º 32
0
def test_status_code():
    app = run.create_app()
    clint = app.test_client()
    res = clint.get('api/properties')
    assert res.status_code == 200
Exemplo n.º 33
0
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from run import create_app
from config import Config
from app.db import db
from app.models.person import Person
from app.models.address import Address

app = create_app(Config)

migrate = Migrate(app, db)
manager = Manager(app)

manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()
Exemplo n.º 34
0
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from models import db
from run import create_app
import os

app = create_app(os.environ['APP_SETTINGS'])
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
migrate = Migrate(app, db)
manager = Manager(app)

manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()