1. Introducción
2. ¿Qué es localise / LOCO?
3. ¿Cómo usar Loco con Appium?
4. Conclusiones
Introducción:
Cuando se trata de aplicaciones multilenguaje, la necesidad de realizar pruebas exhaustivas en diferentes idiomas se vuelve aún más crítica.
En este blog, exploraremos cómo combinar Appium/Pytest con LOCO para lograr una automatización de pruebas efectiva en aplicaciones multilenguaje.
¿Qué es Localise/Loco?
Loco te ayuda a gestionar e integrar traducciones en tu software, independientemente de lo que estés creando. Los desarrolladores pueden importar y exportar traducciones en muchos formatos de archivos diferentes, incluidos Android, iOS, Gettext, PHP, JavaScript, JSON, YAML, XML, XLIFF, TMX y más.
Un único proyecto de Loco puede gestionar el mismo conjunto de traducciones en múltiples plataformas a la vez.
¿Cómo usar Loco con Appium?
- Gestión de diferentes idiomas: Con esta integración entre Appium y Loco podremos verificar que nuestra app presenta los textos esperados en cada idioma.
1. En nuestro conftest.py descargaremos el archivo yml según el idioma seleccionado en nuestra prueba
@pytest.fixture(autouse=True, scope="session")
def download_yaml_file(request):
# Get the language option from the pytest configuration
language = request.config.getoption("language").lower()
# Map the language option to its corresponding language code
languages = {"spanish": "es", "catalan": "ca", "french": "fr", "english": "en"}
language = languages.get(language.lower())
# Get the localization key from the project configuration
loco_key = project_config["loco_key"]
# Construct the URL to download the YAML file for the selected language
url = f"https://localise.biz:443/api/export/locale/{language}.yml?key={loco_key}"
# Define the directory path to save the YAML file
directory_path = f"{CommonUtils.get_project_path()}/utilities/translations"
yaml_file_path = f"{directory_path}/{language}_locale.yml"
# Download the YAML file from the constructed URL
response = requests.get(url)
response.raise_for_status() # Raise an exception for error HTTP statuses
# Check if the directory exists, if not, create it
if not os.path.exists(directory_path):
os.makedirs(directory_path)
logger.info(f"Directory '{directory_path}' created.")
else:
logger.info(f"Directory '{directory_path}' already exists.")
# Write the downloaded YAML content to the file
with open(yaml_file_path, "w") as f:
f.write(response.text)
2. Recuperaremos el id de Loco que deseamos
def get_id_text_for_language(key_in_loco: str):
"""
Retrieves the text associated with a given key for the currently selected language.
Args:
key_in_loco (str): The key for which the text needs to be retrieved.
Returns:
str: The text associated with the given key for the selected language.
The function determines the selected language from the device information and constructs the file path
to the corresponding locale YAML file. It then loads the YAML file and retrieves the text associated
with the provided key.
"""
language_selected = {
"spanish": "es",
"catalan": "ca",
"english": "en",
"french": "fr",
}.get(os.getenv("LANGUAGE"), "en")
file_path = f"utilities/translations/{language_selected}_locale.yml"
try:
with open(file_path, "r") as file:
data = yaml.safe_load(file)
if key_in_loco not in data:
logger.error(f"Key '{key_in_loco}' not found in {file_path}")
raise KeyError(f"Key '{key_in_loco}' not found in {file_path}")
return data.get(key_in_loco)
except FileNotFoundError:
logger.error(f"File not found: {file_path}")
raise FileNotFoundError
except yaml.YAMLError as exc:
logger.error(f"Error parsing YAML file: {exc}")
return None
3. Creamos función para utilizar el id del loco
def get_id_text_for_language(key_in_loco: str):
"""
Retrieves the text associated with a given key for the currently selected language.
Args:
key_in_loco (str): The key for which the text needs to be retrieved.
Returns:
str: The text associated with the given key for the selected language.
The function determines the selected language from the device information and constructs the file path
to the corresponding locale YAML file. It then loads the YAML file and retrieves the text associated
with the provided key.
"""
language_selected = {
"spanish": "es",
"catalan": "ca",
"english": "en",
"french": "fr",
}.get(os.getenv("LANGUAGE"), "en")
file_path = f"utilities/translations/{language_selected}_locale.yml"
try:
with open(file_path, "r") as file:
data = yaml.safe_load(file)
if key_in_loco not in data:
logger.error(f"Key '{key_in_loco}' not found in {file_path}")
raise KeyError(f"Key '{key_in_loco}' not found in {file_path}")
return data.get(key_in_loco)
except FileNotFoundError:
logger.error(f"File not found: {file_path}")
raise FileNotFoundError
except yaml.YAMLError as exc:
logger.error(f"Error parsing YAML file: {exc}")
return None
4. Uso del el elemento creado a través del loco id para localización y como identificador de elementos
Ahora podemos usar el elemento creado a partir del Loco ID para poder verificar que el texto localizado se encuentra en la app y a su vez como ID único para localizar elementos.
element_to_verify = create_element_with_loco_id("welcome.text")
self.driver.find_element(*element_to_verify)
Conclusiones
En resumen, la combinación de Appium y Loco permite:
- Automatizar la verificación de textos localizados: Asegurando que los textos correctos se muestren en cada idioma.
- Simplificar la gestión de traducciones: Utilizando Loco para centralizar y gestionar los archivos de localización.
- Mejorar la mantenibilidad del código de prueba: Al utilizar IDs de Loco como identificadores únicos para elementos.
- Facilitar la configuración de pruebas multilenguaje: A través de la descarga dinámica de archivos YAML y la configuración de pytest.