Skip to content

Commit

Permalink
Add test of slf: PyRefMut<_>
Browse files Browse the repository at this point in the history
  • Loading branch information
kngwyu committed Apr 3, 2019
1 parent bc2aecb commit 43349fa
Showing 1 changed file with 38 additions and 7 deletions.
45 changes: 38 additions & 7 deletions tests/test_nested_iter.rs → tests/test_pyself.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
//! Rust value -> Python Iterator
//! Inspired by https://github.com/jothan/cordoba, thanks.
//! Test slf: PyRef/PyMutRef<Self>(especially, slf.into::<Py>) works
use pyo3;
use pyo3::prelude::*;
use pyo3::types::{PyBytes, PyString};
Expand All @@ -10,20 +9,32 @@ use std::collections::HashMap;
mod common;

/// Assumes it's a file reader or so.
/// Inspired by https://github.com/jothan/cordoba, thanks.
#[pyclass]
#[derive(Clone)]
struct Reader {
inner: HashMap<u8, String>,
}

#[pymethods]
impl Reader {
fn get_optional(&self, test: Option<i32>) -> PyResult<i32> {
Ok(test.unwrap_or(10))
}
fn get_iter(slf: PyRef<Self>, keys: Py<PyBytes>) -> PyResult<Iter> {
Ok(Iter {
reader: slf.into(),
keys: keys,
keys,
idx: 0,
})
}
fn get_iter_and_reset(
mut slf: PyRefMut<Self>,
keys: Py<PyBytes>,
py: Python,
) -> PyResult<Iter> {
let reader = Py::new(py, slf.clone())?;
slf.inner.clear();
Ok(Iter {
reader,
keys,
idx: 0,
})
}
Expand All @@ -42,7 +53,6 @@ impl PyIterProtocol for Iter {
let py = unsafe { Python::assume_gil_acquired() };
Ok(slf.to_object(py))
}

fn __next__(mut slf: PyRefMut<Self>) -> PyResult<Option<PyObject>> {
let py = unsafe { Python::assume_gil_acquired() };
match slf.keys.as_ref(py).as_bytes().get(slf.idx) {
Expand Down Expand Up @@ -76,3 +86,24 @@ fn test_nested_iter() {
"list(reader.get_iter(bytes([3, 5, 2]))) == ['c', 'e', 'b']"
);
}

#[test]
fn test_nested_iter_reset() {
let gil = Python::acquire_gil();
let py = gil.python();
let reader = [(1, "a"), (2, "b"), (3, "c"), (4, "d"), (5, "e")];
let reader = PyRef::new(
py,
Reader {
inner: reader.iter().map(|(k, v)| (*k, v.to_string())).collect(),
},
)
.unwrap();
let obj = reader.into_object(py);
py_assert!(
py,
obj,
"list(obj.get_iter_and_reset(bytes([3, 5, 2]))) == ['c', 'e', 'b']"
);
assert!(reader.inner.is_empty());
}

0 comments on commit 43349fa

Please sign in to comment.