Skip to content

Commit

Permalink
Merge pull request #3 from PAYONE-GmbH/refactor/tests-for-initial-imp…
Browse files Browse the repository at this point in the history
…lementation

refactor/tests for initial implementation
  • Loading branch information
lrosenfeldt authored Jul 29, 2024
2 parents 5c5fe85 + 0924da7 commit bfcb38d
Show file tree
Hide file tree
Showing 14 changed files with 1,198 additions and 91 deletions.
5 changes: 4 additions & 1 deletion phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
<source>
<include>
<directory suffix=".php">src</directory>
<directory suffix=".php">lib</directory>
</include>

<exclude>
<directory suffix=".php">src/PayoneCommercePlatform/Sdk/Models</directory>
</exclude>
</source>
</phpunit>
13 changes: 6 additions & 7 deletions src/PayoneCommercePlatform/Sdk/ApiClient/BaseApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
use Symfony\Component\Serializer\Normalizer\BackedEnumNormalizer;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

class BaseApiClient
Expand Down Expand Up @@ -140,7 +139,7 @@ protected function makeApiCall(Request $request, ?string $type = null): array
$response->getStatusCode(),
$response->getHeaders()
];
} catch (\JsonException $exception) {
} catch (NotEncodableValueException | UnexpectedValueException $exception) {
throw new ApiResponseRetrievalException(
message: sprintf(
'Error JSON decoding server response (%s)',
Expand Down Expand Up @@ -172,13 +171,12 @@ function ($response) use ($returnType) {
$contents = "";
try {
$contents = $response->getBody()->getContents();
$decoded = json_decode($contents, false, 512, JSON_THROW_ON_ERROR);
return [
self::$serializer->deserialize($decoded, $returnType, 'json'),
self::$serializer->deserialize($contents, $returnType, 'json'),
$response->getStatusCode(),
$response->getHeaders()
];
} catch (\JsonException $exception) {
} catch (NotEncodableValueException | UnexpectedValueException $exception) {
throw new ApiResponseRetrievalException(
message: 'Error JSON decoding server response',
statusCode: $response->getStatusCode(),
Expand Down Expand Up @@ -247,8 +245,9 @@ public static function init(): void
$propertyTypeExtractor = new PropertyInfoExtractor([$reflectionExtractor, $phpDocExtractor], [$phpDocExtractor, $reflectionExtractor]);
self::$serializer = new Serializer(
normalizers: [
new ArrayDenormalizer(), new GetSetMethodNormalizer(propertyTypeExtractor: $propertyTypeExtractor),
new DateTimeNormalizer(), new BackedEnumNormalizer(),
new ArrayDenormalizer(), new DateTimeNormalizer(),
new GetSetMethodNormalizer(propertyTypeExtractor: $propertyTypeExtractor),
new BackedEnumNormalizer(),
],
encoders: [new JsonEncoder()]
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ public function createPaymentInformationRequest(
* @param string $merchantId The merchantId identifies uniquely the merchant. (required)
* @param string $commerceCaseId Unique identifier of a Commerce Case. (required)
* @param string $checkoutId Unique identifier of a Checkout (required)
* @param string $paymentInformationId Unique identifier of a paymentInformation (required)
*
* @throws ApiErrorResponseException|ApiResponseRetrievalException
* @return \PayoneCommercePlatform\Sdk\Models\PaymentInformationResponse
Expand Down
54 changes: 0 additions & 54 deletions src/PayoneCommercePlatform/Sdk/CommunicatorConfiguration.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,6 @@ class CommunicatorConfiguration
{
public const SDK_VERSION = '0.0.1';

public const BOOLEAN_FORMAT_INT = 'int';
public const BOOLEAN_FORMAT_STRING = 'string';

/**
* Boolean format for query string
*
* @var string
*/
protected string $booleanFormatForQueryString = self::BOOLEAN_FORMAT_INT;

/**
* Api key for the PAYONE Commerce Platform
*
Expand Down Expand Up @@ -139,30 +129,6 @@ public function __construct(
$this->debugFile = $debugFile;
}

/**
* Sets boolean format for query string.
*
* @param string $booleanFormat Boolean format for query string
*
* @return $this
*/
public function setBooleanFormatForQueryString(string $booleanFormat): self
{
$this->booleanFormatForQueryString = $booleanFormat;

return $this;
}

/**
* Gets boolean format for query string.
*
* @return string Boolean format for query string
*/
public function getBooleanFormatForQueryString(): string
{
return $this->booleanFormatForQueryString;
}

/**
* Sets the API key
*
Expand Down Expand Up @@ -269,10 +235,6 @@ public function getHost(): string
*/
public function setUserAgent(string $userAgent): self
{
if (!is_string($userAgent)) {
throw new \InvalidArgumentException('User-agent must be a string.');
}

$this->userAgent = $userAgent;
return $this;
}
Expand Down Expand Up @@ -422,22 +384,6 @@ public function getTempFolderPath(): string
return $this->tempFolderPath;
}

/**
* Gets the essential information for debugging
*
* @return string The report for debugging
*/
public function toDebugReport(): string
{
$report = 'PHP SDK (PayoneCommercePlatform\Sdk) Debug Report:' . PHP_EOL;
$report .= ' OS: ' . php_uname() . PHP_EOL;
$report .= ' PHP Version: ' . PHP_VERSION . PHP_EOL;
$report .= ' The version of the OpenAPI document: 1.6.0' . PHP_EOL;
$report .= ' Temp Folder Path: ' . $this->getTempFolderPath() . PHP_EOL;

return $report;
}

/**
* Returns an array of host settings
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,11 @@ public function __construct(
string $checkoutId,
string $merchantCustomerId,
string $paymentInformationId,
?PaymentChannel $paymentChannel,
int $paymentProductId,
string $terminalId,
string $cardAcceptorId,
string $merchantReference,
?PaymentChannel $paymentChannel = null,
?CardPaymentDetails $cardPaymentDetails = null,
?array $events = null
) {
Expand Down
143 changes: 115 additions & 28 deletions tests/PayoneCommercePlatform/Sdk/ApiClient/CheckoutApiClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,52 +2,35 @@

namespace PayoneCommercePlatform\Sdk\ApiClient;

use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\MockObject\Stub;
use PayoneCommercePlatform\Sdk\Models\APIError;
use PHPUnit\Framework\TestCase;
use PayoneCommercePlatform\Sdk\TestUtils\TestApiClientTrait;
use PayoneCommercePlatform\Sdk\Models\AddressPersonal;
use PayoneCommercePlatform\Sdk\Models\AmountOfMoney;
use PayoneCommercePlatform\Sdk\Models\CheckoutResponse;
use PayoneCommercePlatform\Sdk\Models\CheckoutsResponse;
use PayoneCommercePlatform\Sdk\Models\CreateCheckoutRequest;
use PayoneCommercePlatform\Sdk\Models\CreateCheckoutResponse;
use PayoneCommercePlatform\Sdk\Models\ErrorResponse;
use PayoneCommercePlatform\Sdk\Errors\ApiErrorResponseException;
use PayoneCommercePlatform\Sdk\CommunicatorConfiguration;
use PHPUnit\Framework\TestCase;
use PayoneCommercePlatform\Sdk\Errors\ApiResponseRetrievalException;
use PayoneCommercePlatform\Sdk\Models\PatchCheckoutRequest;
use PayoneCommercePlatform\Sdk\Models\Shipping;
use PayoneCommercePlatform\Sdk\Queries\GetCheckoutsQuery;

class CheckoutApiClientTest extends TestCase
{
private CommunicatorConfiguration $communicatorConfiguration;
private ClientInterface & Stub $httpClient;
use TestApiClientTrait;
private CheckoutApiClient $checkoutClient;
private String $merchantId = "MY_MERCHANT_ID";

public function setUp(): void
{
$this->communicatorConfiguration = new CommunicatorConfiguration(apiKey: "KEY", apiSecret: "SECRET", host: "awesome-api.com", clientMetaInfo: []);
$this->httpClient = $this->createStub(ClientInterface::class);
$this->initTestConfig();
$this->checkoutClient = new CheckoutApiClient($this->communicatorConfiguration, client: $this->httpClient);
}

protected function makeCheckoutResponse(): CheckoutResponse
{
return new CheckoutResponse(
commerceCaseId: 'id1',
checkoutId: 'id2',
merchantCustomerId: 'id3',
amountOfMoney: new AmountOfMoney(amount: 1000, currencyCode: 'EUR')
);
}

protected function makeErrorResponse(): ErrorResponse
{
return new ErrorResponse(errorId: 'test-id', errors: [new APIError('test-code')]);
}

public function testCreateCheckout(): void
{
$createCheckoutResponse = new CreateCheckoutResponse(amountOfMoney: new AmountOfMoney(amount: 1337, currencyCode: 'EUR'));
Expand Down Expand Up @@ -92,17 +75,24 @@ public function testCreateCheckoutUnsuccessful500(): void
public function testGetCheckoutsSuccessful(): void
{
// arrange
$checkoutsResponse = new CheckoutsResponse(1, [$this->makeCheckoutResponse()]);
$checkoutResponse = new CheckoutResponse(
commerceCaseId: 'id1',
checkoutId: 'id2',
merchantCustomerId: 'id3',
amountOfMoney: new AmountOfMoney(amount: 1000, currencyCode: 'EUR')
);
$checkoutsResponse = new CheckoutsResponse(1, [$checkoutResponse]);
$this->httpClient->method('send')->willReturn(new Response(status: 200, body: BaseApiClient::getSerializer()->serialize($checkoutsResponse, 'json')));

// act
$response = $this->checkoutClient->getCheckouts($this->merchantId);
$query = (new GetCheckoutsQuery())->setOffset(0)->setSize(10);
$response = $this->checkoutClient->getCheckouts($this->merchantId, $query);
$allCheckouts = $response->getCheckouts();
$checkout = $allCheckouts ? $allCheckouts[0] : null;

// assert
$this->assertEquals(1, $checkoutsResponse->getNumberOfCheckouts());
$this->assertEquals($this->makeCheckoutResponse(), $checkout);
$this->assertEquals($checkoutResponse, $checkout);
}

public function testGetCheckoutsUnsuccessful400(): void
Expand All @@ -129,4 +119,101 @@ public function testGetCheckoutsUnsuccessful500(): void
// act
$response = $this->checkoutClient->getCheckouts($this->merchantId);
}

public function testDeleteCheckoutSuccessful(): void
{
$this->expectNotToPerformAssertions();
$this->httpClient->method('send')->willReturn(new Response(status: 204, body: ''));

$this->checkoutClient->deleteCheckout('1', '2', '3');
}

public function testDeleteCheckoutUnsuccessful400(): void
{
$errorResponse = $this->makeErrorResponse();
$this->httpClient->method('send')->willReturn(new Response(status: 400, body: BaseApiClient::getSerializer()->serialize($errorResponse, 'json')));
$this->expectException(ApiErrorResponseException::class);
$this->expectExceptionCode(400);

$this->checkoutClient->deleteCheckout('1', '2', '3');
}

public function testDeleteCheckoutUnsuccessful500(): void
{
$errorResponse = $this->makeErrorResponse();
$this->httpClient->method('send')->willReturn(new Response(status: 500, body: null));
$this->expectException(ApiResponseRetrievalException::class);
$this->expectExceptionCode(500);

$this->checkoutClient->deleteCheckout('1', '2', '3');
}

public function testGetCheckoutSuccessful(): void
{
$checkoutResponse = new CheckoutResponse(
commerceCaseId: 'id1',
checkoutId: 'id2',
merchantCustomerId: 'id3',
amountOfMoney: new AmountOfMoney(amount: 1000, currencyCode: 'EUR')
);
$this->httpClient->method('send')->willReturn(new Response(status: 200, body: BaseApiClient::getSerializer()->serialize($checkoutResponse, 'json')));

$response = $this->checkoutClient->getCheckout('1', '2', '3');

$this->assertEquals($checkoutResponse, $response);
}

public function testGetCheckoutUnsuccessful400(): void
{
$errorResponse = $this->makeErrorResponse();
$this->httpClient->method('send')->willReturn(new Response(status: 400, body: BaseApiClient::getSerializer()->serialize($errorResponse, 'json')));
$this->expectException(ApiErrorResponseException::class);
$this->expectExceptionCode(400);

$this->checkoutClient->getCheckout('1', '2', '3');
}

public function testGetCheckoutUnsuccessful500(): void
{
$errorResponse = $this->makeErrorResponse();
$this->httpClient->method('send')->willReturn(new Response(status: 500, body: null));
$this->expectException(ApiResponseRetrievalException::class);
$this->expectExceptionCode(500);

$this->checkoutClient->getCheckout('1', '2', '3');
}

public function testUpdateCheckoutSuccessful(): void
{
$this->expectNotToPerformAssertions();

$payload = new PatchCheckoutRequest(
amountOfMoney: new AmountOfMoney(amount: 1000, currencyCode: 'EUR'),
shipping: new Shipping(new AddressPersonal(city: 'Hometown')),
);
$this->httpClient->method('send')->willReturn(new Response(status: 204, body: ''));
$this->checkoutClient->updateCheckout('1', '2', '3', $payload);
}

public function testUpdateCheckoutUnsuccessful400(): void
{
$errorResponse = $this->makeErrorResponse();
$this->httpClient->method('send')->willReturn(new Response(status: 400, body: BaseApiClient::getSerializer()->serialize($errorResponse, 'json')));
$this->expectException(ApiErrorResponseException::class);
$this->expectExceptionCode(400);

$payload = new PatchCheckoutRequest();
$this->checkoutClient->updateCheckout('1', '2', '3', $payload);
}

public function testUpdateCheckoutUnsuccessful500(): void
{
$errorResponse = $this->makeErrorResponse();
$this->httpClient->method('send')->willReturn(new Response(status: 500, body: null));
$this->expectException(ApiResponseRetrievalException::class);
$this->expectExceptionCode(500);

$payload = new PatchCheckoutRequest();
$this->checkoutClient->updateCheckout('1', '2', '3', $payload);
}
}
Loading

0 comments on commit bfcb38d

Please sign in to comment.