Skip to content

Commit 81cf119

Browse files
committed
🚀 Enhance Testing using mock
Signed-off-by: Lloric Mayuga Garcia <[email protected]>
1 parent f0525a5 commit 81cf119

File tree

10 files changed

+282
-88
lines changed

10 files changed

+282
-88
lines changed

phpunit.xml.dist

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,6 @@
2929
<junit outputFile="build/report.junit.xml"/>
3030
</logging>
3131
<php>
32-
<!-- https://developers.paymaya.com/blog/entry/api-test-merchants-and-test-cards -->
33-
<!-- Sandbox Party 1 -->
34-
<env name="PAYMAYA_SANDBOX_SECRET_KEY" value="sk-X8qolYjy62kIzEbr0QRK1h4b4KDVHaNcwMYk39jInSl"/>
35-
<env name="PAYMAYA_SANDBOX_PUBLIC_KEY" value="pk-Z0OSzLvIcOI2UIvDhdTGVVfRSSeiGStnceqwUE7n0Ah"/>
32+
3633
</php>
3734
</phpunit>

src/Client/BaseClient.php

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ abstract class BaseClient
99
{
1010
private PaymayaClient $paymayaClient;
1111

12-
abstract protected function uri(int $uriVersion): string;
12+
abstract public static function uri(int $uriVersion = 1): string;
1313

1414
final private function __construct(PaymayaClient $paymayaClient)
1515
{
@@ -57,17 +57,18 @@ protected function secretGet(array $options = [], int $uriVersion = 1): Response
5757
return $this->paymayaClient->secretClient()->get($this->uri($uriVersion), $options);
5858
}
5959

60-
/**
61-
* @param array $options
62-
* @param int $uriVersion
63-
*
64-
* @return \Psr\Http\Message\ResponseInterface
65-
* @throws \GuzzleHttp\Exception\GuzzleException
66-
*/
67-
protected function publicGet(array $options = [], int $uriVersion = 1): ResponseInterface
68-
{
69-
return $this->paymayaClient->publicClient()->get($this->uri($uriVersion), $options);
70-
}
60+
// uncomment when needed
61+
// /**
62+
// * @param array $options
63+
// * @param int $uriVersion
64+
// *
65+
// * @return \Psr\Http\Message\ResponseInterface
66+
// * @throws \GuzzleHttp\Exception\GuzzleException
67+
// */
68+
// protected function publicGet(array $options = [], int $uriVersion = 1): ResponseInterface
69+
// {
70+
// return $this->paymayaClient->publicClient()->get($this->uri($uriVersion), $options);
71+
// }
7172

7273
/**
7374
* @param string $appendUrl

src/Client/Checkout/CheckoutClient.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
class CheckoutClient extends BaseClient
1010
{
11-
protected function uri(int $uriVersion): string
11+
public static function uri(int $uriVersion = 1): string
1212
{
1313
return "checkout/v$uriVersion/checkouts";
1414
}

src/Client/Checkout/WebhookClient.php

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
namespace Lloricode\Paymaya\Client\Checkout;
44

5-
use Carbon\Carbon;
65
use GuzzleHttp\Exception\GuzzleException;
76
use Lloricode\Paymaya\Client\BaseClient;
87
use Lloricode\Paymaya\Request\Checkout\WebhookRequest;
@@ -14,11 +13,16 @@ class WebhookClient extends BaseClient
1413
* @param \Lloricode\Paymaya\Request\Checkout\WebhookRequest $webhookRequest
1514
* @param int $uriVersion
1615
*
16+
* @return \Lloricode\Paymaya\Response\Checkout\WebhookResponse
1717
* @throws \GuzzleHttp\Exception\GuzzleException
1818
*/
19-
public function register(WebhookRequest $webhookRequest, int $uriVersion = 1): void
19+
public function register(WebhookRequest $webhookRequest, int $uriVersion = 1): WebhookResponse
2020
{
21-
$this->secretPost(['json' => $webhookRequest], $uriVersion);
21+
$bodyContent = $this->secretPost(['json' => $webhookRequest], $uriVersion)
22+
->getBody()
23+
->getContents();
24+
25+
return WebhookResponse::new()->fromArray((array)json_decode($bodyContent));
2226
}
2327

2428
/**
@@ -44,11 +48,7 @@ public function retrieve(int $uriVersion = 1): array
4448
$array = [];
4549
foreach (json_decode($content, true) as $value) {
4650
$array[$value['name']] = WebhookResponse::new()
47-
->setId($value['id'])
48-
->setName($value['name'])
49-
->setCallbackUrl($value['callbackUrl'])
50-
->setCreatedAt(Carbon::parse($value['createdAt']))
51-
->setUpdatedAt(Carbon::parse($value['updatedAt']));
51+
->fromArray($value);
5252
}
5353

5454
return $array;
@@ -57,11 +57,15 @@ public function retrieve(int $uriVersion = 1): array
5757
/**
5858
* @param \Lloricode\Paymaya\Request\Checkout\WebhookRequest $webhookRequest
5959
*
60+
* @return \Lloricode\Paymaya\Response\Checkout\WebhookResponse
6061
* @throws \GuzzleHttp\Exception\GuzzleException
6162
*/
62-
public function update(WebhookRequest $webhookRequest): void
63+
public function update(WebhookRequest $webhookRequest): WebhookResponse
6364
{
64-
$this->secretPut($webhookRequest->getId() ?: '', ['json' => $webhookRequest]);
65+
$bodyContent = $this->secretPut($webhookRequest->getId() ?: '', ['json' => $webhookRequest])->getBody()
66+
->getContents();
67+
68+
return WebhookResponse::new()->fromArray((array)json_decode($bodyContent));
6569
}
6670

6771
/**
@@ -84,7 +88,7 @@ public function deleteAll(): void
8488
}
8589
}
8690

87-
protected function uri(int $uriVersion): string
91+
public static function uri(int $uriVersion = 1): string
8892
{
8993
return "/checkout/v$uriVersion/webhooks";
9094
}

src/PaymayaClient.php

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
use ErrorException;
66
use GuzzleHttp\Client as GuzzleClient;
7+
use GuzzleHttp\HandlerStack;
8+
use GuzzleHttp\Middleware;
79

810
final class PaymayaClient
911
{
@@ -12,32 +14,54 @@ final class PaymayaClient
1214

1315
public const ENVIRONMENT_SANDBOX = 'sandbox';
1416
public const ENVIRONMENT_PRODUCTION = 'production';
17+
public const ENVIRONMENT_TESTING = 'testing';
1518

1619
private string $public_key;
1720
private string $secret_key;
1821

1922
private string $environment;
2023
private string $base_url;
2124

25+
private ?HandlerStack $handler_stack = null;
26+
2227
/**
23-
* Client constructor.
28+
* PaymayaClient constructor.
2429
*
2530
* @param string $secretKey
2631
* @param string $publicKey
2732
* @param string $environment
33+
* @param \GuzzleHttp\HandlerStack|null $handlerStack
34+
* @param array $historyContainer
2835
*
2936
* @throws \ErrorException
3037
*/
31-
public function __construct(string $secretKey, string $publicKey, string $environment = self::ENVIRONMENT_SANDBOX)
32-
{
38+
public function __construct(
39+
string $secretKey,
40+
string $publicKey,
41+
string $environment = self::ENVIRONMENT_SANDBOX,
42+
HandlerStack $handlerStack = null,
43+
array &$historyContainer = []
44+
) {
3345
switch ($environment) {
46+
// @codeCoverageIgnoreStart
3447
case self::ENVIRONMENT_PRODUCTION:
3548
$this->base_url = self::BASE_URL_PRODUCTION;
3649

3750
break;
3851
case self::ENVIRONMENT_SANDBOX:
3952
$this->base_url = self::BASE_URL_SANDBOX;
4053

54+
break;
55+
// @codeCoverageIgnoreEnd
56+
case self::ENVIRONMENT_TESTING:
57+
$this->base_url = 'testing';
58+
59+
$this->handler_stack = $handlerStack;
60+
61+
if ( ! is_null($this->handler_stack)) {
62+
$this->handler_stack->push(Middleware::history($historyContainer));
63+
}
64+
4165
break;
4266
default:
4367
throw new ErrorException("Invalid environment `$environment`.");
@@ -54,6 +78,7 @@ private function client(array $header): GuzzleClient
5478
[
5579
'base_uri' => $this->base_url,
5680
'headers' => $header,
81+
'handler' => $this->handler_stack,
5782
]
5883
);
5984
}

src/Response/Checkout/WebhookResponse.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,4 +83,15 @@ public function jsonSerialize()
8383
'callbackUrl' => $this->callback_url,
8484
];
8585
}
86+
87+
public function fromArray(array $array): self
88+
{
89+
$this->setId($array['id'])
90+
->setName($array['name'])
91+
->setCallbackUrl($array['callbackUrl'])
92+
->setCreatedAt(Carbon::parse($array['createdAt']))
93+
->setUpdatedAt(Carbon::parse($array['updatedAt']));
94+
95+
return $this;
96+
}
8697
}

tests/CheckoutTest.php

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
use ErrorException;
66
use GuzzleHttp\Exception\ClientException;
77
use GuzzleHttp\Exception\GuzzleException;
8+
use GuzzleHttp\Handler\MockHandler;
9+
use GuzzleHttp\Psr7\Response;
810
use Lloricode\Paymaya\Client\Checkout\CheckoutClient;
911

1012
class CheckoutTest extends TestCase
@@ -23,10 +25,27 @@ public function json_check_exact_from_docs()
2325
*/
2426
public function check_via_sandbox()
2527
{
28+
$mock = new MockHandler(
29+
[
30+
new Response(
31+
200,
32+
[],
33+
json_encode(
34+
[
35+
'checkoutId' => '2d8416df-db69-4cbc-a694-2f51d81b85c0',
36+
'redirectUrl' => 'http://test',
37+
]
38+
),
39+
),
40+
]
41+
);
42+
43+
2644
$checkoutResponse = null;
2745

2846
try {
29-
$checkoutResponse = CheckoutClient::new(self::generatePaymayaClient())->execute(self::buildCheckout());
47+
$checkoutResponse = CheckoutClient::new(self::generatePaymayaClient($mock))
48+
->execute(self::buildCheckout());
3049
} catch (ErrorException $e) {
3150
$this->fail('ErrorException');
3251
} catch (ClientException $e) {

tests/ExceptionTest.php

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<?php
2+
3+
namespace Lloricode\Paymaya\Tests;
4+
5+
use ErrorException;
6+
use Lloricode\Paymaya\Client\Checkout\WebhookClient;
7+
use Lloricode\Paymaya\PaymayaClient;
8+
9+
class ExceptionTest extends TestCase
10+
{
11+
/**
12+
* @test
13+
*/
14+
public function invalid_env()
15+
{
16+
$this->expectException(ErrorException::class);
17+
$this->expectExceptionMessage('Invalid environment `invalid`.');
18+
$test = new PaymayaClient('', '', 'invalid');
19+
}
20+
21+
/**
22+
* @test
23+
*/
24+
public function webhook_zero_data_retrieved()
25+
{
26+
$history = [];
27+
$data = WebhookClient::new(
28+
self::mockApiClient(
29+
[
30+
],
31+
404,
32+
$history
33+
)
34+
)
35+
->retrieve();
36+
37+
$this->assertCount(0, $data);
38+
39+
40+
/** @var \GuzzleHttp\Psr7\Response $response */
41+
$response = $history[0]['response'];
42+
43+
$this->assertEquals(404, $response->getStatusCode());
44+
}
45+
}

tests/TestCase.php

Lines changed: 44 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
namespace Lloricode\Paymaya\Tests;
44

55
use Carbon\Carbon;
6+
use GuzzleHttp\Handler\MockHandler;
7+
use GuzzleHttp\HandlerStack;
8+
use GuzzleHttp\Psr7\Response;
69
use Lloricode\Paymaya\PaymayaClient;
710
use Lloricode\Paymaya\Request\Checkout\Amount\AmountDetailRequest;
811
use Lloricode\Paymaya\Request\Checkout\Amount\AmountRequest;
@@ -20,14 +23,51 @@
2023
abstract class TestCase extends BaseTestCase
2124
{
2225
/**
26+
* @param array $array
27+
* @param int $status
28+
* @param array $historyContainer
29+
*
2330
* @return \Lloricode\Paymaya\PaymayaClient
2431
* @throws \ErrorException
2532
*/
26-
protected static function generatePaymayaClient(): PaymayaClient
27-
{
33+
protected static function mockApiClient(
34+
array $array,
35+
int $status = 200,
36+
array &$historyContainer = []
37+
): PaymayaClient {
38+
return self::generatePaymayaClient(
39+
new MockHandler(
40+
[
41+
new Response(
42+
$status,
43+
[],
44+
json_encode(
45+
$array
46+
),
47+
),
48+
]
49+
),
50+
$historyContainer
51+
);
52+
}
53+
54+
/**
55+
* @param \GuzzleHttp\Handler\MockHandler $mockHandler
56+
* @param array $historyContainer
57+
*
58+
* @return \Lloricode\Paymaya\PaymayaClient
59+
* @throws \ErrorException
60+
*/
61+
protected static function generatePaymayaClient(
62+
MockHandler $mockHandler,
63+
array &$historyContainer = []
64+
): PaymayaClient {
2865
return new PaymayaClient(
29-
getenv('PAYMAYA_SANDBOX_SECRET_KEY'),
30-
getenv('PAYMAYA_SANDBOX_PUBLIC_KEY')
66+
'',
67+
'',
68+
PaymayaClient::ENVIRONMENT_TESTING,
69+
HandlerStack::create($mockHandler),
70+
$historyContainer
3171
);
3272
}
3373

0 commit comments

Comments
 (0)