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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,8 @@ All yamltrip errors inherit from `YAMLTripError`:
- **No custom Python class serialization.** Values convert to/from
`str`, `int`, `float`, `bool`, `None`, `list`, and `dict` only.
- **UTF-8 only.** Other encodings raise `ParseError`.
- **Non-finite floats rejected.** `float("inf")`, `float("-inf")`, and
`float("nan")` cannot be serialized.
- **Non-finite floats round-trip.** `float("inf")`, `float("-inf")`, and
`float("nan")` map to YAML's `.inf`, `-.inf`, and `.nan`.
- **Integer keys cannot create structures.** `upsert()` with integer path
components can update existing sequence entries but cannot create new
intermediate mappings. Only string keys create new mappings.
Expand Down
40 changes: 29 additions & 11 deletions src/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,7 @@ pub fn py_to_yaml_value(obj: &Bound<'_, PyAny>) -> PyResult<Value> {
}
} else if obj.is_instance_of::<PyFloat>() {
let f: f64 = obj.extract()?;
if f.is_finite() {
Ok(Value::Number(serde_yaml::Number::from(f)))
} else {
Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
"Cannot convert float value {f} to YAML number"
)))
}
Ok(Value::Number(serde_yaml::Number::from(f)))
} else if obj.is_instance_of::<PyString>() {
Ok(Value::String(obj.extract::<String>()?))
} else if obj.is_instance_of::<PyList>() {
Expand Down Expand Up @@ -174,20 +168,44 @@ mod tests {
}

#[test]
fn test_py_to_yaml_float_nan_rejected() {
fn test_py_to_yaml_float_nan() {
pyo3::prepare_freethreaded_python();
Python::with_gil(|py| {
let nan = f64::NAN.into_pyobject(py).unwrap().into_any();
assert!(py_to_yaml_value(&nan).is_err());
let val = py_to_yaml_value(&nan).unwrap();
match val {
Value::Number(n) => assert!(n.is_nan()),
_ => panic!("expected Number"),
}
});
}

#[test]
fn test_py_to_yaml_float_inf_rejected() {
fn test_py_to_yaml_float_inf() {
pyo3::prepare_freethreaded_python();
Python::with_gil(|py| {
let inf = f64::INFINITY.into_pyobject(py).unwrap().into_any();
assert!(py_to_yaml_value(&inf).is_err());
let val = py_to_yaml_value(&inf).unwrap();
match val {
Value::Number(n) => assert!(n.is_infinite()),
_ => panic!("expected Number"),
}
});
}

#[test]
fn test_py_to_yaml_float_neg_inf() {
pyo3::prepare_freethreaded_python();
Python::with_gil(|py| {
let neg_inf = f64::NEG_INFINITY.into_pyobject(py).unwrap().into_any();
let val = py_to_yaml_value(&neg_inf).unwrap();
match val {
Value::Number(n) => {
assert!(n.is_infinite());
assert_eq!(n.as_f64().unwrap(), f64::NEG_INFINITY);
}
_ => panic!("expected Number"),
}
});
}

Expand Down
25 changes: 25 additions & 0 deletions tests/test_roundtrip.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Round-trip preservation tests."""

import math

from yamltrip import Document


Expand Down Expand Up @@ -112,3 +114,26 @@ def test_multi_operation_preserves_structure(self):
assert doc["server", "host"] == "localhost"
assert doc["server", "port"] == 9090
assert doc["database", "pool"] == 10


class TestNonFiniteFloatRoundTrip:
def test_nan_replace_roundtrip(self):
source = "val: .nan\n"
doc = Document(source)
assert math.isnan(doc[("val",)])
doc2 = doc.replace("val", value=float("nan"))
assert math.isnan(doc2[("val",)])

def test_inf_replace_roundtrip(self):
source = "val: .inf\n"
doc = Document(source)
assert doc[("val",)] == float("inf")
doc2 = doc.replace("val", value=float("inf"))
assert doc2[("val",)] == float("inf")

def test_neg_inf_replace_roundtrip(self):
source = "val: -.inf\n"
doc = Document(source)
assert doc[("val",)] == float("-inf")
doc2 = doc.replace("val", value=float("-inf"))
assert doc2[("val",)] == float("-inf")
Loading