forked from MagicStack/asyncpg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_record.py
334 lines (269 loc) · 10.2 KB
/
test_record.py
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
# Copyright (C) 2016-present the asyncpg authors and contributors
# <see AUTHORS file>
#
# This module is part of asyncpg and is released under
# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0
import contextlib
import collections
import gc
import pickle
import sys
import asyncpg
from asyncpg import _testbase as tb
from asyncpg.protocol.protocol import _create_record as Record
R_A = collections.OrderedDict([('a', 0)])
R_AB = collections.OrderedDict([('a', 0), ('b', 1)])
R_AC = collections.OrderedDict([('a', 0), ('c', 1)])
R_ABC = collections.OrderedDict([('a', 0), ('b', 1), ('c', 2)])
class TestRecord(tb.ConnectedTestCase):
@contextlib.contextmanager
def checkref(self, *objs):
cnt = [sys.getrefcount(objs[i]) for i in range(len(objs))]
yield
for _ in range(3):
gc.collect()
for i in range(len(objs)):
before = cnt[i]
after = sys.getrefcount(objs[i])
if before != after:
self.fail('refcounts differ for {!r}: {:+}'.format(
objs[i], after - before))
def test_record_gc(self):
elem = object()
mapping = {}
with self.checkref(mapping, elem):
r = Record(mapping, (elem,))
del r
key = 'spam'
val = int('101010')
mapping = {key: val}
with self.checkref(key, val):
r = Record(mapping, (0,))
with self.assertRaises(KeyError):
r[key]
del r
key = 'spam'
val = 'ham'
mapping = {key: val}
with self.checkref(key, val):
r = Record(mapping, (0,))
with self.assertRaises(KeyError):
r[key]
del r
def test_record_freelist_ok(self):
for _ in range(10000):
Record(R_A, (42,))
Record(R_AB, (42, 42,))
def test_record_len_getindex(self):
r = Record(R_A, (42,))
self.assertEqual(len(r), 1)
self.assertEqual(r[0], 42)
self.assertEqual(r['a'], 42)
r = Record(R_AB, (42, 43))
self.assertEqual(len(r), 2)
self.assertEqual(r[0], 42)
self.assertEqual(r[1], 43)
self.assertEqual(r['a'], 42)
self.assertEqual(r['b'], 43)
with self.assertRaisesRegex(IndexError,
'record index out of range'):
r[1000]
with self.assertRaisesRegex(KeyError, 'spam'):
r['spam']
with self.assertRaisesRegex(KeyError, 'spam'):
Record(None, (1,))['spam']
with self.assertRaisesRegex(KeyError, 'spam'):
Record({'spam': 123}, (1,))['spam']
def test_record_slice(self):
r = Record(R_ABC, (1, 2, 3))
self.assertEqual(r[:], (1, 2, 3))
self.assertEqual(r[:1], (1,))
self.assertEqual(r[::-1], (3, 2, 1))
self.assertEqual(r[::-2], (3, 1))
self.assertEqual(r[1:2], (2,))
self.assertEqual(r[2:2], ())
def test_record_immutable(self):
r = Record(R_A, (42,))
with self.assertRaisesRegex(TypeError, 'does not support item'):
r[0] = 1
def test_record_repr(self):
self.assertEqual(
repr(Record(R_A, (42,))),
'<Record a=42>')
self.assertEqual(
repr(Record(R_AB, (42, -1))),
'<Record a=42 b=-1>')
# test invalid records just in case
with self.assertRaisesRegex(RuntimeError, 'invalid .* mapping'):
repr(Record(R_A, (42, 43)))
self.assertEqual(repr(Record(R_AB, (42,))), '<Record a=42>')
class Key:
def __str__(self):
1 / 0
def __repr__(self):
1 / 0
with self.assertRaises(ZeroDivisionError):
repr(Record({Key(): 0}, (42,)))
with self.assertRaises(ZeroDivisionError):
repr(Record(R_A, (Key(),)))
def test_record_iter(self):
r = Record(R_AB, (42, 43))
with self.checkref(r):
self.assertEqual(iter(r).__length_hint__(), 2)
self.assertEqual(tuple(r), (42, 43))
def test_record_values(self):
r = Record(R_AB, (42, 43))
vv = r.values()
self.assertEqual(tuple(vv), (42, 43))
self.assertTrue(repr(vv).startswith('<RecordIterator '))
def test_record_keys(self):
r = Record(R_AB, (42, 43))
vv = r.keys()
self.assertEqual(tuple(vv), ('a', 'b'))
self.assertEqual(list(Record(None, (42, 43)).keys()), [])
def test_record_items(self):
r = Record(R_AB, (42, 43))
self.assertEqual(dict(r), {'a': 42, 'b': 43})
self.assertEqual(
list(collections.OrderedDict(r).items()),
[('a', 42), ('b', 43)])
with self.checkref(r):
rk = r.items()
self.assertEqual(rk.__length_hint__(), 2)
self.assertEqual(next(rk), ('a', 42))
self.assertEqual(rk.__length_hint__(), 1)
self.assertEqual(next(rk), ('b', 43))
self.assertEqual(rk.__length_hint__(), 0)
with self.assertRaises(StopIteration):
next(rk)
with self.assertRaises(StopIteration):
next(rk)
self.assertEqual(rk.__length_hint__(), 0)
self.assertEqual(list(r.items()), [('a', 42), ('b', 43)])
# Check invalid records just in case
r = Record(R_A, (42, 43))
self.assertEqual(list(r.items()), [('a', 42)])
r = Record(R_AB, (42,))
self.assertEqual(list(r.items()), [('a', 42)])
# Try to iterate over exhausted items() iterator
r = Record(R_A, (42, 43))
it = r.items()
list(it)
list(it)
def test_record_hash(self):
AB = collections.namedtuple('AB', ('a', 'b'))
r1 = Record(R_AB, (42, 43))
r2 = Record(R_AB, (42, 43))
r3 = Record(R_AB, (42, 45))
r4 = (42, 43)
r5 = AB(42, 43)
self.assertEqual(hash(r1), hash(r2))
self.assertNotEqual(hash(r1), hash(r3))
self.assertEqual(hash(r1), hash(r4))
self.assertEqual(hash(r1), hash(r5))
d = {}
d[r1] = 123
self.assertEqual(d[r1], 123)
self.assertIn(r2, d)
self.assertEqual(d[r2], 123)
self.assertNotIn(r3, d)
self.assertIn(r4, d)
def test_record_contains(self):
r = Record(R_AB, (42, 43))
self.assertIn('a', r)
self.assertIn('b', r)
self.assertNotIn('z', r)
r = Record(None, (42, 43))
self.assertNotIn('a', r)
with self.assertRaises(TypeError):
type(r).__contains__(None, 'a')
def test_record_cmp(self):
AB = collections.namedtuple('AB', ('a', 'b'))
r1 = Record(R_AB, (42, 43))
r2 = Record(R_AB, (42, 43))
r3 = Record(R_AB.copy(), (42, 43))
r4 = Record(R_AB.copy(), (42, 45))
r5 = Record(R_ABC, (42, 46, 57))
r6 = Record(R_AC, (42, 43))
r7 = (42, 43)
r8 = [42, 43]
r9 = AB(42, 43)
r10 = AB(42, 44)
self.assertEqual(r1, r2)
self.assertEqual(r1, r3)
self.assertEqual(r1, r6)
self.assertEqual(r1, r7)
self.assertEqual(r1, r9)
self.assertNotEqual(r1, r4)
self.assertNotEqual(r1, r10)
self.assertNotEqual(r1, (42,))
self.assertNotEqual(r1, r5)
self.assertNotEqual(r4, r5)
self.assertNotEqual(r4, r6)
self.assertNotEqual(r6, r5)
self.assertNotEqual(r1, r8)
self.assertNotEqual(r8, r6)
self.assertLess(r1, r4)
self.assertGreater(r4, r1)
self.assertLess(r1, r5)
self.assertLess(r7, r5)
self.assertLess(r1, r10)
self.assertGreater(r5, r6)
self.assertGreater(r5, r7)
self.assertGreater(r5, r4)
with self.assertRaisesRegex(
TypeError, "unorderable|'<' not supported"):
r1 < r8
self.assertEqual(
sorted([r1, r2, r3, r4, r5, r6, r7]),
[r1, r2, r3, r6, r7, r4, r5])
def test_record_not_pickleable(self):
r = Record(R_A, (42,))
with self.assertRaises(Exception):
pickle.dumps(r)
def test_record_empty(self):
r = Record(None, ())
self.assertEqual(r, ())
self.assertLess(r, (1,))
self.assertEqual(len(r), 0)
self.assertFalse(r)
self.assertNotIn('a', r)
self.assertEqual(repr(r), '<Record>')
self.assertEqual(str(r), '<Record>')
with self.assertRaisesRegex(KeyError, 'aaa'):
r['aaa']
self.assertEqual(dict(r.items()), {})
self.assertEqual(list(r.keys()), [])
self.assertEqual(list(r.values()), [])
async def test_record_duplicate_colnames(self):
"""Test that Record handles duplicate column names."""
records_descs = [
[('a', 1)],
[('a', 1), ('a', 2)],
[('a', 1), ('b', 2), ('a', 3)],
[('a', 1), ('b', 2), ('a', 3), ('c', 4), ('b', 5)],
]
for desc in records_descs:
items = collections.OrderedDict(desc)
query = 'SELECT ' + ', '.join(
['{} as {}'.format(p[1], p[0]) for p in desc])
with self.subTest(query=query):
r = await self.con.fetchrow(query)
for idx, (field, val) in enumerate(desc):
self.assertEqual(r[idx], val)
self.assertEqual(r[field], items[field])
expected_repr = '<Record {}>'.format(
' '.join('{}={}'.format(p[0], p[1]) for p in desc))
self.assertEqual(repr(r), expected_repr)
self.assertEqual(list(r.items()), desc)
self.assertEqual(list(r.values()), [p[1] for p in desc])
self.assertEqual(list(r.keys()), [p[0] for p in desc])
async def test_record_isinstance(self):
"""Test that Record works with isinstance."""
r = await self.con.fetchrow('SELECT 1 as a, 2 as b')
self.assertTrue(isinstance(r, asyncpg.Record))
async def test_record_no_new(self):
"""Instances of Record cannot be directly created."""
with self.assertRaisesRegex(
TypeError, "cannot create 'asyncpg.Record' instances"):
asyncpg.Record()