Skip to content

Commit

Permalink
feat: adds toHaveKeys expectation
Browse files Browse the repository at this point in the history
  • Loading branch information
nunomaduro committed Sep 13, 2020
1 parent aa230a1 commit 204f343
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 2 deletions.
18 changes: 17 additions & 1 deletion src/Expectation.php
Original file line number Diff line number Diff line change
Expand Up @@ -376,14 +376,30 @@ public function toBeNull(): 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<int, int|string> $keys
*/
public function toHaveKeys(array $keys): Expectation
{
foreach ($keys as $key) {
$this->toHaveKey($key);
}

return $this;
}

/**
* Asserts that the value is a directory.
*/
Expand Down
20 changes: 20 additions & 0 deletions src/OppositeExpectation.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,26 @@ public function __construct(Expectation $original)
$this->original = $original;
}

/**
* Asserts that the value array not has the provided $keys.
*
* @param array<int, int|string> $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.
*
Expand Down
7 changes: 6 additions & 1 deletion tests/.snapshots/success.txt
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,11 @@
PASS Tests\Expect\toHaveKey
✓ pass
✓ failures
✓ not failures

PASS Tests\Expect\toHaveKeys
✓ pass
✓ failures
✓ not failures

PASS Tests\Expect\toHaveProperty
Expand Down Expand Up @@ -353,5 +358,5 @@
✓ depends with defined arguments
✓ depends run test only once

Tests: 6 skipped, 208 passed
Tests: 6 skipped, 211 passed

15 changes: 15 additions & 0 deletions tests/Expect/toHaveKeys.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

use PHPUnit\Framework\ExpectationFailedException;

test('pass', function () {
expect(['a' => 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);

0 comments on commit 204f343

Please sign in to comment.