为sqlalchemy应用程序编写pytest

问题描述 投票:3回答:2

我正在尝试将单元测试转换为py测试。我正在使用单元测试示例

class TestCase(unittest.TestCase):
    def setUp(self):
        app.config['TESTING'] = True
        app.config['CSRF_ENABLED'] = False
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 
        'test.db')
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()

我不确定,它的py测试版应该是什么。

python sqlalchemy pytest
2个回答
2
投票

我搜索了一个很好解释的解决方案,使用SqlAlchemy而不使用Flask-SQLAlchemy,并使用Pytest运行测试,所以他是我如何实现这个:

  1. 根据文档设置你的engineSession对象。 (我已经选择了sessionmaker,因为我想检查我的应用程序,如果会话仍在Flask的请求线程池中可用,请参阅:https://dev.to/nestedsoftware/flask-and-sqlalchemy-without-the-flask-sqlalchemy-extension-3cf8
  2. 从您在应用中创建它的任何地方导入Base对象。这将创建由engine定义的数据库中的所有表。
  3. 现在我们想要将Session回馈给您的单元测试。想法是在调用Yield&teardown之后设置。现在,在您的测试中,您可以创建一个表并使用一些数据行填充它。
  4. 现在我们必须关闭Session,这很重要!
  5. 现在通过调用Base.metadata.drop_all(bind=engine)我们删除数据库中的所有表(如果需要,我们可以定义要删除的表,默认为:tables=Noneengine = create_engine(create_db_connection_str(config), echo=True) Session = scoped_session(sessionmaker(bind=engine)) @pytest.fixture(scope="function") def db_session(): Base.metadata.create_all(engine) yield Session Session.close_all() Base.metadata.drop_all(bind=engine)
  6. 现在我们可以将函数作用域夹具传递给每个单元测试: class TestNotebookManager: """ Using book1.mon for this test suite """ book_name = "book1" def test_load(self, client: FlaskClient, db_session) -> None: notebook = Notebook(name=self.book_name) db_session.add(book) db_session.commit() rv = client.get(f"/api/v1/manager/load?name={self.name}") assert "200" in rv.status

1
投票

首先,py.test应该运行现有的unittest测试用例。然而,py.test中的本机操作是使用夹具进行设置和拆卸:

import pytest

@pytest.fixture
def some_db(request):
    app.config['TESTING'] = True
    app.config['CSRF_ENABLED'] = False
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'test.db')
    db.create_all()
    def fin():
        db.session.remove()
        db.drop_all()
    request.addfinalizer(fin)

def test_foo(some_db):
    pass

请注意,我不知道SQLAlchemy以及是否有更好的方法来处理它的设置和拆卸。所有这个例子都演示了如何将setup / teardown方法转换为fixture。

© www.soinside.com 2019 - 2024. All rights reserved.