Skip to content

Commit

Permalink
Test static __getitem__ as well as __len__
Browse files Browse the repository at this point in the history
  • Loading branch information
willstott101 committed Mar 18, 2023
1 parent bcdb17d commit b057953
Showing 1 changed file with 38 additions and 24 deletions.
62 changes: 38 additions & 24 deletions tests/test_static_slots.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,49 +9,63 @@ use pyo3::py_run;
mod common;

#[pyclass]
struct Vector3 {
elements: [f64; 3],
}
struct Count5();

#[pymethods]
impl Vector3 {
impl Count5 {
#[new]
fn new(x: f64, y: f64, z: f64) -> Self {
Self {
elements: [x, y, z],
}
fn new() -> Self {
Self()
}

#[staticmethod]
fn __len__() -> usize {
3
5
}

fn __getitem__(&self, idx: isize) -> PyResult<f64> {
self.elements
.get(idx as usize)
.copied()
.ok_or_else(|| PyIndexError::new_err("list index out of range"))
}

fn __setitem__(&mut self, idx: isize, value: f64) {
self.elements[idx as usize] = value;
#[staticmethod]
fn __getitem__(idx: isize) -> PyResult<f64> {
if idx < 0 {
Err(PyIndexError::new_err("Count5 cannot count backwards"))
} else if idx > 4 {
Err(PyIndexError::new_err("Count5 cannot count higher than 5"))
} else {
Ok(idx as f64 + 1.0)
}
}
}

/// Return a dict with `s = Vector3(1, 2, 3)`.
fn seq_dict(py: Python<'_>) -> &pyo3::types::PyDict {
let d = [("Vector3", py.get_type::<Vector3>())].into_py_dict(py);
/// Return a dict with `s = Count5()`.
fn test_dict(py: Python<'_>) -> &pyo3::types::PyDict {
let d = [("Count5", py.get_type::<Count5>())].into_py_dict(py);
// Though we can construct `s` in Rust, let's test `__new__` works.
py_run!(py, *d, "s = Vector3(1, 2, 3)");
py_run!(py, *d, "s = Count5()");
d
}

#[test]
fn test_len() {
Python::with_gil(|py| {
let d = seq_dict(py);
let d = test_dict(py);

py_assert!(py, *d, "len(s) == 5");
});
}

#[test]
fn test_getitem() {
Python::with_gil(|py| {
let d = test_dict(py);

py_assert!(py, *d, "s[4] == 5.0");
});
}

#[test]
fn test_list() {
Python::with_gil(|py| {
let d = test_dict(py);

py_assert!(py, *d, "len(s) == 3");
py_assert!(py, *d, "list(s) == [1.0, 2.0, 3.0, 4.0, 5.0]");
});
}

0 comments on commit b057953

Please sign in to comment.