Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Simplifying the step definitions #15

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 23 additions & 12 deletions src/ApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,12 @@ public function resetHeaders()
$this->headers = [];
}

/**
* Send a post request using form-data
*
* @param $uri
* @param $formData
*/
public function postWithFormData($uri, $formData)
{
$this->lastRequestBody = null;
Expand All @@ -103,8 +109,8 @@ public function postWithFormData($uri, $formData)
* Send a post request
*
* @param string $uri
* @param array $body
* @param array $params
* @param array $body
* @param array $params
*
* @return void
*/
Expand All @@ -129,8 +135,8 @@ public function post($uri, array $body = [], array $params = [])

/**
* @param string $uri
* @param array $body
* @param array $params
* @param array $body
* @param array $params
*
* @return void
*/
Expand All @@ -141,9 +147,9 @@ public function upload($uri, array $body = [], array $params = [])
try {

$this->lastResponse = $this->client->post($uri, [
'query' => $params,
'multipart' => $body,
'headers' => $this->headers,
'query' => $params,
'multipart' => $body,
'headers' => $this->headers,
]);

} catch (RequestException $e) {
Expand All @@ -157,7 +163,7 @@ public function upload($uri, array $body = [], array $params = [])
* Retrieve a uri
*
* @param string $uri
* @param array $params
* @param array $params
*
* @return void
*/
Expand All @@ -181,9 +187,10 @@ public function get($uri, array $params = [])

/**
* @param string $uri
* @param array $body
* @param array $body
* @param array $params
*/
public function put($uri, array $body)
public function put($uri, array $body, array $params = [])
{
$this->lastRequestBody = $body;

Expand All @@ -192,6 +199,7 @@ public function put($uri, array $body)
$this->lastResponse = $this->client->put($uri, [
'json' => $body,
'headers' => $this->headers,
'query' => $params,
]);

} catch (RequestException $e) {
Expand All @@ -201,7 +209,7 @@ public function put($uri, array $body)
}
}

public function patch($uri, array $body)
public function patch($uri, array $body, array $params = [])
{
$this->lastRequestBody = $body;

Expand All @@ -210,6 +218,7 @@ public function patch($uri, array $body)
$this->lastResponse = $this->client->patch($uri, [
'json' => $body,
'headers' => $this->headers,
'query' => $params,
]);

} catch (RequestException $e) {
Expand All @@ -221,15 +230,17 @@ public function patch($uri, array $body)

/**
* @param string $uri
* @param array $params
*/
public function delete($uri)
public function delete($uri, array $params = [])
{
$this->lastRequestBody = null;

try {

$this->lastResponse = $this->client->delete($uri, [
'headers' => $this->headers,
'query' => $params,
]);

} catch (RequestException $e) {
Expand Down
179 changes: 154 additions & 25 deletions src/Context/ApiContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public function convertValueToAlias($value)
{
if (is_array($value)) {

array_walk_recursive($value, function(&$value) {
array_walk_recursive($value, function (&$value) {
$value = $this->replaceValueWithAlias($value);
});

Expand All @@ -101,30 +101,159 @@ public function convertValueToAlias($value)
*/
private function replaceValueWithAlias($value)
{
if (!(strpos($value, '%') === 0) && !(strpos(strrev($value), '%') === 0)) {
if (!is_string($value)) {
return $value;
}

// Remove the last and first characters
$value = substr($value, 1, -1);
$parts = explode('%', $value);
$result = [];

// Covers the case when a field is not specified
$alias = $value;
$field = null;
foreach ($parts as $index => $alias) {
// Due to the way explode works, every second (odd) item in the array should be replaced
if ($index % 2 === 1 && $index !== count($parts) - 1) {
$field = null;

if (strpos($value, ':') !== 0) {
list($alias, $field) = explode(':', $value);
if (strpos($alias, ':') !== false) {
list($alias, $field) = explode(':', $alias);
}

$entity = $this->entityFixtureContext->getEntityFromAlias($alias);

if (!$field) {
$field = $this->entityManager->getClassMetadata(get_class($entity))->getSingleIdentifierColumnName();
}

$result[] = $this->getFieldOfObject($entity, $field);
} else {
$result[] = $alias;
}
}

$entity = $this->entityFixtureContext->getEntityFromAlias($alias);
return implode($result);
}

/**
* @When I send a :method to :url
*
* @param $method
* @param $url
*
* @throws RuntimeException
*/
public function iSendATo($method, $url)
{
$query = $this->parseQuery($url);
$url = explode('?', $url)[0];

call_user_func($this->getApiMethodToCall($method), $this->convertValueToAlias($url), $query);
}

if (!$field) {
$field = $this->entityManager->getClassMetadata(get_class($entity))->getSingleIdentifierColumnName();
/**
* @When I send a :method to :url with json:
*
* @param $method
* @param $url
* @param PyStringNode $string
*
* @throws RuntimeException
*/
public function iSendAToWithJson($method, $url, PyStringNode $string)
{
// Make sure the developer provided valid json
Assertions::assertJson($string->getRaw());

$body = [];
$data = json_decode($string, true);

foreach ($data as $key => $value) {
$body[$key] = $this->convertValueToAlias($value);
}

return $this->getFieldOfObject($entity, $field);
$query = $this->parseQuery($url);
$url = explode('?', $url)[0];

call_user_func($this->getApiMethodToCall($method), $this->convertValueToAlias($url), $body, $query);
}

/**
* @When I send a :method to :url with json values:
*
* @param $method
* @param $url
* @param TableNode $values
*
* @throws RuntimeException
*/
public function iSendAToWithJsonValues($method, $url, TableNode $values)
{
$body = [];

foreach ($values->getRows() as list ($key, $value)) {
$body[$key] = $this->convertValueToAlias($value);
}

$query = $this->parseQuery($url);
$url = explode('?', $url)[0];

call_user_func($this->getApiMethodToCall($method), $this->convertValueToAlias($url), $body, $query);
}

/**
* @When I send a POST to :url with form-data values:
*
* @param $url
* @param TableNode $values
*
* @throws RuntimeException
*/
public function iSendAToWithFormDataValues($url, TableNode $values)
{
$body = [];

foreach ($values->getRows() as list ($key, $value)) {
$body[$key] = $this->convertValueToAlias($value);
}

$this->getClient()->postWithFormData($this->convertValueToAlias($url), $body);
}

/**
* @param string $method
* @return callable
*/
private function getApiMethodToCall(string $method): callable
{
switch (strtoupper($method)) {
case 'GET':
case 'POST':
case 'PUT':
case 'DELETE':
case 'PATCH':
return [$this->getClient(), strtolower($method)];
default:
throw new RuntimeException('Unsuppored http verb provided');
}
}

/**
* Parse query from provided url
*
* @param string $url
* @return array
*/
private function parseQuery(string $url)
{
if (strpos($url, '?') === false) {
return [];
}

$query = explode('?', $url)[1];

return parse_query($query);
}

// todo: Basically everything from below here should be deprecated

/**
* @When I retrieve all :type
*/
Expand All @@ -143,7 +272,7 @@ public function iRetrieveAll($type)
*/
public function iRetrieveAllWith($type, $queryString)
{
$convertedQuery = $this->convertValueToAlias(parse_query($queryString,false));
$convertedQuery = $this->convertValueToAlias(parse_query($queryString, false));

$this->getClient()->get($this->createUri($type), $convertedQuery);
}
Expand Down Expand Up @@ -174,7 +303,7 @@ public function iRetrieveAllFrom($type, $parentType, $parentId)
*/
public function iRetrieveAllFromWithIdAndQueryString($type, $parentType, $parentId, $query)
{
$convertedQuery = $this->convertValueToAlias(parse_query($query,false));
$convertedQuery = $this->convertValueToAlias(parse_query($query, false));

$this->getClient()->get($this->createUri($parentType, $parentId, $type), $convertedQuery);
}
Expand Down Expand Up @@ -705,8 +834,8 @@ public function iSendAActionToResourceWithAliasWithMethodAndValues(
$type,
$alias,
$method,
TableNode $values)
{
TableNode $values
) {
$parent = $this->entityFixtureContext->getEntityFromAlias($alias);
$parentIdColumn = $this->entityFixtureContext->getPrimaryKeyColumnOfEntity($parent);

Expand Down Expand Up @@ -889,7 +1018,7 @@ public function iShouldReceiveAValidationErrorWithCount($count)
Assertions::assertJson($responseBody);
Assertions::assertEquals(422, $this->getClient()->lastResponse->getStatusCode());

Assertions::assertCount((int)$count, json_decode($responseBody, true)['errors']);
Assertions::assertCount((int) $count, json_decode($responseBody, true)['errors']);

} catch (PHPUnit_Framework_ExpectationFailedException $e) {

Expand Down Expand Up @@ -979,7 +1108,7 @@ public function theResponseShouldMatchTheRequestProperties()
Assertions::assertArrayHasKey($key, $json);

if (is_bool($json[$key])) {
Assertions::assertEquals((bool)$value, $json[$key]);
Assertions::assertEquals((bool) $value, $json[$key]);
} else {
Assertions::assertEquals($value, $json[$key]);
}
Expand Down Expand Up @@ -1012,7 +1141,7 @@ public function itShouldContainRecords($records)
$json = json_decode($responseBody, true);

Assertions::assertArrayHasKey('data', $json);
Assertions::assertCount((int)$records, $json['data']);
Assertions::assertCount((int) $records, $json['data']);

} catch (PHPUnit_Framework_ExpectationFailedException $e) {

Expand Down Expand Up @@ -1042,7 +1171,7 @@ public function itShouldMatchTheFollowingProperties(TableNode $table)
Assertions::assertArrayHasKey($key, $json);

if (is_bool($json[$key])) {
Assertions::assertEquals((bool)$value, $json[$key]);
Assertions::assertEquals((bool) $value, $json[$key]);
} else {
Assertions::assertEquals($value, $json[$key]);
}
Expand Down Expand Up @@ -1087,20 +1216,20 @@ public function theBooleanFieldFieldShouldBeValue($typeOfValue, $field, $directi
case 'boolean':
case 'bool':
$shouldBe = (strtolower($shouldBe) === 'false') ? false : $shouldBe;
$shouldBe = (boolean)$shouldBe;
$shouldBe = (boolean) $shouldBe;
break;
case 'string':
$shouldBe = (string)$shouldBe;
$shouldBe = (string) $shouldBe;
break;
case 'int':
case 'integer':
$shouldBe = (int)$shouldBe;
$shouldBe = (int) $shouldBe;
break;
case 'nullable':
$shouldBe = null;
break;
default:
$shouldBe = (string)$shouldBe;
$shouldBe = (string) $shouldBe;
}

Assertions::$direction($shouldBe, $body);
Expand Down
1 change: 0 additions & 1 deletion src/Context/Initializer/ServiceManagerInitializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
use Behat\Behat\Context\Context;
use Behat\Behat\Context\Initializer\ContextInitializer;
use Zend\Mvc\Service\ServiceManagerConfig;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;

Expand Down