-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathtest_transaction.py
More file actions
364 lines (301 loc) · 10.8 KB
/
test_transaction.py
File metadata and controls
364 lines (301 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
from __future__ import annotations
import typing
import pytest
from psqlpy import (
ConnectionPool,
Cursor,
IsolationLevel,
ReadVariant,
)
from psqlpy._internal.exceptions import TransactionClosedError
from psqlpy.exceptions import (
InterfaceError,
TransactionExecuteError,
)
from tests.helpers import count_rows_in_test_table
pytestmark = pytest.mark.anyio
@pytest.mark.parametrize(
("isolation_level", "deferrable", "read_variant"),
[
(None, None, None),
(IsolationLevel.ReadCommitted, True, ReadVariant.ReadOnly),
(IsolationLevel.ReadUncommitted, False, ReadVariant.ReadWrite),
(IsolationLevel.RepeatableRead, True, ReadVariant.ReadOnly),
(IsolationLevel.Serializable, False, ReadVariant.ReadWrite),
],
)
async def test_transaction_init_parameters(
psql_pool: ConnectionPool,
table_name: str,
isolation_level: IsolationLevel | None,
deferrable: bool | None,
read_variant: ReadVariant | None,
) -> None:
async with (
psql_pool.acquire() as connection,
connection.transaction(
isolation_level=isolation_level,
deferrable=deferrable,
read_variant=read_variant,
) as transaction,
):
await transaction.execute("SELECT 1")
try:
await transaction.execute(
f"INSERT INTO {table_name} VALUES ($1, $2)",
parameters=[100, "test_name"],
)
except InterfaceError:
assert read_variant is ReadVariant.ReadOnly
else:
assert read_variant is not ReadVariant.ReadOnly
async def test_transaction_begin(
psql_pool: ConnectionPool,
table_name: str,
number_database_records: int,
) -> None:
"""Test that transaction must be started with `begin()` method."""
connection = await psql_pool.connection()
transaction = connection.transaction()
# with pytest.raises(expected_exception=TransactionBeginError):
await transaction.execute(
f"SELECT * FROM {table_name}",
)
await transaction.begin()
result = await transaction.execute(
f"SELECT * FROM {table_name}",
)
assert len(result.result()) == number_database_records
await transaction.commit()
async def test_transaction_commit(
psql_pool: ConnectionPool,
table_name: str,
) -> None:
"""Test that transaction commit command."""
connection = await psql_pool.connection()
transaction = connection.transaction()
await transaction.begin()
test_name: str = "test_name"
await transaction.execute(
f"INSERT INTO {table_name} VALUES ($1, $2)",
parameters=[100, test_name],
)
# Make request from other connection, it mustn't know
# about new INSERT data before commit.
connection = await psql_pool.connection()
result = await connection.execute(
f"SELECT * FROM {table_name} WHERE name = $1",
parameters=[test_name],
)
assert not result.result()
await transaction.commit()
result = await connection.execute(
f"SELECT * FROM {table_name} WHERE name = $1",
parameters=[test_name],
)
assert len(result.result())
async def test_transaction_savepoint(
psql_pool: ConnectionPool,
table_name: str,
) -> None:
"""Test that it's possible to rollback to savepoint."""
connection = await psql_pool.connection()
transaction = connection.transaction()
await transaction.begin()
test_name = "test_name"
savepoint_name = "sp1"
await transaction.create_savepoint(savepoint_name=savepoint_name)
await transaction.execute(
f"INSERT INTO {table_name} VALUES ($1, $2)",
parameters=[100, test_name],
)
result = await transaction.execute(
f"SELECT * FROM {table_name} WHERE name = $1",
parameters=[test_name],
)
assert result.result()
await transaction.rollback_savepoint(savepoint_name=savepoint_name)
connection = await psql_pool.connection()
result = await connection.execute(
f"SELECT * FROM {table_name} WHERE name = $1",
parameters=[test_name],
)
assert not len(result.result())
await transaction.commit()
async def test_transaction_rollback(
psql_pool: ConnectionPool,
table_name: str,
) -> None:
"""Test that ROLLBACK works correctly."""
connection = await psql_pool.connection()
transaction = connection.transaction()
await transaction.begin()
test_name = "test_name"
await transaction.execute(
f"INSERT INTO {table_name} VALUES ($1, $2)",
parameters=[100, test_name],
)
result = await transaction.execute(
f"SELECT * FROM {table_name} WHERE name = $1",
parameters=[test_name],
)
assert result.result()
await transaction.rollback()
with pytest.raises(expected_exception=TransactionClosedError):
await transaction.execute(
f"SELECT * FROM {table_name} WHERE name = $1",
parameters=[test_name],
)
connection = await psql_pool.connection()
result_from_conn = await connection.execute(
f"INSERT INTO {table_name} VALUES ($1, $2)",
parameters=[100, test_name],
)
connection.close()
assert not (result_from_conn.result())
async def test_transaction_release_savepoint(
psql_pool: ConnectionPool,
) -> None:
"""Test that it is possible to acquire and release savepoint."""
connection = await psql_pool.connection()
transaction = connection.transaction()
await transaction.begin()
sp_name_1 = "sp1"
sp_name_2 = "sp2"
await transaction.create_savepoint(sp_name_1)
# There is no problem in creating the same sp_name
await transaction.create_savepoint(sp_name_1)
await transaction.create_savepoint(sp_name_2)
await transaction.release_savepoint(sp_name_1)
await transaction.create_savepoint(sp_name_1)
async def test_transaction_cursor(
psql_pool: ConnectionPool,
table_name: str,
) -> None:
"""Test that transaction can create cursor."""
connection = await psql_pool.connection()
async with connection.transaction() as transaction:
cursor = transaction.cursor(f"SELECT * FROM {table_name}")
assert isinstance(cursor, Cursor)
async def test_transaction_fetch(
psql_pool: ConnectionPool,
table_name: str,
number_database_records: int,
) -> None:
"""Test that single connection can fetch queries."""
connection = await psql_pool.connection()
async with connection.transaction() as transaction:
conn_result = await transaction.fetch(
querystring=f"SELECT * FROM {table_name}",
)
assert len(conn_result.result()) == number_database_records
@pytest.mark.parametrize(
("insert_values"),
[
[[1, "name1"], [2, "name2"]],
[[10, "name1"], [20, "name2"], [30, "name3"]],
[[1, "name1"]],
[],
],
)
async def test_transaction_execute_many(
psql_pool: ConnectionPool,
table_name: str,
number_database_records: int,
insert_values: list[list[typing.Any]],
) -> None:
connection = await psql_pool.connection()
async with connection.transaction() as transaction:
try:
await transaction.execute_many(
f"INSERT INTO {table_name} VALUES ($1, $2)",
insert_values,
)
except TransactionExecuteError:
assert not insert_values
else:
assert await count_rows_in_test_table(
table_name,
transaction,
) - number_database_records == len(insert_values)
async def test_transaction_fetch_row(
psql_pool: ConnectionPool,
table_name: str,
) -> None:
connection = await psql_pool.connection()
async with connection.transaction() as transaction:
database_single_query_result: typing.Final = await transaction.fetch_row(
f"SELECT * FROM {table_name} LIMIT 1",
[],
)
result = database_single_query_result.result()
assert isinstance(result, dict)
async def test_transaction_fetch_row_more_than_one_row(
psql_pool: ConnectionPool,
table_name: str,
) -> None:
connection = await psql_pool.connection()
async with connection.transaction() as transaction:
with pytest.raises(InterfaceError):
await transaction.fetch_row(
f"SELECT * FROM {table_name}",
[],
)
async def test_transaction_fetch_val(
psql_pool: ConnectionPool,
table_name: str,
) -> None:
connection = await psql_pool.connection()
async with connection.transaction() as transaction:
value: typing.Final = await transaction.fetch_val(
f"SELECT COUNT(*) FROM {table_name}",
[],
)
assert isinstance(value, int)
async def test_transaction_fetch_val_more_than_one_row(
psql_pool: ConnectionPool,
table_name: str,
) -> None:
connection = await psql_pool.connection()
async with connection.transaction() as transaction:
with pytest.raises(InterfaceError):
await transaction.fetch_row(
f"SELECT * FROM {table_name}",
[],
)
async def test_transaction_send_underlying_connection_to_pool(
psql_pool: ConnectionPool,
) -> None:
"""Test send underlying connection to the pool."""
async with psql_pool.acquire() as connection:
async with connection.transaction() as transaction:
await transaction.execute("SELECT 1")
assert not psql_pool.status().available
assert not psql_pool.status().available
assert psql_pool.status().available == 1
async def test_transaction_send_underlying_connection_to_pool_manually(
psql_pool: ConnectionPool,
) -> None:
"""Test send underlying connection to the pool."""
async with psql_pool.acquire() as connection:
transaction = connection.transaction()
await transaction.begin()
await transaction.execute("SELECT 1")
assert not psql_pool.status().available
await transaction.commit()
assert not psql_pool.status().available
assert psql_pool.status().available == 1
async def test_execute_batch_method(psql_pool: ConnectionPool) -> None:
"""Test `execute_batch` method."""
connection = await psql_pool.connection()
await connection.execute(querystring="DROP TABLE IF EXISTS execute_batch")
await connection.execute(querystring="DROP TABLE IF EXISTS execute_batch2")
query = (
"CREATE TABLE execute_batch (name VARCHAR);"
"CREATE TABLE execute_batch2 (name VARCHAR);"
)
async with connection.transaction() as transaction:
await transaction.execute_batch(querystring=query)
await transaction.execute(querystring="SELECT * FROM execute_batch")
await transaction.execute(querystring="SELECT * FROM execute_batch2")
connection.close()