Add assertEqual function to KCL stdlib (#3279)
Takes a tolerance, because floating-point imprecision.
This commit is contained in:
@ -67,6 +67,27 @@ pub async fn assert_gt(args: Args) -> Result<MemoryItem, KclError> {
|
||||
args.make_null_user_val()
|
||||
}
|
||||
|
||||
/// Check that a numerical value equals another at runtime,
|
||||
/// otherwise raise an error.
|
||||
///
|
||||
/// ```no_run
|
||||
/// let n = 1.0285
|
||||
/// let m = 1.0286
|
||||
/// assertEqual(n, m, 0.01, "n is within the given tolerance for m")
|
||||
/// ```
|
||||
#[stdlib {
|
||||
name = "assertEqual",
|
||||
}]
|
||||
async fn inner_assert_equal(left: f64, right: f64, epsilon: f64, message: &str, args: &Args) -> Result<(), KclError> {
|
||||
_assert((right - left).abs() < epsilon, message, args).await
|
||||
}
|
||||
|
||||
pub async fn assert_equal(args: Args) -> Result<MemoryItem, KclError> {
|
||||
let (left, right, epsilon, description): (f64, f64, f64, String) = args.get_data()?;
|
||||
inner_assert_equal(left, right, epsilon, &description, &args).await?;
|
||||
args.make_null_user_val()
|
||||
}
|
||||
|
||||
/// Check that a numerical value is greater than another at runtime,
|
||||
/// otherwise raise an error.
|
||||
///
|
||||
|
||||
@ -120,6 +120,7 @@ lazy_static! {
|
||||
Box::new(crate::std::math::ToRadians),
|
||||
Box::new(crate::std::polar::Polar),
|
||||
Box::new(crate::std::assert::Assert),
|
||||
Box::new(crate::std::assert::AssertEqual),
|
||||
Box::new(crate::std::assert::AssertLessThan),
|
||||
Box::new(crate::std::assert::AssertGreaterThan),
|
||||
Box::new(crate::std::assert::AssertLessThanOrEq),
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 70 KiB |
@ -4,8 +4,7 @@ const arr = [0, 0, 0, 10]
|
||||
const i = 3
|
||||
const ten = arr[i]
|
||||
|
||||
assertLessThanOrEq(ten, 10, "oops")
|
||||
assertGreaterThanOrEq(ten, 10, "oops2")
|
||||
assertEqual(ten, 10, 0.000001, "oops")
|
||||
|
||||
const p = "foo"
|
||||
const obj = {
|
||||
@ -14,5 +13,4 @@ const obj = {
|
||||
}
|
||||
const one = obj[p]
|
||||
|
||||
assertLessThanOrEq(one, 1, "oops")
|
||||
assertGreaterThanOrEq(one, 1, "oops2")
|
||||
assertEqual(one, 1, 0.0000001, "oops")
|
||||
|
||||
Reference in New Issue
Block a user