|
| 1 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +# or more contributor license agreements. See the NOTICE file |
| 3 | +# distributed with this work for additional information |
| 4 | +# regarding copyright ownership. The ASF licenses this file |
| 5 | +# to you under the Apache License, Version 2.0 (the |
| 6 | +# "License"); you may not use this file except in compliance |
| 7 | +# with the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, |
| 12 | +# software distributed under the License is distributed on an |
| 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +# KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations |
| 16 | +# under the License. |
| 17 | +"""Tests for migration ``da0e3f0081bf_enforce_oauth2_token_uniqueness``. |
| 18 | +
|
| 19 | +Runs the migration's ``upgrade()`` and ``downgrade()`` against an |
| 20 | +in-memory SQLite engine seeded with pre-existing duplicate |
| 21 | +(user_id, database_id) rows -- the state a deployment could be in today, |
| 22 | +since the prior plain index never stopped them from accumulating. |
| 23 | +""" |
| 24 | + |
| 25 | +from __future__ import annotations |
| 26 | + |
| 27 | +from importlib import import_module |
| 28 | + |
| 29 | +import pytest |
| 30 | +from alembic.migration import MigrationContext |
| 31 | +from alembic.operations import Operations |
| 32 | +from sqlalchemy import ( |
| 33 | + Column, |
| 34 | + create_engine, |
| 35 | + inspect, |
| 36 | + Integer, |
| 37 | + MetaData, |
| 38 | + select, |
| 39 | + Table, |
| 40 | +) |
| 41 | +from sqlalchemy.engine import Engine |
| 42 | +from sqlalchemy.exc import IntegrityError |
| 43 | + |
| 44 | +migration = import_module( |
| 45 | + "superset.migrations.versions." |
| 46 | + "2026-08-07_09-00_da0e3f0081bf_enforce_oauth2_token_uniqueness" |
| 47 | +) |
| 48 | + |
| 49 | +TABLE_NAME: str = migration.TABLE_NAME # "database_user_oauth2_tokens" |
| 50 | +INDEX_NAME: str = migration.INDEX_NAME # "idx_user_id_database_id" |
| 51 | + |
| 52 | + |
| 53 | +@pytest.fixture |
| 54 | +def engine() -> Engine: |
| 55 | + """In-memory SQLite seeded with a minimal pre-migration token table, |
| 56 | + including duplicate (user_id, database_id) rows -- id 2 and id 3 both |
| 57 | + belong to user 1 + database 10, which the plain index never prevented. |
| 58 | + """ |
| 59 | + engine = create_engine("sqlite:///:memory:", future=True) |
| 60 | + md = MetaData() |
| 61 | + table = Table( |
| 62 | + TABLE_NAME, |
| 63 | + md, |
| 64 | + Column("id", Integer, primary_key=True), |
| 65 | + Column("user_id", Integer, nullable=False), |
| 66 | + Column("database_id", Integer, nullable=False), |
| 67 | + ) |
| 68 | + md.create_all(engine) |
| 69 | + |
| 70 | + with engine.begin() as conn: |
| 71 | + conn.execute( |
| 72 | + table.insert(), |
| 73 | + [ |
| 74 | + {"id": 1, "user_id": 1, "database_id": 20}, |
| 75 | + {"id": 2, "user_id": 1, "database_id": 10}, |
| 76 | + {"id": 3, "user_id": 1, "database_id": 10}, |
| 77 | + {"id": 4, "user_id": 2, "database_id": 10}, |
| 78 | + ], |
| 79 | + ) |
| 80 | + |
| 81 | + return engine |
| 82 | + |
| 83 | + |
| 84 | +def _indexes(engine: Engine) -> dict[str, bool]: |
| 85 | + """Map of index name -> ``unique`` flag on the target table.""" |
| 86 | + return {ix["name"]: ix["unique"] for ix in inspect(engine).get_indexes(TABLE_NAME)} |
| 87 | + |
| 88 | + |
| 89 | +def _rows(engine: Engine) -> list[tuple[int, int, int]]: |
| 90 | + with engine.begin() as conn: |
| 91 | + table = Table(TABLE_NAME, MetaData(), autoload_with=conn) |
| 92 | + return sorted( |
| 93 | + (r.id, r.user_id, r.database_id) |
| 94 | + for r in conn.execute(select(table)).fetchall() |
| 95 | + ) |
| 96 | + |
| 97 | + |
| 98 | +def test_upgrade_deletes_duplicates_keeping_highest_id(engine: Engine) -> None: |
| 99 | + """Only the highest-id row survives per (user_id, database_id) pair; |
| 100 | + unrelated pairs are untouched. |
| 101 | + """ |
| 102 | + with engine.begin() as conn: |
| 103 | + ctx = MigrationContext.configure(conn) |
| 104 | + with Operations.context(ctx): |
| 105 | + migration.upgrade() |
| 106 | + |
| 107 | + assert _rows(engine) == [ |
| 108 | + (1, 1, 20), |
| 109 | + (3, 1, 10), |
| 110 | + (4, 2, 10), |
| 111 | + ], "upgrade() must keep only the highest-id row per duplicate pair" |
| 112 | + |
| 113 | + |
| 114 | +def test_upgrade_makes_the_index_unique(engine: Engine) -> None: |
| 115 | + """upgrade() replaces the plain lookup index with a unique one.""" |
| 116 | + with engine.begin() as conn: |
| 117 | + ctx = MigrationContext.configure(conn) |
| 118 | + with Operations.context(ctx): |
| 119 | + migration.upgrade() |
| 120 | + |
| 121 | + assert _indexes(engine) == {INDEX_NAME: True} |
| 122 | + |
| 123 | + |
| 124 | +def test_upgrade_index_rejects_new_duplicates(engine: Engine) -> None: |
| 125 | + """After upgrade(), inserting a second row for an existing |
| 126 | + (user_id, database_id) pair is rejected at the DB level. |
| 127 | + """ |
| 128 | + with engine.begin() as conn: |
| 129 | + ctx = MigrationContext.configure(conn) |
| 130 | + with Operations.context(ctx): |
| 131 | + migration.upgrade() |
| 132 | + |
| 133 | + table = Table(TABLE_NAME, MetaData(), autoload_with=engine) |
| 134 | + with pytest.raises(IntegrityError): |
| 135 | + with engine.begin() as conn: |
| 136 | + conn.execute(table.insert().values(id=99, user_id=1, database_id=20)) |
| 137 | + |
| 138 | + |
| 139 | +def test_downgrade_restores_a_plain_non_unique_index(engine: Engine) -> None: |
| 140 | + """downgrade() drops the unique index and recreates a plain one -- |
| 141 | + the dedupe deletions from upgrade() are not reversed, since those rows |
| 142 | + already violated the single-token-per-pair invariant the application |
| 143 | + assumed. |
| 144 | + """ |
| 145 | + with engine.begin() as conn: |
| 146 | + ctx = MigrationContext.configure(conn) |
| 147 | + with Operations.context(ctx): |
| 148 | + migration.upgrade() |
| 149 | + migration.downgrade() |
| 150 | + |
| 151 | + assert _indexes(engine) == {INDEX_NAME: False} |
| 152 | + assert _rows(engine) == [ |
| 153 | + (1, 1, 20), |
| 154 | + (3, 1, 10), |
| 155 | + (4, 2, 10), |
| 156 | + ] |
| 157 | + |
| 158 | + # Now that the index is plain again, duplicates are allowed once more. |
| 159 | + table = Table(TABLE_NAME, MetaData(), autoload_with=engine) |
| 160 | + with engine.begin() as conn: |
| 161 | + conn.execute(table.insert().values(id=99, user_id=1, database_id=20)) |
| 162 | + assert (99, 1, 20) in _rows(engine) |
| 163 | + |
| 164 | + |
| 165 | +def test_upgrade_is_idempotent(engine: Engine) -> None: |
| 166 | + """``create_index``/``drop_index`` are skip-if-exists; running |
| 167 | + ``upgrade()`` twice must not raise. |
| 168 | + """ |
| 169 | + with engine.begin() as conn: |
| 170 | + ctx = MigrationContext.configure(conn) |
| 171 | + with Operations.context(ctx): |
| 172 | + migration.upgrade() |
| 173 | + migration.upgrade() |
0 commit comments