ext/python: Fix flaky tests by creating a new db for each test and removing it after the test

This commit is contained in:
Diego Reis 2025-03-21 11:26:46 -03:00
parent f966f7ad0e
commit 3c2bb6c3a8
2 changed files with 33 additions and 3 deletions

Binary file not shown.

View file

@ -1,3 +1,4 @@
import os
import sqlite3 import sqlite3
import pytest import pytest
@ -5,9 +6,38 @@ import pytest
import limbo import limbo
@pytest.fixture(autouse=True)
def setup_database():
db_path = "tests/database.db"
db_wal_path = "tests/database.db-wal"
# Ensure the database file is created fresh for each test
if os.path.exists(db_path):
os.remove(db_path)
if os.path.exists(db_wal_path):
os.remove(db_wal_path)
# Create a new database file
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute("CREATE TABLE users (id INT PRIMARY KEY, username TEXT)")
cursor.execute("INSERT INTO users VALUES (1, 'alice')")
cursor.execute("INSERT INTO users VALUES (2, 'bob')")
conn.commit()
conn.close()
yield db_path
# Cleanup after the test
if os.path.exists(db_path):
os.remove(db_path)
if os.path.exists(db_wal_path):
os.remove(db_wal_path)
@pytest.mark.parametrize("provider", ["sqlite3", "limbo"]) @pytest.mark.parametrize("provider", ["sqlite3", "limbo"])
def test_fetchall_select_all_users(provider): def test_fetchall_select_all_users(provider, setup_database):
conn = connect(provider, "tests/database.db") conn = connect(provider, setup_database)
cursor = conn.cursor() cursor = conn.cursor()
cursor.execute("SELECT * FROM users") cursor.execute("SELECT * FROM users")
@ -76,7 +106,7 @@ def test_commit(provider):
cur.execute(""" cur.execute("""
CREATE TABLE IF NOT EXISTS users_b ( CREATE TABLE IF NOT EXISTS users_b (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL, username TEXT NOT NULL,
email TEXT NOT NULL, email TEXT NOT NULL,
role TEXT NOT NULL, role TEXT NOT NULL,
created_at DATETIME NOT NULL DEFAULT (datetime('now')) created_at DATETIME NOT NULL DEFAULT (datetime('now'))