def tearDown(self): """ executed after each test """ # destroy created data with self.app.app_context(): db.session.remove() db.drop_all()
def setUp(self): """ Creates a new database for the unit test to use """ app.config.from_object('config.%s' % str(APP_SETTING)) db.drop_all() db.create_all() seed_db()
def server(): app = create_app() port = get_open_port() app.url = 'http://localhost:{}'.format(port) def start(): print("start server") app.run(port=port) p = multiprocessing.Process(target=start) p.start() def check(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect(('localhost', port)) return True except Exception: return False finally: s.close() rc = wait_until(check) assert rc, "failed to start service" with app.app_context(): db.drop_all() db.create_all() yield app p.terminate()
def test_get_number_of_all_messages(self, user_1, user_2, channel_to_test) -> None: app.config['WTF_CSRF_ENABLED'] = False with app.app_context(): db.drop_all() db.create_all() db.session.add(user_1) db.session.add(user_2) db.session.add(channel_to_test) with app.test_client() as c: rv = login(c, user_1.email, 'testPassword') assert 'Log out' in str(rv.data) assert u.get_number_of_all_messages() == 0 db.session.add( Message(content='_', time=datetime.utcnow(), author_id=1, target_channel=1)) assert u.get_number_of_all_messages() == 1 for _ in range(10): db.session.add( Message(content='_', time=datetime.utcnow(), author_id=2, target_channel=1)) assert u.get_number_of_all_messages() == 1 with app.test_client() as c: rv = login(c, user_2.email, 'testPassword') assert 'Log out' not in str(rv.data) rv = login(c, user_2.email, 'testPassword2') assert 'Log out' in str(rv.data) assert u.get_number_of_all_messages() == 10
def setUp(self): self.app = app.test_client() app.testing = True with app.app_context(): db.drop_all() db.create_all()
def initdb(drop): if drop: if click.confirm('This operation will DROP ALL TABLES, continue?'): db.drop_all() click.echo('All tables have been dropped.') db.create_all() click.echo('Initialized database.')
def teardown(): db.session.remove() db.drop_all() for f in os.listdir(os.path.join(os.path.abspath(os.path.dirname(__file__)), "images")): if f != "test.jpg": os.remove(os.path.join(os.path.abspath(os.path.dirname(__file__)), "images", f))
def setUp(self): """ Create the database if not created! NOTE: this part work with mysql database, if you use any other database you may consider this part and make the necessary changes """ self.client_app = app.test_client() try: db.drop_all() except Exception as e: from flask_sqlalchemy import sqlalchemy e = sqlalchemy.create_engine(os.getenv('SQLALCHEMY_DATABASE_URI')) existing_databases = e.execute("SHOW DATABASES;") # Results are a list of single item tuples, so unpack each tuple existing_databases = [d[0] for d in existing_databases] # Create database if not exists if os.getenv('DATABASE_NAME_TESTING') not in existing_databases: e.execute( f"CREATE DATABASE {os.getenv('DATABASE_NAME_TESTING')}") # do it again db.drop_all() # now create the tables db.create_all() # add the default Data defaultData(app=app, db=db)
def setUp(self): self.app = create_app('Testing') self.client = self.app.test_client() self.user = { 'name': 'testexample', 'email': '*****@*****.**', 'password': '******' } self.event = { 'name': 'talanta', 'description': 'awesome', 'category': 'social', 'date': '12/9/19', 'location': 'nairobi' } self.rsvp = { 'name': "nameexample", 'email': '*****@*****.**', 'phone_no': '123456789', 'category': 'guest' } with self.app.app_context(): db.session.close() db.drop_all() db.create_all()
def refresh_repos(): """ Calls the GitHub API and writes to the db with the top-starred repos.""" try: # Call GitHubs API, the query params are set in Config response = requests.get(Config.GITHUB_API_STRING) # clear table and repopulate if response exists if response.status_code == 200: db.drop_all() db.create_all() for repo in response.json()['items']: new_repo = Repo( id=repo['id'], name=repo["name"], url=repo["html_url"], description=repo["description"], star_count=repo["stargazers_count"], created_date=repo["created_at"], last_push_date=repo["pushed_at"], modify_dtm=datetime.now(), ) # Insert record db.session.add(new_repo) db.session.commit() finally: # Would ideally want to add more exception handling here. pass # This extra query returns the most recent db timestamp refresh_time = Repo.query.order_by(Repo.modify_dtm.desc()).first().modify_dtm return refresh_time.split(".")[0]
def drop(): """ Drops database tables """ verified = prompt_bool( 'Do you really want to drop all the database tables?') if verified: sys.stdout.write('All tables dropped. Database is now empty.\n') db.drop_all()
def db(test_client): _db.app = test_client _db.create_all() yield _db _db.drop_all()
def createdb(testdata=True): """Initializes the database """ app = create_app() with app.app_context(): db.drop_all() db.create_all() if testdata: for i in range(1, 50): hotel_details = HotelDetails( name='The Apartments Dubai World Trade Centre', address='United Arab Emirates', badge='Clean Rooms', coordinate='25.224747', cost=590, image= 'https://res.cloudinary.com/esanjolabs/image/upload/hotels/3e4564321d5bbc209fcf215f25404de4.jpg', neighbourhood='Palm Jumeirah', rating=9, star_rating=5, type='hotel', id=i, date_created='2018-07-03 00:00:00', date_modified='2018-07-03 00:00:00') db.session.add(hotel_details) db.session.commit()
def tearDown(self): """ Ensures that the database is emptied for next unit test """ try: db.session.remove() db.drop_all() except Exception as e: pass
def test_repr() -> None: channel = Channel(name='channelName', password='******') assert channel.__repr__() == "Channel(name='channelName')" user = User(username='******', password='******', email='*****@*****.**') assert user.__repr__() == "User(name='userName')" with app.app_context(): db.drop_all() db.create_all() db.session.add(user) db.session.add(channel) channel_id = Channel.query.first().id user_id = User.query.first().id channel_allow_list = ChannelAllowList(user_id=user_id, channel_id=channel_id, user_role=UserRole.ADMIN.value) assert channel_allow_list.__repr__() == \ f'ChannelAllowList(channel_id=1, user_id=1, user_role={UserRole.ADMIN.value})' time = datetime.utcnow() message = Message(content='content', author_id=user_id, target_channel=channel_id, time=time) assert message.__repr__( ) == f"Message(author_id=1, target_channel=1, time={time})"
def setUp(self): """ Runs before each test """ service.init_db() db.drop_all() # clean up the last tests db.create_all() # create new tables Pet(name='fido', category='dog', available=True).save() Pet(name='kitty', category='cat', available=True).save() self.app = service.app.test_client()
def tearDown(self): ''' After the tests are done, remove the database session and drop all the tables ''' db.session.remove() db.drop_all()
def drop_all_tables(force=False): 'Drop all database tables. Must use --force to actually execute.' initialize_db_connections() if force: db.drop_all() db.engine.execute('DROP TABLE alembic_version;') else: print("Not dropping any tables without --force")
def initdb(drop): """初始化数据库""" if drop: click.confirm('这个操作会删除数据库,继续吗?', abort=True) db.drop_all() click.echo('删除数据库') db.create_all() click.echo('初始化数据库成功')
def drop_all_tables(force=False): 'Drop all database tables. Must use --force to actually execute.' initialize_db_connections() if force: db.drop_all() db.engine.execute('DROP TABLE alembic_version;') else: print("Not dropping any tables without --force")
def setUp(self): self.app = create_app("testing") self.client = self.app.test_client with self.app.app_context(): db.session.close() db.drop_all() db.create_all()
def database(app): db.drop_all() db.create_all() yield db db.session.close() db.drop_all() for i in app.config['UPLOADS_DEFAULT_DEST'].iterdir(): shutil.rmtree(i)
def wrapper(*args, **kwargs) -> None: """Wrapper of the decorator.""" app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False with app.app_context(): db.drop_all() db.create_all() func(*args, **kwargs)
def new_db(): """ 清空数据,重置数据库 :return: """ db.drop_all() db.create_all() Role.insert_role()
def tearDown(self): with self.app.app_context(): # drop all tables db.session.remove() db.drop_all() self.app = None self.client = None
def db(app, request): """ Session-wide test database """ _db.drop_all() _db.app = app _db.create_all() yield _db _db.drop_all()
def _db(app): """ Necessary to use the ``db_session`` fixture from pytest-flask-sqlalchemy """ with app.app_context(): db.create_all() yield db db.drop_all()
def client(): os.environ['APP_SETTINGS'] = 'config.TestingConfig' os.environ['FLASK_ENV'] = 'test' app = create_app() with app.test_client() as client: with app.app_context(): db.create_all() yield client db.drop_all()
def recreate_db(): """ Recreates a database. This should only be used once when there's a new database instance. This shouldn't be used when you migrate your database. """ db.drop_all() db.create_all() db.session.commit()
def setUp(self): self.db_fd, app.config['DATABASE'] = tempfile.mkstemp() app.testing = True self.app = app.test_client() self.shopping_list = {"name": "test_list"} self.item = {"name": "test_item"} with app.app_context(): db.drop_all() db.create_all()
def populate_db(): # TODO: Don't wipe all data db.drop_all() db.create_all() keys = pd.Series(np.arange(0, int(1e6))) values = pd.Series(np.random.randint(0, 1e6, int(1e6))) df = pd.concat([keys, values], axis=1) df.columns = ['key', 'value'] df.to_sql('KV', con=db.engine, index=False, if_exists='append', chunksize=1000)
def new_db(): """ 清空数据,重置数据库 clean all data and reset database :return: """ db.drop_all() db.create_all() Role.insert_role()
def createdb(testdata=True): """Initializes the database """ app = create_app() with app.app_context(): db.drop_all() db.create_all() if testdata: user = User(username="******", password="******") db.session.add(user) db.session.commit()
def drop_and_create_db(verbose=False): """ Drops database and creates a new one """ if not verbose: db.engine.echo = False db.reflect() db.drop_all() db.create_all() return 0
def drop_db(): with app.test_request_context(): db.session.remove() if app.config['SQLALCHEMY_DATABASE_URI'].find('postgresql://') > -1: # drop_all has problems with foreign keys in postgres database (cyclic dependency) db.engine.execute("drop schema if exists public cascade") db.engine.execute("create schema public") else: # drop all works for SQLite and should work for other DBMS like MySQL, Mongo etc db.drop_all()
def teardown(): app = create_app('test') with app.app_context(): db.session.remove() db.engine.execute("drop sequence suppliers_supplier_id_seq cascade") db.drop_all() db.engine.execute("drop table alembic_version") insp = inspect(db.engine) for enum in insp.get_enums(): db.Enum(name=enum['name']).drop(db.engine) db.get_engine(app).dispose() app_env_var_mock.stop()
def drop_db(verbose=False): """ Drops database """ if verbose: db.engine.echo = False else: db.engine.echo = True db.session.commit() db.reflect() db.drop_all() #db.engine.execute("drop schema if exists public cascade;") #db.engine.execute("create schema public;") #db.create_all() return 0
def tearDown(self): with self.app.app_context(): db.session.remove() db.drop_all()
def tearDown(self): with self.app.app_context(): db.session.remove() db.drop_all() os.unlink(self.app.config.get('DATABASE'))
def drop_db(): with app.test_request_context(): db.session.remove() db.drop_all()
rated=False, result=result, game_record=sgf_data, date_played=datetime.datetime.now() - datetime.timedelta(seconds=random.randint(0, 10000000)), ) return g print("Games...") games = [make_game() for i in range(2000)] print("Saving games...") for g in games: db.session.add(g) db.session.commit() strongest = max(p_priors, key=lambda k: p_priors[k]) strongest_games = [str(g) for g in games if g.white.user_id == strongest or g.black.user_id == strongest] print("Strongest, %d (%f):\n%s" % (strongest, p_priors[strongest], strongest_games)) if __name__ == "__main__": app = get_app("config.DockerConfiguration") with app.app_context(): db.session.remove() db.drop_all() db.get_engine(app).dispose() print("Creating tables...") db.create_all() print("Creating test data...") create_test_data() print("Creating extra data...") create_extra_data()
def teardown(): _db.drop_all()
def create_db(): db.drop_all() db.create_all()
def setUp(self): self.client = current_app.test_client() self.posts_per_page = current_app.config.get('POSTS_PER_PAGE') db.drop_all() db.create_all()
def tearDown(self): db.drop_all()
def tearDown(self): with app.test_request_context(): db.drop_all()
def dropdb(): db.init_app(current_app) db.drop_all()
def destroydb(): """ Destroys the database """ db.drop_all()
def drop_and_create_db(): db.drop_all() db.create_all()
def tearDown(self): db.session.remove() db.drop_all() return super(TestCase, self).tearDown()
def tearDown(self): db.session.remove() db.drop_all() self.app_context.pop()
def drop(): if prompt_bool("Are you sure you want to drop all your data"): db.drop_all()
def teardown(): ctx.pop() db.drop_all()
def test_clear_db(self): db.drop_all()
def tearDown(self): db.session.remove() db.drop_all()
def drop_db(): db.drop_all()
def teardown(): db.session.remove() db.drop_all()
def init_db(): db.drop_all() db.create_all() db.session.commit()