import sqlite3 import pytest from backend.adapters.sqlite import create_db from backend.model.tribe import Tribe from backend.repository.tribe_sqlite_repository import TribeSQLiteRepository from tests.model.fakes import build_tribes def populate_tribes(conn) -> list[Tribe]: cursor = conn.cursor() tribes = build_tribes(3) cursor.executemany( """ INSERT INTO tribes(name, level) VALUES (?, ?) """, [t.to_tuple() for t in tribes], ) conn.commit() return tribes def test_get_tribe(sqlite_conn): create_db(sqlite_conn) prebuild_tribes = populate_tribes(sqlite_conn) name = prebuild_tribes[0].name tribe_repo = TribeSQLiteRepository(sqlite_conn) tribes = tribe_repo.get(name) assert prebuild_tribes[0] == tribes def test_get_tribe_not_exists(sqlite_conn): create_db(sqlite_conn) prebuild_tribes = populate_tribes(sqlite_conn) tribe_repo = TribeSQLiteRepository(sqlite_conn) with pytest.raises(ValueError): tribe_repo.get("Tribe0") def test_list_tribes(sqlite_conn): create_db(sqlite_conn) prebuild_tribes = populate_tribes(sqlite_conn) tribe_repo = TribeSQLiteRepository(sqlite_conn) tribes = tribe_repo.list() assert prebuild_tribes == tribes def test_add_tribe(sqlite_conn): create_db(sqlite_conn) tribe_repo = TribeSQLiteRepository(sqlite_conn) tribe_infos = ("tribe1", "2nd") tribe = Tribe(*tribe_infos) tribe_repo.add(tribe) sqlite_conn.commit() cursor = sqlite_conn.cursor() cursor.execute( """ SELECT * FROM tribes WHERE name=? """, ("tribe1",), ) row = cursor.fetchone() assert row == tribe_infos def test_add_tribe_fail_exists(sqlite_conn): create_db(sqlite_conn) prebuild_tribes = populate_tribes(sqlite_conn) tribe_repo = TribeSQLiteRepository(sqlite_conn) existing_tribe = prebuild_tribes[0] with pytest.raises(sqlite3.IntegrityError): tribe_repo.add(existing_tribe) def test_update_tribe(sqlite_conn): create_db(sqlite_conn) prebuild_tribes = populate_tribes(sqlite_conn) tribe_repo = TribeSQLiteRepository(sqlite_conn) name = prebuild_tribes[0].name new_tribe = Tribe("Tribe0", "Term") tribe_repo.update(name, new_tribe) sqlite_conn.commit() prebuild_tribes[0] = new_tribe assert tribe_repo.list() == prebuild_tribes def test_delete_tribe(sqlite_conn): create_db(sqlite_conn) prebuild_tribes = populate_tribes(sqlite_conn) tribe_repo = TribeSQLiteRepository(sqlite_conn) deleted_tribe = prebuild_tribes.pop() tribe_repo.delete(deleted_tribe) sqlite_conn.commit() assert tribe_repo.list() == prebuild_tribes