问题描述
我正在尝试将单元测试转换为 py 测试.我正在使用单元测试示例
I am trying convert unit test into py test. I am using the unit test example
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 测试版本应该是什么.
I am not sure, What should be its py test version.
推荐答案
我四处寻找一个很好解释的解决方案来使用 SqlAlchemy 没有 Flask-SQLAlchemy 并运行使用 Pytest 进行测试,所以这是我如何实现的:
I searched high and low for a well explained solution to use SqlAlchemy without Flask-SQLAlchemy and run tests with Pytest, so here's how i have achieved this:
设置您的
引擎
&Session
对象按照文档.(我选择了 sessionmaker 因为我想在我的应用程序中检查会话是否在 Flask 的请求线程池中仍然可用,请参阅:https://dev.to/nestedsoftware/flask-and-sqlalchemy-without-the-flask-sqlalchemy-extension-3cf8
Set up your
engine
&Session
objects as per the docs. (I have opted for sessionmaker as i want to check in my app if the session is still available in the Flask's request thread pool, see: https://dev.to/nestedsoftware/flask-and-sqlalchemy-without-the-flask-sqlalchemy-extension-3cf8
从您在应用中创建的任何位置导入 Base
对象.这将在您的数据库中创建由 engine
定义的所有表.
Import your Base
object from wherever you've created it in your app. This will create all the tables in your database defined by the engine
.
现在我们想要将 Session
返回给您的单元测试.这个想法是在调用 Yield
之前进行设置 &拆机后.现在,在您的测试中,您可以创建一个表并用一些数据行等填充它.
Now we want to Yield a Session
back to your unit tests. The idea is to setup before calling Yield
& teardown after. Now, in your test you can create a table and populate it with some rows of data etc.
现在我们必须关闭会话,这很重要!
Now we must close the Session, this is important!
现在通过调用 Base.metadata.drop_all(bind=engine)
我们删除数据库中的所有表(如果需要,我们可以定义要删除的表,默认是: tables=None
)
Now by calling Base.metadata.drop_all(bind=engine)
we drop all the tables in the database ( we can define a table(s) to drop if required, default is: 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)
现在我们可以将函数作用域的fixture传递给每个单元测试:
Now we can pass the function scoped fixture to each unit test:
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
这篇关于为 sqlalchemy 应用编写 py 测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!