def recreate_db(): try: db.drop_all() except Exception: pass db.create_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_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 setUp(self): self.create_app() db.drop_all() db.create_all() db.session.commit() populate_roles() create_admin_user()
def setUp(self): ''' runs before each test ''' # test_client simulates that the server is running # app defined inside server # tells flask that we are testing app.config['TESTING'] = True # gets the flask test client self.client = app.test_client() # connects to a test database connect_to_db(app, "postgresql:///testdb") # creates tables with sample data db.create_all() example_data() # a mock for session with self.client as c: with c.session_transaction() as sess: sess['user_id'] = 1 sess['difficulty_level'] = "1" sess['name'] = 'teddy' sess['game_id'] = 3
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 setUp(self): server.config['TESTING'] = True server.config['WTF_CSRF_ENABLED'] = False server.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( 'DB_TEST_URI') server.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') db.create_all()
def setUp(self): app.config['TESTING'] = True app.config['CSRF_ENABLED'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(app.root_path, 'test.db') self.app = app.test_client() server.clean_db() db.create_all()
def setUp(self): """Set up a blank temp database before each test""" app.config['TESTING'] = True app.config['CSRF_ENABLED'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, TEST_DB) self.app = app.test_client() db.create_all()
def setUp(self): """Set up prior to every test""" self.client = app.test_client() app.config["TESTING"] = True # Set fake login with self.client as c: with c.session_transaction() as sess: sess['user_id'] = 1 # Connect to test database connect_to_db(app, "postgresql:///testdb") # Create tables if not already created. Delete all entries in tables db.create_all() seed.User_Trail.query.delete() seed.Trip_User.query.delete() seed.Trip_Trail.query.delete() seed.Trip.query.delete() seed.Trail.query.delete() seed.User.query.delete() # Seed sample data into the database, and set the PK id values seed.load_sample_users() seed.load_sample_trails() seed.load_sample_user_trails() seed.load_sample_trips() seed.load_sample_trip_users() seed.load_sample_trip_trails() seed.set_val_user_id() seed.set_val_user_trail_id() seed.set_val_trip_id() seed.set_val_trip_user_id() seed.set_val_trip_trail_id()
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 setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() self.client = self.app.test_client()
def db(app_def): db_.drop_all() db_.create_all() db_.session.commit() return db_
def setUp(self): """Setup testcase.""" self.app = self.create_app().test_client() db.create_all() # create & add test user alex = User(username='******', password='******') db.session.add(alex) db.session.commit()
def setUp(self): app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False dir_path = os.path.dirname(os.path.realpath(__file__)) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join( dir_path, 'test.db') self.app = app.test_client() db.create_all()
def setUp(self): self.app = create_app('config.Test') self.tester_app = self.app.test_client() self._ctx = self.app.test_request_context() self._ctx.push() db.create_all() self.admin_token = self.generate_token(True) self.user_token = self.generate_token(False)
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 setUp(self): logger.info("setting up database : %s"%app.config["SQLALCHEMY_DATABASE_URI"]) # upgrade(revision="head") db.create_all() with self.client: data = {"password" : "admin", "invite" : "invite", "email" : "*****@*****.**"} resp = self.client.post("/api/v1/users", data=data)
def initdb(): db.create_all() db.session.add( User(username="******", email="*****@*****.**", password="******")) db.session.add( User(username="******", email="*****@*****.**", password="******")) db.session.commit() print("Initialized the database")
def setUp(self): """Define test variables and initialize app.""" self.app = app self.client = app.test_client(self) with self.app.app_context(): # create all tables db.create_all()
def setUp(self): """Test Setup.""" app.config['TESTING'] = True app.config['DEBUG'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \ os.path.join(os.path.abspath(os.path.dirname(__file__)), 'test.db') self.app = app.test_client() self.app.secret_key = 1 db.create_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 main(): # process the command line first, then run the setup for the application args = parse_args() config_logging(args) if not os.path.isfile(args.config): logger.error( "The configuration file: {} does not exist. Unable to run.".format( args.config)) # config file validation request, so just run that and exit if args.validate: validate_config(load_config(args.config)) return True else: # run the startup routines, such as config loading, this should # return a configuration if the given arguments are valid configuration = load_config(args.config) # we have a config file, validate the config if not validate_config(configuration): return False # set defaults that are missing set_config_defaults(configuration) mode = "prod" if args.devel: mode = "dev" print(mode) # now create the flask app app = create_app(mode, configuration) from server.models import Servers from server.models import Datatable from server.models import Database from server.models import Aggregate from server.models import Attribute db.app = app db.init_app(app) db.create_all() db.session.commit() # setup services services.init_services(configuration) # finally run the app app.run(host="0.0.0.0", port=int(configuration["general"]["listen_on"]), debug=True, use_reloader=False)
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(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 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): ''' runs before each test ''' # test_client simulates that the server is running # app defined inside server app.config['TESTING'] = True self.client = app.test_client() connect_to_db(app, "postgresql:///testdb") db.create_all() example_data()
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 setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() s = Server('192.168.1.1', 'Some Dev Server', True) db.session.add(s) db.session.commit() self.client = self.app.test_client()
def setup_db(): if not database_exists(SQLALCHEMY_DATABASE_URI): db.create_all() e = Enrolment() e.insert_enrolment() p = Password() p.insert_password() c = Course() c.insert_course()
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 setUp(self): self.db_fd, self.db_filename = tempfile.mkstemp() app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////' + self.db_filename app.config['TESTING'] = True app.testing = True app.config['WTF_CSRF_ENABLED'] = False self.test_client = app.test_client() db.app = app db.init_app(app) with app.app_context(): db.create_all() seed.load_users() seed.load_houses()
def setUp(self): args = { 'username': '******', 'password': '******', 'email': '*****@*****.**' } db.create_all() user = User(args) db.session.add(user) db.session.commit() session['user_id'] = user.id with self.client as c: with c.session_transaction() as sess: sess['user_id'] = user.id
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 setUp(self): app.config['TESTING'] = True # app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://travis@localhost/swe_test' # app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:password@localhost/swe_test' app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://*****:*****@localhost/swe_test' self.app = app.test_client() self.endpoints = [] self.endpoints.append('/games') self.endpoints.append('/games/1') self.endpoints.append('/companies') self.endpoints.append('/companies/1234') self.endpoints.append('/years') self.endpoints.append('/years/1995') self.api_endpoints = ['/api'+x for x in self.endpoints] # Below two added after making api_endpoints because these # are not api endpoints self.endpoints.append('/') self.endpoints.append('/about') db.create_all()
def create_tables(): "Create the tables inside the database" db.create_all()
def build_db(): """Builds db that an idiot dropped.""" db.create_all()
def create_db(): db.create_all()
def setUp(self): db.create_all() user = Client(username=self.testUsername,password=self.testPassword) db.session.add(user) db.session.commit()
def create(default_data=True, sample_data=False): """Creates database tables from sqlalchemy models""" db.create_all() populate(default_data, sample_data)
def setUp(self): app.config['TESTING'] = True app.config['CSRF_ENABLED'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + ':memory:' self.app = app.test_client() db.create_all()
def setUp(self): db.create_all() user = User(email="*****@*****.**", password="******") db.session.add(user) db.session.commit()
def setUp(self): db.create_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 setUp(self): app = app_factory(config.test) app.test_request_context().push() self.app = app self.client = app.test_client() db.create_all()
def init_db(): db.drop_all() db.create_all() print 'db init complete'
def setUp(self): db.create_all() # Don't show logging messages while testing logging.disable(logging.WARNING)
def setUp(self): self.test_phone = '+2567888123456' db.create_all()
def create_db(): """Creates the db tables.""" db.create_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 init_db(): db.create_all() u1 = User(name='mao') u2 = User(name=u'毛哥') db.session.add_all([u1, u2]) db.session.commit()
# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # #!/usr/bin/env python from server import app, db if __name__ == "__main__": # print app # print app.config['SQLALCHEMY_DATABASE_URI'] app.debug = True db.create_all(app=app) app.run(host='0.0.0.0',port=5002, debug=True) # if __name__ == "__main__": # from cherrypy import wsgiserver # # db.create_all(app=app) # # app.run(host='0.0.0.0',port=5000, debug=True) # d = wsgiserver.WSGIPathInfoDispatcher({'/': app}) # server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 5001), d) # try: # server.start() # except KeyboardInterrupt: # server.stop()