Exemple #1
0
 def setUp(self):
     self.db_fd, server.app.config['DATABASE'] = tempfile.mkstemp()
     db_conf = "sqlite:///{}".format(self.db_file)
     server.app.config['SQLALCHEMY_DATABASE_URI'] = db_conf
     server.app.config['TESTING'] = True
     self.app = server.app.test_client()
     server.init_db()
Exemple #2
0
 def setUp(self):
     self.db_fd, server.app.config["DATABASE"] = tempfile.mkstemp()
     db_conf = "sqlite:///{}".format(self.db_file)
     server.app.config["SQLALCHEMY_DATABASE_URI"] = db_conf
     server.app.config["TESTING"] = True
     self.app = server.app.test_client()
     server.init_db()
Exemple #3
0
 def setUp(self):
     """ Runs before each test """
     server.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 = server.app.test_client()
Exemple #4
0
 def setUp(self):
     # Create and initialize a temporary database using the tempfile module since SQLite3 is a file-based system.
     self.db_fd, server.app.config['DATABASE'] = tempfile.mkstemp()
     # Disables error catching during request handling to get better error reports when making test requests.
     server.app.config['TESTING'] = True
     self.app = server.app.test_client()
     with server.app.app_context():
         server.init_db()
Exemple #5
0
 def setUp(self):
     self.app = server.app
     with self.app.app_context():
         server.app.config['TESTING'] = True
         self.context_app = current_app.test_client()
         try:
             server.init_db()
         except:
             pass
def client():
    db_fd, server.app.config['DATABASE'] = tempfile.mkstemp()
    server.app.config['TESTING'] = True
    client = server.app.test_client()

    with server.app.app_context():
        server.init_db()

    yield client
    os.close(db_fd)
    os.unlink(server.app.config['DATABASE'])
Exemple #7
0
def create_app(config_path):
	global app, conf, database
	conf = ConfigParser.ConfigParser()
	conf.read([config_path])	

	app =  Flask(__name__, static_folder = conf.get('flask', 'static_folder'), template_folder=conf.get('jinja','template_path'))
	app.config['DATABASE'] = dict(conf.items('database'))
	database = Database(app)
	import server 
	server.init_db()
	#server.load_db()
	#print "load_db"
	return app
Exemple #8
0
    def setUp(self):
        """ Runs before each test """
        server.init_db()
        db.drop_all()    # clean up the last tests
        db.create_all()  # create new tables
        date = datetime.now()

        Item(order_id=1, product_id=1, name='hammer', quantity=1, price=11.50).save()
        Item(order_id=1, product_id=2, name='toilet paper', quantity=2, price=2.50).save()
        Item(order_id=2, product_id=3, name='beer', quantity=2, price=10.50).save()
        order = Order(customer_id=1, date=date, shipped=True).save()
        order = Order(customer_id=2, date=date, shipped=True).save()
        self.app = server.app.test_client()
Exemple #9
0
 def setUp(self):
     self.app = server.app.test_client()
     server.initialize_logging(logging.CRITICAL)
     server.init_db()
     server.data_reset()
     server.data_load({
         "name": "fido",
         "category": "dog",
         "available": True
     })
     server.data_load({
         "name": "kitty",
         "category": "cat",
         "available": True
     })
Exemple #10
0
    def setUp(self):
        """ Runs before each test """
        server.init_db()
        db.create_all()  # create new tables

        item = Item(wishlist_id=1,
                    product_id=1,
                    name='toothpaste',
                    description='I need a toothpaste').save()
        item = Item(wishlist_id=1,
                    product_id=2,
                    name='toilet paper',
                    description='I need a toilet paper').save()
        item = Item(wishlist_id=2,
                    product_id=3,
                    name='beer',
                    description='I need a drink').save()
        wishlist = Wishlist(customer_id=1, wishlist_name='grocery').save()
        wishlist = Wishlist(customer_id=2, wishlist_name='beverage').save()
        self.app = server.app.test_client()
def test_init_db():
    from server import init_db
    answer1, answer2 = init_db()
    expected1 = [{
        'patient_id':
        120,
        'attending_username':
        '******',
        'patient_age':
        23,
        'heart_rate_history': [{
            'heart_rate': 101,
            'status': 'tachycardic',
            'timestamp': '2018-03-09 11:00:36'
        }, {
            'heart_rate': 104,
            'status': 'tachycardic',
            'timestamp': '2018-03-10 11:00:36'
        }]
    }, {
        'patient_id':
        300,
        'attending_username':
        '******',
        'patient_age':
        25,
        'heart_rate_history': [{
            'heart_rate': 75,
            'status': 'not tachycardic',
            'timestamp': '2019-10-10 11:00:36'
        }]
    }, {
        'patient_id': 500,
        'attending_username': '******',
        'patient_age': 29,
        'heart_rate_history': []
    }, {
        'patient_id': 250,
        'attending_username': '******',
        'patient_age': 20,
        'heart_rate_history': []
    }]
    expected2 = [{
        'attending_username': '******',
        'attending_email': '*****@*****.**',
        'attending_phone': '919-865-5674'
    }, {
        'attending_username': '******',
        'attending_email': '*****@*****.**',
        'attending_phone': '919-222-333'
    }]
    assert expected1 == answer1
    assert expected2 == answer2
Exemple #12
0
    def test_no_access_token(self):
        self.app = server.app.test_client()
        server.init_db()

        rv = self.app.get('/')
        assert 'Please log in through Dropbox.' in rv.data
        assert 'Feel free to try out the text editor.' in rv.data

        rv = self.app.get('/home', follow_redirects=True)
        assert 'Please log in through Dropbox.' in rv.data
        assert 'Feel free to try out the text editor.' in rv.data

        # without cookie
        rv = self.app.get('/dropbox-auth-finish', follow_redirects=False)
        assert '403 Forbidden' in rv.data

        rv = self.app.get('/dropbox-auth-start', follow_redirects=False)
        assert 'You should be redirected automatically to target URL: <a href="https://www.dropbox.com/' in rv.data

        # with cookie
        rv = self.app.get('/dropbox-auth-finish', follow_redirects=False)
        assert '400 Bad Request' in rv.data

        rv = self.app.get('/lists')
        assert 'You are not currently logged in through Dropbox.' in rv.data

        rv = self.app.get('/view_note/')
        assert '404 Not Found' in rv.data

        rv = self.app.get('/view_note/asdf')
        assert 'You are not currently logged in through Dropbox.' in rv.data
        
        rv = self.app.get('/dropbox-auth-finish', follow_redirects=False)
        assert '400 Bad Request' in rv.data

        rv = self.app.post('/save')
        assert 'You are not currently logged in through Dropbox.' in rv.data

        rv = self.logout()
        assert 'Please log in through Dropbox.' in rv.data
Exemple #13
0
 def setUp(self):
     self.db_fd, server.app.config['DATABASE'] = tempfile.mkstemp()
     server.app.testing = True
     self.app = server.app.test_client()
     with server.app.app_context():
         server.init_db()
Exemple #14
0
parser.add_argument("-u",
                    "--upgrade",
                    help="Import a old database",
                    default="")
parser.add_argument("--importcsv",
                    help="Import a CSV file for students",
                    default="")
parser.add_argument("--export", type=str, help="Export to file", default="")

program_args = parser.parse_args()

if program_args.init:
    print("Cleaning database")
    clean_db()
    print("Init tables")
    init_db()

if program_args.locations:
    print("Refreshing locations")
    init_location()

if program_args.export:
    from models_helpers import export_all_data_in_csv
    export_all_data_in_csv(program_args.export)
    print("Les données ont été exportées")
    exit(0)

if program_args.upgrade:
    from models_helpers import import_legacy_db
    import_legacy_db(program_args.upgrade)
    print("La base de données a été importée")
Exemple #15
0
 def setUp(self):
   self.client = server.app.test_client()
   self.order = 1
   server.init_db()
Exemple #16
0
    def test_with_access_token(self):
        with server.app.test_client() as self.app:
            with self.app.session_transaction() as sess:
                sess['uid'] = TEST_UID
                sess['real_name'] = TEST_REAL_NAME
            server.init_db()
            with server.app.app_context():
                self.login()

            rv = self.app.get('/')
            assert 'Welcome _Note Test' in rv.data
            assert 'Please log in through Dropbox.' not in rv.data

            rv = self.app.get('/home')
            assert 'ng-app="mainApp"' in rv.data

            rv = self.app.get('/dropbox-auth-start', follow_redirects=False)
            assert 'You should be redirected automatically to target URL: <a href="https://www.dropbox.com/' in rv.data

            rv = self.app.get('/dropbox-auth-finish', follow_redirects=False)
            assert '400 Bad Request' in rv.data

            rv = self.app.get('/lists')
            response = json.loads(rv.data)
            assert response['success']
            assert 'note_titles' in response

            rv = self.app.get('/view_note/')
            assert '404 Not Found' in rv.data

            rv = self.app.get('/view_note/testing')
            response = json.loads(rv.data)
            note = json.loads(response['note'])
            assert response['success']
            assert 'This is a note.' in note['content']
            assert 'testing' in note['title']

            rv = self.app.get('/view_note/this_note_does_not_exist')
            response = json.loads(rv.data)
            assert not response['success']
            assert 'msg' in response

            data = dict(
                overwrite=False,
                note=dict(content='test content', title='test title')
            )

            # valid save
            rv = self.app.post('/save', data=json.dumps(data), content_type='application/json')
            response = json.loads(rv.data)
            assert response['success']
            assert response['msg'] == 'Your note was saved successfully.'

            # save without title
            data['note']['title'] = ''
            rv = self.app.post('/save', data=json.dumps(data), content_type='application/json')
            response = json.loads(rv.data)
            assert not response['success']
            assert response['msg'] == 'The title is missing.'

            # save with invalid title
            data['note']['title'] = 'inv@lid t!tle'
            rv = self.app.post('/save', data=json.dumps(data), content_type='application/json')
            response = json.loads(rv.data)
            assert not response['success']
            assert response['msg'] == 'Allowed characters in the title: A-Z, a-z, 0-9, -, _'

            # save with missing overwrite parameter
            data['note']['title'] = 'valid title'
            del data['overwrite']
            rv = self.app.post('/save', data=json.dumps(data), content_type='application/json')
            response = json.loads(rv.data)
            assert not response['success']
            assert response['msg'] == 'An error occurred while processing the note.'

            # save with invalid json
            data['note']['title'] = 'valid title'
            data['overwrite'] = False
            rv = self.app.post('/save', data=json.dumps(data)+'{abc}', content_type='application/json')
            response = json.loads(rv.data)
            assert not response['success']
            assert response['msg'] == 'Unable to process data.'

            rv = self.logout()
            assert 'Please log in through Dropbox.' in rv.data
Exemple #17
0
from server import init_db
check = raw_input('are you sure you want to delete the database? [Y/n] ')
if check == 'Y':
	init_db('database.db','objectSchema.sql')
	print 'database cleared'
Exemple #18
0
def configure_options(*args):
    if 'create-db' in args:
        init_db()

    if 'with-fixtures' in args:
        fixtures()
Exemple #19
0
 def setUp(self):
     self.app = server.app.test_client()
     server.init_db()
     server.data_reset()
     server.Customer(1, 'happy', [1, 2]).save()
     server.Customer(1, 'sad', [3]).save()
Exemple #20
0
from server import init_db
check = raw_input('are you sure you want to delete the database? [Y/n] ')
if check == 'Y':
    init_db('database.db', 'objectSchema.sql')
    print 'database cleared'
Exemple #21
0
def make_temp_db():

    init_db()

    test_data1 = "ecgimage1b64str"
    test_data2 = "ecgimage2b64str"
    test_data3 = "ecgimage3b64str"
    test_data4 = "ecgimage4b64str"

    medical_image1 = "medicalimage1b64str"
    medical_image2 = "medicalimage2b64str"

    ECG1 = [{
        "filename": "test_data1.jpg",
        "heart rate": 200,
        "ECG image": test_data1,
        "time": "2020-10-10"
    }]
    ECG2 = [{
        "filename": "test_data1.jpg",
        "heart rate": 200,
        "ECG image": test_data1,
        "time": "2020-10-10"
    }, {
        "filename": "test_data2.jpg",
        "heart rate": 210,
        "ECG image": test_data2,
        "time": "2020-11-11"
    }]
    ECG3 = [{
        "filename": "test_data1.jpg",
        "heart rate": 200,
        "ECG image": test_data1,
        "time": "2020-10-10"
    }, {
        "filename": "test_data2.jpg",
        "heart rate": 210,
        "ECG image": test_data2,
        "time": "2020-11-11"
    }, {
        "filename": "test_data3.jpg",
        "heart rate": 220,
        "ECG image": test_data3,
        "time": "2020-12-12"
    }]
    ECG4 = [{
        "filename": "test_data1.jpg",
        "heart rate": 200,
        "ECG image": test_data1,
        "time": "2020-10-10"
    }, {
        "filename": "test_data2.jpg",
        "heart rate": 210,
        "ECG image": test_data2,
        "time": "2020-11-11"
    }, {
        "filename": "test_data3.jpg",
        "heart rate": 220,
        "ECG image": test_data3,
        "time": "2020-12-12"
    }, {
        "filename": "test_data4.jpg",
        "heart rate": 230,
        "ECG image": test_data4,
        "time": "2020-13-13"
    }]

    medical1 = [{"filename": "meet doctor.jpg", "image": medical_image1}]
    medical2 = [{
        "filename": "meet doctor.jpg",
        "image": medical_image1
    }, {
        "filename": "go hospital.png",
        "image": medical_image2
    }]

    global patient1
    patient1 = Patient(MRI=1000,
                       name="patient1",
                       ECG_record=ECG1,
                       medical_image=medical1)

    global patient2
    patient2 = Patient(MRI=1100,
                       name='patient2',
                       ECG_record=ECG2,
                       medical_image=medical2)

    global patient3
    patient3 = Patient(MRI=1200,
                       name='patient3',
                       ECG_record=ECG3,
                       medical_image=medical1)

    global patient4
    patient4 = Patient(MRI=1300,
                       name="patient4",
                       ECG_record=ECG4,
                       medical_image=medical2)
Exemple #22
0
 def setUp(self):
     self.db_fd, server.app.config['DATABASE'] = tempfile.mkstemp()
     server.app.config['TESTING'] = True
     self.app = server.app.test_client()
     server.init_db()
Exemple #23
0
def init():
	if __name__ != "__main__":
		return "ERROR: Must start from terminal."
	print("Initializes the server config and database.")
	reset = False
	conf = config_file_ok()
	if conf:
		inp = input("Config file looks ok. Do you want to reset it (y/n)?")
		reset = inp == "y"
		if reset:
			print("Will create a new config file.")
	if reset or not conf:
		# db = input("Database name: ")
		# if not db:
		# 	print("No database name. Aborting...")
		# 	return None
		secret_key = input("Super secret key: ")
		if not secret_key:
			print("Need a secret key. Aborting...")
			return
		with open("server_config.py", "w") as f:
			f.write("from os import path\n")
			f.write("DEBUG = True\n")
			f.write("SECRET_KEY = '{}'\n".format(secret_key))
			f.write("DATABASE = path.join('db', 'database.db')")

	if path.isdir("db") and path.exists(path.join("db", "database.db")):
		print("A database already exists.")
		print("1. Reset current database.")
		print("2. Transfer data to new database.")
		print("3. Keep old database.")
		inp = input("Action (1,2,3): ")
		# inp = input("A database already exists. Do you want to reset current database? (y/n) ")
		# if inp != "y":
		# 	print("Database was not reseted.")
		# 	return None
		if inp == "2":
			pass
		elif inp != "1":
			print("Old database keeped.")
			return None
	print("Will initialize a new database.")
	print("You will need an admin account.")
	username = input("Username: "******"Password: "******"Retype password: "******"Error! Username or password is empty. Aborting...")
	else:
		if not path.isdir("db"):
			makedirs("db")
		with open(path.join("db", "database.db"), "w") as f:
			pass
		from server import init_db, hash_password, connect_db
		init_db()
		db = connect_db()
		try:
			r = db.execute("insert into User values (?,?,?)", [username, hash_password(password), True])
			# db.execute("insert into Beer_type values (?)", ["Ingen"])
			db.commit()
			print("Database was successfully created.")
		except Exception as e:
			print("Database not created, error.")
			print(e)
			pass
		finally:
			if db:
				db.close()
Exemple #24
0
#!/usr/bin/env python

from server import init_db

init_db()