How to use setUpQueue method in wpt

Best JavaScript code snippet using wpt

index-test.js

Source:index-test.js Github

copy

Full Screen

1import test from 'ava'2import sinon from 'sinon'3import later from 'later'4import mockQueue from '../../tests/helpers/mockQueue'5import setupQueue from '.'6// Helpers7let clock8test.before(() => {9 clock = sinon.useFakeTimers(Date.now())10})11test.after.always(() => {12 clock.restore()13})14// Tests15test('should exist', (t) => {16 t.is(typeof setupQueue, 'function')17})18test('should make underlying queue accessible', (t) => {19 const redisQueue = mockQueue()20 const queue = setupQueue(redisQueue)21 t.is(queue.queue, redisQueue)22})23// Tests -- middleware24test('middleware should return response with status queued and queued id', async (t) => {25 const queue = setupQueue(mockQueue())26 const dispatch = sinon.stub().resolves({ status: 'ok' })27 const action = {28 type: 'GET',29 payload: { type: 'entry' },30 meta: { queue: true },31 }32 const expected = { status: 'queued', data: { id: 'queued1' } }33 const response = await queue.middleware(dispatch)(action)34 t.deepEqual(response, expected)35})36test('middleware should return response with status ok when queuedStatus is ok', async (t) => {37 const queue = setupQueue(mockQueue())38 const dispatch = sinon.stub().resolves({ status: 'ok' })39 const action = {40 type: 'GET',41 payload: { type: 'entry' },42 meta: { queue: true, queuedStatus: 'ok' },43 }44 const expected = { status: 'ok', data: { id: 'queued1' } }45 const response = await queue.middleware(dispatch)(action)46 t.deepEqual(response, expected)47})48test('middleware should queue queuable action', async (t) => {49 const queue = setupQueue(mockQueue())50 const push = sinon.spy(queue.queue, 'push')51 const dispatch = sinon.stub().resolves({ status: 'ok' })52 const action = {53 type: 'GET',54 payload: { type: 'entry' },55 meta: { queue: true },56 }57 const expected = {58 type: 'GET',59 payload: { type: 'entry' },60 meta: { queuedAt: Date.now() },61 }62 await queue.middleware(dispatch)(action)63 t.is(dispatch.callCount, 0)64 t.is(push.callCount, 1)65 t.deepEqual(push.args[0][0], expected)66 t.is(push.args[0][1], null)67 t.is(push.args[0][2], null)68})69test('middleware should dispatch unqueuable actions and return response', async (t) => {70 const queue = setupQueue(mockQueue())71 const push = sinon.spy(queue.queue, 'push')72 const dispatch = sinon.stub().resolves({ status: 'ok' })73 const action = { type: 'GET', payload: { type: 'entry' } }74 const expected = { status: 'ok' }75 const response = await queue.middleware(dispatch)(action)76 t.is(push.callCount, 0)77 t.is(dispatch.callCount, 1)78 t.deepEqual(dispatch.args[0][0], action)79 t.deepEqual(response, expected)80})81test('middleware should queue with timestamp', async (t) => {82 const queue = setupQueue(mockQueue())83 const push = sinon.spy(queue.queue, 'push')84 const action = {85 type: 'GET',86 payload: { type: 'entry' },87 meta: { queue: 1516113629153 },88 }89 await queue.middleware(() => {})(action)90 t.is(push.callCount, 1)91 t.is(push.args[0][1], 1516113629153)92})93test('middleware should queue with id', async (t) => {94 const queue = setupQueue(mockQueue())95 const push = sinon.spy(queue.queue, 'push')96 const action = {97 type: 'GET',98 payload: { type: 'entry' },99 meta: { queue: true, id: 'action1' },100 }101 await queue.middleware(() => {})(action)102 t.is(push.callCount, 1)103 t.is(push.args[0][2], 'action1')104})105test('middleware should return error response when underlying queue throws', async (t) => {106 const queue = setupQueue(mockQueue())107 sinon.stub(queue.queue, 'push').rejects(new Error('The horror'))108 const action = {109 type: 'GET',110 payload: { type: 'entry' },111 meta: { queue: true },112 }113 const expected = {114 status: 'error',115 error: 'Could not push to queue. Error: The horror',116 }117 const response = await queue.middleware(() => {})(action)118 t.deepEqual(response, expected)119})120test('middleware should reschedule repeating action', async (t) => {121 const queue = setupQueue(mockQueue())122 const push = sinon.spy(queue.queue, 'push')123 const schedule = { schedules: [{ h: [2] }] }124 const action = {125 type: 'GET',126 payload: { type: 'entry' },127 meta: {128 queue: false,129 schedule,130 },131 }132 const nextTime = later.schedule(schedule).next().getTime()133 await queue.middleware(() => {})(action)134 t.is(push.callCount, 1)135 const nextAction = push.args[0][0]136 t.is(nextAction.type, 'GET')137 t.is(push.args[0][1], nextTime)138})139test('middleware should not reschedule when schedule is ended', async (t) => {140 const queue = setupQueue(mockQueue())141 const push = sinon.spy(queue.queue, 'push')142 const schedule = { schedules: [{ Y_b: [2015] }] }143 const action = {144 type: 'GET',145 payload: { type: 'entry' },146 meta: {147 queue: false,148 schedule,149 },150 }151 await queue.middleware(() => {})(action)152 t.is(push.callCount, 0)153})154test('middleware should not reschedule with invalid schedule definition', async (t) => {155 const queue = setupQueue(mockQueue())156 const push = sinon.spy(queue.queue, 'push')157 const action = {158 type: 'GET',159 payload: { type: 'entry' },160 meta: {161 queue: false,162 schedule: 'at 42 am',163 },164 }165 await queue.middleware(() => {})(action)166 t.is(push.callCount, 0)167})168// Tests -- setDispatch and dequeueing169test('should subscribe underlying queue and dispatch', async (t) => {170 const dispatch = sinon.stub().resolves({ status: 'ok' })171 const action = { type: 'GET', payload: { type: 'entry' } }172 const queue = setupQueue(mockQueue())173 await queue.setDispatch(dispatch)174 await queue.queue.push(action) // Pushes directly to subscribed handler175 t.is(dispatch.callCount, 1)176 t.deepEqual(dispatch.args[0][0], action)177})178test('should not subscribe unless setDispatch is called', async (t) => {179 const action = { type: 'GET', payload: { type: 'entry' } }180 const mock = mockQueue()181 sinon.spy(mock, 'subscribe')182 const queue = setupQueue(mock)183 await queue.queue.push(action) // Pushes directly to subscribed handler184 t.is(mock.subscribe.callCount, 0)185})186test('should not subscribe twice', async (t) => {187 const dispatch = async () => ({ status: 'ok' })188 const mock = mockQueue()189 sinon.spy(mock, 'subscribe')190 const queue = setupQueue(mock)191 await queue.setDispatch(dispatch)192 await queue.setDispatch(dispatch)193 t.is(mock.subscribe.callCount, 1)194})195test('should not subscribe when called with no-function', async (t) => {196 const mock = mockQueue()197 sinon.spy(mock, 'subscribe')198 const queue = setupQueue(mock)199 await queue.setDispatch(null)200 t.is(mock.subscribe.callCount, 0)201})202test('should not throw when no dispatch function', async (t) => {203 const action = { type: 'GET', payload: { type: 'entry' } }204 const queue = setupQueue(mockQueue())205 await t.notThrows(() => queue.queue.push(action))206})207test('should throw when queue.subscribe rejects', async (t) => {208 const dispatch = sinon.stub().resolves({ status: 'ok' })209 const mock = mockQueue()210 sinon.stub(mock, 'subscribe').rejects('')211 const queue = setupQueue(mock)212 await t.throwsAsync(queue.setDispatch(dispatch))213})214// Tests -- schedule215test('schedule should exist', (t) => {216 const queue = setupQueue(mockQueue())217 t.is(typeof queue.schedule, 'function')218})219test('schedule should enqueue scheduled action', async (t) => {220 const queue = setupQueue(mockQueue())221 const push = sinon.spy(queue.queue, 'push')222 const defs = [223 { schedule: 'at 2:00 am', action: { type: 'SYNC' } },224 { schedule: { h: [3] }, action: { type: 'EXPIRE' } },225 ]226 const expected = {227 type: 'SYNC',228 meta: {229 id: null,230 schedule: {231 exceptions: [],232 schedules: [{ t: [7200] }],233 },234 queuedAt: Date.now(),235 },236 }237 await queue.schedule(defs)238 t.is(push.callCount, 2)239 t.deepEqual(push.args[0][0], expected)240 t.true(Number.isInteger(push.args[0][1]))241 t.truthy(push.args[1][0])242})243test('should return response objects with status queued', async (t) => {244 const queue = setupQueue(mockQueue())245 const defs = [246 { id: 'sched1', schedule: 'at 2:00 am', action: { type: 'SYNC' } },247 { id: 'sched2', schedule: { h: [3] }, action: { type: 'EXPIRE' } },248 ]249 const expected = [250 { status: 'queued', data: { id: 'sched1' } },251 { status: 'queued', data: { id: 'sched2' } },252 ]253 const ret = await queue.schedule(defs)254 t.deepEqual(ret, expected)255})256test('should return response objects with status error when invalid schedule', async (t) => {257 const queue = setupQueue(mockQueue())258 const defs = [259 { id: 'sched1', schedule: 'at 42 am', action: { type: 'SYNC' } },260 ]261 const ret = await queue.schedule(defs)262 t.is(ret.length, 1)263 t.is(ret[0].status, 'error')264})265test('should accept single schedule definition object', async (t) => {266 const queue = setupQueue(mockQueue())267 const defs = {268 id: 'sched1',269 schedule: 'at 2:00 am',270 action: { type: 'SYNC' },271 }272 const expected = [{ status: 'queued', data: { id: 'sched1' } }]273 const ret = await queue.schedule(defs)274 t.deepEqual(ret, expected)...

Full Screen

Full Screen

SystemState.js

Source:SystemState.js Github

copy

Full Screen

1const debug = require('debug')('modularity');2const Module = require('./Module');3const Semaphore = require('./Semaphore');4/**5 * A container for modules. Holds system state. It's a module itself.6 */7class SystemState extends Module {8 constructor() {9 super();10 this.knownClasses = {};11 this.setupQueue = [];12 this.createdNonExclusiveObjects = [];13 this.semaphore = new Semaphore('SystemState');14 }15 /**16 * Add a module to the known classes library.17 * @param classObject The class18 * @param [overrideName] Class name override if encountering issues with transpiled solutions.19 */20 addModuleClass(classObject, overrideName = null) {21 if (!classObject) {22 throw Error(23 `The class object provided is falsy. Make sure to pass a valid class or that the variable ` +24 `does not depend on a circular reference and cannot be transipled correctly.`25 );26 }27 const name = overrideName || classObject.name;28 if (!name) {29 throw Error(`Could not infer class name from provided object. Please provide an alias manually.`);30 }31 if (this.knownClasses[name]) {32 throw Error(`Tried to addModuleClass for an already known class or alias (${name}).`);33 }34 this.knownClasses[name] = classObject;35 }36 /**37 * Prepare module instances but don't initialize them.38 */39 bootstrap(requirements) {40 debug('Bootstrapping system');41 return this.semaphore.oneAtATimeSync(() => {42 const result = {};43 const setupQueue = [];44 const ops = Object.keys(requirements).map(prop => ['resolve', requirements[prop], prop]);45 while (ops.length > 0) {46 const [op, ...args] = ops.shift();47 switch (op) {48 case 'resolve':49 debug('Resolving bootstrap subject ' + args[1]);50 const instance = this.constructModule(args[0]);51 if (!instance.moduleIsExclusive()) {52 this.createdNonExclusiveObjects.push(instance);53 }54 result[args[1]] = instance;55 setupQueue.push(instance);56 ops.push(['inject', instance]);57 break;58 case 'inject':59 // TODO: Ability to request unique?60 const dependencies = [];61 let requestFnLegal = true;62 const requestFn = nameOrClassObject => {63 if (!requestFnLegal) {64 throw Error(`Invalid injection request call. Bootstrap was finished.`);65 }66 // Must return an instance67 // Check if already have an instance68 const ResolvedClass = this.resolveClass(nameOrClassObject);69 debug(`Requested an instance of ${ResolvedClass.name}`);70 const existing = this.createdNonExclusiveObjects.find(obj => obj instanceof ResolvedClass);71 if (existing && !existing.moduleIsExclusive()) {72 debug(`Requested instance is already built and non-exclusive`);73 dependencies.push(existing);74 return existing;75 }76 // Build77 const created = this.constructModule(nameOrClassObject);78 if (created.moduleIsExclusive()) {79 debug(`Created instance of ${ResolvedClass.name} is exclusive and will not be reused`);80 } else {81 this.createdNonExclusiveObjects.push(created);82 }83 setupQueue.push(created);84 ops.push(['inject', created]);85 dependencies.push(created);86 return created;87 };88 args[0].modulePerformInjection(requestFn);89 requestFnLegal = false;90 break;91 /* istanbul ignore next */92 default:93 throw Error('Internal error - unknown op: ' + op);94 }95 }96 debug('Done Bootstrapping, ready to set up');97 this.setupQueue = [...this.setupQueue, ...setupQueue];98 this.invertSetupModulesList();99 if (Array.isArray(requirements)) {100 return Object.values(result);101 }102 return result;103 });104 }105 constructModule(nameOrClassObject) {106 const ResolvedClass = this.resolveClass(nameOrClassObject);107 debug(`Attempting construction of class ${ResolvedClass.name}`);108 const instance = new ResolvedClass();109 instance.setSystemStateReference(this);110 return instance;111 }112 /**113 * Return the class of a given name. If the argument is already a class then return it.114 * @param {*} nameOrClassObject115 */116 resolveClass(nameOrClassObject) {117 let normalizedName = nameOrClassObject;118 if (typeof nameOrClassObject === 'function') {119 normalizedName = nameOrClassObject.name;120 }121 if (typeof normalizedName === 'string') {122 const translated = this.knownClasses[normalizedName];123 if (translated) {124 return translated;125 }126 throw Error('Unable to resolve class ' + normalizedName);127 } else {128 throw Error('Unable to resolve class of a name that is not a string');129 }130 }131 /**132 * Setup bootstrapped modules.133 */134 async setup() {135 debug('Setup starting');136 return this.semaphore.oneAtATime(async () => {137 let leftovers = [...this.setupQueue];138 const newSetupQueue = [];139 const postSetupQueue = [];140 while (leftovers.length > 0) {141 const newLeftovers = [];142 for (const mod of leftovers) {143 debug('Setup of module ' + mod.constructor.name);144 try {145 mod.assertDependenciesSetup();146 } catch (err) {147 newLeftovers.push(mod);148 continue;149 }150 if (!mod.moduleWasSetUp()) {151 await mod.setup();152 postSetupQueue.push(mod);153 }154 newSetupQueue.push(mod);155 if (!mod.moduleWasSetUp()) {156 throw Error(157 `Module ${mod.constructor.name} does not properly implement the setup method. ` +158 `Make sure you're calling super.setup()`159 );160 }161 }162 if (newLeftovers.length >= leftovers.length) {163 const errs = [];164 for (const mod of newLeftovers) {165 try {166 mod.assertDependenciesSetup();167 } catch (err) {168 errs.push(err);169 }170 }171 throw Error(172 `Failed to initialize ${newLeftovers.length} modules. The error messages were:\n${errs.join(173 '\n'174 )}`175 );176 }177 leftovers = newLeftovers;178 }179 for (const mod of postSetupQueue) {180 debug(`postSetup of module ` + mod.constructor.name);181 await mod.postSetup();182 }183 this.setupQueue = newSetupQueue;184 });185 }186 /**187 * Teardown all modules. Cleans up references.188 * Must call bootstrap to use setup again.189 */190 async teardown() {191 return this.semaphore.oneAtATime(async () => {192 this.invertSetupModulesList();193 for (const mod of this.setupQueue) {194 debug('Teardown of module ' + mod.constructor.name);195 await mod.teardown();196 if (mod.moduleWasSetUp()) {197 throw Error(198 `Invalid teardown implementation for module ${mod.constructor.name}. ` +199 `Make sure super.teardown is called.`200 );201 }202 }203 this.setupQueue = [];204 this.createdNonExclusiveObjects = [];205 });206 }207 invertSetupModulesList() {208 this.setupQueue = this.setupQueue.map((_, i, self) => self[self.length - i - 1]); // Invert209 }210 getModulesList() {211 return [...this.setupQueue];212 }213}...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1import compileWasm from '../pkg/lucid_suggest_wasm'2const DEFAULT_LIMIT = 103var NEXT_ID = 14export class LucidSuggest {5 constructor() {6 this.id = NEXT_ID++7 this.limit = DEFAULT_LIMIT8 this.records = new Map()9 this.setupQueue = compileWasm10 this.setup(wasm => {11 wasm.create_store(this.id)12 wasm.highlight_with(this.id, '{{', '}}')13 })14 }15 setup(fn) {16 this.setupQueue = this.setupQueue.then(async wasm => {17 await fn(wasm)18 this.setupQueue = Promise.resolve(wasm)19 return wasm20 })21 return this.setupQueue22 }23 destroy() {24 const oldQueue = this.setupQueue25 this.setupQueue = Promise.reject(new Error('Suggest destroyed'))26 oldQueue.then(wasm => {27 wasm.destroy_store(this.id)28 })29 }30 addRecords(records) {31 return this.setup(wasm => {32 for (const record of records) {33 const {id, title, rating} = record34 wasm.add_record(this.id, id, title, rating || 0)35 this.records.set(id, record)36 }37 })38 }39 setLimit(limit) {40 return this.setup(wasm => {41 this.limit = limit42 wasm.set_limit(this.id, this.limit)43 })44 }45 async search(query) {46 const wasm = await this.setupQueue47 wasm.run_search(this.id, query)48 const ids = wasm.get_result_ids(this.id)49 const titles = wasm.get_result_titles(this.id).split('\0')50 const hits = []51 for (let i = 0; i < ids.length; i++) {52 const id = ids[i]53 const title = titles[i]54 const record = this.records.get(id)55 if (!record) throw new Error(`Missing record ${id}`)56 if (!title) throw new Error(`Missing title for ${id}`)57 hits.push(new Hit(title, record))58 }59 return hits60 }61}62export function highlight(hit, left, right) {63 let result = ''64 for (const {text, highlight} of hit.chunks) {65 result += highlight66 ? left + text + right67 : text68 }69 return result70}71export class Hit {72 constructor(title, record) {73 this.record = record74 this.chunks = toChunks(title)75 }76 get title() {77 return highlight(this, '[', ']')78 }79}80function toChunks(title) {81 const split = title.split(/{{|}}/g)82 const chunks = []83 for (let i = 0; i < split.length; i++) {84 if (split[i] != '') {85 chunks.push({86 text: split[i],87 highlight: i % 2 === 1,88 })89 }90 }91 return chunks...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt.js');2var wpt = new WebPageTest('www.webpagetest.org', 'A.12345678901234567890123456789012');3wpt.setUpQueue(function (err, data) {4 if (err) {5 console.log(err);6 } else {7 console.log(data);8 }9});10WebPageTest.prototype.setUpQueue = function (callback) {11 var url = '/runtest.php?f=json&k=' + this.apiKey;12 this.get(url, callback);13};14WebPageTest.prototype.get = function (url, callback) {15 var options = {16 };17 var req = http.get(options, function (res) {18 var body = '';19 res.on('data', function (chunk) {20 body += chunk;21 });22 res.on('end', function () {23 callback(null, body);24 });25 });26 req.on('error', function (e) {27 callback(e, null);28 });29};30http.get = function (options, callback) {31 var req = new ClientRequest(options);32 req.on('response', callback);33 req.end();34 return req;35};36function ClientRequest(options) {37 OutgoingMessage.call(this);38 this._storeHeader(this.method + ' ' + this.path + ' HTTP/1.1\r\n', 'ascii');39 this.shouldKeepAlive = false;40 if (options.host) {41 var hostHeader = 'Host: ' + options.host;42 if (options.port && options.port !== 80) {43 hostHeader += ':' + options.port;44 }45 hostHeader += '\r\n';46 this._storeHeader(hostHeader, 'ascii');47 }48 this.useChunkedEncodingByDefault = true;49 this._pendingData = null;50 this._pendingEncoding = '';51}52ClientRequest.prototype = Object.create(OutgoingMessage.prototype);

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful