Coder Social home page Coder Social logo

nicholasvuono / xk6-playwright Goto Github PK

View Code? Open in Web Editor NEW
41.0 5.0 9.0 116 KB

k6 extension that adds support for browser automation and end-to-end web testing using playwright-go

License: Apache License 2.0

Go 100.00%
k6 xk6 playwright browser-automation end-to-end-testing xk6-playwright

xk6-playwright's Introduction

ℹ️

This is not supported by the k6 team, and is worked on by a(n) individual contributor(s). It may also break in the future as both xk6 and playwright-go evolve. Any issues with the tool should be raised here.

It is not production ready yet, but definitely works as intended! Please enjoy the tool!



xk6-playwright

xk6 playwright


k6 extension that adds support for browser automation and end-to-end web testing using playwright-go

Special thanks to all the contributors over at k6 and playwright-go

Here's to open source!

GitHub license Go Report Card GitHub license




Origin Story

This project was inspired by xk6-browser. Having previously worked with playwright-go we thought it would be a great idea to create an alternative extension around browser automation for the k6 community. Thus xk6 playwright was born!

Note

Although xk6-browser is still experimental it is pretty awesome and now comes bundled with k6 v0.46.0 and greater! In case this doesn't fit all your needs, go check that out!


Build the executable

To build a k6 binary with this extension, first ensure you have the prerequisites:

  • Docker

Then:

  1. Build the binary:
docker run --rm -e GOOS=darwin -u "$(id -u):$(id -g)" -v "${PWD}:/xk6" \
grafana/xk6 build \
--with github.com/wosp-io/xk6-playwright

on Windows:

docker run --rm -e GOOS=windows -u "$(id -u):$(id -g)" -v "${PWD}:/xk6" `

grafana/xk6 build --output k6.exe `
--with github.com/wosp-io/xk6-playwright

This will create a k6 binary file in the current working directory. This file can be used exactly the same as the main k6 binary, with the addition of being able to run xk6-playwright scripts.

  1. For the tool to work, the browsers and OS dependencies must be installed locally. You can use the following command for this:
go run github.com/playwright-community/playwright-go/cmd/[email protected]  install --with-deps
  1. Run scripts that import k6/x/playwright with the new k6 binary. On Linux and macOS make sure this is done by referencing the file in the current directory, e.g. ./k6 run <script>, or you can place it somewhere in your PATH so that it can be run from anywhere on your system.

Simplest Working Example

import pw from 'k6/x/playwright';

export default function () {
  try {
    pw.launch();
    pw.newPage();
    pw.goto('https://test.k6.io/my_messages.php', { waitUntil: 'networkidle' });
    pw.waitForSelector("input[name='login']", { state: 'visible' });
  } catch (err) {
    console.log(err);
  } finally {
    pw.kill();
  }
}

Simplest Headful Example

import pw from 'k6/x/playwright';

export default function () {
  try {
    pw.launch({ headless: false });
    pw.newPage();
    pw.goto('https://test.k6.io/my_messages.php', { waitUntil: 'networkidle' });
    pw.waitForSelector("input[name='login']", { state: 'visible' });
  } catch (err) {
    console.log(err);
  } finally {
    pw.kill();
  }
}

Monitor Real User Metrics

import pw from 'k6/x/playwright';

export default function () {
  try {
    pw.launch()
    pw.newPage()
    pw.goto('https://test.k6.io/my_messages.php', { waitUntil: 'networkidle' });
    pw.waitForSelector("input[name='login']", { state: 'visible' });
    pw.type("input[name='login']", "admin")
    pw.sleep(500)//give a chance for the browser apis to catch up 

    //print out real user metrics of the google search page
    console.log(`First Paint: ${pw.firstPaint()}ms`)
    console.log(`First Contentful Paint: ${pw.firstContentfulPaint()}ms`)
    console.log(`Time to Minimally Interactive: ${pw.timeToMinimallyInteractive()}ms`)
    console.log(`First Input Delay: ${pw.firstInputDelay()}ms`)
  } catch (err) {
    console.log(err);
  } finally {
    pw.kill();
  }
}

Examples

More example can be found in the ./examples directory


Currently Supported Actions

Playwright API coverage is as follows:

Action Encompassed Playwright Function(s) Description
launch() Run() & Launch() starts playwright client and launches Chromium browser
connect() Run() & Connect() attaches playwright client to existing browser instance
newPage() NewPage() opens up a new page within the browser
goto() Goto() navigates to a specified url
waitForSelector() WaitForSelector() waits for an element to be on the page based on the provided selector
click() Click() clicks an element on the page based on the provided selector
type() Type() types in an 'input' element on the page based on the provided selector and string to be entered
pressKey() PressKey() simulates pressing a key, types in an 'input' element on the page based on a key to be entered
sleep() Sleep() waits for a specified amount of time in milliseconds
screenshot() Screenshot() attempts to take and save a png image of the current screen
focus() Focus() focuses a spcific element based on the provided selector
fill() Fill() fills an 'input' element on the page based on the provided selector and string to be entered
selectOptions() SelectOption() selects an 'input' element from a list or dropdown of options on the page based on the provided selector and values to be selected
check() Check() checks an element on the page based on the provided selector
uncheck() Uncheck() unchecks an element on the page based on the provided selector
dragAndDrop() DragAndDrop() drag an item from one place to another based on two selectors
evaluate() Evaluate() evaluate an expresion or function and get the return value
reload() Reload() reloads the current page
cookies() Cookies() get all the cookies available for the default browser context.
firstPaint() N/A this function is unique to xk6-playwright What is First Paint? captures the first paint metric of the current page milliseconds
firstContentfulPaint() N/A this function is unique to xk6-playwright What is First Contentful Paint? captures the first contentful paint metric of the current page milliseconds
timeToMinimallyInteractive() N/A this function is unique to xk6-playwright - This is based on the first input registerd on the current page - NOTE: this is how we personally like to determine when a page is minimally interactive. captures the time to minimally interactive metric of the current page milliseconds
firstInputDelay() N/A this function is unique to xk6-playwright What is First Input Delay? captures the first input delay metric of the current page in milliseconds

The above 'Encompassed Playwright Function(s)' will link to the playwright-go package documentation to give an in-depth overview of how these functions will behave from a low-level perspective.

If you would like a high-level perspective on how these actions work you will be better served with the Playwright API Documentation


Contributing

  1. Fork it (https://github.com/your-github-user/xk6-playwright/fork)
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Contributors

Nick Vuono - creator and maintainer

xk6-playwright's People

Contributors

egor-romanov avatar mstoykov avatar nicholasvuono avatar nickaccessos avatar selfdeceited avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

xk6-playwright's Issues

Update README

Hi,
I think it would be useful to update the README file with the following information:
For the tool to work, the browsers and OS dependencies must be installed locally. You can use the go run github.com/playwright-community/playwright-go/cmd/playwright@latest install --with-deps command for this.

Additionally, instead of: xk6 build --output xk6-playwright --with github.com/wosp-io/xk6-playwright better use xk6 build --output xk6-playwright.exe --with github.com/wosp-io/xk6-playwright. I know it's a small change, but if someone is using windows, the file will not be executed.

Unable to run on multiple threads

Hi, it is impossible to run a script on multiple threads. Below I attach the interior of the script to reproduce and the error from the console. It appears after 3 seconds after running.

import pw from 'k6/x/playwright';


export const options = {
  duration: '10m', 
  vus: 3
};

export default function () {
  pw.launch()
  pw.newPage()
  pw.goto("https://k6.io/")

  //print out real user metrics of the google serach page
  console.log(`First Paint: ${pw.firstPaint()}ms`)
  console.log(`First Contentful Paint: ${pw.firstContentfulPaint()}ms`)
  console.log(`Time to Minimally Interactive: ${pw.timeToMinimallyInteractive()}ms`)
  console.log(`First Input Delay: ${pw.firstInputDelay()}ms`)

  pw.kill()
}
node:events:368                                                                                                                                               
      throw er; // Unhandled 'error' eventd 0 interrupted iterations                                                                                               
      ^   [--------------------------------------] 3 VUs  00m03.5s/10m0s

Error: EPIPE: broken pipe, write
    at Socket._write (node:internal/net:55:25)
    at writeOrBuffer (node:internal/streams/writable:389:12)
    at _write (node:internal/streams/writable:330:10)
    at Socket.Writable.write (node:internal/streams/writable:334:10)
    at PipeTransport.send (C:\Users\figaro\AppData\Local\ms-playwright-go\1.20.0-beta-1647057403000\package\lib\protocol\transport.js:54:21)
    at DispatcherConnection.dispatcherConnection.onmessage (C:\Users\figaro\AppData\Local\ms-playwright-go\1.20.0-beta-1647057403000\package\lib\cli\driver.js:67:57)
    at DispatcherConnection.sendMessageToClient (C:\Users\figaro\AppData\Local\ms-playwright-go\1.20.0-beta-1647057403000\package\lib\dispatchers\dispatcher.js:187:10)
    at BrowserContextDispatcher._dispose (C:\Users\figaro\AppData\Local\ms-playwright-go\1.20.0-beta-1647057403000\package\lib\dispatchers\dispatcher.js:124:41)   
    at CRBrowserContext.<anonymous> (C:\Users\figaro\AppData\Local\ms-playwright-go\1.20.0-beta-1647057403000\package\lib\dispatchers\browserContextDispatcher.js:80:12)
    at CRBrowserContext.emit (node:events:402:35)
Emitted 'error' event on Socket instance at:
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  errno: -4047,
  sys.\xk6-playwright.exe run .\script.js

handling driver and browser downloads

Very interesting project. Thanks for writing and sharing this extension.

What would be the best way to deal with playwright's downloading of drivers and browsers?

playwright-go has the err := playwright.Install() convenience function, but could this function be integrated into a k6 extension somehow? Obviously the downloading part of the playwright dependencies should not have anything to do with any of the available modes of k6.

Multiple VUs

Hi,

I need to run a performance test for multiple VUs.

When I run my test for 2 VUs it opens two browsers (running headed for testing purposes) but it only interacts with one of the browsers.

It almost looks like it gets confused because two are running concurrently.

This is part of my code that needs to run and as I stated, only one of the browsers performs the actions.

pw.launch({ headless: false })
pw.newPage()
pw.goto(redirectUrl)

pw.waitForSelector("input[name='cvc']", {state: 'visible'})
pw.type("input[name='cvc']", cvv)

pw.waitForSelector("button[type='submit']", {state: 'visible'})
pw.click("button[type='submit']")

Needed to maintain listing in k6 Extensions Registry

We've recently updated the requirements for maintaining an extension within the listing on our site. As such, please address the following items to maintain your listing within the registry:

  • add an examples directory containing k6 test scripts making use of your extension
  • needs to build with a recent version of k6; minimum v0.43

For more information on these and other listing requirements, please take a look at the registry requirements.

Question - How the container gets the script file?

I think the command docker run --rm -i nickvuono/xk6-playwright run script.js is not enough for the beginners like me to starts with. Please could you tell me, how the script file will be uploaded to the container?

Similarly when I run the test by building it locally, the K6 metrics are not displaying. How do I view it?

          /\      |‾‾| /‾‾/   /‾‾/   
     /\  /  \     |  |/  /   /  /    
    /  \/    \    |     (   /   ‾‾\  
   /          \   |  |\  \ |  (‾)  | 
  / __________ \  |__| \__\ \_____/ .io

  execution: local
     script: script.js
     output: -

  scenarios: (100.00%) 1 scenario, 10 max VUs, 25s max duration (incl. graceful stop):
           * example_scenario: 200 iterations shared among 10 VUs (maxDuration: 10s, startTime: 10s, gracefulStop: 5s)

xk6-playright stucks on execution

Hello,
Tried to install according to the Readme.md and tried to run the first script - simplest-working-example.js, started running and got stuck.

kx6_playwright

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.