pyo3/tests/test_mapping.rs

106 lines
2.6 KiB
Rust
Raw Normal View History

2021-12-03 00:03:32 +00:00
#![cfg(feature = "macros")]
use std::collections::HashMap;
use pyo3::exceptions::PyKeyError;
use pyo3::prelude::*;
2021-03-14 07:34:05 +00:00
use pyo3::py_run;
use pyo3::types::IntoPyDict;
use pyo3::types::PyList;
2021-03-14 07:34:05 +00:00
mod common;
#[pyclass]
struct Mapping {
index: HashMap<String, usize>,
}
#[pymethods]
impl Mapping {
#[new]
2019-12-14 14:16:39 +00:00
fn new(elements: Option<&PyList>) -> PyResult<Self> {
if let Some(pylist) = elements {
let mut elems = HashMap::with_capacity(pylist.len());
for (i, pyelem) in pylist.into_iter().enumerate() {
let elem = String::extract(pyelem)?;
elems.insert(elem, i);
}
2019-12-14 14:16:39 +00:00
Ok(Self { index: elems })
} else {
2019-12-14 14:16:39 +00:00
Ok(Self {
index: HashMap::new(),
2019-12-14 14:16:39 +00:00
})
}
}
fn __len__(&self) -> usize {
self.index.len()
}
fn __getitem__(&self, query: String) -> PyResult<usize> {
self.index
.get(&query)
.copied()
2020-08-25 19:33:36 +00:00
.ok_or_else(|| PyKeyError::new_err("unknown key"))
}
fn __setitem__(&mut self, key: String, value: usize) {
self.index.insert(key, value);
}
fn __delitem__(&mut self, key: String) -> PyResult<()> {
if self.index.remove(&key).is_none() {
2020-08-25 19:33:36 +00:00
Err(PyKeyError::new_err("unknown key"))
} else {
Ok(())
}
}
}
2021-03-14 07:34:05 +00:00
/// Return a dict with `m = Mapping(['1', '2', '3'])`.
fn map_dict(py: Python) -> &pyo3::types::PyDict {
let d = [("Mapping", py.get_type::<Mapping>())].into_py_dict(py);
py_run!(py, *d, "m = Mapping(['1', '2', '3'])");
d
}
#[test]
fn test_getitem() {
let gil = Python::acquire_gil();
let py = gil.python();
2021-03-14 07:34:05 +00:00
let d = map_dict(py);
2021-03-14 07:34:05 +00:00
py_assert!(py, *d, "m['1'] == 0");
py_assert!(py, *d, "m['2'] == 1");
py_assert!(py, *d, "m['3'] == 2");
py_expect_exception!(py, *d, "print(m['4'])", PyKeyError);
}
#[test]
fn test_setitem() {
let gil = Python::acquire_gil();
let py = gil.python();
2021-03-14 07:34:05 +00:00
let d = map_dict(py);
2021-03-14 07:34:05 +00:00
py_run!(py, *d, "m['1'] = 4; assert m['1'] == 4");
py_run!(py, *d, "m['0'] = 0; assert m['0'] == 0");
py_assert!(py, *d, "len(m) == 4");
py_expect_exception!(py, *d, "m[0] = 'hello'", PyTypeError);
py_expect_exception!(py, *d, "m[0] = -1", PyTypeError);
}
#[test]
fn test_delitem() {
let gil = Python::acquire_gil();
let py = gil.python();
2021-03-14 07:34:05 +00:00
let d = map_dict(py);
py_run!(
py,
*d,
"del m['1']; assert len(m) == 2 and m['2'] == 1 and m['3'] == 2"
);
2021-03-14 07:34:05 +00:00
py_expect_exception!(py, *d, "del m[-1]", PyTypeError);
py_expect_exception!(py, *d, "del m['4']", PyKeyError);
}