def before_each(transaction): with stash['app'].app_context(): db.engine.execute("drop database geokrety_unittest") db.engine.execute("create database geokrety_unittest") db.engine.execute("use geokrety_unittest") db.create_all() with stash['app'].test_request_context(): mixer.init_app(stash['app']) with mixer.ctx(commit=False): user = mixer.blend(User, name=api_username) user.password = api_password news = mixer.blend(News, author=user) news2 = mixer.blend(News, author=None) news_comment = mixer.blend(NewsComment, author=user, news=news) new_subscription1 = mixer.blend(NewsSubscription, user=user, news=news) user2 = mixer.blend(User) db.session.add(user) db.session.add(user2) db.session.add(news) db.session.add(news2) db.session.add(news_comment) db.session.add(new_subscription1) db.session.commit() if 'token' not in stash: stash['token'] = obtain_token() transaction['request']['headers']['Authorization'] = "JWT " + stash['token']
def create_app(config='config.ProductionDevelopmentConfig'): app = Flask(__name__) app.config.from_object(config) db.init_app(app) mixer.init_app(app) app.before_request(setup_authomatic(app)) app.before_request(load_user) app.add_url_rule('/', 'index', index) app.register_blueprint(auth_bp, url_prefix='/auth') app.register_blueprint(issues_bp, url_prefix='/issues') app.register_blueprint(comments_bp, url_prefix='/comments') app.register_blueprint(organizations_bp, url_prefix='/organizations') admin = Admin(app) # add admin views. admin.add_view(AdminView(User, db.session)) admin.add_view(AdminView(Issue, db.session)) admin.add_view(AdminView(Comment, db.session)) admin.add_view(AdminView(Organization, db.session)) admin.add_view(AdminView(Vote, db.session)) return app
def setUpClass(self): self.app = Setup.create_app() if getattr(self, "hash_password_original", None) is None: self.hash_password_original = phpass.PasswordHash.hash_password phpass.PasswordHash.hash_password = mock_hash_password phpass.PasswordHash.check_password = mock_check_password mixer.init_app(app)
def _blend(self): """Create mocked Geokret/User""" mixer.init_app(app) with mixer.ctx(commit=False): self.admin = mixer.blend(User) self.user1 = mixer.blend(User) self.user2 = mixer.blend(User) self.user3 = mixer.blend(User) self.geokret1 = mixer.blend(Geokret, type=GEOKRET_TYPE_TRADITIONAL, owner=self.user1, holder=self.user2) self.geokret2 = mixer.blend(Geokret, type=GEOKRET_TYPE_TRADITIONAL, owner=self.user2, holder=self.user1) self.geokret3 = mixer.blend(Geokret, type=GEOKRET_TYPE_COIN) db.session.add(self.admin) db.session.add(self.user1) db.session.add(self.user2) db.session.add(self.user3) db.session.add(self.geokret1) db.session.add(self.geokret2) db.session.add(self.geokret3) db.session.commit()
def test_safe_query(self): """Check DBHelper: safe query""" with app.test_request_context(): mixer.init_app(app) user = mixer.blend(User) obj = safe_query(db, User, 'id', user.id, 'user_id') self.assertEqual(obj.name, user.name)
def _blend(self): """ Create mocked User/News/NewsComments """ mixer.init_app(app) with mixer.ctx(commit=False): self.admin = mixer.blend(User) self.user1 = mixer.blend(User) self.user2 = mixer.blend(User) self.news1 = mixer.blend(News, author=self.user1) self.news2 = mixer.blend(News) self.newscomment1 = mixer.blend(NewsComment, author=self.user1, news=self.news1) self.newscomment2 = mixer.blend(NewsComment, author=self.user2, news=self.news1) db.session.add(self.admin) db.session.add(self.user1) db.session.add(self.user2) db.session.add(self.news1) db.session.add(self.news2) db.session.add(self.newscomment1) db.session.add(self.newscomment2) db.session.commit()
def setUp(self): super(TestAuthentication, self).setUp() with app.test_request_context(): mixer.init_app(app) with mixer.ctx(commit=False): user = mixer.blend(User, name=self.username, _password=self.password) db.session.add(user) db.session.commit()
def test_save_to_db(self): """Check DBHelper: save to db""" with app.test_request_context(): with mixer.ctx(commit=False): mixer.init_app(app) obj = mixer.blend(User) save_to_db(obj) user = db.session.query(User).filter(User.id == obj.id).first() self.assertEqual(obj.name, user.name)
def generate_data(self, cls, number, **kwargs): """ Generate random data for a given data model. """ mixer.init_app(self.flask_app) return mixer.cycle(number).blend( cls, id=fields.gen_uuid, **kwargs )
def test_audit_item_method_disabled(self): mixer.init_app(self.app) mixer.blend(ItemAuditScore, technology='test_index', method='check_test (AuditorTestObj)', score=0, disabled=True) auditor = AuditorTestObj(accounts=['test_account']) item = ChangeItem(index='test_index', account='test_account', name='item_name') self.assertEquals(len(item.audit_issues), 0) auditor.items = [item] auditor.audit_objects() self.assertEquals(len(item.audit_issues), 0)
def setUp(self): app.config.from_object('src.configs.settings.DevelopmentConfig') mixer.init_app(app) db.create_all() self.client = app.test_client() self.test_username1 = 'Daniel' self.test_username2 = 'Chris' self.test_username3 = 'Trump' self.valid_card_no1 = "4028571169702107" self.valid_card_no2 = "9440038135573607" self.valid_card_no3 = "5272892672067154"
def app(request): """Session-wide test `Flask` application.""" app = create_app(config.TestingConfig) # Establish an application context before running the tests. ctx = app.app_context() ctx.push() def teardown(): ctx.pop() request.addfinalizer(teardown) mixer.init_app(app) return app
def session(app, db, request): """Creates a new database session for each test, rolling back changes afterwards""" connection = _db.engine.connect() transaction = connection.begin() options = dict(bind=connection, binds={}) session = _db.create_scoped_session(options=options) _db.session = session mixer.init_app(app) yield session transaction.rollback() connection.close() session.remove()
def test_get_or_create(self): """Check DBHelper: get or create""" with app.test_request_context(): mixer.init_app(app) with mixer.ctx(commit=False): user = mixer.blend(User) save_to_db(user) obj, is_created = get_or_create(User, name=user.name) self.assertEqual(user.id, obj.id) self.assertFalse(is_created) obj, is_created = get_or_create(User, name="new user", password="******", email="*****@*****.**") self.assertNotEqual(user.id, obj.id) self.assertTrue(is_created)
def test_audit_item_method_score_override(self): mixer.init_app(self.app) mixer.blend(ItemAuditScore, technology='test_index', method='check_test (AuditorTestObj)', score=5, disabled=False) test_account_type = mixer.blend(AccountType, name='AWS') test_account = mixer.blend(Account, name='test_account', account_type=test_account_type) item = ChangeItem(index='test_index', account=test_account.name, name='item_name') auditor = AuditorTestObj(accounts=[test_account.name]) self.assertEquals(len(item.audit_issues), 0) auditor.items = [item] auditor.audit_objects() self.assertEquals(len(item.audit_issues), 1) self.assertEquals(item.audit_issues[0].issue, 'Test issue') self.assertEquals(item.audit_issues[0].score, 5)
def setUp(self): app.config['TESTING'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \ os.path.join(basedir, 'test.db') self.__app__ = app.test_client() db.create_all() titles = ['Title1', 'Title2', 'Title3'] authors = ['Author1', 'Author2', 'Author3'] user_emails = ['*****@*****.**', '*****@*****.**', '*****@*****.**'] mixer.init_app(app) users = mixer.cycle(2).blend(User, email=(email for email in user_emails)) books = mixer.cycle(2).blend(Book, title=(title for title in titles), author=(author for author in authors)) user_book = mixer.cycle(2).blend(UserBooks, user_id=(user.id for user in users), book_id=(book.id for book in books))
def test_create_geokret(self): """ Check Geokret: POST and Read back a geokret""" with app.test_request_context(): mixer.init_app(app) admin = mixer.blend(User) someone = mixer.blend(User) with mixer.ctx(commit=False): akret = mixer.blend(Geokret) # Test inserting first user payload = { "data": { "type": "geokret", "attributes": { "name": akret.name, "description": akret.description, } } } response = self._send_post('/v1/geokrety', payload=payload, code=201, user=admin) self._check_geokret(response['data'], akret, skip_check=['times', 'tracking-code'], with_private=True) akret.id = response['data']['id'] akret.tracking_code = response['data']['attributes'][ 'tracking-code'] response = self._send_get('/v1/geokrety/%s' % akret.id, code=200) self._check_geokret(response['data'], akret, skip_check=['times']) response = self._send_get('/v1/geokrety/%s' % akret.id, code=200, user=someone) self._check_geokret(response['data'], akret, skip_check=['times']) response = self._send_get('/v1/geokrety/%s' % akret.id, code=200, user=admin) self._check_geokret(response['data'], akret, skip_check=['times'], with_private=True)
def create_app(config={}): app = Flask(__name__) # Config. app.config.from_object('cheese.settings') app.config.update(config) CSRFProtect(app) if app.config['DEBUG']: app.testing = True # For Flask-WTF # Blueprints. from cheese.views import bp as cheese_bp from cheese.filters import bp as filters_bp from cheese.functions import bp as functions_bp app.register_blueprint(cheese_bp) app.register_blueprint(filters_bp) app.register_blueprint(functions_bp) # Models. from cheese.models import db, migrate, user_manager, db_adapter db.init_app(app) migrate.init_app(app, db) user_manager.init_app(app, db_adapter) # Admin. from cheese.views import init_admin, CheeseAdminIndexView admin = flask_admin.Admin(app, name='CHEESE database', index_view=CheeseAdminIndexView(name='Summary'), base_template='admin_master.html', template_mode='bootstrap3') init_admin(admin) # Flask extensions. from cheese.views import mail, pages, s3 mail.init_app(app) pages.init_app(app) mixer.init_app(app) s3.init_app(app) # Register signals. init_signals(app) # Add logging handlers. init_file_logging(app) init_mail_logging(app) app.logger.setLevel(logging.INFO) # Additional CLI commands. from cheese.commands import resetdb resetdb = app.cli.command('resetdb')(resetdb) return app
def test_save_issues(self): mixer.init_app(self.app) test_account = mixer.blend(Account, name='test_account') technology = mixer.blend(Technology, name='testtech') item = Item(region="us-west-2", name="testitem", technology=technology, account=test_account) revision = mixer.blend(ItemRevision, item=item, config={}, active=True) item.latest_revision_id = revision.id mixer.blend(ItemAudit, item=item, issue='test issue') auditor = Auditor(accounts=[test_account.name]) auditor.index = technology.name auditor.i_am_singular = technology.name auditor.items = auditor.read_previous_items() auditor.audit_objects() try: auditor.save_issues() except AttributeError as e: self.fail("Auditor.save_issues() raised AttributeError unexpectedly: {}".format(e.message))
def create_app(): app = Flask(__name__) app.config.from_object('config') db.init_app(app) mixer.init_app(app) app.before_request(setup_authomatic(app)) app.before_request(load_user) app.add_url_rule('/', 'index', index) app.register_blueprint(auth_bp, url_prefix='/auth') admin = Admin(app) # add admin views. admin.add_view(ModelView(User, db.session)) return app
def app(request): app = create_app(env='Testing') # deactivate extensions Config.ALLOW_EXTENSIONS = False mixer.init_app(app) db.drop_all(app=app) db.create_all(app=app) app.test_request_context().push() db.session.execute('create extension if not exists postgis') db.session.execute(""" drop table if exists datastat; create table datastat as select 1::integer as id, 100000::integer as population, 'mylittletown'::varchar as town; drop table if exists geotable; create table geotable as select 'mylittletown'::varchar as town_name, 'SRID=4326;POLYGON((40 2, 40.5 2, 40.5 2.5, 40 2.5, 40 2))'::geometry(polygon, 4326) as geom; """) mixer.blend( Framework, name_attribute='town_name', frameworkuri='geotable', frameworkkeys__name='town_name', geometrycolumn='geom' ) db.session.execute( "update {} set north=0, south=0, east=0, west=0;".format(Framework.__tablename__) ) mixer.blend(Dataset, dataseturi='datastat', framework=mixer.SELECT) mixer.blend(Data, name='population', type='integer', dataset=mixer.SELECT) mixer.blend(Data, name='town', type='string', isframeworkkey=True, dataset=mixer.SELECT) return app
def create_app(self): app = create_app() app.config['TESTING'] = True mixer.init_app(app) return app
app = Flask(__name__) app.config['TESTING'] = True app.config['BOOTSTRAP'] = True app.config['DATABASE'] = 'wiki.db' db_url = 'sqlite:////%s/%s' % (PROJECT_ROOT_PATH, app.config.get('DATABASE')) app.config['SQLALCHEMY_DATABASE_URI'] = db_url # Database Configuration # Use test_request_context is some kind of sorcery, but works?! if app.config['BOOTSTRAP'] is True: with app.test_request_context(): db.init_app(app) db.create_all() else: db.init_app(app) api = Api(app) marsh = Marshmallow(app) migrate = Migrate(app, db) manager = Manager(app) mixer.init_app(app) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run()