Skip to content

Commit

Permalink
Add more tests & code Int > String
Browse files Browse the repository at this point in the history
  • Loading branch information
brenoepics committed Jan 31, 2024
1 parent 58cf4ea commit 7cde6c1
Show file tree
Hide file tree
Showing 8 changed files with 132 additions and 90 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,14 @@ public CompletableFuture<Optional<TranslationResponse>> translate(TranslateParam
.get("translations")
.forEach(node -> translations.add(Translation.ofJSON((ObjectNode) node)));

TranslationResponse translationResponse = new TranslationResponse(translations);
TranslationResponse translationResponse;
if (jsonNode.has("detectedLanguage")) {
JsonNode detectedLanguage = jsonNode.get("detectedLanguage");
translationResponse.setDetectedLanguage(
DetectedLanguage.ofJSON((ObjectNode) detectedLanguage));
translationResponse =
new TranslationResponse(
DetectedLanguage.ofJSON((ObjectNode) detectedLanguage), translations);
} else {
translationResponse = new TranslationResponse(translations);
}

return Optional.of(translationResponse);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,6 @@ public TranslationResponse(Collection<Translation> translations) {
this.translations = translations;
}

/**
* Sets the detected language of the input text.
*
* @param detectedLanguage The detected language of the input text.
*/
public void setDetectedLanguage(DetectedLanguage detectedLanguage) {
this.detectedLanguage = detectedLanguage;
}

/**
* Returns the detected language of the input text.
*
Expand Down
91 changes: 45 additions & 46 deletions src/main/java/io/github/brenoepics/at4j/util/rest/RestRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -280,70 +280,69 @@ private RestRequestResult<T> handleError(int resultCode, RestRequestResult<T> re
RestRequestInformation requestInformation = asRestRequestInformation();
RestRequestResponseInformation responseInformation =
new RestRequestResponseInformationImpl<>(requestInformation, result);
Optional<RestRequestHttpResponseCode> responseCode =
Optional<RestRequestHttpResponseCode> responseCodeOptional =
RestRequestHttpResponseCode.fromCode(resultCode);

if (responseCodeOptional.isEmpty()) {
throw new AzureException(
origin,
"Received a response from Azure with a not found resultCode!",
requestInformation,
responseInformation);
}

RestRequestHttpResponseCode responseCode = responseCodeOptional.get();

String code = responseCode.getCode() + "000";
String error = null;
if (!result.getJsonBody().isNull() && result.getJsonBody().has("error")) {
handleKnownError(result, responseCode.orElse(null), requestInformation, responseInformation);
code = result.getJsonBody().get("error").get("code").asText();
error = result.getJsonBody().get("error").get("message").asText();
}

Optional<? extends AzureException> azureException =
handleKnownError(responseCode, code, error, requestInformation, responseInformation);

if (azureException.isPresent()) {
throw azureException.get();
}

if (resultCode == 429) {
return result;
}

Optional<? extends AzureException> azureException =
responseCode.flatMap(
restRequestHttpResponseCode ->
restRequestHttpResponseCode.getAzureException(
origin,
"Received a "
+ resultCode
+ " response from Azure with"
+ (result.getStringBody().isPresent() ? "" : " empty")
+ " body"
+ result.getStringBody().map(s -> " " + s).orElse("")
+ "!",
requestInformation,
responseInformation));
String message = "Received a " + resultCode + " response from Azure, Meaning: %MEANING%";

String bodyPresent = result.getStringBody().isPresent() ? "" : " empty";
throw azureException.isPresent()
? azureException.get()
: new AzureException(
azureException =
responseCode.getAzureException(
origin,
"Received a "
+ resultCode
+ " response from Azure with"
+ bodyPresent
+ " body"
+ result.getStringBody().map(s -> " " + s).orElse("")
+ "!",
message.replace("%MEANING%", responseCode.getMeaning()),
requestInformation,
responseInformation);

if (azureException.isPresent()) {
throw azureException.get();
} else {
throw new AzureException(
origin, message.replace("%MEANING%", "Unknown"), requestInformation, responseInformation);
}
}

private void handleKnownError(
RestRequestResult<T> result,
private Optional<? extends AzureException> handleKnownError(
RestRequestHttpResponseCode responseCode,
String code,
String message,
RestRequestInformation requestInformation,
RestRequestResponseInformation responseInformation)
throws AzureException {
JsonNode errorBody = result.getJsonBody().get("error");
int code = errorBody.get("code").asInt();
String message = errorBody.has("message") ? errorBody.get("message").asText() : null;
Optional<? extends AzureException> azureException =
RestRequestResultErrorCode.fromCode(code, responseCode)
.flatMap(
restRequestResultCode ->
restRequestResultCode.getAzureException(
origin,
(message == null) ? restRequestResultCode.getMeaning() : message,
requestInformation,
responseInformation));
RestRequestResponseInformation responseInformation) {

if (azureException.isPresent()) {
throw azureException.get();
}
return RestRequestResultErrorCode.fromCode(code, responseCode)
.flatMap(
restRequestResultCode ->
restRequestResultCode.getAzureException(
origin,
(message == null) ? restRequestResultCode.getMeaning() : message,
requestInformation,
responseInformation));
}

private void request(HttpRequest.Builder requestBuilder) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
package io.github.brenoepics.at4j.util.rest;

import io.github.brenoepics.at4j.core.exceptions.AzureException;
import io.github.brenoepics.at4j.core.exceptions.AzureExceptionInstantiation;
import io.github.brenoepics.at4j.core.exceptions.BadRequestException;
import io.github.brenoepics.at4j.core.exceptions.NotFoundException;
import io.github.brenoepics.at4j.core.exceptions.*;

import java.util.Arrays;
import java.util.Collections;
Expand Down Expand Up @@ -38,10 +35,18 @@ public enum RestRequestHttpResponseCode {
BadRequestException.class),

/** The Authorization header was missing or invalid. */
UNAUTHORIZED(401, "The Authorization header was missing or invalid"),
UNAUTHORIZED(
401,
"The Authorization header was missing or invalid",
UnauthorizedException::new,
UnauthorizedException.class),

/** The Authorization token you passed did not have permission to the resource. */
FORBIDDEN(403, "The Authorization token you passed did not have permission to the resource"),
FORBIDDEN(
403,
"The Authorization token you passed did not have permission to the resource",
ForbiddenException::new,
ForbiddenException.class),

/** The resource at the location specified doesn't exist. */
NOT_FOUND(
Expand All @@ -51,14 +56,25 @@ public enum RestRequestHttpResponseCode {
NotFoundException.class),

/** The HTTP method used is not valid for the location specified. */
METHOD_NOT_ALLOWED(405, "The HTTP method used is not valid for the location specified"),
METHOD_NOT_ALLOWED(
405,
"The HTTP method used is not valid for the location specified",
MethodNotAllowedException::new,
MethodNotAllowedException.class),

/** The request timed out, you can retry it again later with the same parameters. */
REQUEST_TIMEOUT(408, "The request timed out, you can retry it again later"),
REQUEST_TIMEOUT(
408,
"The request timed out, you can retry it again later",
RequestTimeoutException::new,
RequestTimeoutException.class),

/** The request entity has a media type which the server or resource does not support. */
UNSUPPORTED_MEDIA_TYPE(
415, "The request entity has a media type which the server or resource does not support"),
415,
"The request entity has a media type which the server or resource does not support",
UnsupportedMediaTypeException::new,
UnsupportedMediaTypeException.class),
/** You've made too many requests. */
TOO_MANY_REQUESTS(429, "You've made too many requests"),

Expand All @@ -67,10 +83,16 @@ public enum RestRequestHttpResponseCode {
502, "There was not a gateway available to process your request. Wait a bit and retry"),

/** There was an internal server error while processing your request. */
INTERNAL_SERVER_ERROR(500, "There was an internal server error while processing your request"),
INTERNAL_SERVER_ERROR(
500,
"There was an internal server error while processing your request",
InternalServerErrorException::new,
InternalServerErrorException.class),

/** There was a service unavailable while processing your request. */
SERVICE_UNAVAILABLE(503, "There was a service unavailable while processing your request");
SERVICE_UNAVAILABLE(503, "There was a service unavailable while processing your request",
ServiceUnavailableException::new,
ServiceUnavailableException.class);

/** A map for retrieving the enum instances by code. */
private static final Map<Integer, RestRequestHttpResponseCode> instanceByCode;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,10 +215,10 @@ public enum RestRequestResultErrorCode {
;

/** A map for retrieving the enum instances by code. */
private static final Map<Integer, RestRequestResultErrorCode> instanceByCode;
private static final Map<String, RestRequestResultErrorCode> instanceByCode;

/** The actual numeric result code. */
private final int code;
private final String code;

/** The textual meaning. */
private final String meaning;
Expand Down Expand Up @@ -263,7 +263,7 @@ public enum RestRequestResultErrorCode {
String meaning,
AzureExceptionInstantiation<AzureException> azureExceptionInstantiation,
RestRequestHttpResponseCode responseCode) {
this.code = code;
this.code = String.valueOf(code);
this.meaning = meaning;
this.azureExceptionInstantiation = azureExceptionInstantiation;
this.responseCode = responseCode;
Expand All @@ -277,7 +277,7 @@ public enum RestRequestResultErrorCode {
* @return The web socket close code with the actual numeric result code.
*/
public static Optional<RestRequestResultErrorCode> fromCode(
int code, RestRequestHttpResponseCode responseCode) {
String code, RestRequestHttpResponseCode responseCode) {
return Optional.ofNullable(instanceByCode.get(code))
.filter(errorCode -> errorCode.responseCode == responseCode);
}
Expand All @@ -287,7 +287,7 @@ public static Optional<RestRequestResultErrorCode> fromCode(
*
* @return The actual numeric result code.
*/
public int getCode() {
public String getCode() {
return code;
}

Expand Down
41 changes: 40 additions & 1 deletion src/test/java/io/github/brenoepics/at4j/AzureApiTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import io.github.brenoepics.at4j.azure.BaseURL;
import io.github.brenoepics.at4j.azure.lang.Language;
import io.github.brenoepics.at4j.data.DetectedLanguage;
import io.github.brenoepics.at4j.data.request.AvailableLanguagesParams;
import io.github.brenoepics.at4j.data.request.DetectLanguageParams;
import io.github.brenoepics.at4j.data.request.TranslateParams;
import io.github.brenoepics.at4j.data.response.TranslationResponse;

Expand All @@ -12,6 +14,7 @@
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;

import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

Expand Down Expand Up @@ -87,10 +90,46 @@ void translateEmptyText() {
void translateEmptySourceLanguage() {
AzureApi api = new AzureApiBuilder().baseURL(BaseURL.GLOBAL).setKey("test").build();

TranslateParams params = new TranslateParams("", List.of("pt")).setTargetLanguages("pt");
TranslateParams params = new TranslateParams("", List.of("pt"));
CompletableFuture<Optional<TranslationResponse>> translation = api.translate(params);
Optional<TranslationResponse> tr = translation.join();
tr.ifPresent(translations -> assertEquals(0, translations.getTranslations().size()));
api.disconnect();
}

@Test
void translateHelloWorld() {
String subscriptionKey = System.getenv("AZURE_KEY");
String subscriptionRegion = System.getenv("AZURE_REGION");
Assumptions.assumeTrue(
subscriptionKey != null && subscriptionRegion != null,
"Azure Credentials are null, skipping the test");

AzureApiBuilder builder =
new AzureApiBuilder().setKey(subscriptionKey).region(subscriptionRegion);
AzureApi api = builder.build();

TranslateParams params = new TranslateParams("Hello World!", List.of("pt", "es"));
Optional<TranslationResponse> translate = api.translate(params).join();
assertTrue(translate.isPresent());
assertEquals(2, translate.get().getTranslations().size());
}

@Test
void detectHelloWorldLanguage() {
String subscriptionKey = System.getenv("AZURE_KEY");
String subscriptionRegion = System.getenv("AZURE_REGION");
Assumptions.assumeTrue(
subscriptionKey != null && subscriptionRegion != null,
"Azure Credentials are null, skipping the test");
AzureApiBuilder builder =
new AzureApiBuilder().setKey(subscriptionKey).region(subscriptionRegion);
AzureApi api = builder.build();

Optional<DetectedLanguage> detect =
api.detectLanguage(new DetectLanguageParams("Hello World!")).join();

assertTrue(detect.isPresent());
assertEquals("en", detect.get().getLanguageCode());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,6 @@ void createsTranslationResponseWithTranslationsOnly() {
assertEquals(translation, response.getTranslations().iterator().next());
}

@Test
void setsDetectedLanguageAfterCreation() {
DetectedLanguage detectedLanguage = new DetectedLanguage("en", 1.0f);
TranslationResponse response = new TranslationResponse(Collections.emptyList());

assertNull(response.getDetectedLanguage());

response.setDetectedLanguage(detectedLanguage);

assertEquals(detectedLanguage, response.getDetectedLanguage());
}

@Test
void returnsEmptyTranslationsWhenNoneProvided() {
TranslationResponse response = new TranslationResponse(Collections.emptyList());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ void test_all_enum_values() {

@Test
void test_getCode() {
Map<RestRequestResultErrorCode, Integer> expectedCodes = new HashMap<>();
Map<RestRequestResultErrorCode, String> expectedCodes = new HashMap<>();
expectedCodes.putAll(
Arrays.stream(RestRequestResultErrorCode.values())
.collect(
Expand All @@ -34,8 +34,8 @@ void test_getCode() {
HashMap::putAll));

for (RestRequestResultErrorCode errorCode : RestRequestResultErrorCode.values()) {
int expectedCode = expectedCodes.get(errorCode);
int actualCode = errorCode.getCode();
String expectedCode = expectedCodes.get(errorCode);
String actualCode = errorCode.getCode();
assertEquals(expectedCode, actualCode);
}
}
Expand Down

0 comments on commit 7cde6c1

Please sign in to comment.