From b13dfa622ce22355d83b4e6c002103cddf7fef80 Mon Sep 17 00:00:00 2001 From: Arman <407448+armanist@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:20:58 +0400 Subject: [PATCH 1/2] [#694] Refresh the cloud access token only for token errors A plain text error body no longer raises a TypeError in the refresh check of the Dropbox and Google Drive apps. Dropbox refreshes only for an invalid or expired token tag, instead of every 401 with a tag, which could repeat a request without end. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + src/Storage/Adapters/Dropbox/DropboxApp.php | 11 ++-- .../Adapters/GoogleDrive/GoogleDriveApp.php | 4 +- .../Adapters/Dropbox/DropboxAppTest.php | 52 +++++++++++++++++-- .../GoogleDrive/GoogleDriveAppTest.php | 23 ++++++++ 5 files changed, 81 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 467e24c74..1688319a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,7 @@ The format is based on Keep a Changelog. - `php qt install:debugbar` copies the toolbar files through the local filesystem. It used the application's default storage, so with `fs.default` set to `dropbox` or `gdrive` it looked for the local files in the cloud and failed. Its message for an installation that is already complete reads "The debug bar is already installed" (#691) - The `@method` annotations of the `Cache` facade declare the PSR-16 types the adapters have, so static analysis and IDEs report `cache()->get(42)`, which throws a `TypeError` at runtime. The `*Multiple()` methods document integer keys and `InvalidCacheKeyException` (#691) - `MemcachedAdapter::set()` handles the TTL as PSR-16 and the other adapters do. A TTL of zero, or a `DateInterval` in the past, removes the item: Memcached read the resulting `0` as "never expires" and kept it. A TTL of more than 30 days is sent as an absolute time: Memcached reads a longer number of seconds as a Unix timestamp, so the item expired at once although `set()` returned `true` (#692) +- The Dropbox and Google Drive storage adapters handle an API error whose body is plain text: it raised a `TypeError` in the check for an expired access token, and now ends in the adapters' `Exception` with that text (Dropbox) or, for a 401, in a token refresh (Google Drive). Dropbox refreshes the token only when the error says it is invalid or expired; it refreshed on every 401 and retried, so another 401, such as a missing permission, repeated the request without end (#694) ## [3.1.2] - 2026-11-19 diff --git a/src/Storage/Adapters/Dropbox/DropboxApp.php b/src/Storage/Adapters/Dropbox/DropboxApp.php index 771a2f56a..5c76507c1 100644 --- a/src/Storage/Adapters/Dropbox/DropboxApp.php +++ b/src/Storage/Adapters/Dropbox/DropboxApp.php @@ -230,18 +230,19 @@ public function path(string $name): array } /** - * Checks if the access token need refresh + * Checks if the access token needs a refresh: a 401, and when the body names an error, + * only the tags of an invalid or expired token; a plain text body is not a token error */ - private function accessTokenNeedsRefresh(int $code, ?object $message = null): bool + private function accessTokenNeedsRefresh(int $code, mixed $message = null): bool { - if ($code !== self::INVALID_TOKEN_ERROR_CODE) { + if ($code !== self::INVALID_TOKEN_ERROR_CODE || is_string($message)) { return false; } - if (isset($message->error)) { + if (is_object($message) && isset($message->error)) { $error = (array) $message->error; - if (!isset($error['.tag']) && !in_array($error['.tag'], self::ACCESS_TOKEN_STATUS)) { + if (!isset($error['.tag']) || !in_array($error['.tag'], self::ACCESS_TOKEN_STATUS, true)) { return false; } } diff --git a/src/Storage/Adapters/GoogleDrive/GoogleDriveApp.php b/src/Storage/Adapters/GoogleDrive/GoogleDriveApp.php index 20a274559..8549f2f23 100644 --- a/src/Storage/Adapters/GoogleDrive/GoogleDriveApp.php +++ b/src/Storage/Adapters/GoogleDrive/GoogleDriveApp.php @@ -180,9 +180,9 @@ public function getFileInfo(string $fileId, bool $media = false, array $params = } /** - * Checks if the access token need refresh + * Checks if the access token needs a refresh: every 401, whatever the body is */ - private function accessTokenNeedsRefresh(int $code, ?object $message = null): bool + private function accessTokenNeedsRefresh(int $code, mixed $message = null): bool { return $code === self::INVALID_TOKEN_ERROR_CODE; } diff --git a/tests/Unit/Storage/Adapters/Dropbox/DropboxAppTest.php b/tests/Unit/Storage/Adapters/Dropbox/DropboxAppTest.php index b12901e17..8b36ecee4 100644 --- a/tests/Unit/Storage/Adapters/Dropbox/DropboxAppTest.php +++ b/tests/Unit/Storage/Adapters/Dropbox/DropboxAppTest.php @@ -2,9 +2,11 @@ namespace Quantum\Tests\Unit\Storage\Adapters\Dropbox; -use Quantum\Storage\Adapters\Dropbox\DropboxApp; use Quantum\Tests\Unit\Storage\HttpClientTestCase; +use Quantum\Storage\Adapters\Dropbox\DropboxApp; +use PHPUnit\Framework\Attributes\DataProvider; use Quantum\Tests\Unit\AppTestCase; +use Exception; class DropboxAppTest extends AppTestCase { @@ -126,11 +128,12 @@ public function testDropboxSendRequest(): void $this->assertEquals((object) $this->profileDataResponse, $response); } - public function testDropboxRequestWithAccessTokenExpired(): void + #[DataProvider('tokenErrorProvider')] + public function testDropboxRequestWithAccessTokenExpired(string $tag): void { $this->currentErrors = ['code' => 401]; - $this->currentResponse = (object) $this->errorResponse; + $this->currentResponse = (object) ['error' => (object) ['.tag' => $tag], 'error_summary' => $tag . '/...']; $response = $this->dropboxApp->sendRequest('https://api.dropboxapi.com/2/users/get_account2'); @@ -139,6 +142,49 @@ public function testDropboxRequestWithAccessTokenExpired(): void $this->assertEquals((object) $this->profileDataResponse, $response); } + public static function tokenErrorProvider(): array + { + return [ + 'expired access token' => ['expired_access_token'], + 'invalid access token' => ['invalid_access_token'], + ]; + } + + public function testDropboxRequestWithAnUnauthorizedErrorWithoutBodyRefreshesTheToken(): void + { + $this->currentErrors = ['code' => 401]; + + $this->currentResponse = null; + + $response = $this->dropboxApp->sendRequest('https://api.dropboxapi.com/2/users/get_account2'); + + $this->assertEquals((object) $this->profileDataResponse, $response); + } + + public function testDropboxRequestWithAnotherUnauthorizedErrorDoesNotRefreshTheToken(): void + { + $this->currentErrors = ['code' => 401]; + + $this->currentResponse = (object) $this->errorResponse; + + $this->expectException(Exception::class); + $this->expectExceptionMessage('no_account'); + + $this->dropboxApp->sendRequest('https://api.dropboxapi.com/2/users/get_account2'); + } + + public function testDropboxRequestWithATextErrorThrowsTheText(): void + { + $this->currentErrors = ['code' => 401]; + + $this->currentResponse = 'Error in call to API function "users/get_account": Bad request'; + + $this->expectException(Exception::class); + $this->expectExceptionMessage('Error in call to API function'); + + $this->dropboxApp->sendRequest('https://api.dropboxapi.com/2/users/get_account2'); + } + public function testDropboxPathNormalizer(): void { $this->assertEquals(['path' => '/message.txt'], $this->dropboxApp->path('/message.txt')); diff --git a/tests/Unit/Storage/Adapters/GoogleDrive/GoogleDriveAppTest.php b/tests/Unit/Storage/Adapters/GoogleDrive/GoogleDriveAppTest.php index 58d7f8f43..2c9d038e6 100644 --- a/tests/Unit/Storage/Adapters/GoogleDrive/GoogleDriveAppTest.php +++ b/tests/Unit/Storage/Adapters/GoogleDrive/GoogleDriveAppTest.php @@ -5,6 +5,7 @@ use Quantum\Storage\Adapters\GoogleDrive\GoogleDriveApp; use Quantum\Tests\Unit\Storage\HttpClientTestCase; use Quantum\Tests\Unit\AppTestCase; +use Exception; class GoogleDriveAppTest extends AppTestCase { @@ -119,4 +120,26 @@ public function testGoogleDriveRequestWithAccessTokenExpired(): void $this->assertEquals((object) $this->fileMetadataResponse, $response); } + public function testGoogleDriveRequestWithATextBodyOnAnExpiredTokenRefreshesTheToken(): void + { + $this->currentErrors = ['code' => 401]; + + $this->currentResponse = 'Unauthorized'; + + $response = $this->googleDriveApp->sendRequest(GoogleDriveApp::FILE_METADATA_URL . '/' . $this->fileMetadataResponse['id']); + + $this->assertEquals((object) $this->fileMetadataResponse, $response); + } + + public function testGoogleDriveRequestWithATextErrorThrowsTheText(): void + { + $this->currentErrors = ['code' => 500]; + + $this->currentResponse = 'Internal Server Error'; + + $this->expectException(Exception::class); + $this->expectExceptionMessage('Internal Server Error'); + + $this->googleDriveApp->sendRequest(GoogleDriveApp::FILE_METADATA_URL . '/' . $this->fileMetadataResponse['id']); + } } From 821b13aa8e9c8e220886c02357aeff37234f69d2 Mon Sep 17 00:00:00 2001 From: Arman <407448+armanist@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:44:58 +0400 Subject: [PATCH 2/2] [#694] Refresh the cloud access token at most once per request The request after a token refresh called sendRequest() again without a limit, and so did a token request that failed, so a 401 that came back repeated the requests without end. A flag now allows one refresh per request; when the token request or the retried request fails, the Exception is thrown. The retry keeps the HTTP method of the request instead of sending POST. Dropbox refreshes only for a 401 without a body or with an invalid or expired token tag. A text error body goes into the Exception as it is. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +- src/Storage/Adapters/Dropbox/DropboxApp.php | 20 +-- src/Storage/Traits/CloudAppTrait.php | 55 +++++---- .../Adapters/Dropbox/DropboxAppTest.php | 114 +++++++++++++++--- .../GoogleDrive/GoogleDriveAppTest.php | 63 +++++++++- tests/Unit/Storage/HttpClientTestCase.php | 23 +++- 6 files changed, 226 insertions(+), 53 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1688319a9..a09281b76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,7 +22,9 @@ The format is based on Keep a Changelog. - `php qt install:debugbar` copies the toolbar files through the local filesystem. It used the application's default storage, so with `fs.default` set to `dropbox` or `gdrive` it looked for the local files in the cloud and failed. Its message for an installation that is already complete reads "The debug bar is already installed" (#691) - The `@method` annotations of the `Cache` facade declare the PSR-16 types the adapters have, so static analysis and IDEs report `cache()->get(42)`, which throws a `TypeError` at runtime. The `*Multiple()` methods document integer keys and `InvalidCacheKeyException` (#691) - `MemcachedAdapter::set()` handles the TTL as PSR-16 and the other adapters do. A TTL of zero, or a `DateInterval` in the past, removes the item: Memcached read the resulting `0` as "never expires" and kept it. A TTL of more than 30 days is sent as an absolute time: Memcached reads a longer number of seconds as a Unix timestamp, so the item expired at once although `set()` returned `true` (#692) -- The Dropbox and Google Drive storage adapters handle an API error whose body is plain text: it raised a `TypeError` in the check for an expired access token, and now ends in the adapters' `Exception` with that text (Dropbox) or, for a 401, in a token refresh (Google Drive). Dropbox refreshes the token only when the error says it is invalid or expired; it refreshed on every 401 and retried, so another 401, such as a missing permission, repeated the request without end (#694) +- The Dropbox and Google Drive storage adapters refresh an expired access token at most once per request. The request after the refresh called the same method again without a limit, so a 401 that came back after the refresh, or a 401 from the token request itself, repeated the requests without end. When the retried request or the token request fails, the adapter throws its `Exception`. The retried request keeps its HTTP method; it was always sent as `POST` (#694) +- Dropbox refreshes the access token only for a 401 without a body or with an error tagged `invalid_access_token` or `expired_access_token`. It refreshed for every 401 with an error tag, such as `no_account` or a missing permission, and an error body that was plain text raised a `TypeError`. Any other 401 now throws the adapter's `Exception` (#694) +- The `Exception` of a failed Dropbox or Google Drive request carries a plain text error body as it is, and the HTTP client's error when the response has no body; a text body was JSON encoded, and an error body that was plain text raised a `TypeError` in the check for an expired access token (#694) ## [3.1.2] - 2026-11-19 diff --git a/src/Storage/Adapters/Dropbox/DropboxApp.php b/src/Storage/Adapters/Dropbox/DropboxApp.php index 5c76507c1..260b959e6 100644 --- a/src/Storage/Adapters/Dropbox/DropboxApp.php +++ b/src/Storage/Adapters/Dropbox/DropboxApp.php @@ -230,23 +230,25 @@ public function path(string $name): array } /** - * Checks if the access token needs a refresh: a 401, and when the body names an error, - * only the tags of an invalid or expired token; a plain text body is not a token error + * Checks if the access token needs a refresh: a 401 with no body, or with an object whose + * error has the tag of an invalid or expired token; any other body is not a token error */ private function accessTokenNeedsRefresh(int $code, mixed $message = null): bool { - if ($code !== self::INVALID_TOKEN_ERROR_CODE || is_string($message)) { + if ($code !== self::INVALID_TOKEN_ERROR_CODE) { return false; } - if (is_object($message) && isset($message->error)) { - $error = (array) $message->error; + if ($message === null || $message === '') { + return true; + } - if (!isset($error['.tag']) || !in_array($error['.tag'], self::ACCESS_TOKEN_STATUS, true)) { - return false; - } + if (!is_object($message) || !isset($message->error)) { + return false; } - return true; + $error = (array) $message->error; + + return isset($error['.tag']) && in_array($error['.tag'], self::ACCESS_TOKEN_STATUS, true); } } diff --git a/src/Storage/Traits/CloudAppTrait.php b/src/Storage/Traits/CloudAppTrait.php index e270938f8..29f67e027 100644 --- a/src/Storage/Traits/CloudAppTrait.php +++ b/src/Storage/Traits/CloudAppTrait.php @@ -20,6 +20,12 @@ */ trait CloudAppTrait { + /** + * Set while the access token is being refreshed: the token request and the retried + * request may not start another refresh, so a request refreshes the token at most once + */ + private bool $refreshingAccessToken = false; + /** * @inheritDoc * @param array|string|null $data @@ -38,35 +44,42 @@ public function sendRequest(string $uri, $data = null, array $headers = [], stri $errors = $this->httpClient->getErrors(); $responseBody = $this->httpClient->getResponseBody(); - if ($errors) { - $code = $errors['code']; - - if ($this->accessTokenNeedsRefresh($code, $responseBody)) { - $prevUrl = $this->httpClient->url(); + if (!$errors) { + return $responseBody; + } - if (empty($prevUrl)) { - throw new Exception('Cannot retry request: original URL is not available.', E_ERROR); - } + if (!$this->refreshingAccessToken && $this->accessTokenNeedsRefresh($errors['code'], $responseBody)) { + $this->refreshingAccessToken = true; - $prevData = $this->httpClient->getData(); - $prevHeaders = $this->httpClient->getRequestHeaders(); + try { + $accessToken = $this->fetchAccessTokenByRefreshToken($this->tokenService->getRefreshToken()); - $refreshToken = $this->tokenService->getRefreshToken(); + $headers['Authorization'] = 'Bearer ' . $accessToken; - $accessToken = $this->fetchAccessTokenByRefreshToken($refreshToken); + return $this->sendRequest($uri, $data, $headers, $method); + } finally { + $this->refreshingAccessToken = false; + } + } - $prevHeaders['Authorization'] = 'Bearer ' . $accessToken; + throw new Exception($this->errorMessage($responseBody, $errors), E_ERROR); + } - $responseBody = $this->sendRequest($prevUrl, $prevData, $prevHeaders); + /** + * The message of a failed request: a text body as it is, the client's error + * when there is no body, and any other body as JSON + * @param array $errors + */ + private function errorMessage(mixed $responseBody, array $errors): string + { + if (is_string($responseBody) && $responseBody !== '') { + return $responseBody; + } - } else { - throw new Exception( - json_encode($responseBody ?? $errors) ?: '', - E_ERROR - ); - } + if ($responseBody === null || $responseBody === '') { + return json_encode($errors) ?: ''; } - return $responseBody; + return json_encode($responseBody) ?: ''; } } diff --git a/tests/Unit/Storage/Adapters/Dropbox/DropboxAppTest.php b/tests/Unit/Storage/Adapters/Dropbox/DropboxAppTest.php index 8b36ecee4..b9a00ee7d 100644 --- a/tests/Unit/Storage/Adapters/Dropbox/DropboxAppTest.php +++ b/tests/Unit/Storage/Adapters/Dropbox/DropboxAppTest.php @@ -150,39 +150,121 @@ public static function tokenErrorProvider(): array ]; } - public function testDropboxRequestWithAnUnauthorizedErrorWithoutBodyRefreshesTheToken(): void + #[DataProvider('noBodyProvider')] + public function testDropboxRefreshesTheTokenWhenTheUnauthorizedErrorHasNoBody(mixed $body): void { - $this->currentErrors = ['code' => 401]; - - $this->currentResponse = null; + $this->responseQueue = [ + ['body' => $body, 'errors' => ['code' => 401]], + ['body' => (object) ['access_token' => 'new_tok'], 'errors' => []], + ['body' => (object) $this->profileDataResponse, 'errors' => []], + ]; $response = $this->dropboxApp->sendRequest('https://api.dropboxapi.com/2/users/get_account2'); $this->assertEquals((object) $this->profileDataResponse, $response); + $this->assertCount(3, $this->sentMethods); } - public function testDropboxRequestWithAnotherUnauthorizedErrorDoesNotRefreshTheToken(): void + public static function noBodyProvider(): array { - $this->currentErrors = ['code' => 401]; + return [ + 'empty body' => [''], + 'no body' => [null], + ]; + } - $this->currentResponse = (object) $this->errorResponse; + #[DataProvider('otherUnauthorizedBodyProvider')] + public function testDropboxDoesNotRefreshTheTokenForAnotherUnauthorizedError(mixed $body): void + { + $this->responseQueue = [ + ['body' => $body, 'errors' => ['code' => 401]], + ]; - $this->expectException(Exception::class); - $this->expectExceptionMessage('no_account'); + try { + $this->dropboxApp->sendRequest('https://api.dropboxapi.com/2/users/get_account2'); + $this->fail('The error was not thrown'); + } catch (Exception) { + $this->assertCount(1, $this->sentMethods); + } + } - $this->dropboxApp->sendRequest('https://api.dropboxapi.com/2/users/get_account2'); + public static function otherUnauthorizedBodyProvider(): array + { + return [ + 'another error tag' => [(object) ['error' => (object) ['.tag' => 'no_account']]], + 'an error without a tag' => [(object) ['error' => (object) ['reason' => 'unknown']]], + 'an object without an error' => [(object) ['message' => 'Unauthorized']], + 'an error that is a string' => [(object) ['error' => 'invalid_grant']], + 'a text body' => ['Error in call to API function "users/get_account": Bad request'], + 'an array body' => [['error' => ['.tag' => 'expired_access_token']]], + 'a number body' => [401], + ]; } - public function testDropboxRequestWithATextErrorThrowsTheText(): void + public function testDropboxThrowsTheTextOfATextErrorAsItIs(): void { - $this->currentErrors = ['code' => 401]; + $text = 'Error in call to API function "users/get_account": Bad request'; + + $this->responseQueue = [ + ['body' => $text, 'errors' => ['code' => 401]], + ]; - $this->currentResponse = 'Error in call to API function "users/get_account": Bad request'; + try { + $this->dropboxApp->sendRequest('https://api.dropboxapi.com/2/users/get_account2'); + $this->fail('The error was not thrown'); + } catch (Exception $e) { + $this->assertSame($text, $e->getMessage()); + } + } + + public function testDropboxThrowsTheClientErrorWhenAnErrorHasNoBody(): void + { + $errors = ['code' => 500, 'message' => 'HTTP/1.1 500 Internal Server Error']; + + $this->responseQueue = [ + ['body' => '', 'errors' => $errors], + ]; + + try { + $this->dropboxApp->sendRequest('https://api.dropboxapi.com/2/users/get_account2'); + $this->fail('The error was not thrown'); + } catch (Exception $e) { + $this->assertSame(json_encode($errors), $e->getMessage()); + } + } + + public function testDropboxRefreshesTheTokenOnlyOnceWhenTheRetryFailsAgain(): void + { + $expired = (object) ['error' => (object) ['.tag' => 'expired_access_token']]; + + $this->responseQueue = [ + ['body' => $expired, 'errors' => ['code' => 401]], + ['body' => (object) ['access_token' => 'new_tok'], 'errors' => []], + ['body' => $expired, 'errors' => ['code' => 401]], + ['body' => (object) ['access_token' => 'newer_tok'], 'errors' => []], + ['body' => (object) $this->profileDataResponse, 'errors' => []], + ]; + + try { + $this->dropboxApp->sendRequest('https://api.dropboxapi.com/2/users/get_account2'); + $this->fail('The error was not thrown'); + } catch (Exception) { + $this->assertCount(3, $this->sentMethods); + } + } - $this->expectException(Exception::class); - $this->expectExceptionMessage('Error in call to API function'); + public function testDropboxRetryKeepsTheMethodOfTheRequest(): void + { + $this->responseQueue = [ + ['body' => (object) ['error' => (object) ['.tag' => 'expired_access_token']], 'errors' => ['code' => 401]], + ['body' => (object) ['access_token' => 'new_tok'], 'errors' => []], + ['body' => (object) $this->profileDataResponse, 'errors' => []], + ]; - $this->dropboxApp->sendRequest('https://api.dropboxapi.com/2/users/get_account2'); + $response = $this->dropboxApp->sendRequest('https://api.dropboxapi.com/2/users/get_account2', null, [], 'GET'); + + $this->assertEquals((object) $this->profileDataResponse, $response); + $this->assertSame(['GET', 'POST', 'GET'], $this->sentMethods); } public function testDropboxPathNormalizer(): void diff --git a/tests/Unit/Storage/Adapters/GoogleDrive/GoogleDriveAppTest.php b/tests/Unit/Storage/Adapters/GoogleDrive/GoogleDriveAppTest.php index 2c9d038e6..dcbc42617 100644 --- a/tests/Unit/Storage/Adapters/GoogleDrive/GoogleDriveAppTest.php +++ b/tests/Unit/Storage/Adapters/GoogleDrive/GoogleDriveAppTest.php @@ -133,13 +133,66 @@ public function testGoogleDriveRequestWithATextBodyOnAnExpiredTokenRefreshesTheT public function testGoogleDriveRequestWithATextErrorThrowsTheText(): void { - $this->currentErrors = ['code' => 500]; + $this->responseQueue = [ + ['body' => 'Internal Server Error', 'errors' => ['code' => 500]], + ]; + + try { + $this->googleDriveApp->sendRequest(GoogleDriveApp::FILE_METADATA_URL . '/' . $this->fileMetadataResponse['id']); + $this->fail('The error was not thrown'); + } catch (Exception $e) { + $this->assertSame('Internal Server Error', $e->getMessage()); + } + } - $this->currentResponse = 'Internal Server Error'; + public function testGoogleDriveRefreshesTheTokenOnlyOnceWhenTheRetryFailsAgain(): void + { + $this->responseQueue = [ + ['body' => 'Unauthorized', 'errors' => ['code' => 401]], + ['body' => (object) ['access_token' => 'new_tok'], 'errors' => []], + ['body' => 'Unauthorized', 'errors' => ['code' => 401]], + ['body' => (object) ['access_token' => 'newer_tok'], 'errors' => []], + ['body' => (object) $this->fileMetadataResponse, 'errors' => []], + ]; + + try { + $this->googleDriveApp->sendRequest(GoogleDriveApp::FILE_METADATA_URL . '/' . $this->fileMetadataResponse['id']); + $this->fail('The error was not thrown'); + } catch (Exception $e) { + $this->assertSame('Unauthorized', $e->getMessage()); + $this->assertCount(3, $this->sentMethods); + } + } - $this->expectException(Exception::class); - $this->expectExceptionMessage('Internal Server Error'); + public function testGoogleDriveDoesNotRefreshAgainWhenTheTokenRequestIsUnauthorized(): void + { + $this->responseQueue = [ + ['body' => (object) $this->errorResponse, 'errors' => ['code' => 401]], + ['body' => (object) ['error' => 'invalid_client'], 'errors' => ['code' => 401]], + ['body' => (object) ['access_token' => 'new_tok'], 'errors' => []], + ['body' => (object) $this->fileMetadataResponse, 'errors' => []], + ]; + + try { + $this->googleDriveApp->sendRequest(GoogleDriveApp::FILE_METADATA_URL . '/' . $this->fileMetadataResponse['id']); + $this->fail('The error was not thrown'); + } catch (Exception $e) { + $this->assertStringContainsString('invalid_client', $e->getMessage()); + $this->assertCount(2, $this->sentMethods); + } + } - $this->googleDriveApp->sendRequest(GoogleDriveApp::FILE_METADATA_URL . '/' . $this->fileMetadataResponse['id']); + public function testGoogleDriveRetryKeepsTheMethodOfTheRequest(): void + { + $this->responseQueue = [ + ['body' => (object) $this->errorResponse, 'errors' => ['code' => 401]], + ['body' => (object) ['access_token' => 'new_tok'], 'errors' => []], + ['body' => (object) $this->fileMetadataResponse, 'errors' => []], + ]; + + $response = $this->googleDriveApp->sendRequest(GoogleDriveApp::FILE_METADATA_URL . '/' . $this->fileMetadataResponse['id'], null, [], 'GET'); + + $this->assertEquals((object) $this->fileMetadataResponse, $response); + $this->assertSame(['GET', 'POST', 'GET'], $this->sentMethods); } } diff --git a/tests/Unit/Storage/HttpClientTestCase.php b/tests/Unit/Storage/HttpClientTestCase.php index 51202ecdc..0d62bdc64 100644 --- a/tests/Unit/Storage/HttpClientTestCase.php +++ b/tests/Unit/Storage/HttpClientTestCase.php @@ -19,6 +19,17 @@ trait HttpClientTestCase protected $options; + /** + * Responses for the next requests, in order: each ['body' => ..., 'errors' => [...]]. + * When it is empty, a request answers with $currentResponse and $currentErrors. + */ + protected array $responseQueue = []; + + /** + * The HTTP method of every request sent, in order + */ + protected array $sentMethods = []; + protected function mockHttpClient() { $httpClientMock = Mockery::mock(HttpClient::class); @@ -28,7 +39,10 @@ protected function mockHttpClient() return $httpClientMock; }); - $httpClientMock->shouldReceive('setMethod')->andReturnSelf(); + $httpClientMock->shouldReceive('setMethod')->andReturnUsing(function ($method) use ($httpClientMock) { + $this->sentMethods[] = $method; + return $httpClientMock; + }); $httpClientMock->shouldReceive('setHeaders')->andReturnSelf(); @@ -47,6 +61,13 @@ protected function mockHttpClient() }); $httpClientMock->shouldReceive('start')->andReturnUsing(function () use ($httpClientMock) { + if ($this->responseQueue !== []) { + $next = array_shift($this->responseQueue); + $this->response[$this->url]['body'] = $next['body']; + $this->response[$this->url]['errors'] = $next['errors']; + return $httpClientMock; + } + $this->response[$this->url]['body'] = $this->currentResponse; $this->response[$this->url]['errors'] = $this->currentErrors; $this->currentResponse = [];