def tearDown(self): # TODO: 未來的 DB 從 production 複製過去 with app.app_context(): db.session.remove() # 把當前的 session 移除掉 #db.drop_all() # 就不要移除 data, 以增加效率 db.session.commit() # 記得要 commit, 不然多組 test 會有 error redis_store.flushdb()
def setUp(self): app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'postgresql://*****:*****@localhost:5432/postgres' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False with app.app_context(): db.init_app(app) self.app = app.test_client() self.app_context = app.app_context
def test_create_user(self): with app.app_context(): user_test = User(spotify_id="123", spotify_token="123hjh123h5j") db.session.add(user_test) db.session.commit() get_user_test = User.query.filter_by(spotify_id="123").first() print get_user_test self.assertEqual(get_user_test.spotify_token, "123hjh123h5j")
def setUp(self): app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///aafood-test.db' app.config['TESTING'] = True self.app = app.test_client() with app.app_context(): db.init_app(app) db.create_all() q = len(Term.query.all()) print(q)
def dict_news_task(): with app.app_context(): dict_config = models.KeyValue.query.filter_by(keyname=DICT_NEWS_KEY).first() or models.KeyValue(DICT_NEWS_KEY, "111") news_items = get_dict_news() current_maxseen = int(dict_config.value) for news_item in get_dict_news(): if news_item['id'] > current_maxseen: current_maxseen = news_item['id'] post_dict_news(news_item) dict_config.value = str(current_maxseen) db.session.add(dict_config) db.session.commit()
def wrapper(*args, **kwargs): """ A wrapped which tries to get ``app`` from ``kwargs`` or creates a new ``app`` otherwise, and actives the application context, so the decorated function is run inside the application context. """ app = kwargs.pop("app", None) if app is None: from app.app import app with app.app_context(): return func(*args, **kwargs)
def test_create_precio_historico(self): with app.app_context(): new_precio_historico = PrecioHistorico(ticker="ETH", precio=1000, fecha=datetime.now()) db.session.add(new_precio_historico) db.session.commit() get_precio_mes = PrecioHistorico.query.filter( extract('month', PrecioHistorico.fecha) == 1).first() self.assertEqual(get_precio_mes.precio, 1000)
def setUp(self): app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///aafood-test.db' app.config['REDIS_URL'] = 'redis://localhost:6379/30' app.config['TESTING'] = True self.app = app.test_client() with app.app_context(): db.init_app(app) if os.path.exists('app/aafood.db') == True: #TODO: 未來的 DB 從 production 複製過去 shutil.copyfile('app/aafood.db', 'app/aafood-test.db') if os.path.exists("app/aafood-test.db") == False: db.create_all() add_data() redis_store.init_app(app)
def client(): file_level_handle, TEST_DB_PATH = tempfile.mkstemp(suffix='.db', prefix='test_db') app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + TEST_DB_PATH db.init_app(app) with app.test_client() as client: with app.app_context(): db.create_all() yield client os.close(file_level_handle) print('TEST DB PATH', TEST_DB_PATH) os.unlink(TEST_DB_PATH)
def populate_db( provider_name: str, product_name: str, truck_id: str): with app.app_context(): provider1 = helper.add_instance(Provider, name=provider_name) rate1 = helper.add_instance(Rate, product_name=product_name, rate=200, scope=provider1.id) truck1 = helper.add_instance(Truck, truck_id=truck_id, provider_id=provider1.id)
def setUp(self): app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['DEBUG'] = False app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://{user}:{pw}@{url}/{db}'.format( user="******", pw="admin", url="127.0.0.1:5432", db="cryptocartera-test") self.app = app.test_client() with app.app_context(): # db.drop_all() db.create_all() moneda = Moneda(moneda="BTC") db.session.add(moneda) db.session.commit()
def test_create_crypto(self): with app.app_context(): btc = Moneda.query.filter_by(moneda="BTC").first() new_crypto_test_with_BTC = CryptoOrden(ticker="ETH", cantidad=1, precio_compra_usd=1200.00, precio_compra=0.090050, moneda_compra=btc, fecha_compra=datetime( 2018, 1, 27, 16, 5)) db.session.add(new_crypto_test_with_BTC) db.session.commit() get_new_crypto = CryptoOrden.query.filter_by(ticker="ETH").first() self.assertEqual(get_new_crypto.moneda_compra, btc)
def flask_app(): import os os.environ["FLASK_ENV"] = "testing" from app.app import app from app.extensions import db from app.extensions.sqla.sqla import DuplicateEntry from migrations.initial_development_data import init_email_templates with app.app_context(): db.create_all() try: init_email_templates() except DuplicateEntry: pass yield app db.session.rollback() db.drop_all()
from app.app import app # from app.app import db if __name__ == '__main__': # creates tables from schema defined in app classes with app.app_context(): db.create_all() db.session.commit() print('initialised database schema')
def __init__(self, db_name=None): with app.app_context(): self._db = Database(app.config['DEFAULT_DB'] if db_name is None else db_name).db
def __init__(cls, db): """ Initialize pymongo db instance""" with app.app_context(): client = MongoClient(app.config['MONGODB_HOST'], app.config['MONGODB_PORT']) cls.db = client[db]
def app_setup(): app.config['DEFAULT_DB'] = 'tests' app.config['SALT'] = "$2b$08$duvTxgV7EW9s98pmpFgRAO" with app.app_context(): yield app
from app.dao.user_interface_module import * import json from werkzeug.security import generate_password_hash, check_password_hash from flask import make_response from app.utils.my_token import * from app.app import app app.app_context().push() # 普通用户注册的封装方法 def common_Register(user): if user.get('telephone') and user.get('password') and user.get('nickname'): pf = generate_password_hash(user['password'], method='pbkdf2:sha1:1001', salt_length=8) user['password'] = pf nn = getUserByName(u['user_nickname']) if nn: return {"status_code": "10000", "status_text": "用户名已经存在"} rr = getUserByTel(user['telephone']) if rr: return json.dumps({ "status_code": "10002", "status_text": "用户已经存在" }) else: res = commonRegister(user) if res: token = createToken(user['telephone']) response = make_response()
def client(): client = app.test_client() ctx = app.app_context() ctx.push() yield client ctx.pop()
from app.models import db from app.app import app with app.app_context(): db.create_all()
def client(): context = app.app_context() context.push() yield app.test_client() context.pop()