|
| 1 | +"""String coercion at identifier / parameter-key / separator sites. |
| 2 | +
|
| 3 | +nanobind's nb::cast<std::string> is stricter than pybind11's: it rejects bytes and non-str scalars and surfaces a |
| 4 | +raw ``RuntimeError: std::bad_cast`` instead of pybind11's lenient conversion. The ``cast_to_string`` helper restores |
| 5 | +the lenient behavior (str as-is, bytes UTF-8 decoded, anything else stringified via str()). These guard the |
| 6 | +std::bad_cast regression and confirm the realistic cases still match pybind11. |
| 7 | +""" |
| 8 | + |
| 9 | +import platform |
| 10 | + |
| 11 | +import pytest |
| 12 | + |
| 13 | +import duckdb |
| 14 | + |
| 15 | +pytestmark = pytest.mark.skipif( |
| 16 | + platform.system() == "Emscripten", |
| 17 | + reason="Extensions are not supported on Emscripten", |
| 18 | +) |
| 19 | + |
| 20 | + |
| 21 | +def test_execute_int_param_key(): |
| 22 | + """An int parameter-dict key stringifies (so {1: v} fills positional $1), matching pybind11.""" |
| 23 | + con = duckdb.connect() |
| 24 | + assert con.execute("SELECT $1 AS a", {1: 5}).fetchall() == [(5,)] |
| 25 | + |
| 26 | + |
| 27 | +def test_execute_str_param_key(): |
| 28 | + con = duckdb.connect() |
| 29 | + assert con.execute("SELECT $name AS a", {"name": 7}).fetchall() == [(7,)] |
| 30 | + |
| 31 | + |
| 32 | +def test_struct_type_int_field_key(): |
| 33 | + """An int struct field-name key stringifies to "1" (matching pybind11), not a raw std::bad_cast.""" |
| 34 | + assert str(duckdb.struct_type({1: "INTEGER"})) == 'STRUCT("1" INTEGER)' |
| 35 | + |
| 36 | + |
| 37 | +def test_struct_type_str_field_key(): |
| 38 | + assert str(duckdb.struct_type({"a": "INTEGER"})) == "STRUCT(a INTEGER)" |
| 39 | + |
| 40 | + |
| 41 | +def test_bytes_param_key_decodes(): |
| 42 | + """A bytes param-dict key is UTF-8 decoded (b'1' -> '1'); bytes consistently decode at coercion sites.""" |
| 43 | + con = duckdb.connect() |
| 44 | + assert con.execute("SELECT $1 AS a", {b"1": 5}).fetchall() == [(5,)] |
| 45 | + |
| 46 | + |
| 47 | +def test_bytes_struct_field_key_decodes(): |
| 48 | + """A bytes struct field-name key is UTF-8 decoded (b'a' -> 'a'); bytes consistently decode at coercion sites. |
| 49 | +
|
| 50 | + These coercion sites previously surfaced a raw 'std::bad_cast' for non-str input; each test here asserting a |
| 51 | + concrete result also guards that regression (a std::bad_cast would raise and fail the assertion). |
| 52 | + """ |
| 53 | + assert str(duckdb.struct_type({b"a": "INTEGER"})) == "STRUCT(a INTEGER)" |
0 commit comments