|
2 | 2 | from os import environ |
3 | 3 | from pathlib import Path |
4 | 4 |
|
| 5 | +import asyncpg |
5 | 6 | import numpy as np |
6 | 7 | import pytest |
| 8 | +from confidence import Configuration |
7 | 9 | from testcontainers.postgres import PostgresContainer |
8 | 10 |
|
9 | 11 | from citatio.db import PostgreSQLDatabase, SQLiteDatabase |
@@ -81,16 +83,50 @@ def connect_pgvector(request, monkeypatch): |
81 | 83 | pytest.param('postgresql', marks=pytest.mark.postgresql), |
82 | 84 | ] |
83 | 85 | ) |
84 | | -async def database(request): |
| 86 | +async def database_config(request): |
85 | 87 | match request.param: |
86 | 88 | case 'sqlite': |
87 | | - # create an in-memory database that will be empty after use by design |
88 | | - async with await SQLiteDatabase.connect(':memory:') as db: |
89 | | - yield db |
| 89 | + # use a in-memory sqlite database |
| 90 | + yield Configuration({'database.sqlite': ':memory:'}) |
90 | 91 | case 'postgresql': |
91 | | - # request pgvector connection settings from a named fixture |
92 | | - # (a pytest.param cannot use pytest.mark.usefixtures, it seems) |
| 92 | + # run a session-scope ephemeral database |
93 | 93 | connect = request.getfixturevalue('connect_pgvector') |
| 94 | + yield Configuration({'database': connect}) |
| 95 | + |
| 96 | + |
| 97 | +@pytest.fixture |
| 98 | +async def database_env(monkeypatch, database_config): |
| 99 | + match database_config: |
| 100 | + case {'database.sqlite': ':memory:'}: |
| 101 | + # NB: add quotes to avoid the configuration's format misparsing :memory: |
| 102 | + monkeypatch.setenv('CITATIO_DATABASE_SQLITE', '":memory:"') |
| 103 | + yield |
| 104 | + case {'database.sqlite': fname}: |
| 105 | + monkeypatch.setenv('CITATIO_DATABASE_SQLITE', fname) |
| 106 | + yield |
| 107 | + case {'database': connect}: |
| 108 | + for var, value in connect.items(): |
| 109 | + monkeypatch.setenv(f'CITATIO_DATABASE_{var}'.upper(), str(value)) |
| 110 | + yield |
| 111 | + # empty the database after use |
| 112 | + connection = await asyncpg.connect(**connect) |
| 113 | + await connection.execute(""" |
| 114 | + DELETE FROM labels; |
| 115 | + DELETE FROM functions; |
| 116 | + """) |
| 117 | + await connection.close() |
| 118 | + case _: |
| 119 | + raise ValueError |
| 120 | + |
| 121 | + |
| 122 | +@pytest.fixture |
| 123 | +async def database(database_config): |
| 124 | + match database_config: |
| 125 | + case {'database.sqlite': name}: |
| 126 | + # create an in-memory database that will be empty after use by design |
| 127 | + async with await SQLiteDatabase.connect(name) as db: |
| 128 | + yield db |
| 129 | + case {'database': connect}: |
94 | 130 | async with await PostgreSQLDatabase.connect(**connect) as db: |
95 | 131 | yield db |
96 | 132 | # empty the database after use |
|
0 commit comments