测试 postgres 数据库 python

testing postgres db python

我不知道如何测试我的存储库。

我想确定我真的将对象及其所有参数保存到数据库中,并且当我执行我的 SQL 语句时,我确实收到了我应该收到的东西。

但是,我不能把 "CREATE TABLE test_table" 放在单元测试用例的 setUp 方法中,因为它会被创建多次(同一个测试用例的测试是并行运行的)。所以,只要我在同一个 class 中创建了 2 个方法,它们需要在同一个 table 上工作,它不会工作(tables 的名称冲突)

同样,我不能放置 "CREATE TABLE test_table" setUpModule,因为,现在 table 被创建一次,但是由于测试是并行运行的,没有什么可以阻止插入同一个对象多次进入我的 table,这打破了某些字段的唯一性约束。

同样,我不能在每个方法中都"CREATE SCHEMA some_random_schema_name",因为我需要为给定的数据库全局"SET search_path TO ...",所以并行运行的每个方法都会受到影响。

我看到的唯一方法是为每个测试创建 "CREATE DATABASE",并使用唯一的名称,并建立到每个数据库的单独连接。这看起来非常浪费。有没有更好的方法?

此外,我无法在内存中使用 SQLite,因为我需要测试 PostgreSQL。

最好的解决方案是使用 testing.postgresql 模块。这会在 user-space 中启动一个数据库,然后在 运行 的末尾再次删除它。您可以将以下内容放入单元测试套件中 - 在 setUpsetUpClasssetUpModule 中 - 取决于您想要的持久性:

import testing.postgresql

def setUp(self):
    self.postgresql = testing.postgresql.Postgresql(port=7654)
    # Get the url to connect to with psycopg2 or equivalent
    print(self.postgresql.url())

def tearDown(self):
    self.postgresql.stop()

如果您希望数据库持续 between/after 测试,您可以 运行 使用 base_dir 选项设置一个目录 - 这将防止它在关闭后被删除:

name = "testdb"
port = "5678"
path = "/tmp/my_test_db"
testing.postgresql.Postgresql(name=name, port=port, base_dir=path)

在测试之外,它也可以用作上下文管理器,当 with 块退出时它会自动清理并关闭:

with testing.postgresql.Postgresql(port=7654) as psql:
    # do something here