Skip to content

Commit

Permalink
Add test for dict subclass iters
Browse files Browse the repository at this point in the history
  • Loading branch information
bschoenmaeckers committed Sep 3, 2024
1 parent 927d2bd commit 3ace91a
Showing 1 changed file with 42 additions and 1 deletion.
43 changes: 42 additions & 1 deletion src/types/dict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -642,7 +642,9 @@ where
#[cfg(test)]
mod tests {
use super::*;
use crate::types::PyTuple;
use crate::tests::common::generate_unique_module_name;
use crate::types::{PyModule, PyTuple};
use pyo3_ffi::c_str;
use std::collections::{BTreeMap, HashMap};

#[test]
Expand Down Expand Up @@ -965,6 +967,45 @@ mod tests {
});
}

#[test]
fn test_iter_subclass() {
Python::with_gil(|py| {
let mut v = HashMap::new();
v.insert(7, 32);
v.insert(8, 42);
v.insert(9, 123);
let ob = v.to_object(py);
let dict = ob.downcast_bound::<PyDict>(py).unwrap();

let module = PyModule::from_code(
py,
c_str!("class DictSubclass(dict): pass"),
c_str!("test.py"),
&generate_unique_module_name("test"),
)
.unwrap();

let subclass = module
.getattr("DictSubclass")
.unwrap()
.call1((dict,))
.unwrap()
.downcast_into::<PyDict>()
.unwrap();

let mut key_sum = 0;
let mut value_sum = 0;
let iter = subclass.iter();
assert!(matches!(iter, BoundDictIterator::ItemIter { .. }));
for (key, value) in iter {
key_sum += key.extract::<i32>().unwrap();
value_sum += value.extract::<i32>().unwrap();
}
assert_eq!(7 + 8 + 9, key_sum);
assert_eq!(32 + 42 + 123, value_sum);
});
}

#[test]
fn test_iter_bound() {
Python::with_gil(|py| {
Expand Down

0 comments on commit 3ace91a

Please sign in to comment.