rhai/tests/mismatched_op.rs

75 lines
2.2 KiB
Rust
Raw Normal View History

use rhai::{Engine, EvalAltResult, INT};
2017-11-03 17:58:51 +01:00
#[test]
fn test_mismatched_op() {
let engine = Engine::new();
2017-11-03 17:58:51 +01:00
assert!(matches!(
*engine.eval::<INT>(r#""hello, " + "world!""#).expect_err("expects error"),
2022-02-08 02:02:15 +01:00
EvalAltResult::ErrorMismatchOutputType(need, actual, ..) if need == std::any::type_name::<INT>() && actual == "string"
));
2019-09-30 19:57:21 +02:00
}
#[test]
fn test_mismatched_op_name() {
let engine = Engine::new();
assert!(matches!(
*engine.eval::<String>("true").expect_err("expects error"),
EvalAltResult::ErrorMismatchOutputType(need, actual, ..) if need == "string" && actual == "bool"
));
assert!(matches!(
*engine.eval::<&str>("true").expect_err("expects error"),
EvalAltResult::ErrorMismatchOutputType(need, actual, ..) if need == "&str" && actual == "bool"
));
}
2019-09-30 19:57:21 +02:00
#[test]
#[cfg(not(feature = "no_object"))]
fn test_mismatched_op_custom_type() -> Result<(), Box<EvalAltResult>> {
2022-12-30 18:07:39 +01:00
#[allow(dead_code)] // used inside `register_type_with_name`
2020-07-03 04:45:01 +02:00
#[derive(Debug, Clone)]
2019-09-30 19:57:21 +02:00
struct TestStruct {
x: INT,
2019-09-30 19:57:21 +02:00
}
impl TestStruct {
2020-03-19 06:52:10 +01:00
fn new() -> Self {
2020-10-19 08:26:15 +02:00
Self { x: 1 }
2019-09-30 19:57:21 +02:00
}
}
let mut engine = Engine::new();
2020-07-12 05:46:53 +02:00
engine
.register_type_with_name::<TestStruct>("TestStruct")
.register_fn("new_ts", TestStruct::new);
2019-09-30 19:57:21 +02:00
assert!(matches!(*engine.eval::<bool>(
"
let x = new_ts();
let y = new_ts();
x == y
2023-04-10 17:23:59 +02:00
").unwrap_err(),
2022-02-08 02:02:15 +01:00
EvalAltResult::ErrorFunctionNotFound(f, ..) if f == "== (TestStruct, TestStruct)"));
assert!(
2023-04-10 17:23:59 +02:00
matches!(*engine.eval::<bool>("new_ts() == 42").unwrap_err(),
EvalAltResult::ErrorFunctionNotFound(f, ..) if f.starts_with("== (TestStruct, "))
);
assert!(matches!(
2023-04-10 17:23:59 +02:00
*engine.eval::<INT>("60 + new_ts()").unwrap_err(),
2022-02-08 02:02:15 +01:00
EvalAltResult::ErrorFunctionNotFound(f, ..) if f == format!("+ ({}, TestStruct)", std::any::type_name::<INT>())
));
assert!(matches!(
2023-04-10 17:23:59 +02:00
*engine.eval::<TestStruct>("42").unwrap_err(),
2022-02-08 02:02:15 +01:00
EvalAltResult::ErrorMismatchOutputType(need, actual, ..)
2020-07-03 04:45:01 +02:00
if need == "TestStruct" && actual == std::any::type_name::<INT>()
));
Ok(())
2017-11-03 17:58:51 +01:00
}