File: test_class_conversion.rs

package info (click to toggle)
rust-pyo3 0.28.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,768 kB
  • sloc: javascript: 59; makefile: 58; python: 39; sh: 1
file content (155 lines) | stat: -rw-r--r-- 3,671 bytes parent folder | download
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#![cfg(feature = "macros")]

use pyo3::prelude::*;

#[macro_use]
mod test_utils;

#[pyclass(from_py_object)]
#[derive(Clone, Debug, PartialEq)]
struct Cloneable {
    x: i32,
}

#[test]
fn test_cloneable_pyclass() {
    let c = Cloneable { x: 10 };

    Python::attach(|py| {
        let py_c = Py::new(py, c.clone()).unwrap();

        let c2: Cloneable = py_c.extract(py).unwrap();
        assert_eq!(c, c2);
        {
            let rc: PyRef<'_, Cloneable> = py_c.extract(py).unwrap();
            assert_eq!(&c, &*rc);
            // Drops PyRef before taking PyRefMut
        }
        let mrc: PyRefMut<'_, Cloneable> = py_c.extract(py).unwrap();
        assert_eq!(&c, &*mrc);
    });
}

#[pyclass(subclass)]
#[derive(Default)]
struct BaseClass {
    value: i32,
}

#[pymethods]
impl BaseClass {
    fn foo(&self) -> &'static str {
        "BaseClass"
    }
}

#[pyclass(extends=BaseClass)]
struct SubClass {}

#[pymethods]
impl SubClass {
    fn foo(&self) -> &'static str {
        "SubClass"
    }
}

#[pyclass]
struct PolymorphicContainer {
    #[pyo3(get, set)]
    inner: Py<BaseClass>,
}

#[test]
fn test_polymorphic_container_stores_base_class() {
    Python::attach(|py| {
        let p = Py::new(
            py,
            PolymorphicContainer {
                inner: Py::new(py, BaseClass::default()).unwrap(),
            },
        )
        .unwrap();

        py_assert!(py, p, "p.inner.foo() == 'BaseClass'");
    });
}

#[test]
fn test_polymorphic_container_stores_sub_class() {
    Python::attach(|py| {
        let p = Py::new(
            py,
            PolymorphicContainer {
                inner: Py::new(py, BaseClass::default()).unwrap(),
            },
        )
        .unwrap();

        p.bind(py)
            .setattr(
                "inner",
                Py::new(
                    py,
                    PyClassInitializer::from(BaseClass::default()).add_subclass(SubClass {}),
                )
                .unwrap(),
            )
            .unwrap();

        py_assert!(py, p, "p.inner.foo() == 'SubClass'");
    });
}

#[test]
fn test_polymorphic_container_does_not_accept_other_types() {
    Python::attach(|py| {
        let p = Py::new(
            py,
            PolymorphicContainer {
                inner: Py::new(py, BaseClass::default()).unwrap(),
            },
        )
        .unwrap();

        let setattr = |value: Bound<'_, PyAny>| p.bind(py).setattr("inner", value);

        assert!(setattr(1i32.into_pyobject(py).unwrap().into_any()).is_err());
        assert!(setattr(py.None().into_bound(py)).is_err());
        assert!(setattr((1i32, 2i32).into_pyobject(py).unwrap().into_any()).is_err());
    });
}

#[test]
fn test_pyref_as_base() {
    Python::attach(|py| {
        let cell = Bound::new(py, (SubClass {}, BaseClass { value: 120 })).unwrap();

        // First try PyRefMut
        let sub: PyRefMut<'_, SubClass> = cell.borrow_mut();
        let mut base: PyRefMut<'_, BaseClass> = sub.into_super();
        assert_eq!(120, base.value);
        base.value = 999;
        assert_eq!(999, base.value);
        drop(base);

        // Repeat for PyRef
        let sub: PyRef<'_, SubClass> = cell.borrow();
        let base: PyRef<'_, BaseClass> = sub.into_super();
        assert_eq!(999, base.value);
    });
}

#[test]
fn test_pycell_deref() {
    Python::attach(|py| {
        let obj = Bound::new(py, (SubClass {}, BaseClass { value: 120 })).unwrap();

        // Should be able to deref as PyAny
        assert_eq!(
            obj.call_method0("foo")
                .and_then(|e| e.extract::<String>())
                .unwrap(),
            "SubClass"
        );
    });
}