python - 为 sqlalchemy 应用程序编写 pytest

标签 python sqlalchemy pytest

我正在尝试将单元测试转换为 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 测试版本应该是什么。

最佳答案

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

  1. 根据文档设置您的engineSession 对象。 (我选择了 sessionmaker,因为如果 session 在 Flask 的请求线程池中仍然可用,我想检查我的应用程序,请参阅:https://dev.to/nestedsoftware/flask-and-sqlalchemy-without-the-flask-sqlalchemy-extension-3cf8

  2. 从您在应用程序中创建它的任何位置导入您的 Base 对象。这将在您的数据库中创建由 engine 定义的所有表。

  3. 现在我们要将 Session 返回给您的单元测试。这个想法是在调用 Yield 之前进行设置,之后进行拆卸。现在,在您的测试中,您可以创建一个表并用一些数据行等填充它。

  4. 现在我们必须关闭 session ,这很重要!

  5. 现在通过调用 Base.metadata.drop_all(bind=engine) 我们删除数据库中的所有表(如果需要,我们可以定义要删除的表,默认为: tables=None)

     engine = create_engine(create_db_connection_str(config), echo=True)
     Session = scoped_session(sessionmaker(bind=engine))
    
     @pytest.fixture(scope="function") # or "module" (to teardown at a module level)
     def db_session():
         Base.metadata.create_all(engine)
         session = Session()
         yield session
         session.close()
         Base.metadata.drop_all(bind=engine)
    
  6. 现在我们可以将函数范围的 fixture 传递给每个单元测试:

     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
    

关于python - 为 sqlalchemy 应用程序编写 pytest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23325669/

相关文章:

python - 我怎样才能使用 pytest 选项作为固定装置而不是重复自己?

python - 如何防止模块代码从 python 中导入的模块执行?

python - 避免在 python 脚本名称中出现关于破折号的 pylint 警告

python - 使用 SqlAlchemy 和 Alembic 创建部分索引

python - 在执行查询之前将日期时间转换为 SQLAlchemy 模型中的 unix 时间戳?

python - 如何使用 pytest 确认引发正确的异常

python - 测试 : excessive memory usage with large number of tests

python - 无需端口转发的点对点套接字通信

python - 如何制作 tkinter 条目小部件?

python - Pandas Dataframe NaN 值替换为无值