aboutsummaryrefslogtreecommitdiff
path: root/lib/std/testing.zig
diff options
context:
space:
mode:
authorantlilja <liljaanton2001@gmail.com>2020-06-23 18:08:15 +0200
committerantlilja <liljaanton2001@gmail.com>2020-06-23 18:08:15 +0200
commit46106b018cc5c870648cf26d4e7413e8a60ad1e4 (patch)
treecb66fae6934fc49741c3e4f490839895e7769c79 /lib/std/testing.zig
parent2fc2355fc3d72cbf1ffdc982a42090ada901d21f (diff)
downloadzig-46106b018cc5c870648cf26d4e7413e8a60ad1e4.tar.gz
zig-46106b018cc5c870648cf26d4e7413e8a60ad1e4.zip
Add expectWithinEpsilon + test
Diffstat (limited to 'lib/std/testing.zig')
-rw-r--r--lib/std/testing.zig27
1 files changed, 27 insertions, 0 deletions
diff --git a/lib/std/testing.zig b/lib/std/testing.zig
index 9dca969f45..9f7601b19e 100644
--- a/lib/std/testing.zig
+++ b/lib/std/testing.zig
@@ -194,6 +194,33 @@ test "expectWithinMargin.f32" {
expectWithinMargin(x, y, 0.1);
}
+/// This function is intended to be used only in tests. When the actual value is not
+/// within the epsilon of the expected value,
+/// prints diagnostics to stderr to show exactly how they are not equal, then aborts.
+/// The types must be floating point
+pub fn expectWithinEpsilon(expected: var, actual: @TypeOf(expected), epsilon: @TypeOf(expected)) void {
+ std.debug.assert(epsilon >= 0.0 and epsilon <= 1.0);
+
+ const margin = epsilon * expected;
+ switch (@typeInfo(@TypeOf(actual))) {
+ .Float,
+ .ComptimeFloat,
+ => {
+ if (@fabs(expected - actual) > margin) {
+ std.debug.panic("actual {}, not within epsilon {}, of expected {}", .{ actual, epsilon, expected });
+ }
+ },
+ else => @compileError("Unable to compare non floating point values"),
+ }
+}
+
+test "expectWithinEpsilon.f32" {
+ const x: f32 = 12.0;
+ const y: f32 = 13.2;
+
+ expectWithinEpsilon(x, y, 0.1);
+}
+
/// This function is intended to be used only in tests. When the two slices are not
/// equal, prints diagnostics to stderr to show exactly how they are not equal,
/// then aborts.