From f55a9c8ab01dac0101814097b502fa319386dbf8 Mon Sep 17 00:00:00 2001 From: mejrs Date: Thu, 12 Aug 2021 02:47:41 +0200 Subject: [PATCH 1/3] tests: switch to python_with_gil --- src/buffer.rs | 94 +++---- src/conversion.rs | 42 +-- src/err/mod.rs | 68 ++--- src/exceptions.rs | 198 +++++++------- src/instance.rs | 25 +- src/marshal.rs | 25 +- src/python.rs | 114 ++++---- src/types/any.rs | 83 +++--- src/types/boolobject.rs | 24 +- src/types/bytearray.rs | 155 +++++------ src/types/bytes.rs | 65 +++-- src/types/dict.rs | 586 ++++++++++++++++++++-------------------- src/types/floatob.rs | 15 +- src/types/iterator.rs | 125 ++++----- src/types/list.rs | 295 ++++++++++---------- src/types/num.rs | 69 +++-- src/types/sequence.rs | 441 +++++++++++++++--------------- src/types/set.rs | 265 +++++++++--------- src/types/tuple.rs | 94 +++---- 19 files changed, 1377 insertions(+), 1406 deletions(-) diff --git a/src/buffer.rs b/src/buffer.rs index fbded572..5f98f794 100644 --- a/src/buffer.rs +++ b/src/buffer.rs @@ -663,64 +663,64 @@ mod tests { #[test] fn test_bytes_buffer() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let bytes = py.eval("b'abcde'", None, None).unwrap(); - let buffer = PyBuffer::get(bytes).unwrap(); - assert_eq!(buffer.dimensions(), 1); - assert_eq!(buffer.item_count(), 5); - assert_eq!(buffer.format().to_str().unwrap(), "B"); - assert_eq!(buffer.shape(), [5]); - // single-dimensional buffer is always contiguous - assert!(buffer.is_c_contiguous()); - assert!(buffer.is_fortran_contiguous()); + Python::with_gil(|py| { + let bytes = py.eval("b'abcde'", None, None).unwrap(); + let buffer = PyBuffer::get(bytes).unwrap(); + assert_eq!(buffer.dimensions(), 1); + assert_eq!(buffer.item_count(), 5); + assert_eq!(buffer.format().to_str().unwrap(), "B"); + assert_eq!(buffer.shape(), [5]); + // single-dimensional buffer is always contiguous + assert!(buffer.is_c_contiguous()); + assert!(buffer.is_fortran_contiguous()); - let slice = buffer.as_slice(py).unwrap(); - assert_eq!(slice.len(), 5); - assert_eq!(slice[0].get(), b'a'); - assert_eq!(slice[2].get(), b'c'); + let slice = buffer.as_slice(py).unwrap(); + assert_eq!(slice.len(), 5); + assert_eq!(slice[0].get(), b'a'); + assert_eq!(slice[2].get(), b'c'); - assert!(buffer.copy_to_slice(py, &mut [0u8]).is_err()); - let mut arr = [0; 5]; - buffer.copy_to_slice(py, &mut arr).unwrap(); - assert_eq!(arr, b"abcde" as &[u8]); + assert!(buffer.copy_to_slice(py, &mut [0u8]).is_err()); + let mut arr = [0; 5]; + buffer.copy_to_slice(py, &mut arr).unwrap(); + assert_eq!(arr, b"abcde" as &[u8]); - assert!(buffer.copy_from_slice(py, &[0u8; 5]).is_err()); - assert_eq!(buffer.to_vec(py).unwrap(), b"abcde"); + assert!(buffer.copy_from_slice(py, &[0u8; 5]).is_err()); + 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 #[test] fn test_array_buffer() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let array = py - .import("array") - .unwrap() - .call_method("array", ("f", (1.0, 1.5, 2.0, 2.5)), None) - .unwrap(); - let buffer = PyBuffer::get(array).unwrap(); - assert_eq!(buffer.dimensions(), 1); - assert_eq!(buffer.item_count(), 4); - assert_eq!(buffer.format().to_str().unwrap(), "f"); - assert_eq!(buffer.shape(), [4]); + Python::with_gil(|py| { + let array = py + .import("array") + .unwrap() + .call_method("array", ("f", (1.0, 1.5, 2.0, 2.5)), None) + .unwrap(); + let buffer = PyBuffer::get(array).unwrap(); + assert_eq!(buffer.dimensions(), 1); + assert_eq!(buffer.item_count(), 4); + assert_eq!(buffer.format().to_str().unwrap(), "f"); + assert_eq!(buffer.shape(), [4]); - let slice = buffer.as_slice(py).unwrap(); - assert_eq!(slice.len(), 4); - assert_eq!(slice[0].get(), 1.0); - assert_eq!(slice[3].get(), 2.5); + let slice = buffer.as_slice(py).unwrap(); + assert_eq!(slice.len(), 4); + assert_eq!(slice[0].get(), 1.0); + assert_eq!(slice[3].get(), 2.5); - let mut_slice = buffer.as_mut_slice(py).unwrap(); - assert_eq!(mut_slice.len(), 4); - assert_eq!(mut_slice[0].get(), 1.0); - mut_slice[3].set(2.75); - assert_eq!(slice[3].get(), 2.75); + let mut_slice = buffer.as_mut_slice(py).unwrap(); + assert_eq!(mut_slice.len(), 4); + assert_eq!(mut_slice[0].get(), 1.0); + mut_slice[3].set(2.75); + assert_eq!(slice[3].get(), 2.75); - buffer - .copy_from_slice(py, &[10.0f32, 11.0, 12.0, 13.0]) - .unwrap(); - assert_eq!(slice[2].get(), 12.0); + buffer + .copy_from_slice(py, &[10.0f32, 11.0, 12.0, 13.0]) + .unwrap(); + 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]); + }); } } diff --git a/src/conversion.rs b/src/conversion.rs index 4d2d395e..7eba64df 100644 --- a/src/conversion.rs +++ b/src/conversion.rs @@ -551,38 +551,38 @@ mod tests { #[test] fn test_try_from() { - let gil = Python::acquire_gil(); - let py = gil.python(); - 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(); + Python::with_gil(|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(); - assert!(PyList::try_from(list).is_ok()); - assert!(PyDict::try_from(dict).is_ok()); + assert!(PyList::try_from(list).is_ok()); + assert!(PyDict::try_from(dict).is_ok()); - assert!(PyAny::try_from(list).is_ok()); - assert!(PyAny::try_from(dict).is_ok()); + assert!(PyAny::try_from(list).is_ok()); + assert!(PyAny::try_from(dict).is_ok()); + }); } #[test] fn test_try_from_exact() { - let gil = Python::acquire_gil(); - let py = gil.python(); - 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(); + Python::with_gil(|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(); - assert!(PyList::try_from_exact(list).is_ok()); - assert!(PyDict::try_from_exact(dict).is_ok()); + assert!(PyList::try_from_exact(list).is_ok()); + assert!(PyDict::try_from_exact(dict).is_ok()); - assert!(PyAny::try_from_exact(list).is_err()); - assert!(PyAny::try_from_exact(dict).is_err()); + assert!(PyAny::try_from_exact(list).is_err()); + assert!(PyAny::try_from_exact(dict).is_err()); + }); } #[test] fn test_try_from_unchecked() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let list = PyList::new(py, &[1, 2, 3]); - let val = unsafe { ::try_from_unchecked(list.as_ref()) }; - assert_eq!(list, val); + Python::with_gil(|py| { + let list = PyList::new(py, &[1, 2, 3]); + let val = unsafe { ::try_from_unchecked(list.as_ref()) }; + assert_eq!(list, val); + }); } } diff --git a/src/err/mod.rs b/src/err/mod.rs index fe5fd1c7..80442881 100644 --- a/src/err/mod.rs +++ b/src/err/mod.rs @@ -602,14 +602,14 @@ mod tests { fn fetching_panic_exception_resumes_unwind() { use crate::panic::PanicException; - let gil = Python::acquire_gil(); - let py = gil.python(); - let err: PyErr = PanicException::new_err("new panic"); - err.restore(py); - assert!(PyErr::occurred(py)); + Python::with_gil(|py| { + let err: PyErr = PanicException::new_err("new panic"); + err.restore(py); + assert!(PyErr::occurred(py)); - // should resume unwind - let _ = PyErr::fetch(py); + // should resume unwind + let _ = PyErr::fetch(py); + }); } #[test] @@ -621,42 +621,42 @@ mod tests { // traceback: Some("); - if py.version_info() >= (3, 7) { - assert_eq!(fields.next().unwrap(), "value: Exception('banana')"); - } else { - // Python 3.6 and below formats the repr differently - assert_eq!(fields.next().unwrap(), ("value: Exception('banana',)")); - } + assert_eq!(fields.next().unwrap(), "type: "); + if py.version_info() >= (3, 7) { + assert_eq!(fields.next().unwrap(), "value: Exception('banana')"); + } else { + // Python 3.6 and below formats the repr differently + assert_eq!(fields.next().unwrap(), ("value: Exception('banana',)")); + } - let traceback = fields.next().unwrap(); - assert!(traceback.starts_with("traceback: Some()")); + let traceback = fields.next().unwrap(); + assert!(traceback.starts_with("traceback: Some()")); - assert!(fields.next().is_none()); + assert!(fields.next().is_none()); + }); } #[test] fn err_display() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let err = py - .run("raise Exception('banana')", None, None) - .expect_err("raising should have given us an error"); - assert_eq!(err.to_string(), "Exception: banana"); + Python::with_gil(|py| { + let err = py + .run("raise Exception('banana')", None, None) + .expect_err("raising should have given us an error"); + assert_eq!(err.to_string(), "Exception: banana"); + }); } #[test] diff --git a/src/exceptions.rs b/src/exceptions.rs index c1cb5832..de8507dd 100644 --- a/src/exceptions.rs +++ b/src/exceptions.rs @@ -342,141 +342,139 @@ mod tests { #[test] fn test_check_exception() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + 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 socket = py - .import("socket") - .map_err(|e| e.print(py)) - .expect("could not import socket"); + let d = PyDict::new(py); + d.set_item("socket", socket) + .map_err(|e| e.print(py)) + .expect("could not setitem"); - let d = PyDict::new(py); - d.set_item("socket", socket) - .map_err(|e| e.print(py)) - .expect("could not setitem"); + d.set_item("exc", err) + .map_err(|e| e.print(py)) + .expect("could not setitem"); - d.set_item("exc", err) - .map_err(|e| e.print(py)) - .expect("could not setitem"); - - py.run("assert isinstance(exc, socket.gaierror)", None, Some(d)) - .map_err(|e| e.print(py)) - .expect("assertion failed"); + py.run("assert isinstance(exc, socket.gaierror)", None, Some(d)) + .map_err(|e| e.print(py)) + .expect("assertion failed"); + }); } #[test] fn test_check_exception_nested() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + 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 email = py - .import("email") - .map_err(|e| e.print(py)) - .expect("could not import email"); + let d = PyDict::new(py); + d.set_item("email", email) + .map_err(|e| e.print(py)) + .expect("could not setitem"); + d.set_item("exc", err) + .map_err(|e| e.print(py)) + .expect("could not setitem"); - let d = PyDict::new(py); - d.set_item("email", email) + py.run( + "assert isinstance(exc, email.errors.MessageError)", + None, + Some(d), + ) .map_err(|e| e.print(py)) - .expect("could not setitem"); - 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"); + .expect("assertion failed"); + }); } #[test] fn custom_exception() { create_exception!(mymodule, CustomError, PyException); - let gil = Python::acquire_gil(); - let py = gil.python(); - let error_type = py.get_type::(); - let ctx = [("CustomError", error_type)].into_py_dict(py); - let type_description: String = py - .eval("str(CustomError)", None, Some(ctx)) - .unwrap() - .extract() + Python::with_gil(|py| { + let error_type = py.get_type::(); + let ctx = [("CustomError", error_type)].into_py_dict(py); + let type_description: String = py + .eval("str(CustomError)", None, Some(ctx)) + .unwrap() + .extract() + .unwrap(); + assert_eq!(type_description, ""); + py.run( + "assert CustomError('oops').args == ('oops',)", + None, + Some(ctx), + ) .unwrap(); - assert_eq!(type_description, ""); - py.run( - "assert CustomError('oops').args == ('oops',)", - None, - Some(ctx), - ) - .unwrap(); + }); } #[test] fn native_exception_debug() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let exc = py - .run("raise Exception('banana')", None, None) - .expect_err("raising should have given us an error") - .into_instance(py) - .into_ref(py); - assert_eq!( - format!("{:?}", exc), - exc.repr().unwrap().extract::().unwrap() - ); + Python::with_gil(|py| { + let exc = py + .run("raise Exception('banana')", None, None) + .expect_err("raising should have given us an error") + .into_instance(py) + .into_ref(py); + assert_eq!( + format!("{:?}", exc), + exc.repr().unwrap().extract::().unwrap() + ); + }); } #[test] fn native_exception_display() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let exc = py - .run("raise Exception('banana')", None, None) - .expect_err("raising should have given us an error") - .into_instance(py) - .into_ref(py); - assert_eq!( - exc.to_string(), - exc.str().unwrap().extract::().unwrap() - ); + Python::with_gil(|py| { + let exc = py + .run("raise Exception('banana')", None, None) + .expect_err("raising should have given us an error") + .into_instance(py) + .into_ref(py); + assert_eq!( + exc.to_string(), + exc.str().unwrap().extract::().unwrap() + ); + }); } #[test] fn native_exception_chain() { use std::error::Error; - let gil = Python::acquire_gil(); - let py = gil.python(); - let exc = py - .run( - "raise Exception('banana') from TypeError('peach')", - None, - None, - ) - .expect_err("raising should have given us an error") - .into_instance(py) - .into_ref(py); + Python::with_gil(|py| { + let exc = py + .run( + "raise Exception('banana') from TypeError('peach')", + None, + None, + ) + .expect_err("raising should have given us an error") + .into_instance(py) + .into_ref(py); - if py.version_info() >= (3, 7) { - assert_eq!(format!("{:?}", exc), "Exception('banana')"); - } else { - assert_eq!(format!("{:?}", exc), "Exception('banana',)"); - } + if py.version_info() >= (3, 7) { + assert_eq!(format!("{:?}", exc), "Exception('banana')"); + } else { + 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) { - assert_eq!(format!("{:?}", source), "TypeError('peach')"); - } else { - assert_eq!(format!("{:?}", source), "TypeError('peach',)"); - } + if py.version_info() >= (3, 7) { + assert_eq!(format!("{:?}", source), "TypeError('peach')"); + } else { + assert_eq!(format!("{:?}", source), "TypeError('peach',)"); + } - let source_source = source.source(); - assert!(source_source.is_none(), "source_source should be None"); + let source_source = source.source(); + assert!(source_source.is_none(), "source_source should be None"); + }); } #[test] diff --git a/src/instance.rs b/src/instance.rs index 18968fcb..97d41f89 100644 --- a/src/instance.rs +++ b/src/instance.rs @@ -867,25 +867,24 @@ mod tests { #[test] fn test_call_for_non_existing_method() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let obj: PyObject = PyDict::new(py).into(); - assert!(obj.call_method0(py, "asdf").is_err()); - assert!(obj - .call_method(py, "nonexistent_method", (1,), None) - .is_err()); - assert!(obj.call_method0(py, "nonexistent_method").is_err()); - assert!(obj.call_method1(py, "nonexistent_method", (1,)).is_err()); + Python::with_gil(|py| { + let obj: PyObject = PyDict::new(py).into(); + assert!(obj.call_method0(py, "asdf").is_err()); + assert!(obj + .call_method(py, "nonexistent_method", (1,), None) + .is_err()); + assert!(obj.call_method0(py, "nonexistent_method").is_err()); + assert!(obj.call_method1(py, "nonexistent_method", (1,)).is_err()); + }); } #[test] fn py_from_dict() { - let dict: Py = { - let gil = Python::acquire_gil(); - let py = gil.python(); + let dict: Py = Python::with_gil(|py| -> Py { let native = PyDict::new(py); Py::from(native) - }; + }); + assert_eq!(unsafe { ffi::Py_REFCNT(dict.as_ptr()) }, 1); } diff --git a/src/marshal.rs b/src/marshal.rs index 6305eab4..fd1cc0a8 100644 --- a/src/marshal.rs +++ b/src/marshal.rs @@ -56,21 +56,20 @@ mod tests { use crate::types::PyDict; #[test] - fn marhshal_roundtrip() { - let gil = Python::acquire_gil(); - let py = gil.python(); + fn marshal_roundtrip() { + Python::with_gil(|py| { + 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); - dict.set_item("aap", "noot").unwrap(); - dict.set_item("mies", "wim").unwrap(); - dict.set_item("zus", "jet").unwrap(); + let bytes = dumps(py, dict, VERSION) + .expect("marshalling failed") + .as_bytes(); + let deserialized = loads(py, bytes).expect("unmarshalling failed"); - let bytes = dumps(py, dict, VERSION) - .expect("marshalling failed") - .as_bytes(); - let deserialzed = loads(py, bytes).expect("unmarshalling failed"); - - assert!(equal(py, dict, deserialzed)); + assert!(equal(py, dict, deserialized)); + }); } fn equal(_py: Python, a: &impl AsPyPointer, b: &impl AsPyPointer) -> bool { diff --git a/src/python.rs b/src/python.rs index b6757820..e546e21e 100644 --- a/src/python.rs +++ b/src/python.rs @@ -709,64 +709,62 @@ mod tests { #[test] fn test_eval() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + // 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 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); - 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 - let v: i32 = py - .eval("foo + 29", Some(d), None) - .unwrap() - .extract() - .unwrap(); - assert_eq!(v, 42); + // Inject our own local namespace + let v: i32 = py + .eval("foo + 29", None, Some(d)) + .unwrap() + .extract() + .unwrap(); + assert_eq!(v, 42); - // Inject our own local namespace - let v: i32 = py - .eval("foo + 29", None, Some(d)) - .unwrap() - .extract() - .unwrap(); - assert_eq!(v, 42); - - // 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); + // 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] fn test_allow_threads_panics_safely() { - let gil = Python::acquire_gil(); - let py = gil.python(); - - let result = std::panic::catch_unwind(|| unsafe { - let py = Python::assume_gil_acquired(); - py.allow_threads(|| { - panic!("There was a panic!"); + Python::with_gil(|py| { + let result = std::panic::catch_unwind(|| unsafe { + let py = Python::assume_gil_acquired(); + 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::>().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::>().unwrap(), vec![1, 2, 3, 4]); } #[test] @@ -805,4 +803,24 @@ mod tests { assert!(PythonVersionInfo::from_str("3.5.2a1+") < (3, 6)); assert!(PythonVersionInfo::from_str("3.5.2a1+") > (3, 4)); } + + #[test] + 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); + } } diff --git a/src/types/any.rs b/src/types/any.rs index a4e1dba7..d014f87c 100644 --- a/src/types/any.rs +++ b/src/types/any.rs @@ -697,23 +697,23 @@ mod tests { #[test] fn test_call_for_non_existing_method() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let a = py.eval("42", None, None).unwrap(); - a.call_method0("__str__").unwrap(); // ok - assert!(a.call_method("nonexistent_method", (1,), None).is_err()); - assert!(a.call_method0("nonexistent_method").is_err()); - assert!(a.call_method1("nonexistent_method", (1,)).is_err()); + Python::with_gil(|py| { + let a = py.eval("42", None, None).unwrap(); + a.call_method0("__str__").unwrap(); // ok + assert!(a.call_method("nonexistent_method", (1,), None).is_err()); + assert!(a.call_method0("nonexistent_method").is_err()); + assert!(a.call_method1("nonexistent_method", (1,)).is_err()); + }); } #[test] fn test_call_with_kwargs() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let list = vec![3, 6, 5, 4, 7].to_object(py); - let dict = vec![("reverse", true)].into_py_dict(py); - list.call_method(py, "sort", (), Some(dict)).unwrap(); - assert_eq!(list.extract::>(py).unwrap(), vec![7, 6, 5, 4, 3]); + Python::with_gil(|py| { + let list = vec![3, 6, 5, 4, 7].to_object(py); + let dict = vec![("reverse", true)].into_py_dict(py); + list.call_method(py, "sort", (), Some(dict)).unwrap(); + assert_eq!(list.extract::>(py).unwrap(), vec![7, 6, 5, 4, 3]); + }); } #[test] @@ -742,47 +742,46 @@ mod tests { #[test] fn test_type() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let obj = py.eval("42", None, None).unwrap(); - assert_eq!(obj.get_type().as_type_ptr(), obj.get_type_ptr()) + Python::with_gil(|py| { + let obj = py.eval("42", None, None).unwrap(); + assert_eq!(obj.get_type().as_type_ptr(), obj.get_type_ptr()); + }); } #[test] fn test_dir() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let obj = py.eval("42", None, None).unwrap(); - let dir = py - .eval("dir(42)", None, None) - .unwrap() - .downcast::() - .unwrap(); - let a = obj - .dir() - .into_iter() - .map(|x| x.extract::().unwrap()); - let b = dir.into_iter().map(|x| x.extract::().unwrap()); - assert!(a.eq(b)); + Python::with_gil(|py| { + let obj = py.eval("42", None, None).unwrap(); + let dir = py + .eval("dir(42)", None, None) + .unwrap() + .downcast::() + .unwrap(); + let a = obj + .dir() + .into_iter() + .map(|x| x.extract::().unwrap()); + let b = dir.into_iter().map(|x| x.extract::().unwrap()); + assert!(a.eq(b)); + }); } #[test] fn test_nan_eq() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let nan = py.eval("float('nan')", None, None).unwrap(); - assert!(nan.compare(nan).is_err()); + Python::with_gil(|py| { + let nan = py.eval("float('nan')", None, None).unwrap(); + assert!(nan.compare(nan).is_err()); + }); } #[test] fn test_any_isinstance() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let x = 5.to_object(py).into_ref(py); + assert!(x.is_instance::().unwrap()); - let x = 5.to_object(py).into_ref(py); - assert!(x.is_instance::().unwrap()); - - let l = vec![x, x].to_object(py).into_ref(py); - assert!(l.is_instance::().unwrap()); + let l = vec![x, x].to_object(py).into_ref(py); + assert!(l.is_instance::().unwrap()); + }); } } diff --git a/src/types/boolobject.rs b/src/types/boolobject.rs index 54924be0..98fc233c 100644 --- a/src/types/boolobject.rs +++ b/src/types/boolobject.rs @@ -65,21 +65,21 @@ mod tests { #[test] fn test_true() { - let gil = Python::acquire_gil(); - let py = gil.python(); - assert!(PyBool::new(py, true).is_true()); - let t: &PyAny = PyBool::new(py, true).into(); - assert!(t.extract::().unwrap()); - assert_eq!(true.to_object(py), PyBool::new(py, true).into()); + Python::with_gil(|py| { + assert!(PyBool::new(py, true).is_true()); + let t: &PyAny = PyBool::new(py, true).into(); + assert!(t.extract::().unwrap()); + assert_eq!(true.to_object(py), PyBool::new(py, true).into()); + }); } #[test] fn test_false() { - let gil = Python::acquire_gil(); - let py = gil.python(); - assert!(!PyBool::new(py, false).is_true()); - let t: &PyAny = PyBool::new(py, false).into(); - assert!(!t.extract::().unwrap()); - assert_eq!(false.to_object(py), PyBool::new(py, false).into()); + Python::with_gil(|py| { + assert!(!PyBool::new(py, false).is_true()); + let t: &PyAny = PyBool::new(py, false).into(); + assert!(!t.extract::().unwrap()); + assert_eq!(false.to_object(py), PyBool::new(py, false).into()); + }); } } diff --git a/src/types/bytearray.rs b/src/types/bytearray.rs index 38126483..16c26bc2 100644 --- a/src/types/bytearray.rs +++ b/src/types/bytearray.rs @@ -172,132 +172,125 @@ mod tests { #[test] fn test_len() { - let gil = Python::acquire_gil(); - let py = gil.python(); - - let src = b"Hello Python"; - let bytearray = PyByteArray::new(py, src); - assert_eq!(src.len(), bytearray.len()); + Python::with_gil(|py| { + let src = b"Hello Python"; + let bytearray = PyByteArray::new(py, src); + assert_eq!(src.len(), bytearray.len()); + }); } #[test] fn test_as_bytes() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let src = b"Hello Python"; + let bytearray = PyByteArray::new(py, src); - let src = b"Hello Python"; - let bytearray = PyByteArray::new(py, src); - - let slice = unsafe { bytearray.as_bytes() }; - 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] fn test_as_bytes_mut() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let src = b"Hello Python"; + let bytearray = PyByteArray::new(py, src); - let src = b"Hello Python"; - let bytearray = PyByteArray::new(py, src); + let slice = unsafe { bytearray.as_bytes_mut() }; + assert_eq!(src, slice); + assert_eq!(bytearray.data(), slice.as_mut_ptr()); - let slice = unsafe { bytearray.as_bytes_mut() }; - assert_eq!(src, slice); - assert_eq!(bytearray.data(), slice.as_mut_ptr()); + slice[0..5].copy_from_slice(b"Hi..."); - slice[0..5].copy_from_slice(b"Hi..."); - - assert_eq!( - bytearray.str().unwrap().to_str().unwrap(), - "bytearray(b'Hi... Python')" - ); + assert_eq!( + bytearray.str().unwrap().to_str().unwrap(), + "bytearray(b'Hi... Python')" + ); + }); } #[test] fn test_to_vec() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let src = b"Hello Python"; + let bytearray = PyByteArray::new(py, src); - let src = b"Hello Python"; - let bytearray = PyByteArray::new(py, src); - - let vec = bytearray.to_vec(); - assert_eq!(src, vec.as_slice()); + let vec = bytearray.to_vec(); + assert_eq!(src, vec.as_slice()); + }); } #[test] fn test_from() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let src = b"Hello Python"; + let bytearray = PyByteArray::new(py, src); - let src = b"Hello Python"; - let bytearray = PyByteArray::new(py, src); + let ba: PyObject = bytearray.into(); + let bytearray = PyByteArray::from(py, &ba).unwrap(); - let ba: PyObject = bytearray.into(); - let bytearray = PyByteArray::from(py, &ba).unwrap(); - - assert_eq!(src, unsafe { bytearray.as_bytes() }); + assert_eq!(src, unsafe { bytearray.as_bytes() }); + }); } #[test] fn test_from_err() { - let gil = Python::acquire_gil(); - let py = gil.python(); - - if let Err(err) = PyByteArray::from(py, &py.None()) { - assert!(err.is_instance::(py)); - } else { - panic!("error"); - } + Python::with_gil(|py| { + if let Err(err) = PyByteArray::from(py, &py.None()) { + assert!(err.is_instance::(py)); + } else { + panic!("error"); + } + }); } #[test] fn test_resize() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let src = b"Hello Python"; + let bytearray = PyByteArray::new(py, src); - let src = b"Hello Python"; - let bytearray = PyByteArray::new(py, src); - - bytearray.resize(20).unwrap(); - assert_eq!(20, bytearray.len()); + bytearray.resize(20).unwrap(); + assert_eq!(20, bytearray.len()); + }); } #[test] fn test_byte_array_new_with() -> super::PyResult<()> { - let gil = Python::acquire_gil(); - let py = gil.python(); - let py_bytearray = PyByteArray::new_with(py, 10, |b: &mut [u8]| { - b.copy_from_slice(b"Hello Rust"); + Python::with_gil(|py| -> super::PyResult<()> { + let py_bytearray = PyByteArray::new_with(py, 10, |b: &mut [u8]| { + b.copy_from_slice(b"Hello Rust"); + Ok(()) + })?; + let bytearray: &[u8] = unsafe { py_bytearray.as_bytes() }; + assert_eq!(bytearray, b"Hello Rust"); Ok(()) - })?; - let bytearray: &[u8] = unsafe { py_bytearray.as_bytes() }; - assert_eq!(bytearray, b"Hello Rust"); - Ok(()) + }) } #[test] fn test_byte_array_new_with_zero_initialised() -> super::PyResult<()> { - let gil = Python::acquire_gil(); - let py = gil.python(); - let py_bytearray = PyByteArray::new_with(py, 10, |_b: &mut [u8]| Ok(()))?; - let bytearray: &[u8] = unsafe { py_bytearray.as_bytes() }; - assert_eq!(bytearray, &[0; 10]); - Ok(()) + Python::with_gil(|py| -> super::PyResult<()> { + let py_bytearray = PyByteArray::new_with(py, 10, |_b: &mut [u8]| Ok(()))?; + let bytearray: &[u8] = unsafe { py_bytearray.as_bytes() }; + assert_eq!(bytearray, &[0; 10]); + Ok(()) + }) } #[test] fn test_byte_array_new_with_error() { use crate::exceptions::PyValueError; - let gil = Python::acquire_gil(); - let py = gil.python(); - let py_bytearray_result = PyByteArray::new_with(py, 10, |_b: &mut [u8]| { - Err(PyValueError::new_err("Hello Crustaceans!")) - }); - assert!(py_bytearray_result.is_err()); - assert!(py_bytearray_result - .err() - .unwrap() - .is_instance::(py)); + Python::with_gil(|py| { + let py_bytearray_result = PyByteArray::new_with(py, 10, |_b: &mut [u8]| { + Err(PyValueError::new_err("Hello Crustaceans!")) + }); + assert!(py_bytearray_result.is_err()); + assert!(py_bytearray_result + .err() + .unwrap() + .is_instance::(py)); + }) } } diff --git a/src/types/bytes.rs b/src/types/bytes.rs index c10d68d5..427ea13c 100644 --- a/src/types/bytes.rs +++ b/src/types/bytes.rs @@ -121,57 +121,56 @@ mod tests { #[test] fn test_extract_bytes() { - let gil = Python::acquire_gil(); - let py = gil.python(); - - let py_bytes = py.eval("b'Hello Python'", None, None).unwrap(); - let bytes: &[u8] = FromPyObject::extract(py_bytes).unwrap(); - assert_eq!(bytes, b"Hello Python"); + Python::with_gil(|py| { + let py_bytes = py.eval("b'Hello Python'", None, None).unwrap(); + let bytes: &[u8] = FromPyObject::extract(py_bytes).unwrap(); + assert_eq!(bytes, b"Hello Python"); + }); } #[test] fn test_bytes_index() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let bytes = PyBytes::new(py, b"Hello World"); - assert_eq!(bytes[1], b'e'); + Python::with_gil(|py| { + let bytes = PyBytes::new(py, b"Hello World"); + assert_eq!(bytes[1], b'e'); + }); } #[test] fn test_bytes_new_with() -> super::PyResult<()> { - let gil = Python::acquire_gil(); - let py = gil.python(); - let py_bytes = PyBytes::new_with(py, 10, |b: &mut [u8]| { - b.copy_from_slice(b"Hello Rust"); + Python::with_gil(|py| -> super::PyResult<()> { + let py_bytes = PyBytes::new_with(py, 10, |b: &mut [u8]| { + b.copy_from_slice(b"Hello Rust"); + Ok(()) + })?; + let bytes: &[u8] = FromPyObject::extract(py_bytes)?; + assert_eq!(bytes, b"Hello Rust"); Ok(()) - })?; - let bytes: &[u8] = FromPyObject::extract(py_bytes)?; - assert_eq!(bytes, b"Hello Rust"); - Ok(()) + }) } #[test] fn test_bytes_new_with_zero_initialised() -> super::PyResult<()> { - let gil = Python::acquire_gil(); - let py = gil.python(); - let py_bytes = PyBytes::new_with(py, 10, |_b: &mut [u8]| Ok(()))?; - let bytes: &[u8] = FromPyObject::extract(py_bytes)?; - assert_eq!(bytes, &[0; 10]); - Ok(()) + Python::with_gil(|py| -> super::PyResult<()> { + let py_bytes = PyBytes::new_with(py, 10, |_b: &mut [u8]| Ok(()))?; + let bytes: &[u8] = FromPyObject::extract(py_bytes)?; + assert_eq!(bytes, &[0; 10]); + Ok(()) + }) } #[test] fn test_bytes_new_with_error() { use crate::exceptions::PyValueError; - let gil = Python::acquire_gil(); - let py = gil.python(); - let py_bytes_result = PyBytes::new_with(py, 10, |_b: &mut [u8]| { - Err(PyValueError::new_err("Hello Crustaceans!")) + Python::with_gil(|py| { + let py_bytes_result = PyBytes::new_with(py, 10, |_b: &mut [u8]| { + Err(PyValueError::new_err("Hello Crustaceans!")) + }); + assert!(py_bytes_result.is_err()); + assert!(py_bytes_result + .err() + .unwrap() + .is_instance::(py)); }); - assert!(py_bytes_result.is_err()); - assert!(py_bytes_result - .err() - .unwrap() - .is_instance::(py)); } } diff --git a/src/types/dict.rs b/src/types/dict.rs index 82e92540..83dfd526 100644 --- a/src/types/dict.rs +++ b/src/types/dict.rs @@ -412,46 +412,43 @@ mod hashbrown_hashmap_conversion { #[test] fn test_hashbrown_hashmap_to_python() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let mut map = hashbrown::HashMap::::new(); + map.insert(1, 1); - let mut map = hashbrown::HashMap::::new(); - map.insert(1, 1); + let m = map.to_object(py); + let py_map = ::try_from(m.as_ref(py)).unwrap(); - let m = map.to_object(py); - let py_map = ::try_from(m.as_ref(py)).unwrap(); - - assert!(py_map.len() == 1); - assert!(py_map.get_item(1).unwrap().extract::().unwrap() == 1); - assert_eq!(map, py_map.extract().unwrap()); + assert!(py_map.len() == 1); + assert!(py_map.get_item(1).unwrap().extract::().unwrap() == 1); + assert_eq!(map, py_map.extract().unwrap()); + }); } #[test] fn test_hashbrown_hashmap_into_python() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let mut map = hashbrown::HashMap::::new(); + map.insert(1, 1); - let mut map = hashbrown::HashMap::::new(); - map.insert(1, 1); + let m: PyObject = map.into_py(py); + let py_map = ::try_from(m.as_ref(py)).unwrap(); - let m: PyObject = map.into_py(py); - let py_map = ::try_from(m.as_ref(py)).unwrap(); - - assert!(py_map.len() == 1); - assert!(py_map.get_item(1).unwrap().extract::().unwrap() == 1); + assert!(py_map.len() == 1); + assert!(py_map.get_item(1).unwrap().extract::().unwrap() == 1); + }); } #[test] fn test_hashbrown_hashmap_into_dict() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let mut map = hashbrown::HashMap::::new(); + map.insert(1, 1); - let mut map = hashbrown::HashMap::::new(); - map.insert(1, 1); + let py_map = map.into_py_dict(py); - let py_map = map.into_py_dict(py); - - assert_eq!(py_map.len(), 1); - assert_eq!(py_map.get_item(1).unwrap().extract::().unwrap(), 1); + assert_eq!(py_map.len(), 1); + assert_eq!(py_map.get_item(1).unwrap().extract::().unwrap(), 1); + }); } } @@ -469,397 +466,388 @@ mod tests { #[test] fn test_new() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let dict = [(7, 32)].into_py_dict(py); - assert_eq!(32, dict.get_item(7i32).unwrap().extract::().unwrap()); - assert_eq!(None, dict.get_item(8i32)); - let map: HashMap = [(7, 32)].iter().cloned().collect(); - assert_eq!(map, dict.extract().unwrap()); - let map: BTreeMap = [(7, 32)].iter().cloned().collect(); - assert_eq!(map, dict.extract().unwrap()); + Python::with_gil(|py| { + let dict = [(7, 32)].into_py_dict(py); + assert_eq!(32, dict.get_item(7i32).unwrap().extract::().unwrap()); + assert_eq!(None, dict.get_item(8i32)); + let map: HashMap = [(7, 32)].iter().cloned().collect(); + assert_eq!(map, dict.extract().unwrap()); + let map: BTreeMap = [(7, 32)].iter().cloned().collect(); + assert_eq!(map, dict.extract().unwrap()); + }); } #[test] #[cfg(not(PyPy))] fn test_from_sequence() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let items = PyList::new(py, &vec![("a", 1), ("b", 2)]); - let dict = PyDict::from_sequence(py, items.to_object(py)).unwrap(); - assert_eq!(1, dict.get_item("a").unwrap().extract::().unwrap()); - assert_eq!(2, dict.get_item("b").unwrap().extract::().unwrap()); - let map: HashMap<&str, i32> = [("a", 1), ("b", 2)].iter().cloned().collect(); - assert_eq!(map, dict.extract().unwrap()); - let map: BTreeMap<&str, i32> = [("a", 1), ("b", 2)].iter().cloned().collect(); - assert_eq!(map, dict.extract().unwrap()); + Python::with_gil(|py| { + let items = PyList::new(py, &vec![("a", 1), ("b", 2)]); + let dict = PyDict::from_sequence(py, items.to_object(py)).unwrap(); + assert_eq!(1, dict.get_item("a").unwrap().extract::().unwrap()); + assert_eq!(2, dict.get_item("b").unwrap().extract::().unwrap()); + let map: HashMap<&str, i32> = [("a", 1), ("b", 2)].iter().cloned().collect(); + assert_eq!(map, dict.extract().unwrap()); + let map: BTreeMap<&str, i32> = [("a", 1), ("b", 2)].iter().cloned().collect(); + assert_eq!(map, dict.extract().unwrap()); + }); } #[test] #[cfg(not(PyPy))] fn test_from_sequence_err() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let items = PyList::new(py, &vec!["a", "b"]); - assert!(PyDict::from_sequence(py, items.to_object(py)).is_err()); + Python::with_gil(|py| { + let items = PyList::new(py, &vec!["a", "b"]); + assert!(PyDict::from_sequence(py, items.to_object(py)).is_err()); + }); } #[test] fn test_copy() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let dict = [(7, 32)].into_py_dict(py); + Python::with_gil(|py| { + let dict = [(7, 32)].into_py_dict(py); - let ndict = dict.copy().unwrap(); - assert_eq!(32, ndict.get_item(7i32).unwrap().extract::().unwrap()); - assert_eq!(None, ndict.get_item(8i32)); + let ndict = dict.copy().unwrap(); + assert_eq!(32, ndict.get_item(7i32).unwrap().extract::().unwrap()); + assert_eq!(None, ndict.get_item(8i32)); + }); } #[test] fn test_len() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let mut v = HashMap::new(); - let ob = v.to_object(py); - let dict = ::try_from(ob.as_ref(py)).unwrap(); - assert_eq!(0, dict.len()); - v.insert(7, 32); - let ob = v.to_object(py); - let dict2 = ::try_from(ob.as_ref(py)).unwrap(); - assert_eq!(1, dict2.len()); + Python::with_gil(|py| { + let mut v = HashMap::new(); + let ob = v.to_object(py); + let dict = ::try_from(ob.as_ref(py)).unwrap(); + assert_eq!(0, dict.len()); + v.insert(7, 32); + let ob = v.to_object(py); + let dict2 = ::try_from(ob.as_ref(py)).unwrap(); + assert_eq!(1, dict2.len()); + }); } #[test] fn test_contains() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let mut v = HashMap::new(); - v.insert(7, 32); - let ob = v.to_object(py); - let dict = ::try_from(ob.as_ref(py)).unwrap(); - assert!(dict.contains(7i32).unwrap()); - assert!(!dict.contains(8i32).unwrap()); + Python::with_gil(|py| { + let mut v = HashMap::new(); + v.insert(7, 32); + let ob = v.to_object(py); + let dict = ::try_from(ob.as_ref(py)).unwrap(); + assert!(dict.contains(7i32).unwrap()); + assert!(!dict.contains(8i32).unwrap()); + }); } #[test] fn test_get_item() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let mut v = HashMap::new(); - v.insert(7, 32); - let ob = v.to_object(py); - let dict = ::try_from(ob.as_ref(py)).unwrap(); - assert_eq!(32, dict.get_item(7i32).unwrap().extract::().unwrap()); - assert_eq!(None, dict.get_item(8i32)); + Python::with_gil(|py| { + let mut v = HashMap::new(); + v.insert(7, 32); + let ob = v.to_object(py); + let dict = ::try_from(ob.as_ref(py)).unwrap(); + assert_eq!(32, dict.get_item(7i32).unwrap().extract::().unwrap()); + assert_eq!(None, dict.get_item(8i32)); + }); } #[test] fn test_set_item() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let mut v = HashMap::new(); - v.insert(7, 32); - let ob = v.to_object(py); - let dict = ::try_from(ob.as_ref(py)).unwrap(); - assert!(dict.set_item(7i32, 42i32).is_ok()); // change - assert!(dict.set_item(8i32, 123i32).is_ok()); // insert - assert_eq!( - 42i32, - dict.get_item(7i32).unwrap().extract::().unwrap() - ); - assert_eq!( - 123i32, - dict.get_item(8i32).unwrap().extract::().unwrap() - ); + Python::with_gil(|py| { + let mut v = HashMap::new(); + v.insert(7, 32); + let ob = v.to_object(py); + let dict = ::try_from(ob.as_ref(py)).unwrap(); + assert!(dict.set_item(7i32, 42i32).is_ok()); // change + assert!(dict.set_item(8i32, 123i32).is_ok()); // insert + assert_eq!( + 42i32, + dict.get_item(7i32).unwrap().extract::().unwrap() + ); + assert_eq!( + 123i32, + dict.get_item(8i32).unwrap().extract::().unwrap() + ); + }); } #[test] fn test_set_item_refcnt() { - let gil = Python::acquire_gil(); - let py = gil.python(); - - let cnt; - { - let _pool = unsafe { crate::GILPool::new() }; - let none = py.None(); - cnt = none.get_refcnt(py); - let _dict = [(10, none)].into_py_dict(py); - } - { - assert_eq!(cnt, py.None().get_refcnt(py)); - } + Python::with_gil(|py| { + let cnt; + { + let _pool = unsafe { crate::GILPool::new() }; + let none = py.None(); + cnt = none.get_refcnt(py); + let _dict = [(10, none)].into_py_dict(py); + } + { + assert_eq!(cnt, py.None().get_refcnt(py)); + } + }); } #[test] fn test_set_item_does_not_update_original_object() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let mut v = HashMap::new(); - v.insert(7, 32); - let ob = v.to_object(py); - let dict = ::try_from(ob.as_ref(py)).unwrap(); - assert!(dict.set_item(7i32, 42i32).is_ok()); // change - assert!(dict.set_item(8i32, 123i32).is_ok()); // insert - assert_eq!(32i32, v[&7i32]); // not updated! - assert_eq!(None, v.get(&8i32)); + Python::with_gil(|py| { + let mut v = HashMap::new(); + v.insert(7, 32); + let ob = v.to_object(py); + let dict = ::try_from(ob.as_ref(py)).unwrap(); + assert!(dict.set_item(7i32, 42i32).is_ok()); // change + assert!(dict.set_item(8i32, 123i32).is_ok()); // insert + assert_eq!(32i32, v[&7i32]); // not updated! + assert_eq!(None, v.get(&8i32)); + }); } #[test] fn test_del_item() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let mut v = HashMap::new(); - v.insert(7, 32); - let ob = v.to_object(py); - let dict = ::try_from(ob.as_ref(py)).unwrap(); - assert!(dict.del_item(7i32).is_ok()); - assert_eq!(0, dict.len()); - assert_eq!(None, dict.get_item(7i32)); + Python::with_gil(|py| { + let mut v = HashMap::new(); + v.insert(7, 32); + let ob = v.to_object(py); + let dict = ::try_from(ob.as_ref(py)).unwrap(); + assert!(dict.del_item(7i32).is_ok()); + assert_eq!(0, dict.len()); + assert_eq!(None, dict.get_item(7i32)); + }); } #[test] fn test_del_item_does_not_update_original_object() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let mut v = HashMap::new(); - v.insert(7, 32); - let ob = v.to_object(py); - let dict = ::try_from(ob.as_ref(py)).unwrap(); - assert!(dict.del_item(7i32).is_ok()); // change - assert_eq!(32i32, *v.get(&7i32).unwrap()); // not updated! + Python::with_gil(|py| { + let mut v = HashMap::new(); + v.insert(7, 32); + let ob = v.to_object(py); + let dict = ::try_from(ob.as_ref(py)).unwrap(); + assert!(dict.del_item(7i32).is_ok()); // change + assert_eq!(32i32, *v.get(&7i32).unwrap()); // not updated! + }); } #[test] fn test_items() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let mut v = HashMap::new(); - v.insert(7, 32); - v.insert(8, 42); - v.insert(9, 123); - let ob = v.to_object(py); - let dict = ::try_from(ob.as_ref(py)).unwrap(); - // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. - let mut key_sum = 0; - let mut value_sum = 0; - for el in dict.items().iter() { - let tuple = el.cast_as::().unwrap(); - key_sum += tuple.get_item(0).extract::().unwrap(); - value_sum += tuple.get_item(1).extract::().unwrap(); - } - assert_eq!(7 + 8 + 9, key_sum); - assert_eq!(32 + 42 + 123, value_sum); + Python::with_gil(|py| { + let mut v = HashMap::new(); + v.insert(7, 32); + v.insert(8, 42); + v.insert(9, 123); + let ob = v.to_object(py); + let dict = ::try_from(ob.as_ref(py)).unwrap(); + // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. + let mut key_sum = 0; + let mut value_sum = 0; + for el in dict.items().iter() { + let tuple = el.cast_as::().unwrap(); + key_sum += tuple.get_item(0).extract::().unwrap(); + value_sum += tuple.get_item(1).extract::().unwrap(); + } + assert_eq!(7 + 8 + 9, key_sum); + assert_eq!(32 + 42 + 123, value_sum); + }); } #[test] fn test_keys() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let mut v = HashMap::new(); - v.insert(7, 32); - v.insert(8, 42); - v.insert(9, 123); - let ob = v.to_object(py); - let dict = ::try_from(ob.as_ref(py)).unwrap(); - // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. - let mut key_sum = 0; - for el in dict.keys().iter() { - key_sum += el.extract::().unwrap(); - } - assert_eq!(7 + 8 + 9, key_sum); + Python::with_gil(|py| { + let mut v = HashMap::new(); + v.insert(7, 32); + v.insert(8, 42); + v.insert(9, 123); + let ob = v.to_object(py); + let dict = ::try_from(ob.as_ref(py)).unwrap(); + // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. + let mut key_sum = 0; + for el in dict.keys().iter() { + key_sum += el.extract::().unwrap(); + } + assert_eq!(7 + 8 + 9, key_sum); + }); } #[test] fn test_values() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let mut v = HashMap::new(); - v.insert(7, 32); - v.insert(8, 42); - v.insert(9, 123); - let ob = v.to_object(py); - let dict = ::try_from(ob.as_ref(py)).unwrap(); - // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. - let mut values_sum = 0; - for el in dict.values().iter() { - values_sum += el.extract::().unwrap(); - } - assert_eq!(32 + 42 + 123, values_sum); + Python::with_gil(|py| { + let mut v = HashMap::new(); + v.insert(7, 32); + v.insert(8, 42); + v.insert(9, 123); + let ob = v.to_object(py); + let dict = ::try_from(ob.as_ref(py)).unwrap(); + // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. + let mut values_sum = 0; + for el in dict.values().iter() { + values_sum += el.extract::().unwrap(); + } + assert_eq!(32 + 42 + 123, values_sum); + }); } #[test] fn test_iter() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let mut v = HashMap::new(); - v.insert(7, 32); - v.insert(8, 42); - v.insert(9, 123); - let ob = v.to_object(py); - let dict = ::try_from(ob.as_ref(py)).unwrap(); - let mut key_sum = 0; - let mut value_sum = 0; - for (key, value) in dict.iter() { - key_sum += key.extract::().unwrap(); - value_sum += value.extract::().unwrap(); - } - assert_eq!(7 + 8 + 9, key_sum); - assert_eq!(32 + 42 + 123, value_sum); + Python::with_gil(|py| { + let mut v = HashMap::new(); + v.insert(7, 32); + v.insert(8, 42); + v.insert(9, 123); + let ob = v.to_object(py); + let dict = ::try_from(ob.as_ref(py)).unwrap(); + let mut key_sum = 0; + let mut value_sum = 0; + for (key, value) in dict.iter() { + key_sum += key.extract::().unwrap(); + value_sum += value.extract::().unwrap(); + } + assert_eq!(7 + 8 + 9, key_sum); + assert_eq!(32 + 42 + 123, value_sum); + }); } #[test] fn test_iter_size_hint() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let mut v = HashMap::new(); - v.insert(7, 32); - v.insert(8, 42); - v.insert(9, 123); - let ob = v.to_object(py); - let dict = ::try_from(ob.as_ref(py)).unwrap(); + Python::with_gil(|py| { + let mut v = HashMap::new(); + v.insert(7, 32); + v.insert(8, 42); + v.insert(9, 123); + let ob = v.to_object(py); + let dict = ::try_from(ob.as_ref(py)).unwrap(); - let mut iter = dict.iter(); - assert_eq!(iter.size_hint(), (v.len(), Some(v.len()))); - iter.next(); - assert_eq!(iter.size_hint(), (v.len() - 1, Some(v.len() - 1))); + let mut iter = dict.iter(); + assert_eq!(iter.size_hint(), (v.len(), Some(v.len()))); + iter.next(); + assert_eq!(iter.size_hint(), (v.len() - 1, Some(v.len() - 1))); - // Exhust iterator. - for _ in &mut iter {} + // Exhust iterator. + for _ in &mut iter {} - assert_eq!(iter.size_hint(), (0, Some(0))); + assert_eq!(iter.size_hint(), (0, Some(0))); + }); } #[test] fn test_into_iter() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let mut v = HashMap::new(); - v.insert(7, 32); - v.insert(8, 42); - v.insert(9, 123); - let ob = v.to_object(py); - let dict = ::try_from(ob.as_ref(py)).unwrap(); - let mut key_sum = 0; - let mut value_sum = 0; - for (key, value) in dict { - key_sum += key.extract::().unwrap(); - value_sum += value.extract::().unwrap(); - } - assert_eq!(7 + 8 + 9, key_sum); - assert_eq!(32 + 42 + 123, value_sum); + Python::with_gil(|py| { + let mut v = HashMap::new(); + v.insert(7, 32); + v.insert(8, 42); + v.insert(9, 123); + let ob = v.to_object(py); + let dict = ::try_from(ob.as_ref(py)).unwrap(); + let mut key_sum = 0; + let mut value_sum = 0; + for (key, value) in dict { + key_sum += key.extract::().unwrap(); + value_sum += value.extract::().unwrap(); + } + assert_eq!(7 + 8 + 9, key_sum); + assert_eq!(32 + 42 + 123, value_sum); + }); } #[test] fn test_hashmap_to_python() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let mut map = HashMap::::new(); + map.insert(1, 1); - let mut map = HashMap::::new(); - map.insert(1, 1); + let m = map.to_object(py); + let py_map = ::try_from(m.as_ref(py)).unwrap(); - let m = map.to_object(py); - let py_map = ::try_from(m.as_ref(py)).unwrap(); - - assert!(py_map.len() == 1); - assert!(py_map.get_item(1).unwrap().extract::().unwrap() == 1); - assert_eq!(map, py_map.extract().unwrap()); + assert!(py_map.len() == 1); + assert!(py_map.get_item(1).unwrap().extract::().unwrap() == 1); + assert_eq!(map, py_map.extract().unwrap()); + }); } #[test] fn test_btreemap_to_python() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let mut map = BTreeMap::::new(); + map.insert(1, 1); - let mut map = BTreeMap::::new(); - map.insert(1, 1); + let m = map.to_object(py); + let py_map = ::try_from(m.as_ref(py)).unwrap(); - let m = map.to_object(py); - let py_map = ::try_from(m.as_ref(py)).unwrap(); - - assert!(py_map.len() == 1); - assert!(py_map.get_item(1).unwrap().extract::().unwrap() == 1); - assert_eq!(map, py_map.extract().unwrap()); + assert!(py_map.len() == 1); + assert!(py_map.get_item(1).unwrap().extract::().unwrap() == 1); + assert_eq!(map, py_map.extract().unwrap()); + }); } #[test] fn test_hashmap_into_python() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let mut map = HashMap::::new(); + map.insert(1, 1); - let mut map = HashMap::::new(); - map.insert(1, 1); + let m: PyObject = map.into_py(py); + let py_map = ::try_from(m.as_ref(py)).unwrap(); - let m: PyObject = map.into_py(py); - let py_map = ::try_from(m.as_ref(py)).unwrap(); - - assert!(py_map.len() == 1); - assert!(py_map.get_item(1).unwrap().extract::().unwrap() == 1); + assert!(py_map.len() == 1); + assert!(py_map.get_item(1).unwrap().extract::().unwrap() == 1); + }); } #[test] fn test_hashmap_into_dict() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let mut map = HashMap::::new(); + map.insert(1, 1); - let mut map = HashMap::::new(); - map.insert(1, 1); + let py_map = map.into_py_dict(py); - let py_map = map.into_py_dict(py); - - assert_eq!(py_map.len(), 1); - assert_eq!(py_map.get_item(1).unwrap().extract::().unwrap(), 1); + assert_eq!(py_map.len(), 1); + assert_eq!(py_map.get_item(1).unwrap().extract::().unwrap(), 1); + }); } #[test] fn test_btreemap_into_py() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let mut map = BTreeMap::::new(); + map.insert(1, 1); - let mut map = BTreeMap::::new(); - map.insert(1, 1); + let m: PyObject = map.into_py(py); + let py_map = ::try_from(m.as_ref(py)).unwrap(); - let m: PyObject = map.into_py(py); - let py_map = ::try_from(m.as_ref(py)).unwrap(); - - assert!(py_map.len() == 1); - assert!(py_map.get_item(1).unwrap().extract::().unwrap() == 1); + assert!(py_map.len() == 1); + assert!(py_map.get_item(1).unwrap().extract::().unwrap() == 1); + }); } #[test] fn test_btreemap_into_dict() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let mut map = BTreeMap::::new(); + map.insert(1, 1); - let mut map = BTreeMap::::new(); - map.insert(1, 1); + let py_map = map.into_py_dict(py); - let py_map = map.into_py_dict(py); - - assert_eq!(py_map.len(), 1); - assert_eq!(py_map.get_item(1).unwrap().extract::().unwrap(), 1); + assert_eq!(py_map.len(), 1); + assert_eq!(py_map.get_item(1).unwrap().extract::().unwrap(), 1); + }); } #[test] fn test_vec_into_dict() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + 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)]; - let py_map = vec.into_py_dict(py); - - assert_eq!(py_map.len(), 3); - assert_eq!(py_map.get_item("b").unwrap().extract::().unwrap(), 2); + assert_eq!(py_map.len(), 3); + assert_eq!(py_map.get_item("b").unwrap().extract::().unwrap(), 2); + }); } #[test] fn test_slice_into_dict() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let arr = [("a", 1), ("b", 2), ("c", 3)]; + let py_map = arr.into_py_dict(py); - let arr = [("a", 1), ("b", 2), ("c", 3)]; - let py_map = arr.into_py_dict(py); - - assert_eq!(py_map.len(), 3); - assert_eq!(py_map.get_item("b").unwrap().extract::().unwrap(), 2); + assert_eq!(py_map.len(), 3); + assert_eq!(py_map.get_item("b").unwrap().extract::().unwrap(), 2); + }); } } diff --git a/src/types/floatob.rs b/src/types/floatob.rs index 2197a888..290975a0 100644 --- a/src/types/floatob.rs +++ b/src/types/floatob.rs @@ -93,11 +93,12 @@ mod tests { fn $func_name() { use assert_approx_eq::assert_approx_eq; - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py|{ + let val = 123 as $t1; let obj = val.to_object(py); assert_approx_eq!(obj.extract::<$t2>(py).unwrap(), val as $t2); + }); } ) ); @@ -111,10 +112,10 @@ mod tests { fn test_as_double_macro() { use assert_approx_eq::assert_approx_eq; - let gil = Python::acquire_gil(); - let py = gil.python(); - let v = 1.23f64; - let obj = v.to_object(py); - assert_approx_eq!(v, unsafe { PyFloat_AS_DOUBLE(obj.as_ptr()) }); + Python::with_gil(|py| { + let v = 1.23f64; + let obj = v.to_object(py); + assert_approx_eq!(v, unsafe { PyFloat_AS_DOUBLE(obj.as_ptr()) }); + }); } } diff --git a/src/types/iterator.rs b/src/types/iterator.rs index 2ce87dc0..0293647a 100644 --- a/src/types/iterator.rs +++ b/src/types/iterator.rs @@ -107,65 +107,62 @@ mod tests { #[test] fn vec_iter() { - let gil_guard = Python::acquire_gil(); - let py = gil_guard.python(); - let obj = vec![10, 20].to_object(py); - let inst = obj.as_ref(py); - let mut it = inst.iter().unwrap(); - assert_eq!(10, it.next().unwrap().unwrap().extract().unwrap()); - assert_eq!(20, it.next().unwrap().unwrap().extract().unwrap()); - assert!(it.next().is_none()); + Python::with_gil(|py| { + let obj = vec![10, 20].to_object(py); + let inst = obj.as_ref(py); + let mut it = inst.iter().unwrap(); + assert_eq!(10, it.next().unwrap().unwrap().extract().unwrap()); + assert_eq!(20, it.next().unwrap().unwrap().extract().unwrap()); + assert!(it.next().is_none()); + }); } #[test] fn iter_refcnt() { - let obj; - let count; - { - let gil_guard = Python::acquire_gil(); - let py = gil_guard.python(); - obj = vec![10, 20].to_object(py); - count = obj.get_refcnt(py); - } + let (obj, count) = Python::with_gil(|py| -> (Py, isize) { + let obj = vec![10, 20].to_object(py); + let count = obj.get_refcnt(py); + (obj, count) + }); - { - let gil_guard = Python::acquire_gil(); - let py = gil_guard.python(); + Python::with_gil(|py| { let inst = obj.as_ref(py); let mut it = inst.iter().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] fn iter_item_refcnt() { - let gil_guard = Python::acquire_gil(); - let py = gil_guard.python(); + Python::with_gil(|py| { + 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 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 _pool = unsafe { GILPool::new() }; + let inst = obj.as_ref(py); + let mut it = inst.iter().unwrap(); - { - let _pool = unsafe { GILPool::new() }; - let inst = obj.as_ref(py); - let mut it = inst.iter().unwrap(); - - assert_eq!(10, it.next().unwrap().unwrap().extract().unwrap()); - assert!(it.next().unwrap().unwrap().is_none()); - } - 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] @@ -181,37 +178,35 @@ mod tests { "# ); - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let context = PyDict::new(py); + py.run(fibonacci_generator, None, Some(context)).unwrap(); - let context = PyDict::new(py); - py.run(fibonacci_generator, None, Some(context)).unwrap(); - - let generator = py.eval("fibonacci(5)", None, Some(context)).unwrap(); - for (actual, expected) in generator.iter().unwrap().zip(&[1, 1, 2, 3, 5]) { - let actual = actual.unwrap().extract::().unwrap(); - assert_eq!(actual, *expected) - } + let generator = py.eval("fibonacci(5)", None, Some(context)).unwrap(); + for (actual, expected) in generator.iter().unwrap().zip(&[1, 1, 2, 3, 5]) { + let actual = actual.unwrap().extract::().unwrap(); + assert_eq!(actual, *expected) + } + }); } #[test] fn int_not_iterable() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let x = 5.to_object(py); + let err = PyIterator::from_object(py, &x).unwrap_err(); - let x = 5.to_object(py); - let err = PyIterator::from_object(py, &x).unwrap_err(); - - assert!(err.is_instance::(py)) + assert!(err.is_instance::(py)); + }); } #[test] #[cfg(any(not(Py_LIMITED_API), Py_3_8))] fn iterator_try_from() { - let gil_guard = Python::acquire_gil(); - let py = gil_guard.python(); - let obj: Py = vec![10, 20].to_object(py).as_ref(py).iter().unwrap().into(); - let iter: &PyIterator = PyIterator::try_from(obj.as_ref(py)).unwrap(); - assert_eq!(obj, iter.into()); + Python::with_gil(|py| { + let obj: Py = vec![10, 20].to_object(py).as_ref(py).iter().unwrap().into(); + let iter: &PyIterator = PyIterator::try_from(obj.as_ref(py)).unwrap(); + assert_eq!(obj, iter.into()); + }); } } diff --git a/src/types/list.rs b/src/types/list.rs index 535f676f..14e9f63b 100644 --- a/src/types/list.rs +++ b/src/types/list.rs @@ -214,224 +214,221 @@ mod tests { #[test] fn test_new() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let list = PyList::new(py, &[2, 3, 5, 7]); - assert_eq!(2, list.get_item(0).extract::().unwrap()); - assert_eq!(3, list.get_item(1).extract::().unwrap()); - assert_eq!(5, list.get_item(2).extract::().unwrap()); - assert_eq!(7, list.get_item(3).extract::().unwrap()); + Python::with_gil(|py| { + let list = PyList::new(py, &[2, 3, 5, 7]); + assert_eq!(2, list.get_item(0).extract::().unwrap()); + assert_eq!(3, list.get_item(1).extract::().unwrap()); + assert_eq!(5, list.get_item(2).extract::().unwrap()); + assert_eq!(7, list.get_item(3).extract::().unwrap()); + }); } #[test] fn test_len() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let list = PyList::new(py, &[1, 2, 3, 4]); - assert_eq!(4, list.len()); + Python::with_gil(|py| { + let list = PyList::new(py, &[1, 2, 3, 4]); + assert_eq!(4, list.len()); + }); } #[test] fn test_get_item() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let list = PyList::new(py, &[2, 3, 5, 7]); - assert_eq!(2, list.get_item(0).extract::().unwrap()); - assert_eq!(3, list.get_item(1).extract::().unwrap()); - assert_eq!(5, list.get_item(2).extract::().unwrap()); - assert_eq!(7, list.get_item(3).extract::().unwrap()); + Python::with_gil(|py| { + let list = PyList::new(py, &[2, 3, 5, 7]); + assert_eq!(2, list.get_item(0).extract::().unwrap()); + assert_eq!(3, list.get_item(1).extract::().unwrap()); + assert_eq!(5, list.get_item(2).extract::().unwrap()); + assert_eq!(7, list.get_item(3).extract::().unwrap()); + }); } #[test] #[should_panic] fn test_get_item_invalid() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let list = PyList::new(py, &[2, 3, 5, 7]); - list.get_item(-1); + Python::with_gil(|py| { + let list = PyList::new(py, &[2, 3, 5, 7]); + list.get_item(-1); + }); } #[test] fn test_set_item() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let list = PyList::new(py, &[2, 3, 5, 7]); - let val = 42i32.to_object(py); - assert_eq!(2, list.get_item(0).extract::().unwrap()); - list.set_item(0, val).unwrap(); - assert_eq!(42, list.get_item(0).extract::().unwrap()); + Python::with_gil(|py| { + let list = PyList::new(py, &[2, 3, 5, 7]); + let val = 42i32.to_object(py); + assert_eq!(2, list.get_item(0).extract::().unwrap()); + list.set_item(0, val).unwrap(); + assert_eq!(42, list.get_item(0).extract::().unwrap()); + }); } #[test] fn test_set_item_refcnt() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let cnt; + { + let _pool = unsafe { crate::GILPool::new() }; + let v = vec![2]; + let ob = v.to_object(py); + let list = ::try_from(ob.as_ref(py)).unwrap(); + let none = py.None(); + cnt = none.get_refcnt(py); + list.set_item(0, none).unwrap(); + } - let cnt; - { - let _pool = unsafe { crate::GILPool::new() }; - let v = vec![2]; - let ob = v.to_object(py); - let list = ::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)); + assert_eq!(cnt, py.None().get_refcnt(py)); + }); } #[test] fn test_insert() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let list = PyList::new(py, &[2, 3, 5, 7]); - let val = 42i32.to_object(py); - assert_eq!(4, list.len()); - assert_eq!(2, list.get_item(0).extract::().unwrap()); - list.insert(0, val).unwrap(); - assert_eq!(5, list.len()); - assert_eq!(42, list.get_item(0).extract::().unwrap()); - assert_eq!(2, list.get_item(1).extract::().unwrap()); + Python::with_gil(|py| { + let list = PyList::new(py, &[2, 3, 5, 7]); + let val = 42i32.to_object(py); + assert_eq!(4, list.len()); + assert_eq!(2, list.get_item(0).extract::().unwrap()); + list.insert(0, val).unwrap(); + assert_eq!(5, list.len()); + assert_eq!(42, list.get_item(0).extract::().unwrap()); + assert_eq!(2, list.get_item(1).extract::().unwrap()); + }); } #[test] fn test_insert_refcnt() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + 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; - { - 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)); + assert_eq!(cnt, py.None().get_refcnt(py)); + }); } #[test] fn test_append() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let list = PyList::new(py, &[2]); - list.append(3).unwrap(); - assert_eq!(2, list.get_item(0).extract::().unwrap()); - assert_eq!(3, list.get_item(1).extract::().unwrap()); + Python::with_gil(|py| { + let list = PyList::new(py, &[2]); + list.append(3).unwrap(); + assert_eq!(2, list.get_item(0).extract::().unwrap()); + assert_eq!(3, list.get_item(1).extract::().unwrap()); + }); } #[test] fn test_append_refcnt() { - let gil = Python::acquire_gil(); - 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.append(none).unwrap(); - } - assert_eq!(cnt, py.None().get_refcnt(py)); + Python::with_gil(|py| { + let cnt; + { + let _pool = unsafe { crate::GILPool::new() }; + let list = PyList::empty(py); + let none = py.None(); + cnt = none.get_refcnt(py); + list.append(none).unwrap(); + } + assert_eq!(cnt, py.None().get_refcnt(py)); + }); } #[test] fn test_iter() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v = vec![2, 3, 5, 7]; - let list = PyList::new(py, &v); - let mut idx = 0; - for el in list.iter() { - assert_eq!(v[idx], el.extract::().unwrap()); - idx += 1; - } - assert_eq!(idx, v.len()); + Python::with_gil(|py| { + let v = vec![2, 3, 5, 7]; + let list = PyList::new(py, &v); + let mut idx = 0; + for el in list.iter() { + assert_eq!(v[idx], el.extract::().unwrap()); + idx += 1; + } + assert_eq!(idx, v.len()); + }); } #[test] fn test_iter_size_hint() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v = vec![2, 3, 5, 7]; - let ob = v.to_object(py); - let list = ::try_from(ob.as_ref(py)).unwrap(); + Python::with_gil(|py| { + let v = vec![2, 3, 5, 7]; + let ob = v.to_object(py); + let list = ::try_from(ob.as_ref(py)).unwrap(); - let mut iter = list.iter(); - assert_eq!(iter.size_hint(), (v.len(), Some(v.len()))); - iter.next(); - assert_eq!(iter.size_hint(), (v.len() - 1, Some(v.len() - 1))); + let mut iter = list.iter(); + assert_eq!(iter.size_hint(), (v.len(), Some(v.len()))); + iter.next(); + assert_eq!(iter.size_hint(), (v.len() - 1, Some(v.len() - 1))); - // Exhust iterator. - for _ in &mut iter {} + // Exhust iterator. + for _ in &mut iter {} - assert_eq!(iter.size_hint(), (0, Some(0))); + assert_eq!(iter.size_hint(), (0, Some(0))); + }); } #[test] fn test_into_iter() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let list = PyList::new(py, &[1, 2, 3, 4]); - for (i, item) in list.iter().enumerate() { - assert_eq!((i + 1) as i32, item.extract::().unwrap()); - } + Python::with_gil(|py| { + let list = PyList::new(py, &[1, 2, 3, 4]); + for (i, item) in list.iter().enumerate() { + assert_eq!((i + 1) as i32, item.extract::().unwrap()); + } + }); } #[test] fn test_extract() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v = vec![2, 3, 5, 7]; - let list = PyList::new(py, &v); - let v2 = list.as_ref().extract::>().unwrap(); - assert_eq!(v, v2); + Python::with_gil(|py| { + let v = vec![2, 3, 5, 7]; + let list = PyList::new(py, &v); + let v2 = list.as_ref().extract::>().unwrap(); + assert_eq!(v, v2); + }); } #[test] fn test_sort() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v = vec![7, 3, 2, 5]; - let list = PyList::new(py, &v); - assert_eq!(7, list.get_item(0).extract::().unwrap()); - assert_eq!(3, list.get_item(1).extract::().unwrap()); - assert_eq!(2, list.get_item(2).extract::().unwrap()); - assert_eq!(5, list.get_item(3).extract::().unwrap()); - list.sort().unwrap(); - assert_eq!(2, list.get_item(0).extract::().unwrap()); - assert_eq!(3, list.get_item(1).extract::().unwrap()); - assert_eq!(5, list.get_item(2).extract::().unwrap()); - assert_eq!(7, list.get_item(3).extract::().unwrap()); + Python::with_gil(|py| { + let v = vec![7, 3, 2, 5]; + let list = PyList::new(py, &v); + assert_eq!(7, list.get_item(0).extract::().unwrap()); + assert_eq!(3, list.get_item(1).extract::().unwrap()); + assert_eq!(2, list.get_item(2).extract::().unwrap()); + assert_eq!(5, list.get_item(3).extract::().unwrap()); + list.sort().unwrap(); + assert_eq!(2, list.get_item(0).extract::().unwrap()); + assert_eq!(3, list.get_item(1).extract::().unwrap()); + assert_eq!(5, list.get_item(2).extract::().unwrap()); + assert_eq!(7, list.get_item(3).extract::().unwrap()); + }); } #[test] fn test_reverse() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v = vec![2, 3, 5, 7]; - let list = PyList::new(py, &v); - assert_eq!(2, list.get_item(0).extract::().unwrap()); - assert_eq!(3, list.get_item(1).extract::().unwrap()); - assert_eq!(5, list.get_item(2).extract::().unwrap()); - assert_eq!(7, list.get_item(3).extract::().unwrap()); - list.reverse().unwrap(); - assert_eq!(7, list.get_item(0).extract::().unwrap()); - assert_eq!(5, list.get_item(1).extract::().unwrap()); - assert_eq!(3, list.get_item(2).extract::().unwrap()); - assert_eq!(2, list.get_item(3).extract::().unwrap()); + Python::with_gil(|py| { + let v = vec![2, 3, 5, 7]; + let list = PyList::new(py, &v); + assert_eq!(2, list.get_item(0).extract::().unwrap()); + assert_eq!(3, list.get_item(1).extract::().unwrap()); + assert_eq!(5, list.get_item(2).extract::().unwrap()); + assert_eq!(7, list.get_item(3).extract::().unwrap()); + list.reverse().unwrap(); + assert_eq!(7, list.get_item(0).extract::().unwrap()); + assert_eq!(5, list.get_item(1).extract::().unwrap()); + assert_eq!(3, list.get_item(2).extract::().unwrap()); + assert_eq!(2, list.get_item(3).extract::().unwrap()); + }); } #[test] fn test_array_into_py() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let array: PyObject = [1, 2].into_py(py); - let list = ::try_from(array.as_ref(py)).unwrap(); - assert_eq!(1, list.get_item(0).extract::().unwrap()); - assert_eq!(2, list.get_item(1).extract::().unwrap()); + Python::with_gil(|py| { + let array: PyObject = [1, 2].into_py(py); + let list = ::try_from(array.as_ref(py)).unwrap(); + assert_eq!(1, list.get_item(0).extract::().unwrap()); + assert_eq!(2, list.get_item(1).extract::().unwrap()); + }); } } diff --git a/src/types/num.rs b/src/types/num.rs index 33953a03..f2151589 100644 --- a/src/types/num.rs +++ b/src/types/num.rs @@ -364,45 +364,45 @@ mod tests { #[test] fn test_u32_max() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v = std::u32::MAX; - let obj = v.to_object(py); - assert_eq!(v, obj.extract::(py).unwrap()); - assert_eq!(u64::from(v), obj.extract::(py).unwrap()); - assert!(obj.extract::(py).is_err()); + Python::with_gil(|py| { + let v = std::u32::MAX; + let obj = v.to_object(py); + assert_eq!(v, obj.extract::(py).unwrap()); + assert_eq!(u64::from(v), obj.extract::(py).unwrap()); + assert!(obj.extract::(py).is_err()); + }); } #[test] fn test_i64_max() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v = std::i64::MAX; - let obj = v.to_object(py); - assert_eq!(v, obj.extract::(py).unwrap()); - assert_eq!(v as u64, obj.extract::(py).unwrap()); - assert!(obj.extract::(py).is_err()); + Python::with_gil(|py| { + let v = std::i64::MAX; + let obj = v.to_object(py); + assert_eq!(v, obj.extract::(py).unwrap()); + assert_eq!(v as u64, obj.extract::(py).unwrap()); + assert!(obj.extract::(py).is_err()); + }); } #[test] fn test_i64_min() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v = std::i64::MIN; - let obj = v.to_object(py); - assert_eq!(v, obj.extract::(py).unwrap()); - assert!(obj.extract::(py).is_err()); - assert!(obj.extract::(py).is_err()); + Python::with_gil(|py| { + let v = std::i64::MIN; + let obj = v.to_object(py); + assert_eq!(v, obj.extract::(py).unwrap()); + assert!(obj.extract::(py).is_err()); + assert!(obj.extract::(py).is_err()); + }); } #[test] fn test_u64_max() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v = std::u64::MAX; - let obj = v.to_object(py); - assert_eq!(v, obj.extract::(py).unwrap()); - assert!(obj.extract::(py).is_err()); + Python::with_gil(|py| { + let v = std::u64::MAX; + let obj = v.to_object(py); + assert_eq!(v, obj.extract::(py).unwrap()); + assert!(obj.extract::(py).is_err()); + }); } macro_rules! test_common ( @@ -414,32 +414,31 @@ mod tests { #[test] fn from_py_string_type_error() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py|{ + let obj = ("123").to_object(py); let err = obj.extract::<$t>(py).unwrap_err(); assert!(err.is_instance::(py)); + }); } #[test] fn from_py_float_type_error() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py|{ let obj = (12.3).to_object(py); let err = obj.extract::<$t>(py).unwrap_err(); - assert!(err.is_instance::(py)); + assert!(err.is_instance::(py));}); } #[test] fn to_py_object_and_back() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py|{ let val = 123 as $t; 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);}); } } ) diff --git a/src/types/sequence.rs b/src/types/sequence.rs index c9a93188..9568135b 100644 --- a/src/types/sequence.rs +++ b/src/types/sequence.rs @@ -338,80 +338,79 @@ mod tests { fn get_object() -> PyObject { // Convenience function for getting a single unique object - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| -> PyObject { + 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] fn test_numbers_are_not_sequences() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v = 42i32; - assert!(::try_from(v.to_object(py).as_ref(py)).is_err()); + Python::with_gil(|py| { + let v = 42i32; + assert!(::try_from(v.to_object(py).as_ref(py)).is_err()); + }); } #[test] fn test_strings_are_sequences() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v = "London Calling"; - assert!(::try_from(v.to_object(py).as_ref(py)).is_ok()); + Python::with_gil(|py| { + let v = "London Calling"; + assert!(::try_from(v.to_object(py).as_ref(py)).is_ok()); + }); } #[test] fn test_seq_empty() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v: Vec = vec![]; - let ob = v.to_object(py); - let seq = ob.cast_as::(py).unwrap(); - assert_eq!(0, seq.len().unwrap()); + Python::with_gil(|py| { + let v: Vec = vec![]; + let ob = v.to_object(py); + let seq = ob.cast_as::(py).unwrap(); + assert_eq!(0, seq.len().unwrap()); - let needle = 7i32.to_object(py); - assert!(!seq.contains(&needle).unwrap()); + let needle = 7i32.to_object(py); + assert!(!seq.contains(&needle).unwrap()); + }); } #[test] fn test_seq_contains() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v: Vec = vec![1, 1, 2, 3, 5, 8]; - let ob = v.to_object(py); - let seq = ob.cast_as::(py).unwrap(); - assert_eq!(6, seq.len().unwrap()); + Python::with_gil(|py| { + let v: Vec = vec![1, 1, 2, 3, 5, 8]; + let ob = v.to_object(py); + let seq = ob.cast_as::(py).unwrap(); + assert_eq!(6, seq.len().unwrap()); - let bad_needle = 7i32.to_object(py); - assert!(!seq.contains(&bad_needle).unwrap()); + let bad_needle = 7i32.to_object(py); + assert!(!seq.contains(&bad_needle).unwrap()); - let good_needle = 8i32.to_object(py); - assert!(seq.contains(&good_needle).unwrap()); + let good_needle = 8i32.to_object(py); + assert!(seq.contains(&good_needle).unwrap()); - let type_coerced_needle = 8f32.to_object(py); - assert!(seq.contains(&type_coerced_needle).unwrap()); + let type_coerced_needle = 8f32.to_object(py); + assert!(seq.contains(&type_coerced_needle).unwrap()); + }); } #[test] fn test_seq_get_item() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v: Vec = vec![1, 1, 2, 3, 5, 8]; - let ob = v.to_object(py); - let seq = ob.cast_as::(py).unwrap(); - assert_eq!(1, seq.get_item(0).unwrap().extract::().unwrap()); - assert_eq!(1, seq.get_item(1).unwrap().extract::().unwrap()); - assert_eq!(2, seq.get_item(2).unwrap().extract::().unwrap()); - assert_eq!(3, seq.get_item(3).unwrap().extract::().unwrap()); - assert_eq!(5, seq.get_item(4).unwrap().extract::().unwrap()); - assert_eq!(8, seq.get_item(5).unwrap().extract::().unwrap()); - assert_eq!(8, seq.get_item(-1).unwrap().extract::().unwrap()); - assert_eq!(5, seq.get_item(-2).unwrap().extract::().unwrap()); - assert_eq!(3, seq.get_item(-3).unwrap().extract::().unwrap()); - assert_eq!(2, seq.get_item(-4).unwrap().extract::().unwrap()); - assert_eq!(1, seq.get_item(-5).unwrap().extract::().unwrap()); - assert!(seq.get_item(10).is_err()); + Python::with_gil(|py| { + let v: Vec = vec![1, 1, 2, 3, 5, 8]; + let ob = v.to_object(py); + let seq = ob.cast_as::(py).unwrap(); + assert_eq!(1, seq.get_item(0).unwrap().extract::().unwrap()); + assert_eq!(1, seq.get_item(1).unwrap().extract::().unwrap()); + assert_eq!(2, seq.get_item(2).unwrap().extract::().unwrap()); + assert_eq!(3, seq.get_item(3).unwrap().extract::().unwrap()); + assert_eq!(5, seq.get_item(4).unwrap().extract::().unwrap()); + assert_eq!(8, seq.get_item(5).unwrap().extract::().unwrap()); + assert_eq!(8, seq.get_item(-1).unwrap().extract::().unwrap()); + assert_eq!(5, seq.get_item(-2).unwrap().extract::().unwrap()); + assert_eq!(3, seq.get_item(-3).unwrap().extract::().unwrap()); + assert_eq!(2, seq.get_item(-4).unwrap().extract::().unwrap()); + assert_eq!(1, seq.get_item(-5).unwrap().extract::().unwrap()); + assert!(seq.get_item(10).is_err()); + }); } // fn test_get_slice() {} @@ -420,259 +419,257 @@ mod tests { #[test] fn test_seq_del_item() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v: Vec = vec![1, 1, 2, 3, 5, 8]; - let ob = v.to_object(py); - let seq = ob.cast_as::(py).unwrap(); - assert!(seq.del_item(10).is_err()); - assert_eq!(1, seq.get_item(0).unwrap().extract::().unwrap()); - assert!(seq.del_item(0).is_ok()); - assert_eq!(1, seq.get_item(0).unwrap().extract::().unwrap()); - assert!(seq.del_item(0).is_ok()); - assert_eq!(2, seq.get_item(0).unwrap().extract::().unwrap()); - assert!(seq.del_item(0).is_ok()); - assert_eq!(3, seq.get_item(0).unwrap().extract::().unwrap()); - assert!(seq.del_item(0).is_ok()); - assert_eq!(5, seq.get_item(0).unwrap().extract::().unwrap()); - assert!(seq.del_item(0).is_ok()); - assert_eq!(8, seq.get_item(0).unwrap().extract::().unwrap()); - assert!(seq.del_item(0).is_ok()); - assert_eq!(0, seq.len().unwrap()); - assert!(seq.del_item(0).is_err()); + Python::with_gil(|py| { + let v: Vec = vec![1, 1, 2, 3, 5, 8]; + let ob = v.to_object(py); + let seq = ob.cast_as::(py).unwrap(); + assert!(seq.del_item(10).is_err()); + assert_eq!(1, seq.get_item(0).unwrap().extract::().unwrap()); + assert!(seq.del_item(0).is_ok()); + assert_eq!(1, seq.get_item(0).unwrap().extract::().unwrap()); + assert!(seq.del_item(0).is_ok()); + assert_eq!(2, seq.get_item(0).unwrap().extract::().unwrap()); + assert!(seq.del_item(0).is_ok()); + assert_eq!(3, seq.get_item(0).unwrap().extract::().unwrap()); + assert!(seq.del_item(0).is_ok()); + assert_eq!(5, seq.get_item(0).unwrap().extract::().unwrap()); + assert!(seq.del_item(0).is_ok()); + assert_eq!(8, seq.get_item(0).unwrap().extract::().unwrap()); + assert!(seq.del_item(0).is_ok()); + assert_eq!(0, seq.len().unwrap()); + assert!(seq.del_item(0).is_err()); + }); } #[test] fn test_seq_set_item() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v: Vec = vec![1, 2]; - let ob = v.to_object(py); - let seq = ob.cast_as::(py).unwrap(); - assert_eq!(2, seq.get_item(1).unwrap().extract::().unwrap()); - assert!(seq.set_item(1, 10).is_ok()); - assert_eq!(10, seq.get_item(1).unwrap().extract::().unwrap()); + Python::with_gil(|py| { + let v: Vec = vec![1, 2]; + let ob = v.to_object(py); + let seq = ob.cast_as::(py).unwrap(); + assert_eq!(2, seq.get_item(1).unwrap().extract::().unwrap()); + assert!(seq.set_item(1, 10).is_ok()); + assert_eq!(10, seq.get_item(1).unwrap().extract::().unwrap()); + }); } #[test] fn test_seq_set_item_refcnt() { let obj = get_object(); - { - let gil = Python::acquire_gil(); - let py = gil.python(); + + Python::with_gil(|py| { let v: Vec = vec![1, 2]; let ob = v.to_object(py); let seq = ob.cast_as::(py).unwrap(); assert!(seq.set_item(1, &obj).is_ok()); assert!(seq.get_item(1).unwrap().as_ptr() == obj.as_ptr()); - } - { - let gil = Python::acquire_gil(); - let py = gil.python(); + }); + + Python::with_gil(|py| { assert_eq!(1, obj.get_refcnt(py)); - } + }); } #[test] fn test_seq_index() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v: Vec = vec![1, 1, 2, 3, 5, 8]; - let ob = v.to_object(py); - let seq = ob.cast_as::(py).unwrap(); - assert_eq!(0, seq.index(1i32).unwrap()); - assert_eq!(2, seq.index(2i32).unwrap()); - assert_eq!(3, seq.index(3i32).unwrap()); - assert_eq!(4, seq.index(5i32).unwrap()); - assert_eq!(5, seq.index(8i32).unwrap()); - assert!(seq.index(42i32).is_err()); + Python::with_gil(|py| { + let v: Vec = vec![1, 1, 2, 3, 5, 8]; + let ob = v.to_object(py); + let seq = ob.cast_as::(py).unwrap(); + assert_eq!(0, seq.index(1i32).unwrap()); + assert_eq!(2, seq.index(2i32).unwrap()); + assert_eq!(3, seq.index(3i32).unwrap()); + assert_eq!(4, seq.index(5i32).unwrap()); + assert_eq!(5, seq.index(8i32).unwrap()); + assert!(seq.index(42i32).is_err()); + }); } #[test] #[cfg(not(PyPy))] fn test_seq_count() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v: Vec = vec![1, 1, 2, 3, 5, 8]; - let ob = v.to_object(py); - let seq = ob.cast_as::(py).unwrap(); - assert_eq!(2, seq.count(1i32).unwrap()); - assert_eq!(1, seq.count(2i32).unwrap()); - assert_eq!(1, seq.count(3i32).unwrap()); - assert_eq!(1, seq.count(5i32).unwrap()); - assert_eq!(1, seq.count(8i32).unwrap()); - assert_eq!(0, seq.count(42i32).unwrap()); + Python::with_gil(|py| { + let v: Vec = vec![1, 1, 2, 3, 5, 8]; + let ob = v.to_object(py); + let seq = ob.cast_as::(py).unwrap(); + assert_eq!(2, seq.count(1i32).unwrap()); + assert_eq!(1, seq.count(2i32).unwrap()); + assert_eq!(1, seq.count(3i32).unwrap()); + assert_eq!(1, seq.count(5i32).unwrap()); + assert_eq!(1, seq.count(8i32).unwrap()); + assert_eq!(0, seq.count(42i32).unwrap()); + }); } #[test] fn test_seq_iter() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v: Vec = vec![1, 1, 2, 3, 5, 8]; - let ob = v.to_object(py); - let seq = ob.cast_as::(py).unwrap(); - let mut idx = 0; - for el in seq.iter().unwrap() { - assert_eq!(v[idx], el.unwrap().extract::().unwrap()); - idx += 1; - } - assert_eq!(idx, v.len()); + Python::with_gil(|py| { + let v: Vec = vec![1, 1, 2, 3, 5, 8]; + let ob = v.to_object(py); + let seq = ob.cast_as::(py).unwrap(); + let mut idx = 0; + for el in seq.iter().unwrap() { + assert_eq!(v[idx], el.unwrap().extract::().unwrap()); + idx += 1; + } + assert_eq!(idx, v.len()); + }); } #[test] fn test_seq_strings() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v = vec!["It", "was", "the", "worst", "of", "times"]; - let ob = v.to_object(py); - let seq = ob.cast_as::(py).unwrap(); + Python::with_gil(|py| { + let v = vec!["It", "was", "the", "worst", "of", "times"]; + let ob = v.to_object(py); + let seq = ob.cast_as::(py).unwrap(); - let bad_needle = "blurst".to_object(py); - assert!(!seq.contains(bad_needle).unwrap()); + let bad_needle = "blurst".to_object(py); + assert!(!seq.contains(bad_needle).unwrap()); - let good_needle = "worst".to_object(py); - assert!(seq.contains(good_needle).unwrap()); + let good_needle = "worst".to_object(py); + assert!(seq.contains(good_needle).unwrap()); + }); } #[test] fn test_seq_concat() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v: Vec = vec![1, 2, 3]; - let ob = v.to_object(py); - let seq = ob.cast_as::(py).unwrap(); - let concat_seq = seq.concat(seq).unwrap(); - assert_eq!(6, concat_seq.len().unwrap()); - let concat_v: Vec = vec![1, 2, 3, 1, 2, 3]; - for (el, cc) in concat_seq.iter().unwrap().zip(concat_v) { - assert_eq!(cc, el.unwrap().extract::().unwrap()); - } + Python::with_gil(|py| { + let v: Vec = vec![1, 2, 3]; + let ob = v.to_object(py); + let seq = ob.cast_as::(py).unwrap(); + let concat_seq = seq.concat(seq).unwrap(); + assert_eq!(6, concat_seq.len().unwrap()); + let concat_v: Vec = vec![1, 2, 3, 1, 2, 3]; + for (el, cc) in concat_seq.iter().unwrap().zip(concat_v) { + assert_eq!(cc, el.unwrap().extract::().unwrap()); + } + }); } #[test] fn test_seq_concat_string() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v = "string"; - let ob = v.to_object(py); - let seq = ob.cast_as::(py).unwrap(); - let concat_seq = seq.concat(seq).unwrap(); - assert_eq!(12, concat_seq.len().unwrap()); - /*let concat_v = "stringstring".to_owned(); - for (el, cc) in seq.iter(py).unwrap().zip(concat_v.chars()) { - assert_eq!(cc, el.unwrap().extract::(py).unwrap()); //TODO: extract::() is not implemented - }*/ + Python::with_gil(|py| { + let v = "string"; + let ob = v.to_object(py); + let seq = ob.cast_as::(py).unwrap(); + let concat_seq = seq.concat(seq).unwrap(); + assert_eq!(12, concat_seq.len().unwrap()); + let concat_v = "stringstring".to_owned(); + for (el, cc) in seq.iter().unwrap().zip(concat_v.chars()) { + assert_eq!(cc, el.unwrap().extract::().unwrap()); + } + }); } #[test] fn test_seq_repeat() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v = vec!["foo", "bar"]; - let ob = v.to_object(py); - let seq = ob.cast_as::(py).unwrap(); - let repeat_seq = seq.repeat(3).unwrap(); - assert_eq!(6, repeat_seq.len().unwrap()); - let repeated = vec!["foo", "bar", "foo", "bar", "foo", "bar"]; - for (el, rpt) in repeat_seq.iter().unwrap().zip(repeated.iter()) { - assert_eq!(*rpt, el.unwrap().extract::().unwrap()); - } + Python::with_gil(|py| { + let v = vec!["foo", "bar"]; + let ob = v.to_object(py); + let seq = ob.cast_as::(py).unwrap(); + let repeat_seq = seq.repeat(3).unwrap(); + assert_eq!(6, repeat_seq.len().unwrap()); + let repeated = vec!["foo", "bar", "foo", "bar", "foo", "bar"]; + for (el, rpt) in repeat_seq.iter().unwrap().zip(repeated.iter()) { + assert_eq!(*rpt, el.unwrap().extract::().unwrap()); + } + }); } #[test] fn test_list_coercion() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v = vec!["foo", "bar"]; - let ob = v.to_object(py); - let seq = ob.cast_as::(py).unwrap(); - assert!(seq.list().is_ok()); + Python::with_gil(|py| { + let v = vec!["foo", "bar"]; + let ob = v.to_object(py); + let seq = ob.cast_as::(py).unwrap(); + assert!(seq.list().is_ok()); + }); } #[test] fn test_strings_coerce_to_lists() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v = "foo"; - let ob = v.to_object(py); - let seq = ::try_from(ob.as_ref(py)).unwrap(); - assert!(seq.list().is_ok()); + Python::with_gil(|py| { + let v = "foo"; + let ob = v.to_object(py); + let seq = ::try_from(ob.as_ref(py)).unwrap(); + assert!(seq.list().is_ok()); + }); } #[test] fn test_tuple_coercion() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v = ("foo", "bar"); - let ob = v.to_object(py); - let seq = ob.cast_as::(py).unwrap(); - assert!(seq.tuple().is_ok()); + Python::with_gil(|py| { + let v = ("foo", "bar"); + let ob = v.to_object(py); + let seq = ob.cast_as::(py).unwrap(); + assert!(seq.tuple().is_ok()); + }); } #[test] fn test_lists_coerce_to_tuples() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v = vec!["foo", "bar"]; - let ob = v.to_object(py); - let seq = ob.cast_as::(py).unwrap(); - assert!(seq.tuple().is_ok()); + Python::with_gil(|py| { + let v = vec!["foo", "bar"]; + let ob = v.to_object(py); + let seq = ob.cast_as::(py).unwrap(); + assert!(seq.tuple().is_ok()); + }); } #[test] fn test_extract_tuple_to_vec() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v: Vec = py.eval("(1, 2)", None, None).unwrap().extract().unwrap(); - assert!(v == [1, 2]); + Python::with_gil(|py| { + let v: Vec = py.eval("(1, 2)", None, None).unwrap().extract().unwrap(); + assert!(v == [1, 2]); + }); } #[test] fn test_extract_range_to_vec() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v: Vec = py - .eval("range(1, 5)", None, None) - .unwrap() - .extract() - .unwrap(); - assert!(v == [1, 2, 3, 4]); + Python::with_gil(|py| { + let v: Vec = py + .eval("range(1, 5)", None, None) + .unwrap() + .extract() + .unwrap(); + assert!(v == [1, 2, 3, 4]); + }); } #[test] fn test_extract_bytearray_to_vec() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v: Vec = py - .eval("bytearray(b'abc')", None, None) - .unwrap() - .extract() - .unwrap(); - assert!(v == b"abc"); + Python::with_gil(|py| { + let v: Vec = py + .eval("bytearray(b'abc')", None, None) + .unwrap() + .extract() + .unwrap(); + assert!(v == b"abc"); + }); } #[test] fn test_seq_try_from_unchecked() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let v = vec!["foo", "bar"]; - let ob = v.to_object(py); - let seq = ob.cast_as::(py).unwrap(); - let type_ptr = seq.as_ref(); - let seq_from = unsafe { ::try_from_unchecked(type_ptr) }; - assert!(seq_from.list().is_ok()); + Python::with_gil(|py| { + let v = vec!["foo", "bar"]; + let ob = v.to_object(py); + let seq = ob.cast_as::(py).unwrap(); + let type_ptr = seq.as_ref(); + let seq_from = unsafe { ::try_from_unchecked(type_ptr) }; + assert!(seq_from.list().is_ok()); + }); } #[test] fn test_is_empty() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let list = vec![1].to_object(py); - let seq = list.cast_as::(py).unwrap(); - assert!(!seq.is_empty().unwrap()); - let vec: Vec = Vec::new(); - let empty_list = vec.to_object(py); - let empty_seq = empty_list.cast_as::(py).unwrap(); - assert!(empty_seq.is_empty().unwrap()); + Python::with_gil(|py| { + let list = vec![1].to_object(py); + let seq = list.cast_as::(py).unwrap(); + assert!(!seq.is_empty().unwrap()); + let vec: Vec = Vec::new(); + let empty_list = vec.to_object(py); + let empty_seq = empty_list.cast_as::(py).unwrap(); + assert!(empty_seq.is_empty().unwrap()); + }); } } diff --git a/src/types/set.rs b/src/types/set.rs index 00632333..8bd46986 100644 --- a/src/types/set.rs +++ b/src/types/set.rs @@ -383,24 +383,22 @@ mod hashbrown_hashset_conversion { #[test] fn test_extract_hashbrown_hashset() { - let gil = Python::acquire_gil(); - let py = gil.python(); - - let set = PySet::new(py, &[1, 2, 3, 4, 5]).unwrap(); - let hash_set: hashbrown::HashSet = set.extract().unwrap(); - assert_eq!(hash_set, [1, 2, 3, 4, 5].iter().copied().collect()); + Python::with_gil(|py| { + let set = PySet::new(py, &[1, 2, 3, 4, 5]).unwrap(); + let hash_set: hashbrown::HashSet = set.extract().unwrap(); + assert_eq!(hash_set, [1, 2, 3, 4, 5].iter().copied().collect()); + }); } #[test] fn test_hashbrown_hashset_into_py() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let hs: hashbrown::HashSet = [1, 2, 3, 4, 5].iter().cloned().collect(); - let hs: hashbrown::HashSet = [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] fn test_set_new() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let set = PySet::new(py, &[1]).unwrap(); + assert_eq!(1, set.len()); - let set = PySet::new(py, &[1]).unwrap(); - assert_eq!(1, set.len()); - - let v = vec![1]; - assert!(PySet::new(py, &[v]).is_err()); + let v = vec![1]; + assert!(PySet::new(py, &[v]).is_err()); + }); } #[test] fn test_set_empty() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let set = PySet::empty(py).unwrap(); - assert_eq!(0, set.len()); + Python::with_gil(|py| { + let set = PySet::empty(py).unwrap(); + assert_eq!(0, set.len()); + }); } #[test] fn test_set_len() { - let gil = Python::acquire_gil(); - let py = gil.python(); - - let mut v = HashSet::new(); - let ob = v.to_object(py); - let set = ::try_from(ob.as_ref(py)).unwrap(); - assert_eq!(0, set.len()); - v.insert(7); - let ob = v.to_object(py); - let set2 = ::try_from(ob.as_ref(py)).unwrap(); - assert_eq!(1, set2.len()); + Python::with_gil(|py| { + let mut v = HashSet::new(); + let ob = v.to_object(py); + let set = ::try_from(ob.as_ref(py)).unwrap(); + assert_eq!(0, set.len()); + v.insert(7); + let ob = v.to_object(py); + let set2 = ::try_from(ob.as_ref(py)).unwrap(); + assert_eq!(1, set2.len()); + }); } #[test] fn test_set_clear() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let set = PySet::new(py, &[1]).unwrap(); - assert_eq!(1, set.len()); - set.clear(); - assert_eq!(0, set.len()); + Python::with_gil(|py| { + let set = PySet::new(py, &[1]).unwrap(); + assert_eq!(1, set.len()); + set.clear(); + assert_eq!(0, set.len()); + }); } #[test] fn test_set_contains() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let set = PySet::new(py, &[1]).unwrap(); - assert!(set.contains(1).unwrap()); + Python::with_gil(|py| { + let set = PySet::new(py, &[1]).unwrap(); + assert!(set.contains(1).unwrap()); + }); } #[test] fn test_set_discard() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let set = PySet::new(py, &[1]).unwrap(); - set.discard(2); - assert_eq!(1, set.len()); - set.discard(1); - assert_eq!(0, set.len()); + Python::with_gil(|py| { + let set = PySet::new(py, &[1]).unwrap(); + set.discard(2); + assert_eq!(1, set.len()); + set.discard(1); + assert_eq!(0, set.len()); + }); } #[test] fn test_set_add() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let set = PySet::new(py, &[1, 2]).unwrap(); - set.add(1).unwrap(); // Add a dupliated element - assert!(set.contains(1).unwrap()); + Python::with_gil(|py| { + let set = PySet::new(py, &[1, 2]).unwrap(); + set.add(1).unwrap(); // Add a dupliated element + assert!(set.contains(1).unwrap()); + }); } #[test] fn test_set_pop() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let set = PySet::new(py, &[1]).unwrap(); - let val = set.pop(); - assert!(val.is_some()); - let val2 = set.pop(); - assert!(val2.is_none()); - assert!(py - .eval("print('Exception state should not be set.')", None, None) - .is_ok()); + Python::with_gil(|py| { + let set = PySet::new(py, &[1]).unwrap(); + let val = set.pop(); + assert!(val.is_some()); + let val2 = set.pop(); + assert!(val2.is_none()); + assert!(py + .eval("print('Exception state should not be set.')", None, None) + .is_ok()); + }); } #[test] fn test_set_iter() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + 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 - for el in set.iter() { - assert_eq!(1i32, el.extract().unwrap()); - } - - // intoiterator iteration - for el in set { - assert_eq!(1i32, el.extract().unwrap()); - } + // intoiterator iteration + for el in set { + assert_eq!(1i32, el.extract().unwrap()); + } + }); } #[test] fn test_set_iter_size_hint() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + 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)); - } else { - assert_eq!(iter.size_hint(), (1, Some(1))); - iter.next(); - assert_eq!(iter.size_hint(), (0, Some(0))); - } + if cfg!(Py_LIMITED_API) { + assert_eq!(iter.size_hint(), (0, None)); + } else { + assert_eq!(iter.size_hint(), (1, Some(1))); + iter.next(); + assert_eq!(iter.size_hint(), (0, Some(0))); + } + }); } #[test] fn test_frozenset_new_and_len() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let set = PyFrozenSet::new(py, &[1]).unwrap(); + assert_eq!(1, set.len()); - let set = PyFrozenSet::new(py, &[1]).unwrap(); - assert_eq!(1, set.len()); - - let v = vec![1]; - assert!(PyFrozenSet::new(py, &[v]).is_err()); + let v = vec![1]; + assert!(PyFrozenSet::new(py, &[v]).is_err()); + }); } #[test] fn test_frozenset_empty() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let set = PyFrozenSet::empty(py).unwrap(); - assert_eq!(0, set.len()); + Python::with_gil(|py| { + let set = PyFrozenSet::empty(py).unwrap(); + assert_eq!(0, set.len()); + }); } #[test] fn test_frozenset_contains() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let set = PyFrozenSet::new(py, &[1]).unwrap(); - assert!(set.contains(1).unwrap()); + Python::with_gil(|py| { + let set = PyFrozenSet::new(py, &[1]).unwrap(); + assert!(set.contains(1).unwrap()); + }); } #[test] fn test_frozenset_iter() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + 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::().unwrap()); + } - // iter method - for el in set.iter() { - assert_eq!(1i32, el.extract::().unwrap()); - } - - // intoiterator iteration - for el in set { - assert_eq!(1i32, el.extract::().unwrap()); - } + // intoiterator iteration + for el in set { + assert_eq!(1i32, el.extract::().unwrap()); + } + }); } #[test] fn test_extract_hashset() { - let gil = Python::acquire_gil(); - let py = gil.python(); - - let set = PySet::new(py, &[1, 2, 3, 4, 5]).unwrap(); - let hash_set: HashSet = set.extract().unwrap(); - assert_eq!(hash_set, [1, 2, 3, 4, 5].iter().copied().collect()); + Python::with_gil(|py| { + let set = PySet::new(py, &[1, 2, 3, 4, 5]).unwrap(); + let hash_set: HashSet = set.extract().unwrap(); + assert_eq!(hash_set, [1, 2, 3, 4, 5].iter().copied().collect()); + }); } #[test] fn test_extract_btreeset() { - let gil = Python::acquire_gil(); - let py = gil.python(); - - let set = PySet::new(py, &[1, 2, 3, 4, 5]).unwrap(); - let hash_set: BTreeSet = set.extract().unwrap(); - assert_eq!(hash_set, [1, 2, 3, 4, 5].iter().copied().collect()); + Python::with_gil(|py| { + let set = PySet::new(py, &[1, 2, 3, 4, 5]).unwrap(); + let hash_set: BTreeSet = set.extract().unwrap(); + assert_eq!(hash_set, [1, 2, 3, 4, 5].iter().copied().collect()); + }); } #[test] fn test_set_into_py() { - let gil = Python::acquire_gil(); - let py = gil.python(); + Python::with_gil(|py| { + let bt: BTreeSet = [1, 2, 3, 4, 5].iter().cloned().collect(); + let hs: HashSet = [1, 2, 3, 4, 5].iter().cloned().collect(); - let bt: BTreeSet = [1, 2, 3, 4, 5].iter().cloned().collect(); - let hs: HashSet = [1, 2, 3, 4, 5].iter().cloned().collect(); + let bto: PyObject = bt.clone().into_py(py); + let hso: PyObject = hs.clone().into_py(py); - let bto: PyObject = bt.clone().into_py(py); - let hso: PyObject = hs.clone().into_py(py); - - assert_eq!(bt, bto.extract(py).unwrap()); - assert_eq!(hs, hso.extract(py).unwrap()); + assert_eq!(bt, bto.extract(py).unwrap()); + assert_eq!(hs, hso.extract(py).unwrap()); + }); } } diff --git a/src/types/tuple.rs b/src/types/tuple.rs index 4c09b75f..b34422b9 100644 --- a/src/types/tuple.rs +++ b/src/types/tuple.rs @@ -322,77 +322,77 @@ mod tests { #[test] fn test_new() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let ob = PyTuple::new(py, &[1, 2, 3]); - assert_eq!(3, ob.len()); - let ob: &PyAny = ob.into(); - assert_eq!((1, 2, 3), ob.extract().unwrap()); + Python::with_gil(|py| { + let ob = PyTuple::new(py, &[1, 2, 3]); + assert_eq!(3, ob.len()); + let ob: &PyAny = ob.into(); + assert_eq!((1, 2, 3), ob.extract().unwrap()); - let mut map = HashSet::new(); - map.insert(1); - map.insert(2); - PyTuple::new(py, &map); + let mut map = HashSet::new(); + map.insert(1); + map.insert(2); + PyTuple::new(py, &map); + }); } #[test] fn test_len() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let ob = (1, 2, 3).to_object(py); - let tuple = ::try_from(ob.as_ref(py)).unwrap(); - assert_eq!(3, tuple.len()); - let ob: &PyAny = tuple.into(); - assert_eq!((1, 2, 3), ob.extract().unwrap()); + Python::with_gil(|py| { + let ob = (1, 2, 3).to_object(py); + let tuple = ::try_from(ob.as_ref(py)).unwrap(); + assert_eq!(3, tuple.len()); + let ob: &PyAny = tuple.into(); + assert_eq!((1, 2, 3), ob.extract().unwrap()); + }); } #[test] fn test_iter() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let ob = (1, 2, 3).to_object(py); - let tuple = ::try_from(ob.as_ref(py)).unwrap(); - assert_eq!(3, tuple.len()); - let mut iter = tuple.iter(); + Python::with_gil(|py| { + let ob = (1, 2, 3).to_object(py); + let tuple = ::try_from(ob.as_ref(py)).unwrap(); + assert_eq!(3, tuple.len()); + 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!(iter.size_hint(), (2, Some(2))); + assert_eq!(1, iter.next().unwrap().extract().unwrap()); + assert_eq!(iter.size_hint(), (2, Some(2))); - assert_eq!(2, iter.next().unwrap().extract().unwrap()); - assert_eq!(iter.size_hint(), (1, Some(1))); + assert_eq!(2, iter.next().unwrap().extract().unwrap()); + assert_eq!(iter.size_hint(), (1, Some(1))); - assert_eq!(3, iter.next().unwrap().extract().unwrap()); - assert_eq!(iter.size_hint(), (0, Some(0))); + assert_eq!(3, iter.next().unwrap().extract().unwrap()); + assert_eq!(iter.size_hint(), (0, Some(0))); + }); } #[test] fn test_into_iter() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let ob = (1, 2, 3).to_object(py); - let tuple = ::try_from(ob.as_ref(py)).unwrap(); - assert_eq!(3, tuple.len()); + Python::with_gil(|py| { + let ob = (1, 2, 3).to_object(py); + let tuple = ::try_from(ob.as_ref(py)).unwrap(); + assert_eq!(3, tuple.len()); - for (i, item) in tuple.iter().enumerate() { - assert_eq!(i + 1, item.extract().unwrap()); - } + for (i, item) in tuple.iter().enumerate() { + assert_eq!(i + 1, item.extract().unwrap()); + } + }); } #[test] #[cfg(not(Py_LIMITED_API))] fn test_as_slice() { - let gil = Python::acquire_gil(); - let py = gil.python(); - let ob = (1, 2, 3).to_object(py); - let tuple = ::try_from(ob.as_ref(py)).unwrap(); + Python::with_gil(|py| { + let ob = (1, 2, 3).to_object(py); + let tuple = ::try_from(ob.as_ref(py)).unwrap(); - let slice = tuple.as_slice(); - assert_eq!(3, slice.len()); - assert_eq!(1, slice[0].extract().unwrap()); - assert_eq!(2, slice[1].extract().unwrap()); - assert_eq!(3, slice[2].extract().unwrap()); + let slice = tuple.as_slice(); + assert_eq!(3, slice.len()); + assert_eq!(1, slice[0].extract().unwrap()); + assert_eq!(2, slice[1].extract().unwrap()); + assert_eq!(3, slice[2].extract().unwrap()); + }); } #[test] From 9fe3e2b2b8611a85be3c4f3606b938b062310728 Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Thu, 12 Aug 2021 11:52:56 +0200 Subject: [PATCH 2/3] Apply suggestions from code review Co-authored-by: David Hewitt <1939362+davidhewitt@users.noreply.github.com> --- src/instance.rs | 4 ++-- src/python.rs | 1 + src/types/iterator.rs | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/instance.rs b/src/instance.rs index 97d41f89..081cc714 100644 --- a/src/instance.rs +++ b/src/instance.rs @@ -880,12 +880,12 @@ mod tests { #[test] fn py_from_dict() { - let dict: Py = Python::with_gil(|py| -> Py { + let dict: Py = Python::with_gil(|py| { let native = PyDict::new(py); 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] diff --git a/src/python.rs b/src/python.rs index e546e21e..daa6d971 100644 --- a/src/python.rs +++ b/src/python.rs @@ -805,6 +805,7 @@ mod tests { } #[test] + #[cfg(not(Py_LIMITED_API))] fn test_acquire_gil() { const GIL_NOT_HELD: c_int = 0; const GIL_HELD: c_int = 1; diff --git a/src/types/iterator.rs b/src/types/iterator.rs index 0293647a..891f9ef5 100644 --- a/src/types/iterator.rs +++ b/src/types/iterator.rs @@ -119,7 +119,7 @@ mod tests { #[test] fn iter_refcnt() { - let (obj, count) = Python::with_gil(|py| -> (Py, isize) { + let (obj, count) = Python::with_gil(|py| { let obj = vec![10, 20].to_object(py); let count = obj.get_refcnt(py); (obj, count) From 596c3ff4b743b32f45b0d423ee75334324111eef Mon Sep 17 00:00:00 2001 From: mejrs Date: Thu, 12 Aug 2021 12:08:54 +0200 Subject: [PATCH 3/3] remove now unused imports --- src/instance.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/instance.rs b/src/instance.rs index 081cc714..fead8bab 100644 --- a/src/instance.rs +++ b/src/instance.rs @@ -863,7 +863,7 @@ impl PyObject { mod tests { use super::{Py, PyObject}; use crate::types::PyDict; - use crate::{ffi, AsPyPointer, Python}; + use crate::Python; #[test] fn test_call_for_non_existing_method() {