Skip to content

Commit c818c3e

Browse files
authored
Fix reversal of loc when building errors from Python (#609)
1 parent 2a7a2f6 commit c818c3e

File tree

2 files changed

+7
-2
lines changed

2 files changed

+7
-2
lines changed

src/errors/location.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,9 +205,11 @@ impl Serialize for Location {
205205
impl TryFrom<Option<&PyAny>> for Location {
206206
type Error = PyErr;
207207

208+
/// Only ever called by ValidationError -> PyLineError to convert user input to our internal Location
209+
/// Thus this expects the location to *not* be reversed and reverses it before storing it.
208210
fn try_from(location: Option<&PyAny>) -> PyResult<Self> {
209211
if let Some(location) = location {
210-
let loc_vec: Vec<LocItem> = if let Ok(tuple) = location.downcast::<PyTuple>() {
212+
let mut loc_vec: Vec<LocItem> = if let Ok(tuple) = location.downcast::<PyTuple>() {
211213
tuple.iter().map(LocItem::try_from).collect::<PyResult<_>>()?
212214
} else if let Ok(list) = location.downcast::<PyList>() {
213215
list.iter().map(LocItem::try_from).collect::<PyResult<_>>()?
@@ -219,6 +221,9 @@ impl TryFrom<Option<&PyAny>> for Location {
219221
if loc_vec.is_empty() {
220222
Ok(Self::Empty)
221223
} else {
224+
// Don't force Python users to give use the location reversed
225+
// just be we internally store it like that
226+
loc_vec.reverse();
222227
Ok(Self::List(loc_vec))
223228
}
224229
} else {

tests/test_errors.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -559,7 +559,7 @@ def test_raise_validation_error():
559559

560560
# insert_assert(exc_info.value.errors(include_url=False))
561561
assert exc_info.value.errors(include_url=False) == [
562-
{'type': 'greater_than', 'loc': (2, 'a'), 'msg': 'Input should be greater than 5', 'input': 4, 'ctx': {'gt': 5}}
562+
{'type': 'greater_than', 'loc': ('a', 2), 'msg': 'Input should be greater than 5', 'input': 4, 'ctx': {'gt': 5}}
563563
]
564564
with pytest.raises(TypeError, match='GreaterThan requires context: {gt: Number}'):
565565
raise ValidationError.from_exception_data('Foobar', [{'type': 'greater_than', 'loc': ('a', 2), 'input': 4}])

0 commit comments

Comments
 (0)