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 365 366 367 368 369 370
|
import json
import logging
from copy import deepcopy
from typing import Any
import pytest
import psycopg.types
from psycopg import pq, sql
from psycopg.adapt import PyFormat
from psycopg.types.json import set_json_dumps, set_json_loads
samples = [
"null",
"true",
'"te\'xt"',
'"\\u00e0\\u20ac"',
"123",
"123.45",
'["a", 100]',
'{"a": 100}',
]
@pytest.mark.parametrize("wrapper", ["Json", "Jsonb"])
@pytest.mark.parametrize("fmt_in", PyFormat)
def test_wrapper_regtype(conn, wrapper, fmt_in):
wrapper = getattr(psycopg.types.json, wrapper)
cur = conn.cursor()
cur.execute(
f"select pg_typeof(%{fmt_in.value})::regtype = %s::regtype",
(wrapper([]), wrapper.__name__.lower()),
)
assert cur.fetchone()[0] is True
@pytest.mark.parametrize("val", samples)
@pytest.mark.parametrize("wrapper", ["Json", "Jsonb"])
@pytest.mark.parametrize("fmt_in", PyFormat)
def test_dump(conn, val, wrapper, fmt_in):
wrapper = getattr(psycopg.types.json, wrapper)
obj = json.loads(val)
cur = conn.cursor()
cur.execute(
f"select %{fmt_in.value}::text = %s::{wrapper.__name__.lower()}::text",
(wrapper(obj), val),
)
assert cur.fetchone()[0] is True
@pytest.mark.parametrize(
"fmt_in, pgtype, dumper_name",
[
("t", "json", "JsonDumper"),
("b", "json", "JsonBinaryDumper"),
("t", "jsonb", "JsonbDumper"),
("b", "jsonb", "JsonbBinaryDumper"),
],
)
def test_dump_dict(conn, fmt_in, pgtype, dumper_name):
obj = {"foo": "bar"}
cur = conn.cursor()
dumper = getattr(psycopg.types.json, dumper_name)
# Skip json on CRDB as the oid doesn't exist.
try:
conn.adapters.types[dumper.oid]
except KeyError:
pytest.skip(
f"{type(conn).__name__} doesn't have the oid {dumper.oid}"
f" used by {dumper.__name__}"
)
cur.adapters.register_dumper(dict, dumper)
cur.execute(f"select %{fmt_in}", (obj,))
assert cur.fetchone()[0] == obj
assert cur.description[0].type_code == conn.adapters.types[pgtype].oid
@pytest.mark.crdb_skip("json array")
@pytest.mark.parametrize("val", samples)
@pytest.mark.parametrize("wrapper", ["Json", "Jsonb"])
@pytest.mark.parametrize("fmt_in", PyFormat)
def test_array_dump(conn, val, wrapper, fmt_in):
wrapper = getattr(psycopg.types.json, wrapper)
obj = json.loads(val)
cur = conn.cursor()
cur.execute(
f"select %{fmt_in.value}::text = array[%s::{wrapper.__name__.lower()}]::text",
([wrapper(obj)], val),
)
assert cur.fetchone()[0] is True
@pytest.mark.parametrize("val", samples)
@pytest.mark.parametrize("jtype", ["json", "jsonb"])
@pytest.mark.parametrize("fmt_out", pq.Format)
def test_load(conn, val, jtype, fmt_out):
cur = conn.cursor(binary=fmt_out)
cur.execute(f"select %s::{jtype}", (val,))
assert cur.fetchone()[0] == json.loads(val)
@pytest.mark.crdb_skip("json array")
@pytest.mark.parametrize("val", samples)
@pytest.mark.parametrize("jtype", ["json", "jsonb"])
@pytest.mark.parametrize("fmt_out", pq.Format)
def test_load_array(conn, val, jtype, fmt_out):
cur = conn.cursor(binary=fmt_out)
cur.execute(f"select array[%s::{jtype}]", (val,))
assert cur.fetchone()[0] == [json.loads(val)]
@pytest.mark.crdb_skip("copy")
@pytest.mark.parametrize("val", samples)
@pytest.mark.parametrize("jtype", ["json", "jsonb"])
@pytest.mark.parametrize("fmt_out", pq.Format)
def test_load_copy(conn, val, jtype, fmt_out):
cur = conn.cursor()
stmt = sql.SQL("copy (select {}::{}) to stdout (format {})").format(
val, sql.Identifier(jtype), sql.SQL(fmt_out.name)
)
with cur.copy(stmt) as copy:
copy.set_types([jtype])
(got,) = copy.read_row()
assert got == json.loads(val)
@pytest.mark.parametrize("fmt_in", PyFormat)
@pytest.mark.parametrize("wrapper", ["Json", "Jsonb"])
def test_dump_customise(conn, wrapper, fmt_in):
wrapper = getattr(psycopg.types.json, wrapper)
obj = {"foo": "bar"}
cur = conn.cursor()
set_json_dumps(my_dumps)
try:
cur.execute(f"select %{fmt_in.value}->>'baz' = 'qux'", (wrapper(obj),))
assert cur.fetchone()[0] is True
finally:
set_json_dumps(json.dumps)
@pytest.mark.parametrize("fmt_in", PyFormat)
@pytest.mark.parametrize("wrapper", ["Json", "Jsonb"])
def test_dump_customise_bytes(conn, wrapper, fmt_in):
wrapper = getattr(psycopg.types.json, wrapper)
obj = {"foo": "bar"}
cur = conn.cursor()
set_json_dumps(my_dumps_bytes)
try:
cur.execute(f"select %{fmt_in.value}->>'baz' = 'qux'", (wrapper(obj),))
assert cur.fetchone()[0] is True
finally:
set_json_dumps(json.dumps)
@pytest.mark.parametrize("fmt_in", PyFormat)
@pytest.mark.parametrize("wrapper", ["Json", "Jsonb"])
def test_dump_customise_context(conn, wrapper, fmt_in):
wrapper = getattr(psycopg.types.json, wrapper)
obj = {"foo": "bar"}
cur1 = conn.cursor()
cur2 = conn.cursor()
set_json_dumps(my_dumps, cur2)
cur1.execute(f"select %{fmt_in.value}->>'baz'", (wrapper(obj),))
assert cur1.fetchone()[0] is None
cur2.execute(f"select %{fmt_in.value}->>'baz'", (wrapper(obj),))
assert cur2.fetchone()[0] == "qux"
@pytest.mark.parametrize("fmt_in", PyFormat)
@pytest.mark.parametrize("wrapper", ["Json", "Jsonb"])
def test_dump_customise_wrapper(conn, wrapper, fmt_in):
wrapper = getattr(psycopg.types.json, wrapper)
obj = {"foo": "bar"}
cur = conn.cursor()
cur.execute(f"select %{fmt_in.value}->>'baz' = 'qux'", (wrapper(obj, my_dumps),))
assert cur.fetchone()[0] is True
@pytest.mark.parametrize("binary", [True, False])
@pytest.mark.parametrize("pgtype", ["json", "jsonb"])
def test_load_customise(conn, binary, pgtype):
cur = conn.cursor(binary=binary)
set_json_loads(my_loads)
try:
cur.execute(f"""select '{{"foo": "bar"}}'::{pgtype}""")
obj = cur.fetchone()[0]
assert obj["foo"] == "bar"
assert obj["answer"] == 42
finally:
set_json_loads(json.loads)
@pytest.mark.parametrize("binary", [True, False])
@pytest.mark.parametrize("pgtype", ["json", "jsonb"])
def test_load_customise_context(conn, binary, pgtype):
cur1 = conn.cursor(binary=binary)
cur2 = conn.cursor(binary=binary)
set_json_loads(my_loads, cur2)
cur1.execute(f"""select '{{"foo": "bar"}}'::{pgtype}""")
got = cur1.fetchone()[0]
assert got["foo"] == "bar"
assert "answer" not in got
cur2.execute(f"""select '{{"foo": "bar"}}'::{pgtype}""")
got = cur2.fetchone()[0]
assert got["foo"] == "bar"
assert got["answer"] == 42
@pytest.mark.parametrize("binary", [True, False])
@pytest.mark.parametrize("pgtype", ["json", "jsonb"])
def test_dump_leak_with_local_functions(dsn, binary, pgtype, caplog):
caplog.set_level(logging.WARNING, logger="psycopg")
# Note: private implementation, it might change
from psycopg.types.json import _dumpers_cache
# A function with no closure is cached on the code, so lambdas are not
# different items.
def register(conn: psycopg.Connection) -> None:
set_json_dumps(lambda x: json.dumps(x), conn)
with psycopg.connect(dsn) as conn1:
register(conn1)
assert (size1 := len(_dumpers_cache))
with psycopg.connect(dsn) as conn2:
register(conn2)
size2 = len(_dumpers_cache)
assert size1 == size2
assert not caplog.records
# A function with a closure won't be cached, but will cause a warning
def register2(conn: psycopg.Connection, skipkeys: bool) -> None:
def f(x: Any) -> str:
return json.dumps(x, skipkeys=skipkeys)
set_json_dumps(f, conn)
with psycopg.connect(dsn) as conn3:
register2(conn3, False)
size3 = len(_dumpers_cache)
assert size2 == size3
assert caplog.records
@pytest.mark.parametrize("binary", [True, False])
@pytest.mark.parametrize("pgtype", ["json", "jsonb"])
@pytest.mark.parametrize("dumps", [str, len])
def test_dumper_warning_builtin(dsn, binary, pgtype, dumps, caplog, recwarn):
caplog.set_level(logging.WARNING, logger="psycopg")
recwarn.clear()
# Note: private implementation, it might change
from psycopg.types.json import _dumpers_cache
# A function with no closure is cached on the code, so lambdas are not
# different items.
with psycopg.connect(dsn) as conn1:
set_json_dumps(dumps, conn1)
assert not recwarn
assert (size1 := len(_dumpers_cache))
with psycopg.connect(dsn) as conn2:
set_json_dumps(dumps, conn2)
size2 = len(_dumpers_cache)
assert size1 == size2
assert not caplog.records
assert not recwarn
@pytest.mark.parametrize("binary", [True, False])
@pytest.mark.parametrize("pgtype", ["json", "jsonb"])
def test_load_leak_with_local_functions(dsn, binary, pgtype, caplog):
caplog.set_level(logging.WARNING, logger="psycopg")
# Note: private implementation, it might change
from psycopg.types.json import _loaders_cache
# A function with no closure is cached on the code, so lambdas are not
# different items.
def register(conn: psycopg.Connection) -> None:
def f(x: str | bytes) -> Any:
return json.loads(x)
set_json_loads(f, conn)
with psycopg.connect(dsn) as conn1:
register(conn1)
assert (size1 := len(_loaders_cache))
with psycopg.connect(dsn) as conn2:
register(conn2)
size2 = len(_loaders_cache)
assert size1 == size2
assert not caplog.records
# A function with a closure won't be cached, but will cause a warning
def register2(conn: psycopg.Connection, parse_float: Any) -> None:
set_json_dumps(lambda x: json.dumps(x, parse_float=parse_float), conn)
with psycopg.connect(dsn) as conn3:
register2(conn3, None)
size3 = len(_loaders_cache)
assert size2 == size3
assert caplog.records
@pytest.mark.parametrize("binary", [True, False])
@pytest.mark.parametrize("pgtype", ["json", "jsonb"])
@pytest.mark.parametrize("loads", [str, len])
def test_loader_warning_builtin(dsn, binary, pgtype, loads, caplog, recwarn):
caplog.set_level(logging.WARNING, logger="psycopg")
recwarn.clear()
# Note: private implementation, it might change
from psycopg.types.json import _loaders_cache
# A function with no closure is cached on the code, so lambdas are not
# different items.
with psycopg.connect(dsn) as conn1:
set_json_loads(loads, conn1)
assert not recwarn
assert (size1 := len(_loaders_cache))
with psycopg.connect(dsn) as conn2:
set_json_loads(loads, conn2)
size2 = len(_loaders_cache)
assert size1 == size2
assert not caplog.records
assert not recwarn
def my_dumps(obj):
obj = deepcopy(obj)
obj["baz"] = "qux"
return json.dumps(obj)
def my_dumps_bytes(obj):
obj = deepcopy(obj)
obj["baz"] = "qux"
return json.dumps(obj).encode()
def my_loads(data):
obj = json.loads(data)
obj["answer"] = 42
return obj
|