Skip to content

Commit

Permalink
UHF-9239: Style fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
hyrsky committed Jan 11, 2024
1 parent f0889f6 commit 65dd80f
Show file tree
Hide file tree
Showing 7 changed files with 62 additions and 52 deletions.
2 changes: 1 addition & 1 deletion src/ApiClient/ApiAuthorizerInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ interface ApiAuthorizerInterface {
* Gets the authorization header value.
*
* @return string|null
* The authorization header value.
* The authorization header value.
*/
public function getAuthorization(): ?string;

Expand Down
14 changes: 8 additions & 6 deletions src/ApiClient/ApiClientBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@ abstract class ApiClientBase {
* Construct an instance.
*
* @param \GuzzleHttp\ClientInterface $httpClient
* The HTTP client.
* The HTTP client.
* @param \Drupal\Core\Cache\CacheBackendInterface $cache
* The cache service.
* @param \Drupal\Component\Datetime\TimeInterface $time
* The time service.
* The time service.
* @param \Drupal\helfi_api_base\Environment\EnvironmentResolverInterface $environmentResolver
* The environment resolver.
* @param \Psr\Log\LoggerInterface $logger
Expand Down Expand Up @@ -94,7 +94,7 @@ public function hasAuthorization(): bool {
* Gets the default request options.
*
* @param string $environmentName
* Environment name.
* Environment name.
* @param array $options
* The optional options.
*
Expand Down Expand Up @@ -130,6 +130,8 @@ protected function getRequestOptions(string $environmentName, array $options = [
* The endpoint in the instance.
* @param array $options
* Body for requests.
* @param string|null $fixture
* Replace failed response from this file in local environment.
*
* @return \Drupal\helfi_api_base\ApiClient\ApiResponse
* The JSON object.
Expand All @@ -140,7 +142,7 @@ protected function makeRequest(
string $method,
string $url,
array $options = [],
?callable $mockCallback = NULL,
string $fixture = NULL,
): ApiResponse {
$activeEnvironmentName = $this->environmentResolver
->getActiveEnvironment()
Expand All @@ -164,15 +166,15 @@ protected function makeRequest(

// Serve mock data in local environments if requests fail.
if (
$mockCallback &&
$fixture &&
($e instanceof ClientException || $e instanceof ConnectException) &&
$activeEnvironmentName === 'local'
) {
$this->logger->warning(
sprintf('Request failed: %s. Mock data is used instead.', $e->getMessage())
);

return $mockCallback();
return ApiFixture::requestFromFile($fixture);
}

$this->logger->error('Request failed with error: ' . $e->getMessage());
Expand Down
4 changes: 2 additions & 2 deletions src/ApiClient/VaultAuthorizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
use Drupal\helfi_api_base\Vault\VaultManager;

/**
Performs HTTP basic authentication using credentials from VaultManager.
* HTTP basic authentication using credentials from VaultManager.
*/
final readonly class VaultAuthorizer implements ApiAuthorizerInterface {

Expand Down Expand Up @@ -36,7 +36,7 @@ public function __construct(
* Gets the authorization value.
*
* @return string|null
* The authorization value.
* The authorization value.
*/
public function getAuthorization(): ?string {
if ($token = $this->getToken()) {
Expand Down
13 changes: 7 additions & 6 deletions tests/modules/helfi_api_client_test/src/ApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,25 @@
use Drupal\helfi_api_base\ApiClient\ApiClientBase;
use Drupal\helfi_api_base\ApiClient\ApiResponse;
use Drupal\helfi_api_base\ApiClient\CacheValue;
use GuzzleHttp\Exception\GuzzleException;

/**
* Class responsible for performing language negotiation.
* Api client for testing.
*/
class ApiClient extends ApiClientBase {

/**
* Expose protected method for testing.
*
* @throws GuzzleException
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function exposedMakeRequest(string $method, string $url, array $options = [], ?callable $mockCallback = NULL): ApiResponse {
return $this->makeRequest($method, $url, $options, $mockCallback);
public function exposedMakeRequest(string $method, string $url, array $options = [], ?string $fixture = NULL): ApiResponse {
return $this->makeRequest($method, $url, $options, $fixture);
}

/**
* Expose protected method for testing
* Expose protected method for testing.
*
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function exposedCache(string $key, callable $callback): CacheValue {
return $this->cache($key, $callback);
Expand Down
75 changes: 41 additions & 34 deletions tests/src/Unit/ApiClient/ApiClientBaseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,12 @@ private function getTimeMock(int $expectedTime) : ObjectProphecy {
* The time prophecy.
* @param \Psr\Log\LoggerInterface|null $logger
* The logger.
* @param string|null $apiKey
* The api key.
* @param \Drupal\helfi_api_base\ApiClient\ApiAuthorizerInterface|null $authorizer
* The api authorizer.
* @param \Drupal\helfi_api_base\Environment\EnvironmentResolverInterface|null $environmentResolver
* The environment resolver.
* @param array $requestOptions
* The default request options.
*
* @return \Drupal\helfi_api_client_test\ApiClient
* The api client instance.
Expand Down Expand Up @@ -126,22 +128,6 @@ private function getSut(
]));
}

/*
return new class (
$client,
$this->cache,
$time,
$environmentResolver,
$logger,
$authorizer,
$requestOptions,
) extends ApiClientBase {
public function publicCache(string $key, callable $callback) {
$this->cache($key, $callback);
}
};
*/

return new ApiClient(
$client,
$this->cache,
Expand Down Expand Up @@ -180,17 +166,44 @@ public function testAuthorization() : void {
]),
'vault_key',
),
requestOptions: [
'headers' => ['X-Custom-Header' => '1'],
],
);

$response = $sut->exposedMakeRequest('GET', '/foo');
$sut->exposedMakeRequest('GET', '/foo');

$this->assertCount(1, $requests);
$this->assertInstanceOf(ApiResponse::class, $response);
$this->assertInstanceOf(RequestInterface::class, $requests[0]['request']);
// Make sure SSL verification is disabled on local.
$this->assertFalse($requests[0]['options']['verify']);
// Make sure Authorization header was set.
// Make sure headers are set.
$this->assertEquals('Basic 123', $requests[0]['request']->getHeader('Authorization')[0]);
$this->assertEquals('1', $requests[0]['request']->getHeader('X-Custom-Header')[0]);
}

/**
* Test makeRequest().
*
* @covers ::__construct
* @covers ::makeRequest
* @covers ::getRequestOptions
* @covers ::hasAuthorization
* @covers \Drupal\helfi_api_base\ApiClient\ApiResponse::__construct
*/
public function testMakeRequest() {
$requests = [];
$client = $this->createMockHistoryMiddlewareHttpClient($requests, [
new Response(200, body: json_encode([])),
new Response(200, body: json_encode(['key' => 'value'])),
]);
$sut = $this->getSut($client);

// Test empty and non-empty response.
for ($i = 0; $i < 2; $i++) {
$response = $sut->exposedMakeRequest('GET', '/foo');
$this->assertInstanceOf(ApiResponse::class, $response);
$this->assertInstanceOf(RequestInterface::class, $requests[0]['request']);
}
}

/**
Expand Down Expand Up @@ -292,18 +305,9 @@ public function testRequestLoggingException() : void {
* @covers ::makeRequest
* @covers ::__construct
* @covers ::getRequestOptions
* @covers \Drupal\helfi_api_base\ApiClient\ApiFixture::requestFromFile
*/
public function testMockFallbackException() : void {
// Create a mock for the callback
$callbackMock = $this->getMockBuilder(\stdClass::class)
->addMethods(['__invoke']) // Assuming it's a callable class
->getMock();

// Expect the callback to be called once
$callbackMock->expects($this->once())
->method('__invoke')
->willThrowException(new FileNotExistsException('Test'));

$this->expectException(FileNotExistsException::class);
$response = $this->prophesize(ResponseInterface::class);
$response->getStatusCode()->willReturn(403);
Expand All @@ -316,7 +320,9 @@ public function testMockFallbackException() : void {
]);
$sut = $this->getSut($client);
// Test with non-existent menu to make sure no mock file exist.
$sut->exposedMakeRequest('GET', '/foo', mockCallback: [$callbackMock, '__invoke']);
$sut->exposedMakeRequest('GET', '/foo', fixture: sprintf('%d/should-not-exists.txt',
__DIR__
));
}

/**
Expand All @@ -326,6 +332,7 @@ public function testMockFallbackException() : void {
* @covers ::__construct
* @covers ::getRequestOptions
* @covers \Drupal\helfi_api_base\ApiClient\ApiResponse::__construct
* @covers \Drupal\helfi_api_base\ApiClient\ApiFixture::requestFromFile
*/
public function testMockFallback() : void {
// Use logger to verify that mock file is actually used.
Expand All @@ -345,7 +352,7 @@ public function testMockFallback() : void {
$response = $sut->exposedMakeRequest(
'GET',
'/foo',
mockCallback: static fn () => new ApiResponse(['value' => 1])
fixture: sprintf('%s/../../../fixtures/environments.json', __DIR__),
);
$this->assertInstanceOf(ApiResponse::class, $response);
}
Expand Down
4 changes: 2 additions & 2 deletions tests/src/Unit/ApiClient/ApiFixtureTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
* @coversDefaultClass \Drupal\helfi_api_base\ApiClient\ApiFixture
* @group helfi_api_base
* */
class ApiFixtureTest extends UnitTestCase {
class ApiFixtureTest extends UnitTestCase {

/**
* Test fixture loading.
Expand All @@ -34,7 +34,7 @@ public function testFixtures() {
*/
public function testException() {
$this->expectException(FileNotExistsException::class);
$response = ApiFixture::requestFromFile(vsprintf('%s/should-not-exists', [
ApiFixture::requestFromFile(vsprintf('%s/should-not-exists', [
__DIR__,
]));
}
Expand Down
2 changes: 1 addition & 1 deletion tests/src/Unit/ApiClient/VaultAuthorizerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@

namespace Drupal\Tests\helfi_api_base\Unit;

use Drupal\helfi_api_base\ApiClient\VaultAuthorizer;
use Drupal\helfi_api_base\Vault\AuthorizationToken;
use Drupal\helfi_api_base\Vault\VaultManager;
use Drupal\helfi_api_base\ApiClient\VaultAuthorizer;
use Drupal\Tests\UnitTestCase;
use Prophecy\PhpUnit\ProphecyTrait;

Expand Down

0 comments on commit 65dd80f

Please sign in to comment.