Комплекс тестування Weblate і неперервна інтеграція¶
Комплекси тестування існують для більшої частини поточного коду. Збільште покриття додаванням тестувань для будь-яких нових функціональних можливостей і перевірте, чи працює тестування.
Неперервна інтеграція¶
Weblate покладається на GitHub Actions для запуску тестів, створення документації, лінтування коду та інших завдань, що забезпечують якість коду.
Codecov збирає інформацію про покриття коду з проведених тестів.
Передбачено декілька завдань для перевірки різних аспектів:
Модульні та функціональні тести з використанням pytest.
Збірка документації та зовнішні посилання за допомогою Sphinx.
Сканування безпеки коду за допомогою CodeQL.
Для тестування візуальних змін використовується Argos CI.
Code formatting using prek, a faster third-party reimplementation of the pre-commit framework.
Тестування перенесення для всіх підтримуваних випусків
Package builds, metadata, manifest, archive-content, and installation checks. The package lint tools are pinned in
pyproject.tomland resolved inuv.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 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.
Налаштування для системи неперервної інтеграції зберігаються у каталозі .github/workflows. Система неперервної інтеграції значною частиною використовує допоміжні скрипти, які зберігаються у каталозі ci. Ці скрипти може бути виконано вручну, але для їхньої роботи потрібні декілька змінних середовища, які, здебільшого, визначають файл параметрів Django, яким слід скористатися, та тестування з’єднання із базою даних. Приклад визначення цих змінних можна знайти у файлі scripts/test-database.sh:
The Selenium screenshot tests in weblate/trans/tests/test_selenium.py
serve two purposes. They generate images for visual change testing in CI, and
the same images are converted into documentation screenshots by
make -C docs update-screenshots. Keep screenshot fixtures close to
real rendered pages so CI catches UI regressions. When a screenshot includes
volatile runtime data, prefer deterministic server-side test inputs over
post-render DOM changes.
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.
# 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
Просте виконання може виглядати так:
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:
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 Модель загрози Weblate. The permissive test settings and local service authentication are test fixtures, not production deployment defaults.
Локальне тестування Weblate¶
For an isolated environment with dependencies and test services already configured, use the development container. Its CLI can run the same pytest and lint commands documented below in each Git worktree.
Before running tests, please ensure development dependencies are installed:
uv sync --all-extras --dev
Тестування за допомогою pytest¶
Перш ніж запускати тести, вам слід зібрати статичні файли, оскільки робота деяких тестів залежить від наявності цих файлів:
DJANGO_SETTINGS_MODULE=weblate.settings_test uv run ./manage.py collectstatic --noinput
You can use pytest to run the test suite locally:
uv run pytest
Property-based tests using 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.
Запуск індивідуального тестового файлу:
uv run pytest weblate/utils/tests/test_search.py
Підказка
Для тестів вам знадобиться сервер бази даних (PostgreSQL). Типово, Django створює окрему базу даних для запуску тестів. У назві цієї бази даних міститься префікс test_. Отже, якщо параметри налаштовано на використання weblate, для тестування буде використано базу даних test_weblate. Див. Налаштування бази даних для Weblate, щоб дізнатися більше про налаштовування.
Файл weblate/settings_test.py також використовується у середовищі неперервної інтеграції (див. Неперервна інтеграція). Його роботу можна скоригувати за допомогою змінних середовища:
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
Підказка
Тести також можна запускати у межах контейнера docker розробника, див. Запуск Weblate локально у Docker.
Дивись також
Див. Testing in Django, щоб дізнатися більше про запуск і написання тестів для 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.
Локальне тестування модулів Weblate¶
The tests are executed using pytest. First you need to install development dependencies:
uv sync --all-extras --dev
Далі, ви можете виконати комплекс перевірок для локальної копії сховища:
uv run pytest
Тестовий репозиторій¶
Багато тестів у наборі тестів Weblate використовують репозиторій тестів. Репозиторій набору тестів знаходиться за адресою https://github.com/WeblateOrg/test. Скрипт scripts/pack-test-data.sh потім використовується для створення tar-архіву з репозиторієм для кожної з підтримуваних систем контролю версій. Вони зберігаються як weblate/trans/tests/data/test-base-repo.git.tar, weblate/trans/tests/data/test-base-repo.hg.tar, і weblate/trans/tests/data/test-base-repo.svn.tar у репозиторії Weblate.
Репозиторій https://github.com/WeblateOrg/test позначається тегами на момент випуску, що гарантує можливість використання тегів випуску для доступу до тестових даних, які використовувалися на момент випуску. Скрипт намагається створити якомога більше відтворюваних архівів.