diff --git a/docs/_partials/html-reporter-config-examples.mdx b/docs/_partials/html-reporter-config-examples.mdx new file mode 100644 index 0000000..2b48b5d --- /dev/null +++ b/docs/_partials/html-reporter-config-examples.mdx @@ -0,0 +1,48 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + + + + ```javascript title="testplane.config.ts" + export = { + // ... + plugins: { + 'html-reporter/testplane': { + enabled: true, + path: 'html-report', + }, + }, + }; + ``` + + + + ```javascript title="playwright.config.ts" + // playwright.config.ts + export default defineConfig({ + // ... + reporter: [ + ['html-reporter/playwright', { + enabled: true, + defaultView: 'failed', + path: 'html-report', + }], + ], + }); + ``` + + + + ```javascript title="jest.config.ts" + const config = { + // ... + reporters: [ + ['html-reporter/jest', { + path: 'html-report', + }] + ], + }; + ``` + + + diff --git a/docs/html-reporter/html-reporter-api.mdx b/docs/html-reporter/html-reporter-api.mdx index a7ebea6..d73d176 100644 --- a/docs/html-reporter/html-reporter-api.mdx +++ b/docs/html-reporter/html-reporter-api.mdx @@ -1,4 +1,8 @@ -# Html-Reporter API +--- +sidebar_class_name: hidden +--- + +# HTML Reporter Object ## Overview {#overview} diff --git a/docs/html-reporter/html-reporter-commands.mdx b/docs/html-reporter/html-reporter-commands.mdx index 03c1302..d8a3f6b 100644 --- a/docs/html-reporter/html-reporter-commands.mdx +++ b/docs/html-reporter/html-reporter-commands.mdx @@ -1,15 +1,25 @@ -# Html-Reporter Commands +import Admonition from "@theme/Admonition"; + +# CLI ## Overview {#overview} -The `html-reporter` plugin adds the following commands to Testplane: +HTML Reporter has the following commands: - [gui](#gui)—to run Testplane in GUI mode; +- [merge-reports](#merge-reports)—to merge multiple reports into one. - [remove-unused-screens](#remove-unused-screens)—to remove reference screenshots that are not used in tests; -- [merge-reports](#merge-reports)—to merge Testplane's separate reports into one general report. + +When using HTML Reporter with Testplane, you can also use commands through Testplane, for example: `npx testplane gui`. + +When using with other tools, you need to specify the tool name in the tool argument, for example: `npx html-reporter gui --tool playwright`. ## gui + + This command is only available when using HTML Reporter with Testplane and Playwright. + + Use the `gui` command to launch Testplane in GUI mode. GUI mode allows you to: @@ -22,11 +32,50 @@ GUI mode allows you to: ### Usage {#gui_usage} ```bash -npx testplane gui +npx html-reporter gui +``` + +## merge-reports + + + This command is only available when using HTML Reporter with Testplane and Playwright. + + +Use the `merge-reports` command to merge multiple reports into one. + +The command accepts paths to report directories, database files, or `databaseUrls.json` files. + +It creates a new html-report in the destination folder with data from all passed reports. + +- When merging local reports—all data, including SQLite databases and screenshots, are copied to the destination directory. +- When merging reports by link (for example, if `databaseUrls.json` files with links to reports in S3 are passed as input)—a report with links to the original reports in `databaseUrls.json` will be created in the destination directory, without downloading and copying all nested resources. When working with the report, this will not be noticeable, but you need to keep in mind that the original reports must remain accessible, as the merged report gets data from them. + +### Usage {#merge_reports_usage} + +The `merge-reports` command supports the following required option: + + + + + + + + + +
**Option****Description**
-d, --destination <folder>The path to the folder where you want to save the final report.
+ +Usage example: + +```bash +npx html-reporter merge-reports report-dir/ path-to-database.db path-to-databaseUrls.json -d dest-report ``` ## remove-unused-screens + + This command is only available when using HTML Reporter with Testplane. + + Use the `remove-unused-screens` command to remove the reference screenshots that are not used in tests. ### How does it work? @@ -82,29 +131,3 @@ Getting the reference information about the command: ```bash npx testplane remove-unused-screens --help ``` - -## merge-reports - -Use the `merge-reports` command to merge Testplane's separate reports into one general report. - -The command accepts paths to database files or to `databaseUrls.json` files from other html-reports. It creates a new html-report in the destination folder with a single file `databaseUrls.json`, which will contain a link to the database file or to the files `databaseUrls.json` from the input parameters. Database files are not copied to the destination folder at the same time. - -### Usage {#merge_reports_usage} - -The `merge-reports` command supports the following required option: - - - - - - - - - -
**Option****Description**
-d, --destination <folder>The path to the folder where you want to save the final report.
- -Usage example: - -```bash -npx testplane merge-reports path-to-database.db path-to-databaseUrls.json -d dest-report -``` diff --git a/docs/html-reporter/html-reporter-custom-gui.mdx b/docs/html-reporter/html-reporter-custom-gui.mdx index 7433bdd..4225084 100644 --- a/docs/html-reporter/html-reporter-custom-gui.mdx +++ b/docs/html-reporter/html-reporter-custom-gui.mdx @@ -1,3 +1,7 @@ +--- +sidebar_class_name: hidden +--- + import Admonition from "@theme/Admonition"; # Html-Reporter Customizing GUI diff --git a/docs/html-reporter/html-reporter-events.mdx b/docs/html-reporter/html-reporter-events.mdx index 7b8c4d1..3494cb4 100644 --- a/docs/html-reporter/html-reporter-events.mdx +++ b/docs/html-reporter/html-reporter-events.mdx @@ -1,4 +1,8 @@ -# Html-Reporter Events +--- +sidebar_class_name: hidden +--- + +# HTML Reporter Events ## Overview {#overview} diff --git a/docs/html-reporter/html-reporter-plugins.mdx b/docs/html-reporter/html-reporter-plugins.mdx index 234a1b6..c731011 100644 --- a/docs/html-reporter/html-reporter-plugins.mdx +++ b/docs/html-reporter/html-reporter-plugins.mdx @@ -1,4 +1,4 @@ -# Html-Reporter Plugins +# HTML Reporter Plugins ## Overview {#overview} diff --git a/docs/html-reporter/html-reporter-setup.mdx b/docs/html-reporter/html-reporter-setup.mdx index 64ba6fd..7c2d4af 100644 --- a/docs/html-reporter/html-reporter-setup.mdx +++ b/docs/html-reporter/html-reporter-setup.mdx @@ -1,5 +1,5 @@ --- -sidebar_class_name: hidden +sidebar_position: 2 --- import Tabs from "@theme/Tabs"; @@ -7,139 +7,80 @@ import TabItem from "@theme/TabItem"; import Admonition from "@theme/Admonition"; -# Html-Reporter Setup +# Configuration -## Overview {#overview} - -Use the [html-reporter][html-reporter] plugin to get an html-report on the tests run. - -![HTML Report](/img/docs/html-reporter/html-reporter.overview.png) - - - For the html-reporter plugin to work correctly, [hermione][testplane] version 4 and higher is - required. - - -The plugin saves the tests run results to the [SQLite][sqlite] database. Therefore, you will not be able to open the local report as a file using the `file://` protocol. - -To view the report, run Testplane in GUI mode: - -```bash -npx testplane gui -``` - -Or run [http-server][http-server] in the report folder: - -```bash -npx http-server -p 8000 -``` - -If you are starting a local server not from the folder with the report, then specify the path to the report: - -```bash -npx http-server ./testplane-report -p 8000 -``` - -Then open the page `http://localhost:8000` in the browser. - -## Install {#install} - -```bash -npm install -D html-reporter -``` - -## Setup {#setup} - -Add the plugin to the `plugins` section of the Testplane config: +## Config Examples {#setup} - -```javascript - module.exports = { + + ```javascript title="testplane.config.ts" + export = { + // ... plugins: { 'html-reporter/testplane': { - enabled: true + enabled: true, + path: 'html-report', }, - - // other Testplane plugins... }, - - // other Testplane settings... }; ``` - -```javascript - module.exports = { - plugins: { - 'html-reporter/testplane': { + + ```javascript title="playwright.config.ts" + // playwright.config.ts + export default defineConfig({ + // ... + reporter: [ + ['html-reporter/playwright', { enabled: true, - path: 'my/testplane-reports', - defaultView: 'all', - baseHost: 'test.com', - errorPatterns: [ - 'Parameter .* must be a string', - { - name: 'Cannot read property of undefined', - pattern: 'Cannot read property .* of undefined', - hint: '
google it, i dont know how to fix it =(
' - } - ], - customScripts: [ - function() { - // custom script - }, - - // other scripts... - ], - customGui: { - // DEPRECATED - // additional controls for GUI mode - // use report plugins instead of customGui - }, - pluginsEnabled: true, - plugins: [ - // report plugins... - ], - yandexMetrika: { - counter: 1234567 - } - }, + defaultView: 'failed', + path: 'html-report', + }], + ], + }); + ``` - // other Testplane plugins... - }, +
- // other Testplane settings... + + ```javascript title="jest.config.ts" + const config = { + // ... + reporters: [ + ['html-reporter/jest', { + path: 'html-report', + }] + ], }; ``` -
-### Description of configuration parameters {#setup_description} +## Configuration Reference {#setup_description} - - - - - - - - - - - - - - + + + + + + + + + + + + + + +
**Parameter****Type****Default value****Description**
[enabled](#enabled)BooleantrueEnable / disable the plugin.
[path](#path)String"testplane-report"The path to the folder for saving html-report files.
[saveErrorDetails](#saveerrordetails)BooleanfalseSave / do not save error details in json files.
[defaultView](#defaultview)String"all"The test filtering mode when displayed, which will be set by default.
[diffMode](#diffmode)String"3-up"The mode of viewing diffs, which will be set by default.
[baseHost](#basehost)String_N/A_Replaces the original host address for viewing in the browser.
[errorPatterns](#errorpatterns)Object[] or String[][ ]Error patterns with hints to improve the UX of the report.
[metaInfoBaseUrls](#metainfobaseurls)Object`{ }`Base URLs for generating links in the _Meta_ section based on meta information about the tests run.
[saveFormat](#saveformat)String"sqlite"DEPRECATED. Allows you to set the format in which the results of the tests run will be saved.
[customGui](#customgui)Object`{ }`DEPRECATED. Use [plugins](#plugins) instead. Description of custom controls for GUI mode.
[pluginsEnabled](#pluginsenabled)BooleanfalseEnable plugins for the report.
[plugins](#plugins)Object[][ ]A list of plugins with their settings.
[customScripts](#customscripts)Function[][ ]A list of functions that implement custom scripts. For example, Yandex.Metrika scripts or a Bug.
[yandexMetrika](#yandexmetrika)Object`{ }`[Yandex.Metrika][yandex-metrika].
[enabled](#enabled)`boolean``true`Enable / disable the plugin.
[path](#path)`string``"testplane-report"`The path to the folder for saving html-report files.
[saveErrorDetails](#saveerrordetails)`boolean``false`Save / do not save error details in json files.
[uiMode](#uimode)`string``null`Default UI mode: "old" for classic interface, "new" for modern interface.
[defaultView](#defaultview)`string``"all"`The test filtering mode when displayed, which will be set by default.
[diffMode](#diffmode)`string``"3-up"`The mode of viewing diffs, which will be set by default.
[baseHost](#basehost)`string`_N/A_Replaces the original host address for viewing in the browser.
[errorPatterns](#errorpatterns)`ErrorPattern[] | string[]``[]`Error patterns with hints to improve the UX of the report.
[metaInfoBaseUrls](#metainfobaseurls)`Record``{}`Base URLs for generating links in the _Meta_ section based on meta information about the tests run.
[saveFormat](#saveformat)`string``"sqlite"`DEPRECATED. Allows you to set the format in which the results of the tests run will be saved.
[customGui](#customgui)`CustomGUI``{ }`DEPRECATED. Use [plugins](#plugins) instead. Description of custom controls for GUI mode.
[pluginsEnabled](#pluginsenabled)`boolean``false`Enable plugins for the report.
[plugins](#plugins)`Plugin[]``[]`A list of plugins with their settings.
[customScripts](#customscripts)`AnyFunction[]``[]`A list of functions that implement custom scripts. For example, Yandex.Metrika scripts or a Bug.
[yandexMetrika](#yandexmetrika)`YandexMetrika`*see below*[Yandex.Metrika][yandex-metrika].
@@ -175,6 +116,16 @@ err.details = { throw err; ``` +### uiMode + +Default UI mode: "old" for classic interface, "new" for modern interface. Affects redirects between old and new interfaces. + +By default, no redirects are performed. + +Available values: `"old"`, `"new"`. + +For example, if set to `"new"`, users will be redirected to the new interface when trying to access the old interface. However, if the user manually clicks "return to old interface", this preference will be saved, and they will always use the old interface until they switch back. + ### defaultView The test filtering mode when displayed, which will be set by default. The following values are available: @@ -246,9 +197,9 @@ where: **Parameter****Type****Description** -nameStringError name. -patternString or RegExpA regular expression or a regular string that the error should match. -hintStringOptional parameter. A hint of what can be done with this error: why it occurred, how to fix it, etc. +name`string`Error name. +pattern`string | RegExp`A regular expression or a regular string that the error should match. +hint`string`Optional parameter. A hint of what can be done with this error: why it occurred, how to fix it, etc. @@ -293,6 +244,21 @@ For example: } ``` +When the value of any key is set to `auto`, the base URL will be set to the base host specified in the report UI, or remain unchanged if the base host is not specified. + +For example, if you have the following `metaInfoBaseUrls` value: + +```javascript +{ + custom_url: "auto"; +} +``` + +And you set the `meta.custom_url` field to `https://example.com/some/path` in your tests, you will see in the meta: + +- A link to `https://example.com/some/path` if the base host is not set in the UI +- A link to `https://another-host.com/some/path` if the base host in the UI is set to `https://another-host.com` + ### saveFormat **DEPRECATED** @@ -346,41 +312,27 @@ customScripts: [ ### yandexMetrika -This parameter allows you to add [Yandex.Metrika][yandex-metrika] to the report. The parameter is set as an object with the key `counterNumber`. As the key value, you must specify the Yandex.Metrica counter number (see "[How to create a counter][how-to-create-counter]"). The number should be set as a Number, not a String. +By default, anonymous data about report UI usage is collected for analysis and UX improvement purposes. Data collected includes report loading speed, frequency of some feature usage (e.g., test sorting), and clicks on UI elements. Data about your project or test content is NOT collected under any circumstances. -Also, in the Yandex.Metrika interface, go to the _"Counter"_ tab in the settings section, click _"Copy"_ and paste the counter code into the [customScripts](#customscripts) field. +If you don't want to share analytics with us, you can disable it in any of the following ways: -With the help of metrics, you can find out how developers interact with your report and what kind of problems they face. - -The report supports the following [goals of metrics][yandex-metrika-goals]: - -- **ACCEPT_SCREENSHOT**—there was a click on the _Accept_ button to accept a screenshot; -- **ACCEPT_OPENED_SCREENSHOTS**—there was a click on the _Accept opened_ button to accept screenshots from open tests. - -Example of setting up Yandex.Metrika in one of the projects: - -```javascript -module.exports = { - plugins: { - 'html-reporter/testplane': { - customScripts: [ - function(){(function(m,e,t,r,i,k,a){m[i]=m[i]function(){(m[i].a=m[i].a[]).push(arguments)}; m[i].l=1*new Date();k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)}) (window, document, "script", "https://mc.yandex.ru/metrika/tag.js", "ym"); ym(56782912, "init", { clickmap:true, trackLinks:true, accurateTrackBounce:true, webvisor:true })}, - - // other scripts... - ], - yandexMetrika: { - counterNumber: 1234567 +- In the config + ```javascript + module.exports = { + plugins: { + "html-reporter/testplane": { + yandexMetrika: { + enabled: false, + }, + // other html-reporter settings... }, - - // other plugin settings... + // other Testplane plugins... }, - - // other Testplane plugins... - }, - - // other Testplane settings... -}; -``` + // other Testplane settings... + }; + ``` +- Using environment variables: `html_reporter_yandex_metrika_enabled=false` or simply `NO_ANALYTICS=true` +- Using CLI arguments: `--html-reporter-yandex_metrika_enabled=false` ### Passing parameters via the CLI {#setup_by_cli} diff --git a/docs/html-reporter/overview.mdx b/docs/html-reporter/overview.mdx new file mode 100644 index 0000000..de67afc --- /dev/null +++ b/docs/html-reporter/overview.mdx @@ -0,0 +1,89 @@ +--- +sidebar_position: 1 +sidebar_label: Overview +title: Testplane UI +--- + +import Admonition from "@theme/Admonition"; +import ConfigExamples from "/docs/_partials/html-reporter-config-examples.mdx"; + +![](/img/docs/html-reporter/html-reporter-demo.png) + +
+ +Testplane UI or, as we also call it, `html-reporter` — is an open-source project that can be used to view test results or interact with tools like [Testplane](https://testplane.io), [Playwright](https://playwright.dev/) or [Jest](https://jestjs.io/). + +## Features + +#### Run and debug your tests + +View test steps, replay them and when something goes wrong, find the root cause with ease. + +![](/gif/docs/ui/run-debug.gif) + +#### Superb visual testing capabilities + +Accept or undo changes in visual checks with one click. Multiple viewing modes and dedicated visual checks tab will help you analyze the difference. + +![](/gif/docs/ui/visual-checks.gif) + +#### Unified UI for CI and local usage + +Something went wrong in CI? Pull the report and continue troubleshooting locally. + +![](/gif/docs/ui/ci-and-local.gif) + +#### Powerful analytics + +Spot flaky tests, slow tests or other issues using "sort by" and "group by" options. + +![](/gif/docs/ui/analytics.gif) + +#### And so much more + +Benefits over regular reporters include: + +- **More than a reporter**: it's not static, you can run your tests, update reference images, analyze test runs and more. +- **Save developer time**: no need to relaunch reports or switch terminals during development — the whole workflow is possible from the UI. +- **No vendor lock-in**: all data is yours, the UI is open-source and everything is running locally on your machine. There's no cloud. +- **Optimized to work at scale**: doesn't matter if you have 100 or 100,000+ tests in one report — the UI will work just as smoothly. Built-in support for artifacts uploading on the fly to S3 or other storage. +- **Multiple data sources**: html-reporter can pull and merge data from any amount of data sources at runtime, or you can use dedicated merge-reports command. + +## Demo + +One link is worth a thousand words, so [here it is](https://storage.yandexcloud.net/testplane-ui-demo/v10.16.3/new-ui.html#/suites/testplane%20New%20UI%20Suites%20page%20Expand%2Fcollapse%20suites%20tree%20button%20should%20offer%20to%20expand%20when%20collapsed%20using%20button%20chrome) — see all the features for yourself. + +## Getting started + + +Currently `html-reporter` needs Node v18 or higher and works with Testplane, Playwright and Jest. + +Note that html-reporter is tool-agnostic at its core, so adding support for a new tool is a matter of implementing new data adapters. If you have a specific tool in mind, [raise an issue](https://github.com/gemini-testing/html-reporter/issues) — let's discuss what can be done. + + + +1. Install `html-reporter` with your favorite package manager: + + ```shell + npm i -D html-reporter + ``` + +2. Turn it on in your tool's config: + + + +3. Run your tests and see the report: + + ```shell + npm test + + npx serve html-report + ``` + +4. Try UI mode to run your tests from the UI: + + ```shell + npx html-reporter gui + ``` + + Note: UI mode is available only for Testplane and Playwright. To use with Playwright, add `--tool playwright`. diff --git a/docusaurus.config.ts b/docusaurus.config.ts index ed40c43..4dbb713 100644 --- a/docusaurus.config.ts +++ b/docusaurus.config.ts @@ -87,6 +87,12 @@ const config: Config = { position: "left", label: "Docs", }, + { + type: "docSidebar", + sidebarId: "ui", + position: "left", + label: "UI", + }, { to: "/blog", label: "Blog", position: "left" }, { type: "docsVersionDropdown", diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/html-reporter-api.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/html-reporter-api.mdx index 7cee0cc..742a990 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/html-reporter-api.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/html-reporter-api.mdx @@ -1,4 +1,8 @@ -# API плагина +--- +sidebar_class_name: hidden +--- + +# Объект HTML Reporter ## Обзор {#overview} diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/html-reporter-commands.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/html-reporter-commands.mdx index 6acd392..830a0e6 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/html-reporter-commands.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/html-reporter-commands.mdx @@ -1,15 +1,25 @@ -# Команды плагина +import Admonition from "@theme/Admonition"; + +# CLI ## Обзор {#overview} -Плагин `html-reporter` добавляет к Testplane следующие команды: +HTML Reporter имеет следующие команды: - [gui](#gui) — чтобы запускать Testplane в GUI-режиме; +- [merge-reports](#merge-reports) — чтобы объединять несколько отчетов в один. - [remove-unused-screens](#remove-unused-screens) — чтобы удалять неиспользуемые в тестах эталонные скриншоты; -- [merge-reports](#merge-reports) — чтобы объединять отдельные отчеты Testplane в один общий отчет. + +При использовании HTML Reporter с Testplane, вы также можете использовать команды через Testplane, например: `npx testplane gui`. + +При использовании с другими инструментами, необходимо указывать название инструмента в аргументе tool, например: `npx html-reporter gui --tool playwright`. ## gui + + Команда доступна только при использовании HTML Reporter с Testplane и Playwright. + + Используйте команду `gui`, чтобы запустить Testplane в GUI-режиме. GUI-режим позволяет: @@ -23,11 +33,50 @@ GUI-режим позволяет: ### Использование {#gui_usage} ```bash -npx testplane gui +npx html-reporter gui +``` + +## merge-reports + + + Команда доступна только при использовании HTML Reporter с Testplane и Playwright. + + +Используйте команду `merge-reports`, чтобы объединить несколько отчетов в один. + +Команда принимает пути к директориям с отчетами, файлам баз данных или к файлам `databaseUrls.json`. + +Она создает новый html-отчет в папке назначения с данными из всех переданных отчетов. + +- При объединении локальных отчетов — все данные, включая SQLite базы данных и скриншоты, копируются в директорию назначения. +- При объединении отчетов по ссылке (например, если на вход переданы файлы `databaseUrls.json` со ссылками на отчеты в S3) — в директории назначения будет создан отчет со ссылками на исходные отчеты в `databaseUrls.json`, без скачивания и копирования всех вложенных ресурсов. При работе с отчетом это никак не будет заметно, но нужно учитывать, что исходные отчеты должны оставаться доступными, так как объединенный отчет получает данные из них. + +### Использование {#merge_reports_usage} + +Команда `merge-reports` поддерживает следующую обязательную опцию: + + + + + + + + + +
**Опция****Описание**
-d, --destination <folder>Путь к папке, в которую нужно сохранить итоговый отчет.
+ +Пример использования: + +```bash +npx html-reporter merge-reports report-dir/ path-to-database.db path-to-databaseUrls.json -d dest-report ``` ## remove-unused-screens + + Команда доступна только при использовании HTML Reporter с Testplane. + + Используйте команду `remove-unused-screens`, чтобы удалить неиспользуемые в тестах эталонные скриншоты. ### Как это работает? @@ -83,29 +132,3 @@ npx testplane remove-unused-screens -p 'testplane-screens-folder' --skip-questio ```bash npx testplane remove-unused-screens --help ``` - -## merge-reports - -Используйте команду `merge-reports`, чтобы объединить отдельные отчеты testplane в один общий отчет. - -Команда принимает пути к файлам баз данных или к файлам `databaseUrls.json` из других html-отчетов. Она создает новый html-отчет в папке назначения с общим файлом `databaseUrls.json`, который будет содержать ссылку на файл базы данных или на файлы `databaseUrls.json` из входных параметров. Файлы баз данных в папку назначения не копируются при этом. - -### Использование {#merge_reports_usage} - -Команда `merge-reports` поддерживает следующую обязательную опцию: - - - - - - - - - -
**Опция****Описание**
-d, --destination <folder>Путь к папке, в которую нужно сохранить итоговый отчет.
- -Пример использования: - -```bash -npx testplane merge-reports path-to-database.db path-to-databaseUrls.json -d dest-report -``` diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/html-reporter-custom-gui.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/html-reporter-custom-gui.mdx index ae9a05c..b510be4 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/html-reporter-custom-gui.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/html-reporter-custom-gui.mdx @@ -1,3 +1,7 @@ +--- +sidebar_class_name: hidden +--- + import Admonition from "@theme/Admonition"; # Кастомизация GUI diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/html-reporter-events.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/html-reporter-events.mdx index 8fa4ab9..abd1af1 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/html-reporter-events.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/html-reporter-events.mdx @@ -1,4 +1,8 @@ -# События плагина +--- +sidebar_class_name: hidden +--- + +# События HTML Reporter ## Обзор {#overview} diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/html-reporter-setup.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/html-reporter-setup.mdx index 486ab27..93d89d2 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/html-reporter-setup.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/html-reporter-setup.mdx @@ -1,5 +1,5 @@ --- -sidebar_class_name: hidden +sidebar_position: 2 --- import Tabs from "@theme/Tabs"; @@ -7,138 +7,80 @@ import TabItem from "@theme/TabItem"; import Admonition from "@theme/Admonition"; -# Подключение html-reporter +# Конфигурация -## Обзор {#overview} - -Используйте плагин [html-reporter][html-reporter], чтобы получить html-отчет о прогоне тестов. - -![Html-отчет](/img/docs/html-reporter/html-reporter.overview.png) - - - Для корректной работы плагина _html-reporter_ требуется [testplane][testplane] версии 4 и выше. - - -Плагин сохраняет результаты прогона тестов в базу данных [SQLite][sqlite]. Поэтому вы не сможете открыть локальный отчет как файл с помощью `file://` протокола. - -Чтобы посмотреть отчет, запустите testplane в GUI-режиме: - -```bash -npx testplane gui -``` - -Или запустите [http-server][http-server] в папке с отчетом: - -```bash -npx http-server -p 8000 -``` - -Если вы запускаете локальный сервер не из папки с отчетом, то укажите путь к отчету: - -```bash -npx http-server ./testplane-report -p 8000 -``` - -После чего откройте страницу `http://localhost:8000` в браузере. - -## Установка {#install} - -```bash -npm install -D html-reporter -``` - -## Настройка {#setup} - -Необходимо подключить плагин в разделе `plugins` конфига `testplane`: +## Примеры настройки {#setup} - -```javascript - module.exports = { + + ```javascript title="testplane.config.ts" + export = { + // ... plugins: { 'html-reporter/testplane': { - enabled: true + enabled: true, + path: 'html-report', }, - - // другие плагины testplane... }, - - // другие настройки testplane... }; ``` - -```javascript - module.exports = { - plugins: { - 'html-reporter/testplane': { + + ```javascript title="playwright.config.ts" + // playwright.config.ts + export default defineConfig({ + // ... + reporter: [ + ['html-reporter/playwright', { enabled: true, - path: 'my/testplane-reports', - defaultView: 'all', - baseHost: 'test.com', - errorPatterns: [ - 'Parameter .* must be a string', - { - name: 'Cannot read property of undefined', - pattern: 'Cannot read property .* of undefined', - hint: '
google it, i dont know how to fix it =(
' - } - ], - customScripts: [ - function() { - // кастомный скрипт - }, - - // другие скрипты... - ], - customGui: { - // DEPRECATED (этот параметр устарел) - // дополнительные элементы управления для GUI-режима - // используйте plugins (плагины для отчета) вместо customGui - }, - pluginsEnabled: true, - plugins: [ - // плагины для отчета... - ], - yandexMetrika: { - counter: 1234567 - } - }, + defaultView: 'failed', + path: 'html-report', + }], + ], + }); + ``` - // другие плагины testplane... - }, +
- // другие настройки testplane... - } + + ```javascript title="jest.config.ts" + const config = { + // ... + reporters: [ + ['html-reporter/jest', { + path: 'html-report', + }] + ], + }; ``` -
-### Расшифровка параметров конфигурации {#setup_description} +## Справочник по параметрам конфигурации {#setup_description} - - - - - - - - - - - - - - + + + + + + + + + + + + + + +
**Параметр****Тип****По умолчанию****Описание**
[enabled](#enabled)BooleantrueВключить / отключить плагин.
[path](#path)String"testplane-report"Путь к папке для сохранения файлов html-отчета.
[saveErrorDetails](#saveerrordetails)BooleanfalseСохранять / не сохранять подробности ошибок в json-файлах.
[defaultView](#defaultview)String"all"Режим фильтрации тестов при отображении, который будет установлен по умолчанию.
[diffMode](#diffmode)String"3-up"Режим просмотра диффов, который будет установлен по умолчанию.
[baseHost](#basehost)String_N/A_Заменяет оригинальный адрес хоста для просмотра в браузере.
[errorPatterns](#errorpatterns)Object[] или String[][ ]Паттерны ошибок с подсказками для улучшения UX отчета.
[metaInfoBaseUrls](#metainfobaseurls)Object`{ }`Базовые URL-адреса для формирования ссылок в разделе _Meta_ на основе мета-информации о прогоне теста.
[saveFormat](#saveformat)String"sqlite"ПАРАМЕТР УСТАРЕЛ. Позволяет задать формат, в котором будут сохранены результаты прогона тестов.
[customGui](#customgui)Object`{ }`ПАРАМЕТР УСТАРЕЛ. Используйте вместо него [plugins](#plugins). Описание собственных элементов управления для GUI-режима.
[pluginsEnabled](#pluginsenabled)BooleanfalseВключить плагины для отчета.
[plugins](#plugins)Object[][ ]Список плагинов с их настройками.
[customScripts](#customscripts)Function[][ ]Список функций, реализующих кастомные скрипты. Например, скрипты Яндекс.Метрики или Жучка.
[yandexMetrika](#yandexmetrika)Object`{ }`[Яндекс.Метрика][yandex-metrika].
[enabled](#enabled)`boolean``true`Включить / отключить плагин.
[path](#path)`string``"testplane-report"`Путь к папке для сохранения файлов html-отчета.
[saveErrorDetails](#saveerrordetails)`boolean``false`Сохранять / не сохранять подробности ошибок в json-файлах.
[uiMode](#uimode)`string``null`Режим интерфейса по умолчанию: "old" для классического интерфейса, "new" для современного интерфейса.
[defaultView](#defaultview)`string``"all"`Режим фильтрации тестов при отображении, который будет установлен по умолчанию.
[diffMode](#diffmode)`string``"3-up"`Режим просмотра диффов, который будет установлен по умолчанию.
[baseHost](#basehost)`string`_N/A_Заменяет оригинальный адрес хоста для просмотра в браузере.
[errorPatterns](#errorpatterns)`ErrorPattern[] | string[]``[]`Паттерны ошибок с подсказками для улучшения UX отчета.
[metaInfoBaseUrls](#metainfobaseurls)`Record``{}`Базовые URL-адреса для формирования ссылок в разделе _Meta_ на основе мета-информации о прогоне теста.
[saveFormat](#saveformat)`string``"sqlite"`ПАРАМЕТР УСТАРЕЛ. Позволяет задать формат, в котором будут сохранены результаты прогона тестов.
[customGui](#customgui)`CustomGUI``{ }`ПАРАМЕТР УСТАРЕЛ. Используйте вместо него [plugins](#plugins). Описание собственных элементов управления для GUI-режима.
[pluginsEnabled](#pluginsenabled)`boolean``false`Включить плагины для отчета.
[plugins](#plugins)`Plugin[]``[]`Список плагинов с их настройками.
[customScripts](#customscripts)`AnyFunction[]``[]`Список функций, реализующих кастомные скрипты. Например, скрипты Яндекс.Метрики или Жучка.
[yandexMetrika](#yandexmetrika)`YandexMetrika`*см. ниже*[Яндекс.Метрика][yandex-metrika].
@@ -157,7 +99,7 @@ npm install -D html-reporter По умолчанию «не сохранять»: `false`. -Любой плагин testplane может добавить какие-либо подробности в объект ошибки при её возникновении. Эти подробности могут помочь пользователю в отладке проблем, которые возникли в тесте. Html-reporter сохраняет эти детали в папке `error-details` в файле с именем: `<хэш от полного названия теста>-<браузер>_<номер ретрая>_<временная метка>.json`. +Любой плагин testplane может добавить какие-либо подробности в объект ошибки при её возникновении. Эти подробности могут помочь пользователю в отладке проблем, которые возникли в тесте. Html-reporter сохраняет эти детали в папке `error-details` в файле с именем: `<хэш от полного названия теста>-<браузер>_<номер ретрая>_<временная метка>.json`. Под стектрейсом html-reporter добавляет раздел `Error details` со ссылкой ``, указывающей на json-файл. Пользователь может открыть этот файл либо в браузере, либо в любой IDE. @@ -174,6 +116,16 @@ err.details = { throw err; ``` +### uiMode + +Режим интерфейса по умолчанию: "old" для классического интерфейса, "new" для современного интерфейса. Влияет на редиректы между старым и новым интерфейсом. + +По умолчанию редиректы не выполняются. + +Доступны следующие значения: `"old"`, `"new"`. + +Например, если установлено значение `"new"`, то пользователи будут перенаправляться на новый интерфейс при попытке доступа к старому интерфейсу. Однако, если пользователь вручную нажмет кнопку "вернуться к старому интерфейсу", эта настройка будет сохранена, и он всегда будет использовать старый интерфейс, пока не переключится обратно. + ### defaultView Режим фильтрации тестов при отображении, который будет установлен по умолчанию. Доступны следующие значения: @@ -232,9 +184,9 @@ throw err; ```javascript { - name: '<название ошибки>', - pattern: '<паттерн ошибки>', - hint: '<подсказка пользователю>' + name: '<название ошибки>', + pattern: '<паттерн ошибки>', + hint: '<подсказка пользователю>' } ``` @@ -245,9 +197,9 @@ throw err; <tr><td>**Параметр**</td><td>**Тип**</td><td>**Описание**</td></tr> </thead> <tbody> -<tr><td>name</td><td>String</td><td>Название ошибки.</td></tr> -<tr><td>pattern</td><td>String или RegExp</td><td>Регулярное выражение или обычная строка, которой должна соответствовать ошибка.</td></tr> -<tr><td>hint</td><td>String</td><td>Необязательный параметр. Подсказка, что можно сделать с данной ошибкой: почему она возникла, как её исправить и т. п.</td></tr> +<tr><td>name</td><td>`string`</td><td>Название ошибки.</td></tr> +<tr><td>pattern</td><td>`string | RegExp`</td><td>Регулярное выражение или обычная строка, которой должна соответствовать ошибка.</td></tr> +<tr><td>hint</td><td>`string`</td><td>Необязательный параметр. Подсказка, что можно сделать с данной ошибкой: почему она возникла, как её исправить и т. п.</td></tr> </tbody> </table> @@ -256,8 +208,8 @@ throw err; ```javascript { - name: '<ошибка>', - pattern: '<ошибка>' + name: '<ошибка>', + pattern: '<ошибка>' } ``` @@ -278,8 +230,8 @@ throw err; ```javascript { - '<опция-1>': 'значение опции 1', - '<опция-2>': 'значение опции 2', + '<опция-1>': 'значение опции 1', + '<опция-2>': 'значение опции 2', // и т. д. } ``` @@ -292,6 +244,21 @@ throw err; } ``` +Когда значение любого ключа установлено на `auto`, базовый URL будет установлен на базовый хост, указанный в интерфейсе отчета, или останется неизменным, если базовый хост не указан. + +Например, если у вас есть следующее значение `metaInfoBaseUrls`: + +```javascript +{ + custom_url: "auto"; +} +``` + +И вы установите поле `meta.custom_url` в `https://example.com/some/path` в ваших тестах, вы увидите в мете: + +- Ссылку на `https://example.com/some/path`, если базовый хост не установлен в интерфейсе пользователя +- Ссылку на `https://another-host.com/some/path`, если базовый хост в интерфейсе пользователя установлен в `https://another-host.com` + ### saveFormat **Параметр устарел** @@ -345,41 +312,27 @@ customScripts: [ ### yandexMetrika -Данный параметр позволяет добавить в отчет [Яндекс.Метрику][yandex-metrika]. Параметр задается в виде объекта с ключом `counterNumber` _(номер счетчика)_. В качестве значения ключа необходимо указать номер счетчика Яндекс.Метрики (см. «[Как создать счетчик][how-to-create-counter]»). Номер должен задаваться как число _(Number)_, а не строка. - -Также в интерфейсе Яндекс.Метрики необходимо перейти в разделе настроек на вкладку _«Счетчик»_, нажать кнопку _«Скопировать»_ и вставить код счетчика в поле [customScripts](#customscripts). - -С помощью метрики вы сможете узнать как разработчики взаимодействуют с вашим отчетом и с какого рода проблемами они сталкиваются. - -Отчет поддерживает следующие [цели для метрики][yandex-metrika-goals]: - -- **ACCEPT_SCREENSHOT** — было нажатие на кнопку _Accept_ для принятия скриншота; -- **ACCEPT_OPENED_SCREENSHOTS** — было нажатие на кнопку _Accept opened_ для принятия скриншотов из открытых тестов. +По умолчанию выполняется сбор анонимных сведений об использовании интерфейса отчета в целях анализа и улучшения UX. Собираются такие сведения, как скорость загрузки отчета, частота использования некоторых функций (например, сортировка тестов) и клики по элементам управления. Сведения о вашем проекте или содержимом тестов НЕ собираются ни при каких обстоятельствах. -Пример настройки _Яндекс.Метрики_ в одном из проектов: +Если вы не хотите делиться аналитикой с нами, вы можете отключить это любым из способов: -```javascript -module.exports = { - plugins: { - 'html-reporter/testplane': { - customScripts: [ - function(){(function(m,e,t,r,i,k,a){m[i]=m[i]<tr><td>function(){(m[i].a=m[i].a</td></tr>[]).push(arguments)}; m[i].l=1*new Date();k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)}) (window, document, "script", "https://mc.yandex.ru/metrika/tag.js", "ym"); ym(56782912, "init", { clickmap:true, trackLinks:true, accurateTrackBounce:true, webvisor:true })}, - - // другие скрипты... - ], - yandexMetrika: { - counterNumber: 1234567 +- В конфиге + ```javascript + module.exports = { + plugins: { + "html-reporter/testplane": { + yandexMetrika: { + enabled: false, + }, + // другие настройки html-reporter... }, - - // другие настройки плагина... + // другие плагины Testplane... }, - - // другие плагины testplane... - }, - - // другие настройки testplane... -}; -``` + // другие настройки Testplane... + }; + ``` +- С помощью переменных окружения: `html_reporter_yandex_metrika_enabled=false` или просто `NO_ANALYTICS=true` +- С помощью аргументов CLI: `--html-reporter-yandex_metrika_enabled=false` ### Передача параметров через CLI {#setup_by_cli} diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/overview.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/overview.mdx new file mode 100644 index 0000000..a0f3289 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/overview.mdx @@ -0,0 +1,89 @@ +--- +sidebar_position: 1 +sidebar_label: Обзор +title: Testplane UI +--- + +import Admonition from "@theme/Admonition"; +import ConfigExamples from "/docs/_partials/html-reporter-config-examples.mdx"; + +![](/img/docs/html-reporter/html-reporter-demo.png) + +<br /> + +Testplane UI или, как мы его также называем, `html-reporter` — это проект с открытым исходным кодом, который можно использовать для просмотра результатов тестов или взаимодействия с инструментами, такими как [Testplane](https://testplane.io), [Playwright](https://playwright.dev/) или [Jest](https://jestjs.io/). + +## Возможности + +#### Запускайте и отлаживайте свои тесты + +Просматривайте шаги теста, воспроизводите их, и когда что-то идет не так, легко находите первопричину. + +![](/gif/docs/ui/run-debug.gif) + +#### Превосходные возможности визуального тестирования + +Принимайте или отменяйте изменения в визуальных проверках одним кликом. Множество режимов просмотра и специальная вкладка визуальных проверок помогут вам проанализировать различия. + +![](/gif/docs/ui/visual-checks.gif) + +#### Единый UI для CI и локального использования + +Что-то пошло не так в CI? Загрузите отчет и продолжайте устранение неполадок локально. + +![](/gif/docs/ui/ci-and-local.gif) + +#### Мощная аналитика + +Находите нестабильные тесты, медленные тесты или другие проблемы с помощью опций "сортировка" и "группировка". + +![](/gif/docs/ui/analytics.gif) + +#### И многое другое + +Вот некоторые преимущества HTML Reporter: + +- **Больше, чем просто отчет**: это не статический отчет — вы можете запускать свои тесты, обновлять эталонные изображения, анализировать прогоны тестов и многое другое. +- **Экономия времени разработчика**: нет необходимости перезапускать отчеты или переключаться между терминалами во время разработки — весь рабочий процесс возможен из UI. +- **Нет vendor-lock**: все данные ваши, UI имеет открытый исходный код, и все работает локально на вашей машине. Нет подписок и привязки к облаку. +- **Оптимизирован для работы в масштабе**: неважно, есть ли у вас 100 или 100 000+ тестов в одном отчете — UI будет работать так же плавно. Встроенная поддержка загрузки артефактов на лету в S3 или другое хранилище. +- **Множество источников данных**: html-reporter может загружать и объединять данные из любого количества источников во время выполнения, или вы можете использовать специальную команду merge-reports. + +## Демо + +Попробуйте HTML Reporter — он доступен [по ссылке](https://storage.yandexcloud.net/testplane-ui-demo/v10.16.3/new-ui.html#/suites/testplane%20New%20UI%20Suites%20page%20Expand%2Fcollapse%20suites%20tree%20button%20should%20offer%20to%20expand%20when%20collapsed%20using%20button%20chrome). + +## Начало работы + +<Admonition type="info"> +В настоящее время `html-reporter` требует Node v18 или выше и работает с Testplane, Playwright и Jest. + +Обратите внимание, что html-reporter не зависит от конкретного инструмента в своей основе, поэтому добавление поддержки нового инструмента — это вопрос реализации новых адаптеров данных. Если у вас есть конкретный инструмент на примете, [создайте issue](https://github.com/gemini-testing/html-reporter/issues) — обсудим, что можно сделать. + +</Admonition> + +1. Установите `html-reporter`: + + ```shell + npm i -D html-reporter + ``` + +2. Включите его в конфиге вашего инструмента: + + <ConfigExamples /> + +3. Запустите ваши тесты и посмотрите отчет: + + ```shell + npm test + + npx serve html-report + ``` + +4. Попробуйте UI режим для запуска тестов из UI: + + ```shell + npx html-reporter gui + ``` + + Примечание: UI режим доступен только для Testplane и Playwright. Для использования с Playwright добавьте `--tool playwright`. diff --git a/sidebars.ts b/sidebars.ts index 4c81b30..ed01678 100644 --- a/sidebars.ts +++ b/sidebars.ts @@ -63,12 +63,6 @@ const sidebars: SidebarsConfig = { label: "Guides", items: [{ type: "autogenerated", dirName: "guides" }], }, - { - type: "category", - label: "HTML Reporter", - items: [{ type: "autogenerated", dirName: "html-reporter" }], - link: { type: "doc", id: "html-reporter/html-reporter-setup" }, - }, { type: "category", label: "Migrations", @@ -85,6 +79,18 @@ const sidebars: SidebarsConfig = { items: [{ type: "autogenerated", dirName: "reference" }], }, ], + ui: [ + { type: "autogenerated", dirName: "html-reporter" }, + { + type: "category", + label: "API", + link: { type: "doc", id: "html-reporter/html-reporter-api" }, + items: [ + { type: "doc", id: "html-reporter/html-reporter-api" }, + { type: "doc", id: "html-reporter/html-reporter-events" }, + ], + }, + ], }; export default sidebars; diff --git a/static/gif/docs/ui/analytics.gif b/static/gif/docs/ui/analytics.gif new file mode 100644 index 0000000..c7739bd Binary files /dev/null and b/static/gif/docs/ui/analytics.gif differ diff --git a/static/gif/docs/ui/ci-and-local.gif b/static/gif/docs/ui/ci-and-local.gif new file mode 100644 index 0000000..06b4b71 Binary files /dev/null and b/static/gif/docs/ui/ci-and-local.gif differ diff --git a/static/gif/docs/ui/run-debug.gif b/static/gif/docs/ui/run-debug.gif new file mode 100644 index 0000000..5d3c999 Binary files /dev/null and b/static/gif/docs/ui/run-debug.gif differ diff --git a/static/gif/docs/ui/visual-checks.gif b/static/gif/docs/ui/visual-checks.gif new file mode 100644 index 0000000..1440c98 Binary files /dev/null and b/static/gif/docs/ui/visual-checks.gif differ diff --git a/static/img/docs/html-reporter/html-reporter-demo.png b/static/img/docs/html-reporter/html-reporter-demo.png new file mode 100644 index 0000000..670a75b Binary files /dev/null and b/static/img/docs/html-reporter/html-reporter-demo.png differ