MCPcopy Create free account
hub / github.com/MagicStack/asyncpg / test_custom_codec_text

Method test_custom_codec_text

tests/test_codecs.py:1232–1284  ·  view source on GitHub ↗

Test encoding/decoding using a custom codec in text mode.

(self)

Source from the content-addressed store, hash-verified

1230 ''')
1231
1232 async def test_custom_codec_text(self):
1233 """Test encoding/decoding using a custom codec in text mode."""
1234 await self.con.execute('''
1235 CREATE EXTENSION IF NOT EXISTS hstore
1236 ''')
1237
1238 def hstore_decoder(data):
1239 result = {}
1240 items = data.split(',')
1241 for item in items:
1242 k, _, v = item.partition('=>')
1243 result[k.strip('"')] = v.strip('"')
1244
1245 return result
1246
1247 def hstore_encoder(obj):
1248 return ','.join('{}=>{}'.format(k, v) for k, v in obj.items())
1249
1250 try:
1251 await self.con.set_type_codec('hstore', encoder=hstore_encoder,
1252 decoder=hstore_decoder)
1253
1254 st = await self.con.prepare('''
1255 SELECT $1::hstore AS result
1256 ''')
1257
1258 res = await st.fetchrow({'ham': 'spam'})
1259 res = res['result']
1260
1261 self.assertEqual(res, {'ham': 'spam'})
1262
1263 pt = st.get_parameters()
1264 self.assertTrue(isinstance(pt, tuple))
1265 self.assertEqual(len(pt), 1)
1266 self.assertEqual(pt[0].name, 'hstore')
1267 self.assertEqual(pt[0].kind, 'scalar')
1268 self.assertEqual(pt[0].schema, 'public')
1269
1270 at = st.get_attributes()
1271 self.assertTrue(isinstance(at, tuple))
1272 self.assertEqual(len(at), 1)
1273 self.assertEqual(at[0].name, 'result')
1274 self.assertEqual(at[0].type, pt[0])
1275
1276 err = 'cannot use custom codec on type public._hstore'
1277 with self.assertRaisesRegex(asyncpg.InterfaceError, err):
1278 await self.con.set_type_codec('_hstore',
1279 encoder=hstore_encoder,
1280 decoder=hstore_decoder)
1281 finally:
1282 await self.con.execute('''
1283 DROP EXTENSION hstore
1284 ''')
1285
1286 async def test_custom_codec_binary(self):
1287 """Test encoding/decoding using a custom codec in binary mode."""

Callers

nothing calls this directly

Calls 6

set_type_codecMethod · 0.80
get_parametersMethod · 0.80
get_attributesMethod · 0.80
executeMethod · 0.45
prepareMethod · 0.45
fetchrowMethod · 0.45

Tested by

no test coverage detected