我正在Flask中尝试“应用程序工厂”的东西。 当我通过flask运行应用程序时,一切正常(按预期)。
#__init__.py
from flask import Flask
from .config import config_by_name
from flask import Flask
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config_by_name[config_name])
return app
#config.py
class Config:
SECRET_KEY = os.getenv('SECRET_KEY', 'my_precious_secret_key')
SQLALCHEMY_TRACK_MODIFICATIONS = False
DEBUG = False
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = "postgresql://postgres@10.11.12.13:1234/DB"
SECRET_KEY = 'dev!'
class TestingConfig(Config):
DEBUG = True
TESTING = True
PRESERVE_CONTEXT_ON_EXCEPTION = False
SQLALCHEMY_DATABASE_URI = 'sqlite:///testing.db'
SECRET_KEY = 'test!'
config_by_name = dict(
dev=DevelopmentConfig,
test=TestingConfig
)
key = Config.SECRET_KEY
#app.py
from flask import Flask
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from application import create_app
app = create_app('dev')
engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
DBSession = sessionmaker(bind=engine)
session = DBSession()
@app.route('/item/<int:id>', methods=['GET', 'POST'])
def do_something(id):
return '%s' % session.bind
if __name__ == '__main__':
app.run()
当我致电http://localhost:5000/item/1时,我得到了预期的结果: 引擎(postgresql://postgres@10.11.12.13:1234 / DB)
现在我要编写一些测试。如何切换到“测试配置”?
# test_app.py
import unittest
from application.app import app
from flask_testing import TestCase
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
class BaseTestCase(TestCase):
def create_app(self):
app.config.from_object('application.config.TestingConfig')
return app
def setUp(self):
engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
DBSession = sessionmaker(bind=engine)
self.session = DBSession()
def tearDown(self):
pass
def test_edit(self):
response = self.client.get('/item/9999')
print(response.data)
if __name__ == '__main__':
unittest.main()
运行单元测试时,我还获得了“开发” DB连接:
python -m unittest application/test_app.py
b'Engine(postgresql://postgres@10.11.12.13:1234/DB)'
如何获取“ sqlite:///testing.db”连接。我在做什么错?!
答案 0 :(得分:1)
主要问题是您正在尝试在测试中使用“创建的应用”。查看test.py
:
from application.app import app
您导入了已配置的应用程序。什么意思执行以下代码:
app = create_app('dev')
之后,您尝试在测试中更新已配置的应用程序,但是它不起作用:
def create_app(self):
app.config.from_object('application.config.TestingConfig')
最简单的方法是使用ENV
变量进行配置:
def create_app(config_name):
app = Flask(__name__)
# get config name from env variable
config_name = os.environ.get('FLASK_CONFIG', config_name)
app.config.from_object(config_by_name[config_name])
return app
从终端:
export FLASK_CONFIG=test
# you can run app with 'test' config python application/app.py
# or run tests etc...
nosetests ./tests/ --exe --logging-level=INFO
希望这会有所帮助。