Skip to content

Commit

Permalink
fix(cts): add tests for HTML error (#4097) (generated) [skip ci]
Browse files Browse the repository at this point in the history
Co-authored-by: Pierre Millot <pierre.millot@algolia.com>
  • Loading branch information
algolia-bot and millotp committed Nov 19, 2024
1 parent f97e44c commit f8a1da7
Show file tree
Hide file tree
Showing 13 changed files with 310 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -84,26 +84,26 @@ export function deserializeSuccess<TObject>(response: Response): TObject {

const httpMessages: Record<number, string> = {
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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
33 changes: 33 additions & 0 deletions tests/output/csharp/src/generated/client/Ingestion.test.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<StatefulHost>
{
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<Exception>(async () =>
{
var res = await client.CustomGetAsync("1/html-error");
});
Assert.Equal(
"<html><body>429 too many requests</body></html>".ToLowerInvariant(),
_ex.Message.ToLowerInvariant()
);
}

[Fact(DisplayName = "calls api with correct user agent")]
public async Task CommonApiTest0()
{
Expand Down
26 changes: 26 additions & 0 deletions tests/output/go/tests/client/ingestion_test.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,33 @@ private ClientOptions withCustomHosts(List<Host> 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() {
Expand Down
26 changes: 26 additions & 0 deletions tests/output/javascript/src/client/ingestion.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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: \"<html><body>429 Too Many Requests</body></html>\"".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")
Expand Down
15 changes: 15 additions & 0 deletions tests/output/php/src/client/IngestionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
52 changes: 52 additions & 0 deletions tests/output/python/tests/client/ingestion_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
31 changes: 31 additions & 0 deletions tests/output/ruby/test/client/ingestion_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
4 changes: 2 additions & 2 deletions tests/output/ruby/test/client/search_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
),
Expand Down
Loading

0 comments on commit f8a1da7

Please sign in to comment.