Skip to content

Commit

Permalink
Add test with generator to PyIterator
Browse files Browse the repository at this point in the history
  • Loading branch information
konstin committed Nov 2, 2018
1 parent da0d6ee commit 569db5f
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 3 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
9 changes: 6 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
33 changes: 33 additions & 0 deletions src/types/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<usize>().unwrap();
assert_eq!(actual, *expected)
}
}
}

0 comments on commit 569db5f

Please sign in to comment.