如何使用pytest嘲笑Asyncpg执行者和获取方法?
我正在使用pytest和asyncpg加载并将项目保存到数据库中。如何测试以下两个函数?
import asyncpg
config = {host: "localhost", port: 5432, database: "postgres"}
async def read_data():
async with asyncpg.create_pool(**config) as pool:
async with pool.acquire() as conn:
feeds = await conn.fetch(
"select feed_id, url, etag, last_modified from feeds WHERE enabled=TRUE"
)
return feeds
async def write_data(items):
async with asyncpg.create_pool(**config) as pool:
async with pool.acquire() as conn:
query = '''
INSERT INTO
feed_items (feed_item_id, pubdate, link, guid, title, summary, content, author, feed_id)
VALUES
(
$1, $2, $3, $4, $5, $6, $7, $8, $9
)
ON CONFLICT DO NOTHING
'''
await conn.executemany(query, items)
I am using pytest and asyncpg to load and save items to the database. How do I test the 2 functions below?
import asyncpg
config = {host: "localhost", port: 5432, database: "postgres"}
async def read_data():
async with asyncpg.create_pool(**config) as pool:
async with pool.acquire() as conn:
feeds = await conn.fetch(
"select feed_id, url, etag, last_modified from feeds WHERE enabled=TRUE"
)
return feeds
async def write_data(items):
async with asyncpg.create_pool(**config) as pool:
async with pool.acquire() as conn:
query = '''
INSERT INTO
feed_items (feed_item_id, pubdate, link, guid, title, summary, content, author, feed_id)
VALUES
(
$1, $2, $3, $4, $5, $6, $7, $8, $9
)
ON CONFLICT DO NOTHING
'''
await conn.executemany(query, items)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我们可以模拟数据库调用,但是这样做时没有太多测试。您的功能只需读取/编写一些数据,逻辑或条件不多。我的建议是将邮政实例旋转在码头容器中,并在您的测试旁边进行测试。
话虽如此,在下面,您可以找到如何模拟数据库调用并测试一些基本功能。您将需要安装
pytest-assyncio
才能使其工作。We can mock the database calls, however there isn't much to test when doing that. Your functions simply read/write some data, there isn't much logic or conditionals to verify. My recommendation would be to spin up a Postgres instance in a Docker container alongside your tests and test by hitting that.
With that being said, below you can find how to mock your database calls and test some basic functionality. You will need to install
pytest-asyncio
to get this to work.