| ... | @@ -171,6 +171,59 @@ test "expectEqual.union(enum)" { | ... | @@ -171,6 +171,59 @@ test "expectEqual.union(enum)" { |
| 171 | expectEqual(a10, a10); | 171 | expectEqual(a10, a10); |
| 172 | } | 172 | } |
| 173 | | 173 | |
| | 174 | /// This function is intended to be used only in tests. When the actual value is not |
| | 175 | /// within the margin of the expected value, |
| | 176 | /// prints diagnostics to stderr to show exactly how they are not equal, then aborts. |
| | 177 | /// The types must be floating point |
| | 178 | pub fn expectWithinMargin(expected: var, actual: @TypeOf(expected), margin: @TypeOf(expected)) void { |
| | 179 | std.debug.assert(margin >= 0.0); |
| | 180 | |
| | 181 | switch (@typeInfo(@TypeOf(actual))) { |
| | 182 | .Float, |
| | 183 | .ComptimeFloat, |
| | 184 | => { |
| | 185 | if (@fabs(expected - actual) > margin) { |
| | 186 | std.debug.panic("actual {}, not within margin {} of expected {}", .{ actual, margin, expected }); |
| | 187 | } |
| | 188 | }, |
| | 189 | else => @compileError("Unable to compare non floating point values"), |
| | 190 | } |
| | 191 | } |
| | 192 | |
| | 193 | test "expectWithinMargin.f32" { |
| | 194 | const x: f32 = 12.0; |
| | 195 | const y: f32 = 12.06; |
| | 196 | |
| | 197 | expectWithinMargin(x, y, 0.1); |
| | 198 | } |
| | 199 | |
| | 200 | /// This function is intended to be used only in tests. When the actual value is not |
| | 201 | /// within the epsilon of the expected value, |
| | 202 | /// prints diagnostics to stderr to show exactly how they are not equal, then aborts. |
| | 203 | /// The types must be floating point |
| | 204 | pub fn expectWithinEpsilon(expected: var, actual: @TypeOf(expected), epsilon: @TypeOf(expected)) void { |
| | 205 | std.debug.assert(epsilon >= 0.0 and epsilon <= 1.0); |
| | 206 | |
| | 207 | const margin = epsilon * expected; |
| | 208 | switch (@typeInfo(@TypeOf(actual))) { |
| | 209 | .Float, |
| | 210 | .ComptimeFloat, |
| | 211 | => { |
| | 212 | if (@fabs(expected - actual) > margin) { |
| | 213 | std.debug.panic("actual {}, not within epsilon {}, of expected {}", .{ actual, epsilon, expected }); |
| | 214 | } |
| | 215 | }, |
| | 216 | else => @compileError("Unable to compare non floating point values"), |
| | 217 | } |
| | 218 | } |
| | 219 | |
| | 220 | test "expectWithinEpsilon.f32" { |
| | 221 | const x: f32 = 12.0; |
| | 222 | const y: f32 = 13.2; |
| | 223 | |
| | 224 | expectWithinEpsilon(x, y, 0.1); |
| | 225 | } |
| | 226 | |
| 174 | /// This function is intended to be used only in tests. When the two slices are not | 227 | /// This function is intended to be used only in tests. When the two slices are not |
| 175 | /// equal, prints diagnostics to stderr to show exactly how they are not equal, | 228 | /// equal, prints diagnostics to stderr to show exactly how they are not equal, |
| 176 | /// then aborts. | 229 | /// then aborts. |