From f8a1da7bbe50a938cc853cbf14ac9e4c100a901d Mon Sep 17 00:00:00 2001 From: algolia-bot Date: Tue, 19 Nov 2024 10:53:23 +0000 Subject: [PATCH] fix(cts): add tests for HTML error (#4097) (generated) [skip ci] Co-authored-by: Pierre Millot --- .../client-common/src/transporter/helpers.ts | 40 +++++++------- .../algolia/transport/http/http_requester.rb | 14 ++++- .../src/generated/client/Ingestion.test.cs | 33 ++++++++++++ .../output/go/tests/client/ingestion_test.go | 26 ++++++++++ .../com/algolia/client/Ingestion.test.java | 27 ++++++++++ .../javascript/src/client/ingestion.test.ts | 26 ++++++++++ .../com/algolia/client/IngestionTest.kt | 10 ++++ tests/output/php/src/client/IngestionTest.php | 15 ++++++ .../python/tests/client/ingestion_test.py | 52 +++++++++++++++++++ .../output/ruby/test/client/ingestion_test.rb | 31 +++++++++++ tests/output/ruby/test/client/search_test.rb | 4 +- .../algoliasearch/client/IngestionTest.scala | 31 +++++++++++ .../swift/Tests/client/IngestionTests.swift | 25 +++++++++ 13 files changed, 310 insertions(+), 24 deletions(-) diff --git a/clients/algoliasearch-client-javascript/packages/client-common/src/transporter/helpers.ts b/clients/algoliasearch-client-javascript/packages/client-common/src/transporter/helpers.ts index 89fb7b0670..a4f85547b8 100644 --- a/clients/algoliasearch-client-javascript/packages/client-common/src/transporter/helpers.ts +++ b/clients/algoliasearch-client-javascript/packages/client-common/src/transporter/helpers.ts @@ -84,26 +84,26 @@ export function deserializeSuccess(response: Response): TObject { const httpMessages: Record = { 400: 'Bad Request', - 401: 'Unauthorized', - 402: 'Payment Required', - 403: 'Forbidden', - 404: 'Not Found', - 405: 'Method Not Allowed', - 406: 'Not Acceptable', - 407: 'Proxy Authentication Required', - 408: 'Request Timeout', - 409: 'Conflict', - 410: 'Gone', - 411: 'Length Required', - 412: 'Precondition Required', - 413: 'Request Entry Too Large', - 414: 'Request-URI Too Long', - 415: 'Unsupported Media Type', - 416: 'Requested Range Not Satisfiable', - 417: 'Expectation Failed', - 418: 'I\'m a teapot', - 429: 'Too Many Requests', -} + 401: 'Unauthorized', + 402: 'Payment Required', + 403: 'Forbidden', + 404: 'Not Found', + 405: 'Method Not Allowed', + 406: 'Not Acceptable', + 407: 'Proxy Authentication Required', + 408: 'Request Timeout', + 409: 'Conflict', + 410: 'Gone', + 411: 'Length Required', + 412: 'Precondition Required', + 413: 'Request Entry Too Large', + 414: 'Request-URI Too Long', + 415: 'Unsupported Media Type', + 416: 'Requested Range Not Satisfiable', + 417: 'Expectation Failed', + 418: "I'm a teapot", + 429: 'Too Many Requests', +}; export function deserializeFailure({ content, status }: Response, stackFrame: StackFrame[]): Error { try { diff --git a/clients/algoliasearch-client-ruby/lib/algolia/transport/http/http_requester.rb b/clients/algoliasearch-client-ruby/lib/algolia/transport/http/http_requester.rb index 1a7c363556..80d5a565c1 100644 --- a/clients/algoliasearch-client-ruby/lib/algolia/transport/http/http_requester.rb +++ b/clients/algoliasearch-client-ruby/lib/algolia/transport/http/http_requester.rb @@ -39,14 +39,24 @@ def send_request(host, method, path, body, query_params, headers, timeout, conne @logger.info("Request succeeded. Response status: #{response.status}, body: #{response.body}") end - return Http::Response.new(status: response.status, reason_phrase: response.reason_phrase, body: response.body, headers: response.headers) + return Http::Response.new( + status: response.status, + reason_phrase: response.reason_phrase, + body: response.body, + headers: response.headers + ) end if ENV["ALGOLIA_DEBUG"] @logger.info("Request failed. Response status: #{response.status}, error: #{response.body}") end - Http::Response.new(status: response.status, reason_phrase: response.reason_phrase, error: response.body, headers: response.headers) + Http::Response.new( + status: response.status, + reason_phrase: response.reason_phrase, + error: response.body, + headers: response.headers + ) rescue Faraday::TimeoutError => e @logger.info("Request timed out. Error: #{e.message}") if ENV["ALGOLIA_DEBUG"] Http::Response.new(error: e.message, has_timed_out: true) diff --git a/tests/output/csharp/src/generated/client/Ingestion.test.cs b/tests/output/csharp/src/generated/client/Ingestion.test.cs index 57b92a775f..7ac74ae5f0 100644 --- a/tests/output/csharp/src/generated/client/Ingestion.test.cs +++ b/tests/output/csharp/src/generated/client/Ingestion.test.cs @@ -26,6 +26,39 @@ public IngestionClientTests() [Fact] public void Dispose() { } + [Fact(DisplayName = "can handle HTML error")] + public async Task ApiTest0() + { + IngestionConfig _config = new IngestionConfig("test-app-id", "test-api-key", "us") + { + CustomHosts = new List + { + new() + { + Scheme = HttpScheme.Http, + Url = + Environment.GetEnvironmentVariable("CI") == "true" + ? "localhost" + : "host.docker.internal", + Port = 6676, + Up = true, + LastUse = DateTime.UtcNow, + Accept = CallType.Read | CallType.Write, + }, + }, + }; + var client = new IngestionClient(_config); + + _ex = await Assert.ThrowsAnyAsync(async () => + { + var res = await client.CustomGetAsync("1/html-error"); + }); + Assert.Equal( + "429 too many requests".ToLowerInvariant(), + _ex.Message.ToLowerInvariant() + ); + } + [Fact(DisplayName = "calls api with correct user agent")] public async Task CommonApiTest0() { diff --git a/tests/output/go/tests/client/ingestion_test.go b/tests/output/go/tests/client/ingestion_test.go index 746b002de2..60a9b64524 100644 --- a/tests/output/go/tests/client/ingestion_test.go +++ b/tests/output/go/tests/client/ingestion_test.go @@ -31,6 +31,32 @@ func createIngestionClient(t *testing.T) (*ingestion.APIClient, *tests.EchoReque return client, echo } +// can handle HTML error +func TestIngestionapi0(t *testing.T) { + var err error + var res any + _ = res + echo := &tests.EchoRequester{} + var client *ingestion.APIClient + var cfg ingestion.IngestionConfiguration + _ = client + _ = echo + cfg = ingestion.IngestionConfiguration{ + Configuration: transport.Configuration{ + AppID: "test-app-id", + ApiKey: "test-api-key", + Hosts: []transport.StatefulHost{transport.NewStatefulHost("http", tests.GetLocalhost()+":6676", call.IsReadWrite)}, + }, + Region: ingestion.Region("us"), + } + client, err = ingestion.NewClientWithConfig(cfg) + require.NoError(t, err) + res, err = client.CustomGet(client.NewApiCustomGetRequest( + "1/html-error", + )) + require.EqualError(t, err, "API error [429] Too Many Requests") +} + // calls api with correct user agent func TestIngestioncommonApi0(t *testing.T) { var err error diff --git a/tests/output/java/src/test/java/com/algolia/client/Ingestion.test.java b/tests/output/java/src/test/java/com/algolia/client/Ingestion.test.java index bcd59ed536..4b284706da 100644 --- a/tests/output/java/src/test/java/com/algolia/client/Ingestion.test.java +++ b/tests/output/java/src/test/java/com/algolia/client/Ingestion.test.java @@ -48,6 +48,33 @@ private ClientOptions withCustomHosts(List hosts, boolean gzipEncoding) { return ClientOptions.builder().setHosts(hosts).setCompressionType(gzipEncoding ? CompressionType.GZIP : CompressionType.NONE).build(); } + @Test + @DisplayName("can handle HTML error") + void apiTest0() { + IngestionClient client = new IngestionClient( + "test-app-id", + "test-api-key", + "us", + withCustomHosts( + Arrays.asList( + new Host( + "true".equals(System.getenv("CI")) ? "localhost" : "host.docker.internal", + EnumSet.of(CallType.READ, CallType.WRITE), + "http", + 6676 + ) + ), + false + ) + ); + { + Exception exception = assertThrows(Exception.class, () -> { + Object res = client.customGet("1/html-error"); + }); + assertEquals("Status Code: 429 - Too Many Requests", exception.getMessage()); + } + } + @Test @DisplayName("calls api with correct user agent") void commonApiTest0() { diff --git a/tests/output/javascript/src/client/ingestion.test.ts b/tests/output/javascript/src/client/ingestion.test.ts index cf7eb3183d..5d2db3bdde 100644 --- a/tests/output/javascript/src/client/ingestion.test.ts +++ b/tests/output/javascript/src/client/ingestion.test.ts @@ -13,6 +13,32 @@ function createClient() { return algoliasearch(appId, apiKey).initIngestion({ options: { requester: nodeEchoRequester() }, region: 'us' }); } +describe('api', () => { + test('can handle HTML error', async () => { + const client = algoliasearch('test-app-id', 'test-api-key').initIngestion({ + options: { + hosts: [ + { + url: 'localhost', + port: 6676, + accept: 'readWrite', + protocol: 'http', + }, + ], + }, + // @ts-ignore + region: 'us', + }); + try { + // @ts-ignore + const result = await client.customGet({ path: '1/html-error' }); + throw new Error('test is expected to throw error'); + } catch (e) { + expect((e as Error).message).toMatch('Too Many Requests'); + } + }, 15000); +}); + describe('commonApi', () => { test('calls api with correct user agent', async () => { const client = createClient(); diff --git a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/IngestionTest.kt b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/IngestionTest.kt index 33272903b0..802019549d 100644 --- a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/IngestionTest.kt +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/IngestionTest.kt @@ -15,6 +15,16 @@ import kotlin.test.* class IngestionTest { + @Test + fun `can handle HTML error`() = runTest { + val client = IngestionClient(appId = "test-app-id", apiKey = "test-api-key", "us", options = ClientOptions(hosts = listOf(Host(url = if (System.getenv("CI") == "true") "localhost" else "host.docker.internal", protocol = "http", port = 6676)))) + assertFails { + client.customGet( + path = "1/html-error", + ) + }.let { error -> assertError(error, "Client request(GET http://%localhost%:6676/1/html-error) invalid: 429 Too Many Requests. Text: \"429 Too Many Requests\"".replace("%localhost%", if (System.getenv("CI") == "true") "localhost" else "host.docker.internal")) } + } + @Test fun `calls api with correct user agent`() = runTest { val client = IngestionClient(appId = "appId", apiKey = "apiKey", region = "us") diff --git a/tests/output/php/src/client/IngestionTest.php b/tests/output/php/src/client/IngestionTest.php index c05bf0de4b..7e3d74470b 100644 --- a/tests/output/php/src/client/IngestionTest.php +++ b/tests/output/php/src/client/IngestionTest.php @@ -38,6 +38,21 @@ public function sendRequest(RequestInterface $request, $timeout, $connectTimeout return new Response(200, [], '{}'); } + #[TestDox('can handle HTML error')] + public function test0api(): void + { + $client = IngestionClient::createWithConfig(IngestionConfig::create('test-app-id', 'test-api-key', 'us')->setFullHosts(['http://'.('true' == getenv('CI') ? 'localhost' : 'host.docker.internal').':6676'])); + + try { + $res = $client->customGet( + '1/html-error', + ); + $this->fail('Expected exception to be thrown'); + } catch (\Exception $e) { + $this->assertEquals($e->getMessage(), '429: Too Many Requests'); + } + } + #[TestDox('calls api with correct user agent')] public function test0commonApi(): void { diff --git a/tests/output/python/tests/client/ingestion_test.py b/tests/output/python/tests/client/ingestion_test.py index c9c81932cd..a9d8cfcf45 100644 --- a/tests/output/python/tests/client/ingestion_test.py +++ b/tests/output/python/tests/client/ingestion_test.py @@ -18,6 +18,32 @@ def create_client(self) -> IngestionClient: config=_config, transporter=EchoTransporter(_config) ) + async def test_api_0(self): + """ + can handle HTML error + """ + + _config = IngestionConfig("test-app-id", "test-api-key", "us") + _config.hosts = HostsCollection( + [ + Host( + url="localhost" + if environ.get("CI") == "true" + else "host.docker.internal", + scheme="http", + port=6676, + ) + ] + ) + _client = IngestionClient.create_with_config(config=_config) + try: + await _client.custom_get( + path="1/html-error", + ) + assert False + except (ValueError, Exception) as e: + assert str(e) == "Too Many Requests" + async def test_common_api_0(self): """ calls api with correct user agent @@ -149,6 +175,32 @@ def create_client(self) -> IngestionClientSync: config=_config, transporter=EchoTransporterSync(_config) ) + def test_api_0(self): + """ + can handle HTML error + """ + + _config = IngestionConfig("test-app-id", "test-api-key", "us") + _config.hosts = HostsCollection( + [ + Host( + url="localhost" + if environ.get("CI") == "true" + else "host.docker.internal", + scheme="http", + port=6676, + ) + ] + ) + _client = IngestionClientSync.create_with_config(config=_config) + try: + _client.custom_get( + path="1/html-error", + ) + assert False + except (ValueError, Exception) as e: + assert str(e) == "Too Many Requests" + def test_common_api_0(self): """ calls api with correct user agent diff --git a/tests/output/ruby/test/client/ingestion_test.rb b/tests/output/ruby/test/client/ingestion_test.rb index bbd318d447..13239b9673 100644 --- a/tests/output/ruby/test/client/ingestion_test.rb +++ b/tests/output/ruby/test/client/ingestion_test.rb @@ -3,6 +3,37 @@ require "test/unit" class TestClientIngestionClient < Test::Unit::TestCase + # can handle HTML error + def test_api0 + client = Algolia::IngestionClient.create_with_config( + Algolia::Configuration.new( + "test-app-id", + "test-api-key", + [ + Algolia::Transport::StatefulHost.new( + ENV.fetch("CI", nil) == "true" ? "localhost" : "host.docker.internal", + protocol: "http://", + port: 6676, + accept: CallType::READ | CallType::WRITE + ) + ], + "ingestionClient" + ) + ) + begin + client.custom_get("1/html-error") + assert(false, "An error should have been raised") + rescue => e + assert_equal( + "429: Too Many Requests".sub( + "%localhost%", + ENV.fetch("CI", nil) == "true" ? "localhost" : "host.docker.internal" + ), + e.message + ) + end + end + # calls api with correct user agent def test_common_api0 client = Algolia::IngestionClient.create( diff --git a/tests/output/ruby/test/client/search_test.rb b/tests/output/ruby/test/client/search_test.rb index 84b19eb0c9..e197400ba3 100644 --- a/tests/output/ruby/test/client/search_test.rb +++ b/tests/output/ruby/test/client/search_test.rb @@ -320,7 +320,7 @@ def test_index_exists2 assert(false, "An error should have been raised") rescue => e assert_equal( - "Invalid API key".sub("%localhost%", ENV.fetch("CI", nil) == "true" ? "localhost" : "host.docker.internal"), + "403: Invalid API key".sub("%localhost%", ENV.fetch("CI", nil) == "true" ? "localhost" : "host.docker.internal"), e.message ) end @@ -597,7 +597,7 @@ def test_save_objects1 assert(false, "An error should have been raised") rescue => e assert_equal( - "Invalid Application-ID or API key".sub( + "403: Invalid Application-ID or API key".sub( "%localhost%", ENV.fetch("CI", nil) == "true" ? "localhost" : "host.docker.internal" ), diff --git a/tests/output/scala/src/test/scala/algoliasearch/client/IngestionTest.scala b/tests/output/scala/src/test/scala/algoliasearch/client/IngestionTest.scala index 541e10d0d1..b445cb9ae0 100644 --- a/tests/output/scala/src/test/scala/algoliasearch/client/IngestionTest.scala +++ b/tests/output/scala/src/test/scala/algoliasearch/client/IngestionTest.scala @@ -39,6 +39,37 @@ class IngestionTest extends AnyFunSuite { ) } + test("can handle HTML error") { + + val client = IngestionClient( + appId = "test-app-id", + apiKey = "test-api-key", + region = "us", + clientOptions = ClientOptions + .builder() + .withHosts( + List( + Host( + if (System.getenv("CI") == "true") "localhost" else "host.docker.internal", + Set(CallType.Read, CallType.Write), + "http", + Option(6676) + ) + ) + ) + .build() + ) + + assertError("429 Too Many Requests") { + var res = Await.result( + client.customGet[JObject]( + path = "1/html-error" + ), + Duration.Inf + ) + } + } + test("calls api with correct user agent") { val (client, echo) = testClient() diff --git a/tests/output/swift/Tests/client/IngestionTests.swift b/tests/output/swift/Tests/client/IngestionTests.swift index 02ba1fc3cd..4ad0cf18e4 100644 --- a/tests/output/swift/Tests/client/IngestionTests.swift +++ b/tests/output/swift/Tests/client/IngestionTests.swift @@ -11,6 +11,31 @@ final class IngestionClientClientTests: XCTestCase { let APPLICATION_ID = "my_application_id" let API_KEY = "my_api_key" + /// can handle HTML error + func testApiTest0() async throws { + let configuration = try IngestionClientConfiguration( + appID: "test-app-id", + apiKey: "test-api-key", + region: Region(rawValue: "us"), + hosts: [RetryableHost(url: URL( + string: "http://" + + (ProcessInfo.processInfo.environment["CI"] == "true" ? "localhost" : "host.docker.internal") + + ":6676" + )!)] + ) + let transporter = Transporter(configuration: configuration) + let client = IngestionClient(configuration: configuration, transporter: transporter) + do { + let response = try await client.customGetWithHTTPInfo(path: "1/html-error") + let responseBodyData = try XCTUnwrap(response.bodyData) + let responseBodyJSON = try XCTUnwrap(responseBodyData.jsonString) + + XCTFail("Expected an error to be thrown") + } catch { + XCTAssertEqual(error.localizedDescription, "HTTP error: Status code: 429 Message: No message") + } + } + /// calls api with correct user agent func testCommonApiTest0() async throws { let configuration = try IngestionClientConfiguration(appID: APPLICATION_ID, apiKey: API_KEY, region: Region.us)