Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/specify_cli/workflows/expressions/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,10 +228,16 @@ def _filter_to_json(value: Any) -> str:
surfacing as an ordering ``TypeError`` from ``sort_keys=True`` (mixed key
types) or as silent ``1`` → ``"1"`` coercion that collides with an existing
``"1"`` key.

Unpaired surrogates accepted by ``from_json`` cannot be encoded as UTF-8,
so they are escaped as JSON ``\\uXXXX`` sequences after serialization.
The result remains valid JSON and round-trips through ``from_json``, while
every ordinarily UTF-8-encodable non-ASCII character remains readable.
"""
_check_json_keys(value)
try:
return json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False)
text = json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False)
return text.encode("utf-8", "backslashreplace").decode("utf-8")
except (TypeError, ValueError) as exc:
raise ValueError(f"to_json: value is not JSON-serializable: {exc}") from exc

Expand Down
116 changes: 115 additions & 1 deletion tests/specify_cli/workflows/expressions/test_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@

from __future__ import annotations

import json
import os

import pytest
import yaml

from specify_cli.workflows.base import StepContext
from specify_cli.workflows.base import RunStatus, StepContext
from specify_cli.workflows.engine import WorkflowDefinition, WorkflowEngine
from specify_cli.workflows.expressions import (
BUILTIN_FILTERS,
FILTER_TABLE,
Expand Down Expand Up @@ -427,3 +432,112 @@ def test_result_round_trips_through_to_json(self):
assert evaluate_expression("{{ inputs.s | make | to_json }}", ctx(s="x")) == (
'{"a": [1]}'
)


# -- UTF-8-safe to_json output -----------------------------------------------


class TestToJson:
@pytest.mark.parametrize(
("value", "expected"),
[
("\ud800", '"\\ud800"'),
("\udfff", '"\\udfff"'),
(["\ud800"], '["\\ud800"]'),
({"value": "\udfff"}, '{"value": "\\udfff"}'),
({"\ud800": "value"}, '{"\\ud800": "value"}'),
(
{"outer": [{"\udfff": ["ok", "\ud800"]}]},
'{"outer": [{"\\udfff": ["ok", "\\ud800"]}]}',
),
("ascii-\ud800-\u00e9", '"ascii-\\ud800-\u00e9"'),
],
ids=[
"high",
"low",
"list",
"dict-value",
"dict-key",
"nested",
"mixed",
],
)
def test_to_json_escapes_only_surrogates(self, value, expected):
result = evaluate_expression("{{ inputs.value | to_json }}", ctx(value=value))

dumped = json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False)
assert result == dumped.encode("utf-8", "backslashreplace").decode("utf-8")
assert result == expected
assert result.encode("utf-8").decode("utf-8") == result
assert json.loads(result) == value

def test_to_json_escapes_two_code_point_surrogate_pair(self):
result = evaluate_expression(
"{{ inputs.value | to_json }}", ctx(value="\ud83d\ude00")
)

assert result == '"\\ud83d\\ude00"'
assert result.encode("utf-8").decode("utf-8") == result

def test_from_json_to_json_round_trips_lone_surrogate(self):
result = evaluate_expression(
"{{ inputs.p | from_json | to_json }}", ctx(p='"\\ud800"')
)

assert result == '"\\ud800"'

@pytest.mark.parametrize("value", ["\u00e9", "\u4e2d", "\U0001f600"])
def test_to_json_keeps_utf8_encodable_non_ascii_raw(self, value):
result = evaluate_expression("{{ inputs.value | to_json }}", ctx(value=value))

assert result == f'"{value}"'
assert "\\u" not in result

def test_to_json_preserves_stable_key_order_and_existing_backslashes(self):
context = ctx(obj={"b": 2, "a": 1}, path="a\\b")

assert evaluate_expression("{{ inputs.obj | to_json }}", context) == (
'{"a": 1, "b": 2}'
)
assert evaluate_expression("{{ inputs.path | to_json }}", context) == '"a\\\\b"'

def test_to_json_preserves_error_contracts(self):
context = ctx(nan=float("nan"), bad_key={1: "value"})

with pytest.raises(ValueError, match="to_json"):
evaluate_expression("{{ inputs.nan | to_json }}", context)
with pytest.raises(ValueError, match="to_json: mapping keys must be strings"):
evaluate_expression("{{ inputs.bad_key | to_json }}", context)

@pytest.mark.skipif(os.name != "posix", reason="shell command uses POSIX quoting")
def test_shell_step_writes_from_json_surrogate_as_utf8(self, project_dir):
output_path = project_dir / "out.json"
definition = WorkflowDefinition.from_string(
yaml.safe_dump(
{
"schema_version": "1.0",
"workflow": {
"id": "surrogate-json",
"name": "Surrogate JSON",
"version": "1.0.0",
},
"inputs": {"p": {"type": "string"}},
"steps": [
{
"id": "write",
"type": "shell",
"run": (
"printf '%s' "
"'{{ inputs.p | from_json | to_json }}' > out.json"
),
}
],
}
)
)

state = WorkflowEngine(project_dir).execute(definition, {"p": '"\\ud800"'})

assert state.status == RunStatus.COMPLETED
assert output_path.exists()
assert output_path.read_bytes() == b'"\\ud800"'
Loading