diff --git a/src/Expectation.php b/src/Expectation.php index 4e5b9633..255c436b 100644 --- a/src/Expectation.php +++ b/src/Expectation.php @@ -376,14 +376,30 @@ final class Expectation /** * Asserts that the value array has the provided $key. + * + * @param string|int $key */ - public function toHaveKey(string $key): Expectation + public function toHaveKey($key): Expectation { Assert::assertArrayHasKey($key, $this->value); return $this; } + /** + * Asserts that the value array has the provided $keys. + * + * @param array $keys + */ + public function toHaveKeys(array $keys): Expectation + { + foreach ($keys as $key) { + $this->toHaveKey($key); + } + + return $this; + } + /** * Asserts that the value is a directory. */ diff --git a/src/OppositeExpectation.php b/src/OppositeExpectation.php index 143d35c9..9e045eb9 100644 --- a/src/OppositeExpectation.php +++ b/src/OppositeExpectation.php @@ -27,6 +27,26 @@ final class OppositeExpectation $this->original = $original; } + /** + * Asserts that the value array not has the provided $keys. + * + * @param array $keys + */ + public function toHaveKeys(array $keys): Expectation + { + foreach ($keys as $key) { + try { + $this->original->toHaveKey($key); + } catch (ExpectationFailedException $e) { + continue; + } + + $this->throwExpectationFailedExpection('toHaveKey', [$key]); + } + + return $this->original; + } + /** * Handle dynamic method calls into the original expectation. * diff --git a/tests/.snapshots/success.txt b/tests/.snapshots/success.txt index 8e16357d..9101af68 100644 --- a/tests/.snapshots/success.txt +++ b/tests/.snapshots/success.txt @@ -180,6 +180,11 @@ PASS Tests\Expect\toHaveKey ✓ pass ✓ failures + ✓ not failures + + PASS Tests\Expect\toHaveKeys + ✓ pass + ✓ failures ✓ not failures PASS Tests\Expect\toHaveProperty @@ -353,5 +358,5 @@ ✓ depends with defined arguments ✓ depends run test only once - Tests: 6 skipped, 208 passed + Tests: 6 skipped, 211 passed \ No newline at end of file diff --git a/tests/Expect/toHaveKeys.php b/tests/Expect/toHaveKeys.php new file mode 100644 index 00000000..a09c8809 --- /dev/null +++ b/tests/Expect/toHaveKeys.php @@ -0,0 +1,15 @@ + 1, 'b', 'c' => 'world'])->toHaveKeys(['a', 'c']); +}); + +test('failures', function () { + expect(['a' => 1, 'b', 'c' => 'world'])->toHaveKeys(['a', 'd']); +})->throws(ExpectationFailedException::class); + +test('not failures', function () { + expect(['a' => 1, 'hello' => 'world', 'c'])->not->toHaveKeys(['hello', 'c']); +})->throws(ExpectationFailedException::class);