Best JavaScript code snippet using playwright-internal
fixtures.js
Source:fixtures.js
...132 if (options.scope === 'worker' && disallowWorkerFixtures) throw errorWithLocations(`Cannot use({ ${name} }) in a describe group, because it forces a new worker.\nMake it top-level in the test file or put in the configuration file.`, {133 location,134 name135 });136 const deps = fixtureParameterNames(fn, location);137 const registration = {138 id: '',139 name,140 location,141 scope: options.scope,142 fn,143 auto: options.auto,144 deps,145 super: previous146 };147 registrationId(registration);148 this.registrations.set(name, registration);149 }150 }151 this.digest = this.validate();152 }153 validate() {154 const markers = new Map();155 const stack = [];156 const visit = registration => {157 markers.set(registration, 'visiting');158 stack.push(registration);159 for (const name of registration.deps) {160 const dep = this.resolveDependency(registration, name);161 if (!dep) {162 if (name === registration.name) throw errorWithLocations(`Fixture "${registration.name}" references itself, but does not have a base implementation.`, registration);else throw errorWithLocations(`Fixture "${registration.name}" has unknown parameter "${name}".`, registration);163 }164 if (registration.scope === 'worker' && dep.scope === 'test') throw errorWithLocations(`Worker fixture "${registration.name}" cannot depend on a test fixture "${name}".`, registration, dep);165 if (!markers.has(dep)) {166 visit(dep);167 } else if (markers.get(dep) === 'visiting') {168 const index = stack.indexOf(dep);169 const regs = stack.slice(index, stack.length);170 const names = regs.map(r => `"${r.name}"`);171 throw errorWithLocations(`Fixtures ${names.join(' -> ')} -> "${dep.name}" form a dependency cycle.`, ...regs);172 }173 }174 markers.set(registration, 'visited');175 stack.pop();176 };177 const hash = crypto.createHash('sha1');178 const names = Array.from(this.registrations.keys()).sort();179 for (const name of names) {180 const registration = this.registrations.get(name);181 visit(registration);182 if (registration.scope === 'worker') hash.update(registration.id + ';');183 }184 return hash.digest('hex');185 }186 validateFunction(fn, prefix, location) {187 const visit = registration => {188 for (const name of registration.deps) visit(this.resolveDependency(registration, name));189 };190 for (const name of fixtureParameterNames(fn, location)) {191 const registration = this.registrations.get(name);192 if (!registration) throw errorWithLocations(`${prefix} has unknown parameter "${name}".`, {193 location,194 name: prefix,195 quoted: false196 });197 visit(registration);198 }199 }200 resolveDependency(registration, name) {201 if (name === registration.name) return registration.super;202 return this.registrations.get(name);203 }204}205exports.FixturePool = FixturePool;206class FixtureRunner {207 constructor() {208 this.testScopeClean = true;209 this.pool = void 0;210 this.instanceForId = new Map();211 }212 setPool(pool) {213 if (!this.testScopeClean) throw new Error('Did not teardown test scope');214 if (this.pool && pool.digest !== this.pool.digest) throw new Error('Digests do not match');215 this.pool = pool;216 }217 async teardownScope(scope) {218 let error; // Teardown fixtures in the reverse order.219 const fixtures = Array.from(this.instanceForId.values()).reverse();220 for (const fixture of fixtures) {221 if (fixture.registration.scope === scope) {222 try {223 await fixture.teardown();224 } catch (e) {225 if (error === undefined) error = e;226 }227 }228 }229 if (scope === 'test') this.testScopeClean = true;230 if (error !== undefined) throw error;231 }232 async resolveParametersAndRunHookOrTest(fn, workerInfo, testInfo, paramsStepCallback) {233 // Install all automatic fixtures.234 for (const registration of this.pool.registrations.values()) {235 const shouldSkip = !testInfo && registration.scope === 'test';236 if (registration.auto && !shouldSkip) await this.setupFixtureForRegistration(registration, workerInfo, testInfo);237 } // Install used fixtures.238 const names = fixtureParameterNames(fn, {239 file: '<unused>',240 line: 1,241 column: 1242 });243 const params = {};244 for (const name of names) {245 const registration = this.pool.registrations.get(name);246 const fixture = await this.setupFixtureForRegistration(registration, workerInfo, testInfo);247 params[name] = fixture.value;248 } // Report fixture hooks step as completed.249 paramsStepCallback === null || paramsStepCallback === void 0 ? void 0 : paramsStepCallback();250 return fn(params, testInfo || workerInfo);251 }252 async setupFixtureForRegistration(registration, workerInfo, testInfo) {253 if (registration.scope === 'test') this.testScopeClean = false;254 let fixture = this.instanceForId.get(registration.id);255 if (fixture) return fixture;256 fixture = new Fixture(this, registration);257 this.instanceForId.set(registration.id, fixture);258 await fixture.setup(workerInfo, testInfo);259 return fixture;260 }261 dependsOnWorkerFixturesOnly(fn, location) {262 const names = fixtureParameterNames(fn, location);263 for (const name of names) {264 const registration = this.pool.registrations.get(name);265 if (registration.scope !== 'worker') return false;266 }267 return true;268 }269}270exports.FixtureRunner = FixtureRunner;271const signatureSymbol = Symbol('signature');272function fixtureParameterNames(fn, location) {273 if (typeof fn !== 'function') return [];274 if (!fn[signatureSymbol]) fn[signatureSymbol] = innerFixtureParameterNames(fn, location);275 return fn[signatureSymbol];276}277function innerFixtureParameterNames(fn, location) {278 const text = fn.toString();279 const match = text.match(/(?:async)?(?:\s+function)?[^(]*\(([^)]*)/);280 if (!match) return [];281 const trimmedParams = match[1].trim();282 if (!trimmedParams) return [];283 const [firstParam] = splitByComma(trimmedParams);284 if (firstParam[0] !== '{' || firstParam[firstParam.length - 1] !== '}') throw errorWithLocations('First argument must use the object destructuring pattern: ' + firstParam, {285 location286 });...
index.js
Source:index.js
1// Main dmxus class2const EventEmitter = require('events');3const SerialPort = require('serialport');4const Driver = require('./drivers');5const Server = require('./server');6const profiles = require('./profiles');7class DMXUS extends EventEmitter {8 constructor(driverName, interfacePort = '', deviceCount = 96) {9 super();10 this.devices = [];11 this.driver = new (Driver(driverName))(interfacePort);12 this.driverName = driverName;13 this.groups = {};14 this.interfacePort = interfacePort;15 this.io = null;16 this.refreshRate = 25;17 this.server = null;18 this.timers = {};19 this.universe = Buffer.alloc(513, 0);20 this.initDevices(deviceCount);21 }22 // Initializes a webserver on the provided port (default 9090) with a reference to the dmxus instance23 initWebServer(port) {24 this.server = new Server(port, this);25 this.server.init();26 }27 // Initializes the device list with a default count of 96 devices28 initDevices(deviceCount) {29 for(let i = 0; i < deviceCount; i++) {30 this.devices[i] = {31 id: i + 1,32 deviceName: null,33 startAddress: null,34 profile: null,35 groups: [],36 }37 }38 }39 // Closes the port used by the current driver and re-initializes the interface40 reinitializeDriver(driverName, interfacePort) {41 this.driver.closePort();42 this.interfacePort = interfacePort;43 this.driverName = driverName;44 this.driver = new (Driver(driverName))(interfacePort);45 }46 // Accepts a deviceId, start address and a device profile object, and adds the device to the device list. Returns the device object.47 addDevice(deviceId, startAddress, profile, deviceName = '', groups = []) {48 const newDevice = {49 deviceName,50 startAddress,51 profile,52 groups53 };54 const deviceIndex = this.devices.findIndex(device => device.id === deviceId);55 this.devices[deviceIndex] = {...this.devices[deviceIndex], ...newDevice};56 return this.devices[deviceIndex];57 }58 // Accepts a DMX address and updates with the provided value.59 updateAddressValue(address, value) {60 this.universe[parseInt(address)] = value;61 this.update();62 }63 // Updates a single device at the provided start address with the provided parameters.64 updateDevice(deviceId, parameters) {65 const device = this.getDeviceById(deviceId);66 if(device.profile) {67 device.profile.parameters.forEach((parameter, index) => {68 this.universe[parseInt(device.startAddress) + index] = parameters[parameter];69 });70 }71 this.update();72 }73 // Changes the start address of the specified deviceId74 changeDeviceStartAddress(deviceId, startAddress) {75 const deviceIndex = this.devices.findIndex(device => device.id === deviceId);76 this.devices[deviceIndex].startAddress = startAddress;77 return this.devices[deviceIndex];78 }79 // Changes the fixture profile of the specified deviceId80 changeDeviceFixtureProfile(deviceId, fixtureProfileType) {81 const deviceIndex = this.devices.findIndex(device => device.id === deviceId);82 const fixtureProfileIndex = Object.keys(profiles).find(profile => profiles[profile].type === fixtureProfileType);83 this.devices[deviceIndex].profile = profiles[fixtureProfileIndex];84 return this.devices[deviceIndex];85 }86 // Updates all devices with the provided parameters.87 updateAllDevices(parameters) {88 this.devices.forEach(device => {89 this.updateDevice(device.id, parameters);90 });91 this.update();92 }93 // Returns the device with the provided deviceId94 getDeviceById(deviceId) {95 const deviceIndex = this.devices.findIndex(device => device.id === deviceId);96 return this.devices[deviceIndex];97 }98 // Returns devices which are a part of the provided group name99 getDevicesByGroup(group) {100 return this.devices.filter(device => device.groups.includes(group));101 }102 // Updates all devices in the provided group name with the provided parameters.103 updateAllDevicesInGroup(groupName, parameters, fadeIn = 0) {104 const oldDeviceParameterValues = {};105 const devices = this.getDevicesByGroup(groupName);106 if(devices) {107 let updateCount = 0;108 const targetUpdateCount = Math.round(fadeIn/this.refreshRate) || 1;109 const intervalTime = fadeIn/targetUpdateCount;110 clearInterval(this.timers[groupName]);111 devices.forEach(device => {112 oldDeviceParameterValues[device.id] = this.getDeviceParameterValues(device.id);113 });114 this.timers[groupName] = setInterval(() => {115 devices.forEach(device => {116 const nextUpdate = {};117 Object.keys(parameters).forEach(parameter => {118 const oldParamValue = oldDeviceParameterValues[device.id][parameter];119 const targetParamValue = parameters[parameter];120 nextUpdate[parameter] = Math.round(oldParamValue + (targetParamValue - oldParamValue) * (updateCount/targetUpdateCount));121 });122 this.updateDevice(device.id, nextUpdate);123 });124 if(updateCount === targetUpdateCount) {125 clearInterval(this.timers[groupName]);126 return true;127 }128 else {129 updateCount+=1;130 }131 }, intervalTime);132 }133 }134 // Returns the parameter values of the specified device135 getDeviceParameterValues(deviceId) {136 const device = this.getDeviceById(deviceId)137 const fixtureParameterValues = {};138 if(device.profile) {139 const fixtureParameterNames = device.profile.parameters;140 let parameterNameIndex = 0;141 for (let address = 0; address < fixtureParameterNames.length; address++) {142 fixtureParameterValues[fixtureParameterNames[parameterNameIndex]] = this.universe[device.startAddress + address];143 parameterNameIndex++;144 }145 }146 return fixtureParameterValues;147 }148 // Returns a list of serial ports as reported by the system149 async listPorts() {150 return await SerialPort.list();151 }152 // Returns the device list153 getDevices() {154 return this.devices;155 }156 // Returns the driver currently used by dmxus157 getDriverName() {158 return this.driverName;159 }160 // Returns the interfacePort currently used by dmxus161 getInterfacePort() {162 return this.interfacePort;163 }164 // Calls the update method on the driver with the current state of the universe then emits and update event with the universe state.165 update() {166 this.driver.send(this.universe);167 this.emit('update', this.universe.toJSON());168 }169 // Returns the JSON value of the current state of the universe170 getUniverseState() {171 return this.universe.toJSON();172 }173 // Returns the device profile of the provided profile name174 static getDeviceProfile(profileName) {175 return profiles[profileName];176 }177 // Returns a random integer value from 0-255178 static getRandom8BitValue() {179 return Math.floor(Math.random() * 255);180 }181}...
Using AI Code Generation
1const { fixtureParameterNames } = require('@playwright/test');2const { test } = require('@playwright/test');3const { expect } = require('@playwright/test');4const { test as base } = require('@playwright/test');5test.describe('fixtureParameterNames', () => {6 const fixture = base.extend({7 foo: async ({}, use) => {8 await use('bar');9 },10 bar: async ({}, use) => {11 await use('baz');12 },13 });14 test('should return names of all fixtures', async ({}) => {15 expect(fixtureParameterNames(fixture)).toEqual(['foo', 'bar']);16 });17});
Using AI Code Generation
1const { fixtureParameterNames } = require('@playwright/test/lib/test');2const { test } = require('@playwright/test');3const { fixtureParameterNames } = require('@playwright/test/lib/test');4const { test } = require('@playwright/test');5test.describe('Test', () => {6 test('Test', async ({ page }) => {7 const testParam = fixtureParameterNames(page);8 });9});10[MIT](LICENSE)
Using AI Code Generation
1const { fixtureParameterNames } = require('@playwright/test/lib/test');2const { test } = require('@playwright/test');3test.describe('Test', () => {4 test('test', async ({ page }) => {5 console.log(fixtureParameterNames);6 });7});
Using AI Code Generation
1const { expect } = require('@playwright/test');2const { fixtureParameterNames } = require('@playwright/test/lib/test');3test.describe('Test Suite', () => {4 test('Test 1', async ({ page }) => {5 expect(await page.title()).toBe('Wikipedia');6 });7 test('Test 2', async ({ page }) => {8 expect(await page.title()).toBe('Wikipedia');9 });10 test('Test 3', async ({ page }) => {11 expect(await page.title()).toBe('Wikipedia');12 });13 test('Test 4', async ({ page }) => {14 expect(await page.title()).toBe('Wikipedia');15 });16});17const { fixtureParameterNames } = require('@playwright/test/lib/test');18const { fixtureParameterNames } = require('@playwright/test/lib/test');19test.describe('Test Suite', () => {20 const user = test.fixtures.user.init();21 const browser = test.fixtures.browser.init();22 test('Test 1', async ({ page }) => {23 expect(fixtureParameterNames()).toEqual([]);24 expect(fixtureParameterNames('user')).toEqual(['user']);25 expect(fixtureParameterNames('user', 'browser')).toEqual(['user', 'browser']);26 });27});28const { fixtureParameter } = require('@playwright/test/lib/test');29const { fixtureParameter } = require('@playwright/test
Using AI Code Generation
1const { test, expect } = require("@playwright/test");2const { fixtureParameterNames } = require("@playwright/test/internal/fixtures");3test.describe("Internal API", () => {4 { name: "John", age: 30 },5 { name: "Mike", age: 25 },6 ];7 test.use({8 myFixture: fixtureParameterNames((...params) => {9 const [name, age] = params;10 return { name, age };11 }),12 });13 test("test", async ({ myFixture }) => {14 const { name, age } = myFixture;15 expect(name).toBe("John");16 expect(age).toBe(30);17 });18});
Using AI Code Generation
1const { test } = require('@playwright/test');2test.describe('My test', () => {3 test.use({4 });5 test('My test', async ({ page }) => {6 });7});8const { test } = require('@playwright/test');9test.describe('My test', () => {10 test.use({11 });12 test('My test', async ({ page }) => {13 });14});15const { test } = require('@playwright/test');16test.describe('My test', () => {17 test.use({18 });19 test('My test', async ({ page }) => {20 });21});22const { test } = require('@playwright/test');23test.describe('My test', () => {24 test.use({25 });26 test('My test', async ({ page }) => {27 });28});29const { test } = require('@playwright/test');30test.describe('My test', () => {31 test.use({
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!