Merge pull request #1786 from mejrs/with_gil2

tests: switch to python_with_gil
This commit is contained in:
David Hewitt 2021-08-13 12:39:17 +01:00 committed by GitHub
commit 388c2552f8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 1380 additions and 1408 deletions

View File

@ -663,64 +663,64 @@ mod tests {
#[test] #[test]
fn test_bytes_buffer() { fn test_bytes_buffer() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let bytes = py.eval("b'abcde'", None, None).unwrap();
let bytes = py.eval("b'abcde'", None, None).unwrap(); let buffer = PyBuffer::get(bytes).unwrap();
let buffer = PyBuffer::get(bytes).unwrap(); assert_eq!(buffer.dimensions(), 1);
assert_eq!(buffer.dimensions(), 1); assert_eq!(buffer.item_count(), 5);
assert_eq!(buffer.item_count(), 5); assert_eq!(buffer.format().to_str().unwrap(), "B");
assert_eq!(buffer.format().to_str().unwrap(), "B"); assert_eq!(buffer.shape(), [5]);
assert_eq!(buffer.shape(), [5]); // single-dimensional buffer is always contiguous
// single-dimensional buffer is always contiguous assert!(buffer.is_c_contiguous());
assert!(buffer.is_c_contiguous()); assert!(buffer.is_fortran_contiguous());
assert!(buffer.is_fortran_contiguous());
let slice = buffer.as_slice(py).unwrap(); let slice = buffer.as_slice(py).unwrap();
assert_eq!(slice.len(), 5); assert_eq!(slice.len(), 5);
assert_eq!(slice[0].get(), b'a'); assert_eq!(slice[0].get(), b'a');
assert_eq!(slice[2].get(), b'c'); assert_eq!(slice[2].get(), b'c');
assert!(buffer.copy_to_slice(py, &mut [0u8]).is_err()); assert!(buffer.copy_to_slice(py, &mut [0u8]).is_err());
let mut arr = [0; 5]; let mut arr = [0; 5];
buffer.copy_to_slice(py, &mut arr).unwrap(); buffer.copy_to_slice(py, &mut arr).unwrap();
assert_eq!(arr, b"abcde" as &[u8]); assert_eq!(arr, b"abcde" as &[u8]);
assert!(buffer.copy_from_slice(py, &[0u8; 5]).is_err()); assert!(buffer.copy_from_slice(py, &[0u8; 5]).is_err());
assert_eq!(buffer.to_vec(py).unwrap(), b"abcde"); assert_eq!(buffer.to_vec(py).unwrap(), b"abcde");
});
} }
#[allow(clippy::float_cmp)] // The test wants to ensure that no precision was lost on the Python round-trip #[allow(clippy::float_cmp)] // The test wants to ensure that no precision was lost on the Python round-trip
#[test] #[test]
fn test_array_buffer() { fn test_array_buffer() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let array = py
let array = py .import("array")
.import("array") .unwrap()
.unwrap() .call_method("array", ("f", (1.0, 1.5, 2.0, 2.5)), None)
.call_method("array", ("f", (1.0, 1.5, 2.0, 2.5)), None) .unwrap();
.unwrap(); let buffer = PyBuffer::get(array).unwrap();
let buffer = PyBuffer::get(array).unwrap(); assert_eq!(buffer.dimensions(), 1);
assert_eq!(buffer.dimensions(), 1); assert_eq!(buffer.item_count(), 4);
assert_eq!(buffer.item_count(), 4); assert_eq!(buffer.format().to_str().unwrap(), "f");
assert_eq!(buffer.format().to_str().unwrap(), "f"); assert_eq!(buffer.shape(), [4]);
assert_eq!(buffer.shape(), [4]);
let slice = buffer.as_slice(py).unwrap(); let slice = buffer.as_slice(py).unwrap();
assert_eq!(slice.len(), 4); assert_eq!(slice.len(), 4);
assert_eq!(slice[0].get(), 1.0); assert_eq!(slice[0].get(), 1.0);
assert_eq!(slice[3].get(), 2.5); assert_eq!(slice[3].get(), 2.5);
let mut_slice = buffer.as_mut_slice(py).unwrap(); let mut_slice = buffer.as_mut_slice(py).unwrap();
assert_eq!(mut_slice.len(), 4); assert_eq!(mut_slice.len(), 4);
assert_eq!(mut_slice[0].get(), 1.0); assert_eq!(mut_slice[0].get(), 1.0);
mut_slice[3].set(2.75); mut_slice[3].set(2.75);
assert_eq!(slice[3].get(), 2.75); assert_eq!(slice[3].get(), 2.75);
buffer buffer
.copy_from_slice(py, &[10.0f32, 11.0, 12.0, 13.0]) .copy_from_slice(py, &[10.0f32, 11.0, 12.0, 13.0])
.unwrap(); .unwrap();
assert_eq!(slice[2].get(), 12.0); assert_eq!(slice[2].get(), 12.0);
assert_eq!(buffer.to_vec(py).unwrap(), [10.0, 11.0, 12.0, 13.0]); assert_eq!(buffer.to_vec(py).unwrap(), [10.0, 11.0, 12.0, 13.0]);
});
} }
} }

View File

@ -551,38 +551,38 @@ mod tests {
#[test] #[test]
fn test_try_from() { fn test_try_from() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let list: &PyAny = vec![3, 6, 5, 4, 7].to_object(py).into_ref(py);
let list: &PyAny = vec![3, 6, 5, 4, 7].to_object(py).into_ref(py); let dict: &PyAny = vec![("reverse", true)].into_py_dict(py).as_ref();
let dict: &PyAny = vec![("reverse", true)].into_py_dict(py).as_ref();
assert!(PyList::try_from(list).is_ok()); assert!(PyList::try_from(list).is_ok());
assert!(PyDict::try_from(dict).is_ok()); assert!(PyDict::try_from(dict).is_ok());
assert!(PyAny::try_from(list).is_ok()); assert!(PyAny::try_from(list).is_ok());
assert!(PyAny::try_from(dict).is_ok()); assert!(PyAny::try_from(dict).is_ok());
});
} }
#[test] #[test]
fn test_try_from_exact() { fn test_try_from_exact() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let list: &PyAny = vec![3, 6, 5, 4, 7].to_object(py).into_ref(py);
let list: &PyAny = vec![3, 6, 5, 4, 7].to_object(py).into_ref(py); let dict: &PyAny = vec![("reverse", true)].into_py_dict(py).as_ref();
let dict: &PyAny = vec![("reverse", true)].into_py_dict(py).as_ref();
assert!(PyList::try_from_exact(list).is_ok()); assert!(PyList::try_from_exact(list).is_ok());
assert!(PyDict::try_from_exact(dict).is_ok()); assert!(PyDict::try_from_exact(dict).is_ok());
assert!(PyAny::try_from_exact(list).is_err()); assert!(PyAny::try_from_exact(list).is_err());
assert!(PyAny::try_from_exact(dict).is_err()); assert!(PyAny::try_from_exact(dict).is_err());
});
} }
#[test] #[test]
fn test_try_from_unchecked() { fn test_try_from_unchecked() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let list = PyList::new(py, &[1, 2, 3]);
let list = PyList::new(py, &[1, 2, 3]); let val = unsafe { <PyList as PyTryFrom>::try_from_unchecked(list.as_ref()) };
let val = unsafe { <PyList as PyTryFrom>::try_from_unchecked(list.as_ref()) }; assert_eq!(list, val);
assert_eq!(list, val); });
} }
} }

View File

@ -638,14 +638,14 @@ mod tests {
fn fetching_panic_exception_resumes_unwind() { fn fetching_panic_exception_resumes_unwind() {
use crate::panic::PanicException; use crate::panic::PanicException;
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let err: PyErr = PanicException::new_err("new panic");
let err: PyErr = PanicException::new_err("new panic"); err.restore(py);
err.restore(py); assert!(PyErr::occurred(py));
assert!(PyErr::occurred(py));
// should resume unwind // should resume unwind
let _ = PyErr::fetch(py); let _ = PyErr::fetch(py);
});
} }
#[test] #[test]
@ -657,42 +657,42 @@ mod tests {
// traceback: Some(<traceback object at 0x..)" // traceback: Some(<traceback object at 0x..)"
// } // }
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let err = py
let err = py .run("raise Exception('banana')", None, None)
.run("raise Exception('banana')", None, None) .expect_err("raising should have given us an error");
.expect_err("raising should have given us an error");
let debug_str = format!("{:?}", err); let debug_str = format!("{:?}", err);
assert!(debug_str.starts_with("PyErr { ")); assert!(debug_str.starts_with("PyErr { "));
assert!(debug_str.ends_with(" }")); assert!(debug_str.ends_with(" }"));
// strip "PyErr { " and " }" // strip "PyErr { " and " }"
let mut fields = debug_str["PyErr { ".len()..debug_str.len() - 2].split(", "); let mut fields = debug_str["PyErr { ".len()..debug_str.len() - 2].split(", ");
assert_eq!(fields.next().unwrap(), "type: <class 'Exception'>"); assert_eq!(fields.next().unwrap(), "type: <class 'Exception'>");
if py.version_info() >= (3, 7) { if py.version_info() >= (3, 7) {
assert_eq!(fields.next().unwrap(), "value: Exception('banana')"); assert_eq!(fields.next().unwrap(), "value: Exception('banana')");
} else { } else {
// Python 3.6 and below formats the repr differently // Python 3.6 and below formats the repr differently
assert_eq!(fields.next().unwrap(), ("value: Exception('banana',)")); assert_eq!(fields.next().unwrap(), ("value: Exception('banana',)"));
} }
let traceback = fields.next().unwrap(); let traceback = fields.next().unwrap();
assert!(traceback.starts_with("traceback: Some(<traceback object at 0x")); assert!(traceback.starts_with("traceback: Some(<traceback object at 0x"));
assert!(traceback.ends_with(">)")); assert!(traceback.ends_with(">)"));
assert!(fields.next().is_none()); assert!(fields.next().is_none());
});
} }
#[test] #[test]
fn err_display() { fn err_display() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let err = py
let err = py .run("raise Exception('banana')", None, None)
.run("raise Exception('banana')", None, None) .expect_err("raising should have given us an error");
.expect_err("raising should have given us an error"); assert_eq!(err.to_string(), "Exception: banana");
assert_eq!(err.to_string(), "Exception: banana"); });
} }
#[test] #[test]

View File

@ -342,141 +342,139 @@ mod tests {
#[test] #[test]
fn test_check_exception() { fn test_check_exception() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let err: PyErr = gaierror::new_err(());
let socket = py
.import("socket")
.map_err(|e| e.print(py))
.expect("could not import socket");
let err: PyErr = gaierror::new_err(()); let d = PyDict::new(py);
let socket = py d.set_item("socket", socket)
.import("socket") .map_err(|e| e.print(py))
.map_err(|e| e.print(py)) .expect("could not setitem");
.expect("could not import socket");
let d = PyDict::new(py); d.set_item("exc", err)
d.set_item("socket", socket) .map_err(|e| e.print(py))
.map_err(|e| e.print(py)) .expect("could not setitem");
.expect("could not setitem");
d.set_item("exc", err) py.run("assert isinstance(exc, socket.gaierror)", None, Some(d))
.map_err(|e| e.print(py)) .map_err(|e| e.print(py))
.expect("could not setitem"); .expect("assertion failed");
});
py.run("assert isinstance(exc, socket.gaierror)", None, Some(d))
.map_err(|e| e.print(py))
.expect("assertion failed");
} }
#[test] #[test]
fn test_check_exception_nested() { fn test_check_exception_nested() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let err: PyErr = MessageError::new_err(());
let email = py
.import("email")
.map_err(|e| e.print(py))
.expect("could not import email");
let err: PyErr = MessageError::new_err(()); let d = PyDict::new(py);
let email = py d.set_item("email", email)
.import("email") .map_err(|e| e.print(py))
.map_err(|e| e.print(py)) .expect("could not setitem");
.expect("could not import email"); d.set_item("exc", err)
.map_err(|e| e.print(py))
.expect("could not setitem");
let d = PyDict::new(py); py.run(
d.set_item("email", email) "assert isinstance(exc, email.errors.MessageError)",
None,
Some(d),
)
.map_err(|e| e.print(py)) .map_err(|e| e.print(py))
.expect("could not setitem"); .expect("assertion failed");
d.set_item("exc", err) });
.map_err(|e| e.print(py))
.expect("could not setitem");
py.run(
"assert isinstance(exc, email.errors.MessageError)",
None,
Some(d),
)
.map_err(|e| e.print(py))
.expect("assertion failed");
} }
#[test] #[test]
fn custom_exception() { fn custom_exception() {
create_exception!(mymodule, CustomError, PyException); create_exception!(mymodule, CustomError, PyException);
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let error_type = py.get_type::<CustomError>();
let error_type = py.get_type::<CustomError>(); let ctx = [("CustomError", error_type)].into_py_dict(py);
let ctx = [("CustomError", error_type)].into_py_dict(py); let type_description: String = py
let type_description: String = py .eval("str(CustomError)", None, Some(ctx))
.eval("str(CustomError)", None, Some(ctx)) .unwrap()
.unwrap() .extract()
.extract() .unwrap();
assert_eq!(type_description, "<class 'mymodule.CustomError'>");
py.run(
"assert CustomError('oops').args == ('oops',)",
None,
Some(ctx),
)
.unwrap(); .unwrap();
assert_eq!(type_description, "<class 'mymodule.CustomError'>"); });
py.run(
"assert CustomError('oops').args == ('oops',)",
None,
Some(ctx),
)
.unwrap();
} }
#[test] #[test]
fn native_exception_debug() { fn native_exception_debug() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let exc = py
let exc = py .run("raise Exception('banana')", None, None)
.run("raise Exception('banana')", None, None) .expect_err("raising should have given us an error")
.expect_err("raising should have given us an error") .into_instance(py)
.into_instance(py) .into_ref(py);
.into_ref(py); assert_eq!(
assert_eq!( format!("{:?}", exc),
format!("{:?}", exc), exc.repr().unwrap().extract::<String>().unwrap()
exc.repr().unwrap().extract::<String>().unwrap() );
); });
} }
#[test] #[test]
fn native_exception_display() { fn native_exception_display() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let exc = py
let exc = py .run("raise Exception('banana')", None, None)
.run("raise Exception('banana')", None, None) .expect_err("raising should have given us an error")
.expect_err("raising should have given us an error") .into_instance(py)
.into_instance(py) .into_ref(py);
.into_ref(py); assert_eq!(
assert_eq!( exc.to_string(),
exc.to_string(), exc.str().unwrap().extract::<String>().unwrap()
exc.str().unwrap().extract::<String>().unwrap() );
); });
} }
#[test] #[test]
fn native_exception_chain() { fn native_exception_chain() {
use std::error::Error; use std::error::Error;
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let exc = py
let exc = py .run(
.run( "raise Exception('banana') from TypeError('peach')",
"raise Exception('banana') from TypeError('peach')", None,
None, None,
None, )
) .expect_err("raising should have given us an error")
.expect_err("raising should have given us an error") .into_instance(py)
.into_instance(py) .into_ref(py);
.into_ref(py);
if py.version_info() >= (3, 7) { if py.version_info() >= (3, 7) {
assert_eq!(format!("{:?}", exc), "Exception('banana')"); assert_eq!(format!("{:?}", exc), "Exception('banana')");
} else { } else {
assert_eq!(format!("{:?}", exc), "Exception('banana',)"); assert_eq!(format!("{:?}", exc), "Exception('banana',)");
} }
let source = exc.source().expect("cause should exist"); let source = exc.source().expect("cause should exist");
if py.version_info() >= (3, 7) { if py.version_info() >= (3, 7) {
assert_eq!(format!("{:?}", source), "TypeError('peach')"); assert_eq!(format!("{:?}", source), "TypeError('peach')");
} else { } else {
assert_eq!(format!("{:?}", source), "TypeError('peach',)"); assert_eq!(format!("{:?}", source), "TypeError('peach',)");
} }
let source_source = source.source(); let source_source = source.source();
assert!(source_source.is_none(), "source_source should be None"); assert!(source_source.is_none(), "source_source should be None");
});
} }
#[test] #[test]

View File

@ -860,30 +860,29 @@ impl PyObject {
mod tests { mod tests {
use super::{Py, PyObject}; use super::{Py, PyObject};
use crate::types::PyDict; use crate::types::PyDict;
use crate::{ffi, AsPyPointer, Python}; use crate::Python;
#[test] #[test]
fn test_call_for_non_existing_method() { fn test_call_for_non_existing_method() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let obj: PyObject = PyDict::new(py).into();
let obj: PyObject = PyDict::new(py).into(); assert!(obj.call_method0(py, "asdf").is_err());
assert!(obj.call_method0(py, "asdf").is_err()); assert!(obj
assert!(obj .call_method(py, "nonexistent_method", (1,), None)
.call_method(py, "nonexistent_method", (1,), None) .is_err());
.is_err()); assert!(obj.call_method0(py, "nonexistent_method").is_err());
assert!(obj.call_method0(py, "nonexistent_method").is_err()); assert!(obj.call_method1(py, "nonexistent_method", (1,)).is_err());
assert!(obj.call_method1(py, "nonexistent_method", (1,)).is_err()); });
} }
#[test] #[test]
fn py_from_dict() { fn py_from_dict() {
let dict: Py<PyDict> = { let dict: Py<PyDict> = Python::with_gil(|py| {
let gil = Python::acquire_gil();
let py = gil.python();
let native = PyDict::new(py); let native = PyDict::new(py);
Py::from(native) Py::from(native)
}; });
assert_eq!(unsafe { ffi::Py_REFCNT(dict.as_ptr()) }, 1);
assert_eq!(Python::with_gil(|py| dict.get_refcnt(py)), 1);
} }
#[test] #[test]

View File

@ -56,21 +56,20 @@ mod tests {
use crate::types::PyDict; use crate::types::PyDict;
#[test] #[test]
fn marhshal_roundtrip() { fn marshal_roundtrip() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let dict = PyDict::new(py);
dict.set_item("aap", "noot").unwrap();
dict.set_item("mies", "wim").unwrap();
dict.set_item("zus", "jet").unwrap();
let dict = PyDict::new(py); let bytes = dumps(py, dict, VERSION)
dict.set_item("aap", "noot").unwrap(); .expect("marshalling failed")
dict.set_item("mies", "wim").unwrap(); .as_bytes();
dict.set_item("zus", "jet").unwrap(); let deserialized = loads(py, bytes).expect("unmarshalling failed");
let bytes = dumps(py, dict, VERSION) assert!(equal(py, dict, deserialized));
.expect("marshalling failed") });
.as_bytes();
let deserialzed = loads(py, bytes).expect("unmarshalling failed");
assert!(equal(py, dict, deserialzed));
} }
fn equal(_py: Python, a: &impl AsPyPointer, b: &impl AsPyPointer) -> bool { fn equal(_py: Python, a: &impl AsPyPointer, b: &impl AsPyPointer) -> bool {

View File

@ -705,64 +705,62 @@ mod tests {
#[test] #[test]
fn test_eval() { fn test_eval() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); // Make sure builtin names are accessible
let v: i32 = py
.eval("min(1, 2)", None, None)
.map_err(|e| e.print(py))
.unwrap()
.extract()
.unwrap();
assert_eq!(v, 1);
// Make sure builtin names are accessible let d = [("foo", 13)].into_py_dict(py);
let v: i32 = py
.eval("min(1, 2)", None, None)
.map_err(|e| e.print(py))
.unwrap()
.extract()
.unwrap();
assert_eq!(v, 1);
let d = [("foo", 13)].into_py_dict(py); // Inject our own global namespace
let v: i32 = py
.eval("foo + 29", Some(d), None)
.unwrap()
.extract()
.unwrap();
assert_eq!(v, 42);
// Inject our own global namespace // Inject our own local namespace
let v: i32 = py let v: i32 = py
.eval("foo + 29", Some(d), None) .eval("foo + 29", None, Some(d))
.unwrap() .unwrap()
.extract() .extract()
.unwrap(); .unwrap();
assert_eq!(v, 42); assert_eq!(v, 42);
// Inject our own local namespace // Make sure builtin names are still accessible when using a local namespace
let v: i32 = py let v: i32 = py
.eval("foo + 29", None, Some(d)) .eval("min(foo, 2)", None, Some(d))
.unwrap() .unwrap()
.extract() .extract()
.unwrap(); .unwrap();
assert_eq!(v, 42); assert_eq!(v, 2);
});
// Make sure builtin names are still accessible when using a local namespace
let v: i32 = py
.eval("min(foo, 2)", None, Some(d))
.unwrap()
.extract()
.unwrap();
assert_eq!(v, 2);
} }
#[test] #[test]
fn test_allow_threads_panics_safely() { fn test_allow_threads_panics_safely() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let result = std::panic::catch_unwind(|| unsafe {
let py = Python::assume_gil_acquired();
let result = std::panic::catch_unwind(|| unsafe { py.allow_threads(|| {
let py = Python::assume_gil_acquired(); panic!("There was a panic!");
py.allow_threads(|| { });
panic!("There was a panic!");
}); });
// Check panic was caught
assert!(result.is_err());
// If allow_threads is implemented correctly, this thread still owns the GIL here
// so the following Python calls should not cause crashes.
let list = PyList::new(py, &[1, 2, 3, 4]);
assert_eq!(list.extract::<Vec<i32>>().unwrap(), vec![1, 2, 3, 4]);
}); });
// Check panic was caught
assert!(result.is_err());
// If allow_threads is implemented correctly, this thread still owns the GIL here
// so the following Python calls should not cause crashes.
let list = PyList::new(py, &[1, 2, 3, 4]);
assert_eq!(list.extract::<Vec<i32>>().unwrap(), vec![1, 2, 3, 4]);
} }
#[test] #[test]
@ -801,4 +799,25 @@ mod tests {
assert!(PythonVersionInfo::from_str("3.5.2a1+") < (3, 6)); assert!(PythonVersionInfo::from_str("3.5.2a1+") < (3, 6));
assert!(PythonVersionInfo::from_str("3.5.2a1+") > (3, 4)); assert!(PythonVersionInfo::from_str("3.5.2a1+") > (3, 4));
} }
#[test]
#[cfg(not(Py_LIMITED_API))]
fn test_acquire_gil() {
const GIL_NOT_HELD: c_int = 0;
const GIL_HELD: c_int = 1;
let state = unsafe { crate::ffi::PyGILState_Check() };
assert_eq!(state, GIL_NOT_HELD);
{
let gil = Python::acquire_gil();
let _py = gil.python();
let state = unsafe { crate::ffi::PyGILState_Check() };
assert_eq!(state, GIL_HELD);
drop(gil);
}
let state = unsafe { crate::ffi::PyGILState_Check() };
assert_eq!(state, GIL_NOT_HELD);
}
} }

View File

@ -694,23 +694,23 @@ mod tests {
#[test] #[test]
fn test_call_for_non_existing_method() { fn test_call_for_non_existing_method() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let a = py.eval("42", None, None).unwrap();
let a = py.eval("42", None, None).unwrap(); a.call_method0("__str__").unwrap(); // ok
a.call_method0("__str__").unwrap(); // ok assert!(a.call_method("nonexistent_method", (1,), None).is_err());
assert!(a.call_method("nonexistent_method", (1,), None).is_err()); assert!(a.call_method0("nonexistent_method").is_err());
assert!(a.call_method0("nonexistent_method").is_err()); assert!(a.call_method1("nonexistent_method", (1,)).is_err());
assert!(a.call_method1("nonexistent_method", (1,)).is_err()); });
} }
#[test] #[test]
fn test_call_with_kwargs() { fn test_call_with_kwargs() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let list = vec![3, 6, 5, 4, 7].to_object(py);
let list = vec![3, 6, 5, 4, 7].to_object(py); let dict = vec![("reverse", true)].into_py_dict(py);
let dict = vec![("reverse", true)].into_py_dict(py); list.call_method(py, "sort", (), Some(dict)).unwrap();
list.call_method(py, "sort", (), Some(dict)).unwrap(); assert_eq!(list.extract::<Vec<i32>>(py).unwrap(), vec![7, 6, 5, 4, 3]);
assert_eq!(list.extract::<Vec<i32>>(py).unwrap(), vec![7, 6, 5, 4, 3]); });
} }
#[test] #[test]
@ -739,47 +739,46 @@ mod tests {
#[test] #[test]
fn test_type() { fn test_type() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let obj = py.eval("42", None, None).unwrap();
let obj = py.eval("42", None, None).unwrap(); assert_eq!(obj.get_type().as_type_ptr(), obj.get_type_ptr());
assert_eq!(obj.get_type().as_type_ptr(), obj.get_type_ptr()) });
} }
#[test] #[test]
fn test_dir() { fn test_dir() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let obj = py.eval("42", None, None).unwrap();
let obj = py.eval("42", None, None).unwrap(); let dir = py
let dir = py .eval("dir(42)", None, None)
.eval("dir(42)", None, None) .unwrap()
.unwrap() .downcast::<PyList>()
.downcast::<PyList>() .unwrap();
.unwrap(); let a = obj
let a = obj .dir()
.dir() .into_iter()
.into_iter() .map(|x| x.extract::<String>().unwrap());
.map(|x| x.extract::<String>().unwrap()); let b = dir.into_iter().map(|x| x.extract::<String>().unwrap());
let b = dir.into_iter().map(|x| x.extract::<String>().unwrap()); assert!(a.eq(b));
assert!(a.eq(b)); });
} }
#[test] #[test]
fn test_nan_eq() { fn test_nan_eq() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let nan = py.eval("float('nan')", None, None).unwrap();
let nan = py.eval("float('nan')", None, None).unwrap(); assert!(nan.compare(nan).is_err());
assert!(nan.compare(nan).is_err()); });
} }
#[test] #[test]
fn test_any_isinstance() { fn test_any_isinstance() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let x = 5.to_object(py).into_ref(py);
assert!(x.is_instance::<PyLong>().unwrap());
let x = 5.to_object(py).into_ref(py); let l = vec![x, x].to_object(py).into_ref(py);
assert!(x.is_instance::<PyLong>().unwrap()); assert!(l.is_instance::<PyList>().unwrap());
});
let l = vec![x, x].to_object(py).into_ref(py);
assert!(l.is_instance::<PyList>().unwrap());
} }
} }

View File

@ -65,21 +65,21 @@ mod tests {
#[test] #[test]
fn test_true() { fn test_true() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); assert!(PyBool::new(py, true).is_true());
assert!(PyBool::new(py, true).is_true()); let t: &PyAny = PyBool::new(py, true).into();
let t: &PyAny = PyBool::new(py, true).into(); assert!(t.extract::<bool>().unwrap());
assert!(t.extract::<bool>().unwrap()); assert_eq!(true.to_object(py), PyBool::new(py, true).into());
assert_eq!(true.to_object(py), PyBool::new(py, true).into()); });
} }
#[test] #[test]
fn test_false() { fn test_false() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); assert!(!PyBool::new(py, false).is_true());
assert!(!PyBool::new(py, false).is_true()); let t: &PyAny = PyBool::new(py, false).into();
let t: &PyAny = PyBool::new(py, false).into(); assert!(!t.extract::<bool>().unwrap());
assert!(!t.extract::<bool>().unwrap()); assert_eq!(false.to_object(py), PyBool::new(py, false).into());
assert_eq!(false.to_object(py), PyBool::new(py, false).into()); });
} }
} }

View File

@ -172,132 +172,125 @@ mod tests {
#[test] #[test]
fn test_len() { fn test_len() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let src = b"Hello Python";
let bytearray = PyByteArray::new(py, src);
let src = b"Hello Python"; assert_eq!(src.len(), bytearray.len());
let bytearray = PyByteArray::new(py, src); });
assert_eq!(src.len(), bytearray.len());
} }
#[test] #[test]
fn test_as_bytes() { fn test_as_bytes() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let src = b"Hello Python";
let bytearray = PyByteArray::new(py, src);
let src = b"Hello Python"; let slice = unsafe { bytearray.as_bytes() };
let bytearray = PyByteArray::new(py, src); assert_eq!(src, slice);
assert_eq!(bytearray.data() as *const _, slice.as_ptr());
let slice = unsafe { bytearray.as_bytes() }; });
assert_eq!(src, slice);
assert_eq!(bytearray.data() as *const _, slice.as_ptr());
} }
#[test] #[test]
fn test_as_bytes_mut() { fn test_as_bytes_mut() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let src = b"Hello Python";
let bytearray = PyByteArray::new(py, src);
let src = b"Hello Python"; let slice = unsafe { bytearray.as_bytes_mut() };
let bytearray = PyByteArray::new(py, src); assert_eq!(src, slice);
assert_eq!(bytearray.data(), slice.as_mut_ptr());
let slice = unsafe { bytearray.as_bytes_mut() }; slice[0..5].copy_from_slice(b"Hi...");
assert_eq!(src, slice);
assert_eq!(bytearray.data(), slice.as_mut_ptr());
slice[0..5].copy_from_slice(b"Hi..."); assert_eq!(
bytearray.str().unwrap().to_str().unwrap(),
assert_eq!( "bytearray(b'Hi... Python')"
bytearray.str().unwrap().to_str().unwrap(), );
"bytearray(b'Hi... Python')" });
);
} }
#[test] #[test]
fn test_to_vec() { fn test_to_vec() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let src = b"Hello Python";
let bytearray = PyByteArray::new(py, src);
let src = b"Hello Python"; let vec = bytearray.to_vec();
let bytearray = PyByteArray::new(py, src); assert_eq!(src, vec.as_slice());
});
let vec = bytearray.to_vec();
assert_eq!(src, vec.as_slice());
} }
#[test] #[test]
fn test_from() { fn test_from() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let src = b"Hello Python";
let bytearray = PyByteArray::new(py, src);
let src = b"Hello Python"; let ba: PyObject = bytearray.into();
let bytearray = PyByteArray::new(py, src); let bytearray = PyByteArray::from(py, &ba).unwrap();
let ba: PyObject = bytearray.into(); assert_eq!(src, unsafe { bytearray.as_bytes() });
let bytearray = PyByteArray::from(py, &ba).unwrap(); });
assert_eq!(src, unsafe { bytearray.as_bytes() });
} }
#[test] #[test]
fn test_from_err() { fn test_from_err() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); if let Err(err) = PyByteArray::from(py, &py.None()) {
assert!(err.is_instance::<exceptions::PyTypeError>(py));
if let Err(err) = PyByteArray::from(py, &py.None()) { } else {
assert!(err.is_instance::<exceptions::PyTypeError>(py)); panic!("error");
} else { }
panic!("error"); });
}
} }
#[test] #[test]
fn test_resize() { fn test_resize() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let src = b"Hello Python";
let bytearray = PyByteArray::new(py, src);
let src = b"Hello Python"; bytearray.resize(20).unwrap();
let bytearray = PyByteArray::new(py, src); assert_eq!(20, bytearray.len());
});
bytearray.resize(20).unwrap();
assert_eq!(20, bytearray.len());
} }
#[test] #[test]
fn test_byte_array_new_with() -> super::PyResult<()> { fn test_byte_array_new_with() -> super::PyResult<()> {
let gil = Python::acquire_gil(); Python::with_gil(|py| -> super::PyResult<()> {
let py = gil.python(); let py_bytearray = PyByteArray::new_with(py, 10, |b: &mut [u8]| {
let py_bytearray = PyByteArray::new_with(py, 10, |b: &mut [u8]| { b.copy_from_slice(b"Hello Rust");
b.copy_from_slice(b"Hello Rust"); Ok(())
})?;
let bytearray: &[u8] = unsafe { py_bytearray.as_bytes() };
assert_eq!(bytearray, b"Hello Rust");
Ok(()) Ok(())
})?; })
let bytearray: &[u8] = unsafe { py_bytearray.as_bytes() };
assert_eq!(bytearray, b"Hello Rust");
Ok(())
} }
#[test] #[test]
fn test_byte_array_new_with_zero_initialised() -> super::PyResult<()> { fn test_byte_array_new_with_zero_initialised() -> super::PyResult<()> {
let gil = Python::acquire_gil(); Python::with_gil(|py| -> super::PyResult<()> {
let py = gil.python(); let py_bytearray = PyByteArray::new_with(py, 10, |_b: &mut [u8]| Ok(()))?;
let py_bytearray = PyByteArray::new_with(py, 10, |_b: &mut [u8]| Ok(()))?; let bytearray: &[u8] = unsafe { py_bytearray.as_bytes() };
let bytearray: &[u8] = unsafe { py_bytearray.as_bytes() }; assert_eq!(bytearray, &[0; 10]);
assert_eq!(bytearray, &[0; 10]); Ok(())
Ok(()) })
} }
#[test] #[test]
fn test_byte_array_new_with_error() { fn test_byte_array_new_with_error() {
use crate::exceptions::PyValueError; use crate::exceptions::PyValueError;
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let py_bytearray_result = PyByteArray::new_with(py, 10, |_b: &mut [u8]| {
let py_bytearray_result = PyByteArray::new_with(py, 10, |_b: &mut [u8]| { Err(PyValueError::new_err("Hello Crustaceans!"))
Err(PyValueError::new_err("Hello Crustaceans!")) });
}); assert!(py_bytearray_result.is_err());
assert!(py_bytearray_result.is_err()); assert!(py_bytearray_result
assert!(py_bytearray_result .err()
.err() .unwrap()
.unwrap() .is_instance::<PyValueError>(py));
.is_instance::<PyValueError>(py)); })
} }
} }

View File

@ -121,57 +121,56 @@ mod tests {
#[test] #[test]
fn test_extract_bytes() { fn test_extract_bytes() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let py_bytes = py.eval("b'Hello Python'", None, None).unwrap();
let bytes: &[u8] = FromPyObject::extract(py_bytes).unwrap();
let py_bytes = py.eval("b'Hello Python'", None, None).unwrap(); assert_eq!(bytes, b"Hello Python");
let bytes: &[u8] = FromPyObject::extract(py_bytes).unwrap(); });
assert_eq!(bytes, b"Hello Python");
} }
#[test] #[test]
fn test_bytes_index() { fn test_bytes_index() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let bytes = PyBytes::new(py, b"Hello World");
let bytes = PyBytes::new(py, b"Hello World"); assert_eq!(bytes[1], b'e');
assert_eq!(bytes[1], b'e'); });
} }
#[test] #[test]
fn test_bytes_new_with() -> super::PyResult<()> { fn test_bytes_new_with() -> super::PyResult<()> {
let gil = Python::acquire_gil(); Python::with_gil(|py| -> super::PyResult<()> {
let py = gil.python(); let py_bytes = PyBytes::new_with(py, 10, |b: &mut [u8]| {
let py_bytes = PyBytes::new_with(py, 10, |b: &mut [u8]| { b.copy_from_slice(b"Hello Rust");
b.copy_from_slice(b"Hello Rust"); Ok(())
})?;
let bytes: &[u8] = FromPyObject::extract(py_bytes)?;
assert_eq!(bytes, b"Hello Rust");
Ok(()) Ok(())
})?; })
let bytes: &[u8] = FromPyObject::extract(py_bytes)?;
assert_eq!(bytes, b"Hello Rust");
Ok(())
} }
#[test] #[test]
fn test_bytes_new_with_zero_initialised() -> super::PyResult<()> { fn test_bytes_new_with_zero_initialised() -> super::PyResult<()> {
let gil = Python::acquire_gil(); Python::with_gil(|py| -> super::PyResult<()> {
let py = gil.python(); let py_bytes = PyBytes::new_with(py, 10, |_b: &mut [u8]| Ok(()))?;
let py_bytes = PyBytes::new_with(py, 10, |_b: &mut [u8]| Ok(()))?; let bytes: &[u8] = FromPyObject::extract(py_bytes)?;
let bytes: &[u8] = FromPyObject::extract(py_bytes)?; assert_eq!(bytes, &[0; 10]);
assert_eq!(bytes, &[0; 10]); Ok(())
Ok(()) })
} }
#[test] #[test]
fn test_bytes_new_with_error() { fn test_bytes_new_with_error() {
use crate::exceptions::PyValueError; use crate::exceptions::PyValueError;
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let py_bytes_result = PyBytes::new_with(py, 10, |_b: &mut [u8]| {
let py_bytes_result = PyBytes::new_with(py, 10, |_b: &mut [u8]| { Err(PyValueError::new_err("Hello Crustaceans!"))
Err(PyValueError::new_err("Hello Crustaceans!")) });
assert!(py_bytes_result.is_err());
assert!(py_bytes_result
.err()
.unwrap()
.is_instance::<PyValueError>(py));
}); });
assert!(py_bytes_result.is_err());
assert!(py_bytes_result
.err()
.unwrap()
.is_instance::<PyValueError>(py));
} }
} }

View File

@ -412,46 +412,43 @@ mod hashbrown_hashmap_conversion {
#[test] #[test]
fn test_hashbrown_hashmap_to_python() { fn test_hashbrown_hashmap_to_python() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut map = hashbrown::HashMap::<i32, i32>::new();
map.insert(1, 1);
let mut map = hashbrown::HashMap::<i32, i32>::new(); let m = map.to_object(py);
map.insert(1, 1); let py_map = <PyDict as PyTryFrom>::try_from(m.as_ref(py)).unwrap();
let m = map.to_object(py); assert!(py_map.len() == 1);
let py_map = <PyDict as PyTryFrom>::try_from(m.as_ref(py)).unwrap(); assert!(py_map.get_item(1).unwrap().extract::<i32>().unwrap() == 1);
assert_eq!(map, py_map.extract().unwrap());
assert!(py_map.len() == 1); });
assert!(py_map.get_item(1).unwrap().extract::<i32>().unwrap() == 1);
assert_eq!(map, py_map.extract().unwrap());
} }
#[test] #[test]
fn test_hashbrown_hashmap_into_python() { fn test_hashbrown_hashmap_into_python() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut map = hashbrown::HashMap::<i32, i32>::new();
map.insert(1, 1);
let mut map = hashbrown::HashMap::<i32, i32>::new(); let m: PyObject = map.into_py(py);
map.insert(1, 1); let py_map = <PyDict as PyTryFrom>::try_from(m.as_ref(py)).unwrap();
let m: PyObject = map.into_py(py); assert!(py_map.len() == 1);
let py_map = <PyDict as PyTryFrom>::try_from(m.as_ref(py)).unwrap(); assert!(py_map.get_item(1).unwrap().extract::<i32>().unwrap() == 1);
});
assert!(py_map.len() == 1);
assert!(py_map.get_item(1).unwrap().extract::<i32>().unwrap() == 1);
} }
#[test] #[test]
fn test_hashbrown_hashmap_into_dict() { fn test_hashbrown_hashmap_into_dict() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut map = hashbrown::HashMap::<i32, i32>::new();
map.insert(1, 1);
let mut map = hashbrown::HashMap::<i32, i32>::new(); let py_map = map.into_py_dict(py);
map.insert(1, 1);
let py_map = map.into_py_dict(py); assert_eq!(py_map.len(), 1);
assert_eq!(py_map.get_item(1).unwrap().extract::<i32>().unwrap(), 1);
assert_eq!(py_map.len(), 1); });
assert_eq!(py_map.get_item(1).unwrap().extract::<i32>().unwrap(), 1);
} }
} }
@ -469,397 +466,388 @@ mod tests {
#[test] #[test]
fn test_new() { fn test_new() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let dict = [(7, 32)].into_py_dict(py);
let dict = [(7, 32)].into_py_dict(py); assert_eq!(32, dict.get_item(7i32).unwrap().extract::<i32>().unwrap());
assert_eq!(32, dict.get_item(7i32).unwrap().extract::<i32>().unwrap()); assert_eq!(None, dict.get_item(8i32));
assert_eq!(None, dict.get_item(8i32)); let map: HashMap<i32, i32> = [(7, 32)].iter().cloned().collect();
let map: HashMap<i32, i32> = [(7, 32)].iter().cloned().collect(); assert_eq!(map, dict.extract().unwrap());
assert_eq!(map, dict.extract().unwrap()); let map: BTreeMap<i32, i32> = [(7, 32)].iter().cloned().collect();
let map: BTreeMap<i32, i32> = [(7, 32)].iter().cloned().collect(); assert_eq!(map, dict.extract().unwrap());
assert_eq!(map, dict.extract().unwrap()); });
} }
#[test] #[test]
#[cfg(not(PyPy))] #[cfg(not(PyPy))]
fn test_from_sequence() { fn test_from_sequence() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let items = PyList::new(py, &vec![("a", 1), ("b", 2)]);
let items = PyList::new(py, &vec![("a", 1), ("b", 2)]); let dict = PyDict::from_sequence(py, items.to_object(py)).unwrap();
let dict = PyDict::from_sequence(py, items.to_object(py)).unwrap(); assert_eq!(1, dict.get_item("a").unwrap().extract::<i32>().unwrap());
assert_eq!(1, dict.get_item("a").unwrap().extract::<i32>().unwrap()); assert_eq!(2, dict.get_item("b").unwrap().extract::<i32>().unwrap());
assert_eq!(2, dict.get_item("b").unwrap().extract::<i32>().unwrap()); let map: HashMap<&str, i32> = [("a", 1), ("b", 2)].iter().cloned().collect();
let map: HashMap<&str, i32> = [("a", 1), ("b", 2)].iter().cloned().collect(); assert_eq!(map, dict.extract().unwrap());
assert_eq!(map, dict.extract().unwrap()); let map: BTreeMap<&str, i32> = [("a", 1), ("b", 2)].iter().cloned().collect();
let map: BTreeMap<&str, i32> = [("a", 1), ("b", 2)].iter().cloned().collect(); assert_eq!(map, dict.extract().unwrap());
assert_eq!(map, dict.extract().unwrap()); });
} }
#[test] #[test]
#[cfg(not(PyPy))] #[cfg(not(PyPy))]
fn test_from_sequence_err() { fn test_from_sequence_err() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let items = PyList::new(py, &vec!["a", "b"]);
let items = PyList::new(py, &vec!["a", "b"]); assert!(PyDict::from_sequence(py, items.to_object(py)).is_err());
assert!(PyDict::from_sequence(py, items.to_object(py)).is_err()); });
} }
#[test] #[test]
fn test_copy() { fn test_copy() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let dict = [(7, 32)].into_py_dict(py);
let dict = [(7, 32)].into_py_dict(py);
let ndict = dict.copy().unwrap(); let ndict = dict.copy().unwrap();
assert_eq!(32, ndict.get_item(7i32).unwrap().extract::<i32>().unwrap()); assert_eq!(32, ndict.get_item(7i32).unwrap().extract::<i32>().unwrap());
assert_eq!(None, ndict.get_item(8i32)); assert_eq!(None, ndict.get_item(8i32));
});
} }
#[test] #[test]
fn test_len() { fn test_len() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut v = HashMap::new();
let mut v = HashMap::new(); let ob = v.to_object(py);
let ob = v.to_object(py); let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap(); assert_eq!(0, dict.len());
assert_eq!(0, dict.len()); v.insert(7, 32);
v.insert(7, 32); let ob = v.to_object(py);
let ob = v.to_object(py); let dict2 = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let dict2 = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap(); assert_eq!(1, dict2.len());
assert_eq!(1, dict2.len()); });
} }
#[test] #[test]
fn test_contains() { fn test_contains() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut v = HashMap::new();
let mut v = HashMap::new(); v.insert(7, 32);
v.insert(7, 32); let ob = v.to_object(py);
let ob = v.to_object(py); let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap(); assert!(dict.contains(7i32).unwrap());
assert!(dict.contains(7i32).unwrap()); assert!(!dict.contains(8i32).unwrap());
assert!(!dict.contains(8i32).unwrap()); });
} }
#[test] #[test]
fn test_get_item() { fn test_get_item() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut v = HashMap::new();
let mut v = HashMap::new(); v.insert(7, 32);
v.insert(7, 32); let ob = v.to_object(py);
let ob = v.to_object(py); let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap(); assert_eq!(32, dict.get_item(7i32).unwrap().extract::<i32>().unwrap());
assert_eq!(32, dict.get_item(7i32).unwrap().extract::<i32>().unwrap()); assert_eq!(None, dict.get_item(8i32));
assert_eq!(None, dict.get_item(8i32)); });
} }
#[test] #[test]
fn test_set_item() { fn test_set_item() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut v = HashMap::new();
let mut v = HashMap::new(); v.insert(7, 32);
v.insert(7, 32); let ob = v.to_object(py);
let ob = v.to_object(py); let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap(); assert!(dict.set_item(7i32, 42i32).is_ok()); // change
assert!(dict.set_item(7i32, 42i32).is_ok()); // change assert!(dict.set_item(8i32, 123i32).is_ok()); // insert
assert!(dict.set_item(8i32, 123i32).is_ok()); // insert assert_eq!(
assert_eq!( 42i32,
42i32, dict.get_item(7i32).unwrap().extract::<i32>().unwrap()
dict.get_item(7i32).unwrap().extract::<i32>().unwrap() );
); assert_eq!(
assert_eq!( 123i32,
123i32, dict.get_item(8i32).unwrap().extract::<i32>().unwrap()
dict.get_item(8i32).unwrap().extract::<i32>().unwrap() );
); });
} }
#[test] #[test]
fn test_set_item_refcnt() { fn test_set_item_refcnt() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let cnt;
{
let cnt; let _pool = unsafe { crate::GILPool::new() };
{ let none = py.None();
let _pool = unsafe { crate::GILPool::new() }; cnt = none.get_refcnt(py);
let none = py.None(); let _dict = [(10, none)].into_py_dict(py);
cnt = none.get_refcnt(py); }
let _dict = [(10, none)].into_py_dict(py); {
} assert_eq!(cnt, py.None().get_refcnt(py));
{ }
assert_eq!(cnt, py.None().get_refcnt(py)); });
}
} }
#[test] #[test]
fn test_set_item_does_not_update_original_object() { fn test_set_item_does_not_update_original_object() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut v = HashMap::new();
let mut v = HashMap::new(); v.insert(7, 32);
v.insert(7, 32); let ob = v.to_object(py);
let ob = v.to_object(py); let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap(); assert!(dict.set_item(7i32, 42i32).is_ok()); // change
assert!(dict.set_item(7i32, 42i32).is_ok()); // change assert!(dict.set_item(8i32, 123i32).is_ok()); // insert
assert!(dict.set_item(8i32, 123i32).is_ok()); // insert assert_eq!(32i32, v[&7i32]); // not updated!
assert_eq!(32i32, v[&7i32]); // not updated! assert_eq!(None, v.get(&8i32));
assert_eq!(None, v.get(&8i32)); });
} }
#[test] #[test]
fn test_del_item() { fn test_del_item() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut v = HashMap::new();
let mut v = HashMap::new(); v.insert(7, 32);
v.insert(7, 32); let ob = v.to_object(py);
let ob = v.to_object(py); let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap(); assert!(dict.del_item(7i32).is_ok());
assert!(dict.del_item(7i32).is_ok()); assert_eq!(0, dict.len());
assert_eq!(0, dict.len()); assert_eq!(None, dict.get_item(7i32));
assert_eq!(None, dict.get_item(7i32)); });
} }
#[test] #[test]
fn test_del_item_does_not_update_original_object() { fn test_del_item_does_not_update_original_object() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut v = HashMap::new();
let mut v = HashMap::new(); v.insert(7, 32);
v.insert(7, 32); let ob = v.to_object(py);
let ob = v.to_object(py); let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap(); assert!(dict.del_item(7i32).is_ok()); // change
assert!(dict.del_item(7i32).is_ok()); // change assert_eq!(32i32, *v.get(&7i32).unwrap()); // not updated!
assert_eq!(32i32, *v.get(&7i32).unwrap()); // not updated! });
} }
#[test] #[test]
fn test_items() { fn test_items() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut v = HashMap::new();
let mut v = HashMap::new(); v.insert(7, 32);
v.insert(7, 32); v.insert(8, 42);
v.insert(8, 42); v.insert(9, 123);
v.insert(9, 123); let ob = v.to_object(py);
let ob = v.to_object(py); let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap(); // Can't just compare against a vector of tuples since we don't have a guaranteed ordering.
// Can't just compare against a vector of tuples since we don't have a guaranteed ordering. let mut key_sum = 0;
let mut key_sum = 0; let mut value_sum = 0;
let mut value_sum = 0; for el in dict.items().iter() {
for el in dict.items().iter() { let tuple = el.cast_as::<PyTuple>().unwrap();
let tuple = el.cast_as::<PyTuple>().unwrap(); key_sum += tuple.get_item(0).extract::<i32>().unwrap();
key_sum += tuple.get_item(0).extract::<i32>().unwrap(); value_sum += tuple.get_item(1).extract::<i32>().unwrap();
value_sum += tuple.get_item(1).extract::<i32>().unwrap(); }
} assert_eq!(7 + 8 + 9, key_sum);
assert_eq!(7 + 8 + 9, key_sum); assert_eq!(32 + 42 + 123, value_sum);
assert_eq!(32 + 42 + 123, value_sum); });
} }
#[test] #[test]
fn test_keys() { fn test_keys() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut v = HashMap::new();
let mut v = HashMap::new(); v.insert(7, 32);
v.insert(7, 32); v.insert(8, 42);
v.insert(8, 42); v.insert(9, 123);
v.insert(9, 123); let ob = v.to_object(py);
let ob = v.to_object(py); let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap(); // Can't just compare against a vector of tuples since we don't have a guaranteed ordering.
// Can't just compare against a vector of tuples since we don't have a guaranteed ordering. let mut key_sum = 0;
let mut key_sum = 0; for el in dict.keys().iter() {
for el in dict.keys().iter() { key_sum += el.extract::<i32>().unwrap();
key_sum += el.extract::<i32>().unwrap(); }
} assert_eq!(7 + 8 + 9, key_sum);
assert_eq!(7 + 8 + 9, key_sum); });
} }
#[test] #[test]
fn test_values() { fn test_values() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut v = HashMap::new();
let mut v = HashMap::new(); v.insert(7, 32);
v.insert(7, 32); v.insert(8, 42);
v.insert(8, 42); v.insert(9, 123);
v.insert(9, 123); let ob = v.to_object(py);
let ob = v.to_object(py); let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap(); // Can't just compare against a vector of tuples since we don't have a guaranteed ordering.
// Can't just compare against a vector of tuples since we don't have a guaranteed ordering. let mut values_sum = 0;
let mut values_sum = 0; for el in dict.values().iter() {
for el in dict.values().iter() { values_sum += el.extract::<i32>().unwrap();
values_sum += el.extract::<i32>().unwrap(); }
} assert_eq!(32 + 42 + 123, values_sum);
assert_eq!(32 + 42 + 123, values_sum); });
} }
#[test] #[test]
fn test_iter() { fn test_iter() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut v = HashMap::new();
let mut v = HashMap::new(); v.insert(7, 32);
v.insert(7, 32); v.insert(8, 42);
v.insert(8, 42); v.insert(9, 123);
v.insert(9, 123); let ob = v.to_object(py);
let ob = v.to_object(py); let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap(); let mut key_sum = 0;
let mut key_sum = 0; let mut value_sum = 0;
let mut value_sum = 0; for (key, value) in dict.iter() {
for (key, value) in dict.iter() { key_sum += key.extract::<i32>().unwrap();
key_sum += key.extract::<i32>().unwrap(); value_sum += value.extract::<i32>().unwrap();
value_sum += value.extract::<i32>().unwrap(); }
} assert_eq!(7 + 8 + 9, key_sum);
assert_eq!(7 + 8 + 9, key_sum); assert_eq!(32 + 42 + 123, value_sum);
assert_eq!(32 + 42 + 123, value_sum); });
} }
#[test] #[test]
fn test_iter_size_hint() { fn test_iter_size_hint() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut v = HashMap::new();
let mut v = HashMap::new(); v.insert(7, 32);
v.insert(7, 32); v.insert(8, 42);
v.insert(8, 42); v.insert(9, 123);
v.insert(9, 123); let ob = v.to_object(py);
let ob = v.to_object(py); let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let mut iter = dict.iter(); let mut iter = dict.iter();
assert_eq!(iter.size_hint(), (v.len(), Some(v.len()))); assert_eq!(iter.size_hint(), (v.len(), Some(v.len())));
iter.next(); iter.next();
assert_eq!(iter.size_hint(), (v.len() - 1, Some(v.len() - 1))); assert_eq!(iter.size_hint(), (v.len() - 1, Some(v.len() - 1)));
// Exhust iterator. // Exhust iterator.
for _ in &mut iter {} for _ in &mut iter {}
assert_eq!(iter.size_hint(), (0, Some(0))); assert_eq!(iter.size_hint(), (0, Some(0)));
});
} }
#[test] #[test]
fn test_into_iter() { fn test_into_iter() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut v = HashMap::new();
let mut v = HashMap::new(); v.insert(7, 32);
v.insert(7, 32); v.insert(8, 42);
v.insert(8, 42); v.insert(9, 123);
v.insert(9, 123); let ob = v.to_object(py);
let ob = v.to_object(py); let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap(); let mut key_sum = 0;
let mut key_sum = 0; let mut value_sum = 0;
let mut value_sum = 0; for (key, value) in dict {
for (key, value) in dict { key_sum += key.extract::<i32>().unwrap();
key_sum += key.extract::<i32>().unwrap(); value_sum += value.extract::<i32>().unwrap();
value_sum += value.extract::<i32>().unwrap(); }
} assert_eq!(7 + 8 + 9, key_sum);
assert_eq!(7 + 8 + 9, key_sum); assert_eq!(32 + 42 + 123, value_sum);
assert_eq!(32 + 42 + 123, value_sum); });
} }
#[test] #[test]
fn test_hashmap_to_python() { fn test_hashmap_to_python() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut map = HashMap::<i32, i32>::new();
map.insert(1, 1);
let mut map = HashMap::<i32, i32>::new(); let m = map.to_object(py);
map.insert(1, 1); let py_map = <PyDict as PyTryFrom>::try_from(m.as_ref(py)).unwrap();
let m = map.to_object(py); assert!(py_map.len() == 1);
let py_map = <PyDict as PyTryFrom>::try_from(m.as_ref(py)).unwrap(); assert!(py_map.get_item(1).unwrap().extract::<i32>().unwrap() == 1);
assert_eq!(map, py_map.extract().unwrap());
assert!(py_map.len() == 1); });
assert!(py_map.get_item(1).unwrap().extract::<i32>().unwrap() == 1);
assert_eq!(map, py_map.extract().unwrap());
} }
#[test] #[test]
fn test_btreemap_to_python() { fn test_btreemap_to_python() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut map = BTreeMap::<i32, i32>::new();
map.insert(1, 1);
let mut map = BTreeMap::<i32, i32>::new(); let m = map.to_object(py);
map.insert(1, 1); let py_map = <PyDict as PyTryFrom>::try_from(m.as_ref(py)).unwrap();
let m = map.to_object(py); assert!(py_map.len() == 1);
let py_map = <PyDict as PyTryFrom>::try_from(m.as_ref(py)).unwrap(); assert!(py_map.get_item(1).unwrap().extract::<i32>().unwrap() == 1);
assert_eq!(map, py_map.extract().unwrap());
assert!(py_map.len() == 1); });
assert!(py_map.get_item(1).unwrap().extract::<i32>().unwrap() == 1);
assert_eq!(map, py_map.extract().unwrap());
} }
#[test] #[test]
fn test_hashmap_into_python() { fn test_hashmap_into_python() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut map = HashMap::<i32, i32>::new();
map.insert(1, 1);
let mut map = HashMap::<i32, i32>::new(); let m: PyObject = map.into_py(py);
map.insert(1, 1); let py_map = <PyDict as PyTryFrom>::try_from(m.as_ref(py)).unwrap();
let m: PyObject = map.into_py(py); assert!(py_map.len() == 1);
let py_map = <PyDict as PyTryFrom>::try_from(m.as_ref(py)).unwrap(); assert!(py_map.get_item(1).unwrap().extract::<i32>().unwrap() == 1);
});
assert!(py_map.len() == 1);
assert!(py_map.get_item(1).unwrap().extract::<i32>().unwrap() == 1);
} }
#[test] #[test]
fn test_hashmap_into_dict() { fn test_hashmap_into_dict() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut map = HashMap::<i32, i32>::new();
map.insert(1, 1);
let mut map = HashMap::<i32, i32>::new(); let py_map = map.into_py_dict(py);
map.insert(1, 1);
let py_map = map.into_py_dict(py); assert_eq!(py_map.len(), 1);
assert_eq!(py_map.get_item(1).unwrap().extract::<i32>().unwrap(), 1);
assert_eq!(py_map.len(), 1); });
assert_eq!(py_map.get_item(1).unwrap().extract::<i32>().unwrap(), 1);
} }
#[test] #[test]
fn test_btreemap_into_py() { fn test_btreemap_into_py() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut map = BTreeMap::<i32, i32>::new();
map.insert(1, 1);
let mut map = BTreeMap::<i32, i32>::new(); let m: PyObject = map.into_py(py);
map.insert(1, 1); let py_map = <PyDict as PyTryFrom>::try_from(m.as_ref(py)).unwrap();
let m: PyObject = map.into_py(py); assert!(py_map.len() == 1);
let py_map = <PyDict as PyTryFrom>::try_from(m.as_ref(py)).unwrap(); assert!(py_map.get_item(1).unwrap().extract::<i32>().unwrap() == 1);
});
assert!(py_map.len() == 1);
assert!(py_map.get_item(1).unwrap().extract::<i32>().unwrap() == 1);
} }
#[test] #[test]
fn test_btreemap_into_dict() { fn test_btreemap_into_dict() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut map = BTreeMap::<i32, i32>::new();
map.insert(1, 1);
let mut map = BTreeMap::<i32, i32>::new(); let py_map = map.into_py_dict(py);
map.insert(1, 1);
let py_map = map.into_py_dict(py); assert_eq!(py_map.len(), 1);
assert_eq!(py_map.get_item(1).unwrap().extract::<i32>().unwrap(), 1);
assert_eq!(py_map.len(), 1); });
assert_eq!(py_map.get_item(1).unwrap().extract::<i32>().unwrap(), 1);
} }
#[test] #[test]
fn test_vec_into_dict() { fn test_vec_into_dict() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let vec = vec![("a", 1), ("b", 2), ("c", 3)];
let py_map = vec.into_py_dict(py);
let vec = vec![("a", 1), ("b", 2), ("c", 3)]; assert_eq!(py_map.len(), 3);
let py_map = vec.into_py_dict(py); assert_eq!(py_map.get_item("b").unwrap().extract::<i32>().unwrap(), 2);
});
assert_eq!(py_map.len(), 3);
assert_eq!(py_map.get_item("b").unwrap().extract::<i32>().unwrap(), 2);
} }
#[test] #[test]
fn test_slice_into_dict() { fn test_slice_into_dict() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let arr = [("a", 1), ("b", 2), ("c", 3)];
let py_map = arr.into_py_dict(py);
let arr = [("a", 1), ("b", 2), ("c", 3)]; assert_eq!(py_map.len(), 3);
let py_map = arr.into_py_dict(py); assert_eq!(py_map.get_item("b").unwrap().extract::<i32>().unwrap(), 2);
});
assert_eq!(py_map.len(), 3);
assert_eq!(py_map.get_item("b").unwrap().extract::<i32>().unwrap(), 2);
} }
} }

View File

@ -93,11 +93,12 @@ mod tests {
fn $func_name() { fn $func_name() {
use assert_approx_eq::assert_approx_eq; use assert_approx_eq::assert_approx_eq;
let gil = Python::acquire_gil(); Python::with_gil(|py|{
let py = gil.python();
let val = 123 as $t1; let val = 123 as $t1;
let obj = val.to_object(py); let obj = val.to_object(py);
assert_approx_eq!(obj.extract::<$t2>(py).unwrap(), val as $t2); assert_approx_eq!(obj.extract::<$t2>(py).unwrap(), val as $t2);
});
} }
) )
); );
@ -111,10 +112,10 @@ mod tests {
fn test_as_double_macro() { fn test_as_double_macro() {
use assert_approx_eq::assert_approx_eq; use assert_approx_eq::assert_approx_eq;
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v = 1.23f64;
let v = 1.23f64; let obj = v.to_object(py);
let obj = v.to_object(py); assert_approx_eq!(v, unsafe { PyFloat_AS_DOUBLE(obj.as_ptr()) });
assert_approx_eq!(v, unsafe { PyFloat_AS_DOUBLE(obj.as_ptr()) }); });
} }
} }

View File

@ -107,65 +107,62 @@ mod tests {
#[test] #[test]
fn vec_iter() { fn vec_iter() {
let gil_guard = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil_guard.python(); let obj = vec![10, 20].to_object(py);
let obj = vec![10, 20].to_object(py); let inst = obj.as_ref(py);
let inst = obj.as_ref(py); let mut it = inst.iter().unwrap();
let mut it = inst.iter().unwrap(); assert_eq!(10, it.next().unwrap().unwrap().extract().unwrap());
assert_eq!(10, it.next().unwrap().unwrap().extract().unwrap()); assert_eq!(20, it.next().unwrap().unwrap().extract().unwrap());
assert_eq!(20, it.next().unwrap().unwrap().extract().unwrap()); assert!(it.next().is_none());
assert!(it.next().is_none()); });
} }
#[test] #[test]
fn iter_refcnt() { fn iter_refcnt() {
let obj; let (obj, count) = Python::with_gil(|py| {
let count; let obj = vec![10, 20].to_object(py);
{ let count = obj.get_refcnt(py);
let gil_guard = Python::acquire_gil(); (obj, count)
let py = gil_guard.python(); });
obj = vec![10, 20].to_object(py);
count = obj.get_refcnt(py);
}
{ Python::with_gil(|py| {
let gil_guard = Python::acquire_gil();
let py = gil_guard.python();
let inst = obj.as_ref(py); let inst = obj.as_ref(py);
let mut it = inst.iter().unwrap(); let mut it = inst.iter().unwrap();
assert_eq!(10, it.next().unwrap().unwrap().extract().unwrap()); assert_eq!(10, it.next().unwrap().unwrap().extract().unwrap());
} });
assert_eq!(count, obj.get_refcnt(Python::acquire_gil().python()));
Python::with_gil(|py| {
assert_eq!(count, obj.get_refcnt(py));
});
} }
#[test] #[test]
fn iter_item_refcnt() { fn iter_item_refcnt() {
let gil_guard = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil_guard.python(); let obj;
let none;
let count;
{
let _pool = unsafe { GILPool::new() };
let l = PyList::empty(py);
none = py.None();
l.append(10).unwrap();
l.append(&none).unwrap();
count = none.get_refcnt(py);
obj = l.to_object(py);
}
let obj; {
let none; let _pool = unsafe { GILPool::new() };
let count; let inst = obj.as_ref(py);
{ let mut it = inst.iter().unwrap();
let _pool = unsafe { GILPool::new() };
let l = PyList::empty(py);
none = py.None();
l.append(10).unwrap();
l.append(&none).unwrap();
count = none.get_refcnt(py);
obj = l.to_object(py);
}
{ assert_eq!(10, it.next().unwrap().unwrap().extract().unwrap());
let _pool = unsafe { GILPool::new() }; assert!(it.next().unwrap().unwrap().is_none());
let inst = obj.as_ref(py); }
let mut it = inst.iter().unwrap(); assert_eq!(count, none.get_refcnt(py));
});
assert_eq!(10, it.next().unwrap().unwrap().extract().unwrap());
assert!(it.next().unwrap().unwrap().is_none());
}
assert_eq!(count, none.get_refcnt(py));
} }
#[test] #[test]
@ -181,37 +178,35 @@ mod tests {
"# "#
); );
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let context = PyDict::new(py);
py.run(fibonacci_generator, None, Some(context)).unwrap();
let context = PyDict::new(py); let generator = py.eval("fibonacci(5)", None, Some(context)).unwrap();
py.run(fibonacci_generator, None, Some(context)).unwrap(); for (actual, expected) in generator.iter().unwrap().zip(&[1, 1, 2, 3, 5]) {
let actual = actual.unwrap().extract::<usize>().unwrap();
let generator = py.eval("fibonacci(5)", None, Some(context)).unwrap(); assert_eq!(actual, *expected)
for (actual, expected) in generator.iter().unwrap().zip(&[1, 1, 2, 3, 5]) { }
let actual = actual.unwrap().extract::<usize>().unwrap(); });
assert_eq!(actual, *expected)
}
} }
#[test] #[test]
fn int_not_iterable() { fn int_not_iterable() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let x = 5.to_object(py);
let err = PyIterator::from_object(py, &x).unwrap_err();
let x = 5.to_object(py); assert!(err.is_instance::<PyTypeError>(py));
let err = PyIterator::from_object(py, &x).unwrap_err(); });
assert!(err.is_instance::<PyTypeError>(py))
} }
#[test] #[test]
#[cfg(any(not(Py_LIMITED_API), Py_3_8))] #[cfg(any(not(Py_LIMITED_API), Py_3_8))]
fn iterator_try_from() { fn iterator_try_from() {
let gil_guard = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil_guard.python(); let obj: Py<PyAny> = vec![10, 20].to_object(py).as_ref(py).iter().unwrap().into();
let obj: Py<PyAny> = vec![10, 20].to_object(py).as_ref(py).iter().unwrap().into(); let iter: &PyIterator = PyIterator::try_from(obj.as_ref(py)).unwrap();
let iter: &PyIterator = PyIterator::try_from(obj.as_ref(py)).unwrap(); assert_eq!(obj, iter.into());
assert_eq!(obj, iter.into()); });
} }
} }

View File

@ -214,224 +214,221 @@ mod tests {
#[test] #[test]
fn test_new() { fn test_new() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let list = PyList::new(py, &[2, 3, 5, 7]);
let list = PyList::new(py, &[2, 3, 5, 7]); assert_eq!(2, list.get_item(0).extract::<i32>().unwrap());
assert_eq!(2, list.get_item(0).extract::<i32>().unwrap()); assert_eq!(3, list.get_item(1).extract::<i32>().unwrap());
assert_eq!(3, list.get_item(1).extract::<i32>().unwrap()); assert_eq!(5, list.get_item(2).extract::<i32>().unwrap());
assert_eq!(5, list.get_item(2).extract::<i32>().unwrap()); assert_eq!(7, list.get_item(3).extract::<i32>().unwrap());
assert_eq!(7, list.get_item(3).extract::<i32>().unwrap()); });
} }
#[test] #[test]
fn test_len() { fn test_len() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let list = PyList::new(py, &[1, 2, 3, 4]);
let list = PyList::new(py, &[1, 2, 3, 4]); assert_eq!(4, list.len());
assert_eq!(4, list.len()); });
} }
#[test] #[test]
fn test_get_item() { fn test_get_item() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let list = PyList::new(py, &[2, 3, 5, 7]);
let list = PyList::new(py, &[2, 3, 5, 7]); assert_eq!(2, list.get_item(0).extract::<i32>().unwrap());
assert_eq!(2, list.get_item(0).extract::<i32>().unwrap()); assert_eq!(3, list.get_item(1).extract::<i32>().unwrap());
assert_eq!(3, list.get_item(1).extract::<i32>().unwrap()); assert_eq!(5, list.get_item(2).extract::<i32>().unwrap());
assert_eq!(5, list.get_item(2).extract::<i32>().unwrap()); assert_eq!(7, list.get_item(3).extract::<i32>().unwrap());
assert_eq!(7, list.get_item(3).extract::<i32>().unwrap()); });
} }
#[test] #[test]
#[should_panic] #[should_panic]
fn test_get_item_invalid() { fn test_get_item_invalid() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let list = PyList::new(py, &[2, 3, 5, 7]);
let list = PyList::new(py, &[2, 3, 5, 7]); list.get_item(-1);
list.get_item(-1); });
} }
#[test] #[test]
fn test_set_item() { fn test_set_item() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let list = PyList::new(py, &[2, 3, 5, 7]);
let list = PyList::new(py, &[2, 3, 5, 7]); let val = 42i32.to_object(py);
let val = 42i32.to_object(py); assert_eq!(2, list.get_item(0).extract::<i32>().unwrap());
assert_eq!(2, list.get_item(0).extract::<i32>().unwrap()); list.set_item(0, val).unwrap();
list.set_item(0, val).unwrap(); assert_eq!(42, list.get_item(0).extract::<i32>().unwrap());
assert_eq!(42, list.get_item(0).extract::<i32>().unwrap()); });
} }
#[test] #[test]
fn test_set_item_refcnt() { fn test_set_item_refcnt() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let cnt;
{
let _pool = unsafe { crate::GILPool::new() };
let v = vec![2];
let ob = v.to_object(py);
let list = <PyList as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let none = py.None();
cnt = none.get_refcnt(py);
list.set_item(0, none).unwrap();
}
let cnt; assert_eq!(cnt, py.None().get_refcnt(py));
{ });
let _pool = unsafe { crate::GILPool::new() };
let v = vec![2];
let ob = v.to_object(py);
let list = <PyList as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let none = py.None();
cnt = none.get_refcnt(py);
list.set_item(0, none).unwrap();
}
assert_eq!(cnt, py.None().get_refcnt(py));
} }
#[test] #[test]
fn test_insert() { fn test_insert() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let list = PyList::new(py, &[2, 3, 5, 7]);
let list = PyList::new(py, &[2, 3, 5, 7]); let val = 42i32.to_object(py);
let val = 42i32.to_object(py); assert_eq!(4, list.len());
assert_eq!(4, list.len()); assert_eq!(2, list.get_item(0).extract::<i32>().unwrap());
assert_eq!(2, list.get_item(0).extract::<i32>().unwrap()); list.insert(0, val).unwrap();
list.insert(0, val).unwrap(); assert_eq!(5, list.len());
assert_eq!(5, list.len()); assert_eq!(42, list.get_item(0).extract::<i32>().unwrap());
assert_eq!(42, list.get_item(0).extract::<i32>().unwrap()); assert_eq!(2, list.get_item(1).extract::<i32>().unwrap());
assert_eq!(2, list.get_item(1).extract::<i32>().unwrap()); });
} }
#[test] #[test]
fn test_insert_refcnt() { fn test_insert_refcnt() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let cnt;
{
let _pool = unsafe { crate::GILPool::new() };
let list = PyList::empty(py);
let none = py.None();
cnt = none.get_refcnt(py);
list.insert(0, none).unwrap();
}
let cnt; assert_eq!(cnt, py.None().get_refcnt(py));
{ });
let _pool = unsafe { crate::GILPool::new() };
let list = PyList::empty(py);
let none = py.None();
cnt = none.get_refcnt(py);
list.insert(0, none).unwrap();
}
assert_eq!(cnt, py.None().get_refcnt(py));
} }
#[test] #[test]
fn test_append() { fn test_append() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let list = PyList::new(py, &[2]);
let list = PyList::new(py, &[2]); list.append(3).unwrap();
list.append(3).unwrap(); assert_eq!(2, list.get_item(0).extract::<i32>().unwrap());
assert_eq!(2, list.get_item(0).extract::<i32>().unwrap()); assert_eq!(3, list.get_item(1).extract::<i32>().unwrap());
assert_eq!(3, list.get_item(1).extract::<i32>().unwrap()); });
} }
#[test] #[test]
fn test_append_refcnt() { fn test_append_refcnt() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let cnt;
{
let cnt; let _pool = unsafe { crate::GILPool::new() };
{ let list = PyList::empty(py);
let _pool = unsafe { crate::GILPool::new() }; let none = py.None();
let list = PyList::empty(py); cnt = none.get_refcnt(py);
let none = py.None(); list.append(none).unwrap();
cnt = none.get_refcnt(py); }
list.append(none).unwrap(); assert_eq!(cnt, py.None().get_refcnt(py));
} });
assert_eq!(cnt, py.None().get_refcnt(py));
} }
#[test] #[test]
fn test_iter() { fn test_iter() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v = vec![2, 3, 5, 7];
let v = vec![2, 3, 5, 7]; let list = PyList::new(py, &v);
let list = PyList::new(py, &v); let mut idx = 0;
let mut idx = 0; for el in list.iter() {
for el in list.iter() { assert_eq!(v[idx], el.extract::<i32>().unwrap());
assert_eq!(v[idx], el.extract::<i32>().unwrap()); idx += 1;
idx += 1; }
} assert_eq!(idx, v.len());
assert_eq!(idx, v.len()); });
} }
#[test] #[test]
fn test_iter_size_hint() { fn test_iter_size_hint() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v = vec![2, 3, 5, 7];
let v = vec![2, 3, 5, 7]; let ob = v.to_object(py);
let ob = v.to_object(py); let list = <PyList as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let list = <PyList as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let mut iter = list.iter(); let mut iter = list.iter();
assert_eq!(iter.size_hint(), (v.len(), Some(v.len()))); assert_eq!(iter.size_hint(), (v.len(), Some(v.len())));
iter.next(); iter.next();
assert_eq!(iter.size_hint(), (v.len() - 1, Some(v.len() - 1))); assert_eq!(iter.size_hint(), (v.len() - 1, Some(v.len() - 1)));
// Exhust iterator. // Exhust iterator.
for _ in &mut iter {} for _ in &mut iter {}
assert_eq!(iter.size_hint(), (0, Some(0))); assert_eq!(iter.size_hint(), (0, Some(0)));
});
} }
#[test] #[test]
fn test_into_iter() { fn test_into_iter() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let list = PyList::new(py, &[1, 2, 3, 4]);
let list = PyList::new(py, &[1, 2, 3, 4]); for (i, item) in list.iter().enumerate() {
for (i, item) in list.iter().enumerate() { assert_eq!((i + 1) as i32, item.extract::<i32>().unwrap());
assert_eq!((i + 1) as i32, item.extract::<i32>().unwrap()); }
} });
} }
#[test] #[test]
fn test_extract() { fn test_extract() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v = vec![2, 3, 5, 7];
let v = vec![2, 3, 5, 7]; let list = PyList::new(py, &v);
let list = PyList::new(py, &v); let v2 = list.as_ref().extract::<Vec<i32>>().unwrap();
let v2 = list.as_ref().extract::<Vec<i32>>().unwrap(); assert_eq!(v, v2);
assert_eq!(v, v2); });
} }
#[test] #[test]
fn test_sort() { fn test_sort() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v = vec![7, 3, 2, 5];
let v = vec![7, 3, 2, 5]; let list = PyList::new(py, &v);
let list = PyList::new(py, &v); assert_eq!(7, list.get_item(0).extract::<i32>().unwrap());
assert_eq!(7, list.get_item(0).extract::<i32>().unwrap()); assert_eq!(3, list.get_item(1).extract::<i32>().unwrap());
assert_eq!(3, list.get_item(1).extract::<i32>().unwrap()); assert_eq!(2, list.get_item(2).extract::<i32>().unwrap());
assert_eq!(2, list.get_item(2).extract::<i32>().unwrap()); assert_eq!(5, list.get_item(3).extract::<i32>().unwrap());
assert_eq!(5, list.get_item(3).extract::<i32>().unwrap()); list.sort().unwrap();
list.sort().unwrap(); assert_eq!(2, list.get_item(0).extract::<i32>().unwrap());
assert_eq!(2, list.get_item(0).extract::<i32>().unwrap()); assert_eq!(3, list.get_item(1).extract::<i32>().unwrap());
assert_eq!(3, list.get_item(1).extract::<i32>().unwrap()); assert_eq!(5, list.get_item(2).extract::<i32>().unwrap());
assert_eq!(5, list.get_item(2).extract::<i32>().unwrap()); assert_eq!(7, list.get_item(3).extract::<i32>().unwrap());
assert_eq!(7, list.get_item(3).extract::<i32>().unwrap()); });
} }
#[test] #[test]
fn test_reverse() { fn test_reverse() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v = vec![2, 3, 5, 7];
let v = vec![2, 3, 5, 7]; let list = PyList::new(py, &v);
let list = PyList::new(py, &v); assert_eq!(2, list.get_item(0).extract::<i32>().unwrap());
assert_eq!(2, list.get_item(0).extract::<i32>().unwrap()); assert_eq!(3, list.get_item(1).extract::<i32>().unwrap());
assert_eq!(3, list.get_item(1).extract::<i32>().unwrap()); assert_eq!(5, list.get_item(2).extract::<i32>().unwrap());
assert_eq!(5, list.get_item(2).extract::<i32>().unwrap()); assert_eq!(7, list.get_item(3).extract::<i32>().unwrap());
assert_eq!(7, list.get_item(3).extract::<i32>().unwrap()); list.reverse().unwrap();
list.reverse().unwrap(); assert_eq!(7, list.get_item(0).extract::<i32>().unwrap());
assert_eq!(7, list.get_item(0).extract::<i32>().unwrap()); assert_eq!(5, list.get_item(1).extract::<i32>().unwrap());
assert_eq!(5, list.get_item(1).extract::<i32>().unwrap()); assert_eq!(3, list.get_item(2).extract::<i32>().unwrap());
assert_eq!(3, list.get_item(2).extract::<i32>().unwrap()); assert_eq!(2, list.get_item(3).extract::<i32>().unwrap());
assert_eq!(2, list.get_item(3).extract::<i32>().unwrap()); });
} }
#[test] #[test]
fn test_array_into_py() { fn test_array_into_py() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let array: PyObject = [1, 2].into_py(py);
let array: PyObject = [1, 2].into_py(py); let list = <PyList as PyTryFrom>::try_from(array.as_ref(py)).unwrap();
let list = <PyList as PyTryFrom>::try_from(array.as_ref(py)).unwrap(); assert_eq!(1, list.get_item(0).extract::<i32>().unwrap());
assert_eq!(1, list.get_item(0).extract::<i32>().unwrap()); assert_eq!(2, list.get_item(1).extract::<i32>().unwrap());
assert_eq!(2, list.get_item(1).extract::<i32>().unwrap()); });
} }
} }

View File

@ -361,45 +361,45 @@ mod tests {
#[test] #[test]
fn test_u32_max() { fn test_u32_max() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v = std::u32::MAX;
let v = std::u32::MAX; let obj = v.to_object(py);
let obj = v.to_object(py); assert_eq!(v, obj.extract::<u32>(py).unwrap());
assert_eq!(v, obj.extract::<u32>(py).unwrap()); assert_eq!(u64::from(v), obj.extract::<u64>(py).unwrap());
assert_eq!(u64::from(v), obj.extract::<u64>(py).unwrap()); assert!(obj.extract::<i32>(py).is_err());
assert!(obj.extract::<i32>(py).is_err()); });
} }
#[test] #[test]
fn test_i64_max() { fn test_i64_max() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v = std::i64::MAX;
let v = std::i64::MAX; let obj = v.to_object(py);
let obj = v.to_object(py); assert_eq!(v, obj.extract::<i64>(py).unwrap());
assert_eq!(v, obj.extract::<i64>(py).unwrap()); assert_eq!(v as u64, obj.extract::<u64>(py).unwrap());
assert_eq!(v as u64, obj.extract::<u64>(py).unwrap()); assert!(obj.extract::<u32>(py).is_err());
assert!(obj.extract::<u32>(py).is_err()); });
} }
#[test] #[test]
fn test_i64_min() { fn test_i64_min() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v = std::i64::MIN;
let v = std::i64::MIN; let obj = v.to_object(py);
let obj = v.to_object(py); assert_eq!(v, obj.extract::<i64>(py).unwrap());
assert_eq!(v, obj.extract::<i64>(py).unwrap()); assert!(obj.extract::<i32>(py).is_err());
assert!(obj.extract::<i32>(py).is_err()); assert!(obj.extract::<u64>(py).is_err());
assert!(obj.extract::<u64>(py).is_err()); });
} }
#[test] #[test]
fn test_u64_max() { fn test_u64_max() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v = std::u64::MAX;
let v = std::u64::MAX; let obj = v.to_object(py);
let obj = v.to_object(py); assert_eq!(v, obj.extract::<u64>(py).unwrap());
assert_eq!(v, obj.extract::<u64>(py).unwrap()); assert!(obj.extract::<i64>(py).is_err());
assert!(obj.extract::<i64>(py).is_err()); });
} }
macro_rules! test_common ( macro_rules! test_common (
@ -411,32 +411,31 @@ mod tests {
#[test] #[test]
fn from_py_string_type_error() { fn from_py_string_type_error() {
let gil = Python::acquire_gil(); Python::with_gil(|py|{
let py = gil.python();
let obj = ("123").to_object(py); let obj = ("123").to_object(py);
let err = obj.extract::<$t>(py).unwrap_err(); let err = obj.extract::<$t>(py).unwrap_err();
assert!(err.is_instance::<exceptions::PyTypeError>(py)); assert!(err.is_instance::<exceptions::PyTypeError>(py));
});
} }
#[test] #[test]
fn from_py_float_type_error() { fn from_py_float_type_error() {
let gil = Python::acquire_gil(); Python::with_gil(|py|{
let py = gil.python();
let obj = (12.3).to_object(py); let obj = (12.3).to_object(py);
let err = obj.extract::<$t>(py).unwrap_err(); let err = obj.extract::<$t>(py).unwrap_err();
assert!(err.is_instance::<exceptions::PyTypeError>(py)); assert!(err.is_instance::<exceptions::PyTypeError>(py));});
} }
#[test] #[test]
fn to_py_object_and_back() { fn to_py_object_and_back() {
let gil = Python::acquire_gil(); Python::with_gil(|py|{
let py = gil.python();
let val = 123 as $t; let val = 123 as $t;
let obj = val.to_object(py); let obj = val.to_object(py);
assert_eq!(obj.extract::<$t>(py).unwrap(), val as $t); assert_eq!(obj.extract::<$t>(py).unwrap(), val as $t);});
} }
} }
) )

View File

@ -338,80 +338,79 @@ mod tests {
fn get_object() -> PyObject { fn get_object() -> PyObject {
// Convenience function for getting a single unique object // Convenience function for getting a single unique object
let gil = Python::acquire_gil(); Python::with_gil(|py| -> PyObject {
let py = gil.python(); let obj = py.eval("object()", None, None).unwrap();
let obj = py.eval("object()", None, None).unwrap(); obj.to_object(py)
})
obj.to_object(py)
} }
#[test] #[test]
fn test_numbers_are_not_sequences() { fn test_numbers_are_not_sequences() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v = 42i32;
let v = 42i32; assert!(<PySequence as PyTryFrom>::try_from(v.to_object(py).as_ref(py)).is_err());
assert!(<PySequence as PyTryFrom>::try_from(v.to_object(py).as_ref(py)).is_err()); });
} }
#[test] #[test]
fn test_strings_are_sequences() { fn test_strings_are_sequences() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v = "London Calling";
let v = "London Calling"; assert!(<PySequence as PyTryFrom>::try_from(v.to_object(py).as_ref(py)).is_ok());
assert!(<PySequence as PyTryFrom>::try_from(v.to_object(py).as_ref(py)).is_ok()); });
} }
#[test] #[test]
fn test_seq_empty() { fn test_seq_empty() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v: Vec<i32> = vec![];
let v: Vec<i32> = vec![]; let ob = v.to_object(py);
let ob = v.to_object(py); let seq = ob.cast_as::<PySequence>(py).unwrap();
let seq = ob.cast_as::<PySequence>(py).unwrap(); assert_eq!(0, seq.len().unwrap());
assert_eq!(0, seq.len().unwrap());
let needle = 7i32.to_object(py); let needle = 7i32.to_object(py);
assert!(!seq.contains(&needle).unwrap()); assert!(!seq.contains(&needle).unwrap());
});
} }
#[test] #[test]
fn test_seq_contains() { fn test_seq_contains() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8];
let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8]; let ob = v.to_object(py);
let ob = v.to_object(py); let seq = ob.cast_as::<PySequence>(py).unwrap();
let seq = ob.cast_as::<PySequence>(py).unwrap(); assert_eq!(6, seq.len().unwrap());
assert_eq!(6, seq.len().unwrap());
let bad_needle = 7i32.to_object(py); let bad_needle = 7i32.to_object(py);
assert!(!seq.contains(&bad_needle).unwrap()); assert!(!seq.contains(&bad_needle).unwrap());
let good_needle = 8i32.to_object(py); let good_needle = 8i32.to_object(py);
assert!(seq.contains(&good_needle).unwrap()); assert!(seq.contains(&good_needle).unwrap());
let type_coerced_needle = 8f32.to_object(py); let type_coerced_needle = 8f32.to_object(py);
assert!(seq.contains(&type_coerced_needle).unwrap()); assert!(seq.contains(&type_coerced_needle).unwrap());
});
} }
#[test] #[test]
fn test_seq_get_item() { fn test_seq_get_item() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8];
let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8]; let ob = v.to_object(py);
let ob = v.to_object(py); let seq = ob.cast_as::<PySequence>(py).unwrap();
let seq = ob.cast_as::<PySequence>(py).unwrap(); assert_eq!(1, seq.get_item(0).unwrap().extract::<i32>().unwrap());
assert_eq!(1, seq.get_item(0).unwrap().extract::<i32>().unwrap()); assert_eq!(1, seq.get_item(1).unwrap().extract::<i32>().unwrap());
assert_eq!(1, seq.get_item(1).unwrap().extract::<i32>().unwrap()); assert_eq!(2, seq.get_item(2).unwrap().extract::<i32>().unwrap());
assert_eq!(2, seq.get_item(2).unwrap().extract::<i32>().unwrap()); assert_eq!(3, seq.get_item(3).unwrap().extract::<i32>().unwrap());
assert_eq!(3, seq.get_item(3).unwrap().extract::<i32>().unwrap()); assert_eq!(5, seq.get_item(4).unwrap().extract::<i32>().unwrap());
assert_eq!(5, seq.get_item(4).unwrap().extract::<i32>().unwrap()); assert_eq!(8, seq.get_item(5).unwrap().extract::<i32>().unwrap());
assert_eq!(8, seq.get_item(5).unwrap().extract::<i32>().unwrap()); assert_eq!(8, seq.get_item(-1).unwrap().extract::<i32>().unwrap());
assert_eq!(8, seq.get_item(-1).unwrap().extract::<i32>().unwrap()); assert_eq!(5, seq.get_item(-2).unwrap().extract::<i32>().unwrap());
assert_eq!(5, seq.get_item(-2).unwrap().extract::<i32>().unwrap()); assert_eq!(3, seq.get_item(-3).unwrap().extract::<i32>().unwrap());
assert_eq!(3, seq.get_item(-3).unwrap().extract::<i32>().unwrap()); assert_eq!(2, seq.get_item(-4).unwrap().extract::<i32>().unwrap());
assert_eq!(2, seq.get_item(-4).unwrap().extract::<i32>().unwrap()); assert_eq!(1, seq.get_item(-5).unwrap().extract::<i32>().unwrap());
assert_eq!(1, seq.get_item(-5).unwrap().extract::<i32>().unwrap()); assert!(seq.get_item(10).is_err());
assert!(seq.get_item(10).is_err()); });
} }
// fn test_get_slice() {} // fn test_get_slice() {}
@ -420,259 +419,257 @@ mod tests {
#[test] #[test]
fn test_seq_del_item() { fn test_seq_del_item() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8];
let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8]; let ob = v.to_object(py);
let ob = v.to_object(py); let seq = ob.cast_as::<PySequence>(py).unwrap();
let seq = ob.cast_as::<PySequence>(py).unwrap(); assert!(seq.del_item(10).is_err());
assert!(seq.del_item(10).is_err()); assert_eq!(1, seq.get_item(0).unwrap().extract::<i32>().unwrap());
assert_eq!(1, seq.get_item(0).unwrap().extract::<i32>().unwrap()); assert!(seq.del_item(0).is_ok());
assert!(seq.del_item(0).is_ok()); assert_eq!(1, seq.get_item(0).unwrap().extract::<i32>().unwrap());
assert_eq!(1, seq.get_item(0).unwrap().extract::<i32>().unwrap()); assert!(seq.del_item(0).is_ok());
assert!(seq.del_item(0).is_ok()); assert_eq!(2, seq.get_item(0).unwrap().extract::<i32>().unwrap());
assert_eq!(2, seq.get_item(0).unwrap().extract::<i32>().unwrap()); assert!(seq.del_item(0).is_ok());
assert!(seq.del_item(0).is_ok()); assert_eq!(3, seq.get_item(0).unwrap().extract::<i32>().unwrap());
assert_eq!(3, seq.get_item(0).unwrap().extract::<i32>().unwrap()); assert!(seq.del_item(0).is_ok());
assert!(seq.del_item(0).is_ok()); assert_eq!(5, seq.get_item(0).unwrap().extract::<i32>().unwrap());
assert_eq!(5, seq.get_item(0).unwrap().extract::<i32>().unwrap()); assert!(seq.del_item(0).is_ok());
assert!(seq.del_item(0).is_ok()); assert_eq!(8, seq.get_item(0).unwrap().extract::<i32>().unwrap());
assert_eq!(8, seq.get_item(0).unwrap().extract::<i32>().unwrap()); assert!(seq.del_item(0).is_ok());
assert!(seq.del_item(0).is_ok()); assert_eq!(0, seq.len().unwrap());
assert_eq!(0, seq.len().unwrap()); assert!(seq.del_item(0).is_err());
assert!(seq.del_item(0).is_err()); });
} }
#[test] #[test]
fn test_seq_set_item() { fn test_seq_set_item() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v: Vec<i32> = vec![1, 2];
let v: Vec<i32> = vec![1, 2]; let ob = v.to_object(py);
let ob = v.to_object(py); let seq = ob.cast_as::<PySequence>(py).unwrap();
let seq = ob.cast_as::<PySequence>(py).unwrap(); assert_eq!(2, seq.get_item(1).unwrap().extract::<i32>().unwrap());
assert_eq!(2, seq.get_item(1).unwrap().extract::<i32>().unwrap()); assert!(seq.set_item(1, 10).is_ok());
assert!(seq.set_item(1, 10).is_ok()); assert_eq!(10, seq.get_item(1).unwrap().extract::<i32>().unwrap());
assert_eq!(10, seq.get_item(1).unwrap().extract::<i32>().unwrap()); });
} }
#[test] #[test]
fn test_seq_set_item_refcnt() { fn test_seq_set_item_refcnt() {
let obj = get_object(); let obj = get_object();
{
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python();
let v: Vec<i32> = vec![1, 2]; let v: Vec<i32> = vec![1, 2];
let ob = v.to_object(py); let ob = v.to_object(py);
let seq = ob.cast_as::<PySequence>(py).unwrap(); let seq = ob.cast_as::<PySequence>(py).unwrap();
assert!(seq.set_item(1, &obj).is_ok()); assert!(seq.set_item(1, &obj).is_ok());
assert!(seq.get_item(1).unwrap().as_ptr() == obj.as_ptr()); assert!(seq.get_item(1).unwrap().as_ptr() == obj.as_ptr());
} });
{
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python();
assert_eq!(1, obj.get_refcnt(py)); assert_eq!(1, obj.get_refcnt(py));
} });
} }
#[test] #[test]
fn test_seq_index() { fn test_seq_index() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8];
let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8]; let ob = v.to_object(py);
let ob = v.to_object(py); let seq = ob.cast_as::<PySequence>(py).unwrap();
let seq = ob.cast_as::<PySequence>(py).unwrap(); assert_eq!(0, seq.index(1i32).unwrap());
assert_eq!(0, seq.index(1i32).unwrap()); assert_eq!(2, seq.index(2i32).unwrap());
assert_eq!(2, seq.index(2i32).unwrap()); assert_eq!(3, seq.index(3i32).unwrap());
assert_eq!(3, seq.index(3i32).unwrap()); assert_eq!(4, seq.index(5i32).unwrap());
assert_eq!(4, seq.index(5i32).unwrap()); assert_eq!(5, seq.index(8i32).unwrap());
assert_eq!(5, seq.index(8i32).unwrap()); assert!(seq.index(42i32).is_err());
assert!(seq.index(42i32).is_err()); });
} }
#[test] #[test]
#[cfg(not(PyPy))] #[cfg(not(PyPy))]
fn test_seq_count() { fn test_seq_count() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8];
let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8]; let ob = v.to_object(py);
let ob = v.to_object(py); let seq = ob.cast_as::<PySequence>(py).unwrap();
let seq = ob.cast_as::<PySequence>(py).unwrap(); assert_eq!(2, seq.count(1i32).unwrap());
assert_eq!(2, seq.count(1i32).unwrap()); assert_eq!(1, seq.count(2i32).unwrap());
assert_eq!(1, seq.count(2i32).unwrap()); assert_eq!(1, seq.count(3i32).unwrap());
assert_eq!(1, seq.count(3i32).unwrap()); assert_eq!(1, seq.count(5i32).unwrap());
assert_eq!(1, seq.count(5i32).unwrap()); assert_eq!(1, seq.count(8i32).unwrap());
assert_eq!(1, seq.count(8i32).unwrap()); assert_eq!(0, seq.count(42i32).unwrap());
assert_eq!(0, seq.count(42i32).unwrap()); });
} }
#[test] #[test]
fn test_seq_iter() { fn test_seq_iter() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8];
let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8]; let ob = v.to_object(py);
let ob = v.to_object(py); let seq = ob.cast_as::<PySequence>(py).unwrap();
let seq = ob.cast_as::<PySequence>(py).unwrap(); let mut idx = 0;
let mut idx = 0; for el in seq.iter().unwrap() {
for el in seq.iter().unwrap() { assert_eq!(v[idx], el.unwrap().extract::<i32>().unwrap());
assert_eq!(v[idx], el.unwrap().extract::<i32>().unwrap()); idx += 1;
idx += 1; }
} assert_eq!(idx, v.len());
assert_eq!(idx, v.len()); });
} }
#[test] #[test]
fn test_seq_strings() { fn test_seq_strings() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v = vec!["It", "was", "the", "worst", "of", "times"];
let v = vec!["It", "was", "the", "worst", "of", "times"]; let ob = v.to_object(py);
let ob = v.to_object(py); let seq = ob.cast_as::<PySequence>(py).unwrap();
let seq = ob.cast_as::<PySequence>(py).unwrap();
let bad_needle = "blurst".to_object(py); let bad_needle = "blurst".to_object(py);
assert!(!seq.contains(bad_needle).unwrap()); assert!(!seq.contains(bad_needle).unwrap());
let good_needle = "worst".to_object(py); let good_needle = "worst".to_object(py);
assert!(seq.contains(good_needle).unwrap()); assert!(seq.contains(good_needle).unwrap());
});
} }
#[test] #[test]
fn test_seq_concat() { fn test_seq_concat() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v: Vec<i32> = vec![1, 2, 3];
let v: Vec<i32> = vec![1, 2, 3]; let ob = v.to_object(py);
let ob = v.to_object(py); let seq = ob.cast_as::<PySequence>(py).unwrap();
let seq = ob.cast_as::<PySequence>(py).unwrap(); let concat_seq = seq.concat(seq).unwrap();
let concat_seq = seq.concat(seq).unwrap(); assert_eq!(6, concat_seq.len().unwrap());
assert_eq!(6, concat_seq.len().unwrap()); let concat_v: Vec<i32> = vec![1, 2, 3, 1, 2, 3];
let concat_v: Vec<i32> = vec![1, 2, 3, 1, 2, 3]; for (el, cc) in concat_seq.iter().unwrap().zip(concat_v) {
for (el, cc) in concat_seq.iter().unwrap().zip(concat_v) { assert_eq!(cc, el.unwrap().extract::<i32>().unwrap());
assert_eq!(cc, el.unwrap().extract::<i32>().unwrap()); }
} });
} }
#[test] #[test]
fn test_seq_concat_string() { fn test_seq_concat_string() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v = "string";
let v = "string"; let ob = v.to_object(py);
let ob = v.to_object(py); let seq = ob.cast_as::<PySequence>(py).unwrap();
let seq = ob.cast_as::<PySequence>(py).unwrap(); let concat_seq = seq.concat(seq).unwrap();
let concat_seq = seq.concat(seq).unwrap(); assert_eq!(12, concat_seq.len().unwrap());
assert_eq!(12, concat_seq.len().unwrap()); let concat_v = "stringstring".to_owned();
/*let concat_v = "stringstring".to_owned(); for (el, cc) in seq.iter().unwrap().zip(concat_v.chars()) {
for (el, cc) in seq.iter(py).unwrap().zip(concat_v.chars()) { assert_eq!(cc, el.unwrap().extract::<char>().unwrap());
assert_eq!(cc, el.unwrap().extract::<char>(py).unwrap()); //TODO: extract::<char>() is not implemented }
}*/ });
} }
#[test] #[test]
fn test_seq_repeat() { fn test_seq_repeat() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v = vec!["foo", "bar"];
let v = vec!["foo", "bar"]; let ob = v.to_object(py);
let ob = v.to_object(py); let seq = ob.cast_as::<PySequence>(py).unwrap();
let seq = ob.cast_as::<PySequence>(py).unwrap(); let repeat_seq = seq.repeat(3).unwrap();
let repeat_seq = seq.repeat(3).unwrap(); assert_eq!(6, repeat_seq.len().unwrap());
assert_eq!(6, repeat_seq.len().unwrap()); let repeated = vec!["foo", "bar", "foo", "bar", "foo", "bar"];
let repeated = vec!["foo", "bar", "foo", "bar", "foo", "bar"]; for (el, rpt) in repeat_seq.iter().unwrap().zip(repeated.iter()) {
for (el, rpt) in repeat_seq.iter().unwrap().zip(repeated.iter()) { assert_eq!(*rpt, el.unwrap().extract::<String>().unwrap());
assert_eq!(*rpt, el.unwrap().extract::<String>().unwrap()); }
} });
} }
#[test] #[test]
fn test_list_coercion() { fn test_list_coercion() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v = vec!["foo", "bar"];
let v = vec!["foo", "bar"]; let ob = v.to_object(py);
let ob = v.to_object(py); let seq = ob.cast_as::<PySequence>(py).unwrap();
let seq = ob.cast_as::<PySequence>(py).unwrap(); assert!(seq.list().is_ok());
assert!(seq.list().is_ok()); });
} }
#[test] #[test]
fn test_strings_coerce_to_lists() { fn test_strings_coerce_to_lists() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v = "foo";
let v = "foo"; let ob = v.to_object(py);
let ob = v.to_object(py); let seq = <PySequence as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let seq = <PySequence as PyTryFrom>::try_from(ob.as_ref(py)).unwrap(); assert!(seq.list().is_ok());
assert!(seq.list().is_ok()); });
} }
#[test] #[test]
fn test_tuple_coercion() { fn test_tuple_coercion() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v = ("foo", "bar");
let v = ("foo", "bar"); let ob = v.to_object(py);
let ob = v.to_object(py); let seq = ob.cast_as::<PySequence>(py).unwrap();
let seq = ob.cast_as::<PySequence>(py).unwrap(); assert!(seq.tuple().is_ok());
assert!(seq.tuple().is_ok()); });
} }
#[test] #[test]
fn test_lists_coerce_to_tuples() { fn test_lists_coerce_to_tuples() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v = vec!["foo", "bar"];
let v = vec!["foo", "bar"]; let ob = v.to_object(py);
let ob = v.to_object(py); let seq = ob.cast_as::<PySequence>(py).unwrap();
let seq = ob.cast_as::<PySequence>(py).unwrap(); assert!(seq.tuple().is_ok());
assert!(seq.tuple().is_ok()); });
} }
#[test] #[test]
fn test_extract_tuple_to_vec() { fn test_extract_tuple_to_vec() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v: Vec<i32> = py.eval("(1, 2)", None, None).unwrap().extract().unwrap();
let v: Vec<i32> = py.eval("(1, 2)", None, None).unwrap().extract().unwrap(); assert!(v == [1, 2]);
assert!(v == [1, 2]); });
} }
#[test] #[test]
fn test_extract_range_to_vec() { fn test_extract_range_to_vec() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v: Vec<i32> = py
let v: Vec<i32> = py .eval("range(1, 5)", None, None)
.eval("range(1, 5)", None, None) .unwrap()
.unwrap() .extract()
.extract() .unwrap();
.unwrap(); assert!(v == [1, 2, 3, 4]);
assert!(v == [1, 2, 3, 4]); });
} }
#[test] #[test]
fn test_extract_bytearray_to_vec() { fn test_extract_bytearray_to_vec() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v: Vec<u8> = py
let v: Vec<u8> = py .eval("bytearray(b'abc')", None, None)
.eval("bytearray(b'abc')", None, None) .unwrap()
.unwrap() .extract()
.extract() .unwrap();
.unwrap(); assert!(v == b"abc");
assert!(v == b"abc"); });
} }
#[test] #[test]
fn test_seq_try_from_unchecked() { fn test_seq_try_from_unchecked() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let v = vec!["foo", "bar"];
let v = vec!["foo", "bar"]; let ob = v.to_object(py);
let ob = v.to_object(py); let seq = ob.cast_as::<PySequence>(py).unwrap();
let seq = ob.cast_as::<PySequence>(py).unwrap(); let type_ptr = seq.as_ref();
let type_ptr = seq.as_ref(); let seq_from = unsafe { <PySequence as PyTryFrom>::try_from_unchecked(type_ptr) };
let seq_from = unsafe { <PySequence as PyTryFrom>::try_from_unchecked(type_ptr) }; assert!(seq_from.list().is_ok());
assert!(seq_from.list().is_ok()); });
} }
#[test] #[test]
fn test_is_empty() { fn test_is_empty() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let list = vec![1].to_object(py);
let list = vec![1].to_object(py); let seq = list.cast_as::<PySequence>(py).unwrap();
let seq = list.cast_as::<PySequence>(py).unwrap(); assert!(!seq.is_empty().unwrap());
assert!(!seq.is_empty().unwrap()); let vec: Vec<u32> = Vec::new();
let vec: Vec<u32> = Vec::new(); let empty_list = vec.to_object(py);
let empty_list = vec.to_object(py); let empty_seq = empty_list.cast_as::<PySequence>(py).unwrap();
let empty_seq = empty_list.cast_as::<PySequence>(py).unwrap(); assert!(empty_seq.is_empty().unwrap());
assert!(empty_seq.is_empty().unwrap()); });
} }
} }

View File

@ -383,24 +383,22 @@ mod hashbrown_hashset_conversion {
#[test] #[test]
fn test_extract_hashbrown_hashset() { fn test_extract_hashbrown_hashset() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let set = PySet::new(py, &[1, 2, 3, 4, 5]).unwrap();
let hash_set: hashbrown::HashSet<usize> = set.extract().unwrap();
let set = PySet::new(py, &[1, 2, 3, 4, 5]).unwrap(); assert_eq!(hash_set, [1, 2, 3, 4, 5].iter().copied().collect());
let hash_set: hashbrown::HashSet<usize> = set.extract().unwrap(); });
assert_eq!(hash_set, [1, 2, 3, 4, 5].iter().copied().collect());
} }
#[test] #[test]
fn test_hashbrown_hashset_into_py() { fn test_hashbrown_hashset_into_py() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let hs: hashbrown::HashSet<u64> = [1, 2, 3, 4, 5].iter().cloned().collect();
let hs: hashbrown::HashSet<u64> = [1, 2, 3, 4, 5].iter().cloned().collect(); let hso: PyObject = hs.clone().into_py(py);
let hso: PyObject = hs.clone().into_py(py); assert_eq!(hs, hso.extract(py).unwrap());
});
assert_eq!(hs, hso.extract(py).unwrap());
} }
} }
@ -412,205 +410,196 @@ mod tests {
#[test] #[test]
fn test_set_new() { fn test_set_new() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let set = PySet::new(py, &[1]).unwrap();
assert_eq!(1, set.len());
let set = PySet::new(py, &[1]).unwrap(); let v = vec![1];
assert_eq!(1, set.len()); assert!(PySet::new(py, &[v]).is_err());
});
let v = vec![1];
assert!(PySet::new(py, &[v]).is_err());
} }
#[test] #[test]
fn test_set_empty() { fn test_set_empty() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let set = PySet::empty(py).unwrap();
let set = PySet::empty(py).unwrap(); assert_eq!(0, set.len());
assert_eq!(0, set.len()); });
} }
#[test] #[test]
fn test_set_len() { fn test_set_len() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let mut v = HashSet::new();
let ob = v.to_object(py);
let mut v = HashSet::new(); let set = <PySet as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let ob = v.to_object(py); assert_eq!(0, set.len());
let set = <PySet as PyTryFrom>::try_from(ob.as_ref(py)).unwrap(); v.insert(7);
assert_eq!(0, set.len()); let ob = v.to_object(py);
v.insert(7); let set2 = <PySet as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let ob = v.to_object(py); assert_eq!(1, set2.len());
let set2 = <PySet as PyTryFrom>::try_from(ob.as_ref(py)).unwrap(); });
assert_eq!(1, set2.len());
} }
#[test] #[test]
fn test_set_clear() { fn test_set_clear() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let set = PySet::new(py, &[1]).unwrap();
let set = PySet::new(py, &[1]).unwrap(); assert_eq!(1, set.len());
assert_eq!(1, set.len()); set.clear();
set.clear(); assert_eq!(0, set.len());
assert_eq!(0, set.len()); });
} }
#[test] #[test]
fn test_set_contains() { fn test_set_contains() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let set = PySet::new(py, &[1]).unwrap();
let set = PySet::new(py, &[1]).unwrap(); assert!(set.contains(1).unwrap());
assert!(set.contains(1).unwrap()); });
} }
#[test] #[test]
fn test_set_discard() { fn test_set_discard() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let set = PySet::new(py, &[1]).unwrap();
let set = PySet::new(py, &[1]).unwrap(); set.discard(2);
set.discard(2); assert_eq!(1, set.len());
assert_eq!(1, set.len()); set.discard(1);
set.discard(1); assert_eq!(0, set.len());
assert_eq!(0, set.len()); });
} }
#[test] #[test]
fn test_set_add() { fn test_set_add() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let set = PySet::new(py, &[1, 2]).unwrap();
let set = PySet::new(py, &[1, 2]).unwrap(); set.add(1).unwrap(); // Add a dupliated element
set.add(1).unwrap(); // Add a dupliated element assert!(set.contains(1).unwrap());
assert!(set.contains(1).unwrap()); });
} }
#[test] #[test]
fn test_set_pop() { fn test_set_pop() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let set = PySet::new(py, &[1]).unwrap();
let set = PySet::new(py, &[1]).unwrap(); let val = set.pop();
let val = set.pop(); assert!(val.is_some());
assert!(val.is_some()); let val2 = set.pop();
let val2 = set.pop(); assert!(val2.is_none());
assert!(val2.is_none()); assert!(py
assert!(py .eval("print('Exception state should not be set.')", None, None)
.eval("print('Exception state should not be set.')", None, None) .is_ok());
.is_ok()); });
} }
#[test] #[test]
fn test_set_iter() { fn test_set_iter() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let set = PySet::new(py, &[1]).unwrap();
let set = PySet::new(py, &[1]).unwrap(); // iter method
for el in set.iter() {
assert_eq!(1i32, el.extract().unwrap());
}
// iter method // intoiterator iteration
for el in set.iter() { for el in set {
assert_eq!(1i32, el.extract().unwrap()); assert_eq!(1i32, el.extract().unwrap());
} }
});
// intoiterator iteration
for el in set {
assert_eq!(1i32, el.extract().unwrap());
}
} }
#[test] #[test]
fn test_set_iter_size_hint() { fn test_set_iter_size_hint() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let set = PySet::new(py, &[1]).unwrap();
let set = PySet::new(py, &[1]).unwrap(); let mut iter = set.iter();
let mut iter = set.iter(); if cfg!(Py_LIMITED_API) {
assert_eq!(iter.size_hint(), (0, None));
if cfg!(Py_LIMITED_API) { } else {
assert_eq!(iter.size_hint(), (0, None)); assert_eq!(iter.size_hint(), (1, Some(1)));
} else { iter.next();
assert_eq!(iter.size_hint(), (1, Some(1))); assert_eq!(iter.size_hint(), (0, Some(0)));
iter.next(); }
assert_eq!(iter.size_hint(), (0, Some(0))); });
}
} }
#[test] #[test]
fn test_frozenset_new_and_len() { fn test_frozenset_new_and_len() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let set = PyFrozenSet::new(py, &[1]).unwrap();
assert_eq!(1, set.len());
let set = PyFrozenSet::new(py, &[1]).unwrap(); let v = vec![1];
assert_eq!(1, set.len()); assert!(PyFrozenSet::new(py, &[v]).is_err());
});
let v = vec![1];
assert!(PyFrozenSet::new(py, &[v]).is_err());
} }
#[test] #[test]
fn test_frozenset_empty() { fn test_frozenset_empty() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let set = PyFrozenSet::empty(py).unwrap();
let set = PyFrozenSet::empty(py).unwrap(); assert_eq!(0, set.len());
assert_eq!(0, set.len()); });
} }
#[test] #[test]
fn test_frozenset_contains() { fn test_frozenset_contains() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let set = PyFrozenSet::new(py, &[1]).unwrap();
let set = PyFrozenSet::new(py, &[1]).unwrap(); assert!(set.contains(1).unwrap());
assert!(set.contains(1).unwrap()); });
} }
#[test] #[test]
fn test_frozenset_iter() { fn test_frozenset_iter() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let set = PyFrozenSet::new(py, &[1]).unwrap();
let set = PyFrozenSet::new(py, &[1]).unwrap(); // iter method
for el in set.iter() {
assert_eq!(1i32, el.extract::<i32>().unwrap());
}
// iter method // intoiterator iteration
for el in set.iter() { for el in set {
assert_eq!(1i32, el.extract::<i32>().unwrap()); assert_eq!(1i32, el.extract::<i32>().unwrap());
} }
});
// intoiterator iteration
for el in set {
assert_eq!(1i32, el.extract::<i32>().unwrap());
}
} }
#[test] #[test]
fn test_extract_hashset() { fn test_extract_hashset() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let set = PySet::new(py, &[1, 2, 3, 4, 5]).unwrap();
let hash_set: HashSet<usize> = set.extract().unwrap();
let set = PySet::new(py, &[1, 2, 3, 4, 5]).unwrap(); assert_eq!(hash_set, [1, 2, 3, 4, 5].iter().copied().collect());
let hash_set: HashSet<usize> = set.extract().unwrap(); });
assert_eq!(hash_set, [1, 2, 3, 4, 5].iter().copied().collect());
} }
#[test] #[test]
fn test_extract_btreeset() { fn test_extract_btreeset() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let set = PySet::new(py, &[1, 2, 3, 4, 5]).unwrap();
let hash_set: BTreeSet<usize> = set.extract().unwrap();
let set = PySet::new(py, &[1, 2, 3, 4, 5]).unwrap(); assert_eq!(hash_set, [1, 2, 3, 4, 5].iter().copied().collect());
let hash_set: BTreeSet<usize> = set.extract().unwrap(); });
assert_eq!(hash_set, [1, 2, 3, 4, 5].iter().copied().collect());
} }
#[test] #[test]
fn test_set_into_py() { fn test_set_into_py() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let bt: BTreeSet<u64> = [1, 2, 3, 4, 5].iter().cloned().collect();
let hs: HashSet<u64> = [1, 2, 3, 4, 5].iter().cloned().collect();
let bt: BTreeSet<u64> = [1, 2, 3, 4, 5].iter().cloned().collect(); let bto: PyObject = bt.clone().into_py(py);
let hs: HashSet<u64> = [1, 2, 3, 4, 5].iter().cloned().collect(); let hso: PyObject = hs.clone().into_py(py);
let bto: PyObject = bt.clone().into_py(py); assert_eq!(bt, bto.extract(py).unwrap());
let hso: PyObject = hs.clone().into_py(py); assert_eq!(hs, hso.extract(py).unwrap());
});
assert_eq!(bt, bto.extract(py).unwrap());
assert_eq!(hs, hso.extract(py).unwrap());
} }
} }

View File

@ -322,77 +322,77 @@ mod tests {
#[test] #[test]
fn test_new() { fn test_new() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let ob = PyTuple::new(py, &[1, 2, 3]);
let ob = PyTuple::new(py, &[1, 2, 3]); assert_eq!(3, ob.len());
assert_eq!(3, ob.len()); let ob: &PyAny = ob.into();
let ob: &PyAny = ob.into(); assert_eq!((1, 2, 3), ob.extract().unwrap());
assert_eq!((1, 2, 3), ob.extract().unwrap());
let mut map = HashSet::new(); let mut map = HashSet::new();
map.insert(1); map.insert(1);
map.insert(2); map.insert(2);
PyTuple::new(py, &map); PyTuple::new(py, &map);
});
} }
#[test] #[test]
fn test_len() { fn test_len() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let ob = (1, 2, 3).to_object(py);
let ob = (1, 2, 3).to_object(py); let tuple = <PyTuple as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let tuple = <PyTuple as PyTryFrom>::try_from(ob.as_ref(py)).unwrap(); assert_eq!(3, tuple.len());
assert_eq!(3, tuple.len()); let ob: &PyAny = tuple.into();
let ob: &PyAny = tuple.into(); assert_eq!((1, 2, 3), ob.extract().unwrap());
assert_eq!((1, 2, 3), ob.extract().unwrap()); });
} }
#[test] #[test]
fn test_iter() { fn test_iter() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let ob = (1, 2, 3).to_object(py);
let ob = (1, 2, 3).to_object(py); let tuple = <PyTuple as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let tuple = <PyTuple as PyTryFrom>::try_from(ob.as_ref(py)).unwrap(); assert_eq!(3, tuple.len());
assert_eq!(3, tuple.len()); let mut iter = tuple.iter();
let mut iter = tuple.iter();
assert_eq!(iter.size_hint(), (3, Some(3))); assert_eq!(iter.size_hint(), (3, Some(3)));
assert_eq!(1, iter.next().unwrap().extract().unwrap()); assert_eq!(1, iter.next().unwrap().extract().unwrap());
assert_eq!(iter.size_hint(), (2, Some(2))); assert_eq!(iter.size_hint(), (2, Some(2)));
assert_eq!(2, iter.next().unwrap().extract().unwrap()); assert_eq!(2, iter.next().unwrap().extract().unwrap());
assert_eq!(iter.size_hint(), (1, Some(1))); assert_eq!(iter.size_hint(), (1, Some(1)));
assert_eq!(3, iter.next().unwrap().extract().unwrap()); assert_eq!(3, iter.next().unwrap().extract().unwrap());
assert_eq!(iter.size_hint(), (0, Some(0))); assert_eq!(iter.size_hint(), (0, Some(0)));
});
} }
#[test] #[test]
fn test_into_iter() { fn test_into_iter() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let ob = (1, 2, 3).to_object(py);
let ob = (1, 2, 3).to_object(py); let tuple = <PyTuple as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let tuple = <PyTuple as PyTryFrom>::try_from(ob.as_ref(py)).unwrap(); assert_eq!(3, tuple.len());
assert_eq!(3, tuple.len());
for (i, item) in tuple.iter().enumerate() { for (i, item) in tuple.iter().enumerate() {
assert_eq!(i + 1, item.extract().unwrap()); assert_eq!(i + 1, item.extract().unwrap());
} }
});
} }
#[test] #[test]
#[cfg(not(Py_LIMITED_API))] #[cfg(not(Py_LIMITED_API))]
fn test_as_slice() { fn test_as_slice() {
let gil = Python::acquire_gil(); Python::with_gil(|py| {
let py = gil.python(); let ob = (1, 2, 3).to_object(py);
let ob = (1, 2, 3).to_object(py); let tuple = <PyTuple as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let tuple = <PyTuple as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
let slice = tuple.as_slice(); let slice = tuple.as_slice();
assert_eq!(3, slice.len()); assert_eq!(3, slice.len());
assert_eq!(1, slice[0].extract().unwrap()); assert_eq!(1, slice[0].extract().unwrap());
assert_eq!(2, slice[1].extract().unwrap()); assert_eq!(2, slice[1].extract().unwrap());
assert_eq!(3, slice[2].extract().unwrap()); assert_eq!(3, slice[2].extract().unwrap());
});
} }
#[test] #[test]