diff --git a/docs/_partials/specs/version-en.mdx b/docs/_partials/specs/version-en.mdx new file mode 100644 index 0000000..0c6f57d --- /dev/null +++ b/docs/_partials/specs/version-en.mdx @@ -0,0 +1 @@ +_Available from testplane v{props.version}_ diff --git a/docs/_partials/specs/version-ru.mdx b/docs/_partials/specs/version-ru.mdx new file mode 100644 index 0000000..79979ad --- /dev/null +++ b/docs/_partials/specs/version-ru.mdx @@ -0,0 +1 @@ +_Доступно начиная с testplane v{props.version}_ diff --git a/docs/command-line/index.mdx b/docs/command-line/index.mdx index a3db8ed..9e95ad9 100644 --- a/docs/command-line/index.mdx +++ b/docs/command-line/index.mdx @@ -192,6 +192,7 @@ testplane --repl --grep 'my test name' --browser chrome - `--keep-browser-on-fail` - the same as the `--keep-browser` option, but the browser will only remain open if the tests fail. Example of console output with connection information to the browser: + ``` [15:44:38 +0700] Testplane run has finished, but the browser won't be closed, because you passed the --keep-browser argument. [15:44:38 +0700] You may attach to this browser using the following capabilities: diff --git a/docs/commands/browser/restoreState.mdx b/docs/commands/browser/restoreState.mdx new file mode 100644 index 0000000..fdcb2cf --- /dev/null +++ b/docs/commands/browser/restoreState.mdx @@ -0,0 +1,154 @@ +import Admonition from "@theme/Admonition"; +import Version from "../../_partials/specs/version-en.mdx"; + +# restoreState + + + +## Overview {#overview} + +Browser command that restores session state (cookies, local and session storages) from a file or variable. + +## Usage {#usage} + +You can restore the browser state from either a file (using the `path` parameter) or directly from an object (using the `data` parameter). + +**Important:** If you provide both `path` and `data` parameters, the file specified in `path` will take priority. + +You can optionally specify which storage types to restore using the `cookies`, `localStorage`, and `sessionStorage` parameters. This allows you to restore only the specific data you need. + +The state data for restoration can be obtained from the [saveState](../saveState) command. + + + You must be on the exact same page from which the cookies were originally saved. You need to + navigate to the page first, use the [url](../url) command before restoring state. + + +```typescript +await browser.restoreState({ + path: "./stateDump.json", + data: stateDump, + cookies: true, + localStorage: true, + sessionStorage: true, +}); +``` + +## Command Parameters {#parameters} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
**Name****Type****Default****Description**
path`string``-`Path to file with state.
data`SaveStateData``-`Object with state.
cookies`boolean``true`Enable restore cookies.
localStorage`boolean``true`Enable restore localStorage.
sessionStorage`boolean``true`Enable restore sessionStorage.
cookieFilter`(cookie: Cookie) => boolean``-` + Function for filtering cookies, receiving cookie objects, and returning boolean. +
+ +## Usage Examples {#examples} + +Restore state from file. + +```typescript +it("test", async ({ browser }) => { + await browser.url("https://github.com/gemini-testing/testplane"); + + await browser.restoreState({ + path: "./stateDump.json", + cookieFilter: ({ domain }) => domain === ".example.com", + }); + + // Reload page for see auth result. + await browser.refresh(); +}); +``` + +Example of implementing authentication in tests with saveState/restoreState and beforeAll hook. + +```typescript +import { ConfigInput, WdioBrowser } from "testplane"; +import { launchBrowser } from "testplane/unstable"; + +export default { + gridUrl: "local", + beforeAll: async ({ config }) => { + const b = await launchBrowser(config.browsers["chrome"]!); + + await b.url("https://our-site.com"); + await b.$("input.login").setValue("user@example.com"); + await b.$("input.password").setValue("password123"); + + await b.saveState({ path: "./.testplane/state.json" }); + await b.deleteSession(); + }, + sets: { + /* ... */ + }, + browsers: { + chrome: { + headless: false, + desiredCapabilities: { + browserName: "chrome", + }, + }, + }, + plugins: { + /* ... */ + "@testplane/global-hook": { + enabled: true, + beforeEach: async ({ browser }: { browser: WdioBrowser }) => { + await browser.url("https://our-site.com"); + await browser.restoreState({ path: "./.testplane/state.json" }); + }, + }, + }, +} satisfies ConfigInput; +``` + +## Related Commands {#related} + +- [saveState](../saveState) +- [afterAll](../../../config/after-all) +- [beforeAll](../../../config/before-all) diff --git a/docs/commands/browser/saveState.mdx b/docs/commands/browser/saveState.mdx new file mode 100644 index 0000000..d70b70e --- /dev/null +++ b/docs/commands/browser/saveState.mdx @@ -0,0 +1,96 @@ +import Version from "../../_partials/specs/version-en.mdx"; + +# saveState + + + +## Overview {#overview} + +Browser command that saves session state (cookies, local and session storages). + +## Usage {#usage} + +This command returns a state of the page state, including cookies, localStorage, and sessionStorage. +You can use parameters to exclude specific types of data if needed. + +If you provide the `path` parameter, the state dump will be saved to a file. +The saved state can later be restored using the [restoreState](../restoreState) command. + +```typescript +import type { SaveStateData } from "testplane"; + +const stateDump: SaveStateData = await browser.saveState({ + path: "./stateDump.json", + cookies: true, + localStorage: true, + sessionStorage: true, +}); +``` + +## Command Parameters {#parameters} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
**Name****Type****Default****Description**
path`string``-`Path to file where state will be saved.
cookies`boolean``true`Enable save cookies.
localStorage`boolean``true`Enable save localStorage.
sessionStorage`boolean``true`Enable save sessionStorage.
cookieFilter`(cookie: Cookie) => boolean``-` + Function for filtering cookies, receiving cookie objects, and returning boolean. +
+ +## Usage Examples {#examples} + +Save state in file. + +```typescript +it("test", async ({ browser }) => { + await browser.url("https://github.com/gemini-testing/testplane"); + + await browser.saveState({ + path: "./stateDump.json", + cookieFilter: ({ domain }) => domain === ".example.com", + }); +}); +``` + +## Related Commands {#related} + +- [restoreState](../restoreState) +- [afterAll](../../../config/after-all) +- [beforeAll](../../../config/before-all) diff --git a/docs/config/after-all.mdx b/docs/config/after-all.mdx new file mode 100644 index 0000000..9c46ceb --- /dev/null +++ b/docs/config/after-all.mdx @@ -0,0 +1,30 @@ +import Version from "../_partials/specs/version-en.mdx"; + +# afterAll + + + +## Overview {#overview} + +This parameter is a hook. The function specified for this parameter will be automatically called after tests are completed. + +The context of the function is the Testplane config. Function receives config in arguments. + +## Usage Example {#example} + +Here is an example of using this hook to remove a file with a page state. + +```typescript title="testplane.config.ts" +import * as fs from "fs"; + +export default { + // ... + afterAll: async () => { + await fs.unlink("./dump.json"); + }, +}; +``` + +## Related {#related} + +- [beforeAll](../before-all) diff --git a/docs/config/before-all.mdx b/docs/config/before-all.mdx new file mode 100644 index 0000000..918f579 --- /dev/null +++ b/docs/config/before-all.mdx @@ -0,0 +1,58 @@ +import Version from "../_partials/specs/version-en.mdx"; + +# beforeAll + + + +## Overview {#overview} + +This parameter is a hook. The function specified for this parameter will be automatically called before tests running. + +The context of the function is the Testplane config. Also function receives config in arguments. + +## Usage Example {#example} + +Here is an example of using this hook for logging in and getting session data for use in tests. + +```typescript title="testplane.config.ts" +import { launchBrowser } from "testplane/unstable"; + +export default { + // ... + browsers: { + chrome: { + headless: true, + desiredCapabilities: { + webSocketUrl: true, + browserName: "chrome", + }, + }, + firefox: { + headless: true, + desiredCapabilities: { + webSocketUrl: true, + browserName: "firefox", + }, + }, + }, + beforeAll: async () => { + // launch a new browser with existing config + const browser = await launchBrowser(this.config.browsers.chrome); + + await browser.url("https://example.com"); + + // do login things, type username/password etc. + + // save dump with state (cookies, localStorage) for using in tests + await browser.saveState({ + path: "./dump.json", + }); + + await browser.deleteSession(); + }, +}; +``` + +## Related {#related} + +- [afterAll](../after-all) diff --git a/docs/reference/testplane-standalone-api.mdx b/docs/reference/testplane-standalone-api.mdx index 6bf2d9e..2c56fa6 100644 --- a/docs/reference/testplane-standalone-api.mdx +++ b/docs/reference/testplane-standalone-api.mdx @@ -18,7 +18,7 @@ import { launchBrowser } from "testplane/unstable"; // Launch a new browser with the given settings const browser = await launchBrowser({ desiredCapabilities: { - browserName: 'chrome', + browserName: "chrome", }, headless: false, }); diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/command-line/index.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/command-line/index.mdx index 62a14bc..923e794 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/command-line/index.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/command-line/index.mdx @@ -193,6 +193,7 @@ testplane --repl --grep 'my test name' --browser chrome - `--keep-browser-on-fail` - то же, что и опция `--keep-browser`, только браузер останется только в том случае, если тесты завершатся неуспешно Пример вывода в консоли c информацией для подключения к браузеру + ``` [15:44:38 +0700] Testplane run has finished, but the browser won't be closed, because you passed the --keep-browser argument. [15:44:38 +0700] You may attach to this browser using the following capabilities: diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/restoreState.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/restoreState.mdx new file mode 100644 index 0000000..b2d9080 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/restoreState.mdx @@ -0,0 +1,152 @@ +import Admonition from "@theme/Admonition"; +import Version from "../../../../../../docs/_partials/specs/version-ru.mdx"; + +# restoreState + + + +## Обзор {#overview} + +Команда для восстановления данных (cookies, local and session storages) из файла или объекта. + +## Использование {#usage} + +Вы можете восстановить состояние браузера из файла (с помощью параметра `path`) или непосредственно из объекта (с помощью параметра `data`). + +**Важно:** Если вы указали оба параметра `path` и `data`, приоритет будет у файла, указанного в `path`. + +При необходимости вы можете указать, какие типы данных восстановить, используя параметры `cookies`, `localStorage` и `sessionStorage`. Это позволяет восстановить только те данные, которые вам нужны. + +Данные для восстановления состояния можно получить с помощью команды [saveState](../saveState). + + + Вы должны находиться на той же странице, с которой были сохранены cookies. Вам нужно сначала + перейти на страницу, используйте команду [url](../url) перед восстановлением состояния. + + +```typescript +await browser.restoreState({ + path: "./stateDump.json", + data: stateDump, + cookies: true, + localStorage: true, + sessionStorage: true, +}); +``` + +## Параметры команды {#parameters} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
**Имя****Тип****Значение по умолчанию****Описание**
path`string``-`Путь к файлу с данными.
data`SaveStateData``-`Объект с данными.
cookies`boolean``true`Включить восстановление кук.
localStorage`boolean``true`Включить восстановление localStorage.
sessionStorage`boolean``true`Включить восстановление sessionStorage.
cookieFilter`(cookie: Cookie) => boolean``-`Функция для фильтрации кук, принимает объект куки и возвращает boolean.
+ +## Примеры использования {#examples} + +Восстановление данных из файла. + +```typescript +it("test", async ({ browser }) => { + await browser.url("https://github.com/gemini-testing/testplane"); + + await browser.restoreState({ + path: "./stateDump.json", + cookieFilter: ({ domain }) => domain === ".example.com", + }); + + // Reload page for see auth result. + await browser.refresh(); +}); +``` + +Пример реализации аутентификации в тестах с использованием saveState/restoreState и хука beforeAll. + +```typescript +import { ConfigInput, WdioBrowser } from "testplane"; +import { launchBrowser } from "testplane/unstable"; + +export default { + gridUrl: "local", + beforeAll: async ({ config }) => { + const b = await launchBrowser(config.browsers["chrome"]!); + + await b.url("https://our-site.com"); + await b.$("input.login").setValue("user@example.com"); + await b.$("input.password").setValue("password123"); + + await b.saveState({ path: "./.testplane/state.json" }); + await b.deleteSession(); + }, + sets: { + /* ... */ + }, + browsers: { + chrome: { + headless: false, + desiredCapabilities: { + browserName: "chrome", + }, + }, + }, + plugins: { + /* ... */ + "@testplane/global-hook": { + enabled: true, + beforeEach: async ({ browser }: { browser: WdioBrowser }) => { + await browser.url("https://our-site.com"); + await browser.restoreState({ path: "./.testplane/state.json" }); + }, + }, + }, +} satisfies ConfigInput; +``` + +## Связанные команды {#related} + +- [saveState](../saveState) +- [afterAll](../../../config/after-all) +- [beforeAll](../../../config/before-all) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/saveState.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/saveState.mdx new file mode 100644 index 0000000..e582791 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/saveState.mdx @@ -0,0 +1,94 @@ +import Version from "../../../../../../docs/_partials/specs/version-ru.mdx"; + +# saveState + + + +## Обзор {#overview} + +Команда для сохранения состояния страницы (cookies, local и session storages). + +## Использование {#usage} + +Эта команда возвращает снимок состояния страницы, включая cookies, localStorage и sessionStorage. +С помощью параметров вы можете при необходимости исключить определённые типы данных. + +Если вы укажете параметр `path`, снимок состояния будет сохранён в файл. +Сохранённое состояние можно впоследствии восстановить с помощью команды [restoreState](../restoreState). + +```typescript +import type { SaveStateData } from "testplane"; + +const stateDump: SaveStateData = await browser.saveState({ + path: "./stateDump.json", + cookies: true, + localStorage: true, + sessionStorage: true, +}); +``` + +## Параметры команды {#parameters} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
**Имя****Тип****Значение по умолчанию****Описание**
path`string``-`Путь где будет сохранён файл с данными.
cookies`boolean``екгу`Включить сохранение кук.
localStorage`boolean``екгу`Включить сохранение localStorage.
sessionStorage`boolean``екгу`Включить сохранение sessionStorage.
cookieFilter`(cookie: Cookie) => boolean``-`Функция для фильтрации кук, принимает объект куки и возвращает boolean.
+ +## Примеры использования {#examples} + +Сохранение данных в файл. + +```typescript +it("test", async ({ browser }) => { + await browser.url("https://github.com/gemini-testing/testplane"); + + await browser.saveState({ + path: "./stateDump.json", + cookieFilter: ({ domain }) => domain === ".example.com", + }); +}); +``` + +## Связанные команды {#related} + +- [restoreState](../restoreState) +- [afterAll](../../../config/after-all) +- [beforeAll](../../../config/before-all) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/config/after-all.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/config/after-all.mdx new file mode 100644 index 0000000..5f67957 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/config/after-all.mdx @@ -0,0 +1,30 @@ +import Version from "../../../../../docs/_partials/specs/version-ru.mdx"; + +# afterAll + + + +## Обзор {#overview} + +Данный параметр является хуком. Функция, заданная для данного параметра, будет автоматически вызвана после прохождения тестов. + +Контекстом функции является конфиг Testplane. Также функция принимает конфиг в аргументе. + +## Пример использования {#example} + +Пример удаления файла с состоянием страницы после выполнения тестов. + +```typescript title="testplane.config.ts" +import * as fs from "fs"; + +export default { + // ... + afterAll: async () => { + fs.unlinkSync("dump.json"); + }, +}; +``` + +## Связанные хуки {#related} + +- [beforeAll](../before-all) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/config/before-all.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/config/before-all.mdx new file mode 100644 index 0000000..0993ace --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/config/before-all.mdx @@ -0,0 +1,58 @@ +import Version from "../../../../../docs/_partials/specs/version-ru.mdx"; + +# beforeAll + + + +## Обзор {#overview} + +Данный параметр является хуком. Функция, заданная для данного параметра, будет автоматически вызвана до запуска тестов. + +Контекстом функции является конфиг Testplane. Также функция принимает конфиг в аргументе. + +## Пример использования {#example} + +Пример логина и сохранения стейта сессии (куки, localStorage) для его последующего использования в тестах. + +```typescript title="testplane.config.ts" +import { launchBrowser } from "testplane/unstable"; + +export default { + // ... + browsers: { + chrome: { + headless: true, + desiredCapabilities: { + webSocketUrl: true, + browserName: "chrome", + }, + }, + firefox: { + headless: true, + desiredCapabilities: { + webSocketUrl: true, + browserName: "firefox", + }, + }, + }, + beforeAll: async () => { + // launch a new browser with existing config + const browser = await launchBrowser(this.config.browsers.chrome); + + await browser.url("https://example.com"); + + // do login things, type username/password etc. + + // save dump with state (cookies, localStorage) for using in tests + await browser.saveState({ + path: "./dump.json", + }); + + await browser.deleteSession(); + }, +}; +``` + +## Связанные хуки {#related} + +- [afterAll](../after-all) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/reference/testplane-standalone-api.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/reference/testplane-standalone-api.mdx index f5707a0..0797435 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/reference/testplane-standalone-api.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/reference/testplane-standalone-api.mdx @@ -18,7 +18,7 @@ import { launchBrowser } from "testplane/unstable"; // Запуск браузера с необходимыми параметрами const browser = await launchBrowser({ desiredCapabilities: { - browserName: 'chrome', + browserName: "chrome", }, headless: false, });