2018-09-21 21:32:48 +00:00
|
|
|
use pyo3::class::{
|
2020-06-15 04:43:46 +00:00
|
|
|
PyAsyncProtocol, PyContextProtocol, PyDescrProtocol, PyIterProtocol, PyMappingProtocol,
|
|
|
|
PyObjectProtocol, PySequenceProtocol,
|
2018-09-21 21:32:48 +00:00
|
|
|
};
|
2020-07-04 15:55:26 +00:00
|
|
|
use pyo3::exceptions::{PyIndexError, PyValueError};
|
2018-05-02 18:49:40 +00:00
|
|
|
use pyo3::prelude::*;
|
2020-07-13 21:38:02 +00:00
|
|
|
use pyo3::types::{IntoPyDict, PySlice, PyType};
|
2020-02-03 13:25:16 +00:00
|
|
|
use pyo3::{ffi, py_run, AsPyPointer, PyCell};
|
2019-10-12 12:03:21 +00:00
|
|
|
use std::convert::TryFrom;
|
2019-02-18 19:07:41 +00:00
|
|
|
use std::{isize, iter};
|
2018-05-02 18:49:40 +00:00
|
|
|
|
|
|
|
mod common;
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyclass]
|
2018-05-02 18:49:40 +00:00
|
|
|
pub struct Len {
|
|
|
|
l: usize,
|
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyproto]
|
2018-05-02 18:49:40 +00:00
|
|
|
impl PyMappingProtocol for Len {
|
2020-06-23 10:40:17 +00:00
|
|
|
fn __len__(&self) -> usize {
|
|
|
|
self.l
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn len() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
|
|
|
|
2019-02-07 18:07:09 +00:00
|
|
|
let inst = Py::new(py, Len { l: 10 }).unwrap();
|
2018-05-02 18:49:40 +00:00
|
|
|
py_assert!(py, inst, "len(inst) == 10");
|
|
|
|
unsafe {
|
|
|
|
assert_eq!(ffi::PyObject_Size(inst.as_ptr()), 10);
|
|
|
|
assert_eq!(ffi::PyMapping_Size(inst.as_ptr()), 10);
|
|
|
|
}
|
|
|
|
|
2019-02-07 18:07:09 +00:00
|
|
|
let inst = Py::new(
|
|
|
|
py,
|
|
|
|
Len {
|
|
|
|
l: (isize::MAX as usize) + 1,
|
|
|
|
},
|
|
|
|
)
|
2018-09-28 21:34:57 +00:00
|
|
|
.unwrap();
|
2020-07-04 15:55:26 +00:00
|
|
|
py_expect_exception!(py, inst, "len(inst)", PyOverflowError);
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyclass]
|
2018-06-15 19:21:12 +00:00
|
|
|
struct Iterator {
|
2019-06-05 10:01:09 +00:00
|
|
|
iter: Box<dyn iter::Iterator<Item = i32> + Send>,
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyproto]
|
2020-08-08 07:55:08 +00:00
|
|
|
impl PyIterProtocol for Iterator {
|
|
|
|
fn __iter__(slf: PyRef<Self>) -> PyRef<Self> {
|
|
|
|
slf
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
|
2020-08-08 07:55:08 +00:00
|
|
|
fn __next__(mut slf: PyRefMut<Self>) -> Option<i32> {
|
2020-06-23 10:40:17 +00:00
|
|
|
slf.iter.next()
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn iterator() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
|
|
|
|
2019-02-07 18:07:09 +00:00
|
|
|
let inst = Py::new(
|
|
|
|
py,
|
|
|
|
Iterator {
|
|
|
|
iter: Box::new(5..8),
|
|
|
|
},
|
|
|
|
)
|
2018-09-28 21:34:57 +00:00
|
|
|
.unwrap();
|
2018-05-02 18:49:40 +00:00
|
|
|
py_assert!(py, inst, "iter(inst) is inst");
|
|
|
|
py_assert!(py, inst, "list(inst) == [5, 6, 7]");
|
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyclass]
|
2018-11-12 12:59:19 +00:00
|
|
|
struct StringMethods {}
|
2018-05-02 18:49:40 +00:00
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyproto]
|
2020-08-08 07:55:08 +00:00
|
|
|
impl PyObjectProtocol for StringMethods {
|
2020-06-23 10:40:17 +00:00
|
|
|
fn __str__(&self) -> &'static str {
|
|
|
|
"str"
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
|
2020-06-23 10:40:17 +00:00
|
|
|
fn __repr__(&self) -> &'static str {
|
|
|
|
"repr"
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
|
2020-06-23 10:40:17 +00:00
|
|
|
fn __format__(&self, format_spec: String) -> String {
|
|
|
|
format!("format({})", format_spec)
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
|
2020-07-13 21:38:02 +00:00
|
|
|
fn __bytes__(&self) -> &'static [u8] {
|
|
|
|
b"bytes"
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn string_methods() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
|
|
|
|
2019-02-07 18:07:09 +00:00
|
|
|
let obj = Py::new(py, StringMethods {}).unwrap();
|
2018-05-02 18:49:40 +00:00
|
|
|
py_assert!(py, obj, "str(obj) == 'str'");
|
|
|
|
py_assert!(py, obj, "repr(obj) == 'repr'");
|
|
|
|
py_assert!(py, obj, "'{0:x}'.format(obj) == 'format(x)'");
|
|
|
|
py_assert!(py, obj, "bytes(obj) == b'bytes'");
|
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyclass]
|
2018-05-02 18:49:40 +00:00
|
|
|
struct Comparisons {
|
|
|
|
val: i32,
|
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyproto]
|
2018-05-02 18:49:40 +00:00
|
|
|
impl PyObjectProtocol for Comparisons {
|
2020-06-23 10:40:17 +00:00
|
|
|
fn __hash__(&self) -> isize {
|
|
|
|
self.val as isize
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
2020-06-23 10:40:17 +00:00
|
|
|
fn __bool__(&self) -> bool {
|
|
|
|
self.val != 0
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn comparisons() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
|
|
|
|
2019-02-07 18:07:09 +00:00
|
|
|
let zero = Py::new(py, Comparisons { val: 0 }).unwrap();
|
|
|
|
let one = Py::new(py, Comparisons { val: 1 }).unwrap();
|
|
|
|
let ten = Py::new(py, Comparisons { val: 10 }).unwrap();
|
|
|
|
let minus_one = Py::new(py, Comparisons { val: -1 }).unwrap();
|
2018-05-02 18:49:40 +00:00
|
|
|
py_assert!(py, one, "hash(one) == 1");
|
|
|
|
py_assert!(py, ten, "hash(ten) == 10");
|
|
|
|
py_assert!(py, minus_one, "hash(minus_one) == -2");
|
|
|
|
|
|
|
|
py_assert!(py, one, "bool(one) is True");
|
|
|
|
py_assert!(py, zero, "not zero");
|
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyclass]
|
2019-10-12 12:03:21 +00:00
|
|
|
#[derive(Debug)]
|
|
|
|
struct Sequence {
|
|
|
|
fields: Vec<String>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for Sequence {
|
|
|
|
fn default() -> Sequence {
|
|
|
|
let mut fields = vec![];
|
2020-02-10 02:20:18 +00:00
|
|
|
for &s in &["A", "B", "C", "D", "E", "F", "G"] {
|
2019-10-12 12:03:21 +00:00
|
|
|
fields.push(s.to_string());
|
|
|
|
}
|
|
|
|
Sequence { fields }
|
|
|
|
}
|
|
|
|
}
|
2018-05-02 18:49:40 +00:00
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyproto]
|
2018-05-02 18:49:40 +00:00
|
|
|
impl PySequenceProtocol for Sequence {
|
2020-06-23 10:40:17 +00:00
|
|
|
fn __len__(&self) -> usize {
|
|
|
|
self.fields.len()
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
|
2019-10-12 12:03:21 +00:00
|
|
|
fn __getitem__(&self, key: isize) -> PyResult<String> {
|
|
|
|
let idx = usize::try_from(key)?;
|
|
|
|
if let Some(s) = self.fields.get(idx) {
|
|
|
|
Ok(s.clone())
|
|
|
|
} else {
|
2020-08-25 19:33:36 +00:00
|
|
|
Err(PyIndexError::new_err(()))
|
2019-10-12 12:03:21 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn __setitem__(&mut self, idx: isize, value: String) -> PyResult<()> {
|
|
|
|
let idx = usize::try_from(idx)?;
|
|
|
|
if let Some(elem) = self.fields.get_mut(idx) {
|
|
|
|
*elem = value;
|
|
|
|
Ok(())
|
|
|
|
} else {
|
2020-08-25 19:33:36 +00:00
|
|
|
Err(PyIndexError::new_err(()))
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn sequence() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
|
|
|
|
2019-10-12 12:03:21 +00:00
|
|
|
let c = Py::new(py, Sequence::default()).unwrap();
|
|
|
|
py_assert!(py, c, "list(c) == ['A', 'B', 'C', 'D', 'E', 'F', 'G']");
|
|
|
|
py_assert!(py, c, "c[-1] == 'G'");
|
|
|
|
py_run!(
|
|
|
|
py,
|
|
|
|
c,
|
|
|
|
r#"
|
|
|
|
c[0] = 'H'
|
|
|
|
assert c[0] == 'H'
|
|
|
|
"#
|
|
|
|
);
|
2020-07-04 15:55:26 +00:00
|
|
|
py_expect_exception!(py, c, "c['abc']", PyTypeError);
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyclass]
|
2018-11-12 12:59:19 +00:00
|
|
|
struct Callable {}
|
2018-05-02 18:49:40 +00:00
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pymethods]
|
2018-05-02 18:49:40 +00:00
|
|
|
impl Callable {
|
|
|
|
#[__call__]
|
2020-06-23 10:40:17 +00:00
|
|
|
fn __call__(&self, arg: i32) -> i32 {
|
|
|
|
arg * 6
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn callable() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
|
|
|
|
2019-02-13 20:35:26 +00:00
|
|
|
let c = Py::new(py, Callable {}).unwrap();
|
2018-05-02 18:49:40 +00:00
|
|
|
py_assert!(py, c, "callable(c)");
|
|
|
|
py_assert!(py, c, "c(7) == 42");
|
|
|
|
|
2019-02-13 20:35:26 +00:00
|
|
|
let nc = Py::new(py, Comparisons { val: 0 }).unwrap();
|
2018-05-02 18:49:40 +00:00
|
|
|
py_assert!(py, nc, "not callable(nc)");
|
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyclass]
|
2020-02-15 15:24:38 +00:00
|
|
|
#[derive(Debug)]
|
2018-05-02 18:49:40 +00:00
|
|
|
struct SetItem {
|
|
|
|
key: i32,
|
|
|
|
val: i32,
|
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyproto]
|
2020-08-08 07:55:08 +00:00
|
|
|
impl PyMappingProtocol for SetItem {
|
2020-06-23 10:40:17 +00:00
|
|
|
fn __setitem__(&mut self, key: i32, val: i32) {
|
2018-05-02 18:49:40 +00:00
|
|
|
self.key = key;
|
|
|
|
self.val = val;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn setitem() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
|
|
|
|
2020-02-15 15:24:38 +00:00
|
|
|
let c = PyCell::new(py, SetItem { key: 0, val: 0 }).unwrap();
|
2018-05-02 18:49:40 +00:00
|
|
|
py_run!(py, c, "c[1] = 2");
|
2020-02-15 15:24:38 +00:00
|
|
|
{
|
|
|
|
let c = c.borrow();
|
|
|
|
assert_eq!(c.key, 1);
|
|
|
|
assert_eq!(c.val, 2);
|
|
|
|
}
|
2020-07-04 15:55:26 +00:00
|
|
|
py_expect_exception!(py, c, "del c[1]", PyNotImplementedError);
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyclass]
|
2018-05-02 18:49:40 +00:00
|
|
|
struct DelItem {
|
|
|
|
key: i32,
|
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyproto]
|
2018-05-02 18:49:40 +00:00
|
|
|
impl PyMappingProtocol<'a> for DelItem {
|
2020-06-23 10:40:17 +00:00
|
|
|
fn __delitem__(&mut self, key: i32) {
|
2018-05-02 18:49:40 +00:00
|
|
|
self.key = key;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn delitem() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
|
|
|
|
2020-02-15 15:24:38 +00:00
|
|
|
let c = PyCell::new(py, DelItem { key: 0 }).unwrap();
|
2018-05-02 18:49:40 +00:00
|
|
|
py_run!(py, c, "del c[1]");
|
2020-02-15 15:24:38 +00:00
|
|
|
{
|
|
|
|
let c = c.borrow();
|
|
|
|
assert_eq!(c.key, 1);
|
|
|
|
}
|
2020-07-04 15:55:26 +00:00
|
|
|
py_expect_exception!(py, c, "c[1] = 2", PyNotImplementedError);
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyclass]
|
2018-05-02 18:49:40 +00:00
|
|
|
struct SetDelItem {
|
|
|
|
val: Option<i32>,
|
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyproto]
|
2018-05-02 18:49:40 +00:00
|
|
|
impl PyMappingProtocol for SetDelItem {
|
2020-06-23 10:40:17 +00:00
|
|
|
fn __setitem__(&mut self, _key: i32, val: i32) {
|
2018-05-02 18:49:40 +00:00
|
|
|
self.val = Some(val);
|
|
|
|
}
|
|
|
|
|
2020-06-23 10:40:17 +00:00
|
|
|
fn __delitem__(&mut self, _key: i32) {
|
2018-05-02 18:49:40 +00:00
|
|
|
self.val = None;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn setdelitem() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
|
|
|
|
2020-02-15 15:24:38 +00:00
|
|
|
let c = PyCell::new(py, SetDelItem { val: None }).unwrap();
|
2018-05-02 18:49:40 +00:00
|
|
|
py_run!(py, c, "c[1] = 2");
|
2020-02-15 15:24:38 +00:00
|
|
|
{
|
|
|
|
let c = c.borrow();
|
|
|
|
assert_eq!(c.val, Some(2));
|
|
|
|
}
|
2018-05-02 18:49:40 +00:00
|
|
|
py_run!(py, c, "del c[1]");
|
2020-02-15 15:24:38 +00:00
|
|
|
let c = c.borrow();
|
2018-05-02 18:49:40 +00:00
|
|
|
assert_eq!(c.val, None);
|
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyclass]
|
2018-11-12 12:59:19 +00:00
|
|
|
struct Reversed {}
|
2018-05-02 18:49:40 +00:00
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyproto]
|
2018-06-15 19:21:12 +00:00
|
|
|
impl PyMappingProtocol for Reversed {
|
2020-06-23 10:40:17 +00:00
|
|
|
fn __reversed__(&self) -> &'static str {
|
|
|
|
"I am reversed"
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn reversed() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
|
|
|
|
2019-02-13 20:35:26 +00:00
|
|
|
let c = Py::new(py, Reversed {}).unwrap();
|
2018-05-02 18:49:40 +00:00
|
|
|
py_run!(py, c, "assert reversed(c) == 'I am reversed'");
|
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyclass]
|
2018-11-12 12:59:19 +00:00
|
|
|
struct Contains {}
|
2018-05-02 18:49:40 +00:00
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyproto]
|
2018-05-02 18:49:40 +00:00
|
|
|
impl PySequenceProtocol for Contains {
|
2020-06-23 10:40:17 +00:00
|
|
|
fn __contains__(&self, item: i32) -> bool {
|
|
|
|
item >= 0
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn contains() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
|
|
|
|
2019-02-13 20:35:26 +00:00
|
|
|
let c = Py::new(py, Contains {}).unwrap();
|
2018-05-02 18:49:40 +00:00
|
|
|
py_run!(py, c, "assert 1 in c");
|
|
|
|
py_run!(py, c, "assert -1 not in c");
|
2020-07-04 15:55:26 +00:00
|
|
|
py_expect_exception!(py, c, "assert 'wrong type' not in c", PyTypeError);
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyclass]
|
2018-05-02 18:49:40 +00:00
|
|
|
struct ContextManager {
|
|
|
|
exit_called: bool,
|
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyproto]
|
2020-08-08 07:55:08 +00:00
|
|
|
impl PyContextProtocol for ContextManager {
|
2020-06-23 10:40:17 +00:00
|
|
|
fn __enter__(&mut self) -> i32 {
|
|
|
|
42
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
|
2018-06-15 19:21:12 +00:00
|
|
|
fn __exit__(
|
|
|
|
&mut self,
|
2020-08-08 07:55:08 +00:00
|
|
|
ty: Option<&PyType>,
|
|
|
|
_value: Option<&PyAny>,
|
|
|
|
_traceback: Option<&PyAny>,
|
2020-06-23 10:40:17 +00:00
|
|
|
) -> bool {
|
2020-07-13 21:38:02 +00:00
|
|
|
let gil = Python::acquire_gil();
|
2018-05-02 18:49:40 +00:00
|
|
|
self.exit_called = true;
|
2020-07-04 15:55:26 +00:00
|
|
|
ty == Some(gil.python().get_type::<PyValueError>())
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn context_manager() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
|
|
|
|
2020-02-15 15:24:38 +00:00
|
|
|
let c = PyCell::new(py, ContextManager { exit_called: false }).unwrap();
|
2018-06-13 16:02:45 +00:00
|
|
|
py_run!(py, c, "with c as x: assert x == 42");
|
2020-02-15 15:24:38 +00:00
|
|
|
{
|
|
|
|
let mut c = c.borrow_mut();
|
|
|
|
assert!(c.exit_called);
|
|
|
|
c.exit_called = false;
|
|
|
|
}
|
2018-06-13 16:02:45 +00:00
|
|
|
py_run!(py, c, "with c as x: raise ValueError");
|
2020-02-15 15:24:38 +00:00
|
|
|
{
|
|
|
|
let mut c = c.borrow_mut();
|
|
|
|
assert!(c.exit_called);
|
|
|
|
c.exit_called = false;
|
|
|
|
}
|
2018-05-02 18:49:40 +00:00
|
|
|
py_expect_exception!(
|
2018-06-15 19:21:12 +00:00
|
|
|
py,
|
|
|
|
c,
|
|
|
|
"with c as x: raise NotImplementedError",
|
2020-07-04 15:55:26 +00:00
|
|
|
PyNotImplementedError
|
2018-06-15 19:21:12 +00:00
|
|
|
);
|
2020-02-15 15:24:38 +00:00
|
|
|
let c = c.borrow();
|
2018-05-02 18:49:40 +00:00
|
|
|
assert!(c.exit_called);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_basics() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
|
|
|
|
|
|
|
let v = PySlice::new(py, 1, 10, 2);
|
|
|
|
let indices = v.indices(100).unwrap();
|
|
|
|
assert_eq!(1, indices.start);
|
|
|
|
assert_eq!(10, indices.stop);
|
|
|
|
assert_eq!(2, indices.step);
|
|
|
|
assert_eq!(5, indices.slicelength);
|
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyclass]
|
2018-11-12 12:59:19 +00:00
|
|
|
struct Test {}
|
2018-05-02 18:49:40 +00:00
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyproto]
|
2018-06-15 19:21:12 +00:00
|
|
|
impl<'p> PyMappingProtocol<'p> for Test {
|
2020-07-13 21:38:02 +00:00
|
|
|
fn __getitem__(&self, idx: &PyAny) -> PyResult<&'static str> {
|
2018-05-02 18:49:40 +00:00
|
|
|
if let Ok(slice) = idx.cast_as::<PySlice>() {
|
|
|
|
let indices = slice.indices(1000)?;
|
|
|
|
if indices.start == 100 && indices.stop == 200 && indices.step == 1 {
|
2020-07-13 21:38:02 +00:00
|
|
|
return Ok("slice");
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
2018-06-15 19:21:12 +00:00
|
|
|
} else if let Ok(idx) = idx.extract::<isize>() {
|
2018-05-02 18:49:40 +00:00
|
|
|
if idx == 1 {
|
2020-07-13 21:38:02 +00:00
|
|
|
return Ok("int");
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
}
|
2020-08-25 19:33:36 +00:00
|
|
|
Err(PyValueError::new_err("error"))
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_cls_impl() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
|
|
|
|
2019-02-13 20:35:26 +00:00
|
|
|
let ob = Py::new(py, Test {}).unwrap();
|
2019-03-20 18:37:27 +00:00
|
|
|
let d = [("ob", ob)].into_py_dict(py);
|
2018-05-02 18:49:40 +00:00
|
|
|
|
|
|
|
py.run("assert ob[1] == 'int'", None, Some(d)).unwrap();
|
2018-06-15 19:21:12 +00:00
|
|
|
py.run("assert ob[100:200:1] == 'slice'", None, Some(d))
|
|
|
|
.unwrap();
|
2018-05-02 18:49:40 +00:00
|
|
|
}
|
2018-06-13 16:02:45 +00:00
|
|
|
|
2020-09-01 00:36:26 +00:00
|
|
|
#[pyclass(dict, subclass)]
|
2018-11-12 12:59:19 +00:00
|
|
|
struct DunderDictSupport {}
|
2018-06-13 16:02:45 +00:00
|
|
|
|
|
|
|
#[test]
|
2020-12-27 17:56:52 +00:00
|
|
|
#[cfg_attr(all(Py_LIMITED_API, not(Py_3_9)), ignore)]
|
2018-06-13 16:02:45 +00:00
|
|
|
fn dunder_dict_support() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
2020-02-15 15:24:38 +00:00
|
|
|
let inst = PyCell::new(py, DunderDictSupport {}).unwrap();
|
2018-06-15 19:21:12 +00:00
|
|
|
py_run!(
|
|
|
|
py,
|
|
|
|
inst,
|
|
|
|
r#"
|
2018-06-13 16:02:45 +00:00
|
|
|
inst.a = 1
|
|
|
|
assert inst.a == 1
|
2018-06-15 19:21:12 +00:00
|
|
|
"#
|
|
|
|
);
|
2018-06-13 16:02:45 +00:00
|
|
|
}
|
|
|
|
|
2020-12-27 17:56:52 +00:00
|
|
|
// Accessing inst.__dict__ only supported in limited API from Python 3.10
|
2019-03-17 10:08:05 +00:00
|
|
|
#[test]
|
2020-12-27 17:56:52 +00:00
|
|
|
#[cfg_attr(all(Py_LIMITED_API, not(Py_3_10)), ignore)]
|
2019-03-17 10:08:05 +00:00
|
|
|
fn access_dunder_dict() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
2020-02-15 15:24:38 +00:00
|
|
|
let inst = PyCell::new(py, DunderDictSupport {}).unwrap();
|
2019-03-17 10:08:05 +00:00
|
|
|
py_run!(
|
|
|
|
py,
|
|
|
|
inst,
|
|
|
|
r#"
|
|
|
|
inst.a = 1
|
|
|
|
assert inst.__dict__ == {'a': 1}
|
|
|
|
"#
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2020-02-25 11:02:03 +00:00
|
|
|
// If the base class has dict support, child class also has dict
|
|
|
|
#[pyclass(extends=DunderDictSupport)]
|
|
|
|
struct InheritDict {
|
|
|
|
_value: usize,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2020-12-27 17:56:52 +00:00
|
|
|
#[cfg_attr(all(Py_LIMITED_API, not(Py_3_9)), ignore)]
|
2020-02-25 11:02:03 +00:00
|
|
|
fn inherited_dict() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
|
|
|
let inst = PyCell::new(py, (InheritDict { _value: 0 }, DunderDictSupport {})).unwrap();
|
|
|
|
py_run!(
|
|
|
|
py,
|
|
|
|
inst,
|
|
|
|
r#"
|
|
|
|
inst.a = 1
|
2020-12-27 17:56:52 +00:00
|
|
|
assert inst.a == 1
|
2020-02-25 11:02:03 +00:00
|
|
|
"#
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
#[pyclass(weakref, dict)]
|
2018-11-12 12:59:19 +00:00
|
|
|
struct WeakRefDunderDictSupport {}
|
2018-06-13 16:02:45 +00:00
|
|
|
|
|
|
|
#[test]
|
2020-12-27 17:56:52 +00:00
|
|
|
#[cfg_attr(all(Py_LIMITED_API, not(Py_3_9)), ignore)]
|
2018-06-13 16:02:45 +00:00
|
|
|
fn weakref_dunder_dict_support() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
2020-02-15 15:24:38 +00:00
|
|
|
let inst = PyCell::new(py, WeakRefDunderDictSupport {}).unwrap();
|
2018-06-15 19:21:12 +00:00
|
|
|
py_run!(
|
|
|
|
py,
|
|
|
|
inst,
|
|
|
|
"import weakref; assert weakref.ref(inst)() is inst; inst.a = 1; assert inst.a == 1"
|
|
|
|
);
|
2018-06-13 16:02:45 +00:00
|
|
|
}
|
2019-07-13 14:46:25 +00:00
|
|
|
|
|
|
|
#[pyclass]
|
|
|
|
struct ClassWithGetAttr {
|
|
|
|
#[pyo3(get, set)]
|
|
|
|
data: u32,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[pyproto]
|
|
|
|
impl PyObjectProtocol for ClassWithGetAttr {
|
2020-06-23 10:40:17 +00:00
|
|
|
fn __getattr__(&self, _name: &str) -> u32 {
|
|
|
|
self.data * 2
|
2019-07-13 14:46:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn getattr_doesnt_override_member() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
2020-02-15 15:24:38 +00:00
|
|
|
let inst = PyCell::new(py, ClassWithGetAttr { data: 4 }).unwrap();
|
2019-07-13 14:46:25 +00:00
|
|
|
py_assert!(py, inst, "inst.data == 4");
|
|
|
|
py_assert!(py, inst, "inst.a == 8");
|
|
|
|
}
|
2020-06-13 07:44:14 +00:00
|
|
|
|
|
|
|
/// Wraps a Python future and yield it once.
|
|
|
|
#[pyclass]
|
|
|
|
struct OnceFuture {
|
|
|
|
future: PyObject,
|
|
|
|
polled: bool,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[pymethods]
|
|
|
|
impl OnceFuture {
|
|
|
|
#[new]
|
|
|
|
fn new(future: PyObject) -> Self {
|
|
|
|
OnceFuture {
|
|
|
|
future,
|
|
|
|
polled: false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[pyproto]
|
|
|
|
impl PyAsyncProtocol for OnceFuture {
|
2020-08-08 07:55:08 +00:00
|
|
|
fn __await__(slf: PyRef<Self>) -> PyRef<Self> {
|
2020-06-23 10:40:17 +00:00
|
|
|
slf
|
2020-06-13 07:44:14 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[pyproto]
|
|
|
|
impl PyIterProtocol for OnceFuture {
|
2020-08-08 07:55:08 +00:00
|
|
|
fn __iter__(slf: PyRef<Self>) -> PyRef<Self> {
|
2020-06-23 10:40:17 +00:00
|
|
|
slf
|
2020-06-13 07:44:14 +00:00
|
|
|
}
|
2020-06-23 10:40:17 +00:00
|
|
|
fn __next__(mut slf: PyRefMut<Self>) -> Option<PyObject> {
|
2020-06-13 07:44:14 +00:00
|
|
|
if !slf.polled {
|
|
|
|
slf.polled = true;
|
2020-06-23 10:40:17 +00:00
|
|
|
Some(slf.future.clone())
|
2020-06-13 07:44:14 +00:00
|
|
|
} else {
|
2020-06-23 10:40:17 +00:00
|
|
|
None
|
2020-06-13 07:44:14 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_await() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
|
|
|
let once = py.get_type::<OnceFuture>();
|
|
|
|
let source = pyo3::indoc::indoc!(
|
|
|
|
r#"
|
|
|
|
import asyncio
|
|
|
|
import sys
|
|
|
|
|
|
|
|
async def main():
|
|
|
|
res = await Once(await asyncio.sleep(0.1))
|
|
|
|
return res
|
2020-06-17 13:17:04 +00:00
|
|
|
# For an odd error similar to https://bugs.python.org/issue38563
|
2020-06-13 07:44:14 +00:00
|
|
|
if sys.platform == "win32" and sys.version_info >= (3, 8, 0):
|
|
|
|
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
|
2020-06-17 13:17:04 +00:00
|
|
|
# get_event_loop can raise an error: https://github.com/PyO3/pyo3/pull/961#issuecomment-645238579
|
|
|
|
loop = asyncio.new_event_loop()
|
|
|
|
asyncio.set_event_loop(loop)
|
2020-06-13 07:44:14 +00:00
|
|
|
assert loop.run_until_complete(main()) is None
|
|
|
|
loop.close()
|
|
|
|
"#
|
|
|
|
);
|
|
|
|
let globals = PyModule::import(py, "__main__").unwrap().dict();
|
|
|
|
globals.set_item("Once", once).unwrap();
|
2020-06-15 04:43:46 +00:00
|
|
|
py.run(source, Some(globals), None)
|
|
|
|
.map_err(|e| e.print(py))
|
|
|
|
.unwrap();
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Increment the count when `__get__` is called.
|
|
|
|
#[pyclass]
|
|
|
|
struct DescrCounter {
|
|
|
|
#[pyo3(get)]
|
|
|
|
count: usize,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[pymethods]
|
|
|
|
impl DescrCounter {
|
|
|
|
#[new]
|
|
|
|
fn new() -> Self {
|
|
|
|
DescrCounter { count: 0 }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[pyproto]
|
|
|
|
impl PyDescrProtocol for DescrCounter {
|
|
|
|
fn __get__(
|
2020-08-08 07:55:08 +00:00
|
|
|
mut slf: PyRefMut<Self>,
|
2020-06-15 04:43:46 +00:00
|
|
|
_instance: &PyAny,
|
2020-08-08 07:55:08 +00:00
|
|
|
_owner: Option<&PyType>,
|
|
|
|
) -> PyRefMut<Self> {
|
2020-06-15 04:43:46 +00:00
|
|
|
slf.count += 1;
|
2020-06-23 10:40:17 +00:00
|
|
|
slf
|
2020-06-15 04:43:46 +00:00
|
|
|
}
|
2020-08-08 07:55:08 +00:00
|
|
|
fn __set__(_slf: PyRef<Self>, _instance: &PyAny, mut new_value: PyRefMut<Self>) {
|
2020-06-15 04:43:46 +00:00
|
|
|
new_value.count = _slf.count;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn descr_getset() {
|
|
|
|
let gil = Python::acquire_gil();
|
|
|
|
let py = gil.python();
|
|
|
|
let counter = py.get_type::<DescrCounter>();
|
|
|
|
let source = pyo3::indoc::indoc!(
|
|
|
|
r#"
|
|
|
|
class Class:
|
|
|
|
counter = Counter()
|
|
|
|
c = Class()
|
|
|
|
c.counter # count += 1
|
|
|
|
assert c.counter.count == 2
|
|
|
|
c.counter = Counter()
|
|
|
|
assert c.counter.count == 3
|
|
|
|
"#
|
|
|
|
);
|
|
|
|
let globals = PyModule::import(py, "__main__").unwrap().dict();
|
|
|
|
globals.set_item("Counter", counter).unwrap();
|
|
|
|
py.run(source, Some(globals), None)
|
2020-06-13 07:44:14 +00:00
|
|
|
.map_err(|e| e.print(py))
|
|
|
|
.unwrap();
|
|
|
|
}
|