Skip to content

Commit

Permalink
Playwright with Automate support (#355)
Browse files Browse the repository at this point in the history
* Playwright with Automate support

* Adding specs

* Adding coverage

* Adding coverage

* Updating cache changes

* Adding readme for POA
  • Loading branch information
rishigupta1599 authored Jun 17, 2024
1 parent 1922eaa commit d8543d5
Show file tree
Hide file tree
Showing 12 changed files with 865 additions and 98 deletions.
1 change: 1 addition & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
extends: standard
parser: babel-eslint
rules:
prefer-const: off
no-unused-expressions: off
Expand Down
87 changes: 87 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,90 @@ $ percy exec -- node script.js
- `page` (**required**) - A `playwright` page instance
- `name` (**required**) - The snapshot name; must be unique to each snapshot
- `options` - [See per-snapshot configuration options](https://www.browserstack.com/docs/percy/take-percy-snapshots/overview#per-snapshot-configuration)


## Percy on Automate

## Usage

```javascript
const { chromium } = require('playwright');
const percyScreenshot = require('@percy/playwright');

const desired_cap = {
'browser': 'chrome',
'browser_version': 'latest',
'os': 'osx',
'os_version': 'ventura',
'name': 'Percy Playwright PoA Demo',
'build': 'percy-playwright-javascript-tutorial',
'browserstack.username': 'username',
'browserstack.accessKey': 'accesskey'
};

(async () => {
const cdpUrl = `wss://cdp.browserstack.com/playwright?caps=${encodeURIComponent(JSON.stringify(desired_cap))}`;
const browser = await chromium.connect(cdpUrl);
const page = await browser.newPage();
await page.goto("https://percy.io/");
await percyScreenshot(page, 'Screenshot 1');

// Options for percyScreenshot
// await percyScreenshot(page, 'Screenshot 1', {
// fullPage: true,
// percyCSS: 'body { background: red; }',
// ignoreRegionSelectors: ['#ignore-this'],
// customIgnoreRegions: [{ top: 10, right: 10, bottom: 120, left: 10 }],
// });

await browser.close();
})();
```

## Configuration

`percyScreenshot(page, name[, options])`

- `page` (**required**) - A `playwright` page instance
- `name` (**required**) - The snapshot name; must be unique to each snapshot
- `options` (**optional**) - There are various options supported by percyScreenshot to server further functionality.
- `sync` - Boolean value by default it falls back to `false`, Gives the processed result around screenshot [From CLI v1.28.0-beta.0+]
- `fullPage` - Boolean value by default it falls back to `false`, Takes full page screenshot [From CLI v1.27.6+]
- `freezeAnimatedImage` - Boolean value by default it falls back to `false`, you can pass `true` and percy will freeze image based animations.
- `freezeImageBySelectors` - List of selectors. Images will be freezed which are passed using selectors. For this to work `freezeAnimatedImage` must be set to true.
- `freezeImageByXpaths` - List of xpaths. Images will be freezed which are passed using xpaths. For this to work `freezeAnimatedImage` must be set to true.
- `percyCSS` - Custom CSS to be added to DOM before the screenshot being taken. Note: This gets removed once the screenshot is taken.
- `ignoreRegionXpaths` - List of xpaths. elements in the DOM can be ignored using xpath
- `ignoreRegionSelectors` - List of selectors. elements in the DOM can be ignored using selectors.
- `customIgnoreRegions` - List of custom objects. elements can be ignored using custom boundaries. Just passing a simple object for it like below.
- example: ```{top: 10, right: 10, bottom: 120, left: 10}```
- In above example it will draw rectangle of ignore region as per given coordinates.
- `top` (int): Top coordinate of the ignore region.
- `bottom` (int): Bottom coordinate of the ignore region.
- `left` (int): Left coordinate of the ignore region.
- `right` (int): Right coordinate of the ignore region.
- `considerRegionXpaths` - List of xpaths. elements in the DOM can be considered for diffing and will be ignored by Intelli Ignore using xpaths.
- `considerRegionSelectors` - List of selectors. elements in the DOM can be considered for diffing and will be ignored by Intelli Ignore using selectors.
- `customConsiderRegions` - List of custom objects. elements can be considered for diffing and will be ignored by Intelli Ignore using custom boundaries
- example: ```{top: 10, right: 10, bottom: 120, left: 10}```
- In above example it will draw rectangle of consider region will be drawn.
- Parameters:
- `top` (int): Top coordinate of the consider region.
- `bottom` (int): Bottom coordinate of the consider region.
- `left` (int): Left coordinate of the consider region.
- `right` (int): Right coordinate of the consider region.

### Creating Percy on automate build
Note: Automate Percy Token starts with `auto` keyword. The command can be triggered using `exec` keyword.
```sh-session
$ export PERCY_TOKEN=[your-project-token]
$ percy exec -- [playwright test command]
[percy] Percy has started!
[percy] [Playwright example] : Starting automate screenshot ...
[percy] Screenshot taken "Playwright example"
[percy] Stopping percy...
[percy] Finalized build #1: https://percy.io/[your-project]
[percy] Done!
```

Refer to docs here: [Percy on Automate](https://www.browserstack.com/docs/percy/integrate/functional-and-visual)
51 changes: 51 additions & 0 deletions cache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
class Cache {
static CACHE = {};
static CACHE_TIMEOUT = 5 * 60; // 300 seconds
static TIMEOUT_KEY = 'last_access_time';

// Caching Keys
static sessionDetails = 'sessionDetails';

static checkTypes(sessionId, property) {
if (typeof sessionId !== 'string') {
throw new TypeError('Argument sessionId should be a string');
}
if (typeof property !== 'string') {
throw new TypeError('Argument property should be a string');
}
}

static setCache(sessionId, property, value) {
this.checkTypes(sessionId, property);
let session = this.CACHE[sessionId] || {};
session[this.TIMEOUT_KEY] = Math.floor(Date.now() / 1000);
session[property] = value;
this.CACHE[sessionId] = session;
}

static getCache(sessionId, property) {
this.cleanupCache();
this.checkTypes(sessionId, property);
/* Below line is covered even then nyc is not able to consider it as coverage */
/* istanbul ignore next */
let session = this.CACHE[sessionId] || {};
return session[property] || null;
}

static cleanupCache() {
let now = Math.floor(Date.now() / 1000);
for (let sessionId in this.CACHE) {
let session = this.CACHE[sessionId];
let timestamp = session[this.TIMEOUT_KEY];
if (now - timestamp >= this.CACHE_TIMEOUT) {
this.CACHE[sessionId] = {
[this.sessionDetails]: session[this.sessionDetails]
};
}
}
}
}

module.exports = {
Cache
};
37 changes: 35 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
const utils = require('@percy/sdk-utils');
const { Utils } = require('./utils');

// Collect client and environment information
const sdkPkg = require('./package.json');
const playwrightPkg = require('playwright/package.json');
const CLIENT_INFO = `${sdkPkg.name}/${sdkPkg.version}`;
const ENV_INFO = `${playwrightPkg.name}/${playwrightPkg.version}`;
const log = utils.logger('playwright');

// Take a DOM snapshot and post it to the snapshot endpoint
async function percySnapshot(page, name, options) {
if (!page) throw new Error('A Playwright `page` object is required.');
if (!name) throw new Error('The `name` argument is required.');
if (!(await utils.isPercyEnabled())) return;
let log = utils.logger('playwright');

try {
// Inject the DOM serialization script
Expand Down Expand Up @@ -40,4 +41,36 @@ async function percySnapshot(page, name, options) {
}
}

module.exports = percySnapshot;
// Takes Playwright screenshot with Automate
async function percyScreenshot(page, name, options) {
if (!page) throw new Error('A Playwright `page` object is required.');
if (!name) throw new Error('The `name` argument is required.');
if (!(await utils.isPercyEnabled())) return;
if (Utils.projectType() !== 'automate') {
throw new Error('Invalid function call - percyScreenshot(). Please use percySnapshot() function for taking screenshot. percyScreenshot() should be used only while using Percy with Automate. For more information on usage of PercySnapshot(), refer doc for your language https://docs.percy.io/docs/end-to-end-testing');
}

try {
const sessionDetails = await Utils.sessionDetails(page);
const sessionId = sessionDetails.hashed_id;
const pageGuid = page._guid;
const frameGuid = page._mainFrame._guid;
const data = {
environmentInfo: ENV_INFO,
clientInfo: CLIENT_INFO,
sessionId: sessionId,
pageGuid: pageGuid,
frameGuid: frameGuid,
framework: 'playwright',
snapshotName: name,
options
};
const response = await Utils.captureAutomateScreenshot(data);
return response?.body?.data;
} catch (err) {
log.error(`Could not take percy screenshot "${name}"`);
log.error(err);
}
}

module.exports = { percySnapshot, percyScreenshot, CLIENT_INFO, ENV_INFO };
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"devDependencies": {
"@percy/cli": "^1.28.2",
"@playwright/test": "^1.24.2",
"babel-eslint": "^10.1.0",
"cross-env": "^7.0.2",
"eslint": "^7.18.0",
"eslint-config-standard": "^16.0.2",
Expand All @@ -43,6 +44,7 @@
"eslint-plugin-standard": "^5.0.0",
"nyc": "^15.1.0",
"playwright": "^1.24.2",
"sinon": "^18.0.0",
"tsd": "^0.25.0"
}
}
107 changes: 107 additions & 0 deletions tests/cache.spec.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { test, expect } from '@playwright/test';
import { Cache } from '../cache.js';
import sinon from 'sinon';

test.describe('Cache', () => {
test.afterEach(() => {
sinon.restore();
Cache.cleanupCache();
});

test.describe('setCache', () => {
test('should set cache correctly', () => {
const sessionId = 'mockSessionId';
const property = 'mockProperty';
const value = 'mockValue';
const now = 1234567890;

// Stub Date.now() to return a fixed value
sinon.stub(Date, 'now').returns(now * 1000);

Cache.setCache(sessionId, property, value);

expect(Cache.CACHE[sessionId]).toEqual({
[Cache.TIMEOUT_KEY]: now,
[property]: value
});
});

test('should initialize session to empty object if not found in CACHE', () => {
const sessionId = 'nonExistentSessionId';
const property = 'mockProperty';
sinon.stub(Date, 'now').returns(1234567890 * 1000);

Cache.setCache(sessionId, property, 'mockValue');

expect(Cache.CACHE[sessionId]).toEqual({ [Cache.TIMEOUT_KEY]: 1234567890, [property]: 'mockValue' });
});
});

test.describe('getCache', () => {
test('should return null if cache entry does not exist', () => {
const sessionId = 'nonExistentSessionId';
const property = 'mockProperty';
const value = Cache.getCache(sessionId, property);

expect(value).toBeNull();
});

test('should return cached value if cache entry exists', () => {
const sessionId = 'existingSessionId';
const property = 'mockProperty';
const cachedValue = 'cachedValue';
const now = 1234567890;
sinon.stub(Cache, 'cleanupCache');

Cache.CACHE[sessionId] = {
[Cache.TIMEOUT_KEY]: now,
[property]: cachedValue
};

const value = Cache.getCache(sessionId, property);

expect(value).toEqual(cachedValue);
});
});

test.describe('cleanupCache', () => {
test('should remove expired cache entries', () => {
const sessionId1 = 'expiredSessionId';
const sessionId2 = 'validSessionId';
const property = 'mockProperty';
const now = 1234567890;
const expiredTime = now - (Cache.CACHE_TIMEOUT + 1);
const validTime = now - (Cache.CACHE_TIMEOUT - 1);

Cache.CACHE[sessionId1] = {
[Cache.TIMEOUT_KEY]: expiredTime,
[property]: 'expiredValue'
};
Cache.CACHE[sessionId2] = {
[Cache.TIMEOUT_KEY]: validTime,
[property]: 'validValue'
};

sinon.stub(Date, 'now').returns(now * 1000);

Cache.cleanupCache();

expect(Cache.CACHE[sessionId1]).toEqual({ sessionDetails: undefined });
expect(Cache.CACHE[sessionId2]).toBeDefined();
});
});

test.describe('checkTypes', () => {
test('should throw TypeError if sessionId is not a string', () => {
expect(() => Cache.checkTypes(123, 'property')).toThrowError(TypeError, 'Argument sessionId should be a string');
});

test('should throw TypeError if property is not a string', () => {
expect(() => Cache.checkTypes('sessionId', 123)).toThrowError(TypeError, 'Argument property should be a string');
});

test('should not throw any error if sessionId and property are strings', () => {
expect(() => Cache.checkTypes('sessionId', 'property')).not.toThrowError(TypeError);
});
});
});
Loading

0 comments on commit d8543d5

Please sign in to comment.