Skip to content

Commit

Permalink
Refactored ContextAbstract and improved error handling (#23)
Browse files Browse the repository at this point in the history
  • Loading branch information
emulgeator authored Dec 19, 2017
1 parent 0206528 commit a93f3fc
Show file tree
Hide file tree
Showing 4 changed files with 233 additions and 151 deletions.
68 changes: 68 additions & 0 deletions src/Test/Integration/ErrorLogHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php
declare(strict_types = 1);

namespace ShoppinPal\YapepCommon\Test\Integration;

use YapepBase\Config;
use YapepBase\ErrorHandler\ErrorHandlerHelper;
use YapepBase\File\FileHandlerPhp;

class ErrorLogHandler
{
/**
* @var array
*/
protected $ignoredErrors = [];


public function ignoreError(int $errorCode, string $messagePrefix)
{
$errorHandlerHelper = new ErrorHandlerHelper();
$message = '[' . $errorHandlerHelper->getPhpErrorLevelDescription($errorCode) . '(' . $errorCode . ')]: '
. $messagePrefix;

$this->ignoredErrors[] = $message;
}

public function getLoggedErrors(): array
{
$errorLogPath = Config::getInstance()->get('resource.log.error.path');

$fileHandlerPhp = new FileHandlerPhp();

if (!$fileHandlerPhp->checkIsPathExists($errorLogPath)) {
return [];
}

$errorString = $fileHandlerPhp->getAsString($errorLogPath, 0);

if (empty($errorString)) {
return [];
}
$errors = [];
foreach (explode(PHP_EOL, $errorString) as $error) {
$errorMessage = json_decode($error, true)['message'];
if (empty($errorMessage)) {
continue;
}

if (!$this->isErrorIgnored($errorMessage)) {
$errors[] = $errorMessage;
}
}

return $errors;
}


protected function isErrorIgnored(string $errorMessage): bool
{
foreach ($this->ignoredErrors as $ignoredError) {
if (mb_strpos($errorMessage, $ignoredError) === 0) {
return true;
}
}

return false;
}
}
164 changes: 13 additions & 151 deletions src/Test/Integration/FeatureContextAbstract.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,9 @@

use Behat\Behat\Context\Context;
use PHPUnit\Framework\Assert;
use ShoppinPal\YapepCommon\Bootstrap\BootstrapAbstract;
use ShoppinPal\YapepCommon\Storage\StorageFactory;
use YapepBase\Application;
use YapepBase\Communication\CurlHttpRequest;
use YapepBase\Communication\CurlHttpRequestResult;
use YapepBase\Config;
use YapepBase\Exception\Exception;
use YapepBase\File\FileHandlerPhp;


/**
Expand All @@ -25,24 +20,19 @@ abstract class FeatureContextAbstract implements Context
{

/**
* @var string
* @var ErrorLogHandler
*/
protected $responseBody;
protected $errorLogHandler;

/**
* @var string
* @var LogHandler
*/
protected $responseHeaders;
protected $logHandler;

/**
* @var array
* @var RequestHandler
*/
protected $sentParams = array();

/**
* @var string
*/
protected $calledUrl;
protected $requestHandler;

/**
* @return DbInitializerAbstract
Expand Down Expand Up @@ -71,8 +61,12 @@ protected function doAfterInitScenario()
*/
public function initScenario()
{
$this->errorLogHandler = new ErrorLogHandler();
$this->logHandler = new LogHandler();
$this->requestHandler = new RequestHandler();

$this->getDbInitializer()->initDatabase();
$this->initLogs();
$this->logHandler->initLogs($this->getLogResourceNames());
$this->cleanUpStorages();
Application::getInstance()->getDiContainer()->getViewDo()->clear();
$this->doAfterInitScenario();
Expand All @@ -84,26 +78,13 @@ public function initScenario()
*/
public function afterScenario()
{
$loggedErrors = $this->getLoggedErrors();
$loggedErrors = $this->errorLogHandler->getLoggedErrors();

if (!empty($loggedErrors)) {
throw new Exception('Errors logged during the test: ' . PHP_EOL . implode(PHP_EOL, $loggedErrors));
}
}

public function initLogs()
{
$config = Config::getInstance();
foreach ($this->getLogResourceNames() as $resourceName) {
$errorLogPath = $config->get('resource.log.' . $resourceName . '.path');

$fileHandler = new FileHandlerPhp();

if ($fileHandler->checkIsPathExists($errorLogPath)) {
$fileHandler->remove($errorLogPath);
}
}
}

/**
* Cleans the given storage.
Expand All @@ -117,132 +98,13 @@ protected function cleanUpStorages()
}
}


protected function getLoggedErrors(): array
{
$errorLogPath = Config::getInstance()->get('resource.log.error.path');

$fileHandlerPhp = new FileHandlerPhp();

if (!$fileHandlerPhp->checkIsPathExists($errorLogPath)) {
return [];
}

$errorString = $fileHandlerPhp->getAsString($errorLogPath, 0);

if (empty($errorString)) {
return [];
}
$errors = [];
foreach (explode(PHP_EOL, $errorString) as $error) {
$errors[] = json_decode($error, true)['message'];
}
return $errors;
}

protected function callUrl(string $url, string $method = CurlHttpRequest::METHOD_GET, array $params = [], $storeResponse = true): CurlHttpRequestResult
{
$params[BootstrapAbstract::GET_PARAM_NAME_TESTING_MODE] = 1;
$this->sentParams = $params;
$this->calledUrl = $url;

$request = new CurlHttpRequest();
$request->setUrl($url);
$request->setMethod($method);
$request->setPayload($params, CurlHttpRequest::PAYLOAD_TYPE_QUERY_STRING_ARRAY);

$result = $request->send();
if ($storeResponse) {
$this->responseHeaders = $result->getResponseHeaders();
$this->responseBody = $result->getResponseBody();
}

return $result;
}

protected function callRestApi(
string $url,
string $method = CurlHttpRequest::METHOD_GET,
array $params = [],
array $headers = [],
$storeResponse = true
): CurlHttpRequestResult
{
$url = $url
. (strpos($url, '?') === false ? '?' : '&')
. BootstrapAbstract::GET_PARAM_NAME_TESTING_MODE . '=1';

$request = new CurlHttpRequest();
$request->setUrl($url);
$request->setMethod($method);
$request->addHeader('Content-Type: application/json');
if (!empty($this->sessionId)) {
$request->addHeader('Authorization: Session ' . $this->sessionId);
}
foreach ($headers as $header) {
$request->addHeader($header);
}

$request->setPayload(json_encode($params), CurlHttpRequest::PAYLOAD_TYPE_RAW);

$result = $request->send();
if ($storeResponse) {
$this->responseHeaders = $result->getResponseHeaders();
$this->responseBody = $result->getResponseBody();
}

return $result;
}

protected function getResponseBody(): array
{
return json_decode($this->responseBody, true);
}

protected function getResponseHeaders(): string
{
return $this->responseHeaders;
}


protected function formatDataForPost(array $post, array &$output, string $paramNamePrefix = null)
{
foreach ($post as $key => $value) {
$currentKey = !empty($paramNamePrefix) ? $paramNamePrefix . '[' . $key . ']' : $key;

if (is_array($value) || is_object($value)) {
$this->formatDataForPost($value, $output, $currentKey);
}
else {
$output[$currentKey] = $value;
}
}
}


protected function getLoggedEntries(string $logResourceName): array
{
$logPath = Config::getInstance()->get('resource.log.' . $logResourceName . '.path');
$logEntries = (new FileHandlerPhp())->getAsString($logPath);

if (empty($logEntries)) {
return array();
}

$loggedEntries = array();
foreach (explode(PHP_EOL, trim($logEntries, PHP_EOL)) as $logEntry) {
$loggedEntries[] = json_decode($logEntry, true);
}
return $loggedEntries;
}

/**
* @Then the http status of the response should be :statusCode
*/
public function theHttpStatusOfTheResponseShouldBe(int $statusCode)
{
Assert::assertContains(
'HTTP/1.1 ' . $statusCode . ' ', $this->responseHeaders, 'Expected status code not received'
'HTTP/1.1 ' . $statusCode . ' ', $this->requestHandler->getResponseHeaders(), 'Expected status code not received'
);
}
}
40 changes: 40 additions & 0 deletions src/Test/Integration/LogHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php
declare(strict_types = 1);

namespace ShoppinPal\YapepCommon\Test\Integration;

use YapepBase\Config;
use YapepBase\File\FileHandlerPhp;

class LogHandler
{
public function initLogs(array $resourceNames)
{
$config = Config::getInstance();
foreach ($resourceNames as $resourceName) {
$errorLogPath = $config->get('resource.log.' . $resourceName . '.path');

$fileHandler = new FileHandlerPhp();

if ($fileHandler->checkIsPathExists($errorLogPath)) {
$fileHandler->remove($errorLogPath);
}
}
}

public function getLoggedEntries(string $logResourceName): array
{
$logPath = Config::getInstance()->get('resource.log.' . $logResourceName . '.path');
$logEntries = (new FileHandlerPhp())->getAsString($logPath);

if (empty($logEntries)) {
return array();
}

$loggedEntries = array();
foreach (explode(PHP_EOL, trim($logEntries, PHP_EOL)) as $logEntry) {
$loggedEntries[] = json_decode($logEntry, true);
}
return $loggedEntries;
}
}
Loading

0 comments on commit a93f3fc

Please sign in to comment.