Add a Python test exploring from which types a Vec can be extracted.

This commit is contained in:
Adam Reichold 2022-09-18 20:09:23 +02:00
parent d72989f986
commit b2da5b20b1
4 changed files with 56 additions and 0 deletions

View File

@ -1,4 +1,5 @@
import nox
import platform
nox.options.sessions = ["test"]
@ -6,6 +7,8 @@ nox.options.sessions = ["test"]
@nox.session
def test(session):
session.install("-rrequirements-dev.txt")
if platform.system() == "Linux" and platform.python_implementation() == "CPython":
session.install("numpy>=1.16")
session.install("maturin")
session.run_always("maturin", "develop")
session.run("pytest")

View File

@ -11,6 +11,7 @@ pub mod othermod;
pub mod path;
pub mod pyclasses;
pub mod pyfunctions;
pub mod sequence;
pub mod subclassing;
#[pymodule]
@ -26,6 +27,7 @@ fn pyo3_pytests(py: Python<'_>, m: &PyModule) -> PyResult<()> {
m.add_wrapped(wrap_pymodule!(path::path))?;
m.add_wrapped(wrap_pymodule!(pyclasses::pyclasses))?;
m.add_wrapped(wrap_pymodule!(pyfunctions::pyfunctions))?;
m.add_wrapped(wrap_pymodule!(sequence::sequence))?;
m.add_wrapped(wrap_pymodule!(subclassing::subclassing))?;
// Inserting to sys.modules allows importing submodules nicely from Python
@ -42,6 +44,7 @@ fn pyo3_pytests(py: Python<'_>, m: &PyModule) -> PyResult<()> {
sys_modules.set_item("pyo3_pytests.path", m.getattr("path")?)?;
sys_modules.set_item("pyo3_pytests.pyclasses", m.getattr("pyclasses")?)?;
sys_modules.set_item("pyo3_pytests.pyfunctions", m.getattr("pyfunctions")?)?;
sys_modules.set_item("pyo3_pytests.sequence", m.getattr("sequence")?)?;
sys_modules.set_item("pyo3_pytests.subclassing", m.getattr("subclassing")?)?;
Ok(())

19
pytests/src/sequence.rs Normal file
View File

@ -0,0 +1,19 @@
use pyo3::prelude::*;
use pyo3::types::PyString;
#[pyfunction]
fn vec_to_vec_i32(vec: Vec<i32>) -> Vec<i32> {
vec
}
#[pyfunction]
fn vec_to_vec_pystring(vec: Vec<&PyString>) -> Vec<&PyString> {
vec
}
#[pymodule]
pub fn sequence(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(vec_to_vec_i32, m)?)?;
m.add_function(wrap_pyfunction!(vec_to_vec_pystring, m)?)?;
Ok(())
}

View File

@ -0,0 +1,31 @@
import pytest
import platform
from pyo3_pytests import sequence
def test_vec_from_list_i32():
assert sequence.vec_to_vec_i32([1, 2, 3]) == [1, 2, 3]
def test_vec_from_list_pystring():
assert sequence.vec_to_vec_pystring(["1", "2", "3"]) == ["1", "2", "3"]
def test_vec_from_bytes():
assert sequence.vec_to_vec_i32(b"123") == [49, 50, 51]
def test_vec_from_str():
with pytest.raises(ValueError):
sequence.vec_to_vec_pystring("123")
@pytest.mark.skipif(
platform.system() != "Linux" or platform.python_implementation() != "CPython",
reason="Binary NumPy wheels are not available for all platforms and Python implementations",
)
def test_vec_from_array():
import numpy
assert sequence.vec_to_vec_i32(numpy.array([1, 2, 3])) == [1, 2, 3]