Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(tests): add engine.dispose() / db.reset() cleanup to journal quality tests (#3760)

LearningCircuite9e45ce17462
diff --git a/tests/advanced_search_system/filters/test_journal_reputation_filter.py b/tests/advanced_search_system/filters/test_journal_reputation_filter.py
index d91c246676..bd2b76c0e7 100644
--- a/tests/advanced_search_system/filters/test_journal_reputation_filter.py
+++ b/tests/advanced_search_system/filters/test_journal_reputation_filter.py
@@ -1003,7 +1003,7 @@ class TestTier4SettingWiring:
quality_reanalysis_period=timedelta(days=365),
)
- return filter_obj, mock_model, mock_engine
+ return filter_obj, mock_model, mock_engine, empty_db
def test_tier4_disabled_by_default_does_not_call_llm(self):
"""With the setting OFF, an unknown journal should fall through
@@ -1012,52 +1012,58 @@ class TestTier4SettingWiring:
hardcoded `_enable_tier4 = False` which made the setting unreachable;
now the setting is the only knob.
"""
- filter_obj, mock_model, mock_engine = self._build_filter(
+ filter_obj, mock_model, mock_engine, empty_db = self._build_filter(
enable_llm=False
)
- with self._setting_patcher(enable_llm=False):
- # __score_journal now returns (score, source_tag). The tag
- # identifies which tier produced the score for rendering;
- # quality itself is resolved live, not frozen on Paper.
- score, source_tag = (
- filter_obj._JournalReputationFilter__score_journal(
- "Some Unknown Journal",
- {"journal_ref": "Some Unknown Journal"},
+ try:
+ with self._setting_patcher(enable_llm=False):
+ # __score_journal now returns (score, source_tag). The tag
+ # identifies which tier produced the score for rendering;
+ # quality itself is resolved live, not frozen on Paper.
+ score, source_tag = (
+ filter_obj._JournalReputationFilter__score_journal(
+ "Some Unknown Journal",
+ {"journal_ref": "Some Unknown Journal"},
+ )
)
- )
- # Real Tier 1/2/3 ran against an empty DB → all returned None.
- # Tier 4 is gated off → __score_journal exits via the
- # low-confidence branch, returning 3 (below default threshold).
- assert score == 3
- assert source_tag == "low_confidence"
- # The actual external boundary: the LLM was never invoked.
- mock_model.invoke.assert_not_called()
- # SearXNG was never queried either.
- mock_engine.run.assert_not_called()
+ # Real Tier 1/2/3 ran against an empty DB → all returned None.
+ # Tier 4 is gated off → __score_journal exits via the
+ # low-confidence branch, returning 3 (below default threshold).
+ assert score == 3
+ assert source_tag == "low_confidence"
+ # The actual external boundary: the LLM was never invoked.
+ mock_model.invoke.assert_not_called()
+ # SearXNG was never queried either.
+ mock_engine.run.assert_not_called()
+ finally:
+ empty_db.reset()
def test_tier4_enabled_invokes_llm_for_unknown_journal(self):
"""With the setting ON, the same unknown journal should reach
Tier 4 — the LLM gets called and we get back the parsed score.
"""
- filter_obj, mock_model, mock_engine = self._build_filter(
+ filter_obj, mock_model, mock_engine, empty_db = self._build_filter(
enable_llm=True
)
- with self._setting_patcher(enable_llm=True):
- score, source_tag = (
- filter_obj._JournalReputationFilter__score_journal(
- "Some Unknown Journal",
- {"journal_ref": "Some Unknown Journal"},
+ try:
+ with self._setting_patcher(enable_llm=True):
+ score, source_tag = (
+ filter_obj._JournalReputationFilter__score_journal(
+ "Some Unknown Journal",
+ {"journal_ref": "Some Unknown Journal"},
+ )
)
- )
- # Real Tier 1/2/3 missed → real Tier 4 ran → mocked LLM returned 8.
- assert score == 8
- assert source_tag == "llm"
- assert mock_model.invoke.call_count >= 1
- assert mock_engine.run.call_count >= 1
+ # Real Tier 1/2/3 missed → real Tier 4 ran → mocked LLM returned 8.
+ assert score == 8
+ assert source_tag == "llm"
+ assert mock_model.invoke.call_count >= 1
+ assert mock_engine.run.call_count >= 1
+ finally:
+ empty_db.reset()
class TestLlmCacheWriteUsesNfkcNormalization:
diff --git a/tests/database/test_journal_rebuild_data_preservation.py b/tests/database/test_journal_rebuild_data_preservation.py
index 029bfa198c..6d3ef055c7 100644
--- a/tests/database/test_journal_rebuild_data_preservation.py
+++ b/tests/database/test_journal_rebuild_data_preservation.py
@@ -72,42 +72,48 @@ def _seed(engine, n: int) -> list[tuple[str, int]]:
def test_all_rows_survive_the_chain_with_correct_backfill():
engine = _make_engine()
- Base.metadata.create_all(engine)
- seed_rows = _seed(engine, 100)
+ try:
+ Base.metadata.create_all(engine)
+ seed_rows = _seed(engine, 100)
- # Wipe any name_lower the ORM default might have set so the backfill
- # branch is the one under test.
- with engine.begin() as conn:
- conn.execute(text("UPDATE journals SET name_lower = NULL"))
+ # Wipe any name_lower the ORM default might have set so the backfill
+ # branch is the one under test.
+ with engine.begin() as conn:
+ conn.execute(text("UPDATE journals SET name_lower = NULL"))
- run_migrations(engine)
+ run_migrations(engine)
- # 100 rows still there; name / quality_analysis_time preserved;
- # name_lower backfilled correctly.
- with engine.begin() as conn:
- actual = conn.execute(
- text(
- "SELECT name, name_lower, quality_analysis_time "
- "FROM journals ORDER BY id"
- )
- ).all()
-
- assert len(actual) == len(seed_rows), (
- f"Row count regression: {len(actual)} vs {len(seed_rows)}"
- )
- for (seed_name, seed_t), row in zip(seed_rows, actual):
- assert row.name == seed_name
- assert row.name_lower == _expected_name_lower(seed_name)
- assert row.quality_analysis_time == seed_t
+ # 100 rows still there; name / quality_analysis_time preserved;
+ # name_lower backfilled correctly.
+ with engine.begin() as conn:
+ actual = conn.execute(
+ text(
+ "SELECT name, name_lower, quality_analysis_time "
+ "FROM journals ORDER BY id"
+ )
+ ).all()
+
+ assert len(actual) == len(seed_rows), (
+ f"Row count regression: {len(actual)} vs {len(seed_rows)}"
+ )
+ for (seed_name, seed_t), row in zip(seed_rows, actual):
+ assert row.name == seed_name
+ assert row.name_lower == _expected_name_lower(seed_name)
+ assert row.quality_analysis_time == seed_t
+ finally:
+ engine.dispose()
def test_no_orphan_tmp_table_after_migration():
"""Alembic's batch rebuild must not leave ``_alembic_tmp_journals``."""
engine = _make_engine()
- Base.metadata.create_all(engine)
- _seed(engine, 10)
- run_migrations(engine)
- insp = inspect(engine)
- table_names = set(insp.get_table_names())
- orphans = {t for t in table_names if t.startswith("_alembic_tmp_")}
- assert not orphans, f"Orphan rebuild tables remain: {orphans}"
+ try:
+ Base.metadata.create_all(engine)
+ _seed(engine, 10)
+ run_migrations(engine)
+ insp = inspect(engine)
+ table_names = set(insp.get_table_names())
+ orphans = {t for t in table_names if t.startswith("_alembic_tmp_")}
+ assert not orphans, f"Orphan rebuild tables remain: {orphans}"
+ finally:
+ engine.dispose()
diff --git a/tests/integration/test_journal_quality_release_gate.py b/tests/integration/test_journal_quality_release_gate.py
index 91c434da20..3dc21167c8 100644
--- a/tests/integration/test_journal_quality_release_gate.py
+++ b/tests/integration/test_journal_quality_release_gate.py
@@ -325,52 +325,55 @@ def test_build_journal_quality_db(downloaded_data_dir: Path):
assert db_file.exists()
engine = create_engine(f"sqlite:///{db_file}")
- with engine.connect() as conn:
- # 1. Source table populated.
- n_sources = conn.execute(
- select(func.count()).select_from(Source)
- ).scalar()
- assert n_sources >= MIN_OPENALEX_SOURCES, (
- f"Source row count below minimum: {n_sources}"
- )
-
- # 2. cited_by_count populated for at least some rows (it's
- # NULL on DOAJ-only entries by design).
- n_with_citations = conn.execute(
- select(func.count())
- .select_from(Source)
- .where(Source.cited_by_count.is_not(None))
- ).scalar()
- assert n_with_citations > 0, (
- "cited_by_count is NULL for every source — either the "
- "OpenAlex API stopped exposing the field or the openalex.py "
- "data source loader regressed."
- )
-
- # 3. Quartile post-pass ran and assigned every bucket.
- quartiles = {
- row[0]
- for row in conn.execute(
- select(Source.quartile)
- .where(Source.quartile.is_not(None))
- .distinct()
- ).all()
- }
- assert quartiles == {"Q1", "Q2", "Q3", "Q4"}, (
- f"Quartile buckets not all populated: got {quartiles}"
- )
-
- # 4. Predatory list loaded into its dedicated table.
- n_pred = conn.execute(
- select(func.count()).select_from(PredatoryJournal)
- ).scalar()
- assert n_pred >= MIN_PREDATORY_JOURNALS
-
- # 5. Institutions loaded (used by Tier 3.5 affiliation salvage).
- n_inst = conn.execute(
- select(func.count()).select_from(Institution)
- ).scalar()
- assert n_inst >= MIN_INSTITUTIONS
+ try:
+ with engine.connect() as conn:
+ # 1. Source table populated.
+ n_sources = conn.execute(
+ select(func.count()).select_from(Source)
+ ).scalar()
+ assert n_sources >= MIN_OPENALEX_SOURCES, (
+ f"Source row count below minimum: {n_sources}"
+ )
+
+ # 2. cited_by_count populated for at least some rows (it's
+ # NULL on DOAJ-only entries by design).
+ n_with_citations = conn.execute(
+ select(func.count())
+ .select_from(Source)
+ .where(Source.cited_by_count.is_not(None))
+ ).scalar()
+ assert n_with_citations > 0, (
+ "cited_by_count is NULL for every source — either the "
+ "OpenAlex API stopped exposing the field or the openalex.py "
+ "data source loader regressed."
+ )
+
+ # 3. Quartile post-pass ran and assigned every bucket.
+ quartiles = {
+ row[0]
+ for row in conn.execute(
+ select(Source.quartile)
+ .where(Source.quartile.is_not(None))
+ .distinct()
+ ).all()
+ }
+ assert quartiles == {"Q1", "Q2", "Q3", "Q4"}, (
+ f"Quartile buckets not all populated: got {quartiles}"
+ )
+
+ # 4. Predatory list loaded into its dedicated table.
+ n_pred = conn.execute(
+ select(func.count()).select_from(PredatoryJournal)
+ ).scalar()
+ assert n_pred >= MIN_PREDATORY_JOURNALS
+
+ # 5. Institutions loaded (used by Tier 3.5 affiliation salvage).
+ n_inst = conn.execute(
+ select(func.count()).select_from(Institution)
+ ).scalar()
+ assert n_inst >= MIN_INSTITUTIONS
+ finally:
+ engine.dispose()
def test_runtime_accessor_can_score_real_journal(
@@ -394,15 +397,18 @@ def test_runtime_accessor_can_score_real_journal(
db._engine = create_engine(f"sqlite:///{db_file}")
db._SessionLocal = sessionmaker(bind=db._engine, expire_on_commit=False)
- nature = db.lookup_openalex(name="Nature")
- assert nature is not None, "Nature not found in built DB"
- assert nature["h_index"] is not None and nature["h_index"] > 1000
- # Field shape contract used by the filter (`is_in_doaj`,
- # `publisher`, `issn_l`, `openalex_source_id`).
- assert "is_in_doaj" in nature
- assert "publisher" in nature
- assert "issn_l" in nature
- assert "openalex_source_id" in nature
+ try:
+ nature = db.lookup_openalex(name="Nature")
+ assert nature is not None, "Nature not found in built DB"
+ assert nature["h_index"] is not None and nature["h_index"] > 1000
+ # Field shape contract used by the filter (`is_in_doaj`,
+ # `publisher`, `issn_l`, `openalex_source_id`).
+ assert "is_in_doaj" in nature
+ assert "publisher" in nature
+ assert "issn_l" in nature
+ assert "openalex_source_id" in nature
+ finally:
+ db.reset()
def test_dashboard_queries_against_real_db(downloaded_data_dir: Path):
@@ -425,41 +431,46 @@ def test_dashboard_queries_against_real_db(downloaded_data_dir: Path):
db._engine = create_engine(f"sqlite:///{db_file}")
db._SessionLocal = sessionmaker(bind=db._engine, expire_on_commit=False)
- # 1. Summary card on the dashboard top.
- summary = db.get_summary()
- assert summary["total"] >= MIN_OPENALEX_SOURCES
- assert summary["avg_quality"] is not None
- assert summary["doaj_count"] >= MIN_DOAJ_JOURNALS // 2
- assert summary["predatory_count"] >= MIN_PREDATORY_JOURNALS
-
- # 2. Quality histogram (powers the bar chart).
- qdist = db.get_quality_distribution()
- assert qdist, "quality distribution is empty"
- assert all(int(k) >= 1 and int(k) <= 10 for k in qdist.keys())
- assert sum(qdist.values()) >= MIN_OPENALEX_SOURCES // 2
-
- # 3. Source breakdown (openalex / doaj / predatory / llm).
- sdist = db.get_source_distribution()
- assert "openalex" in sdist
- assert sdist["openalex"] >= MIN_OPENALEX_SOURCES // 2
-
- # 4. Default first page of the journals table.
- journals, total = db.get_journals_page(page=1, per_page=50)
- assert total >= MIN_OPENALEX_SOURCES
- assert len(journals) == 50
- # Default sort=quality desc — first page should be Q1 / elite.
- assert journals[0]["quality"] >= journals[-1]["quality"]
- # Field shape consumed by the dashboard JS.
- j0 = journals[0]
- for key in ("name", "quality", "h_index", "score_source"):
- assert key in j0, f"dashboard row missing field: {key}"
-
- # 5. Search filter — "nature" should always match a real journal.
- journals, total = db.get_journals_page(page=1, per_page=10, search="nature")
- assert total > 0
- assert any("nature" in (j["name"] or "").lower() for j in journals)
-
- # 6. Tier filter — elite tier should always have entries given the
- # ~280K-row corpus.
- _, total_elite = db.get_journals_page(page=1, per_page=10, tier="elite")
- assert total_elite > 0
+ try:
+ # 1. Summary card on the dashboard top.
+ summary = db.get_summary()
+ assert summary["total"] >= MIN_OPENALEX_SOURCES
+ assert summary["avg_quality"] is not None
+ assert summary["doaj_count"] >= MIN_DOAJ_JOURNALS // 2
+ assert summary["predatory_count"] >= MIN_PREDATORY_JOURNALS
+
+ # 2. Quality histogram (powers the bar chart).
+ qdist = db.get_quality_distribution()
+ assert qdist, "quality distribution is empty"
+ assert all(int(k) >= 1 and int(k) <= 10 for k in qdist.keys())
+ assert sum(qdist.values()) >= MIN_OPENALEX_SOURCES // 2
+
+ # 3. Source breakdown (openalex / doaj / predatory / llm).
+ sdist = db.get_source_distribution()
+ assert "openalex" in sdist
+ assert sdist["openalex"] >= MIN_OPENALEX_SOURCES // 2
+
+ # 4. Default first page of the journals table.
+ journals, total = db.get_journals_page(page=1, per_page=50)
+ assert total >= MIN_OPENALEX_SOURCES
+ assert len(journals) == 50
+ # Default sort=quality desc — first page should be Q1 / elite.
+ assert journals[0]["quality"] >= journals[-1]["quality"]
+ # Field shape consumed by the dashboard JS.
+ j0 = journals[0]
+ for key in ("name", "quality", "h_index", "score_source"):
+ assert key in j0, f"dashboard row missing field: {key}"
+
+ # 5. Search filter — "nature" should always match a real journal.
+ journals, total = db.get_journals_page(
+ page=1, per_page=10, search="nature"
+ )
+ assert total > 0
+ assert any("nature" in (j["name"] or "").lower() for j in journals)
+
+ # 6. Tier filter — elite tier should always have entries given the
+ # ~280K-row corpus.
+ _, total_elite = db.get_journals_page(page=1, per_page=10, tier="elite")
+ assert total_elite > 0
+ finally:
+ db.reset()
diff --git a/tests/journal_quality/test_db.py b/tests/journal_quality/test_db.py
index 384cdd73fe..33f07519df 100644
--- a/tests/journal_quality/test_db.py
+++ b/tests/journal_quality/test_db.py
@@ -285,17 +285,20 @@ class TestBuildReferenceDb:
)
engine = create_engine("sqlite:///:memory:")
- JournalQualityBase.metadata.create_all(engine)
- indexed_cols = {
- col
- for idx in inspect(engine).get_indexes("sources")
- for col in idx["column_names"]
- }
- assert "score_source" in indexed_cols, (
- "sources.score_source must be indexed — it's a dashboard "
- "filter predicate; without the index the query does a "
- "full-table scan of ~217K rows."
- )
+ try:
+ JournalQualityBase.metadata.create_all(engine)
+ indexed_cols = {
+ col
+ for idx in inspect(engine).get_indexes("sources")
+ for col in idx["column_names"]
+ }
+ assert "score_source" in indexed_cols, (
+ "sources.score_source must be indexed — it's a dashboard "
+ "filter predicate; without the index the query does a "
+ "full-table scan of ~217K rows."
+ )
+ finally:
+ engine.dispose()
def test_score_source_check_constraint_rejects_invalid(self):
"""CHECK constraint on ``sources.score_source`` must reject
@@ -317,35 +320,40 @@ class TestBuildReferenceDb:
# round-trip.
JournalQualityBase.metadata.create_all(engine)
- # Minimal columns needed for a valid row — the NOT NULL flags
- # come from the model, not this test. is_in_doaj / has_doaj_seal
- # / is_predatory all default to False but the insert still has
- # to satisfy NOT NULL.
- cols = (
- "name, name_lower, is_in_doaj, has_doaj_seal, "
- "is_predatory, score_source"
- )
-
- with engine.begin() as conn:
- # Happy path: known-valid value goes through.
- conn.execute(
- text(
- f"INSERT INTO sources ({cols}) "
- "VALUES ('Test Journal', 'test journal', "
- "0, 0, 0, 'openalex')"
- )
+ try:
+ # Minimal columns needed for a valid row — the NOT NULL flags
+ # come from the model, not this test. is_in_doaj / has_doaj_seal
+ # / is_predatory all default to False but the insert still has
+ # to satisfy NOT NULL.
+ cols = (
+ "name, name_lower, is_in_doaj, has_doaj_seal, "
+ "is_predatory, score_source"
)
- with engine.begin() as conn:
- with pytest.raises(IntegrityError, match=r"(?i)CHECK|score_source"):
+ with engine.begin() as conn:
+ # Happy path: known-valid value goes through.
conn.execute(
text(
f"INSERT INTO sources ({cols}) "
- "VALUES ('Bad Journal', 'bad journal', "
- "0, 0, 0, 'garbage')"
+ "VALUES ('Test Journal', 'test journal', "
+ "0, 0, 0, 'openalex')"
)
)
+ with engine.begin() as conn:
+ with pytest.raises(
+ IntegrityError, match=r"(?i)CHECK|score_source"
+ ):
+ conn.execute(
+ text(
+ f"INSERT INTO sources ({cols}) "
+ "VALUES ('Bad Journal', 'bad journal', "
+ "0, 0, 0, 'garbage')"
+ )
+ )
+ finally:
+ engine.dispose()
+
def test_built_db_stamps_schema_version(self, tmp_path):
"""``build_db`` must stamp ``PRAGMA user_version`` to the
current ``JOURNAL_QUALITY_SCHEMA_VERSION`` constant. The
@@ -429,13 +437,18 @@ class TestPopulateSources:
"long_pubs": [],
}
engine = self._build_in_memory(sources, {}, pred)
- with sessionmaker(bind=engine)() as s:
- row = s.scalars(
- select(Source).where(Source.name_lower == "fake cloned journal")
- ).first()
- assert row is not None
- assert row.is_predatory is True
- assert row.predatory_source == "stop-predatory-hijacked"
+ try:
+ with sessionmaker(bind=engine)() as s:
+ row = s.scalars(
+ select(Source).where(
+ Source.name_lower == "fake cloned journal"
+ )
+ ).first()
+ assert row is not None
+ assert row.is_predatory is True
+ assert row.predatory_source == "stop-predatory-hijacked"
+ finally:
+ engine.dispose()
def test_doaj_only_journal_inserted(self):
from sqlalchemy import select
@@ -457,16 +470,19 @@ class TestPopulateSources:
"long_pubs": [],
}
engine = self._build_in_memory({}, doaj, pred)
- with sessionmaker(bind=engine)() as s:
- row = s.scalars(
- select(Source).where(
- Source.name_lower == "some small oa journal"
- )
- ).first()
- assert row is not None
- assert row.score_source == "doaj"
- assert row.is_in_doaj is True
- assert row.openalex_source_id is None
+ try:
+ with sessionmaker(bind=engine)() as s:
+ row = s.scalars(
+ select(Source).where(
+ Source.name_lower == "some small oa journal"
+ )
+ ).first()
+ assert row is not None
+ assert row.score_source == "doaj"
+ assert row.is_in_doaj is True
+ assert row.openalex_source_id is None
+ finally:
+ engine.dispose()
def test_quartile_derivation_global_per_type(self):
"""Sources are bucketed Q1–Q4 by cited_by_count percentile within
@@ -500,39 +516,47 @@ class TestPopulateSources:
}
engine = self._build_in_memory(sources, {}, pred)
- with sessionmaker(bind=engine)() as s:
- rows = s.scalars(
- select(Source).order_by(Source.cited_by_count)
- ).all()
-
- quartiled = [r for r in rows if r.cited_by_count is not None]
- assert len(quartiled) == 8
-
- # Highest two should be Q1, lowest two should be Q4.
- assert quartiled[-1].quartile == "Q1"
- assert quartiled[-2].quartile == "Q1"
- assert quartiled[0].quartile == "Q4"
- assert quartiled[1].quartile == "Q4"
-
- # Every quartile bucket is represented.
- assert {r.quartile for r in quartiled} == {"Q1", "Q2", "Q3", "Q4"}
-
- # NULL cited_by_count → NULL quartile.
- citationless = s.scalars(
- select(Source).where(Source.name == "Citationless Journal")
- ).first()
- assert citationless is not None
- assert citationless.quartile is None
-
- # Quartile now feeds into quality (fixed in Round 5 review):
- # Q1 → 8 (STRONG), Q2 → 7, Q3 → 6, Q4 → 5. h_index=5 is below
- # the quartile-bump threshold so Q1 does not promote to 10.
- quartile_to_quality = {"Q1": 8, "Q2": 7, "Q3": 6, "Q4": 5}
- for r in quartiled:
- assert r.quality == quartile_to_quality[r.quartile], (
- f"Journal with quartile={r.quartile} should score "
- f"{quartile_to_quality[r.quartile]} not {r.quality}"
- )
+ try:
+ with sessionmaker(bind=engine)() as s:
+ rows = s.scalars(
+ select(Source).order_by(Source.cited_by_count)
+ ).all()
+
+ quartiled = [r for r in rows if r.cited_by_count is not None]
+ assert len(quartiled) == 8
+
+ # Highest two should be Q1, lowest two should be Q4.
+ assert quartiled[-1].quartile == "Q1"
+ assert quartiled[-2].quartile == "Q1"
+ assert quartiled[0].quartile == "Q4"
+ assert quartiled[1].quartile == "Q4"
+
+ # Every quartile bucket is represented.
+ assert {r.quartile for r in quartiled} == {
+ "Q1",
+ "Q2",
+ "Q3",
+ "Q4",
+ }
+
+ # NULL cited_by_count → NULL quartile.
+ citationless = s.scalars(
+ select(Source).where(Source.name == "Citationless Journal")
+ ).first()
+ assert citationless is not None
+ assert citationless.quartile is None
+
+ # Quartile now feeds into quality (fixed in Round 5 review):
+ # Q1 → 8 (STRONG), Q2 → 7, Q3 → 6, Q4 → 5. h_index=5 is below
+ # the quartile-bump threshold so Q1 does not promote to 10.
+ quartile_to_quality = {"Q1": 8, "Q2": 7, "Q3": 6, "Q4": 5}
+ for r in quartiled:
+ assert r.quality == quartile_to_quality[r.quartile], (
+ f"Journal with quartile={r.quartile} should score "
+ f"{quartile_to_quality[r.quartile]} not {r.quality}"
+ )
+ finally:
+ engine.dispose()
def test_quartile_separates_journals_from_conferences(self):
"""Journal pool and conference pool are percentile-binned
@@ -568,15 +592,18 @@ class TestPopulateSources:
"long_pubs": [],
}
engine = self._build_in_memory(sources, {}, pred)
- with sessionmaker(bind=engine)() as s:
- rows = s.scalars(select(Source)).all()
- by_name = {r.name: r for r in rows}
- # Pool size 1 → percentile 0/1=0.0 → Q4 (lowest bucket).
- # The point of the test is that they're processed in
- # separate pools, not merged: the conference's huge cb does
- # NOT affect the journal's quartile.
- assert by_name["Solo Journal"].quartile is not None
- assert by_name["Solo Conference"].quartile is not None
+ try:
+ with sessionmaker(bind=engine)() as s:
+ rows = s.scalars(select(Source)).all()
+ by_name = {r.name: r for r in rows}
+ # Pool size 1 → percentile 0/1=0.0 → Q4 (lowest bucket).
+ # The point of the test is that they're processed in
+ # separate pools, not merged: the conference's huge cb does
+ # NOT affect the journal's quartile.
+ assert by_name["Solo Journal"].quartile is not None
+ assert by_name["Solo Conference"].quartile is not None
+ finally:
+ engine.dispose()
def test_print_and_electronic_issn_both_survive(self):
from sqlalchemy import select
@@ -595,13 +622,16 @@ class TestPopulateSources:
"long_pubs": [],
}
engine = self._build_in_memory(sources, {}, pred)
- with sessionmaker(bind=engine)() as s:
- rows = s.scalars(
- select(Source).where(Source.name_lower == "journal of x")
- ).all()
- # ISSNs are stored in canonical 8-char no-dash form (normalize_issn)
- issns = {r.issn for r in rows}
- assert issns == {"11111111", "22222222"}
+ try:
+ with sessionmaker(bind=engine)() as s:
+ rows = s.scalars(
+ select(Source).where(Source.name_lower == "journal of x")
+ ).all()
+ # ISSNs are stored in canonical 8-char no-dash form (normalize_issn)
+ issns = {r.issn for r in rows}
+ assert issns == {"11111111", "22222222"}
+ finally:
+ engine.dispose()
# ---------------------------------------------------------------------------
diff --git a/tests/journal_quality/test_lookup_institution_keys.py b/tests/journal_quality/test_lookup_institution_keys.py
index cf8c7cfbdd..aa2ba763e3 100644
--- a/tests/journal_quality/test_lookup_institution_keys.py
+++ b/tests/journal_quality/test_lookup_institution_keys.py
@@ -64,14 +64,17 @@ def test_populate_institutions_nfkc_normalizes_name_lower():
}
engine = create_engine("sqlite:///:memory:")
- JournalQualityBase.metadata.create_all(engine)
- Session = sessionmaker(bind=engine)
- with Session() as s:
- _populate_institutions(s, institutions)
- s.commit()
+ try:
+ JournalQualityBase.metadata.create_all(engine)
+ Session = sessionmaker(bind=engine)
+ with Session() as s:
+ _populate_institutions(s, institutions)
+ s.commit()
- with Session() as s:
- rows = s.scalars(
- select(Institution).order_by(Institution.openalex_id)
- ).all()
- assert [r.name_lower for r in rows] == ["university", "university"]
+ with Session() as s:
+ rows = s.scalars(
+ select(Institution).order_by(Institution.openalex_id)
+ ).all()
+ assert [r.name_lower for r in rows] == ["university", "university"]
+ finally:
+ engine.dispose()
diff --git a/tests/research_library/conftest.py b/tests/research_library/conftest.py
index 4ab99a7bcd..a3344bee23 100644
--- a/tests/research_library/conftest.py
+++ b/tests/research_library/conftest.py
@@ -30,7 +30,8 @@ def library_engine():
"""Create an in-memory SQLite database with all library models."""
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(engine)
- return engine
+ yield engine
+ engine.dispose()
@pytest.fixture