设置数据库以在Flask中进行测试

Bar*_*ski 2 python testing sqlalchemy flask

我正在开发我的第一个Flask应用程序.这是我的侧面项目,所以我专注于良好的实践和设计,并花时间.我有点坚持测试 - 我在文档中找到了一些示例,这里有SO,但它们要么不适用于我的应用程序,要么看起来不像Pythonic /设计得好.

相关的代码片段是:

# application module __init__.py
def create_app(config):
    app = Flask(__name__)
    app.config.from_object('config.%s' % config.title())
    return app  

config = os.getenv('CONFIG', 'development')
app = create_app(config)
db = SQLAlchemy(app)
Run Code Online (Sandbox Code Playgroud)

# config.py
class Testing(Base):
    TESTING = True
    SQLALCHEMY_DATABASE_URI = \
        'sqlite:///' + os.path.join(_basedir, 'testing.sqlite')
Run Code Online (Sandbox Code Playgroud)

# models.py
class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(60), unique=True, nullable=False)
    password_hash = db.Column(db.String(60), nullable=False)
Run Code Online (Sandbox Code Playgroud)

# testing.py
class TestCase(unittest.TestCase):

    def setUp(self):
        self.app = create_app('testing')
        # TODO: create connection to testing db

    def tearDown(self):
        # TODO: abort transaction
        pass
Run Code Online (Sandbox Code Playgroud)

问题是:如何实现setUptearDown在我的测试中我可以使用我的模型和连接做测试数据库?如果我只是导入db,它将适用于开发数据库.

如果它有帮助,我不需要从头开始创建测试数据库,我使用Flask-Migrate并且测试可以假设测试数据库已初始化并为空.

欢迎任何评论,如果我的设计存在缺陷,我不介意重构.

Sea*_*ira 5

看起来像你就应该能够运行CONFIG=Testing python -m unittest discover,并拥有一切只是工作.您可能想要更改的唯一想法是,而不是create_app在测试中调用,只需从__init__.py导入它:

# testing.py
from . import config, db

class TestCase(unittest.TestCase):

    def setUp(self):
        self.app = create_app(config)
        # db is properly set up to use the testing config
        # but any *changes* you make to the db object
        # (e. g. monkey-patching) will persist between tests
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()
Run Code Online (Sandbox Code Playgroud)

请看这里的例子.