pyo3/tests/test_class_basics.rs

116 lines
2.9 KiB
Rust
Raw Normal View History

use pyo3::prelude::*;
2019-06-13 09:09:17 +00:00
use pyo3::py_run;
2019-12-14 14:16:39 +00:00
use pyo3::pyclass::initialize_type;
mod common;
#[pyclass]
struct EmptyClass {}
#[test]
fn empty_class() {
let gil = Python::acquire_gil();
let py = gil.python();
let typeobj = py.get_type::<EmptyClass>();
// By default, don't allow creating instances from python.
2019-02-23 17:01:22 +00:00
assert!(typeobj.call((), None).is_err());
py_assert!(py, typeobj, "typeobj.__name__ == 'EmptyClass'");
}
/// Line1
///Line2
/// Line3
// this is not doc string
#[pyclass]
struct ClassWithDocs {}
#[test]
fn class_with_docstr() {
{
let gil = Python::acquire_gil();
let py = gil.python();
let typeobj = py.get_type::<ClassWithDocs>();
py_run!(
py,
typeobj,
"assert typeobj.__doc__ == 'Line1\\nLine2\\n Line3'"
);
}
}
#[pyclass(name=CustomName)]
struct EmptyClass2 {}
#[pymethods]
impl EmptyClass2 {
#[name = "custom_fn"]
fn bar(&self) {}
#[staticmethod]
#[name = "custom_static"]
fn bar_static() {}
}
#[test]
fn custom_names() {
let gil = Python::acquire_gil();
let py = gil.python();
let typeobj = py.get_type::<EmptyClass2>();
py_assert!(py, typeobj, "typeobj.__name__ == 'CustomName'");
py_assert!(py, typeobj, "typeobj.custom_fn.__name__ == 'custom_fn'");
py_assert!(
py,
typeobj,
"typeobj.custom_static.__name__ == 'custom_static'"
);
py_assert!(py, typeobj, "not hasattr(typeobj, 'bar')");
py_assert!(py, typeobj, "not hasattr(typeobj, 'bar_static')");
}
#[pyclass]
struct RawIdents {}
#[pymethods]
impl RawIdents {
2019-12-17 22:58:34 +00:00
fn r#fn(&self) {}
}
#[test]
fn test_raw_idents() {
let gil = Python::acquire_gil();
let py = gil.python();
let typeobj = py.get_type::<RawIdents>();
py_assert!(py, typeobj, "not hasattr(typeobj, 'r#fn')");
py_assert!(py, typeobj, "hasattr(typeobj, 'fn')");
}
#[pyclass]
struct EmptyClassInModule {}
#[test]
fn empty_class_in_module() {
let gil = Python::acquire_gil();
let py = gil.python();
let module = PyModule::new(py, "test_module.nested").unwrap();
module.add_class::<EmptyClassInModule>().unwrap();
let ty = module.getattr("EmptyClassInModule").unwrap();
assert_eq!(
ty.getattr("__name__").unwrap().extract::<String>().unwrap(),
"EmptyClassInModule"
);
2019-02-01 16:15:33 +00:00
let module: String = ty.getattr("__module__").unwrap().extract().unwrap();
// Rationale: The class can be added to many modules, but will only be initialized once.
// We currently have no way of determining a canonical module, so builtins is better
// than using whatever calls init first.
2019-03-22 13:07:33 +00:00
assert_eq!(module, "builtins");
// The module name can also be set manually by calling `initialize_type`.
initialize_type::<EmptyClassInModule>(py, Some("test_module.nested")).unwrap();
let module: String = ty.getattr("__module__").unwrap().extract().unwrap();
assert_eq!(module, "test_module.nested");
}