def convert(): create_app() for v in TuVote.select(): creator = User.get_or_none(User.id == v.user_voter) if not creator: print("Skipped vote. Owner:" + TuUser.get(TuUser.user == v.user_voter).user_login) continue t_id = v.target t_type = 1 if v.target_type == "user": t_type = 1 elif v.target_type == "blog": t_type = 2 elif v.target_type == "topic": t_type = 3 elif v.target_type == "comment": t_type = 4 value = 1 if v.vote_direction > 0 else -1 Vote.create( target_id=t_id, target_type=t_type, voter=creator, vote_value=value, created_date=v.vote_date, updated_date=v.vote_date, )
def test_config(): assert not create_app().testing assert create_app({ "TESTING": True, "SQLALCHEMY_DATABASE_URI": "sqlite:///:telecom-test.db", "SQLALCHEMY_TRACK_MODIFICATIONS": False, }).testing
def convert(): create_app() print("Replacing content") for c in Content.select(): c.path = c.path.replace("/home/service/kolenka-backend/", "/home/service/kolenka-beta-backend/") print("New path " + c.path) c.save()
def convert(): create_app() for p in Post.select(): if not p.text: continue p.text = process_text(p.text) p.save() for c in Comment.select(): if not c.text: continue c.text = process_text(c.text) c.save()
def convert(): create_app() for post in Post.select(): if not post.text: continue post.text = process_text(post.text) cut_info = process_cut(post.text) post.has_cut = cut_info["has_cut"] post.cut_text = cut_info["text_before_cut"] post.cut_name = cut_info["cut_name"] post.save()
def setUp(self): app = src.create_app() app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['DEBUG'] = False self.app = app.test_client() self.assertEqual(app.debug, False)
def setUp(self): self.app = create_app() self.client = self.app.test_client UserBase.metadata.create_all(engine) AthleteBase.metadata.create_all(engine) ActivityBase.metadata.create_all(engine) self.user = User(first_name='Dina', last_name='Asher-Smith', type='athlete') g.db.session.add(self.user) g.db.session.commit() self.athlete = Athlete(user_id=self.user.id, weight=Decimal('57.83')) g.db.session.add(self.athlete) g.db.session.commit() self.headers = {'content-type': 'application/json'} self.payload = { 'athlete_id': self.athlete.id, 'operation': 'add', 'activity_type': 'run', 'activity_date': '2019-09-27', 'activity_distance': '100', 'activity_duration': '10.83' } self.data = json.dumps(self.payload)
def create_app(self): app = create_app() app.config['TESTING'] = True app.config['PRESERVE_CONTEXT_ON_EXCEPTION'] = False setup_logging(path='../../logging.json', tofile=False) self.logger = logging.getLogger(__name__) return app
def test_app(): app = create_app() app.config.from_object('src.config.TestingConfig') with app.app_context(): print("[fixture] In test_app(), before yield") yield app # testing happens here print("[fixture] In test_app(), after yield")
def setUp(self): self.app = create_app(config_name="testing") self.client = self.app.test_client # binds the app to the current context with self.app.app_context(): db.create_all()
def run(): logging.config.fileConfig('logging.conf') logger = logging.getLogger() app = create_app(Config) logger.info('run application') app.run() logger.info('finish application')
def setUp(self): self.app = create_app() self.app.config['TESTING'] = True register_blueprints(self.app) self.DBBase = DBBase self.EventStoreBase = EventStoreBase self.DBSession = DBSession self.EventStoreSession = EventStoreSession # to mock a client doing REST API calls self.client = self.app.test_client() # to simulate eventual consistency between the command and the query side self.simulate_eventual_consistency = lambda: time.sleep(0.1) DBBase.metadata.create_all(db_engine) EventStoreBase.metadata.create_all(event_store_engine) self.conn = create_connection(RABBITMQ_IP, RABBITMQ_PORT) self.app.sending_channel = setup_channel_for_sending() self.app.secret_key = '\x0c|f9\x91%1\xb2\xd2\xdd\xeeM\x15\xa1\xf1\xb09U\xb5Oj&\xe0M' self.t = Thread(target=receive, args=(setup_channel_for_receiving(), )) self.t.daemon = True self.t.start()
class Test_Conducted_Survey_Model: app = create_app( mode="development", static_path="../static", templates_path="../templates", instance_path="../instance" ) def test_create_node(self): with self.app.app_context(): from src.database.db import get_db, init_db, distroy_db from src.models.conducted_survey_question_model import ConductedSurveyQuestion distroy_db(self.app) init_db(self.app) current_transaction = get_db().transaction with current_transaction: test_conducted_survey_question_1 = ConductedSurveyQuestion() test_conducted_survey_question_1.save() assert test_conducted_survey_question_1.nodeId is not None assert test_conducted_survey_question_1.addedOn is not None assert isinstance(test_conducted_survey_question_1.addedOn, datetime) assert test_conducted_survey_question_1.sentimentSet is True assert test_conducted_survey_question_1.sentimentCalculated is False
def persist_spot_artist_tuple(artist: SpotArtistTuple): current = create_app('docker') with current.app_context(): try: _artist = Persist.get_or_create(db.session, Artist, name=artist.name, spot_uri=artist.uri) _genres = [ Persist.get_or_create(db.session, Genre, name=genre.name) for genre in artist.genres ] if artist.genres else list() img = artist.images[0]["url"] if artist.images else None if img: _artist.img = img thumb = artist.images[-1]["url"] if len( artist.images) > 1 else None if thumb: _artist.thumb = thumb db.session.add(_artist) [ _artist.genres.append(g) for g in _genres if g not in _artist.genres ] db.session.commit() except Exception: db.session.rollback() raise finally: db.session.close()
class Test_Survey_Schema_Dump: app = create_app(mode="development", static_path="../static", instance_path="../instance", templates_path="../templates") def test_schema_dump(self): with self.app.app_context(): from src.database.db import get_db, init_db, distroy_db from src.models.survey_model import Survey from src.utils.marshmallow.survey_schema import SurveySchema distroy_db(self.app) init_db(self.app) current_transaction = get_db().transaction with current_transaction: test_survey_1 = Survey( slug="test_survey_1", language="en", ) test_survey_1.save() test_output_1 = SurveySchema().dump(test_survey_1) pytest.test_survey_1 = test_survey_1 pytest.test_output_1_data = test_output_1.data assert bool(test_output_1.errors) is False def test_addedOn_field_is_ISO8601(self): output_addedOn = pytest.test_output_1_data['addedOn'] addedOn = datetime.strptime(output_addedOn, '%Y-%m-%dT%H:%M:%S.%f%z') assert addedOn == pytest.test_survey_1.addedOn # decided to remove the nesting responsability from marshmallo to the wrappers for efficiency """def test_nested_surveyversion(self):
def test_application_database_initialisation(self): """testing initialising the application initialisation""" from src import create_app app = create_app(mode='development', static_path='../static', templates_path='../templates', instance_path='../instance') with app.app_context(): from src.database.db import init_db init_db(app) from neomodel import config assert config.DATABASE_URL == app.config['NEOMODEL_DATABASE_URI'] from neomodel import db from src.models.survey_model import Survey, SurveyVersion from src.models.conducted_survey_model import ConductedSurvey from src.models.conducted_survey_question_model import ConductedSurveyQuestion from src.models.question_model import Question, PreQuestion from src.models.answers_model import Answer assert Survey in db._NODE_CLASS_REGISTRY.values() assert Question in db._NODE_CLASS_REGISTRY.values() assert ConductedSurvey in db._NODE_CLASS_REGISTRY.values() assert ConductedSurveyQuestion in db._NODE_CLASS_REGISTRY.values() assert Answer in db._NODE_CLASS_REGISTRY.values() assert SurveyVersion in db._NODE_CLASS_REGISTRY.values() assert PreQuestion in db._NODE_CLASS_REGISTRY.values()
def create_app(self): app = create_app() app.config['SQLALCHEMY_DATABASE_URI '] = os.environ[ "SQLALCHEMY_DATABASE_URI"] app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.config['TESTING'] = True return app
def setUp(self): self.app = create_app('testing') self.client = self.app.test_client() self.client.testing = True with self.app.app_context(): db.create_all()
def app(): args = { "ENABLE_DATABASE": False, "ENABLE_BACKGROUND_WORKER": False, } app = create_app(args) yield app
class Test_SurveyVersion_Prequestion_Relationship: app = create_app(mode="development", static_path="../static", templates_path="../templates", instance_path="../instance") def test_create_relationship(self): with self.app.app_context(): from src.database.db import get_db, init_db, distroy_db from src.models.question_model import PreQuestion from src.models.survey_model import SurveyVersion distroy_db(self.app) init_db(self.app) current_transaction = get_db().transaction with current_transaction: test_prequestion_1 = PreQuestion( slug="test_prequestion_1", text="This is and example PreQuestion 1", language="en") test_prequestion_1.save() test_surveyversion_1 = SurveyVersion( title="Test SurveyVersion 1") test_surveyversion_1.save() rel = test_surveyversion_1.prequestions.connect( test_prequestion_1) pytest.test_prequestion_1 = test_prequestion_1 pytest.test_surveyversion_1 = test_surveyversion_1 pytest.test_surveyversion_prequestion_rel_1 = rel
class Test_SurveyVersion_Schema_Dump: app = create_app(mode="development", static_path="../static", instance_path="../instance", templates_path="../templates") def test_schema_dump(self): with self.app.app_context(): from src.database.db import get_db, init_db, distroy_db from src.models.survey_model import SurveyVersion from src.utils.marshmallow.surveyversion_schema import SurveyVersionSchema distroy_db(self.app) init_db(self.app) current_transaction = get_db().transaction with current_transaction: test_surveyversion_1 = SurveyVersion( title="Test SurveyVersion 1", ) test_surveyversion_1.save() pytest.test_surveyversion_1 = test_surveyversion_1 test_output_1 = SurveyVersionSchema().dump(test_surveyversion_1) pytest.test_output_1_data = test_output_1.data pytest.test_output_1_errors = test_output_1.errors assert bool(pytest.test_output_1_errors) == False
def test_development_config(client): """Test create_app with development config.""" app = create_app() assert current_app is not None assert app.config["SECRET_KEY"] == "top_secret" assert app.config["SQLALCHEMY_DATABASE_URI"] == \ os.environ.get("DATABASE_DEV_URL")
def app(): flask_app = create_app() flask_app.config['DATABASE'] = DBTEST_NAME flask_app.config['DB_USER'] = DBTEST_USER flask_app.config['DB_PASSWORD'] = DBTEST_PASSWORD flask_app.config['TESTING'] = True flask_app.config['DEBUG'] = True with flask_app.app_context(): conn = db.get_db() cursor = conn.cursor() db.drop_all_tables(conn, cursor) db.reset_all_primarykey(conn, cursor) build_records(conn, cursor) conn.commit() db.close_db() yield flask_app with flask_app.app_context(): db.close_db() conn = db.get_db() cursor = conn.cursor() db.drop_all_tables(conn, cursor) db.reset_all_primarykey(conn, cursor) db.close_db()
def persist_spot_track_tuple(track: SpotTrackTuple): current = create_app('docker') with current.app_context(): try: img = track.album.images[0][ "url"] if track.album.images else None thumb = track.album.images[-1][ "url"] if track.album.images and len( track.album.images) > 1 else None _album = Persist.get_or_create( db.session, Album, name=track.album.name, spot_uri=track.album.uri, release_date=track.album.release_date, release_date_string=track.album.release_date_string) _track = Persist.get_or_create(db.session, Track, name=track.name, spot_uri=track.uri, preview_url=track.preview_url, album_id=_album.id) _primary_artists = [ Persist.get_or_create(db.session, Artist, name=artist.name, spot_uri=artist.uri) for artist in track.primary_artists ] _featured_artists = [ Persist.get_or_create(db.session, Artist, name=artist.name, spot_uri=artist.uri) for artist in track.featured_artists ] if img: _album.img = img if thumb: _album.thumb = thumb [ _album.artists.append(a) for a in _primary_artists if a not in _album.artists ] [ _track.primary_artists.append(a) for a in _primary_artists if a not in _track.primary_artists ] [ _track.primary_artists.append(a) for a in _featured_artists if a not in _track.featured_artists ] db.session.commit() except Exception: db.session.rollback() raise finally: db.session.close()
def app(strand_api_client_factory, slack_client_class): app = create_app( strand_api_client=strand_api_client_factory, SlackClientClass=slack_client_class, slack_verification_tokens=config['SLACK_VERIFICATION_TOKENS'], strand_api_verification_token=config['STRAND_API_VERIFICATION_TOKEN']) app.testing = True return app
def setUp(cls): cls.app = create_app() cls.app_context = cls.app.app_context() cls.app_context.push() cls.client = cls.app.test_client() db.create_all() runner = cls.app.test_cli_runner() runner.invoke(args=["db-custom", "seed"])
def convert(): create_app() print("Replacing stickers") stickers_set = set() def replace_sticker(text): if text: pattern = r'<img src="\/common\/templates\/skin\/start-kit\/assets\/images\/(.*?)\..*?">' items = re.findall(pattern, text) for i in items: stickers_set.add(i) text = re.sub(pattern, r":\1:", text) pattern = r'<img src="\/common\/templates\/skin\/start-kit\/assets\/images\/(.*?)\..*?" />' items = re.findall(pattern, text) for i in items: stickers_set.add(i) text = re.sub(pattern, r":\1:", text) pattern = r'<img src="http:\/\/k\.faisu\.net\/kreguzda\/images\/smilies\/(.*?)\..*?" />' items = re.findall(pattern, text) for i in items: stickers_set.add(i) return re.sub(pattern, r":\1:", text) return None for p in Post.select(): p.text = replace_sticker(p.text) p.cut_text = replace_sticker(p.cut_text) p.save() for p in Comment.select(): p.text = replace_sticker(p.text) p.save() for p in Message.select(): p.text = replace_sticker(p.text) p.save() for p in User.select(): p.about = replace_sticker(p.about) p.save() print(stickers_set)
def testClient(): flaskApp = create_app('test') with flaskApp.test_client() as testClient: with flaskApp.app_context(): db.drop_all() db.create_all() upgrade('./resources/migration/main/') yield testClient
def test_app(): # create instance from app factory app = create_app() # add test config app.config.from_object('src.config.TestConfig') with app.app_context(): yield app # testing happens here
def client(): """Test client for Flask WSGI application""" app = create_app(TestConfig) with app.app_context(): t_client = app.test_client() db.create_all() yield t_client db.drop_all()
import os from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from src import api, db, ma, create_app, configs, bp, security config = os.environ.get('PYTH_SRVR') config = configs.get(config, 'default') extensions = [api, db, ma, security] bps = [bp] app = create_app(__name__, config, extensions=extensions, blueprints=bps) manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) @manager.shell def _shell_context(): return dict( app=app, db=db, ma=ma, config=config ) if __name__ == "__main__":
import os import sys import logging dirname = os.path.dirname(os.path.dirname(__file__)) sys.path.insert(0, dirname) from src import create_app if __name__ == "__main__": app = create_app() app.run(debug=True)
#! /usr/bin/env python #coding=utf-8 from flask.ext.script import Manager,Server,Shell from src import create_app from src.database import db manager = Manager(create_app('settings.py')) @manager.shell def make_shell_context(): return dict(db=db) manager.add_command('runserver',Server(host="0.0.0.0", port=9000)) @manager.command def syncdb(): db.create_all() @manager.command def dropall(): """drop all tables""" db.drop_all() if __name__ == "__main__": manager.run()
import os from src import create_app, db from src.models import BlogContent, Blog from flask.ext.script import Manager, Shell from flask.ext.migrate import Migrate, MigrateCommand app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) migrate = Migrate(app, db) def make_shell_context(): return dict(app=app, db=db, BlogContent=BlogContent, Blog=Blog) manager.add_command('shell', Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run()