aboutsummaryrefslogtreecommitdiff
path: root/lib/std/testing.zig
diff options
context:
space:
mode:
authorAndrew Kelley <andrew@ziglang.org>2020-08-04 17:09:40 -0700
committerAndrew Kelley <andrew@ziglang.org>2020-08-04 17:09:40 -0700
commitc6e0df6213af1ecf5734bc6bcb4d7c29a4b41351 (patch)
tree42d358704ab86a506d1c53c0fc6da73738560fa7 /lib/std/testing.zig
parent41a8b6f57b3bd50b2ed6fdced74fba9130eac3d3 (diff)
parentd61a9e37ae8f140407d1369500d21efbe2b198ab (diff)
downloadzig-c6e0df6213af1ecf5734bc6bcb4d7c29a4b41351.tar.gz
zig-c6e0df6213af1ecf5734bc6bcb4d7c29a4b41351.zip
Merge remote-tracking branch 'origin/master' into llvm11
Diffstat (limited to 'lib/std/testing.zig')
-rw-r--r--lib/std/testing.zig53
1 files changed, 53 insertions, 0 deletions
diff --git a/lib/std/testing.zig b/lib/std/testing.zig
index 44c221d76a..8f16b50cd2 100644
--- a/lib/std/testing.zig
+++ b/lib/std/testing.zig
@@ -171,6 +171,59 @@ test "expectEqual.union(enum)" {
expectEqual(a10, a10);
}
+/// This function is intended to be used only in tests. When the actual value is not
+/// within the margin 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 expectWithinMargin(expected: anytype, actual: @TypeOf(expected), margin: @TypeOf(expected)) void {
+ std.debug.assert(margin >= 0.0);
+
+ switch (@typeInfo(@TypeOf(actual))) {
+ .Float,
+ .ComptimeFloat,
+ => {
+ if (@fabs(expected - actual) > margin) {
+ std.debug.panic("actual {}, not within margin {} of expected {}", .{ actual, margin, expected });
+ }
+ },
+ else => @compileError("Unable to compare non floating point values"),
+ }
+}
+
+test "expectWithinMargin.f32" {
+ const x: f32 = 12.0;
+ const y: f32 = 12.06;
+
+ 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: anytype, 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.