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 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
|
#![cfg(feature = "macros")]
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::sync::GILOnceCell;
use pyo3::types::IntoPyDict;
#[pyclass]
struct EmptyClassWithNew {}
#[pymethods]
impl EmptyClassWithNew {
#[new]
fn new() -> EmptyClassWithNew {
EmptyClassWithNew {}
}
}
#[test]
fn empty_class_with_new() {
Python::with_gil(|py| {
let typeobj = py.get_type_bound::<EmptyClassWithNew>();
assert!(typeobj
.call((), None)
.unwrap()
.downcast::<EmptyClassWithNew>()
.is_ok());
// Calling with arbitrary args or kwargs is not ok
assert!(typeobj.call(("some", "args"), None).is_err());
assert!(typeobj
.call((), Some(&[("some", "kwarg")].into_py_dict_bound(py)))
.is_err());
});
}
#[pyclass]
struct UnitClassWithNew;
#[pymethods]
impl UnitClassWithNew {
#[new]
fn new() -> Self {
Self
}
}
#[test]
fn unit_class_with_new() {
Python::with_gil(|py| {
let typeobj = py.get_type_bound::<UnitClassWithNew>();
assert!(typeobj
.call((), None)
.unwrap()
.downcast::<UnitClassWithNew>()
.is_ok());
});
}
#[pyclass]
struct TupleClassWithNew(i32);
#[pymethods]
impl TupleClassWithNew {
#[new]
fn new(arg: i32) -> Self {
Self(arg)
}
}
#[test]
fn tuple_class_with_new() {
Python::with_gil(|py| {
let typeobj = py.get_type_bound::<TupleClassWithNew>();
let wrp = typeobj.call((42,), None).unwrap();
let obj = wrp.downcast::<TupleClassWithNew>().unwrap();
let obj_ref = obj.borrow();
assert_eq!(obj_ref.0, 42);
});
}
#[pyclass]
#[derive(Debug)]
struct NewWithOneArg {
data: i32,
}
#[pymethods]
impl NewWithOneArg {
#[new]
fn new(arg: i32) -> NewWithOneArg {
NewWithOneArg { data: arg }
}
}
#[test]
fn new_with_one_arg() {
Python::with_gil(|py| {
let typeobj = py.get_type_bound::<NewWithOneArg>();
let wrp = typeobj.call((42,), None).unwrap();
let obj = wrp.downcast::<NewWithOneArg>().unwrap();
let obj_ref = obj.borrow();
assert_eq!(obj_ref.data, 42);
});
}
#[pyclass]
struct NewWithTwoArgs {
data1: i32,
data2: i32,
}
#[pymethods]
impl NewWithTwoArgs {
#[new]
fn new(arg1: i32, arg2: i32) -> Self {
NewWithTwoArgs {
data1: arg1,
data2: arg2,
}
}
}
#[test]
fn new_with_two_args() {
Python::with_gil(|py| {
let typeobj = py.get_type_bound::<NewWithTwoArgs>();
let wrp = typeobj
.call((10, 20), None)
.map_err(|e| e.display(py))
.unwrap();
let obj = wrp.downcast::<NewWithTwoArgs>().unwrap();
let obj_ref = obj.borrow();
assert_eq!(obj_ref.data1, 10);
assert_eq!(obj_ref.data2, 20);
});
}
#[pyclass(subclass)]
struct SuperClass {
#[pyo3(get)]
from_rust: bool,
}
#[pymethods]
impl SuperClass {
#[new]
fn new() -> Self {
SuperClass { from_rust: true }
}
}
/// Checks that `subclass.__new__` works correctly.
/// See https://github.com/PyO3/pyo3/issues/947 for the corresponding bug.
#[test]
fn subclass_new() {
Python::with_gil(|py| {
let super_cls = py.get_type_bound::<SuperClass>();
let source = pyo3::indoc::indoc!(
r#"
class Class(SuperClass):
def __new__(cls):
return super().__new__(cls) # This should return an instance of Class
@property
def from_rust(self):
return False
c = Class()
assert c.from_rust is False
"#
);
let globals = PyModule::import_bound(py, "__main__").unwrap().dict();
globals.set_item("SuperClass", super_cls).unwrap();
py.run_bound(source, Some(&globals), None)
.map_err(|e| e.display(py))
.unwrap();
});
}
#[pyclass]
#[derive(Debug)]
struct NewWithCustomError {}
struct CustomError;
impl From<CustomError> for PyErr {
fn from(_error: CustomError) -> PyErr {
PyValueError::new_err("custom error")
}
}
#[pymethods]
impl NewWithCustomError {
#[new]
fn new() -> Result<NewWithCustomError, CustomError> {
Err(CustomError)
}
}
#[test]
fn new_with_custom_error() {
Python::with_gil(|py| {
let typeobj = py.get_type_bound::<NewWithCustomError>();
let err = typeobj.call0().unwrap_err();
assert_eq!(err.to_string(), "ValueError: custom error");
});
}
#[pyclass]
struct NewExisting {
#[pyo3(get)]
num: usize,
}
#[pymethods]
impl NewExisting {
#[new]
fn new(py: pyo3::Python<'_>, val: usize) -> pyo3::Py<NewExisting> {
static PRE_BUILT: GILOnceCell<[pyo3::Py<NewExisting>; 2]> = GILOnceCell::new();
let existing = PRE_BUILT.get_or_init(py, || {
[
pyo3::Py::new(py, NewExisting { num: 0 }).unwrap(),
pyo3::Py::new(py, NewExisting { num: 1 }).unwrap(),
]
});
if val < existing.len() {
return existing[val].clone_ref(py);
}
pyo3::Py::new(py, NewExisting { num: val }).unwrap()
}
}
#[test]
fn test_new_existing() {
Python::with_gil(|py| {
let typeobj = py.get_type_bound::<NewExisting>();
let obj1 = typeobj.call1((0,)).unwrap();
let obj2 = typeobj.call1((0,)).unwrap();
let obj3 = typeobj.call1((1,)).unwrap();
let obj4 = typeobj.call1((1,)).unwrap();
let obj5 = typeobj.call1((2,)).unwrap();
let obj6 = typeobj.call1((2,)).unwrap();
assert!(obj1.getattr("num").unwrap().extract::<u32>().unwrap() == 0);
assert!(obj2.getattr("num").unwrap().extract::<u32>().unwrap() == 0);
assert!(obj3.getattr("num").unwrap().extract::<u32>().unwrap() == 1);
assert!(obj4.getattr("num").unwrap().extract::<u32>().unwrap() == 1);
assert!(obj5.getattr("num").unwrap().extract::<u32>().unwrap() == 2);
assert!(obj6.getattr("num").unwrap().extract::<u32>().unwrap() == 2);
assert!(obj1.is(&obj2));
assert!(obj3.is(&obj4));
assert!(!obj1.is(&obj3));
assert!(!obj1.is(&obj5));
assert!(!obj5.is(&obj6));
});
}
#[pyclass]
struct NewReturnsPy;
#[pymethods]
impl NewReturnsPy {
#[new]
fn new(py: Python<'_>) -> PyResult<Py<NewReturnsPy>> {
Py::new(py, NewReturnsPy)
}
}
#[test]
fn test_new_returns_py() {
Python::with_gil(|py| {
let type_ = py.get_type_bound::<NewReturnsPy>();
let obj = type_.call0().unwrap();
assert!(obj.is_exact_instance_of::<NewReturnsPy>());
})
}
#[pyclass]
struct NewReturnsBound;
#[pymethods]
impl NewReturnsBound {
#[new]
fn new(py: Python<'_>) -> PyResult<Bound<'_, NewReturnsBound>> {
Bound::new(py, NewReturnsBound)
}
}
#[test]
fn test_new_returns_bound() {
Python::with_gil(|py| {
let type_ = py.get_type_bound::<NewReturnsBound>();
let obj = type_.call0().unwrap();
assert!(obj.is_exact_instance_of::<NewReturnsBound>());
})
}
|