From da390e8f12ce3b44ae4566717672839c04afcb82 Mon Sep 17 00:00:00 2001 From: Sawjan Gurung Date: Tue, 21 Nov 2023 18:29:19 +0545 Subject: [PATCH] [tests-only] Retry listing roles if the response body is invalid (#7735) * retry listing roles if the response body is invalid * fix php style * reset tryAgain --- .../features/bootstrap/SettingsContext.php | 39 +++++++++++++++---- 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/tests/acceptance/features/bootstrap/SettingsContext.php b/tests/acceptance/features/bootstrap/SettingsContext.php index 97672c4780..62805b2cb4 100644 --- a/tests/acceptance/features/bootstrap/SettingsContext.php +++ b/tests/acceptance/features/bootstrap/SettingsContext.php @@ -153,15 +153,38 @@ class SettingsContext implements Context { * @return string */ public function getRoleIdByRoleName(string $user, string $role): string { - $response = $this->getRoles($user); - $this->featureContext->theHTTPStatusCodeShouldBe( - 201, - "Expected response status code should be 201", - $response - ); + // Sometimes the response body is not complete and results invalid json. + // so we try again until we get a valid json. + $tryAgain = false; + $retried = 0; + do { + $response = $this->getRoles($user); + $this->featureContext->theHTTPStatusCodeShouldBe( + 201, + "Expected response status code should be 201", + $response + ); + + $rawBody = $response->getBody()->getContents(); + try { + $decodedBody = \json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR); + $tryAgain = false; + } catch (Exception $e) { + $tryAgain = $retried < HttpRequestHelper::numRetriesOnHttpTooEarly(); + + if (!$tryAgain) { + throw $e; + } + } + + if ($tryAgain) { + $retried += 1; + echo "Invalid json body, retrying ($retried)...\n"; + // wait 500ms and try again + \usleep(500 * 1000); + } + } while ($tryAgain); - $rawBody = $response->getBody()->getContents(); - $decodedBody = \json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR); Assert::assertArrayHasKey( 'bundles', $decodedBody,