diff --git a/docs/basic-guides/configuration.mdx b/docs/basic-guides/configuration.mdx new file mode 100644 index 0000000..a0ac827 --- /dev/null +++ b/docs/basic-guides/configuration.mdx @@ -0,0 +1,405 @@ +import Admonition from "@theme/Admonition"; + +# Configuration + + + +- Where Testplane looks for the configuration file +- How to override settings without modifying the configuration file +- How settings inheritance works +- How to configure parallel test execution and timeouts +- How to connect plugins + + + +## Introduction + +Testplane is configured in three ways: through a configuration file, environment variables, and command-line arguments. + +The configuration file is the primary source of settings: it specifies browsers, test paths, parallelism, plugins, and timeouts. Environment variables and CLI arguments allow you to override individual parameters without modifying the file, which is convenient for CI/CD or local experiments. + +For a complete reference of parameters, see the [configuration documentation](../reference/config/main.mdx). + +## Configuration file {#config-location} + +When launched, Testplane looks for a configuration file in the current working directory. The following file names are supported (in order of priority): + +- `.testplane.conf.ts` +- `.testplane.conf.js` +- `testplane.config.ts` +- `testplane.config.js` +- `testplane.config.cts` +- `testplane.config.cjs` + +If you need to use a config from a different location, specify the path using the `--config` option: + +```bash +npx testplane --config ./configs/testplane.local.ts +``` + +## Setting parameters {#config-sources} + +Testplane configuration parameters can be set in three ways: + +1. Configuration file: the primary method, suitable for most settings +2. Environment variables: convenient for CI/CD and sensitive data +3. CLI arguments: for quick overrides at runtime + +### Overriding via environment variables {#env-override} + +Any configuration parameter can be overridden via environment variables. The variable name is formed from the parameter name in the config: + +1. Replace `camelCase` with `snake_case` (e.g., `baseUrl` → `base_url`) +2. For nested parameters, join all levels with `_` +3. Add the `testplane_` prefix + +```bash +# gridUrl in config → testplane_grid_url +testplane_grid_url=local npx testplane + +# browsers.firefox.headless in config → testplane_browsers_firefox_headless +testplane_browsers_firefox_headless=false npx testplane +``` + +### Overriding via CLI {#cli-override} + +Parameters can also be overridden via CLI arguments: + +1. Replace `camelCase` with `kebab-case` (e.g., `baseUrl` → `base-url`) +2. For nested parameters, join all levels with hyphens +3. Add `--` at the beginning + +```bash +# gridUrl in config → --grid-url in CLI +npx testplane --grid-url local + +# browsers.firefox.headless in config → --browsers-firefox-headless in CLI +npx testplane --browsers-firefox-headless false +``` + +### Parameter priority {#priority} + +When values conflict, the following priority applies (from highest to lowest): + +| Priority | Source | Example | +| -------- | -------------------- | --------------------------------------- | +| 1 | CLI argument | `--base-url http://example.com` | +| 2 | Environment variable | `testplane_base_url=http://example.com` | +| 3 | Configuration file | `baseUrl: "http://example.com"` | +| 4 | Default value | — | + +## Parameter inheritance {#inheritance} + +Testplane supports cascading parameter inheritance: settings defined at the root level of the config apply to all browsers. Browsers can override these values. + +### Inheritance example {#inheritance-example} + +```typescript title="testplane.config.ts" +import type { ConfigInput } from "testplane"; + +export default { + // Root settings — apply to all browsers + baseUrl: "http://localhost:3000", + retry: 2, + sessionsPerBrowser: 3, + browsers: { + chrome: { + // Inherits retry: 2 and sessionsPerBrowser: 3 + desiredCapabilities: { + browserName: "chrome", + }, + }, + firefox: { + // Overrides retry, inherits sessionsPerBrowser: 3 + retry: 5, + desiredCapabilities: { + browserName: "firefox", + }, + }, + }, + // ... +} satisfies ConfigInput; +``` + +In this example: + +- Chrome will get `retry: 2` and `sessionsPerBrowser: 3` (inheritance) +- Firefox will get `retry: 5` (override) and `sessionsPerBrowser: 3` (inheritance) + + + The only parameter that cannot be moved to the root level is `desiredCapabilities`. It must be + defined for each browser separately. + + +## Basic parameters {#basic-params} + +### Retries (retry) {#retry} + +The [`retry`](../reference/config/browsers.mdx#retry) parameter determines how many times Testplane will restart a failed test. + +```typescript title="testplane.config.ts" +import type { ConfigInput } from "testplane"; + +export default { + // Global value for all browsers + retry: 2, + browsers: { + chrome: { + // Can be increased for an unstable browser + retry: 5, + desiredCapabilities: { browserName: "chrome" }, + }, + }, + // ... +} satisfies ConfigInput; +``` + +### Test file locations {#test-files} + +Test file sets and browsers for running them are specified in the `sets` section: + +```typescript title="testplane.config.ts" +import type { ConfigInput } from "testplane"; + +export default { + sets: { + desktop: { + // Paths to tests + files: ["tests/desktop/**/*.test.ts"], + browsers: ["chrome", "firefox"], + }, + mobile: { + files: ["tests/mobile/**/*.test.ts"], + // Files can be excluded + ignoreFiles: ["tests/mobile/**/*.skip.ts"], + browsers: ["iphone", "android"], + }, + }, + // ... +} satisfies ConfigInput; +``` + +Running a specific set: + +```bash +npx testplane --set desktop +``` + +For more details about sets, see the [sets documentation](../reference/config/sets.mdx). + +### Dev Server {#dev-server} + +The `devServer` section allows you to automatically start a development server before tests: + +```typescript title="testplane.config.ts" +import type { ConfigInput } from "testplane"; + +const SERVER_PORT = 3000; + +export default { + devServer: { + command: "npm run dev", + env: { PORT: SERVER_PORT }, + reuseExisting: true, + readinessProbe: { + url: `http://localhost:${SERVER_PORT}/health`, + }, + }, + baseUrl: "http://localhost:3000", + // ... +} satisfies ConfigInput; +``` + +Testplane will run the command and wait for the server to be ready at the specified URL. + + + The `devServer` section only starts the server. Don't forget to also configure `baseUrl`. + + + + When using `reuseExisting: true`, be sure to specify `readinessProbe.url`: Testplane will check + if the server is running and won't start a new one. + + +For more details, see the [devServer documentation](../reference/config/dev-server.mdx). + +### Execution parallelism {#parallelism} + +Testplane runs tests in parallel, which significantly speeds up the test run. Two main parameters are used to configure parallelism: `sessionsPerBrowser` and `workers`. + +- `sessionsPerBrowser` determines the maximum number of parallel browser sessions for each browser +- `workers` determines the number of Node.js worker processes for parallel test execution + +```typescript title="testplane.config.ts" +import type { ConfigInput } from "testplane"; + +export default { + browsers: { + chrome: { + sessionsPerBrowser: 5, + desiredCapabilities: { + browserName: "chrome", + }, + }, + firefox: { + sessionsPerBrowser: 3, + desiredCapabilities: { + browserName: "firefox", + }, + }, + }, + system: { + workers: 4, + }, + // ... +} satisfies ConfigInput; +``` + +In this example, Testplane can run up to 5 parallel Chrome sessions and up to 3 Firefox sessions, distributing tests among 4 worker processes. + +## Timeouts {#timeouts} + +Testplane allows you to configure timeouts to control operation execution time: + +- `httpTimeout` — timeout for HTTP requests to WebDriver +- `testTimeout` — maximum execution time for a single test +- `pageLoadTimeout` — page load timeout in the browser +- `waitTimeout` — timeout for wait commands (`waitFor*`) + +```typescript title="testplane.config.ts" +import type { ConfigInput } from "testplane"; + +export default { + // Global timeouts + pageLoadTimeout: 20000, + httpTimeout: 20000, + testTimeout: 90000, + browsers: { + chrome: { + // Timeouts can be overridden for a specific browser + pageLoadTimeout: 30000, + waitTimeout: 5000, + desiredCapabilities: { browserName: "chrome" }, + }, + }, + // ... +} satisfies ConfigInput; +``` + +For a complete list of timeouts and their descriptions, see the [documentation](../reference/config/browsers.mdx#timeouts). + +## Connecting plugins {#plugins} + +Plugins are connected and configured in the `plugins` section of the configuration file. Each key is the npm package name of the plugin, and the value is an object with its parameters. + +### Example with html-reporter {#html-reporter-example} + +[html-reporter](../html-reporter/html-reporter-setup.mdx) is a plugin for generating HTML test reports. + +**Installation:** + +```bash +npm install html-reporter --save-dev +``` + +**Connection:** + +```typescript title="testplane.config.ts" +import type { ConfigInput } from "testplane"; + +export default { + plugins: { + "html-reporter/testplane": { + enabled: true, + path: "testplane-report", + defaultView: "all", + diffMode: "3-up-scaled", + }, + }, + // ... +} satisfies ConfigInput; +``` + +Plugin parameters can be overridden via environment variables: + +```bash +# Disable the plugin +html_reporter_enabled=false npx testplane + +# Change the report path +html_reporter_path=./custom-report npx testplane +``` + +Similarly, parameters can be passed via command line: + +```bash +# Change the report path +npx testplane --html-reporter-path=./custom-report + +# Change the diff display mode +npx testplane --html-reporter-diff_mode=only-diff +``` + +If a parameter is specified in multiple places, the value with the highest priority is applied: + +1. CLI — highest priority +2. Environment variables +3. Configuration file — lowest priority + +This allows flexible control of plugin behavior in CI/CD without modifying the config. + +## Setting defaults for commands {#command-defaults} + +Testplane allows you to set default values for parameters of certain commands. Instead of passing the same options with each call, you can specify them once in the configuration. + +### assertViewOpts {#assert-view-opts} + +Default settings for screenshot testing. Allows you to specify which elements to ignore, acceptable pixel difference, delay before capture, and other screenshot comparison parameters. + +```typescript +export default { + assertViewOpts: { + ignoreElements: [".ads", ".dynamic-banner"], + ignoreDiffPixelCount: "0.5%", + }, + // ... +}; +``` + +For a complete list of parameters, see the [assertView](../commands/browser/assertView.mdx) documentation. + +### expectOpts {#expect-opts} + +Settings for asynchronous assertions with waiting. + +```typescript +export default { + system: { + expectOpts: { + wait: 5000, // max wait time (ms) + interval: 200, // check interval (ms) + }, + }, + // ... +}; +``` + +For a complete list of parameters, see the [expect matchers](../commands/expect/overview.mdx) documentation. + +### stateOpts {#state-opts} + +Settings for browser state save and restore commands. Defines what to save (cookies, localStorage, sessionStorage), where to save, and whether to delete the file after tests. + +```typescript +export default { + stateOpts: { + path: "./tmp/auth-state.json", + cookies: true, + localStorage: true, + sessionStorage: false, + }, + // ... +}; +``` + +For a complete list of parameters, see the [saveState](../commands/browser/saveState.mdx) and [restoreState](../commands/browser/restoreState.mdx) documentation. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/basic-guides/configuration.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/basic-guides/configuration.mdx new file mode 100644 index 0000000..51c7307 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/basic-guides/configuration.mdx @@ -0,0 +1,405 @@ +import Admonition from "@theme/Admonition"; + +# Конфигурация + + + +- Где Testplane ищет конфигурационный файл +- Как переопределить настройки без изменения конфигурационного файла +- Как работает наследование настроек +- Как настроить параллельный запуск тестов и тайм-ауты +- Как подключить плагины + + + +## Введение + +Testplane настраивается тремя способами: через конфигурационный файл, переменные окружения и аргументы командной строки. + +Конфигурационный файл — основной источник настроек: в нём указывают браузеры, пути к тестам, параллельность, плагины и тайм-ауты. Переменные окружения и CLI-аргументы позволяют переопределить отдельные параметры без изменения файла, это удобно для CI/CD или локальных экспериментов. + +Полный справочник параметров см. в [документации по конфигурации](../reference/config/main.mdx). + +## Конфигурационный файл {#config-location} + +При запуске Testplane ищет конфигурационный файл в текущей рабочей директории. Поддерживаются следующие имена файлов (в порядке приоритета): + +- `.testplane.conf.ts` +- `.testplane.conf.js` +- `testplane.config.ts` +- `testplane.config.js` +- `testplane.config.cts` +- `testplane.config.cjs` + +Если нужно использовать конфиг из другого места, укажите путь через опцию `--config`: + +```bash +npx testplane --config ./configs/testplane.local.ts +``` + +## Способы задания параметров {#config-sources} + +Параметры конфигурации Testplane можно задавать тремя способами: + +1. Файл конфигурации: основной способ, подходит для большинства настроек +2. Переменные окружения: удобно для CI/CD и чувствительных данных +3. Аргументы CLI: для быстрого переопределения при запуске + +### Переопределение через переменные окружения {#env-override} + +Любой параметр конфигурации можно переопределить через переменные окружения. Имя переменной формируется из имени параметра в конфиге: + +1. Замените `camelCase` на `snake_case` (например, `baseUrl` → `base_url`) +2. Для вложенных параметров соедините все уровни через `_` +3. Добавьте префикс `testplane_` + +```bash +# gridUrl в конфиге → testplane_grid_url +testplane_grid_url=local npx testplane + +# browsers.firefox.headless в конфиге → testplane_browsers_firefox_headless +testplane_browsers_firefox_headless=false npx testplane +``` + +### Переопределение через CLI {#cli-override} + +Параметры также можно переопределить через CLI-аргумент: + +1. Замените `camelCase` на `kebab-case` (например, `baseUrl` → `base-url`) +2. Для вложенных параметров соедините все уровни через дефис +3. Добавьте `--` в начале + +```bash +# gridUrl в конфиге → --grid-url в CLI +npx testplane --grid-url local + +# browsers.firefox.headless в конфиге → --browsers-firefox-headless в CLI +npx testplane --browsers-firefox-headless false +``` + +### Приоритет параметров {#priority} + +При конфликте значений применяется следующий приоритет (от высшего к низшему): + +| Приоритет | Источник | Пример | +| --------- | --------------------- | --------------------------------------- | +| 1 | CLI аргумент | `--base-url http://example.com` | +| 2 | Переменная окружения | `testplane_base_url=http://example.com` | +| 3 | Файл конфигурации | `baseUrl: "http://example.com"` | +| 4 | Значение по умолчанию | — | + +## Наследование параметров {#inheritance} + +Testplane поддерживает каскадное наследование параметров: настройки, заданные на корневом уровне конфига, применяются ко всем браузерам. Браузеры могут переопределять эти значения. + +### Пример наследования {#inheritance-example} + +```typescript title="testplane.config.ts" +import type { ConfigInput } from "testplane"; + +export default { + // Корневые настройки — применяются ко всем браузерам + baseUrl: "http://localhost:3000", + retry: 2, + sessionsPerBrowser: 3, + browsers: { + chrome: { + // Наследует retry: 2 и sessionsPerBrowser: 3 + desiredCapabilities: { + browserName: "chrome", + }, + }, + firefox: { + // Переопределяет retry, наследует sessionsPerBrowser: 3 + retry: 5, + desiredCapabilities: { + browserName: "firefox", + }, + }, + }, + // ... +} satisfies ConfigInput; +``` + +В этом примере: + +- Chrome получит `retry: 2` и `sessionsPerBrowser: 3` (наследование) +- Firefox получит `retry: 5` (переопределение) и `sessionsPerBrowser: 3` (наследование) + + + Единственный параметр, который нельзя вынести на корневой уровень — это `desiredCapabilities`. + Он должен быть задан для каждого браузера отдельно. + + +## Базовые параметры {#basic-params} + +### Ретраи (retry) {#retry} + +Параметр [`retry`](../reference/config/browsers.mdx#retry) определяет, сколько раз Testplane будет перезапускать упавший тест. + +```typescript title="testplane.config.ts" +import type { ConfigInput } from "testplane"; + +export default { + // Глобальное значение для всех браузеров + retry: 2, + browsers: { + chrome: { + // Для нестабильного браузера можно увеличить + retry: 5, + desiredCapabilities: { browserName: "chrome" }, + }, + }, + // ... +} satisfies ConfigInput; +``` + +### Расположение тестовых файлов {#test-files} + +Наборы тестовых файлов и браузеры для их запуска указываются в секции `sets`: + +```typescript title="testplane.config.ts" +import type { ConfigInput } from "testplane"; + +export default { + sets: { + desktop: { + // Пути к тестам + files: ["tests/desktop/**/*.test.ts"], + browsers: ["chrome", "firefox"], + }, + mobile: { + files: ["tests/mobile/**/*.test.ts"], + // Можно исключить файлы + ignoreFiles: ["tests/mobile/**/*.skip.ts"], + browsers: ["iphone", "android"], + }, + }, + // ... +} satisfies ConfigInput; +``` + +Запуск конкретного сета: + +```bash +npx testplane --set desktop +``` + +Подробнее о сетах см. в [документации по sets](../reference/config/sets.mdx). + +### Dev Server {#dev-server} + +Секция `devServer` позволяет автоматически запускать сервер разработки перед тестами: + +```typescript title="testplane.config.ts" +import type { ConfigInput } from "testplane"; + +const SERVER_PORT = 3000; + +export default { + devServer: { + command: "npm run dev", + env: { PORT: SERVER_PORT }, + reuseExisting: true, + readinessProbe: { + url: `http://localhost:${SERVER_PORT}/health`, + }, + }, + baseUrl: "http://localhost:3000", + // ... +} satisfies ConfigInput; +``` + +Testplane запустит команду и дождётся готовности сервера по указанному URL. + + + Секция `devServer` только запускает сервер. Не забудьте также настроить `baseUrl`. + + + + При использовании `reuseExisting: true` обязательно укажите `readinessProbe.url`: Testplane + проверит, запущен ли сервер, и не будет запускать новый. + + +Подробнее см. в [документации по devServer](../reference/config/dev-server.mdx). + +### Параллельность выполнения {#parallelism} + +Testplane запускает тесты параллельно, что значительно ускоряет прогон. Для настройки параллельности используются два основных параметра: `sessionsPerBrowser` и `workers`. + +- `sessionsPerBrowser` определяет максимальное число параллельных браузерных сессий для каждого браузера +- `workers` определяет число воркер-процессов Node.js для параллельного выполнения тестов + +```typescript title="testplane.config.ts" +import type { ConfigInput } from "testplane"; + +export default { + browsers: { + chrome: { + sessionsPerBrowser: 5, + desiredCapabilities: { + browserName: "chrome", + }, + }, + firefox: { + sessionsPerBrowser: 3, + desiredCapabilities: { + browserName: "firefox", + }, + }, + }, + system: { + workers: 4, + }, + // ... +} satisfies ConfigInput; +``` + +В этом примере Testplane может запустить до 5 параллельных сессий Chrome и до 3 сессий Firefox, распределяя тесты между 4 воркер-процессами. + +## Тайм-ауты {#timeouts} + +Testplane позволяет настроить тайм-ауты для для контроля времени выполнения операций: + +- `httpTimeout` — тайм-аут HTTP-запросов к WebDriver +- `testTimeout` — максимальное время выполнения одного теста +- `pageLoadTimeout` — тайм-аут загрузки страницы в браузере +- `waitTimeout` — тайм-аут для команд ожидания (`waitFor*`) + +```typescript title="testplane.config.ts" +import type { ConfigInput } from "testplane"; + +export default { + // Глобальные тайм-ауты + pageLoadTimeout: 20000, + httpTimeout: 20000, + testTimeout: 90000, + browsers: { + chrome: { + // Тайм-ауты можно переопределить для конкретного браузера + pageLoadTimeout: 30000, + waitTimeout: 5000, + desiredCapabilities: { browserName: "chrome" }, + }, + }, + // ... +} satisfies ConfigInput; +``` + +Полный список тайм-аутов и их описание см. в [документации](../reference/config/browsers.mdx#timeouts). + +## Подключение плагинов {#plugins} + +Плагины подключаются и настраиваются в секции `plugins` в конфигурационном файле. Каждый ключ — это имя npm-пакета плагина, а значение — объект с его параметрами. + +### Пример с html-reporter {#html-reporter-example} + +[html-reporter](../html-reporter/html-reporter-setup.mdx) — плагин для генерации HTML-отчётов о тестах. + +**Установка:** + +```bash +npm install html-reporter --save-dev +``` + +**Подключение:** + +```typescript title="testplane.config.ts" +import type { ConfigInput } from "testplane"; + +export default { + plugins: { + "html-reporter/testplane": { + enabled: true, + path: "testplane-report", + defaultView: "all", + diffMode: "3-up-scaled", + }, + }, + // ... +} satisfies ConfigInput; +``` + +Параметры плагина можно переопределить через переменные окружения: + +```bash +# Отключить плагин +html_reporter_enabled=false npx testplane + +# Изменить путь к отчёту +html_reporter_path=./custom-report npx testplane +``` + +Аналогично можно передать параметры через командную строку: + +```bash +# Изменить путь к отчёту +npx testplane --html-reporter-path=./custom-report + +# Изменить режим отображения diff +npx testplane --html-reporter-diff_mode=only-diff +``` + +Если параметр указан в нескольких местах, применяется значение с наивысшим приоритетом: + +1. CLI — высший приоритет +2. Переменные окружения +3. Конфигурационный файл — низший приоритет + +Это позволяет гибко управлять поведением плагинов в CI/CD без изменения конфига. + +## Настройка дефолтов для команд {#command-defaults} + +Testplane позволяет задать значения по умолчанию для параметров некоторых команд. Вместо того чтобы передавать одни и те же опции при каждом вызове, можно указать их один раз в конфигурации. + +### assertViewOpts {#assert-view-opts} + +Настройки по умолчанию для скриншотного тестирования. Позволяют задать, какие элементы игнорировать, допустимую разницу в пикселях, задержку перед снимком и другие параметры сравнения скриншотов. + +```typescript +export default { + assertViewOpts: { + ignoreElements: [".ads", ".dynamic-banner"], + ignoreDiffPixelCount: "0.5%", + }, + // ... +}; +``` + +Полный список параметров см. в документации [assertView](../commands/browser/assertView.mdx). + +### expectOpts {#expect-opts} + +Настройки для асинхронных проверок с ожиданием. + +```typescript +export default { + system: { + expectOpts: { + wait: 5000, // макс. время ожидания (мс) + interval: 200, // интервал проверок (мс) + }, + }, + // ... +}; +``` + +Полный список параметров см. в документации по [expect-матчерам](../commands/expect/overview.mdx). + +### stateOpts {#state-opts} + +Настройки для команд сохранения и восстановления состояния браузера. Определяют, что сохранять (cookies, localStorage, sessionStorage), куда сохранять, и нужно ли удалять файл после тестов. + +```typescript +export default { + stateOpts: { + path: "./tmp/auth-state.json", + cookies: true, + localStorage: true, + sessionStorage: false, + }, + // ... +}; +``` + +Полный список параметров см. в документации по [saveState](../commands/browser/saveState.mdx) и [restoreState](../commands/browser/restoreState.mdx).