|
| 1 | +/* |
| 2 | + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 3 | + * or more contributor license agreements. Licensed under the Elastic License |
| 4 | + * 2.0; you may not use this file except in compliance with the Elastic License |
| 5 | + * 2.0. |
| 6 | + */ |
| 7 | + |
| 8 | +package org.elasticsearch.xpack.inference.services.custom; |
| 9 | + |
| 10 | +import org.apache.http.HttpResponse; |
| 11 | +import org.apache.http.StatusLine; |
| 12 | +import org.elasticsearch.common.Strings; |
| 13 | +import org.elasticsearch.common.xcontent.XContentHelper; |
| 14 | +import org.elasticsearch.test.ESTestCase; |
| 15 | +import org.elasticsearch.xpack.inference.external.http.HttpResult; |
| 16 | +import org.elasticsearch.xpack.inference.external.http.retry.ErrorResponse; |
| 17 | + |
| 18 | +import java.io.IOException; |
| 19 | +import java.nio.charset.StandardCharsets; |
| 20 | + |
| 21 | +import static org.elasticsearch.xpack.inference.services.custom.CustomResponseHandler.ERROR_PARSER; |
| 22 | +import static org.hamcrest.Matchers.is; |
| 23 | +import static org.mockito.Mockito.mock; |
| 24 | +import static org.mockito.Mockito.when; |
| 25 | + |
| 26 | +public class CustomResponseHandlerTests extends ESTestCase { |
| 27 | + |
| 28 | + public void testErrorBodyParser() throws IOException { |
| 29 | + var expected = XContentHelper.stripWhitespace(Strings.format(""" |
| 30 | + { |
| 31 | + "error": { |
| 32 | + "message": "%s", |
| 33 | + "type": "content_too_large", |
| 34 | + "param": null, |
| 35 | + "code": null |
| 36 | + } |
| 37 | + } |
| 38 | + """, "message")); |
| 39 | + |
| 40 | + assertThat(ERROR_PARSER.apply(createResult(400, "message")), is(new ErrorResponse(expected))); |
| 41 | + } |
| 42 | + |
| 43 | + private static HttpResult createResult(int statusCode, String message) throws IOException { |
| 44 | + var statusLine = mock(StatusLine.class); |
| 45 | + when(statusLine.getStatusCode()).thenReturn(statusCode); |
| 46 | + var httpResponse = mock(HttpResponse.class); |
| 47 | + when(httpResponse.getStatusLine()).thenReturn(statusLine); |
| 48 | + |
| 49 | + String responseJson = XContentHelper.stripWhitespace(Strings.format(""" |
| 50 | + { |
| 51 | + "error": { |
| 52 | + "message": "%s", |
| 53 | + "type": "content_too_large", |
| 54 | + "param": null, |
| 55 | + "code": null |
| 56 | + } |
| 57 | + } |
| 58 | + """, message)); |
| 59 | + |
| 60 | + return new HttpResult(httpResponse, responseJson.getBytes(StandardCharsets.UTF_8)); |
| 61 | + } |
| 62 | +} |
0 commit comments