authorgravatar for liljaanton2001@gmail.comantlilja <liljaanton2001@gmail.com> 2020-06-23 18:05:32+02:00
committergravatar for liljaanton2001@gmail.comantlilja <liljaanton2001@gmail.com> 2020-06-23 18:05:32+02:00
log2fc2355fc3d72cbf1ffdc982a42090ada901d21f
treec50ed8575f85afead03df44458c44809827aa590
parent5229f6ec68708c3e66393a50ad9f9032ee7f4257

Add expectWithinMargin and test


1 files changed, 26 insertions(+), 0 deletions(-)

lib/std/testing.zig+26
......@@ -168,6 +168,32 @@ test "expectEqual.union(enum)" {
168168 expectEqual(a10, a10);
169169}
170170
171/// This function is intended to be used only in tests. When the actual value is not
172/// within the margin of the expected value,
173/// prints diagnostics to stderr to show exactly how they are not equal, then aborts.
174/// The types must be floating point
175pub fn expectWithinMargin(expected: var, actual: @TypeOf(expected), margin: @TypeOf(expected)) void {
176 std.debug.assert(margin >= 0.0);
177
178 switch (@typeInfo(@TypeOf(actual))) {
179 .Float,
180 .ComptimeFloat,
181 => {
182 if (@fabs(expected - actual) > margin) {
183 std.debug.panic("actual {}, not within margin {} of expected {}", .{ actual, margin, expected });
184 }
185 },
186 else => @compileError("Unable to compare non floating point values"),
187 }
188}
189
190test "expectWithinMargin.f32" {
191 const x: f32 = 12.0;
192 const y: f32 = 12.06;
193
194 expectWithinMargin(x, y, 0.1);
195}
196
171197/// This function is intended to be used only in tests. When the two slices are not
172198/// equal, prints diagnostics to stderr to show exactly how they are not equal,
173199/// then aborts.