From 569db5fb02b1540ce6a710595ad7601c098cffd4 Mon Sep 17 00:00:00 2001 From: konstin Date: Fri, 2 Nov 2018 22:34:32 +0100 Subject: [PATCH] Add test with generator to PyIterator --- Cargo.toml | 1 + src/lib.rs | 9 ++++++--- src/types/iterator.rs | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 42e592ce73f..f50d0c34819 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,6 +29,7 @@ num-complex = { version = "0.2.1", optional = true } [dev-dependencies] assert_approx_eq = "1.0.0" docmatic = "0.1.2" +indoc = "0.2.8" [build-dependencies] regex = "1.0.5" diff --git a/src/lib.rs b/src/lib.rs index a9ea06c192b..5841450bd58 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -122,15 +122,18 @@ //! //! [`setuptools-rust`](https://github.com/PyO3/setuptools-rust) can be used to generate a python package and includes the commands above by default. See [examples/word-count](examples/word-count) and the associated setup.py. +#[cfg(test)] +#[macro_use] +extern crate assert_approx_eq; +#[cfg(test)] +#[macro_use] +extern crate indoc; // We need those types in the macro exports #[doc(hidden)] pub extern crate libc; // We need that reexport for wrap_function #[doc(hidden)] pub extern crate mashup; -#[cfg(test)] -#[macro_use] -extern crate assert_approx_eq; extern crate pyo3cls; extern crate spin; diff --git a/src/types/iterator.rs b/src/types/iterator.rs index 2f8a1ccc097..b46074a9542 100644 --- a/src/types/iterator.rs +++ b/src/types/iterator.rs @@ -136,3 +136,36 @@ mod tests { assert_eq!(count, none.get_refcnt()); } } + +#[cfg(test)] +mod test { + use crate::objectprotocol::ObjectProtocol; + use crate::GILGuard; + use crate::types::PyDict; + + #[test] + fn fibonacci_generator() { + let fibonacci_generator = indoc!( + r#" + def fibonacci(target): + a = 1 + b = 1 + for _ in range(target): + yield a + a, b = b, a + b + "# + ); + + let gil = GILGuard::acquire(); + let py = gil.python(); + + 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) + } + } +}