pyo3/tests/test_inheritance.rs

67 lines
1.3 KiB
Rust
Raw Normal View History

use pyo3::prelude::*;
2019-06-13 09:09:17 +00:00
use pyo3::py_run;
#[cfg(feature = "unsound-subclass")]
use pyo3::types::IntoPyDict;
use std::isize;
mod common;
#[pyclass]
struct BaseClass {
#[pyo3(get)]
val1: usize,
}
#[cfg(feature = "unsound-subclass")]
#[pyclass(subclass)]
struct SubclassAble {}
#[cfg(feature = "unsound-subclass")]
#[test]
fn subclass() {
let gil = Python::acquire_gil();
let py = gil.python();
let d = [("SubclassAble", py.get_type::<SubclassAble>())].into_py_dict(py);
py.run(
"class A(SubclassAble): pass\nassert issubclass(A, SubclassAble)",
None,
Some(d),
)
.map_err(|e| e.print(py))
.unwrap();
}
#[pymethods]
impl BaseClass {
#[new]
2019-02-23 17:38:00 +00:00
fn new(obj: &PyRawObject) {
obj.init(BaseClass { val1: 10 })
}
}
#[pyclass(extends=BaseClass)]
struct SubClass {
#[pyo3(get)]
val2: usize,
}
#[pymethods]
impl SubClass {
#[new]
2019-02-23 17:38:00 +00:00
fn new(obj: &PyRawObject) {
obj.init(SubClass { val2: 5 });
2019-02-23 17:38:00 +00:00
BaseClass::new(obj);
}
}
#[test]
fn inheritance_with_new_methods() {
let gil = Python::acquire_gil();
let py = gil.python();
let _typebase = py.get_type::<BaseClass>();
let typeobj = py.get_type::<SubClass>();
2019-02-23 17:01:22 +00:00
let inst = typeobj.call((), None).unwrap();
py_run!(py, inst, "assert inst.val1 == 10; assert inst.val2 == 5");
}