Skip to content

Commit

Permalink
minor #15922 [Unit][Admin] Missing Payments Tests (Rafikooo)
Browse files Browse the repository at this point in the history
This PR was merged into the 1.13 branch.

Discussion
----------

| Q               | A                                                            |
|-----------------|--------------------------------------------------------------|
| Branch?         | 1.13 <!-- see the comment below -->                  |
| Bug fix?        | no                                                      |
| New feature?    | no                                                      |
| BC breaks?      | no                                                      |
| Deprecations?   | no<!-- don't forget to update the UPGRADE-*.md file --> |
| License         | MIT                                                          |

<!--
 - Bug fixes must be submitted against the 1.12 branch
 - Features and deprecations must be submitted against the 1.13 branch
 - Make sure that the correct base branch is set

 To be sure you are not breaking any Backward Compatibilities, check the documentation:
 https://docs.sylius.com/en/latest/book/organization/backward-compatibility-promise.html
-->


Commits
-------
  [Unit][Admin] Add a payment completion test
  [Unit] Add requestPatch method to utils functions
  [Unit][Admin] Add another payment completion test
  [Unit][Admin] Add payments filtering by payment state test
  [ECS] Apply ecs fixes
  • Loading branch information
NoResponseMate committed Feb 29, 2024
2 parents bf67089 + 98f758d commit 339d393
Show file tree
Hide file tree
Showing 10 changed files with 233 additions and 42 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
/** @experimental */
final class ShippingMethodDocumentationModifier implements DocumentationModifierInterface
{

public const ROUTE_ADMIN_SHIPPING_METHODS = '/admin/shipping-methods';

public const ROUTE_ADMIN_SHIPPING_METHOD = '/admin/shipping-methods/{code}';
Expand All @@ -31,7 +30,7 @@ final class ShippingMethodDocumentationModifier implements DocumentationModifier
public function __construct(
private string $apiRoute,
private array $ruleTypes,
private array $shippingMethodCalculators
private array $shippingMethodCalculators,
) {
}

Expand Down
2 changes: 1 addition & 1 deletion tests/Api/Admin/OrdersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ protected function setUp(): void
{
$this->setUpOrderPlacer();
$this->setUpAdminContext();
$this->setUpDefaultHeaders();
$this->setUpDefaultGetHeaders();

parent::setUp();
}
Expand Down
103 changes: 81 additions & 22 deletions tests/Api/Admin/PaymentsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,25 +14,46 @@
namespace Sylius\Tests\Api\Admin;

use Sylius\Tests\Api\JsonApiTestCase;
use Sylius\Tests\Api\Utils\AdminUserLoginTrait;
use Sylius\Tests\Api\Utils\OrderPlacerTrait;
use Symfony\Component\HttpFoundation\Response;

final class PaymentsTest extends JsonApiTestCase
{
use AdminUserLoginTrait;
use OrderPlacerTrait;

protected function setUp(): void
{
$this->setUpOrderPlacer();
$this->setUpAdminContext();

parent::setUp();
}

/** @test */
public function it_gets_payments_of_the_specific_order(): void
public function it_gets_payments(): void
{
$this->setUpDefaultGetHeaders();

$this->loadFixturesFromFiles([
'authentication/api_administrator.yaml',
'channel.yaml',
'cart.yaml',
'country.yaml',
'shipping_method.yaml',
'payment_method.yaml',
]);

$this->placeOrder('nAWw2jewpA');

$this->requestGet(uri: '/api/v2/admin/payments');

$this->assertResponseSuccessful('admin/payment/get_payments_response');
}

/** @test */
public function it_gets_payments_filtered_by_state(): void
{
$this->setUpDefaultGetHeaders();

$this->loadFixturesFromFiles([
'authentication/api_administrator.yaml',
'channel.yaml',
Expand All @@ -41,27 +62,67 @@ public function it_gets_payments_of_the_specific_order(): void
'shipping_method.yaml',
'payment_method.yaml',
]);
$header = array_merge($this->logInAdminUser('api@example.com'), self::CONTENT_TYPE_HEADER);

$tokenValue = 'nAWw2jewpA';
$order = $this->placeOrder('paidOrder');
$this->payOrder($order);

$this->placeOrder('unpaidOrder');

$this->requestGet(uri: '/api/v2/admin/payments', queryParameters: ['state' => 'new']);

$this->placeOrder($tokenValue);
$this->assertResponseSuccessful('admin/payment/get_payments_filtered_by_state_response');
}

$this->client->request(method: 'GET', uri: '/api/v2/admin/orders/nAWw2jewpA', server: $header);
/** @test */
public function it_gets_payments_of_the_specific_order(): void
{
$this->setUpDefaultGetHeaders();

$this->loadFixturesFromFiles([
'authentication/api_administrator.yaml',
'channel.yaml',
'cart.yaml',
'country.yaml',
'shipping_method.yaml',
'payment_method.yaml',
]);

$this->placeOrder('nAWw2jewpA');

$this->requestGet(uri: '/api/v2/admin/orders/nAWw2jewpA');
$orderResponse = json_decode($this->client->getResponse()->getContent(), true);

$this->client->request(
method: 'GET',
uri: '/api/v2/admin/payments/' . $orderResponse['payments'][0]['id'],
server: $header,
);
$response = $this->client->getResponse();
$this->assertResponse($response, 'admin/payment/get_payment_response', Response::HTTP_OK);
$this->requestGet(uri: '/api/v2/admin/payments/' . $orderResponse['payments'][0]['id']);

$this->assertResponseSuccessful('admin/payment/get_payment_response');
}

/** @test */
public function it_gets_payments(): void
public function it_completes_payment(): void
{
$this->setUpDefaultPatchHeaders();

$this->loadFixturesFromFiles([
'authentication/api_administrator.yaml',
'channel.yaml',
'cart.yaml',
'country.yaml',
'shipping_method.yaml',
'payment_method.yaml',
]);

$order = $this->placeOrder('nAWw2jewpA');

$this->requestPatch(uri: sprintf('/api/v2/admin/payments/%s/complete', $order->getPayments()->first()->getId()));

$this->assertResponseSuccessful('admin/payment/patch_complete_payment_response');
}

/** @test */
public function it_does_not_complete_payment_if_it_is_not_in_the_new_state(): void
{
$this->setUpDefaultPatchHeaders();

$this->loadFixturesFromFiles([
'authentication/api_administrator.yaml',
'channel.yaml',
Expand All @@ -70,14 +131,12 @@ public function it_gets_payments(): void
'shipping_method.yaml',
'payment_method.yaml',
]);
$tokenValue = 'nAWw2jewpA';

$this->placeOrder($tokenValue);
$order = $this->placeOrder('nAWw2jewpA');

$header = array_merge($this->logInAdminUser('api@example.com'), self::CONTENT_TYPE_HEADER);
$this->payOrder($order);
$this->requestPatch(uri: sprintf('/api/v2/admin/payments/%s/complete', $order->getPayments()->first()->getId()));

$this->client->request(method: 'GET', uri: '/api/v2/admin/payments', server: $header);
$response = $this->client->getResponse();
$this->assertResponse($response, 'admin/payment/get_payments_response', Response::HTTP_OK);
$this->assertResponseUnprocessableEntity('admin/payment/patch_not_complete_payment_response');
}
}
2 changes: 1 addition & 1 deletion tests/Api/Admin/ProductReviewsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ public function it_does_not_allow_to_update_a_product_review_with_invalid_rating
[
'propertyPath' => 'rating',
'message' => 'Review rating must be between 1 and 5.',
]
],
],
);
}
Expand Down
67 changes: 55 additions & 12 deletions tests/Api/JsonApiTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ abstract class JsonApiTestCase extends BaseJsonApiTestCase
/** @var array <string, string> */
private array $defaultGetHeaders = [];

/** @var array <string, string> */
private array $defaultPatchHeaders = [];

/**
* @param array<array-key, mixed> $data
*/
Expand All @@ -49,14 +52,22 @@ protected function setUpAdminContext(): void
$this->isAdminContext = true;
}

protected function setUpDefaultHeaders(): void
protected function setUpDefaultGetHeaders(): void
{
$this->defaultGetHeaders = [
'HTTP_ACCEPT' => 'application/ld+json',
'CONTENT_TYPE' => 'application/ld+json',
];
}

protected function setUpDefaultPatchHeaders(): void
{
$this->defaultPatchHeaders = [
'HTTP_ACCEPT' => 'application/ld+json',
'CONTENT_TYPE' => 'application/merge-patch+json',
];
}

protected function get(string $id): ?object
{
if (property_exists(static::class, 'container')) {
Expand Down Expand Up @@ -87,23 +98,24 @@ protected function headerBuilder(): HeadersBuilder
*/
protected function requestGet(string $uri, array $queryParameters = [], array $headers = []): Crawler
{
if ($this->isAdminContext) {
$headers = array_merge($this->headerBuilder()->withAdminUserAuthorization('api@example.com')->build(), $headers);
}

if (!empty($this->defaultGetHeaders)) {
$headers = array_merge($this->defaultGetHeaders, $headers);
}

$queryStrings = empty($queryParameters) ? '' : http_build_query($queryParameters);
return $this->request('GET', $uri, $queryParameters, $headers);
}

$uri = $queryStrings ? $uri . '?' . $queryStrings : $uri;
/**
* @param array<string, array<string>|string> $queryParameters
* @param array<string, string> $headers
*/
protected function requestPatch(string $uri, array $queryParameters = [], array $headers = []): Crawler
{
if (!empty($this->defaultPatchHeaders)) {
$headers = array_merge($this->defaultPatchHeaders, $headers);
}

return $this->client->request(
method: 'GET',
uri: $uri,
server: $headers,
);
return $this->request('PATCH', $uri, $queryParameters, $headers);
}

/** @throws \Exception */
Expand All @@ -116,6 +128,16 @@ protected function assertResponseSuccessful(string $filename): void
);
}

/** @throws \Exception */
protected function assertResponseUnprocessableEntity(string $filename): void
{
$this->assertResponse(
$this->client->getResponse(),
$filename,
Response::HTTP_UNPROCESSABLE_ENTITY,
);
}

/**
* @throws \Exception
*
Expand Down Expand Up @@ -156,4 +178,25 @@ protected function assertJsonResponseViolations(Response $response, array $expec
$this->assertContains($expectedViolation['message'], $violationMap[$propertyPath], $responseContent);
}
}

/**
* @param array<string, array<string>|string> $queryParameters
* @param array<string, string> $headers
*/
protected function request(string $method, string $uri, array $queryParameters = [], array $headers = []): Crawler
{
if ($this->isAdminContext) {
$headers = array_merge($this->headerBuilder()->withAdminUserAuthorization('api@example.com')->build(), $headers);
}

$queryStrings = empty($queryParameters) ? '' : http_build_query($queryParameters);

$uri = $queryStrings ? $uri . '?' . $queryStrings : $uri;

return $this->client->request(
method: $method,
uri: $uri,
server: $headers,
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
{
"@context": "\/api\/v2\/contexts\/Payment",
"@id": "\/api\/v2\/admin\/payments",
"@type": "hydra:Collection",
"hydra:member": [
{
"@id": "\/api\/v2\/admin\/payments\/@integer@",
"@type": "Payment",
"order": "\/api\/v2\/admin\/orders\/unpaidOrder",
"id": @integer@,
"method": {
"@id": "\/api\/v2\/admin\/payment-methods\/CASH_ON_DELIVERY",
"@type": "PaymentMethod",
"translations": {
"en_US": {
"@id": "\/api\/v2\/admin\/payment-method-translations\/@integer@",
"@type": "PaymentMethodTranslation",
"name": "Cash on delivery"
}
}
},
"currencyCode": "USD",
"amount": 6500,
"state": "new",
"details": [],
"createdAt": @datetime@,
"updatedAt": @datetime@
}
],
"hydra:totalItems": 1,
"hydra:view": {
"@id": "\/api\/v2\/admin\/payments?state=new",
"@type": "hydra:PartialCollectionView"
},
"hydra:search": {
"@type": "hydra:IriTemplate",
"hydra:template": "\/api\/v2\/admin\/payments{?state,state[],order.channel.code,order.channel.code[]}",
"hydra:variableRepresentation": "BasicRepresentation",
"hydra:mapping": [
{
"@type": "IriTemplateMapping",
"variable": "state",
"property": "state",
"required": false
},
{
"@type": "IriTemplateMapping",
"variable": "state[]",
"property": "state",
"required": false
},
{
"@type": "IriTemplateMapping",
"variable": "order.channel.code",
"property": "order.channel.code",
"required": false
},
{
"@type": "IriTemplateMapping",
"variable": "order.channel.code[]",
"property": "order.channel.code",
"required": false
}
]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"@context": "\/api\/v2\/contexts\/Payment",
"@id": "\/api\/v2\/admin\/payments\/@integer@",
"@type": "Payment",
"order": "\/api\/v2\/admin\/orders\/nAWw2jewpA",
"id": @integer@,
"method": "\/api\/v2\/admin\/payment-methods\/CASH_ON_DELIVERY",
"currencyCode": "USD",
"amount": 6500,
"state": "completed",
"details": [],
"createdAt": @string@,
"updatedAt": @string@
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"@context": "\/api\/v2\/contexts\/Error",
"@type": "hydra:Error",
"hydra:title": "An error occurred",
"hydra:description": "Cannot complete the payment."
}
4 changes: 2 additions & 2 deletions tests/Api/Shop/ProductReviewsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,8 @@ public function it_prevents_from_creating_a_product_review_without_email(): void
[
'propertyPath' => 'email',
'message' => 'Please enter your email.',
]
]
],
],
);
}

Expand Down

0 comments on commit 339d393

Please sign in to comment.