← 中文资源

简体中文版本

带隔离数据库的 Pytest 夹具

提供为每个测试创建全新数据库并销毁的 pytest 夹具,使测试互相独立且不受执行顺序影响。

阅读英文原文

实现说明

活动部件是函数 db、test_insert_item。 从 sqlite3 导入了 Iterator——导入清单就是这段代码触碰的库表面。

使用要点

  • 依赖检查:sqlite3、pytest——不是内建的,项目里必须有。
  • 把 db 当作 API:导入它,其余代码可以忽略。

常见问题

它需要从包仓库拿什么?

这些是真实的依赖:sqlite3、pytest。缺了就加载不起来。

入口签名:def db() -> Iterator[sqlite3.Connection]

核心语句

def test_insert_item(db: sqlite3.Connection) -> None:
    db.execute("INSERT INTO items (name) VALUES (?)", ("widget",))
    count = db.execute("SELECT COUNT(*) FROM items").fetchone()[0]
    assert count == 1
def db() -> Iterator[sqlite3.Connection]:
    connection = sqlite3.connect(":memory:")
    connection.execute(
        "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL)"
    )
    try:
        yield connection
    finally:
        connection.close()

代码示例

import sqlite3
from typing import Iterator

import pytest


@pytest.fixture
def db() -> Iterator[sqlite3.Connection]:
    connection = sqlite3.connect(":memory:")
    connection.execute(
        "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL)"
    )
    try:
        yield connection
    finally:
        connection.close()


def test_insert_item(db: sqlite3.Connection) -> None:
    db.execute("INSERT INTO items (name) VALUES (?)", ("widget",))
    count = db.execute("SELECT COUNT(*) FROM items").fetchone()[0]
    assert count == 1