Asserts that an array has a specified key.
public static assertArrayHasKey ( mixed $key, array | ArrayAccess $array, string $message = '' ) | ||
$key | mixed | |
$array | array | ArrayAccess | |
$message | string |
/** * @param string $property * @param string $format * * @return mixed[] */ private function decodeByProperty($property, $format) { return array_map(function ($entry) use($property) { \PHPUnit_Framework_Assert::assertInternalType('array', $entry); \PHPUnit_Framework_Assert::assertArrayHasKey($property, $entry); return $entry[$property]; }, $this->decode($format)); }
/** * @test * @dataProvider eventProvider */ public function itInstallsASite($eventName, LifecycleEvent $event) { $dispatcher = $this->prophesize('Symfony\\Component\\EventDispatcher\\EventDispatcherInterface'); $drupal = $this->generateDrupal(); $processRunner = $this->prophesize('eLife\\IsolatedDrupalBehatExtension\\Process\\ProcessRunner'); $listener = new InstallSiteListener($dispatcher->reveal(), $drupal, '/path/to/drush', $processRunner->reveal()); $dispatcher->dispatch(InstallingSite::NAME, Argument::type('eLife\\IsolatedDrupalBehatExtension\\Event\\InstallingSite'))->shouldBeCalledTimes(1)->should(new CallbackPrediction(function (array $calls) use($drupal) { /** @var Call $call */ $call = $calls[0]; /** @var InstallingSite $event */ $event = $call->getArguments()[1]; $process = $event->getCommand()->getProcess(); Assert::assertSame("'/path/to/drush' 'site-install' 'standard' " . "'--sites-subdir=localhost' '--account-name=admin' " . "'--account-pass=password' '--yes'", $process->getCommandLine()); Assert::assertArrayHasKey('PHP_OPTIONS', $process->getEnv()); Assert::assertSame('-d sendmail_path=' . `which true`, $process->getEnv()['PHP_OPTIONS']); Assert::assertSame($drupal->getPath(), $process->getWorkingDirectory()); })); $processRunner->run(Argument::type('Symfony\\Component\\Process\\Process'))->shouldBeCalledTimes(1); $dispatcher->dispatch(SiteInstalled::NAME, Argument::type('eLife\\IsolatedDrupalBehatExtension\\Event\\SiteInstalled'))->shouldBeCalledTimes(1)->should(new CallbackPrediction(function (array $calls) use($drupal) { /** @var Call $call */ $call = $calls[0]; /** @var SiteInstalled $event */ $event = $call->getArguments()[1]; Assert::assertEquals($drupal, $event->getDrupal()); })); $this->getDispatcher($listener)->dispatch($eventName, $event); }
public function shouldHaveKey($key) { if ($this->it instanceof \ArrayAccess) { Assert::assertEquals(isset($this->it[$key]), true, 'key ' . $key . ' does not exist'); } else { Assert::assertArrayHasKey($key, $this->it); } }
/** * Assert that 3D Secure information is present on order page in Admin. * * @param SalesOrderView $salesOrderView * @param array $paymentInformation * @return void */ public function processAssert(SalesOrderView $salesOrderView, array $paymentInformation) { $actualPaymentInformation = $salesOrderView->getBraintreeInfoBlock()->getPaymentInfo(); foreach ($paymentInformation as $key => $value) { \PHPUnit_Framework_Assert::assertArrayHasKey($key, $actualPaymentInformation, '3D Secure information is not present.'); \PHPUnit_Framework_Assert::assertEquals($paymentInformation[$key], $value, '3D Secure information is not equal to information from data set.'); } }
/** * @Then /^I should get an access token\.$/ */ public function iShouldGetAnAccessToken() { $this->assertResponseStatus(200); $content = json_decode($this->client->getResponse()->getContent(), true); PHPUnit::assertArrayHasKey('access_token', $content); PHPUnit::assertArrayHasKey('expires_in', $content); PHPUnit::assertArrayHasKey('token_type', $content); PHPUnit::assertEquals('Bearer', $content['token_type']); }
/** * Checks the integrity of operations links. * * @param mixed[] $operations_links */ protected function assertOperationsLinks(array $operations_links) { foreach ($operations_links as $link) { \PHPUnit_Framework_Assert::assertArrayHasKey('title', $link); \PHPUnit_Framework_Assert::assertNotEmpty($link['title']); \PHPUnit_Framework_Assert::assertArrayHasKey('url', $link); \PHPUnit_Framework_Assert::assertInstanceOf(Url::class, $link['url']); } }
/** * Asserts the existence of some path in the result, represented by any additional parameters. * * @param string[] $path * @param array $response */ public function assertResultHasKeyInPath(array $path, array $response) { $obj = $response; $p = '/'; foreach ($path as $key) { Assert::assertArrayHasKey($key, $obj, "Expected key {$key} under path {$p} in the response."); $obj = $obj[$key]; $p .= "/{$key}"; } }
/** * @Then I should be redirected to :url * @Then I should be redirected to :url with :status * * @param string $url * @param int $status */ public function iAmRedirected($url, $status = 302) { $headers = $this->getSession()->getResponseHeaders(); Assert::assertEquals($status, $this->getSession()->getStatusCode()); Assert::assertArrayHasKey('location', $headers, 'The response contains a "location" header'); Assert::assertEquals($url, $headers['location'][0], 'The "location" header does not point to the correct URI'); $client = $this->getClient(); $client->followRedirects(true); $client->followRedirect(); }
/** * @test */ public function it_detects_proper_values_and_constants() { $enum = new FakeEnum(); \PHPUnit_Framework_Assert::assertContains('SOME_KEY', $enum->keys()); \PHPUnit_Framework_Assert::assertArrayHasKey('SOME_KEY', $enum->values()); \PHPUnit_Framework_Assert::assertArrayNotHasKey('some-value', $enum->values()); \PHPUnit_Framework_Assert::assertContains('some-value', $enum->values()); \PHPUnit_Framework_Assert::assertSame('SOME_KEY', $enum->getConstantForValue('some-value')); \PHPUnit_Framework_Assert::assertTrue($enum->has('some-value')); \PHPUnit_Framework_Assert::assertFalse($enum->has('SOME-VALUE')); }
/** * Check if one array is subset of another. * * @param array $needle Subset. * @param array $haystack Set. */ protected function assertArrayContainsArray($needle, $haystack) { foreach ($needle as $key => $val) { \PHPUnit_Framework_Assert::assertArrayHasKey($key, $haystack); if (is_array($val)) { $this->assertArrayContainsArray($val, $haystack[$key]); } else { \PHPUnit_Framework_Assert::assertEquals($val, $haystack[$key]); } } }
private function check_response_status($body, $command_info) { $array = json_decode(trim($body), true); if (!is_null($array)) { $response_status_code = $array["status"]; PHPUnit_Framework_Assert::assertArrayHasKey($response_status_code, self::$status_codes, "Unknown status code {$response_status_code} returned from server.\n{$body}"); $response_info = $response_status_code . " - " . self::$status_codes[$response_status_code][0] . " - " . self::$status_codes[$response_status_code][1]; $additional_info = isset($array['value']['message']) ? "Message: " . $array['value']['message'] : "Response: " . $body; PHPUnit_Framework_Assert::assertEquals(0, $response_status_code, "Unsuccessful WebDriver command: {$response_info}\nCommand: {$command_info}\n{$additional_info}"); } }
/** * Assert that the response view has a given piece of bound data. * * @param string|array $key * @param mixed $value * @return void */ public function assertViewHas($key, $value = null) { if (is_array($key)) { return $this->assertViewHasAll($key); } if (!isset($this->response->original) || !$this->response->original instanceof View) { return PHPUnit::assertTrue(false, 'The response was not a view.'); } if (is_null($value)) { PHPUnit::assertArrayHasKey($key, $this->response->original->getData()); } else { PHPUnit::assertEquals($value, $this->response->original->{$key}); } }
/** * @Given /^Records in \'([^\']+)\' where \'([^\']+)\', has data$/ * @param $tableName * @param $where * @param TableNode $table * @throws \Doctrine\DBAL\DBALException * @throws \Exception */ public function thereAreRecordsInWhere($tableName, $where, TableNode $table) { /** @var Connection $connection */ $connection = $this->container->get('doctrine')->getConnection(); $exists = new ArrayCollection($connection->query("SELECT * FROM {$tableName} WHERE {$where}")->fetchAll()); $criteria = new Criteria(); $recordsMatching = $exists->matching($criteria); $record = $recordsMatching->first(); $i = 1; foreach ($table as $row) { foreach ($row as $key => $value) { \PHPUnit_Framework_Assert::assertArrayHasKey($key, $record, "Column '{$key}' doesn't exists in database"); \PHPUnit_Framework_Assert::assertEquals($value, $record[$key], "Invalid value for '{$key}' in row {$i}"); } ++$i; } }
public function toHaveKey($key) { if ($this->negate) { a::assertArrayNotHasKey($key, $this->actual); } else { a::assertArrayHasKey($key, $this->actual); } }
public function it_can_receive_due_scheduled_commands() { $date = new \DateTimeImmutable(); $timestamp = $date->getTimestamp(); $lua = $this->getLua('receive_due_messages'); $this->adapter->evalLua($lua, ['test', 0, $timestamp, SchedulerWorker::DEFAULT_THROTTLE])->shouldBeCalled()->willReturn([['test', 'test', 'test', $timestamp]]); $commandsWrapper = $this->receiveDueCommands($date); $commands = $commandsWrapper->getWrappedObject(); \PHPUnit_Framework_Assert::assertArrayHasKey(0, $commands); \PHPUnit_Framework_Assert::assertArrayNotHasKey(1, $commands); \PHPUnit_Framework_Assert::assertEquals('test', $commands[0]->getId()); }
public function hasKey($key) { a::assertArrayHasKey($key, $this->actual, $this->description); }
/** * @Given /^the response json should have a "([^"]*)" key$/ */ public function theResponseJsonShouldHaveAKey($key_name) { PHPUnit_Framework_Assert::assertArrayHasKey($key_name, $this->response->json()); }
/** * @Then /^I should have the following nodes(| in any order):$/ */ public function iShouldHaveTheFollowingNodes($orderIndependent, $table) { if ($this->isolated === true) { $this->callStepInSubProcess(__METHOD__, sprintf(' %s %s %s %s', 'string', escapeshellarg($orderIndependent), escapeshellarg('TYPO3\\Flow\\Tests\\Functional\\Command\\TableNode'), escapeshellarg(json_encode($table->getHash())))); } else { $rows = $table->getHash(); Assert::assertCount(count($rows), $this->currentNodes, 'Current nodes should match count of examples'); if ($orderIndependent === '') { foreach ($rows as $index => $row) { if (isset($row['Path'])) { Assert::assertEquals($row['Path'], $this->currentNodes[$index]->getPath(), 'Path should match on element ' . $index); } if (isset($row['Properties'])) { $nodeProperties = $this->currentNodes[$index]->getProperties(); $testProperties = json_decode($row['Properties'], true); foreach ($testProperties as $property => $value) { Assert::assertArrayHasKey($property, $nodeProperties, 'Expected property should exist'); Assert::assertEquals($value, $nodeProperties[$property], 'The value for property "' . $property . '" should match the expected value'); } } if (isset($row['Language'])) { $dimensions = $this->currentNodes[$index]->getDimensions(); Assert::assertEquals($row['Language'], implode(',', $dimensions['language']), 'Language should match'); } } } else { $currentNodes = $this->currentNodes; foreach ($currentNodes as $nodeIndex => $node) { foreach ($rows as $rowIndex => $row) { if (isset($row['Path']) && $row['Path'] !== $node->getPath()) { continue; } if (isset($row['Properties'])) { $nodeProperties = $node->getProperties(); $testProperties = json_decode($row['Properties'], true); foreach ($testProperties as $property => $value) { if (!isset($nodeProperties[$property]) || $nodeProperties[$property] !== $value) { continue 2; } } } if (isset($row['Language'])) { $dimensions = $node->getDimensions(); if ($row['Language'] !== implode(',', $dimensions['language'])) { continue; } } unset($currentNodes[$nodeIndex]); unset($rows[$rowIndex]); } } Assert::assertEquals(array(), $rows, 'All examples should have matched'); Assert::assertCount(0, $currentNodes, 'All nodes should be matched'); } } }
/** * @Then the composer.json :key for :project should read :name */ public function theComposerJsonNameShouldRead($key, $project, $name) { $composer = json_decode(file_get_contents("{$this->cwd}/{$project}/composer.json"), true); Assert::assertArrayHasKey($key, $composer); Assert::assertSame($name, $composer[$key]); }
/** * Checks that response body contains JSON from PyString. * * @param PyStringNode $jsonString * * @Then /^(?:the )?response should contain json:$/ */ public function theResponseShouldContainJson(PyStringNode $jsonString) { $etalon = json_decode($this->replacePlaceHolder($jsonString->getRaw()), true); $actual = json_decode($this->browser->getLastResponse()->getContent(), true); if (null === $etalon) { throw new \RuntimeException("Can not convert etalon to json:\n" . $this->replacePlaceHolder($jsonString->getRaw())); } \PHPUnit_Framework_Assert::assertCount(count($etalon), $actual); foreach ($actual as $key => $needle) { \PHPUnit_Framework_Assert::assertArrayHasKey($key, $etalon); \PHPUnit_Framework_Assert::assertEquals($etalon[$key], $actual[$key]); } }
/** * Checks that response body contains JSON from PyString. * * Do not check that the response body /only/ contains the JSON from PyString, * * @param PyStringNode $jsonString * * @throws \RuntimeException * * @Then /^(?:the )?response should contain json:$/ */ public function theResponseShouldContainJson(PyStringNode $jsonString) { $etalon = json_decode($this->replacePlaceHolder($jsonString->getRaw()), true); $actual = $this->response->json(); if (null === $etalon) { throw new \RuntimeException("Can not convert etalon to json:\n" . $this->replacePlaceHolder($jsonString->getRaw())); } Assertions::assertGreaterThanOrEqual(count($etalon), count($actual)); foreach ($etalon as $key => $needle) { Assertions::assertArrayHasKey($key, $actual); Assertions::assertEquals($etalon[$key], $actual[$key]); } }
public static function GetJSONValue($curl_response, $attribute = null) { PHPUnit_Framework_Assert::assertArrayHasKey('body', $curl_response, "Response had no body\n{$curl_response['header']}"); $array = json_decode(trim($curl_response['body']), true); PHPUnit_Framework_Assert::assertNotNull($array, "Body could not be decoded as JSON\n{$curl_response['body']}"); PHPUnit_Framework_Assert::assertArrayHasKey('value', $array, "JSON had no value\n" . print_r($array, true)); if ($attribute === null) { $rv = $array["value"]; } else { if (isset($array["value"][$attribute])) { $rv = $array["value"][$attribute]; } else { if (is_array($array["value"])) { $rv = array(); foreach ($array["value"] as $a_value) { PHPUnit_Framework_Assert::assertArrayHasKey($attribute, $a_value, "JSON value did not have attribute {$attribute}\n" . print_r($array, true)); $rv[] = $a_value[$attribute]; } } } PHPUnit_Framework_Assert::assertNotNull($rv, "JSON value did not have attribute {$attribute}\n" . print_r($array["value"], true)); } return $rv; }
/** * Checks that response body contains JSON from PyString. * * Do not check that the response body /only/ contains the JSON from PyString, * * @param PyStringNode $jsonString * * @throws \RuntimeException * * @Then /^(?:the )?response should contain json:$/ */ public function theResponseShouldContainJson(PyStringNode $jsonString) { $etalon = json_decode($this->replacePlaceHolder($jsonString->getRaw()), true); $actual = json_decode($this->getResponse()->getBody(), true); if (null === $etalon) { throw new \RuntimeException("Can not convert etalon to json:\n" . $this->replacePlaceHolder($jsonString->getRaw())); } Assertions::assertGreaterThanOrEqual(count($etalon), count($actual)); foreach ($etalon as $key => $needle) { if (is_array($needle)) { foreach ($needle as $k => $v) { if (is_array($v) && in_array('id', array_keys($v))) { continue 2; } } } if (in_array($key, ['id', 'updated_at', 'created_at', 'start_at', 'end_at', 'slug'])) { continue; } Assertions::assertArrayHasKey($key, $actual); Assertions::assertEquals($etalon[$key], $actual[$key]); } }
public function arrayToHaveKey($key) { \PHPUnit_Framework_Assert::assertArrayHasKey($key, $this->actual); }
/** * Sets Headers "Link" as one header "Link" based on linkEntries * * @param array $linkEntries (entry is array with keys "uri" and "link-param") * * @link http://tools.ietf.org/html/rfc2068#section-19.6.2.4 * * @author samva.ua@gmail.com */ private function setHeaderLink(array $linkEntries) { $values = array(); foreach ($linkEntries as $linkEntry) { \PHPUnit_Framework_Assert::assertArrayHasKey('uri', $linkEntry, 'linkEntry should contain property "uri"'); \PHPUnit_Framework_Assert::assertArrayHasKey('link-param', $linkEntry, 'linkEntry should contain property "link-param"'); $values[] = $linkEntry['uri'] . '; ' . $linkEntry['link-param']; } $this->headers['Link'] = join(', ', $values); }
/** * Expect that an array has a specified key. * * @param mixed $key * @param string $message * * @return Expect */ public function toHaveKey($key, $message = '') { Assert::assertArrayHasKey($key, $this->value, $message); return $this; }
/** * Asserts that an array has a specified key. * * @param mixed $key * @param array $array * @param string $message * @since Method available since Release 3.0.0 */ function assertArrayHasKey($key, array $array, $message = '') { return PHPUnit_Framework_Assert::assertArrayHasKey($key, $array, $message); }
public function execute($http_type, $relative_url, $payload = null) { if ($payload !== null) { $payload = json_encode($payload); } $relative_url = str_replace(':sessionId', $this->session_id, $relative_url); $full_url = $this->server_url . $relative_url; $response = WebDriver::Curl($http_type, $full_url, $payload); if (isset($response['body'])) { $command_info = $http_type . " - " . $full_url . " - " . print_r($payload, true); $response_json = json_decode(trim($response['body']), true); if (!is_null($response_json)) { $response_status_code = $response_json["status"]; PHPUnit_Framework_Assert::assertArrayHasKey($response_status_code, self::$status_codes, "Unknown status code {$response_status_code} returned from server.\n{$response['body']}"); $response_info = $response_status_code . " - " . self::$status_codes[$response_status_code][0] . " - " . self::$status_codes[$response_status_code][1]; $additional_info = isset($response_json['value']['message']) ? "Message: " . $response_json['value']['message'] : "Response: " . $response['body']; if ($response_status_code == 7) { throw new WebDriver_NoSuchElementException("Could not find element: " . print_r($payload, true)); } if ($response_status_code == 10) { throw new WebDriver_StaleElementReferenceException(); } if ($response_status_code == 11) { throw new WebDriver_ElementNotVisibleException($command_info); } if ($response_status_code == 13 && strpos($response_json['value']['message'], 'Please upgrade to add more parallel sessions') !== false) { throw new WebDriver_OverParallelLimitException(); } PHPUnit_Framework_Assert::assertEquals(0, $response_status_code, "Unsuccessful WebDriver command: {$response_info}\nCommand: {$command_info}\n{$additional_info}"); } } return $response; }
/** * @Given Service is available */ public function isServiceAvailable() { PHPUnit_Framework_Assert::assertArrayHasKey('sitemap', $this->app); }
/** * @Then the players :arg1, :arg2 and :arg3 are equal with :arg4 */ public function thePlayersAndAreEqualWith($arg1, $arg2, $arg3, $arg4) { $winners = $this->winnerFinder->findAWinner($this->players); PHPUnit_Framework_Assert::assertArrayHasKey($arg1, $winners['winners']); PHPUnit_Framework_Assert::assertEquals($arg4, $winners['winners'][$arg1]['hand_name']); PHPUnit_Framework_Assert::assertArrayHasKey($arg2, $winners['winners']); PHPUnit_Framework_Assert::assertEquals($arg4, $winners['winners'][$arg2]['hand_name']); PHPUnit_Framework_Assert::assertArrayHasKey($arg3, $winners['winners']); PHPUnit_Framework_Assert::assertEquals($arg4, $winners['winners'][$arg3]['hand_name']); }