Skip to content

Commit

Permalink
test: add portuguese util unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
RMCampos committed Nov 30, 2024
1 parent bf8797e commit 1c0d965
Show file tree
Hide file tree
Showing 9 changed files with 304 additions and 266 deletions.
37 changes: 37 additions & 0 deletions client/src/__test__/utils/PortugueseUtils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { describe, expect, it } from 'vitest';
import { translateTimeAgoPtBr, translateTimeLeftPtBr } from '../../utils/PortugueseUtils';
// import USER_LANG from '../../types/UserLangs';

describe('Portuguese Utils unit tests', () => {
// const target = USER_LANG.PORTUGUESE;

it('should translate all time ago messages', () => {
expect(translateTimeAgoPtBr('years ago', 2)).toBe('2 anos atrás');
expect(translateTimeAgoPtBr('year ago', 1)).toBe('1 ano atrás');
expect(translateTimeAgoPtBr('months ago', 2)).toBe('2 meses atrás');
expect(translateTimeAgoPtBr('month ago', 1)).toBe('1 mês atrás');
expect(translateTimeAgoPtBr('days ago', 2)).toBe('2 dias atrás');
expect(translateTimeAgoPtBr('day ago', 1)).toBe('1 dia atrás');
expect(translateTimeAgoPtBr('hours ago', 2)).toBe('2 horas atrás');
expect(translateTimeAgoPtBr('hour ago', 1)).toBe('1 hora atrás');
expect(translateTimeAgoPtBr('minutes ago', 2)).toBe('2 minutos atrás');
expect(translateTimeAgoPtBr('minute ago', 1)).toBe('1 minuto atrás');
expect(translateTimeAgoPtBr('seconds ago', 2)).toBe('2 segundos atrás');
expect(translateTimeAgoPtBr('second ago', 1)).toBe('1 segundo atrás');
expect(translateTimeAgoPtBr('lala', 1)).toBe('Momentos atrás');
expect(translateTimeAgoPtBr('null', 1)).toBe('Momentos atrás');
expect(translateTimeAgoPtBr('null', 0)).toBe('Momentos atrás');
});

it('should translate all time left messages', () => {
expect(translateTimeLeftPtBr('years left', 2)).toBe('2 anos restantes');
expect(translateTimeLeftPtBr('year left', 1)).toBe('1 ano restante');
expect(translateTimeLeftPtBr('months left', 2)).toBe('2 meses restantes');
expect(translateTimeLeftPtBr('month left', 1)).toBe('1 mês restante');
expect(translateTimeLeftPtBr('days left', 2)).toBe('2 dias restantes');
expect(translateTimeLeftPtBr('day left', 1)).toBe('1 dia restante');
expect(translateTimeLeftPtBr('lala', 1)).toBe('lala');
expect(translateTimeLeftPtBr('null', 1)).toBe('null');
expect(translateTimeLeftPtBr('null', 0)).toBe('null');
});
});
8 changes: 4 additions & 4 deletions client/src/components/LoginForm/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
import { Link, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import AuthContext from '../../context/AuthContext';
import { translateMessage } from '../../utils/TranslatorUtils';
import { translateServerResponse } from '../../utils/TranslatorUtils';
import { handleDefaultLang } from '../../lang-service/LangHandler';

/**
Expand Down Expand Up @@ -53,7 +53,7 @@ function LoginForm({ prefix }: { prefix: string }): JSX.Element {
const form = event.currentTarget;
if (form.checkValidity() === false) {
setFormInvalid(true);
setErrorMessage(translateMessage('Please fill in your username and password!', i18n.language));
setErrorMessage(translateServerResponse('Please fill in your username and password!', i18n.language));
return;
}

Expand All @@ -70,10 +70,10 @@ function LoginForm({ prefix }: { prefix: string }): JSX.Element {
catch (e) {
setFormInvalid(true);
if (typeof e === 'string') {
setErrorMessage(translateMessage(e, i18n.language));
setErrorMessage(translateServerResponse(e, i18n.language));
}
else if (e instanceof Error) {
setErrorMessage(translateMessage(e.message, i18n.language));
setErrorMessage(translateServerResponse(e.message, i18n.language));
}
}
};
Expand Down
66 changes: 60 additions & 6 deletions client/src/utils/PortugueseUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
*
* @param {string} textValue The text message to be translated.
* @param {number} numberValue The number value to be used in the message.
* @returns The message translated.
* @returns The translated message.
*/
function translateTimeAgoPtBr(textValue: string, numberValue: number): string {
if (textValue.includes('year')) {
Expand All @@ -16,7 +16,7 @@ function translateTimeAgoPtBr(textValue: string, numberValue: number): string {
? `${numberValue} meses atrás`
: `${numberValue} mês atrás`;
}
else if (textValue.includes('days')) {
else if (textValue.includes('day')) {
return textValue.includes('s ')
? `${numberValue} dias atrás`
: `${numberValue} dia atrás`;
Expand All @@ -26,12 +26,12 @@ function translateTimeAgoPtBr(textValue: string, numberValue: number): string {
? `${numberValue} horas atrás`
: `${numberValue} hora atrás`;
}
else if (textValue.includes('minutes')) {
else if (textValue.includes('minute')) {
return textValue.includes('s ')
? `${numberValue} minutos atrás`
: `${numberValue} minuto atrás`;
}
else if (textValue.includes('seconds')) {
else if (textValue.includes('second')) {
return textValue.includes('s ')
? `${numberValue} segundos atrás`
: `${numberValue} segundo atrás`;
Expand All @@ -45,7 +45,7 @@ function translateTimeAgoPtBr(textValue: string, numberValue: number): string {
*
* @param {string} textValue The text message to be translated.
* @param {number} numberValue The number value to be used in the message.
* @returns The message translated.
* @returns The translated message.
*/
function translateTimeLeftPtBr(textValue: string, numberValue: number): string {
if (textValue.includes('year')) {
Expand All @@ -66,4 +66,58 @@ function translateTimeLeftPtBr(textValue: string, numberValue: number): string {
return textValue;
}

export { translateTimeAgoPtBr, translateTimeLeftPtBr };
/**
* Translates a server response message from English to brazilian Portuguese.
*
* @param {string} message The text message to be translated.
* @returns The translated message.
*/
function translateServerResponsePtBr(message: string): string {
switch (message) {
case 'Bad password: Password must have at least at least 8 characters, 1 uppercase, 1 special character': {
return 'Senha fraca: Senha deve possuir pelo menos 8 letras, 1 maiúscula, 1 caracter especial';
}
case 'Bad password: Password must have at least 1 uppercase, 1 special character': {
return 'Senha fraca: Senha deve possuir pelo menos 1 maiúscula, 1 caracter especial';
}
case 'Bad password: Password must have at least 1 special character': {
return 'Senha fraca: Senha deve possuir pelo menos 1 caracter especial';
}
case 'Email already exists!': {
return 'E-mail já cadastrado!';
}
case 'Forbidden! Access denied!': {
return 'Proibido! Acesso negado';
}
case 'Internal Server Error!': {
return 'Erro Interno do Servidor!';
}
case 'Max login attempt limit reached. Please wait 30 minutes': {
return 'Limite máximo de tentativas atingido. Por favor aguarde 30 minutos';
}
case 'Please fill in all the fields': {
return 'Por ravor, preencha todos os campos';
}
case 'Please fill in your username and password!': {
return 'Por favor, informe seu e-mail e senha!';
}
case 'Please type at least 3 characters': {
return 'Por favor, digite pelo menos 3 letras';
}
case 'The maximum text length is 2000': {
return 'O tamanho máximo do texto é 2000';
}
case 'Unknown error': {
return 'Erro desconhecido';
}
case 'Wrong or missing information!': {
return 'Informação errada ou incompleta!';
}
case 'Wrong user or password': {
return 'E-mail ou senha inválidos!';
}
default: return message;
}
}

export { translateTimeAgoPtBr, translateTimeLeftPtBr, translateServerResponsePtBr };
89 changes: 88 additions & 1 deletion client/src/utils/RussianUtils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
/**
* Translates a time ago message from English to Russian.
*
* @param {string} textValue The text message to be translated.
* @param {number} numberValue The number value to be used in the message.
* @returns The translated message.
*/
function translateTimeAgoRu(textValue: string, numberValue: number): string {
if (textValue.includes('year')) {
return textValue.includes('s ')
Expand Down Expand Up @@ -33,4 +40,84 @@ function translateTimeAgoRu(textValue: string, numberValue: number): string {
return 'Несколько минут назад';
}

export { translateTimeAgoRu };
/**
* Translates a time left message from English to Russian.
*
* @param {string} textValue The text message to be translated.
* @param {number} numberValue The number value to be used in the message.
* @returns The translated message.
*/
function translateTimeLeftRu(textValue: string, numberValue: number): string {
if (textValue.includes('year')) {
return textValue.includes('s ')
? `осталось ${numberValue} лет`
: `Остался ${numberValue} год`;
}
else if (textValue.includes('month')) {
return textValue.includes('s ')
? `осталось ${numberValue} месяцев`
: `Остался ${numberValue} месяц`;
}
else if (textValue.includes('day')) {
return textValue.includes('s ')
? `осталось ${numberValue} дней`
: `Остался ${numberValue} день`;
}
return textValue;
}

/**
* Translates a server response message from English to Russian.
*
* @param {string} message The text message to be translated.
* @returns The translated message.
*/
function translateServerResponseRu(message: string): string {
switch (message) {
case 'Bad password: Password must have at least at least 8 characters, 1 uppercase, 1 special character': {
return 'Неправильный пароль: Пароль должен содержать не менее 8 символов, 1 заглавную букву, 1 специальный символ.';
}
case 'Bad password: Password must have at least 1 uppercase, 1 special character': {
return 'Неправильный пароль: Пароль должен содержать как минимум 1 заглавную букву и 1 специальный символ.';
}
case 'Bad password: Password must have at least 1 special character': {
return 'Неправильный пароль: Пароль должен содержать хотя бы 1 специальный символ.';
}
case 'Email already exists!': {
return 'Электронная почта уже существует!';
}
case 'Forbidden! Access denied!': {
return 'Запрещено! Доступ запрещен!';
}
case 'Internal Server Error!': {
return 'Внутренняя ошибка сервера!';
}
case 'Max login attempt limit reached. Please wait 30 minutes': {
return 'Достигнут максимальный лимит попыток входа. Пожалуйста, подождите 30 минут';
}
case 'Please fill in all the fields': {
return 'Пожалуйста, заполните все поля';
}
case 'Please fill in your username and password!': {
return 'Пожалуйста, введите свое имя пользователя и пароль!';
}
case 'Please type at least 3 characters': {
return 'Пожалуйста, введите не менее 3 символов';
}
case 'The maximum text length is 2000': {
return 'Максимальная длина текста — 2000.';
}
case 'Unknown error': {
return 'Неизвестная ошибка';
}
case 'Wrong or missing information!': {
return 'Неверная или отсутствующая информация!';
}
case 'Wrong user or password': {
return 'Неправильный пользователь или пароль';
}
default: return message;
}
}

export { translateTimeAgoRu, translateTimeLeftRu, translateServerResponseRu };
60 changes: 57 additions & 3 deletions client/src/utils/SpanishUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
*
* @param {string} textValue The text message to be translated.
* @param {number} numberValue The number value to be used in the message.
* @returns The message translated.
* @returns The translated message.
*/
function translateTimeAgoEs(textValue: string, numberValue: number): string {
if (textValue.includes('year')) {
Expand Down Expand Up @@ -45,7 +45,7 @@ function translateTimeAgoEs(textValue: string, numberValue: number): string {
*
* @param {string} textValue The text message to be translated.
* @param {number} numberValue The number value to be used in the message.
* @returns The message translated.
* @returns The translated message.
*/
function translateTimeLeftEs(textValue: string, numberValue: number): string {
if (textValue.includes('year')) {
Expand All @@ -66,4 +66,58 @@ function translateTimeLeftEs(textValue: string, numberValue: number): string {
return textValue;
}

export { translateTimeAgoEs, translateTimeLeftEs };
/**
* Translates a server response message from English to Spanish.
*
* @param {string} message The text message to be translated.
* @returns The translated message.
*/
function translateServerResponseEs(message: string): string {
switch (message) {
case 'Bad password: Password must have at least at least 8 characters, 1 uppercase, 1 special character': {
return 'Contraseña inválida: La contraseña debe tener al menos 8 caracteres, 1 mayúscula y 1 carácter especial';
}
case 'Bad password: Password must have at least 1 uppercase, 1 special character': {
return 'Contraseña inválida: La contraseña debe tener al menos 1 mayúscula y 1 carácter especial';
}
case 'Bad password: Password must have at least 1 special character': {
return 'Contraseña inválida: La contraseña debe tener al menos 1 carácter especial';
}
case 'Email already exists!': {
return '¡El correo ya está registrado!';
}
case 'Forbidden! Access denied!': {
return '¡Prohibido! Acceso denegado';
}
case 'Internal Server Error!': {
return '¡Error interno del servidor!';
}
case 'Max login attempt limit reached. Please wait 30 minutes': {
return 'Has alcanzado el límite máximo de intentos de inicio de sesión. Por favor, espera 30 minutos';
}
case 'Please fill in all the fields': {
return 'Por favor, completa todos los campos';
}
case 'Please fill in your username and password!': {
return '¡Por favor, ingresa tu nombre de usuario y contraseña!';
}
case 'Please type at least 3 characters': {
return '¡Por favor, escriba al menos 3 caracteres';
}
case 'The maximum text length is 2000': {
return 'La longitud máxima del texto es 2000';
}
case 'Unknown error': {
return 'Error desconocido';
}
case 'Wrong or missing information!': {
return '¡Información incorrecta o incompleta!';
}
case 'Wrong user or password': {
return '¡Usuario o contraseña incorrectos!';
}
default: return message;
}
}

export { translateTimeAgoEs, translateTimeLeftEs, translateServerResponseEs };
Loading

0 comments on commit 1c0d965

Please sign in to comment.