|
| 1 | +from types import SimpleNamespace |
| 2 | +from unittest.mock import AsyncMock, MagicMock |
| 3 | + |
| 4 | +import pytest |
| 5 | + |
| 6 | +from rhosocial.activerecord.backend.base import StorageBackend |
| 7 | +from rhosocial.activerecord.backend.errors import DatabaseError |
| 8 | +from rhosocial.activerecord.backend.impl.sqlserver import ( |
| 9 | + AsyncSQLServerBackend, |
| 10 | + SQLServerBackend, |
| 11 | + SQLServerExecutionOptions, |
| 12 | +) |
| 13 | +from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig |
| 14 | +from rhosocial.activerecord.backend.options import ExecutionOptions, StatementType |
| 15 | + |
| 16 | + |
| 17 | +SQL = "SELECT {fn UCASE(?)} AS [value], '?' AS [literal]" |
| 18 | +PARAMS = ("{not an ODBC escape}",) |
| 19 | +OPTION_CASES = [ |
| 20 | + pytest.param(SQLServerExecutionOptions(StatementType.DQL, noscan=True), id="true"), |
| 21 | + pytest.param(SQLServerExecutionOptions(StatementType.DQL, noscan=False), id="false"), |
| 22 | + pytest.param(SQLServerExecutionOptions(StatementType.DQL, noscan=None), id="none"), |
| 23 | + pytest.param(ExecutionOptions(StatementType.DQL), id="core"), |
| 24 | +] |
| 25 | + |
| 26 | + |
| 27 | +@pytest.fixture(scope="session", autouse=True) |
| 28 | +def _prepare_read_committed_snapshot(): |
| 29 | + return None |
| 30 | + |
| 31 | + |
| 32 | +@pytest.fixture(autouse=True) |
| 33 | +def block_connections(monkeypatch): |
| 34 | + monkeypatch.setattr( |
| 35 | + SQLServerBackend, "connect", MagicMock(side_effect=AssertionError("Unexpected database connection")) |
| 36 | + ) |
| 37 | + monkeypatch.setattr( |
| 38 | + AsyncSQLServerBackend, "connect", AsyncMock(side_effect=AssertionError("Unexpected database connection")) |
| 39 | + ) |
| 40 | + |
| 41 | + |
| 42 | +class NativeCursor: |
| 43 | + def __init__(self, noscan): |
| 44 | + self._noscan = noscan |
| 45 | + self.accesses = [] |
| 46 | + |
| 47 | + @property |
| 48 | + def noscan(self): |
| 49 | + self.accesses.append(("get",)) |
| 50 | + return self._noscan |
| 51 | + |
| 52 | + @noscan.setter |
| 53 | + def noscan(self, value): |
| 54 | + self.accesses.append(("set", value)) |
| 55 | + self._noscan = value |
| 56 | + |
| 57 | + |
| 58 | +class AsyncCursor: |
| 59 | + def __init__(self, previous, error=None): |
| 60 | + self._impl = NativeCursor(previous) |
| 61 | + self.noscan = "wrapper must not change" |
| 62 | + self.operations = [] |
| 63 | + self.executions = [] |
| 64 | + self.error = error |
| 65 | + self.description = None |
| 66 | + self.rowcount = 0 |
| 67 | + self.lastrowid = None |
| 68 | + self.exit_value = None |
| 69 | + |
| 70 | + async def _run_operation(self, operation, *args): |
| 71 | + self.operations.append((operation, args)) |
| 72 | + return operation(*args) |
| 73 | + |
| 74 | + async def __aenter__(self): |
| 75 | + return self |
| 76 | + |
| 77 | + async def __aexit__(self, exc_type, exc_value, traceback): |
| 78 | + self.exit_value = self._impl._noscan |
| 79 | + |
| 80 | + async def execute(self, sql, params): |
| 81 | + self.executions.append((sql, params, self._impl._noscan, self.noscan)) |
| 82 | + if self.error is not None: |
| 83 | + raise self.error |
| 84 | + |
| 85 | + |
| 86 | +def make_backend(backend_class): |
| 87 | + config = SQLServerConnectionConfig(host="localhost", database="master", username="sa", password="") |
| 88 | + backend = backend_class(connection_config=config) |
| 89 | + backend._connection = object() |
| 90 | + return backend |
| 91 | + |
| 92 | + |
| 93 | +def expected_accesses(noscan, previous): |
| 94 | + return [] if noscan is None else [("get",), ("set", noscan), ("set", previous)] |
| 95 | + |
| 96 | + |
| 97 | +def test_execution_options_default(): |
| 98 | + options = SQLServerExecutionOptions(StatementType.DQL) |
| 99 | + assert isinstance(options, ExecutionOptions) |
| 100 | + assert options.noscan is None |
| 101 | + |
| 102 | + |
| 103 | +@pytest.mark.parametrize("options", OPTION_CASES) |
| 104 | +@pytest.mark.parametrize("fails", [False, True], ids=["success", "error"]) |
| 105 | +@pytest.mark.parametrize("outer", [None, True, False]) |
| 106 | +def test_sync_execution_restores_cursor_and_context(monkeypatch, options, fails, outer): |
| 107 | + backend = make_backend(SQLServerBackend) |
| 108 | + assert backend._execution_noscan.get() is None |
| 109 | + noscan = getattr(options, "noscan", None) |
| 110 | + previous = noscan is not True |
| 111 | + cursor = NativeCursor(previous) |
| 112 | + error = RuntimeError("execution failed") |
| 113 | + executions = [] |
| 114 | + delegated = [] |
| 115 | + |
| 116 | + def execute(sql, params): |
| 117 | + executions.append((sql, params, cursor._noscan)) |
| 118 | + if fails: |
| 119 | + raise error |
| 120 | + |
| 121 | + cursor.execute = execute |
| 122 | + |
| 123 | + def core_execute(self, sql, params, *, options): |
| 124 | + delegated.append((sql, params, options, self._execution_noscan.get())) |
| 125 | + return self._execute_query(cursor, sql, params) |
| 126 | + |
| 127 | + monkeypatch.setattr(StorageBackend, "execute", core_execute) |
| 128 | + token = backend._execution_noscan.set(outer) |
| 129 | + try: |
| 130 | + if fails: |
| 131 | + with pytest.raises(RuntimeError, match="execution failed") as caught: |
| 132 | + backend.execute(SQL, PARAMS, options=options) |
| 133 | + assert caught.value is error |
| 134 | + else: |
| 135 | + assert backend.execute(SQL, PARAMS, options=options) is cursor |
| 136 | + assert backend._execution_noscan.get() is outer |
| 137 | + assert cursor._noscan is previous |
| 138 | + assert cursor.accesses == expected_accesses(noscan, previous) |
| 139 | + assert delegated == [(SQL, PARAMS, options, noscan)] |
| 140 | + assert delegated[0][2] is options |
| 141 | + assert executions == [(SQL, PARAMS, previous if noscan is None else noscan)] |
| 142 | + finally: |
| 143 | + backend._execution_noscan.reset(token) |
| 144 | + |
| 145 | + assert backend._execution_noscan.get() is None |
| 146 | + fails = False |
| 147 | + cursor.accesses.clear() |
| 148 | + assert backend.execute(SQL, PARAMS) is cursor |
| 149 | + assert backend._execution_noscan.get() is None |
| 150 | + assert executions[-1] == (SQL, PARAMS, previous) |
| 151 | + assert len(executions) == 2 |
| 152 | + assert type(delegated[-1][2]) is ExecutionOptions |
| 153 | + assert delegated[-1][3] is None |
| 154 | + assert cursor.accesses == [] |
| 155 | + |
| 156 | + |
| 157 | +@pytest.mark.parametrize("options", OPTION_CASES) |
| 158 | +@pytest.mark.parametrize("fails", [False, True], ids=["success", "error"]) |
| 159 | +@pytest.mark.parametrize("previous", [False, True]) |
| 160 | +@pytest.mark.asyncio |
| 161 | +async def test_async_statement_uses_native_noscan(monkeypatch, options, fails, previous): |
| 162 | + backend = make_backend(AsyncSQLServerBackend) |
| 163 | + noscan = getattr(options, "noscan", None) |
| 164 | + cursor = AsyncCursor(previous, RuntimeError("execution failed") if fails else None) |
| 165 | + monkeypatch.setattr(backend, "_get_cursor", AsyncMock(return_value=cursor)) |
| 166 | + monkeypatch.setattr(backend, "_handle_auto_commit_if_needed", AsyncMock()) |
| 167 | + |
| 168 | + if fails: |
| 169 | + with pytest.raises(DatabaseError, match="execution failed"): |
| 170 | + await backend.execute(SQL, PARAMS, options=options) |
| 171 | + else: |
| 172 | + result = await backend.execute(SQL, PARAMS, options=options) |
| 173 | + assert result.affected_rows == 0 |
| 174 | + assert result.data is None |
| 175 | + |
| 176 | + assert cursor.executions == [ |
| 177 | + (SQL, PARAMS, previous if noscan is None else noscan, "wrapper must not change") |
| 178 | + ] |
| 179 | + assert cursor._impl._noscan is previous |
| 180 | + assert cursor.exit_value is previous |
| 181 | + assert cursor.noscan == "wrapper must not change" |
| 182 | + assert cursor._impl.accesses == expected_accesses(noscan, previous) |
| 183 | + assert cursor.operations == ([] if noscan is None else [ |
| 184 | + (getattr, (cursor._impl, "noscan")), |
| 185 | + (setattr, (cursor._impl, "noscan", noscan)), |
| 186 | + (setattr, (cursor._impl, "noscan", previous)), |
| 187 | + ]) |
| 188 | + |
| 189 | + cursor.error = None |
| 190 | + cursor.operations.clear() |
| 191 | + cursor._impl.accesses.clear() |
| 192 | + await backend.execute(SQL, PARAMS) |
| 193 | + assert cursor.executions[-1] == (SQL, PARAMS, previous, "wrapper must not change") |
| 194 | + assert len(cursor.executions) == 2 |
| 195 | + assert cursor.operations == [] |
| 196 | + assert cursor._impl.accesses == [] |
| 197 | + |
| 198 | + |
| 199 | +@pytest.mark.parametrize("noscan", [True, False, None]) |
| 200 | +@pytest.mark.parametrize("fails", [False, True], ids=["success", "error"]) |
| 201 | +@pytest.mark.asyncio |
| 202 | +async def test_async_cursor_noscan_context_restores_native_value(noscan, fails): |
| 203 | + backend = make_backend(AsyncSQLServerBackend) |
| 204 | + previous = noscan is not True |
| 205 | + cursor = AsyncCursor(previous) |
| 206 | + error = RuntimeError("context failed") |
| 207 | + |
| 208 | + async def use_context(): |
| 209 | + async with backend._cursor_noscan(cursor, noscan): |
| 210 | + assert cursor._impl._noscan is (previous if noscan is None else noscan) |
| 211 | + assert cursor.noscan == "wrapper must not change" |
| 212 | + if fails: |
| 213 | + raise error |
| 214 | + |
| 215 | + if fails: |
| 216 | + with pytest.raises(RuntimeError, match="context failed") as caught: |
| 217 | + await use_context() |
| 218 | + assert caught.value is error |
| 219 | + else: |
| 220 | + await use_context() |
| 221 | + assert cursor._impl._noscan is previous |
| 222 | + assert cursor.noscan == "wrapper must not change" |
| 223 | + assert cursor._impl.accesses == expected_accesses(noscan, previous) |
| 224 | + |
| 225 | + |
| 226 | +@pytest.mark.asyncio |
| 227 | +async def test_async_cursor_noscan_none_does_not_require_native_cursor(): |
| 228 | + backend = make_backend(AsyncSQLServerBackend) |
| 229 | + cursor = SimpleNamespace() |
| 230 | + async with backend._cursor_noscan(cursor, None): |
| 231 | + assert vars(cursor) == {} |
| 232 | + assert vars(cursor) == {} |
0 commit comments