File: test_static_slots.rs

package info (click to toggle)
rust-pyo3 0.22.6-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,420 kB
  • sloc: makefile: 58; python: 39; sh: 1
file content (72 lines) | stat: -rw-r--r-- 1,442 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#![cfg(feature = "macros")]

use pyo3::exceptions::PyIndexError;
use pyo3::prelude::*;
use pyo3::types::IntoPyDict;

use pyo3::py_run;

#[path = "../src/tests/common.rs"]
mod common;

#[pyclass]
struct Count5();

#[pymethods]
impl Count5 {
    #[new]
    fn new() -> Self {
        Self()
    }

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

    #[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 = Count5()`.
fn test_dict(py: Python<'_>) -> Bound<'_, pyo3::types::PyDict> {
    let d = [("Count5", py.get_type_bound::<Count5>())].into_py_dict_bound(py);
    // Though we can construct `s` in Rust, let's test `__new__` works.
    py_run!(py, *d, "s = Count5()");
    d
}

#[test]
fn test_len() {
    Python::with_gil(|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, "list(s) == [1.0, 2.0, 3.0, 4.0, 5.0]");
    });
}