Skip to content

Commit f8a1da7

Browse files
algolia-botmillotp
andcommitted
fix(cts): add tests for HTML error (#4097) (generated) [skip ci]
Co-authored-by: Pierre Millot <[email protected]>
1 parent f97e44c commit f8a1da7

File tree

13 files changed

+310
-24
lines changed

13 files changed

+310
-24
lines changed

clients/algoliasearch-client-javascript/packages/client-common/src/transporter/helpers.ts

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -84,26 +84,26 @@ export function deserializeSuccess<TObject>(response: Response): TObject {
8484

8585
const httpMessages: Record<number, string> = {
8686
400: 'Bad Request',
87-
401: 'Unauthorized',
88-
402: 'Payment Required',
89-
403: 'Forbidden',
90-
404: 'Not Found',
91-
405: 'Method Not Allowed',
92-
406: 'Not Acceptable',
93-
407: 'Proxy Authentication Required',
94-
408: 'Request Timeout',
95-
409: 'Conflict',
96-
410: 'Gone',
97-
411: 'Length Required',
98-
412: 'Precondition Required',
99-
413: 'Request Entry Too Large',
100-
414: 'Request-URI Too Long',
101-
415: 'Unsupported Media Type',
102-
416: 'Requested Range Not Satisfiable',
103-
417: 'Expectation Failed',
104-
418: 'I\'m a teapot',
105-
429: 'Too Many Requests',
106-
}
87+
401: 'Unauthorized',
88+
402: 'Payment Required',
89+
403: 'Forbidden',
90+
404: 'Not Found',
91+
405: 'Method Not Allowed',
92+
406: 'Not Acceptable',
93+
407: 'Proxy Authentication Required',
94+
408: 'Request Timeout',
95+
409: 'Conflict',
96+
410: 'Gone',
97+
411: 'Length Required',
98+
412: 'Precondition Required',
99+
413: 'Request Entry Too Large',
100+
414: 'Request-URI Too Long',
101+
415: 'Unsupported Media Type',
102+
416: 'Requested Range Not Satisfiable',
103+
417: 'Expectation Failed',
104+
418: "I'm a teapot",
105+
429: 'Too Many Requests',
106+
};
107107

108108
export function deserializeFailure({ content, status }: Response, stackFrame: StackFrame[]): Error {
109109
try {

clients/algoliasearch-client-ruby/lib/algolia/transport/http/http_requester.rb

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,14 +39,24 @@ def send_request(host, method, path, body, query_params, headers, timeout, conne
3939
@logger.info("Request succeeded. Response status: #{response.status}, body: #{response.body}")
4040
end
4141

42-
return Http::Response.new(status: response.status, reason_phrase: response.reason_phrase, body: response.body, headers: response.headers)
42+
return Http::Response.new(
43+
status: response.status,
44+
reason_phrase: response.reason_phrase,
45+
body: response.body,
46+
headers: response.headers
47+
)
4348
end
4449

4550
if ENV["ALGOLIA_DEBUG"]
4651
@logger.info("Request failed. Response status: #{response.status}, error: #{response.body}")
4752
end
4853

49-
Http::Response.new(status: response.status, reason_phrase: response.reason_phrase, error: response.body, headers: response.headers)
54+
Http::Response.new(
55+
status: response.status,
56+
reason_phrase: response.reason_phrase,
57+
error: response.body,
58+
headers: response.headers
59+
)
5060
rescue Faraday::TimeoutError => e
5161
@logger.info("Request timed out. Error: #{e.message}") if ENV["ALGOLIA_DEBUG"]
5262
Http::Response.new(error: e.message, has_timed_out: true)

tests/output/csharp/src/generated/client/Ingestion.test.cs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,39 @@ public IngestionClientTests()
2626
[Fact]
2727
public void Dispose() { }
2828

29+
[Fact(DisplayName = "can handle HTML error")]
30+
public async Task ApiTest0()
31+
{
32+
IngestionConfig _config = new IngestionConfig("test-app-id", "test-api-key", "us")
33+
{
34+
CustomHosts = new List<StatefulHost>
35+
{
36+
new()
37+
{
38+
Scheme = HttpScheme.Http,
39+
Url =
40+
Environment.GetEnvironmentVariable("CI") == "true"
41+
? "localhost"
42+
: "host.docker.internal",
43+
Port = 6676,
44+
Up = true,
45+
LastUse = DateTime.UtcNow,
46+
Accept = CallType.Read | CallType.Write,
47+
},
48+
},
49+
};
50+
var client = new IngestionClient(_config);
51+
52+
_ex = await Assert.ThrowsAnyAsync<Exception>(async () =>
53+
{
54+
var res = await client.CustomGetAsync("1/html-error");
55+
});
56+
Assert.Equal(
57+
"<html><body>429 too many requests</body></html>".ToLowerInvariant(),
58+
_ex.Message.ToLowerInvariant()
59+
);
60+
}
61+
2962
[Fact(DisplayName = "calls api with correct user agent")]
3063
public async Task CommonApiTest0()
3164
{

tests/output/go/tests/client/ingestion_test.go

Lines changed: 26 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

tests/output/java/src/test/java/com/algolia/client/Ingestion.test.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,33 @@ private ClientOptions withCustomHosts(List<Host> hosts, boolean gzipEncoding) {
4848
return ClientOptions.builder().setHosts(hosts).setCompressionType(gzipEncoding ? CompressionType.GZIP : CompressionType.NONE).build();
4949
}
5050

51+
@Test
52+
@DisplayName("can handle HTML error")
53+
void apiTest0() {
54+
IngestionClient client = new IngestionClient(
55+
"test-app-id",
56+
"test-api-key",
57+
"us",
58+
withCustomHosts(
59+
Arrays.asList(
60+
new Host(
61+
"true".equals(System.getenv("CI")) ? "localhost" : "host.docker.internal",
62+
EnumSet.of(CallType.READ, CallType.WRITE),
63+
"http",
64+
6676
65+
)
66+
),
67+
false
68+
)
69+
);
70+
{
71+
Exception exception = assertThrows(Exception.class, () -> {
72+
Object res = client.customGet("1/html-error");
73+
});
74+
assertEquals("Status Code: 429 - Too Many Requests", exception.getMessage());
75+
}
76+
}
77+
5178
@Test
5279
@DisplayName("calls api with correct user agent")
5380
void commonApiTest0() {

tests/output/javascript/src/client/ingestion.test.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,32 @@ function createClient() {
1313
return algoliasearch(appId, apiKey).initIngestion({ options: { requester: nodeEchoRequester() }, region: 'us' });
1414
}
1515

16+
describe('api', () => {
17+
test('can handle HTML error', async () => {
18+
const client = algoliasearch('test-app-id', 'test-api-key').initIngestion({
19+
options: {
20+
hosts: [
21+
{
22+
url: 'localhost',
23+
port: 6676,
24+
accept: 'readWrite',
25+
protocol: 'http',
26+
},
27+
],
28+
},
29+
// @ts-ignore
30+
region: 'us',
31+
});
32+
try {
33+
// @ts-ignore
34+
const result = await client.customGet({ path: '1/html-error' });
35+
throw new Error('test is expected to throw error');
36+
} catch (e) {
37+
expect((e as Error).message).toMatch('Too Many Requests');
38+
}
39+
}, 15000);
40+
});
41+
1642
describe('commonApi', () => {
1743
test('calls api with correct user agent', async () => {
1844
const client = createClient();

tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/IngestionTest.kt

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,16 @@ import kotlin.test.*
1515

1616
class IngestionTest {
1717

18+
@Test
19+
fun `can handle HTML error`() = runTest {
20+
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))))
21+
assertFails {
22+
client.customGet(
23+
path = "1/html-error",
24+
)
25+
}.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")) }
26+
}
27+
1828
@Test
1929
fun `calls api with correct user agent`() = runTest {
2030
val client = IngestionClient(appId = "appId", apiKey = "apiKey", region = "us")

tests/output/php/src/client/IngestionTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,21 @@ public function sendRequest(RequestInterface $request, $timeout, $connectTimeout
3838
return new Response(200, [], '{}');
3939
}
4040

41+
#[TestDox('can handle HTML error')]
42+
public function test0api(): void
43+
{
44+
$client = IngestionClient::createWithConfig(IngestionConfig::create('test-app-id', 'test-api-key', 'us')->setFullHosts(['http://'.('true' == getenv('CI') ? 'localhost' : 'host.docker.internal').':6676']));
45+
46+
try {
47+
$res = $client->customGet(
48+
'1/html-error',
49+
);
50+
$this->fail('Expected exception to be thrown');
51+
} catch (\Exception $e) {
52+
$this->assertEquals($e->getMessage(), '429: Too Many Requests');
53+
}
54+
}
55+
4156
#[TestDox('calls api with correct user agent')]
4257
public function test0commonApi(): void
4358
{

tests/output/python/tests/client/ingestion_test.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,32 @@ def create_client(self) -> IngestionClient:
1818
config=_config, transporter=EchoTransporter(_config)
1919
)
2020

21+
async def test_api_0(self):
22+
"""
23+
can handle HTML error
24+
"""
25+
26+
_config = IngestionConfig("test-app-id", "test-api-key", "us")
27+
_config.hosts = HostsCollection(
28+
[
29+
Host(
30+
url="localhost"
31+
if environ.get("CI") == "true"
32+
else "host.docker.internal",
33+
scheme="http",
34+
port=6676,
35+
)
36+
]
37+
)
38+
_client = IngestionClient.create_with_config(config=_config)
39+
try:
40+
await _client.custom_get(
41+
path="1/html-error",
42+
)
43+
assert False
44+
except (ValueError, Exception) as e:
45+
assert str(e) == "Too Many Requests"
46+
2147
async def test_common_api_0(self):
2248
"""
2349
calls api with correct user agent
@@ -149,6 +175,32 @@ def create_client(self) -> IngestionClientSync:
149175
config=_config, transporter=EchoTransporterSync(_config)
150176
)
151177

178+
def test_api_0(self):
179+
"""
180+
can handle HTML error
181+
"""
182+
183+
_config = IngestionConfig("test-app-id", "test-api-key", "us")
184+
_config.hosts = HostsCollection(
185+
[
186+
Host(
187+
url="localhost"
188+
if environ.get("CI") == "true"
189+
else "host.docker.internal",
190+
scheme="http",
191+
port=6676,
192+
)
193+
]
194+
)
195+
_client = IngestionClientSync.create_with_config(config=_config)
196+
try:
197+
_client.custom_get(
198+
path="1/html-error",
199+
)
200+
assert False
201+
except (ValueError, Exception) as e:
202+
assert str(e) == "Too Many Requests"
203+
152204
def test_common_api_0(self):
153205
"""
154206
calls api with correct user agent

tests/output/ruby/test/client/ingestion_test.rb

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,37 @@
33
require "test/unit"
44

55
class TestClientIngestionClient < Test::Unit::TestCase
6+
# can handle HTML error
7+
def test_api0
8+
client = Algolia::IngestionClient.create_with_config(
9+
Algolia::Configuration.new(
10+
"test-app-id",
11+
"test-api-key",
12+
[
13+
Algolia::Transport::StatefulHost.new(
14+
ENV.fetch("CI", nil) == "true" ? "localhost" : "host.docker.internal",
15+
protocol: "http://",
16+
port: 6676,
17+
accept: CallType::READ | CallType::WRITE
18+
)
19+
],
20+
"ingestionClient"
21+
)
22+
)
23+
begin
24+
client.custom_get("1/html-error")
25+
assert(false, "An error should have been raised")
26+
rescue => e
27+
assert_equal(
28+
"429: Too Many Requests".sub(
29+
"%localhost%",
30+
ENV.fetch("CI", nil) == "true" ? "localhost" : "host.docker.internal"
31+
),
32+
e.message
33+
)
34+
end
35+
end
36+
637
# calls api with correct user agent
738
def test_common_api0
839
client = Algolia::IngestionClient.create(

tests/output/ruby/test/client/search_test.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -320,7 +320,7 @@ def test_index_exists2
320320
assert(false, "An error should have been raised")
321321
rescue => e
322322
assert_equal(
323-
"Invalid API key".sub("%localhost%", ENV.fetch("CI", nil) == "true" ? "localhost" : "host.docker.internal"),
323+
"403: Invalid API key".sub("%localhost%", ENV.fetch("CI", nil) == "true" ? "localhost" : "host.docker.internal"),
324324
e.message
325325
)
326326
end
@@ -597,7 +597,7 @@ def test_save_objects1
597597
assert(false, "An error should have been raised")
598598
rescue => e
599599
assert_equal(
600-
"Invalid Application-ID or API key".sub(
600+
"403: Invalid Application-ID or API key".sub(
601601
"%localhost%",
602602
ENV.fetch("CI", nil) == "true" ? "localhost" : "host.docker.internal"
603603
),

0 commit comments

Comments
 (0)