def recreate_db(): try: db.drop_all() except Exception: pass db.create_all()
def setUp(self): self.create_app() db.drop_all() db.create_all() db.session.commit() populate_roles() create_admin_user()
def setUp(self): config = Config() config.SQLALCHEMY_DATABASE_URI = "sqlite:///:memory:" self.app = create_app(config) self.client = self.app.test_client() with self.app.app_context(): db.drop_all() db.create_all() db.session.commit() self.success_test_bad_post = [{KEY_EXPECTED: {"error": "Malformed request"}}] self.success_test_bad_username_pwd = [ { KEY_INPUT: "bad username", KEY_EXPECTED: { KEY_SUCCESS: False, KEY_MESSAGE: "Username does not exist or password is invalid.", }, }, { KEY_INPUT: "bad password", KEY_EXPECTED: { KEY_SUCCESS: False, KEY_MESSAGE: "Username does not exist or password is invalid.", }, }, ] self.success_test_valid_pwd = [ {KEY_EXPECTED: {KEY_SUCCESS: True, KEY_USER_ID: 1}} ]
def test_db(): db.create_all() yield db db.session.rollback() db.drop_all()
def db(app): def create_user(username, password, admin=False): return User(public_id=str(uuid.uuid4()), name=username, password_hash=generate_password_hash(password), admin=admin) def create_todo(text, user, complete=False): return Todo(text=text, complete=complete, user=user) if os.path.exists(app.config['DB_PATH']): os.unlink(app.config['DB_PATH']) with app.app_context(): _db.init_app(app) _db.create_all() admin_user = create_user("Admin", "password", admin=True) regular_user = create_user("User", "snowman") promotable_user = create_user("Promotable User", "greenman") _db.session.add(admin_user) _db.session.add(regular_user) _db.session.add(promotable_user) incomplete_todo = create_todo("Incomplete", regular_user) complete_todo = create_todo("Complete", regular_user, complete=True) _db.session.add(incomplete_todo) _db.session.add(complete_todo) _db.session.commit() yield _db _db.drop_all()
def tearDown(self): # If I drop DB before any asynchronous tasks are completed, # it will cause error. How to smoothly resolve this problem? # currently, I make sure each test containing celery task # to be completed before calling tearDown. db.drop_all() self.ctx.pop()
def tearDown(self): "Tear down User API test fixtures" print('### Tearing down the flask server ###') with app.app_context(): # drop all tables db.session.remove() db.drop_all()
def db(app_def): db_.drop_all() db_.create_all() db_.session.commit() return db_
def setUp(self): app.config['TESTING'] = True app.config['DEBUG'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db/' + TEST_DB self.app = app.test_client() db.drop_all() db.create_all()
def reset_db(): """ Recreates a local database. You probably should not use this on production. """ db.drop_all() db.create_all() db.session.commit()
def test_integrity_error_returns_500(self): with mock.patch('server.db.session.commit') as db_mock: db_mock.side_effect = IntegrityError(None, None, None, None) r = self.app.post(self.endpoints['responses'], data=test_message) self.assertEqual(r.status_code, 500) db.session.remove() db.drop_all()
def setUp(self): config = Config() config.SQLALCHEMY_DATABASE_URI = "sqlite:///:memory:" self.app = create_app(config) self.client = self.app.test_client() with self.app.app_context(): db.drop_all() db.create_all() db.session.commit()
def setUp(self): self.app = create_app() self.ctx = self.app.app_context() self.ctx.push() db.drop_all() # just in case db.create_all() self.client = self.app.test_client()
def setUp(self): # Only log criticl errors app.debug = True app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.CRITICAL) # Set up the test database app.config['SQLALCHEMY_DATABASE_URI'] = get_database_uri() db.drop_all() # clean up the last tests db.create_all() # make our sqlalchemy tables self.app = app.test_client()
def initdb(): db.drop_all() db.create_all() admin_user = User.new( username=app.config.get('ADMIN_USERNAME'), password='******', name=u'admin') db.session.add(admin_user) db.session.commit()
def initdb(drop): """Initialize the database.""" if drop: click.confirm( 'This operation will delete the database, do you want to continue?', abort=True) db.drop_all() click.echo('Drop tables.') db.create_all() click.echo('Initialized database.')
def init_database(): # Create the database and the database table with current_app.app_context(): db.create_all() # todo- use manage.py yield db # this is where the testing happens! with current_app.app_context(): db.session.close_all( ) # DO NOT DELETE THIS LINE. We need to close sessions before dropping tables. db.drop_all()
def setUp(self): """Define test variables and initialize app.""" self.app = create_app(config_name="testing") self.client = self.app.test_client self.bucketlist = {'name': 'Go to Borabora for vacay'} # binds the app to the current context with self.app.app_context(): # create all tables db.session.close() db.drop_all() db.create_all()
def client(): db_fd, db_fu = tempfile.mkstemp() server.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' server.app.config['TESTING'] = True with server.app.test_client() as client: with server.app.app_context(): db.create_all() yield client db.drop_all() os.close(db_fd) os.unlink(db_fu)
def main(): print "Creating tables..." db.drop_all() db.create_all() create_user('admin', '*****@*****.**', 'password') create_user('user', '*****@*****.**', 'password') print "Ingesting class data..." insert_class_data('data/uno_class_data.json') print "Ingesting requirements data..." not_found_count = insert_requirements_data('data/ist_requirements.json') print "\nCouldn't find {} courses".format(not_found_count)
def test_get_feedback_id_returns_valid_id_and_200(self): """Posts a valid feedback and calls a feedback end point GET to check stored tx_id""" expected_id = self.feedback_decrypted_json['tx_id'] self.app.post(self.endpoints['responses'], data=feedback_decrypted, content_type='application/json') r = self.app.get(self.endpoints['feedback'] + '/' + '1') i = json.loads(r.data).get('tx_id') self.assertEqual(i, expected_id) self.assertEqual(r.status_code, 200) db.session.remove() db.drop_all()
def init_database(): # Create the database and the database table with current_app.app_context(): db.create_all() yield db # this is where the testing happens! with current_app.app_context(): try: db.session.execute('DROP MATERIALIZED VIEW IF EXISTS search_view;') db.session.commit() except: pass db.session.remove() # DO NOT DELETE THIS LINE. We need to close sessions before dropping tables. db.drop_all()
def test_get_responses_per_page(self): self.app.post(self.endpoints['responses'], data=second_test_message, content_type='application/json') self.app.post(self.endpoints['responses'], data=test_message, content_type='application/json') r = self.app.get(self.endpoints['responses'] + '?per_page=1') page_count = len(json.loads(r.data.decode('utf8'))) total_count = json.loads(r.data.decode('utf8')) self.assertEqual(page_count, 1) self.assertGreaterEqual(len(total_count), page_count) db.session.remove() db.drop_all()
def setUp(self): db.drop_all() db.create_all() # administrator u = User(username='******', email='*****@*****.**', password='******') db.session.add(u) db.session.commit() # add empty component prototype c = ComponentPrototype(name='None', introduction='This is the empty component') db.session.add(c) db.session.commit() # add testing component prototype pro = ComponentPrototype(name='Promotor', introduction='I\'m Promotor') rbs = ComponentPrototype(name='RBS', introduction='I\'m RBS') db.session.add_all([pro, rbs]) db.session.commit()
def init(slient=False): with app.app_context(): # re-create the database if not slient: print bcolors.HEADER+'Destroying previous database ...', db.drop_all() if not slient: print bcolors.OKGREEN+'OK'+bcolors.HEADER+'\nCreating empty database ...', db.create_all() # administrator if not slient: print bcolors.OKGREEN+'OK'+bcolors.HEADER+'\nCreating Administrator ...', u = User(username='******', email='*****@*****.**', password='******') db.session.add(u) db.session.commit() # add empty component prototype if not slient: print bcolors.OKGREEN+'OK'+bcolors.HEADER+'\nCreating None prototype ...', c = ComponentPrototype(name='None', introduction='This is the empty component') db.session.add(c) db.session.commit() # add upload file directory if not slient: print bcolors.OKGREEN+'OK'+bcolors.HEADER+'\nCreating upload file directory ...', import os if not os.path.isdir(app.config['UPLOAD_FOLDER_FULL']): os.makedirs(app.config['UPLOAD_FOLDER_FULL']) # default tracks if not slient: print bcolors.OKGREEN+'OK'+bcolors.HEADER+'\nCreating default tracks ...', from server.models import Track track_names = ['artanddesign', 'communitylabs', 'energy', 'environment', 'foodandnutrition', 'foundationaladvance', 'healthandmedicine', 'informationprocessing', 'manufacturing', 'measurement', 'newapplication', 'policyandpractices', 'software'] track_descriptions = ['Art & Design', 'Community Labs', 'Energy', 'Environment', 'Food & Nutrition', 'Foundational Advance', 'Health & Medicine', 'Information Processing', 'Manufacturing', 'Measurement', 'New Application', 'Policy & Practices', 'Software'] for n, d in zip(track_names, track_descriptions): db.session.add(Track(name=n, description=d)) db.session.commit() print bcolors.OKGREEN+'OK'+'\nInit done.'+bcolors.ENDC
def test_get_valid_id_returns_id_and_200(self): expected_id = self.test_message_json['tx_id'] response_size_original = len(self.test_message_sorted) response_hash_original = hashlib.md5( self.test_message_sorted.encode('utf-8')).hexdigest() self.app.post(self.endpoints['responses'], data=test_message, content_type='application/json') r = self.app.get(self.endpoints['responses'] + '/' + expected_id) self.assertEqual(r.data, self.test_message_sorted.encode('utf-8')) self.assertEqual(r.status_code, 200) self.assertEqual(r.headers['Content-MD5'], response_hash_original) self.assertEqual(r.headers['Content-Length'], str(response_size_original)) db.session.remove() db.drop_all()
def setUp(self): config = Config() config.SQLALCHEMY_DATABASE_URI = "sqlite:///:memory:" self.app = create_app(config) self.client = self.app.test_client() with self.app.app_context(): db.drop_all() db.create_all() db.session.commit() self.success_test_params_error = [ { KEY_INPUT: "same email", KEY_EXPECTED: { KEY_SUCCESS: False, KEY_MESSAGE: "Another account seems to be using the same email.", }, }, { KEY_INPUT: "same username", KEY_EXPECTED: { KEY_SUCCESS: False, KEY_MESSAGE: "Username has already been taken please try another username", }, }, ] self.success_test_data_error = [{ KEY_EXPECTED: { "error": "Malformed request" } }] self.success_test_params = [{ KEY_EXPECTED: { "success": True, "user_id": None } }]
def setUp(self): db.drop_all() db.create_all() db.session.commit() self.client = app.test_client() self.success_test_params_user = [ { KEY_INPUT: json.dumps({"token": "google_oauth_token"}), }, ] self.fail_test_params_user = [ { KEY_INPUT: json.dumps({"token": "google_oauth_token"}), KEY_EXPECTED: "Invalid Value", }, { KEY_INPUT: "{bad_json_string}", KEY_EXPECTED: "Malformed request", }, ]
def test_api_db(): db.create_all() db.session.add(LocationEvent(robot="Bender", x=0, y=0, timestamp=0)) db.session.add(LocationEvent(robot="Bender", x=1, y=0, timestamp=1)) new_event = LocationEvent(robot="Bender", x=0, y=0, timestamp=2) db.session.add(new_event) db.session.flush() new_robot = Robot(name="Bender", last_x=0.0, last_y=0.0, last_event_id=new_event.id, odometer=2.0) db.session.add(new_robot) db.session.commit() yield db db.session.rollback() db.drop_all()
def clean_db(): """Drops the db tables.""" db.drop_all()
def db_import(): global year_cache global header db.drop_all() db.configure_mappers() db.create_all() game_cache = [g.game_id for g in Game.query.all()] platform_cache = [] # GAME DATA PULLING # data: id, name, release_date url = "https://www.igdb.com/api/v1/games" r = requests.get(url, params = header) j = r.json() # while len(j["games"]) > 0: while header["offset"] < 100: # pp = pprint.PrettyPrinter(indent = 4) # pp.pprint(j) games = j["games"] # loop through games for game in games: game_id = game["id"] if(game_id not in game_cache): game_cache += [game_id] name = game["name"] release_year = int((re.split("-", game["release_date"]))[0]) #check year cache before adding a new year if(release_year not in year_cache): y = Year(release_year) db.session.add(y) year_cache += [release_year] url_specific_game = "https://www.igdb.com/api/v1/games/" + str(game_id) r = requests.get(url_specific_game, params = header) #get specific game information game_info = r.json()["game"] #image image_url = None if("cover" in game_info and "url" in game_info["cover"]): image_url = "https:" + game_info["cover"]["url"] #rating rating = 0.0 if("rating" in game_info): rating = game_info["rating"] g = Game(id=game_id, name=name, image_url=image_url, rating=rating, release_year=release_year) #loop through platforms for v in game_info["release_dates"]: c = None platform = v["platform_name"] if platform not in platform_cache: platform_cache += [platform] c = Platform(platform) db.session.add(c) else: c = Platform.query.filter_by(platform_name = platform).first() g.associated_platforms.append(c) if "genres" not in game_info: continue add_genres(game_info["genres"], g) add_companies(game_info["companies"], g) #add game db.session.add(g) db.session.commit() r = requests.get(url, params = header) j = r.json() header["offset"] += 25
def drop(): "Drops database tables" if prompt_bool("Are you sure you want to lose all your data"): db.drop_all()
import json import os import server from server import db, create_user, create_transaction, model import csv db.drop_all() db.create_all() admin_user = create_user('admin', '*****@*****.**', 'password', is_admin=True) # Read in checking data count = 0 with open('checkingData.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for description, category_name, amount, date in readCSV: category = model.Category.query.filter_by(title=category_name).first() count += 1 if category is None: category = model.Category(category_name) db.session.add(category) db.session.commit() print(count) print("Adding entry for {} at {}".format(category_name, date)) create_transaction(admin_user, description, amount, category, date) # Read in questions with open("knowledgebase.json") as f: for topic_name, answer in json.load(f).items(): print("Inserting knowledgebase item for", topic_name) knowledge = model.Knowledge(topic_name, answer)
def tearDown(self): logger.info("downgrading database") # downgrade(revision="base") db.session.remove() db.drop_all()
def tearDown(self): db.session.remove() db.drop_all()
def tearDown(self): """Clean up.""" db.session.remove() db.drop_all()
def tearDown(self): logging.disable(logging.NOTSET) db.session.remove() db.drop_all()
def drop(): """Drops database tables""" if prompt_bool('Are you sure you want to lose all your data'): db.drop_all()
def init_db(): db.drop_all() db.create_all() print 'db init complete'
def drop_db(): db.drop_all()
def drop_db(): """Drops the db tables.""" db.drop_all()
from server import db from werkzeug.security import generate_password_hash from models import Persoongegevens, User, Pensioengegevens, Pensioenen db.drop_all() db.create_all() usernames = ["Petertje01", "Mariekdepiek", "Barrydebaas95", "Charlottekapot"] voornaam = ['Peter', 'Marieke', 'Barrie', 'Charlotte'] tussenvoegsel = 'von' achternaam = 'Petermans' telefoonnr = '123123123' geboortedatum = ['12-12-1212', '13-12-1212', '14-12-1212', '15-12-1212'] adres = 'Peterstraat' postcode = '1212QW' provincie = 'Peteria' land = 'Peterland' emailadres = [ '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**' ] bsn = '123123' bruto = 500 partner = "No" pensioen_leeftijd_jaar = [68, 68, 68, 70] pensioen_leeftijd_maand = [0, 1, 6, 11] verwacht_inkomen = [300, 12000, 6000, 1200] verwacht_uitgaven = [800, 5000, 6000, 800] pensioen_ref = [1, 1, 1, 2, 2, 3, 4] pensioen_uitvoerder = [
def tearDown(self): """Destroy blank temp database after each test""" db.session.remove() db.drop_all()
def recreate_db(): """Recreates a database.""" db.drop_all() db.create_all() db.session.commit()
def drop_all(): "Drops all data (USE WITH CAUTION)" db.drop_all()