Add tests for mutability checking

This commit is contained in:
kngwyu 2020-02-18 14:20:39 +09:00
parent 4b746af11b
commit 1f5cb83ef8
2 changed files with 43 additions and 0 deletions

View File

@ -22,6 +22,7 @@ pub unsafe trait PyObjectLayout<T: PyTypeInfo> {
unsafe fn py_init(&mut self, _value: T) {}
unsafe fn py_drop(&mut self, _py: Python) {}
unsafe fn unchecked_ref(&self) -> &T;
#[allow(clippy::mut_from_ref)]
unsafe fn unchecked_mut(&self) -> &mut T;
}

View File

@ -36,6 +36,14 @@ impl BaseClass {
fn new() -> Self {
BaseClass { val1: 10 }
}
fn base_method(&self, x: usize) -> usize {
x * self.val1
}
fn base_set(&mut self, fn_: &pyo3::types::PyAny) -> PyResult<()> {
let value: usize = fn_.call0()?.extract()?;
self.val1 = value;
Ok(())
}
}
#[pyclass(extends=BaseClass)]
@ -50,6 +58,13 @@ impl SubClass {
fn new() -> (Self, BaseClass) {
(SubClass { val2: 5 }, BaseClass { val1: 10 })
}
fn sub_method(&self, x: usize) -> usize {
x * self.val2
}
fn sub_set_and_ret(&mut self, x: usize) -> usize {
self.val2 = x;
x
}
}
#[test]
@ -61,6 +76,33 @@ fn inheritance_with_new_methods() {
py_run!(py, inst, "assert inst.val1 == 10; assert inst.val2 == 5");
}
#[test]
fn call_base_and_sub_methods() {
let gil = Python::acquire_gil();
let py = gil.python();
let obj = PyCell::new(py, SubClass::new()).unwrap();
py_run!(
py,
obj,
r#"
assert obj.base_method(10) == 100
assert obj.sub_method(10) == 50
"#
);
}
#[test]
fn mutation_fails() {
let gil = Python::acquire_gil();
let py = gil.python();
let obj = PyCell::new(py, SubClass::new()).unwrap();
let global = Some([("obj", obj)].into_py_dict(py));
let e = py
.run("obj.base_set(lambda: obj.sub_set_and_ret(1))", global, None)
.unwrap_err();
assert!(e.is_instance::<pyo3::pycell::PyBorrowMutError>(py))
}
#[pyclass]
struct BaseClassWithResult {
_val: usize,