diff --git a/blog/support-bidi-protocol.mdx b/blog/support-bidi-protocol.mdx new file mode 100644 index 0000000..cbd49d8 --- /dev/null +++ b/blog/support-bidi-protocol.mdx @@ -0,0 +1,144 @@ +--- +title: Поддержка WebDriver BiDi протокола +slug: support-bidi-protocol +hide_table_of_contents: false +date: 2025-05-06T14:00 +--- + +import Admonition from "@theme/Admonition"; +import mockNetworkRequestExampleUrl from "/video/blog/bidi/mock-network-request-example.mp4"; +import networkResponsesExampleUrl from "/video/blog/bidi/network-responses-example.mp4"; +import browserLogsExampleUrl from "/video/blog/bidi/browser-logs-example.mp4"; +import screenFullPageExampleUrl from "/video/blog/bidi/screen-full-page-example.mp4"; + +В [testplane@8.27.0][testplane@8.27.0] добавлена поддержка [WebDriver BiDi протокола][bidi] (будущий единый стандарт для автоматизации браузеров). + + + +WebDriver BiDi (Bidirectional) — это новый протокол кросс-браузерной автоматизации, который сочетает в себе лучшее из существующих протоколов: [W3C WebDriver][webdriver] и [Chrome DevTools Protocol (CDP)][cdp] (подробнее о них можно почитать в нашей [статье][webvider-vs-cdp]). По сути новый протокол расширяет существующий +W3C Webdriver протокол и добавляет в него новые кросс-браузерные команды, которые заменяют CDP протокол (не является кросс-браузерным). Старые webdriver-команды работают как и раньше по http, а новые команды обеспечивают двунаправленную коммуникацию между клиентом и браузером по websocket соединению. + +Новый протокол на данный момент поддержан следующими браузерами: Chrome, Firefox, Edge. В safari поддержки пока нет. Следить за поддерживаемыми браузерами можно на этой [странице][bidi-browsers-support]. + +Список команд BiDi протокола доступен на этой [странице][bidi-commands]. + +### Как использовать? + + + В Testplane поддержка BiDi протокола доступна в браузерах начиная с версии: chrome@128 и + firefox@129. + + +Для использования BiDi протокола необходимо: + +- установить testplane@8.27.0 или старше; +- указать капабилити `webSocketUrl: true` в поле `desiredCapabilities` для необходимого браузера (в следующей мажорной версии будет выставляться по умолчанию); +- запустить тесты. + +### Что можно сделать с помощью нового протокола? + +#### Отслеживание и перехват сетевых запросов/ответов + +1. Можно замокать запрос к testplane.io и вернуть свой ответ: + +```typescript +it("should mock testplane.io", async ({ browser }) => { + await browser.networkAddIntercept({ phases: ["beforeRequestSent"] }); + + browser.on("network.beforeRequestSent", networkRequest => { + browser.networkProvideResponse({ + request: networkRequest.request.request, + body: { + type: "string", + value: "hello world", + }, + }); + }); + + await browser.url("https://testplane.io"); +}); +``` + + + +2. Перехватим все запросы к ресурсу testplane.io и отобразим список всех загружаемых урлов: + +```typescript +it("should log all loaded urls", async ({ browser }) => { + browser.on("network.responseCompleted", networkResponse => + console.log("got response from url:", networkResponse.response.url), + ); + + await browser.url("https://testplane.io"); +}); +``` + + + +#### Отображение логов в браузере + +```typescript +it("should show browser console logs", async ({ browser }) => { + browser.on("log.entryAdded", entryAdded => console.log(JSON.stringify(entryAdded, null, 4))); + + await browser.execute(() => console.log("Hello Bidi")); +}); +``` + + + +#### Снятие скриншота всей страницы + +```typescript +import * as fs from "node:fs"; + +it("should screen full page", async ({ browser }) => { + await browser.url("https://www.npmjs.com/"); + + const tree = await browser.browsingContextGetTree({}); + const file = await browser.browsingContextCaptureScreenshot({ + context: tree.contexts[0].context, + origin: "document", + }); + + fs.writeFileSync("screenshot.png", Buffer.from(file.data, "base64")); +}); +``` + + + +### Заключение + +Хотя протокол BiDi все еще находится в [Editor's Draft][editors-draft], но уже очевидно, что за этим протоколом будущее. Так например браузер firefox уже объявил о том, что [прекращает поддержку CDP протокола с версии 129][ff-deprecate-cdp]. + +Поддержка протокола BiDi позволяет нашим пользователям: + +- использовать больше возможностей для автоматизации тестов, которых не было в WebDriver протоколе; +- возможность отказаться от использования [Puppeteer][puppeteer] (используются под капотом для поддержки CDP протокола), который по нашему опыту приводит к множеству проблем в тестах; +- идти в ногу со временем и уже начинать привыкать к будущему единому стандарту. + +Переходите на новую версию Testplane и приносите фидбек. В случае обнаружения проблем приходите в [issue github][gh-issues] — мы вам обязательно поможем! + +[testplane@8.27.0]: https://github.com/gemini-testing/testplane/releases/tag/v8.27.0 +[bidi]: https://w3c.github.io/webdriver-bidi/ +[webdriver]: https://www.w3.org/TR/webdriver1/ +[cdp]: https://chromedevtools.github.io/devtools-protocol/ +[webvider-vs-cdp]: https://testplane.io/ru/docs/v8/reference/webdriver-vs-cdp/ +[bidi-browsers-support]: https://wpt.fyi/results/webdriver/tests/bidi?label=master&label=stable&aligned +[bidi-commands]: https://webdriver.io/docs/api/webdriverBidi +[editors-draft]: https://www.w3.org/standards/types/#ED +[ff-deprecate-cdp]: https://fxdx.dev/deprecating-cdp-support-in-firefox-embracing-the-future-with-webdriver-bidi/ +[puppeteer]: https://pptr.dev/ +[gh-issues]: https://github.com/gemini-testing/testplane/issues diff --git a/i18n/en/docusaurus-plugin-content-blog/support-bidi-protocol.mdx b/i18n/en/docusaurus-plugin-content-blog/support-bidi-protocol.mdx new file mode 100644 index 0000000..036675d --- /dev/null +++ b/i18n/en/docusaurus-plugin-content-blog/support-bidi-protocol.mdx @@ -0,0 +1,146 @@ +--- +title: WebDriver BiDi protocol support +slug: support-bidi-protocol +hide_table_of_contents: false +date: 2025-05-06T14:00 +--- + +import Admonition from "@theme/Admonition"; +import mockNetworkRequestExampleUrl from "/video/blog/bidi/mock-network-request-example.mp4"; +import networkResponsesExampleUrl from "/video/blog/bidi/network-responses-example.mp4"; +import browserLogsExampleUrl from "/video/blog/bidi/browser-logs-example.mp4"; +import screenFullPageExampleUrl from "/video/blog/bidi/screen-full-page-example.mp4"; + +Support for the [WebDriver BiDi protocol][bidi] (the future unified standard for browser automation) has been added in [testplane@8.27.0][testplane@8.27.0]. + + + +WebDriver BiDi (Bidirectional) is a new cross-browser automation protocol that combines the best features of existing protocols: [W3C WebDriver][webdriver] and [Chrome DevTools Protocol (CDP)][cdp] (you can read more about them in our [article][webvider-vs-cdp]). +Essentially, the new protocol extends the existing W3C WebDriver protocol and adds new cross-browser commands that replace the CDP protocol (which is not cross-browser compatible). +Old webdriver commands still work via HTTP, while new commands provide bidirectional communication between the client and the browser via a WebSocket connection. + +The new protocol is currently supported by the following browsers: Chrome, Firefox, Edge. Safari support is not available yet. You can follow the supported browsers on this [page][bidi-browsers-support]. + +A list of BiDi protocol commands is available on this [page][bidi-commands]. + +### How to use? + + + BiDi protocol support in Testplane is available in browsers starting from version: chrome@128 + and firefox@129. + + +To use the BiDi protocol, you need to: + +- install testplane@8.27.0 or older; +- specify the capability `webSocketUrl: true` in the `desiredCapabilities` field for the desired browser (it will be set by default in the next major version); +- run the tests. + +### What can be done with the new protocol? + +#### Tracking and intercepting network requests/responses + +1. You can mock a request to testplane.io and return your own response: + +```typescript +it("should mock testplane.io", async ({ browser }) => { + await browser.networkAddIntercept({ phases: ["beforeRequestSent"] }); + + browser.on("network.beforeRequestSent", networkRequest => { + browser.networkProvideResponse({ + request: networkRequest.request.request, + body: { + type: "string", + value: "hello world", + }, + }); + }); + + await browser.url("https://testplane.io"); +}); +``` + + + +2. We will intercept all requests to the testplane.io resource and display a list of all loaded URLs: + +```typescript +it("should log all loaded urls", async ({ browser }) => { + browser.on("network.responseCompleted", networkResponse => + console.log("got response from url:", networkResponse.response.url), + ); + + await browser.url("https://testplane.io"); +}); +``` + + + +#### Displaying logs in the browser + +```typescript +it("should show browser console logs", async ({ browser }) => { + browser.on("log.entryAdded", entryAdded => console.log(JSON.stringify(entryAdded, null, 4))); + + await browser.execute(() => console.log("Hello Bidi")); +}); +``` + + + +#### Taking a screenshot of the entire page + +```typescript +import * as fs from "node:fs"; + +it("should screen full page", async ({ browser }) => { + await browser.url("https://www.npmjs.com/"); + + const tree = await browser.browsingContextGetTree({}); + const file = await browser.browsingContextCaptureScreenshot({ + context: tree.contexts[0].context, + origin: "document", + }); + + fs.writeFileSync("screenshot.png", Buffer.from(file.data, "base64")); +}); +``` + + + +### Conclusion + +While the BiDi protocol remains in the [Editor's Draft][editors-draft] stage, its potential as the future standard is already clear. +Major browsers like Firefox have taken decisive steps toward adoption, [announcing the deprecation of CDP protocol support starting in version 129][ff-deprecate-cdp]. + +By embracing BiDi protocol support, we're empowering our users with: + +- enhanced test automation capabilities beyond what WebDriver could offer; +- freedom from Puppeteer dependencies - eliminating the instability issues we've consistently observed in CDP-based implementations; +- Future-proof testing infrastructure by aligning with emerging industry standards + +We encourage you to upgrade to the latest Testplane version and share your experience. Should you encounter any challenges, our team is ready to assist through [GitHub issue][gh-issues] - just create a ticket and we'll help resolve it promptly! + +[testplane@8.27.0]: https://github.com/gemini-testing/testplane/releases/tag/v8.27.0 +[bidi]: https://w3c.github.io/webdriver-bidi/ +[webdriver]: https://www.w3.org/TR/webdriver1/ +[cdp]: https://chromedevtools.github.io/devtools-protocol/ +[webvider-vs-cdp]: https://testplane.io/ru/docs/v8/reference/webdriver-vs-cdp/ +[bidi-browsers-support]: https://wpt.fyi/results/webdriver/tests/bidi?label=master&label=stable&aligned +[bidi-commands]: https://webdriver.io/docs/api/webdriverBidi +[editors-draft]: https://www.w3.org/standards/types/#ED +[ff-deprecate-cdp]: https://fxdx.dev/deprecating-cdp-support-in-firefox-embracing-the-future-with-webdriver-bidi/ +[puppeteer]: https://pptr.dev/ +[gh-issues]: https://github.com/gemini-testing/testplane/issues diff --git a/static/video/blog/bidi/browser-logs-example.mp4 b/static/video/blog/bidi/browser-logs-example.mp4 new file mode 100644 index 0000000..18337e5 Binary files /dev/null and b/static/video/blog/bidi/browser-logs-example.mp4 differ diff --git a/static/video/blog/bidi/mock-network-request-example.mp4 b/static/video/blog/bidi/mock-network-request-example.mp4 new file mode 100644 index 0000000..504d08e Binary files /dev/null and b/static/video/blog/bidi/mock-network-request-example.mp4 differ diff --git a/static/video/blog/bidi/network-responses-example.mp4 b/static/video/blog/bidi/network-responses-example.mp4 new file mode 100644 index 0000000..26fb69e Binary files /dev/null and b/static/video/blog/bidi/network-responses-example.mp4 differ diff --git a/static/video/blog/bidi/screen-full-page-example.mp4 b/static/video/blog/bidi/screen-full-page-example.mp4 new file mode 100644 index 0000000..237cd34 Binary files /dev/null and b/static/video/blog/bidi/screen-full-page-example.mp4 differ