# Juego de pruebas de Weblate e integración continua

Existe un conjunto de pruebas para muchos de los códigos actuales, incremente cobertura por añadir casos de pruebas para cualquier funcionalidad nueva, y verifica que esto funcione.

<a id="ci-tests"></a>

## Integración continua

Weblate se basa en [Acciones GitHub](https://github.com/WeblateOrg/weblate/actions) para ejecutar pruebas, crear documentación, revisar código y realizar otras tareas para garantizar la calidad del código.

[Codecov](https://app.codecov.io/gh/WeblateOrg/weblate/) recolecta información de cobertura del código desde las pruebas que fueron ejecutadas.

Hay varias tareas para verificar aspectos diferentes:

* Pruebas unitarias y funcionales utilizando [pytest](https://pytest.org/).
* Documentación de compilación y enlaces externos utilizando [Sphinx](https://www.sphinx-doc.org/).
* Control de calidad y revisión de código mediante [ruff](https://docs.astral.sh/ruff/) y [pylint](https://www.pylint.org/).
* Digitalización de seguridad de código usando [CodeQL](https://codeql.github.com/).
* Los cambios visuales de pruebas utilizan [Argos CI](https://argos-ci.com).
* Formato de código utilizando [prek](https://pypi.org/project/prek/), una re‐implementación de terceros más rápida del framework [pre-commit](https://pre-commit.com/).
* Pruebas de migración desde todas las versiones mantenidas
* Package builds, metadata, manifest, archive-content, and installation checks.
  The package lint tools are pinned in `pyproject.toml` and resolved in
  `uv.lock`; CI runs them with **uv run --frozen**.
* Dependency review of pull requests.

GitHub rulesets protect `main` and `stable`. They require pull requests and
passing status checks, including package build and lint checks and dependency
review. The [GitHub repository rules](https://github.com/WeblateOrg/weblate/rules) show the current required checks and
permitted writers. Membership in the writer allowlist does not by itself
bypass the pull-request or CI requirements. Repository administrators and
organization owners have a separate bypass for maintainer operations.

La configuración para la CI se encuentra en el directorio `.github/workflows`. Utiliza en gran medida scripts auxiliares almacenados en el directorio `ci`. Los script también se pueden ejecutar manualmente, pero requieren varias variables de entorno, principalmente para definir el archivo de configuración de Django que se va a utilizar y probar la conexión a la base de datos. El ejemplo de definición se encuentra en `scripts/test-database.sh`:

Las pruebas de captura de pantalla de Selenium en `weblate/trans/tests/test_selenium.py` tienen dos propósitos. Generan imágenes para pruebas de cambios visuales en CI, y las mismas imágenes se convierten en capturas de pantalla de documentación mediante: **make -C docs update-screenshots**. Mantenga las capturas de pantalla cerca de las páginas renderizadas reales para que CI detecte las regresiones de la interfaz de usuario. Cuando una captura de pantalla incluye datos de tiempo de ejecución volátiles, prefiera entradas de prueba deterministas del lado del servidor a cambios DOM posteriores al renderizado.

GitHub repository URLs in these screenshots use local Git transport rewrites.
The shared Git fixture archive contains the ordinary test data and a separate,
pinned demo revision, so repository discovery shows only demo content. Regenerate
the archive with `scripts/pack-test-data.sh`; update its `DEMO_REVISION`
when intentionally refreshing the demo data. Runtime tests do not fetch GitHub
repositories or resolve their hostname. The `TEST_REVISION` pin controls the
ordinary Git, Mercurial, and Subversion data independently.

Selenium tests that consume the standard demo can opt in with
`@reuse_demo_fixture` from `weblate/trans/tests/selenium_fixtures.py`.
Place it outside other method decorators. It restores committed database rows
and the demo’s working repositories before the test body, so call
`create_component()` before creating additional components as usual. Create
users and other test-specific data inside the test body; restoration replaces
the database. GitHub transports and browser state remain isolated per test.
Keep creation and empty-state tests undecorated so they continue to exercise
the browser forms and generate their screenshots.

```sh
# Copyright © Michal Čihař <michal@weblate.org>
#
# SPDX-License-Identifier: GPL-3.0-or-later

# Simple way to configure test database from environment

# shellcheck shell=sh

# Database server configuration
export CI_DB_USER=weblate
export CI_DB_PASSWORD=weblate
export CI_DB_HOST=127.0.0.1

# Django settings module to use
export DJANGO_SETTINGS_MODULE=weblate.settings_test
```

La única ejecución puede parecer a esto:

```sh
source scripts/test-database.sh
./ci/run-migrate
./ci/run-test
./ci/run-docs
```

## OSS Scanner verification

The development Dockerfile shares its native dependencies and tooling between
the `development` and `scanner` targets. VS Code, agent verification, and
`rundev.sh` select `development` and retain mounted checkouts and
separate Compose services. The final `scanner` target includes the checkout,
locked Python dependencies, compiled assets, and local PostgreSQL and Valkey
for verification without Internet access.

Build it from the repository root and run its offline smoke test:

```sh
docker build -f dev-docker/weblate-dev/Dockerfile -t weblate-oss-scanner .
docker run --rm --init --network none --user 0 --workdir /src --entrypoint bash \
    weblate-oss-scanner .oss-scanner/smoke
```

To run the complete backend suite, replace `.oss-scanner/smoke` with
`.oss-scanner/test`. Append pytest selections or `-n 0` for focused tests.
No host mounts or external service containers are needed. The
`.github/workflows/rundev.yml` workflow runs the focused smoke test on
amd64, alongside the existing development-container checks.

The scanner uses [Modelo de amenazas de Weblate](https://docs.weblate.org/es/latest/security/threat-model.md). The permissive test settings
and local service authentication are test fixtures, not production deployment
defaults.

<a id="local-tests"></a>

## Pruebas locales de Weblate

For an isolated environment with dependencies and test services already
configured, use the [development container](https://docs.weblate.org/es/latest/contributing/start.md#devcontainer). Its CLI can
run the same pytest and lint commands documented below in each Git worktree.

Antes de ejecutar pruebas, asegúrese que estén instaladas las dependencias del desarrollo:

```sh
uv sync --all-extras --dev
```

### Pruebas utilizando pytest

Previo a ejecutar pruebas recogería archivos de estadísticas como algunas pruebas confían en ellas estando presentes:

```sh
DJANGO_SETTINGS_MODULE=weblate.settings_test uv run ./manage.py collectstatic --noinput
```

You can use pytest to run the test suite locally:

```sh
uv run pytest
```

Property-based tests using [hypothesis](https://pypi.org/project/hypothesis/) run as part of the normal pytest
suite. They check Markdown output safety, backup archive member paths, and SSH
URL parsing with bounded generated inputs. Each property runs up to 100
generated examples deterministically, alongside explicit regression examples.
Unexpected exceptions fail the test, and Hypothesis minimizes failing inputs.
Add minimized inputs as explicit regression examples when fixing a failure.
Timing deadlines are disabled to avoid failures caused by CI load.

Ejecutar un archivo de test individual:

```sh
uv run pytest weblate/utils/tests/test_search.py
```

#### HINT
Necesitarás un servidor de base de datos (PostgreSQL) para ser utilizada para pruebas. Por defecto Django crea bases de datos separadas para ejecutar pruebas con el prefijo `test_`, tal que en caso que su ajustes estén configurados para utilizar `weblate`, las pruebas utilizarán la base de datos `test_weblate`. Consulte [Configuración de base de datos para Weblate](https://docs.weblate.org/es/latest/admin/install.md#database-setup) para instrucciones de configuración.

El `weblate/settings_test.py` es utilizado en el entorno CI también (consulte [Integración continua](#ci-tests)) y puede ser ajustado utilizando variables del entorno:

```sh
export CI_DB_USER=weblate
export CI_DB_PASSWORD=weblate
export CI_DB_HOST=127.0.0.1
export CI_DB_PORT=60000
export DJANGO_SETTINGS_MODULE=weblate.settings_test
```

#### HINT
Las pruebas también se pueden ejecutar dentro del contenedor Docker del desarrollador, consulte [Ejecuta Weblate localmente en Docker](https://docs.weblate.org/es/latest/contributing/start.md#dev-docker).

#### SEE ALSO
Consulte [Testing in Django](https://docs.djangoproject.com/es/stable/topics/testing/) para obtener más información sobre como ejecutar y escribir pruebas para Django.

Tests that repeatedly import the same component can inherit from
`ReusableComponentTestCase` or `ReusableViewTestCase` in
`weblate/trans/tests/test_views.py`. These bases build the initial user,
project, component, and translations once per class in `setUpTestData()`.
Override `create_component()` to select a repository fixture or file format,
as with `ComponentTestCase`. For additional shared setup, override the
`build_fixture(cls, builder)` class method, call `super().build_fixture(builder)`,
and use the builder’s repository helpers and model instances.

Each test reloads its model instances and receives a restored copy of the working
repositories, upstream repositories used during construction, and test Git
configuration. Database changes are rolled back by Django. Clients,
authentication, and application caches are initialized per test. Snapshots are
temporary and local to each class and worker; extra components created within a
test still use the normal component factories.

API tests inheriting `APIBaseTest` in `weblate/api/tests.py` use the same
repository restoration. The API user and initial component, including its
automatic glossary, are created once per class. Component construction callbacks
run during this shared setup. API clients, credentials, and subclass setup such
as screenshots and announcements are initialized per test.

Use the existing bases for `TransactionTestCase` and concurrency tests, or when
component construction itself must run under a method-specific settings override.
The reusable bases do not replay component construction signals or commit
callbacks before each test.

# Pruebas locales de módulos de Weblate

Las pruebas se ejecutan utilizando **pytest**. Primero necesitas instalar las dependencias de desarrollo:

```sh
uv sync --all-extras --dev
```

Entonces puede ejecutar la suit de test en el checkout del repositorio:

```sh
uv run pytest
```

<a id="test-data"></a>

# Probar repositorio

Muchas de las pruebas del conjunto de pruebas de Weblate utilizan el repositorio de pruebas. Este repositorio se encuentra en [https://github.com/WeblateOrg/test](https://github.com/WeblateOrg/test). El script `scripts/pack-test-data.sh` se utiliza para generar un archivo tar con un repositorio para cada uno de los sistemas de control de versiones compatibles. Estos se almacenan como `weblate/trans/tests/data/test-base-repo.git.tar`, `weblate/trans/tests/data/test-base-repo.hg.tar` y `weblate/trans/tests/data/test-base-repo.svn.tar` en el repositorio de Weblate.

El repositorio [https://github.com/WeblateOrg/test](https://github.com/WeblateOrg/test) se etiqueta en el momento del lanzamiento, lo que garantiza que las etiquetas de lanzamiento se puedan usar para acceder a los datos de prueba utilizados en el momento del lanzamiento. El script intenta crear archivos tar lo más reproducibles posible.
