コード例 #1
0
def recreate_db():
    try:
        db.drop_all()
    except Exception:
        pass

    db.create_all()
コード例 #2
0
ファイル: base.py プロジェクト: satwikkansal/jogging_times
 def setUp(self):
     self.create_app()
     db.drop_all()
     db.create_all()
     db.session.commit()
     populate_roles()
     create_admin_user()
コード例 #3
0
    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}}
        ]
コード例 #4
0
ファイル: conftest.py プロジェクト: starpogi/fr_telemetry
def test_db():
    db.create_all()

    yield db

    db.session.rollback()
    db.drop_all()
コード例 #5
0
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()
コード例 #6
0
 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()
コード例 #7
0
 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()
コード例 #8
0
def db(app_def):
    db_.drop_all()
    db_.create_all()

    db_.session.commit()

    return db_
コード例 #9
0
 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()
コード例 #10
0
ファイル: manage.py プロジェクト: vinayakvinay/flask-lite
def reset_db():
    """
    Recreates a local database. You probably should not use this on
    production.
    """
    db.drop_all()
    db.create_all()
    db.session.commit()
コード例 #11
0
    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()
コード例 #12
0
ファイル: database_test.py プロジェクト: mhk8/ticket-and-game
 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()
コード例 #13
0
    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()
コード例 #14
0
 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()
コード例 #15
0
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()
コード例 #16
0
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.')
コード例 #17
0
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()
コード例 #18
0
    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()
コード例 #19
0
ファイル: conftest.py プロジェクト: texx00/sandypi
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)
コード例 #20
0
ファイル: setup.py プロジェクト: BenDoan/SPA
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)
コード例 #21
0
    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()
コード例 #22
0
ファイル: conftest.py プロジェクト: gtaschuk/SempoBlockchain
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()
コード例 #23
0
    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()
コード例 #24
0
    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()
コード例 #25
0
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
コード例 #26
0
    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()
コード例 #27
0
ファイル: signup_test.py プロジェクト: mhk8/ticket-and-game
    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
            }
        }]
コード例 #28
0
    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",
            },
        ]
コード例 #29
0
ファイル: conftest.py プロジェクト: starpogi/fr_telemetry
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()
コード例 #30
0
ファイル: manage.py プロジェクト: Andrew47/jobber
def clean_db():
    """Drops the db tables."""
    db.drop_all()
コード例 #31
0
ファイル: db_setup.py プロジェクト: lobsterrolldb/cs373-idb
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
コード例 #32
0
ファイル: manager.py プロジェクト: fengjincao/shopCart
def drop():
    "Drops database tables"
    if prompt_bool("Are you sure you want to lose all your data"):
        db.drop_all()
コード例 #33
0
ファイル: setup.py プロジェクト: bam-omaha/CodeOne2015
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)
コード例 #34
0
ファイル: base.py プロジェクト: topogram/weibo-miner-server
 def tearDown(self):
     logger.info("downgrading database")
     # downgrade(revision="base")
     db.session.remove()
     db.drop_all()
コード例 #35
0
ファイル: tests.py プロジェクト: gsathya/centinel-server
 def tearDown(self):
     db.session.remove()
     db.drop_all()
コード例 #36
0
ファイル: test_api.py プロジェクト: andela-akiura/bucketlist
 def tearDown(self):
     """Clean up."""
     db.session.remove()
     db.drop_all()
コード例 #37
0
 def tearDown(self):
     logging.disable(logging.NOTSET)
     db.session.remove()
     db.drop_all()
コード例 #38
0
ファイル: db.py プロジェクト: mikew/brunch-flask
def drop():
    """Drops database tables"""
    if prompt_bool('Are you sure you want to lose all your data'):
        db.drop_all()
コード例 #39
0
ファイル: manage.py プロジェクト: lhang/BookCan_V2
def init_db():
    db.drop_all()
    db.create_all()
    print 'db init complete'
 def tearDown(self):
     db.session.remove()
     db.drop_all()
コード例 #41
0
ファイル: app.py プロジェクト: CamelBackNotation/cs373-idb
def drop_db():
	db.drop_all()
コード例 #42
0
def drop_db():
    """Drops the db tables."""
    db.drop_all()
コード例 #43
0
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 = [
コード例 #44
0
ファイル: tests.py プロジェクト: Nerevarsoul/bookmark
 def tearDown(self):
 	"""Destroy blank temp database after each test"""
     db.session.remove()
     db.drop_all()
コード例 #45
0
ファイル: manage.py プロジェクト: ykrsm/jjh
def recreate_db():
    """Recreates a database."""
    db.drop_all()
    db.create_all()
    db.session.commit()
コード例 #46
0
ファイル: manage.py プロジェクト: uems/segue-api
def drop_all():
  "Drops all data (USE WITH CAUTION)"
  db.drop_all()