Skip to content

Commit

Permalink
Add a (failing test) for issue PyO3#1064
Browse files Browse the repository at this point in the history
RichComparisonToSelf expects to compare itself with objects of the same type,
but they we shouldn't raise TypeError but return NotImplemented.
  • Loading branch information
mvaled committed Jul 30, 2020
1 parent 51171f7 commit 6e305b0
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ macros = ["ctor", "indoc", "inventory", "paste", "pyo3cls", "unindent"]
# Optimizes PyObject to Vec conversion and so on.
nightly = []

no-return-notimplemented = []

# this is no longer needed internally, but setuptools-rust assumes this feature
python3 = []

Expand Down
62 changes: 62 additions & 0 deletions tests/test_arithmetics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -423,3 +423,65 @@ fn rich_comparisons_python_3_type_error() {
py_expect_exception!(py, c2, "c2 >= 1", PyTypeError);
py_expect_exception!(py, c2, "1 >= c2", PyTypeError);
}

#[cfg(not(feature = "no-return-notimplemented"))]
#[cfg(test)]
mod not_implemented {
use super::*;

#[pyclass]
struct RichComparisonToSelf {}

#[pyproto]
impl<'p> PyObjectProtocol<'p> for RichComparisonToSelf {
fn __repr__(&self) -> &'static str {
"RC_Self"
}

fn __richcmp__(&self, other: PyRef<'p, Self>, _op: CompareOp) -> PyObject {
other.py().None()
}
}

macro_rules! not_implemented_test {
($dunder: ident, $operator: literal) => {
#[test]
fn $dunder() {
let gil = Python::acquire_gil();
let py = gil.python();
let c2 = PyCell::new(py, RichComparisonToSelf {}).unwrap();
py_run!(
py,
c2,
&format!(
"\
class Other:
def __{}__(self, other):
return True
assert c2 {} Other()",
stringify!($dunder), $operator
)
);
py_expect_exception!(
py,
c2,
&format!("class Other: pass; assert c2 {} Other()", $operator),
PyTypeError
);
}
};

[$( ($dunder: ident, $operator: literal) ),*] => {
$(not_implemented_test!{$dunder, $operator})*
};
}

not_implemented_test![
(eq, "=="),
(ne, "!="),
(lt, "<"),
(le, "<="),
(gt, ">"),
(ge, ">=")
];
}

0 comments on commit 6e305b0

Please sign in to comment.