Ejemplo n.º 1
0
def main():
    db.drop_all()
    db.create_all()
    
    if len(sys.argv) > 1 and sys.argv[1] == 'd':
        # Entering some sample data
        b = Board('Random', 'b', True)
        b_thread1 = Thread(b, 'A Subject')
        b_thread1_post1 = Post(b_thread1, 'Person 1', 'First post content', None,
                               '*****@*****.**', datetime.datetime.now())
        b_thread1_post2 = Post(b_thread1, 'Person 2', 'Second post content', None,
                               '*****@*****.**', datetime.datetime.now())
        b_thread1_post3 = Post(b_thread1, 'Person 3', 'Third post content', None,
                               '*****@*****.**', datetime.datetime.now())
        
        # The UndefinedVariable comments tell PyDev to suppress errors that it
        # wrongly generates for the add and commit methods.
        db.session.add(b) #@UndefinedVariable
        db.session.add(b_thread1) #@UndefinedVariable
        db.session.add(b_thread1_post1) #@UndefinedVariable
        db.session.add(b_thread1_post2) #@UndefinedVariable
        db.session.add(b_thread1_post3) #@UndefinedVariable
        
        db.session.commit() #@UndefinedVariable
    
    print('The database has been set up.')
Ejemplo n.º 2
0
def reset_db():
    db.drop_all()
    print("Tables dropped")
    db.create_all()
    print("Tables created")
    seed_db()
    print("Tables seeded")
Ejemplo n.º 3
0
def drop_db():
    db.drop_all()
    db.session.execute("DROP TABLE IF EXISTS alembic_version;")
    db.session.execute("DROP TABLE IF EXISTS secondary_schema.users;")
    db.session.execute("DROP TABLE IF EXISTS secondary_schema.google_users;")
    db.session.commit()
    print("dropped all tables")
def reset():
    db.drop_all()
    db.create_all()
    for sdg in ALL_SDG:
        db.session.add(sdg)
    db.session.commit()
    return {"status": "completed"}
Ejemplo n.º 5
0
def get_app():
    if 'SETTINGS_FILE' not in os.environ:
        root = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
        os.environ['SETTINGS_FILE'] = os.path.join(root, 'config', 'test.cfg')

    tmpdir = os.environ.get('TMPDIR', '/tmp')
    prometheus_dir = os.path.join(tmpdir, 'emf_test_prometheus')
    os.environ['prometheus_multiproc_dir'] = prometheus_dir

    if os.path.exists(prometheus_dir):
        shutil.rmtree(prometheus_dir)
    if not os.path.exists(prometheus_dir):
        os.mkdir(prometheus_dir)

    app = create_app()

    with app.app_context():
        try:
            db.session.close()
        except:
            pass

        db.drop_all()

        db.create_all()
        CreateBankAccounts().run()
        CreateTickets().run()

    return app.test_client(), app, db
Ejemplo n.º 6
0
    def setUp(self):

        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False
        app.config['DEBUG'] = False
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \
            os.path.join(path, TEST_DB)
        self.app = app.test_client()
        db.drop_all()
        db.create_all()

        #setting up org and users
        org = Organization(name='Test', org_key='12345')
        add_db_entry(org)
        admin = User(organization=org.id,
                     email=self.admin_username,
                     password=generate_password_hash(self.admin_password),
                     name='Admin',
                     role='admin')
        add_db_entry(admin)
        user = User(organization=org.id,
                    email=self.user_username,
                    password=generate_password_hash(self.user_password),
                    name='User',
                    role='user')
        add_db_entry(user)

        self.assertEqual(app.debug, False)
Ejemplo n.º 7
0
    def setUp(self):
        self.app = app
        self.ctx = self.app.app_context()
        self.ctx.push()
        db.drop_all()
        db.create_all()

        # Creating the 1st user. This user will issue a request
        user = User(username=self.default_username)
        user.set_password_hash(self.default_password)
        db.session.add(user)
        db.session.commit()
        self.client = TestClient(self.app, user.generate_auth_token(), '')

        # Create a request for 1st user
        request_data = {
            'meal_type': 'Vietnamese',
            'meal_time': 'Dinner',
            'location_string': 'San Francisco'
        }
        rv, json = self.client.post(API_VERSION + '/requests/',
                                    data=request_data)
        self.request_location = rv.headers['Location']

        # Create the 2nd user. This user will make proposal for the request by
        # 1st user
        user_2 = User(username='******')
        user_2.set_password_hash('123456')
        db.session.add(user_2)
        db.session.commit()
        self.client = TestClient(self.app, user_2.generate_auth_token(), '')
Ejemplo n.º 8
0
def add_posts_to_db():
    db.drop_all()
    db.create_all()
    for post in posts:
        db.session.add(Post(post["name"], post["max_votes"], post["applied_hostel"],
                            post["help_text"]))
    db.session.commit()
Ejemplo n.º 9
0
def drop_db():

    """drops all tables in database
    """

    db.drop_all()
    db.engine.execute("DROP TABLE IF EXISTS alembic_version;")
    print("Deleted Tables")
Ejemplo n.º 10
0
    def flush_db(flush=False):

        if flush:
            db.reflect()
            db.drop_all()
            db.create_all()

            return print('Database cleared!')
Ejemplo n.º 11
0
 def setUp(self):
     with app.app_context():
         app.config.from_object(app_config['testing'])
         self.app = app.test_client()
         db.drop_all()
         db.create_all()
         self.create_user()
         self.assertEqual(app.debug, False)
Ejemplo n.º 12
0
def add_posts_to_db():
    db.drop_all()
    db.create_all()
    for post in posts:
        db.session.add(
            Post(post["name"], post["max_votes"], post["applied_hostel"],
                 post["help_text"]))
    db.session.commit()
Ejemplo n.º 13
0
def populate_all():
    db.drop_all()
    db.create_all()

    create_roles()
    create_user()
    create_books()

    db.session.commit()
Ejemplo n.º 14
0
def populate_all():
    db.drop_all()
    db.create_all()

    create_roles()
    create_user()
    create_books()

    db.session.commit()
Ejemplo n.º 15
0
def client():
    app.config["TESTING"] = True
    os.environ["DATABASE_URL"] = "sqlite:///memory:"
    client = app.test_client()

    db.drop_all()
    db.create_all()

    yield client
Ejemplo n.º 16
0
    def setUp(self):
        """Define test variables and initialize app."""
        self.app = app
        db.drop_all()
        db.create_all()
        self.client = self.app.test_client
        # binds the app to the current context

        with self.app.app_context():
            self.db = SQLAlchemy()
Ejemplo n.º 17
0
 def setUp(self):
     self.app = app
     self.ctx = self.app.app_context()
     self.ctx.push()
     db.drop_all()
     db.create_all()
     user = User(username=self.default_username)
     user.set_password_hash(self.default_password)
     db.session.add(user)
     db.session.commit()
     self.client = TestClient(self.app, user.generate_auth_token(), '')
Ejemplo n.º 18
0
def init_db():
    from main import db
    from main.models import Repo, Commit
    
    db.drop_all()
    db.create_all()
    for _, repos in REPOS:
        for user, repo in repos:
            repo = Repo(username=user, reponame=repo)
            db.session.add(repo)
    db.session.commit()
Ejemplo n.º 19
0
    def tearDown(self):
        """
        Recreate DB with only basic data
        :return:
        """
        with self.app.app_context():
            db.reflect()
            db.drop_all()

        self.metadata.create_all()
        self.populateDb()
Ejemplo n.º 20
0
    def setUp(self):
        app.config['TESTING'] = True
        app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get(
            "DB_STRING",
            'postgres://*****:*****@localhost:5432/mealsdb')
        self.app = app.test_client()
        db.session.remove()

        db.drop_all()
        db.create_all()
        create_meals()
        self.json_file = load_json("meals.json")
Ejemplo n.º 21
0
def init_db():
    db.drop_all()
    db.create_all()

    with open("test3.json") as test_json:
        test_data = json.load(test_json)

    for item in test_data['items']:
        book = Book(item["volumeInfo"]['title'],
                    item["volumeInfo"]['categories'][0],
                    item["volumeInfo"]['publishedDate'], 420,
                    item["volumeInfo"]['industryIdentifiers'][1]["identifier"],
                    item["saleInfo"]['retailPrice']['amount'])
    def setUp(cls):

        if not cls.setup:
            os.environ["FLASK_ENV"] = "testing"
            cls.app = create_app()
            cls.app_context = cls.app.app_context()
            cls.app_context.push()
            db.drop_all()
            db.create_all()

            cls.client = cls.app.test_client()
            cls.setup = True
        return cls
Ejemplo n.º 23
0
 def test_create_meals(self):
     # test data is loaded successfully
     db.drop_all()
     db.create_all()
     mealId1 = self.json_file["meals"][0]["idMeal"]
     # expect index out of bounds exception
     with self.assertRaises(IndexError):
         response = self.app.get("/meals/" + str(mealId1))
     create_meals()
     all_meals = db.session.query(Meal_Name).all()
     self.assertEqual(len(all_meals), len(self.json_file["meals"]))
     response = self.app.get("/meals/" + str(mealId1))
     self.assertEqual(response.status, "200 OK")
Ejemplo n.º 24
0
    def setUp(cls):
        cls.app = create_app()  # creates an app
        cls.app.config.from_object(
            'default_settings.Testing')  # forces testing configuration
        cls.app_context = cls.app.app_context()  # app_context is retrieved
        cls.app_context.push()  # binds app context to the current context
        cls.client = cls.app.test_client(
        )  # test client is made using the app context
        db.drop_all()
        db.create_all()

        # invokes 'flask db_cli seed' in console
        runner = cls.app.test_cli_runner()
        runner.invoke(args=["db_cli", "seed"])
Ejemplo n.º 25
0
def app_factory(cache):
    if "SETTINGS_FILE" not in os.environ:
        root = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
        os.environ["SETTINGS_FILE"] = os.path.join(root, "config", "test.cfg")

    tmpdir = os.environ.get("TMPDIR", "/tmp")
    prometheus_dir = os.path.join(tmpdir, "emf_test_prometheus")
    os.environ["prometheus_multiproc_dir"] = prometheus_dir

    if os.path.exists(prometheus_dir):
        shutil.rmtree(prometheus_dir)
    if not os.path.exists(prometheus_dir):
        os.mkdir(prometheus_dir)

    #  For test purposes we're perpetually 2 weeks into ticket sales and 10 weeks before the event.
    fake_event_start = datetime.datetime.now() + datetime.timedelta(weeks=10)
    config_override = {
        "SALES_START":
        (datetime.datetime.now() - datetime.timedelta(weeks=2)).isoformat(),
        "EVENT_START":
        fake_event_start.isoformat(),
        "EVENT_END":
        (fake_event_start + datetime.timedelta(days=4)).isoformat(),
    }
    if cache:
        config_override["CACHE_TYPE"] = "simple"

    app = create_app(dev_server=True, config_override=config_override)

    with app.app_context():
        try:
            db_obj.session.close()
        except:
            pass

        db_obj.drop_all()

        # We're not using migrations here so we have to create the extension manually
        db_obj.session.execute(text("CREATE EXTENSION IF NOT EXISTS postgis"))
        db_obj.session.commit()
        db_obj.session.close()

        db_obj.create_all()
        create_bank_accounts()
        create_product_groups()

        yield app

        db_obj.session.close()
        db_obj.drop_all()
Ejemplo n.º 26
0
def init_db():
    """删除数据库中所有数据并初始化"""
    db.drop_all()
    db.create_all()

    admins = Role(id=1, name='管理员')
    admins.save()

    admins.set_permission('user')
    admins.set_permission('users')

    users = Role(id=2, name='普通用户')
    users.save()

    print("The database has been created.")
def client():
    test_client = app.test_client()
    db.drop_all()
    db.create_all()
    user = User(username='******')
    user.set_password_hash('123456')
    db.session.add(user)
    db.session.commit()

    yield test_client
    """
		tearDown code
	"""
    db.session.remove()
    db.drop_all()
Ejemplo n.º 28
0
def drop_db():
    db.drop_all()
    print("Tables Drop")


# @db_commands.cli.command("seed")
# def seed_db():
#     from models.Book import Book
#     from faker import Faker
#     faker = Faker()

#     for i in range(20):
#         book = Book()
#         book.title = faker.catch_phrase()
#         db.session.add(book)
    
#     db.session.commit()
#     print("Tables seeded")
Ejemplo n.º 29
0
def app():
    """ Fixture to provide an instance of the app.
        This will also create a Flask app_context and tear it down.

        This fixture is scoped to the module level to avoid too much
        Postgres teardown/creation activity which is slow.
    """
    if "SETTINGS_FILE" not in os.environ:
        root = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
        os.environ["SETTINGS_FILE"] = os.path.join(root, "config", "test.cfg")

    tmpdir = os.environ.get("TMPDIR", "/tmp")
    prometheus_dir = os.path.join(tmpdir, "emf_test_prometheus")
    os.environ["prometheus_multiproc_dir"] = prometheus_dir

    if os.path.exists(prometheus_dir):
        shutil.rmtree(prometheus_dir)
    if not os.path.exists(prometheus_dir):
        os.mkdir(prometheus_dir)

    app = create_app()

    with app.app_context():
        try:
            db_obj.session.close()
        except:
            pass

        db_obj.drop_all()

        # We're not using migrations here so we have to create the extension manually
        db_obj.session.execute(text("CREATE EXTENSION IF NOT EXISTS postgis"))
        db_obj.session.commit()
        db_obj.session.close()

        db_obj.create_all()
        create_bank_accounts()
        create_product_groups()

        yield app

        db_obj.session.close()
        db_obj.drop_all()
Ejemplo n.º 30
0
def app():
    """ Fixture to provide an instance of the app.
        This will also create a Flask app_context and tear it down.

        This fixture is scoped to the module level to avoid too much
        Postgres teardown/creation activity which is slow.
    """
    if 'SETTINGS_FILE' not in os.environ:
        root = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
        os.environ['SETTINGS_FILE'] = os.path.join(root, 'config', 'test.cfg')

    tmpdir = os.environ.get('TMPDIR', '/tmp')
    prometheus_dir = os.path.join(tmpdir, 'emf_test_prometheus')
    os.environ['prometheus_multiproc_dir'] = prometheus_dir

    if os.path.exists(prometheus_dir):
        shutil.rmtree(prometheus_dir)
    if not os.path.exists(prometheus_dir):
        os.mkdir(prometheus_dir)

    app = create_app()

    with app.app_context():
        try:
            db_obj.session.close()
        except:
            pass

        db_obj.drop_all()

        # We're not using migrations here so we have to create the extension manually
        db_obj.session.execute(text("CREATE EXTENSION IF NOT EXISTS postgis"))
        db_obj.session.commit()
        db_obj.session.close()

        db_obj.create_all()
        CreateBankAccounts().run()
        CreateTickets().run()

        yield app

        db_obj.session.close()
        db_obj.drop_all()
Ejemplo n.º 31
0
def test_new_user(test_client):
    db.create_all()
    user = User(first_name='Paul',
                last_name='Asalu',
                email='*****@*****.**',
                tel='09045444444',
                country='Nigeria',
                state='Lagos',
                address='66 Baruwa Street, Agboju',
                age=22,
                user_id='1234',
                sign_up_date=d.datetime.utcnow(),
                sign_up_method='Firebase',
                days_left=1)
    Role.insert_roles()
    role = Role.query.filter_by(id=1).first()
    user.role = role

    Guides.insert_guides()
    guide = Guides.query.filter_by(id=1).first()
    user.guides.append(guide)

    db.session.add(user)
    db.session.commit()

    assert user.first_name == 'Paul'
    assert user.last_name == 'Asalu'
    assert user.email == '*****@*****.**'
    assert user.tel == '09045444444'
    assert user.country == 'Nigeria'
    assert user.state == 'Lagos'
    assert user.address == '66 Baruwa Street, Agboju'
    assert user.travel_history == 0
    assert user.age == 22
    assert user.user_id == '1234'
    assert user.sign_up_date == user.sign_up_date
    assert user.sign_up_method == 'Firebase'
    assert user.med_state == 'Mild'
    assert user.days_left == 1
    assert user.role.name == 'USER'
    db.drop_all()
def initdb(drop):
   if drop:
      click.confirm('你想删除全部数据吗?', abort=True)
      db.drop_all()
      click.echo('已删除')
   db.create_all()
   admin = User.query.filter_by(is_admin=True).first()
   if admin:
      password = os.getenv("ADMIN_PASSWORD")
      username = os.getenv("ADMIN_USERNAME")
      admin.username = username
      admin.set_password(password)
   else:
      password = os.getenv("ADMIN_PASSWORD")
      username = os.getenv("ADMIN_USERNAME")
      name = os.getenv("ADMIN_NAME")
      email = os.getenv("ADMIN_EMAIL")
      admin = User(username=username,name=name,email=email,Intellectual_disability=0,is_admin=True)
      admin.set_password(password)
      db.session.add(admin)
   db.session.commit()
   click.echo('已完成')
Ejemplo n.º 33
0
def app():
    """ Fixture to provide an instance of the app.
        This will also create a Flask app_context and tear it down.

        This fixture is scoped to the module level to avoid too much
        Postgres teardown/creation activity which is slow.
    """
    if 'SETTINGS_FILE' not in os.environ:
        root = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
        os.environ['SETTINGS_FILE'] = os.path.join(root, 'config', 'test.cfg')

    tmpdir = os.environ.get('TMPDIR', '/tmp')
    prometheus_dir = os.path.join(tmpdir, 'emf_test_prometheus')
    os.environ['prometheus_multiproc_dir'] = prometheus_dir

    if os.path.exists(prometheus_dir):
        shutil.rmtree(prometheus_dir)
    if not os.path.exists(prometheus_dir):
        os.mkdir(prometheus_dir)

    app = create_app()

    with app.app_context():
        try:
            db_obj.session.close()
        except:
            pass

        db_obj.drop_all()

        db_obj.create_all()
        CreateBankAccounts().run()
        CreateTickets().run()

        yield app

        db_obj.session.close()
        db_obj.drop_all()
Ejemplo n.º 34
0
    def setUp(self):
        """
        Prepare DB: drop all tables, and recreate DB
        :return:
        """
        app.config['TESTING'] = True
        app.config['LOGIN_DISABLED'] = True
        app.config['DEBUG'] = True
        app.config['IS_PINGER'] = True
        app.config['IS_PONGER'] = True
        app.config['IS_MASTER'] = True

        self.app = app

        app.config.update(
            TESTING=True,
            LOGIN_DISABLED=True,
            DEBUG=True,
            IS_PINGER=True,
            IS_PONGER=True,
            IS_MASTER=True,
        )

        self.client = self.app.test_client()
        self.auth_header = {'Authorization': ' Basic dXNlcjE6MDAwMA=='}

        engine = sa.create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
        models.metadata.bind = engine
        self.metadata = models.metadata

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

        self.metadata.create_all()
        self.populateDb()
Ejemplo n.º 35
0
from main import db
db.drop_all()
Ejemplo n.º 36
0
 def tearDown(self):
     self.driver.quit()
     db.drop_all()
Ejemplo n.º 37
0
 def tearDown(self):
     with self.app.test_request_context():
         db.drop_all()
         db.metadata.clear()
Ejemplo n.º 38
0
 def tearDown(self):
     db.session.remove()
     db.drop_all()
Ejemplo n.º 39
0
def delete_db():
    db.drop_all()
    return 'Success!'
Ejemplo n.º 40
0
 def tearDown(self):
     """测试完成的清除工作"""
     db.session.remove()
     db.drop_all()
     self.app_context.pop()
def resetTables():
	db.drop_all()
	db.create_all()
Ejemplo n.º 42
0
def dropdb():
    if prompt_bool('This will delete all data, are you sure'):
        db.drop_all()
Ejemplo n.º 43
0
def reset():   
    db.drop_all()
    db.create_all()
    return 'Success: reset'
Ejemplo n.º 44
0
 def setUp(self):
     db.drop_all()
     db.create_all()
Ejemplo n.º 45
0
 def tearDown(self):
     db.drop_all()