从pytest-pgsql获取psycopg2`连接`

发布于 2025-01-24 07:39:55 字数 1159 浏览 3 评论 0原文

为什么我要这样做,

我想在一个名为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 &

  1. 是否可以从pytest-pgsql获得psycopg2 连接对象?
  2. 我应该考虑不同的测试固定装置吗? (由于限制了Psycopg版本3,因此不热衷于pytest-postgresql
  3. 。 ?

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

  1. Is it possible to get a psycopg2 connection object from pytest-pgsql?
  2. Is there a different test fixture I should consider instead? (Not keen on pytest-postgresql because of the restriction to psycopg version 3.)
  3. Is it a design error to pass a connection object from a specific driver to my DataStore wrapper class?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文