diff options
| author | antlilja <liljaanton2001@gmail.com> | 2020-06-23 18:05:32 +0200 |
|---|---|---|
| committer | antlilja <liljaanton2001@gmail.com> | 2020-06-23 18:05:32 +0200 |
| commit | 2fc2355fc3d72cbf1ffdc982a42090ada901d21f (patch) | |
| tree | c50ed8575f85afead03df44458c44809827aa590 /lib/std/testing.zig | |
| parent | 5229f6ec68708c3e66393a50ad9f9032ee7f4257 (diff) | |
| download | zig-2fc2355fc3d72cbf1ffdc982a42090ada901d21f.tar.gz zig-2fc2355fc3d72cbf1ffdc982a42090ada901d21f.zip | |
Add expectWithinMargin and test
Diffstat (limited to 'lib/std/testing.zig')
| -rw-r--r-- | lib/std/testing.zig | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/lib/std/testing.zig b/lib/std/testing.zig index 2d136d56c9..9dca969f45 100644 --- a/lib/std/testing.zig +++ b/lib/std/testing.zig @@ -168,6 +168,32 @@ 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: var, 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 two slices are not /// equal, prints diagnostics to stderr to show exactly how they are not equal, /// then aborts. |
