Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature Request] Investigate if we need an unit tests for Python functions created in Rust #311

Closed
sansyrox opened this issue Nov 14, 2022 · 1 comment

Comments

@sansyrox
Copy link
Member

Current Behavior

Right now, we have zero unit tests.

Desired Behavior

While I am not a big fan of writing unit tests, investigate if there is a need to write any. A potential way would be something like the one below.

use pyo3::prelude::*;

#[derive(Debug, Clone)]
#[pyclass]
pub struct RustStruct {
    #[pyo3(get, set)]
    value: usize,
}

#[pymethods]
impl RustStruct {
    #[new]
    pub fn new(value: usize) -> Self {
        Self { value }
    }
}

#[pymodule]
fn rustlib(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_class::<RustStruct>()?;
    Ok(())
}



#[cfg(test)]
mod tests {
    use pyo3::{prepare_freethreaded_python, types::PyModule, Python};
    use crate::RustStruct;

    #[test]
    fn test_struct() {
        prepare_freethreaded_python();
        Python::with_gil(|py| {
            const CODE: &str = r#"
from rustlib import RustStruct
def test_fn(value):
    return isinstance(value, RustStruct)
"#;
            let module = PyModule::from_code(py, CODE, "test_mod.py", "test_mod").unwrap();
            let test_fn = module.getattr("test_fn").unwrap();
            let py_res = test_fn.call1((RustStruct::new(12),)).unwrap();
            let res: bool = py_res.extract().unwrap();
            assert!(res); // Fails because the types are not the same
        })
    }

    #[test]
    fn test_struct2() {
        prepare_freethreaded_python();
        Python::with_gil(|py| {
            const CODE: &str = r#"
from rustlib import RustStruct
def test_fn(value):
    return type(value)(13)
"#;
            let module = PyModule::from_code(py, CODE, "test_mod.py", "test_mod").unwrap();
            let test_fn = module.getattr("test_fn").unwrap();
            let py_res = test_fn.call1((RustStruct::new(12),)).unwrap();
            let res: RustStruct = py_res.extract().unwrap();
            assert_eq!(res.value, 13)
        })
    }
}

Screenshots / Mockups

Alternatives


@sansyrox
Copy link
Member Author

Not really necessary at the moment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant