Exemplo n.º 1
0
def browser():
    client = None
    options = webdriver.ChromeOptions()
    options.add_argument('headless')
    try:
        client = webdriver.Chrome(options=options)
    except Exception:
        pass

    if client:
        app_context = app.app_context()
        app_context.push()

        db_fd, db_path = tempfile.mkstemp()
        db_url = 'sqlite:///' + db_path
        app.config['SQLALCHEMY_DATABASE_URI'] = db_url
        app.config["SQLALCHEMY_ECHO"] = False
        app.config['TESTING'] = True

        server = Process(target=app.run)
        server.start()
        time.sleep(1)
        with app.app_context():
            db.drop_all()
            db.create_all()
            bind_factories(db.session)
        client.get('http://127.0.0.1:5000/')
        # time.sleep(2)
        yield client
        server.terminate()
        client.close()
        os.close(db_fd)
        os.unlink(db_path)
        app_context.pop()
Exemplo n.º 2
0
    def setUpClass(cls):
        app.config[
            'SQLALCHEMY_DATABASE_URI'] = 'postgresql://{user}:{password}@{host}/{database}'.format(
                **config)
        app.app_context().push()
        db.init_app(app)

        cls.app = app.test_client()
Exemplo n.º 3
0
    def test_create_ticket(self):

        with app.app_context():

            title = 'this is the title'
            content = 'this is some content'

            # get data for forms submission
            priority = FlicketPriority.query.first()
            category = FlicketCategory.query.first()

            user = CreateUser()

            self.login(username=user.username, password=user.password)
            _url = url_for('flicket_bp.ticket_create')

            result = self.client.post(_url,
                                      buffered=True,
                                      content_type='multipart/form-data',
                                      data={
                                          'title': title,
                                          'content': content,
                                          'priority': str(priority.id),
                                          'category': str(category.id),
                                          'file[]': '',
                                          'submit': 'Submit'
                                      },
                                      follow_redirects=True)

            self.assertIn(b'new ticket created', result.data.lower())
            self.logout()
Exemplo n.º 4
0
def initDB():
  with app.app_context():
  	db = getDB()
  	with app.open_resource(app.config['SCHEMA'], mode='r') as f:
			db.cursor().executescript(f.read())
			print "Initialized Database."
  	db.commit()
Exemplo n.º 5
0
def UpgradeDB():
    """ Mise à jour de la DB """
    with app.app_context():
        app.logger.info("Migration de la base de donnees...")

        try:
            flask_migrate.migrate(directory=REP_MIGRATIONS)
            app.logger.info("Migrate - Migration ok.")
        except SystemExit as e:
            app.logger.info("SystemQuit -> Erreur dans migration > migrate")
            app.logger.info(traceback.format_exc())
        except Exception, err:
            app.logger.info("Erreur dans migration > migrate.")
            app.logger.info(err)

        app.logger.info("Upgrade de la base de donnees...")
        try:
            flask_migrate.upgrade(directory=REP_MIGRATIONS)
            app.logger.info("Migrate - Upgrade ok.")
        except SystemExit as e:
            app.logger.info("SystemQuit -> Erreur dans migration > upgrade.")
            app.logger.info(traceback.format_exc())
        except Exception, err:
            app.logger.info("Erreur dans migration > upgrade.")
            app.logger.info(err)

            # Si la revision n'existe pas
            if "Can't locate revision" in str(err):
                app.logger.info("Suppression table alembic_version...")
                result = db.session.execute(
                    "DROP TABLE IF EXISTS alembic_version;")
                app.logger.info("Suppression du repertoire migrations...")
                shutil.rmtree(REP_MIGRATIONS)
                flask_migrate.init(directory=REP_MIGRATIONS)
                flask_migrate.migrate()
Exemplo n.º 6
0
def generate_qrcode(inputText):
    with app.app_context():

        img = qrcode.make(inputText)
        img.save('qrcode.png')

        album = None
        image_path = 'qrcode.png'
        clientId = 'F5a0da0ee22b6b9'  # Please get your own ClientId from imgur

        url = "https://api.imgur.com/3/image"
        payload = {'image': open(image_path, 'rb').read(), 'type': 'file'}
        headers = {
            'authorization': 'Client-ID ' + clientId
        }  # notice the space after Client-ID, concat

        response = requests.request(
            "POST", url, data=payload,
            headers=headers)  # post image anonymously to imgur

        # return json.dumps(response.text)

        temp_obj = json.loads(
            response.text)  # json encode response again since it's a string
        app.logger.info(temp_obj)
        responseURL = temp_obj["data"]["link"]

        return responseURL
Exemplo n.º 7
0
    def post_blog(self, db, json):
        with app.app_context():
            blogger = json.get('blogger')
            url = json.get('url')
            title = json.get('title')

            rec = Recommendation()
            blog = Blog(url=url, title=title,
                        blogger=blogger, recommendation=rec)

            db.session.add(rec)
            db.session.add(blog)
            db.session.commit()

            db.session.refresh(rec)

            if json.get('tags'):
                for tag in json.get('tags'):
                    tag_in_database = Tag.query.filter(Tag.name == tag).first()
                    if tag_in_database == None:
                        self.add_tag(self, rec, db, tag)
                    else:
                        self.add_tag_recommendation(
                            self, rec, db, tag_in_database)

            return jsonify(blog.serialize)
Exemplo n.º 8
0
    def test_userGet(self):
        with app.app_context():
            """ 
            Getting the mock data of the by passing the username as a parameter to the get.
            """
            valid_code = routes.UserId().get("James")
            # This form is preferred over getting key value pairs from dict because it makes ID fetching easier.
            valid_user = User.objects().first()
            self.assertEqual(200, valid_code.status_code)
            self.assertEqual(models.ObjectId("6062dabdbbb2c3f109a049e9"),
                             valid_user._id)
            self.assertEqual("James", valid_user.username)
            self.assertEqual("123", valid_user.password)
            """
            Retrieving status code and user data
            """

            invalid_code1 = routes.UserId().get("Sam")
            print(
                f"GetOne - Expecting error message, getting: '{invalid_code1.json['error']}'"
            )
            self.assertEqual(400, invalid_code1.status_code)
            """
            Testing for a user which does not exist
            """
            invalid_code2 = routes.UserId().get("jAmEs")
            print(
                f"GetOne - Expecting error message, getting: '{invalid_code2.json['error']}'"
            )
            self.assertEqual(400, invalid_code2.status_code)
            """
Exemplo n.º 9
0
    def post_book(self, db, json):
        with app.app_context():
            title = json.get('title')
            author = json.get('author')
            isbn = json.get('isbn')
            isRead = 0

            rec = Recommendation()
            book = Book(title=title, author=author, isbn=isbn,
                        isRead=isRead, recommendation=rec)

            db.session.add(rec)
            db.session.add(book)
            db.session.commit()

            db.session.refresh(rec)

            if json.get('tags'):
                for tag in json.get('tags'):
                    tag_in_database = Tag.query.filter(Tag.name == tag).first()
                    if tag_in_database == None:
                        self.add_tag(self, rec, db, tag)
                    else:
                        self.add_tag_recommendation(
                            self, rec, db, tag_in_database)

            return jsonify(book.serialize)
Exemplo n.º 10
0
 def test_cache_control(self):
     with app.app_context():
         response = self.get_response()
         self.assertEqual(response.headers['Cache-Control'],
                          'private, max-age=%s' % 3600)
         self.assertTrue('Expires' in response.headers)
         self.assertTrue('Last-Modified' in response.headers)
Exemplo n.º 11
0
def UpgradeDB():
    """ Mise à jour de la DB """
    with app.app_context():
        app.logger.info("Migration de la base de donnees...")
        try:
            flask_migrate.migrate(directory=REP_MIGRATIONS)
        except Exception, err:
            if "Path doesn't exist" in str(err):
                app.logger.info(
                    "Repertoire Migrations manquant -> Initialisation de flask_migrate maintenant..."
                )
                flask_migrate.init(directory=REP_MIGRATIONS)
                flask_migrate.migrate()

        app.logger.info("Migration ok.")
        app.logger.info("Upgrade de la base de donnees...")
        try:
            flask_migrate.upgrade(directory=REP_MIGRATIONS)
            app.logger.info("Upgrade ok.")
        except Exception, err:
            app.logger.info("Erreur Upgrade.")
            app.logger.info(err)

            # Si la revision n'existe pas
            if "Can't locate revision" in str(err):
                app.logger.info("Suppression table alembic_version...")
                result = db.session.execute(
                    "DROP TABLE IF EXISTS alembic_version;")
                app.logger.info("Suppression du repertoire migrations...")
                shutil.rmtree(REP_MIGRATIONS)
                flask_migrate.init(directory=REP_MIGRATIONS)
                flask_migrate.migrate()
Exemplo n.º 12
0
def nmap():
    with app.app_context():

        info = Monitor.query.all()
        if info is None:
            exit(1)
        ip = ''
        for item in info:
            ip = ip + item.ipaddr + ' '
        nmap = nmap3.NmapHostDiscovery()
        results = nmap.nmap_no_portscan(ip)
        db.session.execute(Monitor.__table__.update(), [{'isok': '0'}])
        db.session.commit()
        if results is None:
            exit(1)
        for i in range(0, len(results['hosts'])):
            ip = results['hosts'][i]['addr']
            status = 1 if results['hosts'][i]['state'] == 'up' else '0'
            mon = Monitor.query.filter_by(ipaddr=ip).first()
            if mon:
                mon.update_time = getCurrentDate()
                mon.isok = status
                db.session.add(mon)
                db.session.execute(MonLog.__table__.insert(),
                                   [{
                                       'mon_id': mon.id,
                                       'update_time': getCurrentDate()
                                   }])
                db.session.commit()
Exemplo n.º 13
0
def CreationDB():
    """ Création de la DB """
    with app.app_context():
        if "mysql" in app.config["SQLALCHEMY_DATABASE_URI"]:

            # Création d'une base MySQL
            app.logger.info(
                "Creation de la base de donnees MySQL si besoin...")
            import sqlalchemy
            temp = app.config["SQLALCHEMY_DATABASE_URI"].split("/")
            url = temp[0] + "//" + temp[2]
            nom_db = temp[3].split("?")[0]
            engine = sqlalchemy.create_engine(url)
            engine.execute("CREATE DATABASE IF NOT EXISTS %s;" % nom_db)
            engine.execute("USE %s;" % nom_db)
            engine.dispose()

        app.logger.info("Creation des tables des donnees...")
        db.create_all()
        app.logger.info("Creation ok.")

        if os.path.isdir(REP_MIGRATIONS):
            app.logger.info("Suppression du repertoire migrations...")
            shutil.rmtree(REP_MIGRATIONS)

        app.logger.info("Initialisation de la migration de sqlalchemy...")
        flask_migrate.init(directory=REP_MIGRATIONS)
        app.logger.info("Initialisation ok.")

    # Mémorisation du numéro de version dans la DB
    m = Parametre(nom="version", parametre=app.config["VERSION_APPLICATION"])
    db.session.add(m)
    db.session.commit()
Exemplo n.º 14
0
def sync_delete(app, datas):
    with app.app_context():
        for data in datas:
            cur_goods = Goods.query.filter_by(goods_id=data.goods_id).first()
            if cur_goods is not None:
                db.session.delete(cur_goods)
                db.session.commit()
Exemplo n.º 15
0
 def test_compare_borrower_bad(self, mock_register_adapter):
     with app.app_context() as ac:
         ac.g.trace_id = None
         with app.test_request_context():
             mock_register_adapter.return_value = ["Alice", "Bob"]
             self.assertRaises(BorrowerNamesDifferException,
                               compare_borrower_names, PAYLOAD)
Exemplo n.º 16
0
def all_tasks():
    from application import app
    with app.app_context():
        task_obj_list = TasksModel.query.filter_by(is_deleted=False,
                                                   status=True).all()

        ret = dict()
        for task_obj in task_obj_list:
            _task_dict = {
                "year": task_obj.year,
                "month": task_obj.month,
                "day": task_obj.day,
                "week": task_obj.week,
                "day_of_week": task_obj.day_of_week,
                "hour": task_obj.hour,
                "minute": task_obj.minute,
                "second": task_obj.second,
            }

            task_dict = {"trigger": task_obj.task_type}
            for k, v in _task_dict.items():
                if v is not None:
                    task_dict[k] = v

            ret[task_obj.task_no] = task_dict

        return ret
Exemplo n.º 17
0
    def test_delete(self):
        response = self.client.post('admin')

        with app.app_context():
            product = db.session.execute(
                'SELECT * FROM products WHERE id=2').fetchone()
            assert product is None
Exemplo n.º 18
0
    def get_book(self, db, book_id):
        with app.app_context():
            book = db.session.query(Book).filter(Book.id == book_id).first()
            if book == None:
                return Response("", status=404)

            return jsonify(book.serialize)
Exemplo n.º 19
0
    def test_create(self):
        assert self.client.get('/admin').status_code == 200
        self.client.post('/admin', data={'title': 'created', 'body': ''})

        with app.app_context():
            count = db.session.execute(
                'SELECT COUNT(id) FROM products').fetchone()[0]
            assert count == 1
Exemplo n.º 20
0
 def test_create_deed_html(self, mock_format):
     deed = DeedModelMock
     mock_format.return_value = 'a house'
     with app.app_context() as ac:
         ac.g.trace_id = None
         with app.test_request_context():
             self.assertTrue('Digital Mortgage Deed' in create_deed_html(deed.deed))
             self.assertTrue('e-MD12344' in create_deed_html(deed.deed))
Exemplo n.º 21
0
    def get_video(self, db, video_id):
        with app.app_context():
            video = db.session.query(Video).filter(
                Video.id == video_id).first()
            if video == None:
                return Response("", status=404)

            return jsonify(video.serialize)
Exemplo n.º 22
0
    def test_auth_sms_deed_not_found(self, mock_get_deed):
        with app.app_context() as ac:
            ac.g.trace_id = None
            with app.test_request_context():
                mock_get_deed.return_value = None

                with self.assertRaises(NotFound):
                    auth_sms("11", "11", "11")
Exemplo n.º 23
0
    def test_calls_decorated_function(self):
        with app.app_context():
            @as_feature_collection
            def stub_function():
                return 'STUB_STRING'

            result = stub_function()

            self.assertEqual('STUB_STRING', result)
Exemplo n.º 24
0
 def test_borrowers_present_bad(self, mock_register_adapter):
     with app.app_context() as ac:
         ac.g.trace_id = None
         with app.test_request_context():
             mock_register_adapter.return_value = [
                 "Jake Bullet", "Jill Beatrix Bullet", "Another Name"
             ]
             self.assertRaises(BorrowerNamesMissingException,
                               all_borrower_names_present, PAYLOAD)
Exemplo n.º 25
0
 def drop_table(cls):
     if ORM == 'peewee':
         cls.model.drop_table(True)
     elif ORM == 'sql-alchemy':
         with app.app_context():
             db.session.remove()
             db.drop_all()
     elif ORM == 'mongo_engine':
         cls.model.drop_collection()
Exemplo n.º 26
0
    def setUp(self):
        app.config.from_object('config.TestingConfig')
        self.client = app.test_client()

        db.init_app(app)
        with app.app_context():
            db.create_all()
            user_datastore.create_user(email='test', password=encrypt_password('test'))
            db.session.commit()
Exemplo n.º 27
0
 def test_auth_sms_no_esec_id(self, mock_get_deed, mock_get_borrower, mock_convert_json, mock_borrower_pos,
                              mock_akuma):
     mock_get_borrower.return_value = BorrowerModelMock
     with app.app_context() as ac:
         ac.g.trace_id = None
         with app.test_request_context():
             mock_get_deed.return_value = DeedModelMock()
             with self.assertRaises(InternalServerError):
                 auth_sms("11", "11", "11")
Exemplo n.º 28
0
def client():
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database_test.db'

    app.config['TESTING'] = True

    with app.test_client() as client:
        with app.app_context():
            init_db()
        yield client
Exemplo n.º 29
0
    def setUp(self):
        app.config.from_object('config.TestingConfig')
        self.client = app.test_client()

        db.init_app(app)
        with app.app_context():
            db.create_all()
            user_datastore.create_user(email='test',
                                       password=encrypt_password('test'))
            db.session.commit()
Exemplo n.º 30
0
 def test_create_deed_html_with_date_of_mortgage_offer(self, mock_format):
     deed = MortgageDocMockWithDateOfMortgageOffer
     mock_format.return_value = 'a house'
     with app.app_context() as ac:
         ac.g.trace_id = None
         with app.test_request_context():
             self.assertTrue('Digital Mortgage Deed' in create_deed_html(deed.deed))
             self.assertTrue('e-MD1291A' in create_deed_html(deed.deed))
             self.assertTrue('Date of Mortgage Offer' in create_deed_html(deed.deed))
             self.assertTrue('a date string' in create_deed_html(deed.deed))
Exemplo n.º 31
0
def reset(app):
    with app.app_context():
        db.drop_all()
        db.create_all()

        test_product = Product(name="Snake Oil", price=9.99, stock=3)
        db.session.add(test_product)
        
        test_product2 = Product(name="Trump Steaks", price=999.99, stock=10)
        db.session.add(test_product2)
        db.session.commit()
Exemplo n.º 32
0
 def test_auth_sms_akuma_result_z(self, mock_get_deed, mock_akuma):
     with app.app_context() as ac:
         ac.g.trace_id = None
         with app.test_request_context():
             mock_get_deed.return_value = DeedModelMock()
             mock_akuma.return_value = {
                 "result": "Z",
                 "id": "2b9115b2-d956-11e5-942f-08002719cd16"
             }
             result = auth_sms("11", "11", "11")
             self.assertEqual(result, 'Failed to sign Mortgage document')
Exemplo n.º 33
0
    def get_recommendations(self, app):
        with app.app_context():
            books = Book.query.all()
            videos = Video.query.all()
            blogs = Blog.query.all()

            dict = {
                "book": [book.serialize for book in books],
                "video": [video.serialize for video in videos],
                "blog": [blog.serialize for blog in blogs]
            }
            return jsonify(dict)
Exemplo n.º 34
0
    def test_update(self):
        assert self.client.get('/admin').status_code == 200
        self.client.post('/admin',
                         data={
                             'productPrice': 'updated',
                             'body': ''
                         })

        with app.app_context():
            up = db.session.execute(
                'SELECT * FROM products WHERE id=1').fetchone()
            assert up['productPrice'] == 10.0
Exemplo n.º 35
0
def add_entry_task(title, text):
    """
    Definicao da task para salvar um novo post
    :param title: titulo do post
    :param text: conteudo do post
    :return: None
    """
    with app.app_context():
        logger.info('Processing add_entry_task....')
        entry = Entry(title, text)
        db.session.add(entry)
        db.session.commit()
        logger.info('Finished.')
Exemplo n.º 36
0
def CreationDB():
    """ Création de la DB """
    with app.app_context():
        app.logger.info("Creation de la base de donnees...")
        db.create_all()
        app.logger.info("Creation ok.")
        app.logger.info("Initialisation de la migration de sqlalchemy...")
        flask_migrate.init()
        app.logger.info("Initialisation ok.")
    
    # Mémorisation du numéro de version dans la DB
    m = Parametre(nom="version", parametre=app.config["VERSION_APPLICATION"])
    db.session.add(m)
    db.session.commit()
Exemplo n.º 37
0
def send_email(app, to, subject, body):
    with app.app_context():
        sg = sendgrid.SendGridClient("SG.pRFA8c9bRXXXXXXXXXXXXXXXXXXXXXXXXX")
        message = sendgrid.Mail()
        message.add_to(to)
        message.set_subject(subject)
        message.set_html(body)
        message.set_from('Template No-Reply <*****@*****.**>')
        try:
            status, msg = sg.send(message)
            print("Status: " + str(status) + " Message: " + str(msg))
            if status == 200:
                return True
        except Exception, ex:
            print("------------ ERROR SENDING EMAIL ------------" + str(ex.message))
Exemplo n.º 38
0
    def test_create_user(self):
        with app.app_context():
            user = User.create(email='*****@*****.**', password='******', auth_type='simple')
            assert user

            facebook_user = User.create(email='*****@*****.**',
                                        auth_type='facebook',
                                        auth_id='12345',
                                        auth_token='token')
            assert facebook_user

            instagram_user = User(email='*****@*****.**',
                                  auth_type='instagram',
                                  auth_id='123456',
                                  auth_token='token1')
            instagram_user.save()
Exemplo n.º 39
0
def UpgradeDB():
    """ Mise à jour de la DB """
    with app.app_context():
        app.logger.info("Migration de la base de donnees...")
        try :
            flask_migrate.migrate()
        except Exception, err :
            if "Path doesn't exist" in str(err) :
                app.logger.info("Repertoire Migrations manquant -> Initialisation de flask_migrate maintenant...")
                flask_migrate.init()
                flask_migrate.migrate()
            
        app.logger.info("Migration ok.")
        app.logger.info("Upgrade de la base de donnees...")
        flask_migrate.upgrade()
        app.logger.info("Upgrade ok.")
Exemplo n.º 40
0
def send_email(player_name, title, body_text, cc=None):
    player_full_name, email_address = get_player_email(player_name)

    if cc:
        cc = get_players_email(cc)

    if email_address is None:
        return False

    with app.app_context():
        mailer = Mail(app)
        message = Message(title, recipients=[(player_full_name, email_address)])
        message.body = body_text
        if cc:
            message.cc = cc
            message.reply_to = cc[0]
        mailer.send(message)

    return True
Exemplo n.º 41
0
def create_data():
    with app.app_context():
        from application import db
        import models
        db.create_all()
Exemplo n.º 42
0
 def create_table(cls):
     if ORM == 'peewee':
         cls.model.create_table(True)
     elif ORM == 'sql-alchemy':
         with app.app_context():
             db.create_all()
Exemplo n.º 43
0
    def setUpClass(cls):
        app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://{user}:{password}@{host}/{database}'.format(**config)
        app.app_context().push()
        db.init_app(app)

        cls.app = app.test_client()
Exemplo n.º 44
0
    def test_get_user(self):
        with app.app_context():
            user = User.get(email='*****@*****.**')
            assert user

            assert not User.get(email='*****@*****.**')
Exemplo n.º 45
0
def init_db():
    with app.app_context():
        db = get_db()
        with app.open_resource('databases/schema.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()
Exemplo n.º 46
0
    def test_get_document(self):
        with app.app_context():
            with app.test_request_context():
                resp = get_document()

                self.assertEqual(str(resp.mimetype), "application/pdf")
Exemplo n.º 47
0

# Setup Admin  ================================================================
init_admin()


# Bootstrap  ==================================================================
def create_test_models():
    user_datastore.create_user(email='test', password=encrypt_password('test'))
    user_datastore.create_user(email='test2', password=encrypt_password('test2'))
    stuff = SomeStuff(data1=2, data2='toto', user_id=1)
    db.session.add(stuff)
    stuff = SomeStuff(data1=5, data2='titi', user_id=1)
    db.session.add(stuff)
    db.session.commit()


@app.before_first_request
def bootstrap_app():
    if not app.config['TESTING']:
        if db.session.query(User).count() == 0:
            create_test_models()


# Start server  ===============================================================
if __name__ == '__main__':
    db.init_app(app)
    with app.app_context():
        db.create_all()
    app.run()
Exemplo n.º 48
0
 def test_protectedstuff(self):
     with app.app_context():
         instance = SomeStuff(data1=1337, data2='Test')
         db.session.add(instance)
         db.session.commit()
         self.assertTrue(hasattr(instance, 'id'))
Exemplo n.º 49
0
 def test_content_type(self):
     with app.app_context():
         response = self.get_response()
         self.assertEqual(response.headers['Content-Type'],
                          'application/json')
Exemplo n.º 50
0
# -*- coding: utf-8 -*-
from application import app
if __name__ == '__main__':
   with app.app_context():
       from tasks import celery
       celery.worker_main(argv=[''])
Exemplo n.º 51
0
def send_async_email_helper(msg):
    with app.app_context():
        mail.send(msg)
Exemplo n.º 52
0
# -*- coding: utf-8 -*-
Exemplo n.º 53
0
 def tearDown(self):
     with app.app_context():
         db.session.remove()
         db.drop_all()
Exemplo n.º 54
0
 def test_error_handlers(self):
     with app.app_context():
         self.assertTrue(400 in app.error_handler_spec[None])
         self.assertTrue(401 in app.error_handler_spec[None])
         self.assertTrue(404 in app.error_handler_spec[None])
         self.assertTrue(500 in app.error_handler_spec[None])