从pytest-pgsql获取psycopg2`连接`
为什么我要这样做,
我想在一个名为datastore
的Python类背后的数据库上抽象一些操作。这将具有诸如get_last_update_for_user(用户名:str) - >日期
将使用数据库了解任何SQL的任何人抽象。
我希望dataStore
的构造函数将Psycopg2 连接
对象作为参数,并使用它来连接到相关数据库。创建连接
对象的责任将属于调用代码。
我的理解是,Psycopg2是Python的Perstrant Postgres数据库驱动程序,也是一个合理的选择。
测试
我想对诸如get_last_update_for_user
之类的方法进行单元测试,以确保我的查询表现出我的期望(尤其是对于更复杂的查询)。为此,我需要设置数据库作为测试固定装置。
我正在尝试使用Pytest-PGSQL来做到这一点。我的理解是,这使用Psycopg2作为驱动程序。但是,我无法确定如何获得Psycopg2 连接
对象。我只能得到sqlalchemy对象。例如,以下
import pytest_pgsql
def test_foo(postgresql_db: pytest_pgsql.PostgreSQLTestDB):
with postgresql_db.engine.connect() as conn:
print(conn)
conn.cursor()
gt; 并提高异常:attributeError:'connection'connection'
将打印< sqlalchemy.engine.base.base.connection对象在0x7F983AA503A0 &
- 是否可以从
pytest-pgsql
获得psycopg2连接
对象? - 我应该考虑不同的测试固定装置吗? (由于限制了Psycopg版本3,因此不热衷于
pytest-postgresql
- 。 ?
Why I am trying to do this
I want to abstract some operations on a database behind a python class called DataStore
. This will have methods such as get_last_update_for_user(username: str) -> date
that abstract away the need for anyone using the database to understand any SQL.
I would like the constructor of DataStore
to take a psycopg2 connection
object as an argument, and use that to connect to the relevant database. Responsibility for creating the connection
object will lie with the calling code.
My understanding is that psycopg2 is a performant Postgres database driver for python and a reasonable option for this.
Testing
I want to have unit tests for methods such as get_last_update_for_user
, to ensure that my queries are behaving as I expect (particularly for more complex queries). To do so I need to set up a database as a test fixture.
I am trying to do this using pytest-pgsql. My understanding is that this uses psycopg2 as its driver. However, I am not able to work out how to get a psycopg2 connection
object. I am only able to get SQLAlchemy objects. e.g. the following
import pytest_pgsql
def test_foo(postgresql_db: pytest_pgsql.PostgreSQLTestDB):
with postgresql_db.engine.connect() as conn:
print(conn)
conn.cursor()
will print <sqlalchemy.engine.base.Connection object at 0x7f983aa503a0>
and raise an exception: AttributeError: 'Connection' object has no attribute 'cursor'
Questions
- Is it possible to get a psycopg2
connection
object frompytest-pgsql
? - Is there a different test fixture I should consider instead? (Not keen on
pytest-postgresql
because of the restriction to psycopg version 3.) - Is it a design error to pass a connection object from a specific driver to my
DataStore
wrapper class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论