Skip to content
This repository has been archived by the owner on Aug 1, 2023. It is now read-only.

Commit

Permalink
Allow toAlmostEqual with nulls
Browse files Browse the repository at this point in the history
  • Loading branch information
fredemmott committed Feb 14, 2019
1 parent f0bc389 commit cf8afe9
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 6 deletions.
28 changes: 26 additions & 2 deletions src/Assert.hack
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,35 @@ abstract class Assert {
}

public function assertEqualsWithDelta(
num $expected,
num $actual,
?num $expected,
?num $actual,
float $delta,
string $message = '',
): void {
if (($actual === null) && ($expected === null)) {
return;
}
if ($actual === null) {
throw new ExpectationFailedException(
Str\format(
"%s\nnull is not equal to %f (with delta %f)",
$message,
(float) $expected,
$delta,
)
);
}
if ($expected === null) {
throw new ExpectationFailedException(
Str\format(
"%s\n%f is not equal to null (with delta %f)",
$message,
(float) $actual,
$delta,
)
);
}

if ($actual >= $expected - $delta && $actual <= $expected + $delta) {
return;
}
Expand Down
8 changes: 4 additions & 4 deletions src/ExpectObj.hack
Original file line number Diff line number Diff line change
Expand Up @@ -51,20 +51,20 @@ class ExpectObj<T> extends Assert {
* and $expected are not within $delta of each other.
*/
public function toEqualWithDelta(
num $expected,
?num $expected,
float $delta,
string $msg = '',
mixed ...$args
): void where T as num {
): void where T as ?num {
$msg = \vsprintf($msg, $args);
$this->assertEqualsWithDelta($expected, $this->var, $delta, $msg);
}

public function toAlmostEqual(
num $expected,
?num $expected,
string $msg = '',
mixed ...$args
): void where T as num {
): void where T as ?num {
$msg = \vsprintf($msg, $args);
$this->toEqualWithDelta(
$expected,
Expand Down
3 changes: 3 additions & 0 deletions tests/ExpectObjTest.hack
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ final class ExpectObjTest extends HackTest {
expect(dict[])->toBeType('KeyedContainer');
expect(array(1, 2, 3))->toContain(2);
expect(array(1, 2, 3))->toNotContain(7);
expect(1)->toAlmostEqual(1);
expect(null)->toAlmostEqual(null);

// hack arrays
expect(keyset[1])->toContain(1);
Expand Down Expand Up @@ -134,6 +136,7 @@ final class ExpectObjTest extends HackTest {
array('toNotBeType', 1, 'int'),
array('toContain', array(1, 2, 3), 7),
array('toNotContain', array(1, 2, 3), 2),
array('toAlmostEqual', null, 0.0),

// hack arrays
array('toContain', keyset[1, 2, 3], 7),
Expand Down

0 comments on commit cf8afe9

Please sign in to comment.