Example #1
0
 def setUp(self):
     """Define test variables and initialize app."""
     self.app = app
     self.app.config.from_object(TestingConfig)
     self.client = self.app.test_client()
     with self.app.app_context():
         db.create_all()
def init_database():
    '''
    若数据库还未初始化, 则初始化数据库, 数据库中应人为保证没有名为roles和users的表, 才能完成初始化
    若数据库已经初始化, 则什么都不会发生
    '''
    from manage import db
    db.reflect()
    all_table = {
        table_obj.name: table_obj
        for table_obj in db.get_tables_for_bind()
    }
    try:
        str(all_table['roles'])
        str(all_table['users'])
    except KeyError:
        from db_models.user_model import User
        from db_models.role_model import Role
        db.drop_all()
        db.create_all()
        role1 = Role(name='admin')
        role2 = Role(name='ordinary_user')
        db.session.add_all([role1, role2])
        db.session.commit()
        user1 = User(name='hshs', password='******', role_id=role1.id)
        user2 = User(name='hkhk', password='******', role_id=role1.id)
        user3 = User(name='郑某人', password='******', role_id=role2.id)
        user4 = User(name='王维', password='******', role_id=role2.id)
        db.session.add_all([user1, user2, user3, user4])
        db.session.commit()
        print('新建了roles和users表')
    else:
        print('已存在roles和users表')
Example #3
0
    def setUp(self):
        password = generate_password_hash('password')
        challonge_api_key = xor_crypt_string('challonge123', encode=True)
        test_user = User('testuser', password, '*****@*****.**', 'testuser',
                         challonge_api_key)
        self.test_user = test_user

        db.drop_all()
        db.create_all()
        db.session.add(self.test_user)
        db.session.commit()

        valid_credentials = base64.b64encode(b'testuser:password').decode(
            'utf-8')
        response = self.client.post(
            LOGIN_URL, headers={'Authorization': 'Basic ' + valid_credentials})
        returned = json.loads(response.data)
        tk_valid_user = returned['token']
        tk_invalid = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTV9.LZaaRkg7THSCD-8VDtjX43Wxn5gKktR6m8DJQDH2SpM'
        self.headers = {
            'Content-Type': 'application/json',
            'x-access-token': tk_valid_user
        }
        self.badheaders = {
            'Content-Type': 'application/json',
            'x-access-token': tk_invalid
        }
Example #4
0
    def setUp(self):
        self.app = self.create_app().test_client()
        self.database = db
        db.create_all()

        # Add dummy data for test purposes
        user = User(username="******")
        user.set_password('master12')

        user2 = User(username="******")
        user2.set_password('password')

        b_list1 = BucketList(
            name="btest1", description="test one", created_by=1)
        b_list2 = BucketList(
            name="btest2", description="test two", created_by=1)

        b_item1 = BucketListItem(
            name="itest1", description="part of test", created_by=1, bucketlist_id=1)
        b_item2 = BucketListItem(
            name="itest2", description="part of 2nd test", created_by=1, bucketlist_id=2)

        db.session.add(user)
        db.session.add(user2)
        db.session.add(b_list1)
        db.session.add(b_list2)
        db.session.add(b_item1)
        db.session.add(b_item2)
        db.session.commit()
Example #5
0
    def get_db(self):
        db.session.close()
        # db.drop_all()
        DataOfficerAllegation.query.filter_by(id=1).delete()
        db.session.commit()
        db.create_all(bind=COPA_DB_BIND_KEY)

        yield db
Example #6
0
    def setUp(self):
        """Adds resources for use int the test suites"""

        # Sets up the test client"""

        self.test_app = self.create_app().test_client()

        db.create_all()
Example #7
0
 def setUp(self):
     """Setting the app up for tests suite"""
     self.app = app.test_client()
     self.base_request_url = "/pay/?client_id=1&buyer_name=Vittor&[email protected]&" \
                             "buyer_cpf=12345678910&payment_amount=1200&"
     db.create_all()
     db.session.add(Client())
     db.session.commit()
Example #8
0
 def setUp(self):
     """Define test variables and initialize app."""
     self.app = app
     self.app.config.from_object(TestingConfig)
     self.client = self.app.test_client()
     # binds the app to the current context
     with self.app.app_context():
         # create all tables
         db.create_all()
Example #9
0
    def setUp(self):
        password = generate_password_hash('password')
        test_user = User('testuser', password, '*****@*****.**',
                         'matchuptesting', challonge_api_key)
        self.test_user = test_user

        db.drop_all()
        db.create_all()
        db.session.add(self.test_user)
        db.session.commit()
Example #10
0
def init_db():
    db.create_all()
    Role.insert_roles()
    admin = User.query.get(1) or User()
    admin.username = Config.FLASKY_ADMIN
    admin.password = '******'
    db.session.add(admin)
    db.session.commit()
    admin.role_id = 3
    db.session.commit()
Example #11
0
    def test_adding_augmented_copa_record_to_db_no_category_matches(self):
        copa_split_csv = os.path.join(IFTestBase.resource_directory,
                                      'copa_scraped_split.csv')
        df = pd.read_csv(copa_split_csv)
        db.drop_all()
        db.create_all(bind=COPA_DB_BIND_KEY)

        augmented = Augment().get_augmented_copa_data(copa_split_csv)
        assert_frame_equal(augmented, df)
        assert len(augmented) == len(df)
Example #12
0
    def test_copa_scrape_integration(self, get_copa_data_demographics):
        with patch.object(StorageFactory, 'get_storage') as storage_mock, \
                patch('invisible_flow.app.scrape_data') as scrape_mock:
            scrape_mock.return_value = get_copa_data_demographics

            storage_mock.return_value = LocalStorage()

            db.session.close()
            db.drop_all()
            db.create_all(COPA_DB_BIND_KEY)

            self.initialize_database(db)

            copa_scrape()

            match_data_file_contents = LocalStorage().get('match_data.csv', "COPA_SCRAPE-2019-03-25_05-30-50")
            new_allegation_file_contents = LocalStorage().get('new_allegation_data.csv',
                                                              "COPA_SCRAPE-2019-03-25_05-30-50")
            new_officer_unknown_file_contents = LocalStorage().get('new_officer_unknown.csv',
                                                                   "COPA_SCRAPE-2019-03-25_05-30-50")
            new_officer_allegation_file_contents = LocalStorage().get('new_officer_allegation.csv',
                                                                      "COPA_SCRAPE-2019-03-25_05-30-50")

            expected_match_data_file_contents = open(os.path.join(IFTestBase.resource_directory,
                                                                  'expected_match_copa_data.csv')).read()
            expected_new_allegation_data = open(os.path.join(IFTestBase.resource_directory,
                                                             'expected_new_allegation_data.csv')).read()
            expected_new_officer_unknown_data = open(os.path.join(IFTestBase.resource_directory,
                                                                  'expected_new_officer_unknown.csv')).read()
            expected_new_officer_allegation_data = open(os.path.join(IFTestBase.resource_directory,
                                                                     'expected_new_officer_allegation.csv')).read()

            entry_from_db = DataAllegation.query.get('1087387')
            number_of_rows_in_db = DataAllegation.query.count()

            # tests > helpers > resources (can find csv contents used in these tests
            # first two asserts; beat_ids were added to expected files in resource folder
            # new_data & match_data should show up in local_upload_folder
            assert (match_data_file_contents == expected_match_data_file_contents)
            assert (new_allegation_file_contents == expected_new_allegation_data)
            assert (new_officer_unknown_file_contents == expected_new_officer_unknown_data)
            assert (new_officer_allegation_file_contents == expected_new_officer_allegation_data)

            assert (entry_from_db is not None)
            assert (number_of_rows_in_db == 151)
            # ^was bumped up +1 due to added entry in copa_scraped_demographics.csv when checking test with new data

            local_upload_dir = LocalStorage().local_upload_directory

            os.remove(os.path.join(local_upload_dir, "COPA_SCRAPE-2019-03-25_05-30-50", 'match_data.csv'))
            os.remove(os.path.join(local_upload_dir, "COPA_SCRAPE-2019-03-25_05-30-50", 'new_allegation_data.csv'))
            os.remove(os.path.join(local_upload_dir, "COPA_SCRAPE-2019-03-25_05-30-50", 'new_officer_allegation.csv'))
            os.remove(os.path.join(local_upload_dir, "COPA_SCRAPE-2019-03-25_05-30-50", 'new_officer_unknown.csv'))

            os.rmdir(os.path.join(local_upload_dir, "COPA_SCRAPE-2019-03-25_05-30-50"))
Example #13
0
    def test_copa_scrape_integration(self, get_copa_data_demographics):
        with patch.object(StorageFactory, 'get_storage') as storage_mock, \
                patch('invisible_flow.app.scrape_data') as scrape_mock:

            scrape_mock.return_value = get_copa_data_demographics

            storage_mock.return_value = LocalStorage()

            db.session.close()
            db.drop_all()
            db.create_all(COPA_DB_BIND_KEY)

            self.initialize_database(db)

            copa_scrape()

            match_data_file_contents = LocalStorage().get(
                'match_data.csv', "COPA_SCRAPE-2019-03-25_05-30-50")
            new_data_file_contents = LocalStorage().get(
                'new_data.csv', "COPA_SCRAPE-2019-03-25_05-30-50")

            expected_match_data_file_contents = open(
                os.path.join(IFTestBase.resource_directory,
                             'expected_match_copa_data.csv')).read()
            expected_new_data_file_contents = open(
                os.path.join(IFTestBase.resource_directory,
                             'expected_new_copa_data.csv')).read()

            entry_from_db = DataAllegation.query.get('1087387')
            number_of_rows_in_db = DataAllegation.query.count()

            assert (new_data_file_contents == expected_new_data_file_contents)
            assert (
                match_data_file_contents == expected_match_data_file_contents)

            assert (entry_from_db is not None)
            assert (number_of_rows_in_db == 150)

            local_upload_dir = LocalStorage().local_upload_directory

            os.remove(
                os.path.join(local_upload_dir,
                             "COPA_SCRAPE-2019-03-25_05-30-50",
                             'match_data.csv'))
            os.remove(
                os.path.join(local_upload_dir,
                             "COPA_SCRAPE-2019-03-25_05-30-50",
                             'new_data.csv'))

            os.rmdir(
                os.path.join(local_upload_dir,
                             "COPA_SCRAPE-2019-03-25_05-30-50"))
Example #14
0
def client():
    app = make_app("test")
    app.app_context().push()
    app.test_client_class = TestClient
    client = app.test_client()

    with app.app_context():
        db.create_all()
        seed.main()

    yield client

    db.session.remove()
    db.drop_all()
Example #15
0
    def setUp(self):
        self.app = app

        # initialize the test client
        self.client = self.app.test_client()

        with self.app.app_context():
            db.drop_all()
            db.create_all()
            email = '*****@*****.**'

            self.user = {
                'username': '******',
                'password': '******',
                'email': email
            }

            self.user1 = {
                'username': '******',
                'password': '******',
                'email': email
            }

            self.client.post('/api/auth/logout',
                             content_type='application/json')

            self.client.post('/api/auth/register',
                             data=json.dumps(self.user),
                             content_type='application/json')
            self.user.pop('email')
            res = self.client.post('/api/auth/login',
                                   data=json.dumps(self.user),
                                   content_type='application/json')
            data = json.loads(res.data.decode())
            self.token = data['token']

            self.business = {
                'name': 'business',
                'location': 'kampala',
                'category': 'technology',
                'description': 'service providers for repair of computers'
            }

            self.business1 = {
                'name': 'business1',
                'location': 'mukono',
                'category': 'bio-tech',
                'description': 'service providers of bio-tech chemicals'
            }
Example #16
0
    def setUp(self):
        password = generate_password_hash('password')
        test_user = User('testuser', password, '*****@*****.**',
                         'matchuptesting', challonge_api_key)
        self.test_user = test_user

        db.drop_all()
        db.create_all()
        db.session.add(self.test_user)
        db.session.commit()

        valid_credentials = base64.b64encode(b'testuser:password').decode(
            'utf-8')
        response = self.client.post(
            LOGIN_URL, headers={'Authorization': 'Basic ' + valid_credentials})
        returned = json.loads(response.data)
        self.tk_valid_user = returned['token']
        self.headers = {
            'Content-Type': 'application/json',
            'x-access-token': self.tk_valid_user
        }

        challonge.set_credentials(
            self.test_user.challonge_username,
            xor_crypt_string(self.test_user.api_key, decode=True))

        challonge.tournaments.reset(bracket_1_id)
        challonge.tournaments.start(bracket_1_id)

        event_data = {
            'event_name':
            'Test Event',
            'brackets': [{
                'bracket_id': bracket_1_id,
                'number_of_setups': 0
            }, {
                'bracket_id': bracket_2_id,
                'number_of_setups': 0
            }]
        }

        response = self.client.post(EVENT_URL,
                                    json=event_data,
                                    headers=self.headers)
        self.event = Event.query.get(json.loads(response.data)['id'])

        self.matches_available_bracket_1 = challonge.matches.index(
            bracket_1_id, state='open')
        self.match_to_test = self.matches_available_bracket_1[0]
Example #17
0
    def setUp(self):
        """
        Add bucketlists and items directly to db to avoid using tokens 
        required for POST request.
        """
        app.config.from_object(TestingConfig)
        self.client = app.test_client()
        db.create_all()

        self.client.post("/auth/register",
                         data=json.dumps(
                             dict(username="******", password="******")),
                         content_type="application/json")

        response = self.client.post("/auth/login",
                                    data=json.dumps(
                                        dict(username="******",
                                             password="******")),
                                    content_type="application/json")
        response_msg = json.loads(response.data)
        self.token = response_msg["Token"]

        bucket = {"name": "testbucketlist"}
        test_bucket = Bucketlist()
        test_bucket.import_data(bucket)
        test_bucket.created_by = 1

        bucket2 = {"name": "testbucketlist2"}
        test_bucket2 = Bucketlist()
        test_bucket2.import_data(bucket2)
        test_bucket2.created_by = 1

        bucket3 = {"name": "testbucketlist3"}
        test_bucket3 = Bucketlist()
        test_bucket3.import_data(bucket3)
        test_bucket3.created_by = 2

        item = {"name": "testitem", "done": ""}
        test_item = BucketlistItem()
        test_item.import_data(item)
        test_item.bucket = 1
        test_item.created_by = 1

        db.session.add(test_bucket)
        db.session.add(test_bucket2)
        db.session.add(test_bucket3)
        db.session.add(test_item)
        db.session.commit()
Example #18
0
    def test_copa_scrape_endpoint_responds(self, client):
        with patch.object(CopaScrapeTransformer, 'transform') as transform_mock, \
                patch.object(StorageFactory, 'get_storage'):
            transform_mock.return_value = [pd.DataFrame(), pd.DataFrame()]
            db.session.close()
            self.drop_with_cascade()
            db.create_all(bind=COPA_DB_BIND_KEY)

            response = client.get('/copa_scrape', content_type='html/text')

            assert response.status_code == 200
            assert b'Success' in response.data
            transform_mock.assert_called()

            self.drop_with_cascade()
            db.session.close()
Example #19
0
    def setUp(self):
        self.app=app
        
        # initialize the test client
        self.client = self.app.test_client()

        with self.app.app_context():
            db.drop_all()
            db.create_all()

            self.user = {
                'username': '******',
                'password': '******',
                'email': '*****@*****.**'
            }

            self.user_login = {
                'username': '******',
                'password': '******',
            }

            self.business={
                'name':'business',
                'location':'kampala',
                'category':'technology',
                'description':'service providers for repair of computers'
            }

            self.client.post('/api/auth/logout', content_type='application/json')

            self.client.post('/api/auth/register', data=json.dumps(self.user), content_type='application/json')

            res = self.client.post('/api/auth/login', data=json.dumps(self.user_login), content_type='application/json')
            data  = json.loads(res.data.decode())
            self.token = data['token']

            self.client.post('/api/businesses', data=json.dumps(self.business), headers={'x-access-token': self.token})

            self.review= {
                'review': 'test review for a business'
            }
            # db.session.close()
Example #20
0
    def test_adding_augmented_copa_record_to_db(self):
        # using test file that is not actual copa that has been  cleaned/transformed
        copa_csv_file = os.path.join(IFTestBase.resource_directory,
                                     'copa_scraped_split.csv')
        original_dataframe = pd.read_csv(copa_csv_file)
        db.create_all(bind=COPA_DB_BIND_KEY)

        log_no_column = original_dataframe.loc[:, 'log_no'].unique()
        categories_column = original_dataframe.loc[:,
                                                   'current_category'].unique(
                                                   )
        augmented_dataframe = Augment().get_augmented_copa_data(copa_csv_file)

        assert log_no_column.all()
        assert categories_column is not None
        assert augmented_dataframe is not None
        assert original_dataframe.equals(augmented_dataframe)

        print("orginal", original_dataframe.loc[:, 'current_category'], "/n")
        print("augmented", augmented_dataframe.loc[:, 'current_category'])
Example #21
0
    def setUp(self):
        self.app=app
        
        # initialize the test client
        self.client = self.app.test_client()

        with self.app.app_context():
            db.drop_all()
            db.create_all()
            self.client.post('api/')
            email = '*****@*****.**'
            self.user = {
                'username': '******',
                'password': '******',
                'email': email
                }
            
            self.user1 = {
                'username': '******',
                'password': '******',
                'email': email
                }
Example #22
0
    def setUp(self):
        db.drop_all()
        db.create_all()

        password = generate_password_hash('password')
        test_user = User('testuser', password, '*****@*****.**',
                         'matchuptesting', challonge_api_key)
        self.test_user = test_user
        db.session.add(self.test_user)
        db.session.commit()

        valid_credentials = base64.b64encode(b'testuser:password').decode(
            'utf-8')
        response = self.client.post(
            LOGIN_URL, headers={'Authorization': 'Basic ' + valid_credentials})
        returned = json.loads(response.data)
        self.tk_valid_user = returned['token']
        self.headers = {
            'Content-Type': 'application/json',
            'x-access-token': self.tk_valid_user
        }

        event_data = {
            'event_name':
            'Test Event',
            'brackets': [{
                'bracket_id': bracket_1_id,
                'number_of_setups': 4
            }, {
                'bracket_id': bracket_2_id,
                'number_of_setups': 5
            }]
        }
        response = self.client.post(CREATE_EVENT_URL,
                                    json=event_data,
                                    headers=self.headers)
        self.test_event = Event.query.get(json.loads(response.data)['id'])
Example #23
0
from models.users import Role, User
from models.issues import Attachment, Category, Issue, IssueHistory, Status
from manage import db
from config import Config

#Checking if database exists, and if not -> create it with all tables.

db_credentials = Config.db_credentials

if 'DATABASE_URL' in os.environ:
    db_credentials = os.environ['DATABASE_URL']


if not database_exists(db_credentials):
    create_database(db_credentials)
    db.create_all()
    db.session.commit()


#Creating some test data.
role = Role(role='admin')
role1 = Role(role='moderator')
role2 = Role(role='user')

category = Category(category='road accident', favicon='')
category1 = Category(category='infrastructure accident', favicon='')
category2 = Category(category='another accident', favicon='')

status1 = Status(status="new")
status2 = Status(status="working")
status3 = Status(status="closed")
    def get_db(self):
        db.session.close()
        db.drop_all()
        db.create_all(bind=COPA_DB_BIND_KEY)

        yield db
 def set_up(self):
     db.session.close()
     db.drop_all()
     db.create_all(bind=COPA_DB_BIND_KEY)
 def setUp(self):
     db.create_all()
     db.session.commit()
 def setUp(self):
     db.create_all()
     db.session.add(Client())
     db.session.commit()
Example #28
0
    def setUp(self):
        db.create_all(app=self.app_t)

        self.today = datetime.now().strftime('%Y-%m-%d')
        self.http = self.create_app().test_client()

        # Create and add a user to the db
        user = User(username='******',
                    password=generate_password_hash('migwi123'))
        user.save()

        # Add a BucketList to the db
        bucketlist = BucketList(name='December Vacation',
                                date_created=datetime.now(),
                                date_modified=datetime.now(),
                                created_by=1)
        bucketlist.save()

        # Add Items to the db
        # Task 1
        tasks1 = Item(name='Visit Nigeria',
                      bucketlist_id=1,
                      date_created=datetime.now(),
                      date_modified=datetime.now(),
                      done=False)
        tasks1.save()

        # Task 2
        tasks2 = Item(name='Visit New York',
                      bucketlist_id=1,
                      date_created=datetime.now(),
                      date_modified=datetime.now(),
                      done=False)
        tasks2.save()

        # Task 3
        tasks3 = Item(name='Visit Las Vegas',
                      bucketlist_id=1,
                      date_created=datetime.now(),
                      date_modified=datetime.now(),
                      done=False)
        tasks3.save()

        query_user = User.query.filter_by(username='******').first()
        if query_user:
            user = {}
            user['username'] = '******'
            user['id'] = query_user.id
            token = generate_a_token(user)

        # retrieve a token ::: Token should not a contain password
        if token:
            self.auth_head = {'Authorization': 'Bearer %s' % token}
        else:
            log.error('No Token Was Generated')
            self.fail()  # stop if a token generation failed

        # Add Other Users
        user = User(username='******',
                    password=generate_password_hash('njirap123'))
        user.save()

        user = User(username='******',
                    password=generate_password_hash('kimani123'))
        user.save()

        # Add a BucketList to the db
        bucketlist = BucketList(name='Visit Kenya',
                                date_created=datetime.now(),
                                date_modified=datetime.now(),
                                created_by=1)
        bucketlist.save()
Example #29
0
# -*- coding: utf-8 -*-

"""
Just for development time
"""

from manage import db
from wtxlog.models import User, Role, Category

if __name__ == '__main__':
    # init database
    db.create_all()

    # create user roles
    Role.insert_roles()

    # add administrator
    user = User()
    user.username = '******'
    user.password = '******'
    user.email = '*****@*****.**'
    user.role = Role.query.filter_by(permissions=0xff).first()
    user.confirmed = True

    # add default category
    category = Category()
    category.slug = 'default'
    category.name = 'Default'

    # commit
    db.session.add(user)
Example #30
0
 def setUp(self):
     self.app = create_app('testing')
     self.app_context = self.app.app_context()
     self.app_context.push()
     db.create_all()
     Role.insert_roles()
Example #31
0
 def set_up(self):
     db.session.close()
     db.drop_all()
     db.create_all()