def start(): fake = Faker() db.drop_all() db.create_all() # Users for _ in range(100): u = User() u.username = fake.unique.user_name() u.password = fake.password() u.email = fake.email() db.session.add(u) db.session.commit() # Posts all_users = User.query.all() for _ in range(1000): p = Post() p.user = random.choice(all_users) p.title = fake.sentence() p.content = fake.paragraph() db.session.add(p) db.session.commit() # Comments all_posts = Post.query.all() for _ in range(5000): c = Comment() c.content = fake.paragraph() c.user = random.choice(all_users) c.post = random.choice(all_posts) db.session.add(c) db.session.commit()
def drop_database(environment): ''' Delete a database for the given environment ''' flask_app = create_app(environment) flask_app.app_context().push() db.drop_all()
def setup_db(): with app.app_context(): # print app db.drop_all() db.create_all() db.session.commit() print "database is set up!"
def init_app(app): engine = create_engine(config.SQLALCHEMY_DATABASE_URI_PREFIX) DB_Session = sessionmaker(bind=engine) session = DB_Session() @app.context_processor def ctx(): return { "ID_ROOT": ID_ROOT, "Resource": Resource, } try: session.execute("USE %s" % config.DB_NAME) except Exception as e: if 'Unknown database' in e.message: # init database session.execute(""" CREATE DATABASE IF NOT EXISTS %s DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci """ % config.DB_NAME) session.commit() with app.app_context(): db.drop_all() db.create_all() build_db()
def test_initDB(self): _app = create_app(debug=True) with _app.app_context(): db.drop_all() db.create_all() session: scoped_session = db.session stats_record1: StatsTab = StatsTab() stats_record1.user_id = 30 stats_record1.email = '*****@*****.**' stats_record1.firstname = 'Mario' stats_record1.lastname = 'Rossi' session.add(stats_record1) session.commit() stats_check: StatsTab = session.query(StatsTab).filter( StatsTab.user_id == 30).first() self.assertIsNotNone(stats_check) self.assertEqual(stats_record1.user_id, stats_check.user_id) self.assertEqual(stats_record1.email, stats_check.email) stats_check.email = '*****@*****.**' session.commit() stats_check_mod: StatsTab = session.query(StatsTab).filter( StatsTab.user_id == 30).first() self.assertIsNotNone(stats_check_mod) self.assertNotEqual('*****@*****.**', stats_check_mod.email) stats = stats_check_mod.to_json() print(stats)
def teardownrdown(): # As a tear down downgrade the revision to base. # Safer option, got to check with different constraints though. downgrade(config, revision='base') # Just a make sure. _db.drop_all()
def admin_install(user): db.drop_all() db.create_all() create_test_data() return redirect("/admin", code=302)
def setUp(self): """Define test variables and initialize app.""" self.app = app_factory(config.Testing, config.project_name) self.client = self.app.test_client self.new_company = company = { "name": "New Company", "description": "A company", "company_type": "buyer" } self.updated_company = company = { "name": "Updated Company", "description": "A company", "company_type": "buyer" } self.comparison_company = { "id": 1, "name": "New Company", "description": "A company", "company_type": "buyer", "products": [], "orders": [] } self.updated_comparison_company = { "id": 1, "name": "Updated Company", "description": "A company", "company_type": "buyer", "products": [], "orders": [] } # binds the app to the current context with self.app.app_context(): # drop and create all tables db.drop_all() db.create_all()
def tearDown(self): db.session.remove() db.drop_all() bdb.drop() bdb_refseq.drop() scheduler.shutdown()
def db(app): _db.app = app _db.init_app(app) _db.create_all() yield _db _db.drop_all()
def app(): app = create_app() with app.app_context(): db.create_all() yield app db.session.close() db.drop_all() db.session.remove()
def init(): """ The init function for the database. The function deconstructs and then constructs the database. """ db.drop_all() db.create_all()
def setUp(self): if not main.app.config['SQLALCHEMY_DATABASE_URI'].startswith('sqlite://'): raise RuntimeError('Test against sqlite DB! not %r' % main.app.config['SQLALCHEMY_DATABASE_URI']) main.app.config['TESTING'] = True main.app.debug = True main.app.test_request_context().push() db.drop_all() db.create_all()
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(app.config['BASEDIR'], test_db) self.app = app.test_client() db.drop_all() db.create_all()
def reset_db(): # Deleting up the databasae print("Deleting the database...") db.reflect() db.drop_all() # Creating all tables for the models print("Creating database models...") db.create_all()
def tearDown(self): db.session.remove() db.drop_all() bdb.drop() bdb_refseq.drop() try: scheduler.shutdown() except SchedulerNotRunningError: warn('Scheduler was not running at the end of the test')
def initialize_database(): """ Initialisiere die Datenbank mit Testdaten. Alle vorhandenen Daten werden geluescht. """ stations = (("Oper", "Operngasse 1", "1010", "Wien", u"Österreich"), ("Hohe Warte Stadium", "Heiligenstadt", "1190", "Wien", u"Österreich"), ("Fliegerhorst Brumowski", "Brumowskigasse 23", "3425", "Tulln an der Donau", u"Österreich"), ("FH Technikum Wien", "Höchstädtplatz 6", "1200", "Wien", u"Österreich"), ("Red Bull Ring", u"Schloßweg 1", "8724", "Spielberg", u"Österreich")) cars = (("Citroen", u"C3", "silber", 5, 4.8, 50, "W-997G"), ("Ford", u"Focus", "rot", 5, 5.9, 70, "W-997GH"), ("Smart", u"ForTwo", "gelb", 2, 3.5, 70, "W-997GI"), ("VW", u"Käfer", "Rost", 4, 6.8, 40, "W 992223" ), ("Renault", "Grand Espace", "schwarz", 7, 8.8, 120, "K 009DF"), ("McLaren", "P1", "gelb", 2, 12.3, 190, "S 99823")) kunden = (("Alice Amber", "Nussdorfer Strasse 77", "1090", "Wien", u"Österreich"), ("Bob Builder", "Lederwaschstrasse 2", "5589", "Tamsweg", u"Österreich"), ("Istvan Nagy", "Halasz utca 25", "9400", "Sopron", u"Ungarn"), ("Ignaz Zurbgriggen", "Wildbachstrasse 9", "8340", "Hinwil", u"Schweiz"), ("Charly Custer", "Albrechtgasse 530", "3571", "Gars am Kamp", u"Österreich"), ("Eve Easter", "Kardinal Piffl Platz 2", "3400", "Klosterneuburg", u"Österreich")) db.drop_all() db.create_all() for c in cars: d = dict(zip( ('manufacturer', 'typ', 'color', 'seats', 'consumption', 'price', 'platenumber'), c)) db.session.add(Car(**d)) for s in stations: d = dict(zip( ('name', 'street', 'plz', 'city', 'country'), s)) db.session.add(Station(**d)) for k in kunden: d = dict(zip( ('name', 'street', 'plz', 'city', 'country'), k)) db.session.add(Kunde(**d)) db.session.flush() c3, focus, fortwo, kaefer, espace, p1 = Car.query.all() oper, hohewarte, lale, fh, rbr = Station.query.all() alice, bob, istvan, ignaz, charly, eve = Kunde.query.all() c3.station = hohewarte focus.station = lale espace.station = hohewarte Leihe(kunde=alice, car=c3, von=parsedate('2014-02-01 14:00'), bis=parsedate('2014-02-10 10:00'), returned=True, station_abhol=hohewarte, station_return=hohewarte) Leihe(kunde=alice, car=c3, von=parsedate('2014-02-14 08:00'), bis=parsedate('2014-02-15 22:00'), returned=True, station_abhol=hohewarte, station_return=lale) Leihe(kunde=ignaz, car=c3, von=datetime.today() - timedelta(days=2), bis=datetime.today() + timedelta(days=5), returned=False, station_abhol=hohewarte, station_return=rbr) Leihe(kunde=istvan, car=p1, von=parsedate('2014-01-14 09:00'), bis=datetime.today() + timedelta(days=2), returned=False, station_abhol=lale, station_return=fh) Leihe(kunde=charly, car=p1, von=datetime.today() + timedelta(days=10), bis=datetime.today() + timedelta(days=12), returned=False, station_abhol=lale, station_return=fh) db.session.commit()
def init_app(app, config_type): configure_app(app, config_type) app.url_map.strict_slashes = False db.init_app(app) api.init_app(app) api.add_namespace(ns) if config_type == "testing": with app.app_context(): db.drop_all() db.create_all()
def setup(): db.drop_all() db.create_all() user = Users(username='******', email=environ.get('EMAIL_ADDRESS')) user.password = environ.get('PASSWORD') db.session.add(Tags(name='flask')) db.session.add(Tags(name='biology')) db.session.add(Tags(name='chemistry')) db.session.add(user) db.session.commit()
def test_getstats_fail(self, pippo, pluto): _app = create_app(debug=True) with _app.app_context(): app = _app.test_client() db.drop_all() db.create_all() reply = app.get('/stats/' + str(user1_json['id'])) body = json.loads(str(reply.data, 'utf8')) expected = NoStats() self.assertEqual(expected['code'], body['code']) self.assertEqual(expected['data'], body['data'])
def test_Update(self, pippo): _app = create_app(debug=True) with _app.app_context(): db.drop_all() db.create_all() calc_stats_async(user1_json['id']) session = db.session stats_check: StatsTab = session.query(StatsTab).filter( StatsTab.user_id == user1_json['id']).first() self.assertIsNotNone(stats_check) self.assertEqual(user1_json['id'], stats_check.user_id) self.assertEqual(user1_json['email'], stats_check.email)
def build_db(app): with app.app_context(): print("dropping...") db.drop_all() print("creating structure...") db.create_all() if prompt_bool("Populate from 'rare pepes (tm)' album"): if not client: raise RuntimeError("no imgur credentials found") for album in ["U2dTR"]: for img in client.get_album_images(album): add_from_img(img, origin="1270 rare pepes (U2dTR)") #sleep(1) db.session.commit()
def test_getstats(self, pippo, pluto): _app = create_app(debug=True) with _app.app_context(): app = _app.test_client() db.drop_all() db.create_all() # calc_stats_async(user1_json['id']) # reply = _get_stats(user1_json['id']) # print(reply) reply = app.get('/stats/' + str(user1_json['id'])) body = json.loads(str(reply.data, 'utf8')) self.assertEqual(user1_json['id'], body['user_id']) self.assertEqual(user1_json['email'], body['email'])
def ragnarok(): db.session.close() db.drop_all() db.create_all() for name, url in url_master.url_master_list.items(): print(name) new_url = URLList(name=name, url=url) db.session.add(new_url) db.session.commit() return "NUKED!! ☢ (and rebuilt database)"
def init_database(): # Create the database and the database table db.create_all() # Insert user data country1 = Country(name='United States') country2 = Country(name='Canada') # user1 = User(email='*****@*****.**', plaintext_password='******') # user2 = User(email='*****@*****.**', plaintext_password='******') db.session.add(country1) db.session.add(country2) # Commit the changes for the users db.session.commit() yield db # this is where the testing happens! db.drop_all()
def setup(): if not config.get('setup', bool): abort(404) if request.method == 'POST': if not check_keys(): flash(error_message) return render_template('setup.html') username = request.form['username'] password = request.form['password_1'] email = request.form['email'] db_uri = request.form['database_uri'] # create database config.set('database_uri', db_uri) app.config['SQLALCHEMY_DATABASE_URI'] = db_uri db.drop_all() db.create_all() # create admin user admin = NewUser(username, password, email) admin.admin = True admin.active = True admin.create() # generate secret key secret_key = os.urandom(24) config.set('secret_key', secret_key) app.config['SECRET_KEY'] = secret_key # set a default upload directory blackboard_root = os.path.dirname(os.path.abspath(__file__)) config.set('upload_destination', blackboard_root + '/static/upload') # disable setup config.set('setup', 'False') flash(messages.setup_finished, 'message') return redirect(url_for('login')) else: return render_template('setup.html')
def __init__(self, name, config=None, reinit_db=False): if not config: config = {"SQLALCHEMY_DATABASE_URI": "sqlite:///platformer_node_{}.db".format(name)} self.app = flask.Flask(__name__) self.app.config.update(config) db.init_app(self.app) with self.app.app_context(): if reinit_db: db.drop_all() db.create_all() manager = flask.ext.restless.APIManager(self.app, flask_sqlalchemy_db=db) manager.create_api(Peer, url_prefix="", methods=["GET", "POST", "PUT", "DELETE"], include_columns=["url"]) manager.create_api(Secret, url_prefix="", methods=["POST"]) # Note that route definitions have to go here, because the app is not global. @self.app.route("/", methods=["HEAD"]) def pong(): return ""
def setup_flask(drop_all=False): ''' initialize top level objects give orm and router accesss flash returns app and api to simplify usining this independently of the full app ''' # TODO error handling app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db.init_app(app) with app.app_context(): # Extensions like Flask-SQLAlchemy now know what the "current" app # is while within this block. Therefore, you can now run........ if drop_all: db.drop_all() db.create_all() api = Api(app, catch_all_404s=True) build_endpoints(api) return app, api
def run(self, suite=None): blueprint = None tests = None if suite: if suite.find('.'): blueprint, tests = suite.split('.', 1) else: blueprint = suite app = app_factory(config=config.Testing) client = app.test_client() with app.app_context(): db.drop_all() db.create_all() db.engine.execute('SET foreign_key_checks=0' ) # We don't need foreign key checks on tests unittest.TextTestRunner(verbosity=2).run( BlueprintTesting(blueprint, tests).suite()) db.drop_all()
def initialize_app(flask_app): configure_app(flask_app) blueprint = Blueprint('api', __name__, url_prefix='/api') api.init_app(blueprint) api.add_namespace(service_namespace) api.add_namespace(user_profile_namespace) api.add_namespace(domain_profile_namespace) api.add_namespace(implicit_profile_namespace) api.add_namespace(gbu_namespace) api.add_namespace(vul_record_namespace) api.add_namespace(vulnerabilities_namespace) api.add_namespace(oracle_severity_score_namespace) flask_app.register_blueprint(blueprint) with flask_app.test_request_context(): db.init_app(app) db.drop_all() db.create_all() db_seed()
def setupdb(app): # pylint: disable=redefined-outer-name,unused-argument """Prepare the test database before use.""" db.create_all() # Create test database from generated test data for user_data in TEST_DATA: user_filtered = {k: user_data[k] for k in user_data if k != 'inventories'} user = user_store.create_user(**user_filtered) for inventory_data in user_data['inventories']: inventory_filtered = {k: inventory_data[k] for k in inventory_data if k != 'things'} inventory = models.Inventory(user=user, **inventory_filtered) db.session.add(inventory) for thing_data in inventory_data['things']: thing = models.Thing(inventory=inventory, **thing_data) db.session.add(thing) db.session.commit() # Set up test values test_user_id = models.User.query.order_by(models.User.id.desc()).first().id test_inventory_id = models.Inventory.query. \ order_by(models.Inventory.id.desc()).filter_by(user_id=test_user_id).first().id test_values_dict = { 'test_user_id': test_user_id, 'test_alt_user_id': models.User.query.order_by(models.User.id.asc()).first().id, 'test_user_bad_id': db.session.query(db.func.max(models.User.id)).scalar() + 1, 'test_inventory_id': test_inventory_id, 'test_inventory_bad_id': db.session.query(db.func.max(models.Inventory.id)).scalar() + 1, 'test_thing_id': models.Thing.query. order_by(models.Thing.id.desc()). filter_by(inventory_id=test_inventory_id).first().id, 'test_thing_bad_id': db.session.query(db.func.max(models.Thing.id)).scalar() + 1 } test_values = namedtuple('TestData', test_values_dict.keys())(**test_values_dict) yield test_values db.session.remove() db.drop_all()
def setUp(self): """Define test variables and initialize app.""" self.app = app_factory(config.Testing, config.project_name) self.client = self.app.test_client self.company = {"name":"Seller Company", "description":"A selling company", "company_type": "seller"} self.product = {"name":"First Product", "description":"A first product", "price": 10.0, "company_id": 1} self.updated_product = {"name":"Updated Product", "description":"A first product", "price": 10.0, "company_id": 1} self.comparison_product = { "company": { "company_type": "seller", "description": "A selling company", "id": 1, "name": "Seller Company" }, "description": "A first product", "id": 1, "name": "First Product", "price": 10.0 } self.updated_comparison_product = { "company": { "company_type": "seller", "description": "A selling company", "id": 1, "name": "Seller Company" }, "description": "A first product", "id": 1, "name": "Updated Product", "price": 10.0 } # binds the app to the current context with self.app.app_context(): # drop and create all tables db.drop_all() db.create_all() self.client().post('/companies', data=self.company)
def setUp(self): with app.app_context(): db.session.close() db.drop_all() db.create_all() # creates a test client self.app = app.test_client() # propagate the exceptions to the test client self.app.testing = True a1 = User(username="******", password="******") db.session.add(a1) a2 = User(username="******", password="******") db.session.add(a2) a3 = User(username="******", password="******") db.session.add(a3) a4 = User(username="******", password="******") db.session.add(a4) a5 = User(username="******", password="******") db.session.add(a5) db.session.commit()
def _app_and_db(_database_uri, _temp_uploads_folder): app = create_app( TmvConfig( SECRET_KEY="testing_secret_key", SECURITY_PASSWORD_SALT="testing_password_salt", SQLALCHEMY_DATABASE_URI=_database_uri, TEMP_UPLOADS_FOLDER=_temp_uploads_folder, JIRA_FIELD_SPRINT="Sprint", JIRA_FIELD_STORYPOINTS="Story Points", ), config_override=dict( TESTING=True, SECURITY_HASHING_SCHEMES=["hex_md5"], SECURITY_DEPRECATED_HASHING_SCHEMES=[], SECURITY_PASSWORD_HASH="plaintext", # to reduce user creation time ), ) with app.app_context(): print("waiting for DB to be up") MAX_CONNECTION_ATTEMPTS = 5 connected = False last_exc = None for _ in range(MAX_CONNECTION_ATTEMPTS): try: flask_app_db.drop_all() upgrade(revision="head") connected = True except Exception as e: last_exc = e time.sleep(1) else: break if not connected: raise last_exc yield app
from database import db from app import create_app app = create_app() db.init_app(app) app.app_context().push() from models import Strain, Plasmid, Gene db.drop_all(bind=None) db.create_all() # Test strains strain1 = Strain("E. coli", "Andrew", "2019-10-24", "It's hungry", "yes") strain2 = Strain("S. aureus", "Andrew", "2019-10-23", "It's cool", "yes") # Test plasmids plasmid1 = Plasmid("ACTG", "TCTA", "Andrew", "2019-10-24", "some notes", "file.txt", "1,2") plasmid2 = Plasmid("TTCA", "GGTA", "Andrew", "2019-10-24", "some more notes", "file2.txt", "3,4") # Test genes gene1 = Gene("A happy gene", "CCCA", "Andrew", "2019-10-23", "notes here", "file3.txt") gene2 = Gene("A sad gene", "GTCA", "Andrew", "2019-10-23", "even more notes here", "file4.txt") db.session.add_all([strain1, strain2, plasmid1, plasmid2, gene1, gene2]) db.session.commit()
def drop_all(): with request_context(): db.drop_all()
def tearDown(self): db.session.remove() db.drop_all()
def tearDown(self): with app.app_context(): db.drop_all()
def tearDown(self): db.drop_all()
def db(app): _db.create_all() yield _db _db.drop_all()
def drop_db(): db.drop_all()
def create_db(): db.drop_all() create_database()
def drop_db(): """Drop all database""" if prompt_bool( "Are you sure you want to lose all your data"): db.drop_all()
from database import db class User(db.Model): id = db.Column(db.Integer,primary_key=True) username = db.Column(db.String(255), unique=True) age = db.Column(db.Integer) def __init__(self,username,age): self.username = username self.age = age def __repr__(self): return '<User %r>' % self.username if __name__ == '__main__': db.drop_all() db.create_all() user1 = User('ologist', 10) user2 = User('josh', 20) db.session.add(user1) db.session.add(user2) db.session.commit() # user = User.query.filter_by(username='******').first() user = User.query.get(1) print user.username print user.age print User.query.all()
def drop_tables(): db.drop_all() return 'dropped db tables'
def tearDown(self): with app.app_context(): db.session.remove() db.drop_all()