Ejemplo n.º 1
1
    def setUp(self):
        self.app = create_app('TESTING_CONFIG')
        self.app_context = self.app.app_context()
        self.app_context.push()
        self.client = self.app.test_client()
        self.basedir = os.path.abspath(os.path.dirname(__file__))
        db.create_all()
        test_password = '******'
        Organization.insert_org()
        UserScope.insert_scopes()
        User.insert_user(password=test_password)

        self.client = self.app.test_client(use_cookies=False)

        # set the vars for the connection
        self.cmisUrl =  \
            'https://alfresco.oceanobservatories.org/alfresco/s/api/cmis'
        self.cmisUsername = '******'
        self.cmisPassword = '******'
        self.cmisId = 'c161bc66-4f7e-4a4f-b5f2-aac9fbf1d3cd'

        # cmis is tested elsewhere

        from cmislib.model import CmisClient
        client = CmisClient(self.cmisUrl, self.cmisUsername, self.cmisPassword)
        repo = client.getRepository(self.cmisId)
Ejemplo n.º 2
0
def deploy(password, bulkload):
    from flask.ext.migrate import upgrade
    from ooiservices.app.models import User, UserScope, UserScopeLink, Array
    from ooiservices.app.models import PlatformDeployment, InstrumentDeployment, Stream, StreamParameterLink
    from sh import psql
    #Create the local database
    app.logger.info('Creating DEV and TEST Databases')
    psql('-c', 'create database ooiuidev;', '-U', 'postgres')
    psql('ooiuidev', '-c', 'create schema ooiui')
    psql('ooiuidev', '-c', 'create extension postgis')
    #Create the local test database
    psql('-c', 'create database ooiuitest;', '-U', 'postgres')
    psql('ooiuitest', '-c', 'create schema ooiui')
    psql('ooiuitest', '-c', 'create extension postgis')
    db.create_all()
    if bulkload:
        with open('db/ooiui_schema_data.sql') as f:
            psql('ooiuidev', _in=f)
        app.logger.info('Bulk test data loaded.')

    # migrate database to latest revision
    #upgrade()
    UserScope.insert_scopes()
    app.logger.info('Insert default user, name: admin')
    User.insert_user(password=password)
    admin = User.query.first()
    admin.scopes.append(UserScope.query.filter_by(scope_name='user_admin').first())
    db.session.add(admin)
    db.session.commit()
Ejemplo n.º 3
0
def rebuild_schema(schema, schema_owner):
    """
    Creates the OOI UI Services schema based on models.py
    :usage: python manage.py rebuild_schema --schema ooiui --schema_owner postgres --backup_schema True
    :param schema:
    :param schema_owner:
    :return:
    """

    # Check if schema exists
    sql = "SELECT schema_name FROM information_schema.schemata WHERE schema_name = '{0}'".format(schema)
    sql_result = db.engine.execute(sql).first()
    if sql_result != None:
        # Move current schema to _timestamp
        timestamp = int((datetime.utcnow() - datetime(1970, 1, 1)).total_seconds())
        app.logger.info('Backing up schema container {0} to {0}_{1}'.format(schema, timestamp))
        db.engine.execute('ALTER SCHEMA {0} RENAME TO {0}_{1}'.format(schema, timestamp))

    #app.logger.info('Dropping schema container: {0}'.format(schema))
    #db.engine.execute('DROP SCHEMA %s CASCADE' % schema)

    app.logger.info('Creating schema container: {0}'.format(schema))
    db.engine.execute('CREATE SCHEMA IF NOT EXISTS {0} AUTHORIZATION {1}'.format(schema, schema_owner))

    app.logger.info('Building schema objects')
    db.create_all()

    app.logger.info('Adding base user_scopes')
    UserScope.insert_scopes()
Ejemplo n.º 4
0
    def setUp(self):
        self.app = create_app('TESTING_CONFIG')
        self.app_context = self.app.app_context()
        self.app_context.push()
        from sqlalchemy.orm.mapper import configure_mappers
        configure_mappers()
        db.create_all()

        test_username = '******'
        test_password = '******'
        Organization.insert_org()
        User.insert_user(username=test_username, password=test_password, email='*****@*****.**')


        OperatorEventType.insert_operator_event_types()

        self.client = self.app.test_client(use_cookies=False)

        UserScope.insert_scopes()

        admin = User.query.filter_by(user_name='admin').first()
        scope = UserScope.query.filter_by(scope_name='asset_manager').first()
        admin.scopes.append(scope)

        db.session.add(admin)
        db.session.commit()

        joe = User.insert_user(username='******', password='******', email='*****@*****.**')
        bob = User.insert_user(username='******', password='******', email='*****@*****.**')
Ejemplo n.º 5
0
    def setUp(self):
        self.app = create_app('TESTING_CONFIG')
        self.app_context = self.app.app_context()
        self.app_context.push()
        from sqlalchemy.orm.mapper import configure_mappers
        configure_mappers()
        db.create_all()

        test_username = '******'
        test_password = '******'
        Organization.insert_org()
        User.insert_user(username=test_username,
                         password=test_password,
                         email='*****@*****.**')

        OperatorEventType.insert_operator_event_types()

        self.client = self.app.test_client(use_cookies=False)

        UserScope.insert_scopes()

        admin = User.query.filter_by(user_name='admin').first()
        scope = UserScope.query.filter_by(scope_name='user_admin').first()
        admin.scopes.append(scope)

        db.session.add(admin)
        db.session.commit()

        joe = User.insert_user(username='******',
                               password='******',
                               email='*****@*****.**')
        bob = User.insert_user(username='******',
                               password='******',
                               email='*****@*****.**')
Ejemplo n.º 6
0
 def setUp(self):
     self.app = create_app('TESTING_CONFIG')
     self.app_context = self.app.app_context()
     self.app_context.push()
     db.create_all()
     self.client = self.app.test_client(use_cookies=False)
     User.insert_user(username=test_username, password=test_password)
     UserScope.insert_scopes()
Ejemplo n.º 7
0
 def setUp(self):
     self.app = create_app('TESTING_CONFIG')
     self.app_context = self.app.app_context()
     self.app_context.push()
     db.create_all()
     self.client = self.app.test_client(use_cookies=False)
     Organization.insert_org()
     User.insert_user(username=test_username, password=test_password)
     UserScope.insert_scopes()
Ejemplo n.º 8
0
    def test_put_user_changes(self):
        '''
        test ability to create new user and change scopes and/or active status of new user
        '''
        headers = self.get_api_headers('admin', 'test')

        # 1. get current user
        response = self.client.get(url_for('main.get_current_user'), headers=headers)
        self.assertEquals(response.status_code,  200)

        # 2. Create new user - test_user duplicate test
        data=json.dumps({'email': 'test@test', 'password': '******', 'repeatPassword': '******',
                         'role_name':'Administrator','username': '******','first_name':'Tester',
                         'last_name':'Testing', 'organization_id':1, 'role_id': 1})
        response = self.client.post(url_for('main.create_user'), headers=headers, data=data)
        self.assertEquals(response.status_code, 201)

        # 3a. Add scope for user_admin
        UserScope.insert_scopes()
        admin = User.query.filter_by(user_name='admin').first()
        scope = UserScope.query.filter_by(scope_name='user_admin').first()
        admin.scopes.append(scope)
        db.session.add(admin)
        db.session.commit()

        # 3b. Get all users
        response = self.client.get(url_for('main.get_users'), headers=headers)
        self.assertEquals(response.status_code, 200)

        # 4. Verify user count is now == 2
        response_data = response.data[:]
        self.assertTrue(len(response_data) > 0)
        self.assertTrue(type(response_data) == type(''))
        self.assertTrue('users' in response_data)
        user_data = json.loads(response_data)
        user_list = user_data['users']
        self.assertTrue(len(user_list) == 2)

        # 5. Update new user's scopes, add scopes = ['asset_manager']
        expected_data = {'active': True, 'scopes': ['asset_manager'], 'role_id': 1}
        data = json.dumps(expected_data)
        response = self.client.put(url_for('main.put_user', id=2), headers=headers, data=data)
        self.assertTrue(response.status_code == 201)

        # 6. Get the new (and updated) user
        response = self.client.get(url_for('main.get_user',id=2), headers=headers)
        self.assertTrue(response.status_code == 200)

        # 7. Verify new user data includes expected_data: scopes=['asset_manager'] and 'active' == True
        response_data = response.data[:]
        self.assertTrue(len(response_data) > 0)
        self.assertTrue(type(response_data) == type(''))
        self.assertTrue('active' in response_data)
        self.assertTrue('scopes' in response_data)
        dict_data = json.loads(response_data)
        self.assertTrue(dict_data['active'] == expected_data['active'])
        self.assertTrue(dict_data['scopes'] == expected_data['scopes'])
Ejemplo n.º 9
0
    def setUp(self):
        self.app = create_app('TESTING_CONFIG')
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()
        test_password = '******'
        Organization.insert_org()
        UserScope.insert_scopes()
        User.insert_user(password=test_password)

        self.client = self.app.test_client(use_cookies=False)
Ejemplo n.º 10
0
    def setUp(self):
        self.app = create_app("TESTING_CONFIG")
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()
        test_password = "******"
        Organization.insert_org()
        UserScope.insert_scopes()
        User.insert_user(password=test_password, email="test@localhost")

        self.client = self.app.test_client(use_cookies=False)
Ejemplo n.º 11
0
    def test_put_user_route(self):
        '''
        test ability to change current user ('admin') scopes
        '''
        headers = self.get_api_headers('admin', 'test')

        # add scopes to user_name admin
        UserScope.insert_scopes()
        admin = User.query.filter_by(user_name='admin').first()
        scope = UserScope.query.filter_by(scope_name='user_admin').first()
        admin.scopes.append(scope)
        db.session.add(admin)
        db.session.commit()

        # 1. get current user (username 'admin')
        response = self.client.get(url_for('main.get_current_user'),
                                   headers=headers)
        self.assertTrue(response.status_code == 200)

        # 2. update current user's scopes = ['user_admin', 'asset_manager']
        data = json.dumps({'scopes': ['user_admin', 'asset_manager']})
        response = self.client.put(url_for('main.put_user', id=1),
                                   headers=headers,
                                   data=data)
        self.assertTrue(response.status_code == 201)

        # 3. Observe current use, verify new scope ('asset_manager') added
        response = self.client.get(url_for('main.get_current_user'),
                                   headers=headers)
        self.assertTrue(response.status_code == 200)

        # 4. Change scopes back to single scope of 'user_admin'; send redundant active value
        expected_data = {'active': True, 'scopes': ['user_admin']}
        data = json.dumps(expected_data)
        response = self.client.put(url_for('main.put_user', id=1),
                                   headers=headers,
                                   data=data)
        self.assertTrue(response.status_code == 201)

        # 5. Assert: (1) response.data is string, (2) greater than 0 in length and (3) contains 'user roles'
        response_data = response.data[:]
        self.assertTrue(len(response_data) > 0)
        self.assertTrue(type(response_data) == type(''))
        self.assertTrue('active' in response_data)
        self.assertTrue('scopes' in response_data)

        # 6. Create dictionary from resonse_data; compare response_data with expected data dict
        dict_data = json.loads(response_data)
        self.assertTrue('active' in dict_data)
        self.assertTrue('active' in expected_data)
        self.assertTrue(dict_data['active'] == expected_data['active'])
        self.assertTrue(dict_data['scopes'] == expected_data['scopes'])
Ejemplo n.º 12
0
    def test_get_users_route(self):
        '''
        get all users; currently scope_required is 'user_admin'
        '''
        #TODO: if role_required is utilized, suggest using @role_required('administrator').
        #TODO: (See also, arrays.py delete_array)
        UserScope.insert_scopes()
        admin = User.query.filter_by(user_name='admin').first()
        scope = UserScope.query.filter_by(scope_name='user_admin').first()
        admin.scopes.append(scope)
        db.session.add(admin)
        db.session.commit()

        response = self.client.get(url_for('main.get_users'), headers=self.get_api_headers('admin', 'test'))
        self.assertTrue(response.status_code == 200)
Ejemplo n.º 13
0
    def test_get_users_route(self):
        """
        get all users; currently scope_required is 'user_admin'
        """
        # TODO: if role_required is utilized, suggest using @role_required('administrator').
        # TODO: (See also, arrays.py delete_array)
        UserScope.insert_scopes()
        admin = User.query.filter_by(user_name="admin").first()
        scope = UserScope.query.filter_by(scope_name="user_admin").first()
        admin.scopes.append(scope)
        db.session.add(admin)
        db.session.commit()

        response = self.client.get(url_for("main.get_users"), headers=self.get_api_headers("admin", "test"))
        self.assertTrue(response.status_code == 200)
    def setUp(self):
        self.app = create_app('TESTING_CONFIG')
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()
        test_username = '******'
        test_password = '******'
        Organization.insert_org()
        User.insert_user(username=test_username, password=test_password)

        self.client = self.app.test_client(use_cookies=False)
        UserScope.insert_scopes()
        admin = User.query.filter_by(user_name='admin').first()
        scope = UserScope.query.filter_by(scope_name='user_admin').first()
        admin.scopes.append(scope)
        db.session.add(admin)
        db.session.commit()
Ejemplo n.º 15
0
    def test_put_user_route(self):
        """
        test ability to change current user ('admin') scopes
        """
        headers = self.get_api_headers("admin", "test")

        # add scopes to user_name admin
        UserScope.insert_scopes()
        admin = User.query.filter_by(user_name="admin").first()
        scope = UserScope.query.filter_by(scope_name="user_admin").first()
        admin.scopes.append(scope)
        db.session.add(admin)
        db.session.commit()

        # 1. get current user (username 'admin')
        response = self.client.get(url_for("main.get_current_user"), headers=headers)
        self.assertTrue(response.status_code == 200)

        # 2. update current user's scopes = ['user_admin', 'asset_manager']
        data = json.dumps({"scopes": ["user_admin", "asset_manager"]})
        response = self.client.put(url_for("main.put_user", id=1), headers=headers, data=data)
        self.assertTrue(response.status_code == 201)

        # 3. Observe current use, verify new scope ('asset_manager') added
        response = self.client.get(url_for("main.get_current_user"), headers=headers)
        self.assertTrue(response.status_code == 200)

        # 4. Change scopes back to single scope of 'user_admin'; send redundant active value
        expected_data = {"active": True, "scopes": ["user_admin"]}
        data = json.dumps(expected_data)
        response = self.client.put(url_for("main.put_user", id=1), headers=headers, data=data)
        self.assertTrue(response.status_code == 201)

        # 5. Assert: (1) response.data is string, (2) greater than 0 in length and (3) contains 'user roles'
        response_data = response.data[:]
        self.assertTrue(len(response_data) > 0)
        self.assertTrue(type(response_data) == type(""))
        self.assertTrue("active" in response_data)
        self.assertTrue("scopes" in response_data)

        # 6. Create dictionary from resonse_data; compare response_data with expected data dict
        dict_data = json.loads(response_data)
        self.assertTrue("active" in dict_data)
        self.assertTrue("active" in expected_data)
        self.assertTrue(dict_data["active"] == expected_data["active"])
        self.assertTrue(dict_data["scopes"] == expected_data["scopes"])
Ejemplo n.º 16
0
    def setUp(self):
        self.app = create_app('TESTING_CONFIG')
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()
        test_password = '******'
        Organization.insert_org()
        UserScope.insert_scopes()
        User.insert_user(password=test_password)

        self.client = self.app.test_client(use_cookies=False)
        self.basedir = os.path.abspath(os.path.dirname(__file__))
        with open(self.basedir + '/mock_data/event_post.json', 'r') as f:
            doc = json.load(f)
        self.event_json_in = doc

        with open(self.basedir + '/mock_results/event_from.json', 'r') as f:
            doc = json.load(f)
        self.event_from_json = doc
Ejemplo n.º 17
0
    def setUp(self):
        self.app = create_app('TESTING_CONFIG')
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()
        test_password = '******'
        Organization.insert_org()
        UserScope.insert_scopes()
        User.insert_user(password=test_password)

        self.client = self.app.test_client(use_cookies=False)
        self.basedir = os.path.abspath(os.path.dirname(__file__))
        with open(self.basedir + '/mock_data/event_post.json', 'r') as f:
            doc = json.load(f)
        self.event_json_in = doc

        with open(self.basedir + '/mock_results/event_from.json', 'r') as f:
            doc = json.load(f)
        self.event_from_json = doc
Ejemplo n.º 18
0
    def test_get_user_scope_route(self):

        headers = self.get_api_headers("admin", "test")

        # Test unauthorized
        response = self.client.get(url_for("main.get_user_scopes"), content_type="application/json")
        self.assertTrue(response.status_code == 401)

        UserScope.insert_scopes()

        admin = User.query.filter_by(user_name="admin").first()
        scope = UserScope.query.filter_by(scope_name="user_admin").first()
        admin.scopes.append(scope)
        db.session.add(admin)
        db.session.commit()

        # Test authorized
        response = self.client.get(url_for("main.get_user_scopes"), headers=headers)
        self.assertTrue(response.status_code == 200)

        # Expected user_scopes
        user_scopes_data = {
            "user_scopes": [
                {"id": 1, "scope_description": None, "scope_name": "user_admin"},
                {"id": 2, "scope_description": None, "scope_name": "command_control"},
                {"id": 3, "scope_description": None, "scope_name": "annotate"},
                {"id": 4, "scope_description": None, "scope_name": "asset_manager"},
                {"id": 5, "scope_description": None, "scope_name": "sys_admin"},
                {"id": 6, "scope_description": None, "scope_name": "redmine"},
                {"id": 7, "scope_description": None, "scope_name": "data_manager"},
                {"id": 8, "scope_description": None, "scope_name": "organization"},
            ]
        }

        # assert: (1) response.data is string, (2) greater than 0 in length and (3) contains 'user roles'
        response_data = response.data[:]
        self.assertTrue(len(response_data) > 0)
        self.assertTrue(type(response_data) == type(""))
        self.assertTrue("user_scopes" in response_data)

        # create dictionary from string; compare response data with expected user scopes
        dict_scopes = json.loads(response_data)
        self.assertTrue(dict_scopes == user_scopes_data)
    def setUp(self):
        self.app = create_app("TESTING_CONFIG")
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()
        test_username = "******"
        test_password = "******"
        Organization.insert_org()

        User.insert_user(username=test_username, password=test_password)

        self.client = self.app.test_client(use_cookies=False)
        UserScope.insert_scopes()
        admin = User.query.filter_by(user_name="admin").first()
        scope = UserScope.query.filter_by(scope_name="user_admin").first()
        cc_scope = UserScope.query.filter_by(scope_name="command_control").first()
        admin.scopes.append(scope)
        admin.scopes.append(cc_scope)
        db.session.add(admin)
        db.session.commit()

        self.headers = self.get_api_headers("admin", "test")
Ejemplo n.º 20
0
def deploy(password, bulkload):
    from flask.ext.migrate import upgrade
    from ooiservices.app.models import User, UserScope, UserScopeLink, Array, Organization
    from ooiservices.app.models import PlatformDeployment, InstrumentDeployment, Stream, StreamParameterLink
    from sh import psql
    #Create the local database
    app.logger.info('Creating DEV and TEST Databases')
    psql('-c', 'create database ooiuidev;', '-U', 'postgres')
    psql('ooiuidev', '-c', 'create schema ooiui')
    psql('ooiuidev', '-c', 'create extension postgis')
    #Create the local test database
    psql('-c', 'create database ooiuitest;', '-U', 'postgres')
    psql('ooiuitest', '-c', 'create schema ooiui')
    psql('ooiuitest', '-c', 'create extension postgis')
    from sqlalchemy.orm.mapper import configure_mappers
    configure_mappers()
    db.create_all()
    if bulkload:
        with open('db/ooiui_schema_data.sql') as f:
            psql('ooiuidev', _in=f)
        app.logger.info('Bulk test data loaded.')

    # migrate database to latest revision
    #upgrade()
    if not os.getenv('TRAVIS'):
        Organization.insert_org()
        UserScope.insert_scopes()
        app.logger.info('Insert default user, name: admin')
        User.insert_user(password=password)
        admin = User.query.first()
        admin.scopes.append(UserScope.query.filter_by(scope_name='user_admin').first())
        admin.scopes.append(UserScope.query.filter_by(scope_name='redmine').first())
        db.session.add(admin)
        db.session.commit()
        if bulkload:
            with open('db/ooiui_schema_data_notifications.sql') as f:
                psql('ooiuidev', _in=f)
            app.logger.info('Bulk test data loaded for notifications.')
Ejemplo n.º 21
0
    def test_get_user_scope_route(self):

        headers = self.get_api_headers('admin', 'test')

        #Test unauthorized
        response = self.client.get(url_for('main.get_user_scopes'),
                                   content_type='application/json')
        self.assertTrue(response.status_code == 401)

        UserScope.insert_scopes()

        admin = User.query.filter_by(user_name='admin').first()
        scope = UserScope.query.filter_by(scope_name='user_admin').first()
        admin.scopes.append(scope)
        db.session.add(admin)
        db.session.commit()

        #Test authorized
        response = self.client.get(url_for('main.get_user_scopes'),
                                   headers=headers)
        self.assertTrue(response.status_code == 200)

        # Expected user_scopes
        user_scopes_data = \
            {"user_scopes": [{"id": 1, "scope_description": None, "scope_name": "annotate"},
                             {"id": 2, "scope_description": None, "scope_name": "asset_manager"},
                             {"id": 3, "scope_description": None, "scope_name": "user_admin"},
                             {"id": 4, "scope_description": None, "scope_name": "redmine"} ]}

        # assert: (1) response.data is string, (2) greater than 0 in length and (3) contains 'user roles'
        response_data = response.data[:]
        self.assertTrue(len(response_data) > 0)
        self.assertTrue(type(response_data) == type(''))
        self.assertTrue('user_scopes' in response_data)

        # create dictionary from string; compare response data with expected user scopes
        dict_scopes = json.loads(response_data)
        self.assertTrue(dict_scopes == user_scopes_data)
Ejemplo n.º 22
0
    def test_update_user_event_notification(self):
        verbose = False  #self.verbose
        root = self.root

        if verbose: print '\n'
        content_type = 'application/json'
        headers = self.get_api_headers('admin', 'test')

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # Add a second user ('foo', password 'test')
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test_username = '******'
        test_password = '******'
        test_email = '*****@*****.**'
        Organization.insert_org()
        User.insert_user(username=test_username,
                         password=test_password,
                         email=test_email)
        self.client = self.app.test_client(use_cookies=False)
        UserScope.insert_scopes()
        foo = User.query.filter_by(user_name='foo').first()
        scope = UserScope.query.filter_by(scope_name='user_admin').first()
        foo.scopes.append(scope)
        scope = UserScope.query.filter_by(
            scope_name='redmine').first()  # added
        foo.scopes.append(scope)
        db.session.add(foo)
        db.session.commit()

        response = self.client.get(url_for('main.get_user', id=1),
                                   headers=headers)
        self.assertTrue(response.status_code == 200)

        response = self.client.get(url_for('main.get_user', id=2),
                                   headers=headers)
        self.assertTrue(response.status_code == 200)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # # Create alert and an alarm
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        ref_def = "CE01ISSP-XX099-01-CTDPFJ999"
        # Create an alarm with user_event_notification - uses definition 1 and user_id 1
        test_alarm = self.create_alert_alarm_definition(ref_def,
                                                        event_type='alarm',
                                                        uframe_id=2,
                                                        severity=1)

        # Create an alarm without user_event_notification - uses definition 1 and user_id 1
        bad_alarm = self.create_alert_alarm_definition_wo_notification(
            ref_def, event_type='alarm', uframe_filter_id=2, severity=1)

        notification = self.create_user_event_notification(bad_alarm.id, 2)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # GET alarm definition by SystemEventDefinition id
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        response = self.client.get(url_for('main.get_alert_alarm_def',
                                           id=test_alarm.id),
                                   headers=headers)
        self.assertEquals(response.status_code, 200)
        alarm_definition = json.loads(response.data)
        self.assertTrue(alarm_definition is not None)

        response = self.client.get(url_for('main.get_alert_alarm_def',
                                           id=bad_alarm.id),
                                   headers=headers)
        self.assertEquals(response.status_code, 200)
        bad_alarm_definition = json.loads(response.data)
        self.assertTrue(bad_alarm_definition is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # Get user_event_notifications (1)
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        response = self.client.get(
            url_for('main.get_user_event_notifications'), headers=headers)
        self.assertEquals(response.status_code, 200)
        data = json.loads(response.data)
        self.assertTrue(data is not None)
        notifications = data['notifications']
        self.assertTrue(notifications is not None)
        self.assertEquals(len(notifications), 2)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # Get user_event_notification by id=1
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        url = url_for('main.get_user_event_notification', id=1)
        response = self.client.get(url,
                                   content_type=content_type,
                                   headers=headers)
        self.assertEquals(response.status_code, 200)
        notification = json.loads(response.data)
        self.assertTrue(len(notification) > 0)
        self.assertEquals(len(notification), 8)
        """
        Error messages for the following tests:

            1. bad_notification:  {}

            2. 'Invalid ID, user_event_notification record not found.'

            3. 'Inconsistent ID, user_event_notification id provided in data does not match id provided.'

            4. 'Inconsistent User ID, user_id provided in data does not match id.'

            5. 'IntegrityError creating user_event_notification.'

            6. (no error)

            7. 'Insufficient data, or bad data format.'
        """

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (1) Get user_event_notification by id=5 (doesn't exist) response: {}
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        url = url_for('main.get_user_event_notification', id=5)
        response = self.client.get(url,
                                   content_type=content_type,
                                   headers=headers)
        self.assertEquals(response.status_code, 200)
        bad_notification = json.loads(response.data)
        self.assertTrue(bad_notification is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (2) (Negative) Update event_event_notification;
        # error: 'Invalid ID, user_event_notification record not found.'
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test = {
            'user_id': 1,
            'system_event_definition_id': test_alarm.id,
            'use_email': False,
            'use_log': False,
            'use_phone': False,
            'use_redmine': False,
            'use_sms': False,
            'id': 50
        }
        bad_stuff = json.dumps(test)
        response = self.client.put(url_for(
            'main.update_user_event_notification', id=50),
                                   headers=headers,
                                   data=bad_stuff)
        self.assertEquals(response.status_code, 400)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue('message' in notify_data)
        self.assertTrue(notify_data['message'] is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (3) (Negative) Update event_event_notification
        # error: 'Inconsistent ID, user_event_notification id provided in data does not match id provided.'
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test = {
            'user_id': 999,
            'system_event_definition_id': 1,
            'use_email': True,
            'use_log': True,
            'use_phone': True,
            'use_redmine': True,
            'use_sms': True,
            'id': 1
        }
        good_stuff = json.dumps(test)
        response = self.client.put(url_for(
            'main.update_user_event_notification', id=800),
                                   headers=headers,
                                   data=good_stuff)
        self.assertEquals(response.status_code, 400)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue('message' in notify_data)
        self.assertTrue(notify_data['message'] is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (4) (Negative) Update user_event_notification, with invalid user_id
        # error: 'Inconsistent User ID, user_id provided in data does not match id.'
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test = {
            'user_id': 1,
            'system_event_definition_id': 2,
            'use_email': True,
            'use_log': True,
            'use_phone': True,
            'use_redmine': True,
            'use_sms': True,
            'id': 2
        }
        good_stuff = json.dumps(test)
        response = self.client.put(url_for(
            'main.update_user_event_notification', id=2),
                                   headers=headers,
                                   data=good_stuff)
        self.assertEquals(response.status_code, 400)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue('message' in notify_data)
        self.assertTrue(notify_data['message'] is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (5) # (Negative) Update event_event_notification
        # error: 'IntegrityError creating user_event_notification.'
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test = {
            'user_id': 2,
            'system_event_definition_id': bad_alarm.id,
            'use_email': False,
            'use_log': 'log',
            'use_phone': False,
            'use_redmine': False,
            'use_sms': False,
            'id': 2
        }
        bad_stuff = json.dumps(test)
        response = self.client.put(url_for(
            'main.update_user_event_notification', id=2),
                                   headers=headers,
                                   data=bad_stuff)
        self.assertEquals(response.status_code, 400)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue('message' in notify_data)
        self.assertTrue(notify_data['message'] is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (6) (Positive) Update event_event_notification
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test = {
            'user_id': 1,
            'system_event_definition_id': 1,
            'use_email': True,
            'use_log': True,
            'use_phone': True,
            'use_redmine': True,
            'use_sms': True,
            'id': 1
        }
        good_stuff = json.dumps(test)
        response = self.client.put(url_for(
            'main.update_user_event_notification', id=1),
                                   headers=headers,
                                   data=good_stuff)
        self.assertEquals(response.status_code, 201)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue(len(notify_data) > 0)
        notify = UserEventNotification.query.get(1)

        for attribute in UserEventNotification.__table__.columns._data:
            self.assertTrue(attribute in notify_data)
            if attribute != 'user_id' or attribute != 'id':
                self.assertEquals(getattr(notify, attribute), True)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (Negative) Update event_event_notification - expect failure, invalid user_id
        # error 'Insufficient data, or bad data format.'
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        data = {'user_id': 10}
        good_stuff = json.dumps(data)
        response = self.client.put(url_for(
            'main.update_user_event_notification', id=1),
                                   headers=headers,
                                   data=good_stuff)
        self.assertEquals(response.status_code, 409)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue('message' in notify_data)
        self.assertTrue(notify_data['message'] is not None)

        if verbose: print '\n'
Ejemplo n.º 23
0
def rebuild_schema(schema, schema_owner, save_users, save_disabled_streams, admin_username, admin_password, first_name, last_name, email, org_name):
    """
    Creates the OOI UI Services schema based on models.py
    :usage: python manage.py rebuild_schema --schema ooiui --schema_owner postgres --save_users False --save_disabled_streams True --admin_username admin --admin_password password --first_name Default --last_name Admin --email [email protected] --org_name Rutgers
    :param schema:
    :param schema_owner:
    :return:
    """
    # Check if schema exists
    timestamp = int((datetime.utcnow() - datetime(1970, 1, 1)).total_seconds())
    sql = "SELECT schema_name FROM information_schema.schemata WHERE schema_name = '{0}'".format(schema)
    sql_result = db.engine.execute(sql).first()
    if sql_result != None:
        # Move current schema to _timestamp
        app.logger.info('Backing up schema container {0} to {0}_{1}'.format(schema, timestamp))
        db.engine.execute('ALTER SCHEMA {0} RENAME TO {0}_{1}'.format(schema, timestamp))

    app.logger.info('Creating schema container: {0}'.format(schema))
    db.engine.execute('CREATE SCHEMA IF NOT EXISTS {0} AUTHORIZATION {1}'.format(schema, schema_owner))

    app.logger.info('Building schema objects')
    db.create_all()

    app.logger.info('Adding base user_scopes')
    UserScope.insert_scopes()
    db.session.commit()

    app.logger.info('Loading default data into database')
    load_data('ooiui_schema_data.sql')
    db.session.commit()

    app.logger.info('Loading params data into database')
    load_data(sql_file='ooiui_params_streams_data.sql')
    db.session.commit()

    # app.logger.info('Loading new vocab data into database')
    # load_data(sql_file='ooiui_vocab.sql')
    db.session.commit()

    if save_disabled_streams == 'True':
        app.logger.info('Re-populating disabledstreams table from backup schema')
        ds_sql = 'SELECT * FROM {0}_{1}.disabledstreams'.format(schema, timestamp)
        sql_result = db.engine.execute(ds_sql)
        fa = sql_result.fetchall()
        for sresult in fa:
            ds_record = DisabledStreams()
            ds_record.id = sresult.id
            ds_record.ref_des = getattr(sresult, 'ref_des', '')
            ds_record.stream_name = getattr(sresult, 'stream_name', '')
            ds_record.disabled_by = getattr(sresult, 'disabled_by', '')
            ds_record.timestamp = getattr(sresult, 'timestamp', '')
            db.session.add(ds_record)
            db.engine.execute("SELECT nextval('ooiui.disabledstreams_id_seq')")
            db.session.commit()

    if save_users == 'True':
        app.logger.info('Re-populating users from backup schema')
        users_sql = 'SELECT * FROM {0}_{1}.users'.format(schema, timestamp)
        sql_result = db.engine.execute(users_sql)
        fa = sql_result.fetchall()
        for sresult in fa:
            try:
                new_user = User()
                new_user.id = sresult.id
                new_user.user_id = getattr(sresult, 'user_id', '')
                if hasattr(sresult, 'pass_hash'):
                    new_user._password = getattr(sresult, 'pass_hash', '')
                else:
                    new_user._password = getattr(sresult, '_password', '')
                new_user.email = getattr(sresult, 'email', '')
                new_user.user_name = getattr(sresult, 'user_name', '')
                new_user.active = getattr(sresult, 'active', '')
                new_user.confirmed_at = getattr(sresult, 'confirmed_at', '')
                new_user.first_name = getattr(sresult, 'first_name', '')
                new_user.last_name = getattr(sresult, 'last_name', '')
                new_user.phone_primary = getattr(sresult, 'phone_primary', '')
                new_user.phone_alternate = getattr(sresult, 'phone_alternate', '')
                new_user.role = getattr(sresult, 'role', '')
                new_user.email_opt_in = getattr(sresult, 'email_opt_in', '')
                new_user.organization_id = getattr(sresult, 'organization_id', '')
                new_user.other_organization = getattr(sresult, 'other_organization', '')
                new_user.vocation = getattr(sresult, 'vocation', '')
                new_user.country = getattr(sresult, 'country', '')
                new_user.state = getattr(sresult, 'state', '')
                db.session.add(new_user)
                db.engine.execute("SELECT nextval('ooiui.users_id_seq')")
                db.session.commit()
            except sqlalchemy.exc.IntegrityError, exc:
                app.logger.info('Failure: rebuild_schema failed: ')
                reason = exc.message
                app.logger.info('Cause: ' + reason)
                app.logger.info('Restoring to previous version')
                app.logger.info('Restoring schema container {0}_{1} to {0}'.format(schema, timestamp))
                db.engine.execute('ALTER SCHEMA {0} RENAME TO {0}_{1}_failed'.format(schema, timestamp))
                db.engine.execute('ALTER SCHEMA {0}_{1} RENAME TO {0}'.format(schema, timestamp))


        user_scope_link_sql = 'SELECT * FROM {0}_{1}.user_scope_link'.format(schema, timestamp)
        sql_resultc = db.engine.execute(user_scope_link_sql)
        fac = sql_resultc.fetchall()
        for scresult in fac:
            try:
                new_user_scope_link = UserScopeLink()
                new_user_scope_link.id = scresult.id
                new_user_scope_link.user_id = scresult.user_id
                new_user_scope_link.scope_id = scresult.scope_id
                db.session.add(new_user_scope_link)
                db.engine.execute("SELECT nextval('ooiui.user_scope_link_id_seq')")
                db.session.commit()
            except sqlalchemy.exc.IntegrityError, exc:
                app.logger.info('Failure: rebuild_schema failed: ')
                reason = exc.message
                app.logger.info('Cause: ' + reason)
                app.logger.info('Restoring to previous version')
                app.logger.info('Restoring schema container {0}_{1} to {0}'.format(schema, timestamp))
                db.engine.execute('ALTER SCHEMA {0} RENAME TO {0}_{1}_failed'.format(schema, timestamp))
                db.engine.execute('ALTER SCHEMA {0}_{1} RENAME TO {0}'.format(schema, timestamp))
Ejemplo n.º 24
0
def rebuild_schema(schema, schema_owner, save_users, admin_username,
                   admin_password, first_name, last_name, email, org_name):
    """
    Creates the OOI UI Services schema based on models.py
    :usage: python manage.py rebuild_schema --schema ooiui --schema_owner postgres --save_users False --admin_username admin --admin_password password --first_name Default --last_name Admin --email [email protected] --org_name Rutgers
    :param schema:
    :param schema_owner:
    :return:
    """
    # Check if schema exists
    timestamp = int((datetime.utcnow() - datetime(1970, 1, 1)).total_seconds())
    sql = "SELECT schema_name FROM information_schema.schemata WHERE schema_name = '{0}'".format(
        schema)
    sql_result = db.engine.execute(sql).first()
    if sql_result != None:
        # Move current schema to _timestamp
        app.logger.info('Backing up schema container {0} to {0}_{1}'.format(
            schema, timestamp))
        db.engine.execute('ALTER SCHEMA {0} RENAME TO {0}_{1}'.format(
            schema, timestamp))

    app.logger.info('Creating schema container: {0}'.format(schema))
    db.engine.execute(
        'CREATE SCHEMA IF NOT EXISTS {0} AUTHORIZATION {1}'.format(
            schema, schema_owner))

    app.logger.info('Building schema objects')
    db.create_all()

    app.logger.info('Adding base user_scopes')
    UserScope.insert_scopes()

    app.logger.info('Loading default data into database')
    load_data('ooiui_schema_data.sql')
    db.session.commit()

    if save_users == 'True':
        app.logger.info('Re-populating users from backup schema')
        users_sql = 'SELECT * FROM {0}_{1}.users'.format(schema, timestamp)
        sql_result = db.engine.execute(users_sql)
        fa = sql_result.fetchall()
        for sresult in fa:
            new_user = User()
            new_user.id = sresult.id
            new_user.user_id = sresult.user_id
            new_user.pass_hash = sresult.pass_hash
            new_user.email = sresult.email
            new_user.user_name = sresult.user_name
            new_user.active = sresult.active
            new_user.confirmed_at = sresult.confirmed_at
            new_user.first_name = sresult.first_name
            new_user.last_name = sresult.last_name
            new_user.phone_primary = sresult.phone_primary
            new_user.phone_alternate = sresult.phone_alternate
            new_user.role = sresult.role
            new_user.organization_id = sresult.organization_id
            db.session.add(new_user)
            db.engine.execute("SELECT nextval('ooiui.users_id_seq')")
            db.session.commit()

        user_scope_link_sql = 'SELECT * FROM {0}_{1}.user_scope_link'.format(
            schema, timestamp)
        sql_resultc = db.engine.execute(user_scope_link_sql)
        fac = sql_resultc.fetchall()
        for scresult in fac:
            new_user_scope_link = UserScopeLink()
            new_user_scope_link.id = scresult.id
            new_user_scope_link.user_id = scresult.user_id
            new_user_scope_link.scope_id = scresult.scope_id
            db.session.add(new_user_scope_link)
            db.engine.execute("SELECT nextval('ooiui.user_scope_link_id_seq')")
            db.session.commit()

        # db.engine.execute('INSERT INTO {0}.users SELECT * FROM {0}_{1}.users'.format(schema, timestamp))
        # db.engine.execute('INSERT INTO {0}.user_scope_link SELECT * FROM {0}_{1}.user_scope_link'.format(schema, timestamp))

    else:
        app.logger.info('Adding the default admin user')
        if admin_username is None:
            app.logger.info('Admin username set to: admin')
            admin_username = '******'
        if admin_password is None:
            app.logger.info('Admin password set to: password')
            admin_password = '******'
        if first_name is None:
            app.logger.info('Admin first_name set to: Default')
            first_name = 'Default'
        if last_name is None:
            app.logger.info('Admin last_name set to: Admin')
            last_name = 'Admin'
        if email is None:
            app.logger.info('Admin email set to: [email protected]')
            email = '*****@*****.**'
        if org_name is None:
            app.logger.info('Admin org_name set to: Rutgers')
            org_name = 'Rutgers'
        add_admin_user(username=admin_username,
                       password=admin_password,
                       first_name=first_name,
                       last_name=last_name,
                       email=email,
                       org_name=org_name)
    load_data(sql_file='ooiui_schema_data_notifications.sql')
    app.logger.info('Database reloaded successfully')
Ejemplo n.º 25
0
    def test_user_scope(self):
        user_scope = UserScope()
        user_scope.insert_scopes()

        scope = UserScope.query.filter_by(scope_name="asset_manager").first()
        self.assertTrue(scope.scope_name == "asset_manager")
Ejemplo n.º 26
0
    def test_put_user_changes(self):
        """
        test ability to create new user and change scopes and/or active status of new user
        """
        headers = self.get_api_headers("admin", "test")

        # 1. get current user
        response = self.client.get(url_for("main.get_current_user"), headers=headers)
        self.assertEquals(response.status_code, 200)

        # 2. Create new user - test_user duplicate test
        data = json.dumps(
            {
                "email": "test@test",
                "password": "******",
                "repeatPassword": "******",
                "role_name": "Administrator",
                "username": "******",
                "first_name": "Tester",
                "last_name": "Testing",
                "organization_id": 1,
                "role_id": 1,
            }
        )
        response = self.client.post(url_for("main.create_user"), headers=headers, data=data)
        self.assertEquals(response.status_code, 201)

        # 3a. Add scope for user_admin
        UserScope.insert_scopes()
        admin = User.query.filter_by(user_name="admin").first()
        scope = UserScope.query.filter_by(scope_name="user_admin").first()
        admin.scopes.append(scope)
        db.session.add(admin)
        db.session.commit()

        # 3b. Get all users
        response = self.client.get(url_for("main.get_users"), headers=headers)
        self.assertEquals(response.status_code, 200)

        # 4. Verify user count is now == 2
        response_data = response.data[:]
        self.assertTrue(len(response_data) > 0)
        self.assertTrue(type(response_data) == type(""))
        self.assertTrue("users" in response_data)
        user_data = json.loads(response_data)
        user_list = user_data["users"]
        self.assertTrue(len(user_list) == 2)

        # 5. Update new user's scopes, add scopes = ['asset_manager']
        expected_data = {"active": True, "scopes": ["asset_manager"], "role_id": 1, "email": "test@localhost"}
        data = json.dumps(expected_data)
        response = self.client.put(url_for("main.put_user", id=2), headers=headers, data=data)
        self.assertTrue(response.status_code == 201)

        # 6. Get the new (and updated) user
        response = self.client.get(url_for("main.get_user", id=2), headers=headers)
        self.assertTrue(response.status_code == 200)

        # 7. Verify new user data includes expected_data: scopes=['asset_manager'] and 'active' == True
        response_data = response.data[:]
        self.assertTrue(len(response_data) > 0)
        self.assertTrue(type(response_data) == type(""))
        self.assertTrue("active" in response_data)
        self.assertTrue("scopes" in response_data)
        dict_data = json.loads(response_data)
        self.assertTrue(dict_data["active"] == expected_data["active"])
        self.assertTrue(dict_data["scopes"] == expected_data["scopes"])
Ejemplo n.º 27
0
    def test_user_scope(self):
        user_scope = UserScope()
        user_scope.insert_scopes()

        scope = UserScope.query.filter_by(scope_name='asset_manager').first()
        self.assertTrue(scope.scope_name == 'asset_manager')
Ejemplo n.º 28
0
def rebuild_schema(schema, schema_owner, save_users, admin_username, admin_password, first_name, last_name, email, org_name):
    """
    Creates the OOI UI Services schema based on models.py
    :usage: python manage.py rebuild_schema --schema ooiui --schema_owner postgres --save_users False --admin_username admin --admin_password password --first_name Default --last_name Admin --email [email protected] --org_name Rutgers
    :param schema:
    :param schema_owner:
    :return:
    """
    # Check if schema exists
    timestamp = int((datetime.utcnow() - datetime(1970, 1, 1)).total_seconds())
    sql = "SELECT schema_name FROM information_schema.schemata WHERE schema_name = '{0}'".format(schema)
    sql_result = db.engine.execute(sql).first()
    if sql_result != None:
        # Move current schema to _timestamp
        app.logger.info('Backing up schema container {0} to {0}_{1}'.format(schema, timestamp))
        db.engine.execute('ALTER SCHEMA {0} RENAME TO {0}_{1}'.format(schema, timestamp))

    app.logger.info('Creating schema container: {0}'.format(schema))
    db.engine.execute('CREATE SCHEMA IF NOT EXISTS {0} AUTHORIZATION {1}'.format(schema, schema_owner))

    app.logger.info('Building schema objects')
    db.create_all()

    app.logger.info('Adding base user_scopes')
    UserScope.insert_scopes()

    app.logger.info('Loading default data into database')
    load_data('ooiui_schema_data.sql')
    db.session.commit()

    if save_users == 'True':
        app.logger.info('Re-populating users from backup schema')
        users_sql = 'SELECT * FROM {0}_{1}.users'.format(schema, timestamp)
        sql_result = db.engine.execute(users_sql)
        fa = sql_result.fetchall()
        for sresult in fa:
            new_user = User()
            new_user.id = sresult.id
            new_user.user_id = sresult.user_id
            new_user.pass_hash = sresult.pass_hash
            new_user.email = sresult.email
            new_user.user_name = sresult.user_name
            new_user.active = sresult.active
            new_user.confirmed_at = sresult.confirmed_at
            new_user.first_name = sresult.first_name
            new_user.last_name = sresult.last_name
            new_user.phone_primary = sresult.phone_primary
            new_user.phone_alternate = sresult.phone_alternate
            new_user.role = sresult.role
            new_user.organization_id = sresult.organization_id
            db.session.add(new_user)
            db.engine.execute("SELECT nextval('ooiui.users_id_seq')")
            db.session.commit()

        user_scope_link_sql = 'SELECT * FROM {0}_{1}.user_scope_link'.format(schema, timestamp)
        sql_resultc = db.engine.execute(user_scope_link_sql)
        fac = sql_resultc.fetchall()
        for scresult in fac:
            new_user_scope_link = UserScopeLink()
            new_user_scope_link.id = scresult.id
            new_user_scope_link.user_id = scresult.user_id
            new_user_scope_link.scope_id = scresult.scope_id
            db.session.add(new_user_scope_link)
            db.engine.execute("SELECT nextval('ooiui.user_scope_link_id_seq')")
            db.session.commit()

        # db.engine.execute('INSERT INTO {0}.users SELECT * FROM {0}_{1}.users'.format(schema, timestamp))
        # db.engine.execute('INSERT INTO {0}.user_scope_link SELECT * FROM {0}_{1}.user_scope_link'.format(schema, timestamp))

    else:
        app.logger.info('Adding the default admin user')
        if admin_username is None:
            app.logger.info('Admin username set to: admin')
            admin_username = '******'
        if admin_password is None:
            app.logger.info('Admin password set to: password')
            admin_password = '******'
        if first_name is None:
            app.logger.info('Admin first_name set to: Default')
            first_name = 'Default'
        if last_name is None:
            app.logger.info('Admin last_name set to: Admin')
            last_name = 'Admin'
        if email is None:
            app.logger.info('Admin email set to: [email protected]')
            email = '*****@*****.**'
        if org_name is None:
            app.logger.info('Admin org_name set to: Rutgers')
            org_name = 'Rutgers'
        add_admin_user(username=admin_username, password=admin_password, first_name=first_name, last_name=last_name, email=email, org_name=org_name)
    load_data(sql_file='ooiui_schema_data_notifications.sql')
    app.logger.info('Database reloaded successfully')
    def test_update_user_event_notification(self):
        verbose = False #self.verbose
        root = self.root

        if verbose: print '\n'
        content_type =  'application/json'
        headers = self.get_api_headers('admin', 'test')

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # Add a second user ('foo', password 'test')
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test_username = '******'
        test_password = '******'
        test_email = '*****@*****.**'
        Organization.insert_org()
        User.insert_user(username=test_username, password=test_password, email=test_email)
        self.client = self.app.test_client(use_cookies=False)
        UserScope.insert_scopes()
        foo = User.query.filter_by(user_name='foo').first()
        scope = UserScope.query.filter_by(scope_name='user_admin').first()
        foo.scopes.append(scope)
        scope = UserScope.query.filter_by(scope_name='redmine').first()     # added
        foo.scopes.append(scope)
        db.session.add(foo)
        db.session.commit()

        response = self.client.get(url_for('main.get_user',id=1), headers=headers)
        self.assertTrue(response.status_code == 200)

        response = self.client.get(url_for('main.get_user',id=2), headers=headers)
        self.assertTrue(response.status_code == 200)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # # Create alert and an alarm
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        ref_def = "CE01ISSP-XX099-01-CTDPFJ999"
        # Create an alarm with user_event_notification - uses definition 1 and user_id 1
        test_alarm = self.create_alert_alarm_definition(ref_def, event_type='alarm', uframe_id=2, severity=1)

        # Create an alarm without user_event_notification - uses definition 1 and user_id 1
        bad_alarm = self.create_alert_alarm_definition_wo_notification(ref_def, event_type='alarm',
                                                                       uframe_filter_id=2, severity=1)

        notification = self.create_user_event_notification(bad_alarm.id, 2)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # GET alarm definition by SystemEventDefinition id
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        response = self.client.get(url_for('main.get_alert_alarm_def', id=test_alarm.id), headers=headers)
        self.assertEquals(response.status_code, 200)
        alarm_definition = json.loads(response.data)
        self.assertTrue(alarm_definition is not None)

        response = self.client.get(url_for('main.get_alert_alarm_def', id=bad_alarm.id), headers=headers)
        self.assertEquals(response.status_code, 200)
        bad_alarm_definition = json.loads(response.data)
        self.assertTrue(bad_alarm_definition is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # Get user_event_notifications (1)
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        response = self.client.get(url_for('main.get_user_event_notifications'), headers=headers)
        self.assertEquals(response.status_code, 200)
        data = json.loads(response.data)
        self.assertTrue(data is not None)
        notifications = data['notifications']
        self.assertTrue(notifications is not None)
        self.assertEquals(len(notifications), 2)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # Get user_event_notification by id=1
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        url = url_for('main.get_user_event_notification', id=1)
        response = self.client.get(url, content_type=content_type, headers=headers)
        self.assertEquals(response.status_code, 200)
        notification = json.loads(response.data)
        self.assertTrue(len(notification) > 0)
        self.assertEquals(len(notification), 8)

        """
        Error messages for the following tests:

            1. bad_notification:  {}

            2. 'Invalid ID, user_event_notification record not found.'

            3. 'Inconsistent ID, user_event_notification id provided in data does not match id provided.'

            4. 'Inconsistent User ID, user_id provided in data does not match id.'

            5. 'IntegrityError creating user_event_notification.'

            6. (no error)

            7. 'Insufficient data, or bad data format.'
        """

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (1) Get user_event_notification by id=5 (doesn't exist) response: {}
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        url = url_for('main.get_user_event_notification', id=5)
        response = self.client.get(url, content_type=content_type, headers=headers)
        self.assertEquals(response.status_code, 200)
        bad_notification = json.loads(response.data)
        self.assertTrue(bad_notification is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (2) (Negative) Update event_event_notification;
        # error: 'Invalid ID, user_event_notification record not found.'
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test = {'user_id': 1,
                'system_event_definition_id': test_alarm.id,
                'use_email': False,
                'use_log': False,
                'use_phone': False,
                'use_redmine': False,
                'use_sms': False,
                'id': 50}
        bad_stuff = json.dumps(test)
        response = self.client.put(url_for('main.update_user_event_notification', id=50), headers=headers, data=bad_stuff)
        self.assertEquals(response.status_code, 400)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue('message' in notify_data)
        self.assertTrue(notify_data['message'] is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (3) (Negative) Update event_event_notification
        # error: 'Inconsistent ID, user_event_notification id provided in data does not match id provided.'
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test = {'user_id': 999,
                'system_event_definition_id': 1,
                'use_email': True,
                'use_log': True,
                'use_phone': True,
                'use_redmine': True,
                'use_sms': True,
                'id': 1}
        good_stuff = json.dumps(test)
        response = self.client.put(url_for('main.update_user_event_notification', id=800), headers=headers, data=good_stuff)
        self.assertEquals(response.status_code, 400)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue('message' in notify_data)
        self.assertTrue(notify_data['message'] is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (4) (Negative) Update user_event_notification, with invalid user_id
        # error: 'Inconsistent User ID, user_id provided in data does not match id.'
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test = {'user_id': 1,
                'system_event_definition_id': 2,
                'use_email': True,
                'use_log': True,
                'use_phone': True,
                'use_redmine': True,
                'use_sms': True,
                'id': 2}
        good_stuff = json.dumps(test)
        response = self.client.put(url_for('main.update_user_event_notification', id=2), headers=headers, data=good_stuff)
        self.assertEquals(response.status_code, 400)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue('message' in notify_data)
        self.assertTrue(notify_data['message'] is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (5) # (Negative) Update event_event_notification
        # error: 'IntegrityError creating user_event_notification.'
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test = {'user_id': 2,
                'system_event_definition_id': bad_alarm.id,
                'use_email': False,
                'use_log': 'log',
                'use_phone': False,
                'use_redmine': False,
                'use_sms': False,
                'id': 2}
        bad_stuff = json.dumps(test)
        response = self.client.put(url_for('main.update_user_event_notification', id=2), headers=headers, data=bad_stuff)
        self.assertEquals(response.status_code, 400)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue('message' in notify_data)
        self.assertTrue(notify_data['message'] is not None)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (6) (Positive) Update event_event_notification
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        test = {'user_id': 1,
                'system_event_definition_id': 1,
                'use_email': True,
                'use_log': True,
                'use_phone': True,
                'use_redmine': True,
                'use_sms': True,
                'id': 1}
        good_stuff = json.dumps(test)
        response = self.client.put(url_for('main.update_user_event_notification', id=1), headers=headers, data=good_stuff)
        self.assertEquals(response.status_code, 201)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue(len(notify_data) > 0)
        notify = UserEventNotification.query.get(1)

        for attribute in UserEventNotification.__table__.columns._data:
            self.assertTrue(attribute in notify_data)
            if attribute != 'user_id' or attribute != 'id':
                self.assertEquals(getattr(notify,attribute), True)

        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # (Negative) Update event_event_notification - expect failure, invalid user_id
        # error 'Insufficient data, or bad data format.'
        #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        data = {'user_id': 10}
        good_stuff = json.dumps(data)
        response = self.client.put(url_for('main.update_user_event_notification', id=1), headers=headers, data=good_stuff)
        self.assertEquals(response.status_code, 409)
        notify_data = json.loads(response.data)
        self.assertTrue(notify_data is not None)
        self.assertTrue('message' in notify_data)
        self.assertTrue(notify_data['message'] is not None)

        if verbose: print '\n'
Ejemplo n.º 30
0
def deploy(password, production, psqluser):
    from flask.ext.migrate import upgrade
    from ooiservices.app.models import User, UserScope, UserScopeLink, Array, Organization
    from ooiservices.app.models import PlatformDeployment, InstrumentDeployment, Stream, StreamParameterLink
    from sh import psql
    if production:
        app.logger.info('Creating PRODUCTION Database')
        try:
            psql('-c', 'CREATE ROLE postgres LOGIN SUPERUSER')
        except:
            pass
        psql('-c', 'create database ooiuiprod;', '-U', psqluser)
        psql('ooiuiprod', '-c', 'create schema ooiui', '-U', psqluser)
        psql('ooiuiprod', '-c', 'create extension postgis', '-U', psqluser)
    else:
        try:
            psql('-c', 'CREATE ROLE postgres LOGIN SUPERUSER')
        except:
            pass
        #Create the local database
        app.logger.info('Creating DEV and TEST Databases')
        psql('-c', 'create database ooiuidev;', '-U', psqluser)
        psql('ooiuidev', '-c', 'create schema ooiui', '-U', psqluser)
        psql('ooiuidev', '-c', 'create extension postgis', '-U', psqluser)
        #Create the local test database
        psql('-c', 'create database ooiuitest;', '-U', psqluser)
        psql('ooiuitest', '-c', 'create schema ooiui', '-U', psqluser)
        psql('ooiuitest', '-c', 'create extension postgis', '-U', psqluser)

    from sqlalchemy.orm.mapper import configure_mappers
    configure_mappers()
    db.create_all()

    if production:
        app.logger.info('Populating Production Database . . .')
        with open('db/ooiui_schema_data.sql') as f:
            psql('-U', psqluser, 'ooiuiprod', _in=f)
        with open('db/ooiui_params_streams_data.sql') as h:
            psql('-U', psqluser, 'ooiuiprod', _in=h)
        # with open('db/ooiui_vocab.sql') as i:
        #     psql('-U', psqluser, 'ooiuiprod', _in=i)
        app.logger.info('Production Database loaded.')
    else:
        app.logger.info('Populating Dev Database . . .')
        with open('db/ooiui_schema_data.sql') as f:
            psql('-U', psqluser, 'ooiuidev', _in=f)
        with open('db/ooiui_params_streams_data.sql') as h:
            psql('-U', psqluser, 'ooiuidev', _in=h)
        # with open('db/ooiui_vocab.sql') as i:
        #     psql('-U', psqluser, 'ooiuidev', _in=i)
        app.logger.info('Dev Database loaded.')

    # migrate database to latest revision
    #upgrade()
    if not os.getenv('TRAVIS'):
        UserScope.insert_scopes()
        app.logger.info('Insert default user, name: admin')
        User.insert_user(password=password)
        admin = User.query.first()
        admin.scopes.append(UserScope.query.filter_by(scope_name='user_admin').first())
        admin.scopes.append(UserScope.query.filter_by(scope_name='sys_admin').first())
        admin.scopes.append(UserScope.query.filter_by(scope_name='data_manager').first())
        admin.scopes.append(UserScope.query.filter_by(scope_name='redmine').first())
        db.session.add(admin)
        db.session.commit()