How to use abortRequests method in wpt

Best JavaScript code snippet using wpt

general.any.js

Source:general.any.js Github

copy

Full Screen

...6const BODY_METHODS = ['arrayBuffer', 'blob', 'formData', 'json', 'text'];7// This is used to close connections that weren't correctly closed during the tests,8// otherwise you can end up running out of HTTP connections.9let requestAbortKeys = [];10function abortRequests() {11 const keys = requestAbortKeys;12 requestAbortKeys = [];13 return Promise.all(14 keys.map(key => fetch(`../resources/stash-put.py?key=${key}&value=close`))15 );16}17const hostInfo = get_host_info();18const urlHostname = hostInfo.REMOTE_HOST;19promise_test(async t => {20 const controller = new AbortController();21 const signal = controller.signal;22 controller.abort();23 const fetchPromise = fetch('../resources/data.json', { signal });24 await promise_rejects_dom(t, "AbortError", fetchPromise);25}, "Aborting rejects with AbortError");26promise_test(async t => {27 const controller = new AbortController();28 const signal = controller.signal;29 controller.abort();30 const url = new URL('../resources/data.json', location);31 url.hostname = urlHostname;32 const fetchPromise = fetch(url, {33 signal,34 mode: 'no-cors'35 });36 await promise_rejects_dom(t, "AbortError", fetchPromise);37}, "Aborting rejects with AbortError - no-cors");38// Test that errors thrown from the request constructor take priority over abort errors.39// badRequestArgTests is from response-error.js40for (const { args, testName } of badRequestArgTests) {41 promise_test(async t => {42 try {43 // If this doesn't throw, we'll effectively skip the test.44 // It'll fail properly in ../request/request-error.html45 new Request(...args);46 }47 catch (err) {48 const controller = new AbortController();49 controller.abort();50 // Add signal to 2nd arg51 args[1] = args[1] || {};52 args[1].signal = controller.signal;53 await promise_rejects_js(t, TypeError, fetch(...args));54 }55 }, `TypeError from request constructor takes priority - ${testName}`);56}57test(() => {58 const request = new Request('');59 assert_true(Boolean(request.signal), "Signal member is present & truthy");60 assert_equals(request.signal.constructor, AbortSignal);61}, "Request objects have a signal property");62promise_test(async t => {63 const controller = new AbortController();64 const signal = controller.signal;65 controller.abort();66 const request = new Request('../resources/data.json', { signal });67 assert_true(Boolean(request.signal), "Signal member is present & truthy");68 assert_equals(request.signal.constructor, AbortSignal);69 assert_not_equals(request.signal, signal, 'Request has a new signal, not a reference');70 assert_true(request.signal.aborted, `Request's signal has aborted`);71 const fetchPromise = fetch(request);72 await promise_rejects_dom(t, "AbortError", fetchPromise);73}, "Signal on request object");74promise_test(async t => {75 const controller = new AbortController();76 const signal = controller.signal;77 controller.abort();78 const request = new Request('../resources/data.json', { signal });79 const requestFromRequest = new Request(request);80 const fetchPromise = fetch(requestFromRequest);81 await promise_rejects_dom(t, "AbortError", fetchPromise);82}, "Signal on request object created from request object");83promise_test(async t => {84 const controller = new AbortController();85 const signal = controller.signal;86 controller.abort();87 const request = new Request('../resources/data.json');88 const requestFromRequest = new Request(request, { signal });89 const fetchPromise = fetch(requestFromRequest);90 await promise_rejects_dom(t, "AbortError", fetchPromise);91}, "Signal on request object created from request object, with signal on second request");92promise_test(async t => {93 const controller = new AbortController();94 const signal = controller.signal;95 controller.abort();96 const request = new Request('../resources/data.json', { signal: new AbortController().signal });97 const requestFromRequest = new Request(request, { signal });98 const fetchPromise = fetch(requestFromRequest);99 await promise_rejects_dom(t, "AbortError", fetchPromise);100}, "Signal on request object created from request object, with signal on second request overriding another");101promise_test(async t => {102 const controller = new AbortController();103 const signal = controller.signal;104 controller.abort();105 const request = new Request('../resources/data.json', { signal });106 const fetchPromise = fetch(request, {method: 'POST'});107 await promise_rejects_dom(t, "AbortError", fetchPromise);108}, "Signal retained after unrelated properties are overridden by fetch");109promise_test(async t => {110 const controller = new AbortController();111 const signal = controller.signal;112 controller.abort();113 const request = new Request('../resources/data.json', { signal });114 const data = await fetch(request, { signal: null }).then(r => r.json());115 assert_equals(data.key, 'value', 'Fetch fully completes');116}, "Signal removed by setting to null");117promise_test(async t => {118 const controller = new AbortController();119 const signal = controller.signal;120 controller.abort();121 const log = [];122 await Promise.all([123 fetch('../resources/data.json', { signal }).then(124 () => assert_unreached("Fetch must not resolve"),125 () => log.push('fetch-reject')126 ),127 Promise.resolve().then(() => log.push('next-microtask'))128 ]);129 assert_array_equals(log, ['fetch-reject', 'next-microtask']);130}, "Already aborted signal rejects immediately");131promise_test(async t => {132 const controller = new AbortController();133 const signal = controller.signal;134 controller.abort();135 const request = new Request('../resources/data.json', {136 signal,137 method: 'POST',138 body: 'foo',139 headers: { 'Content-Type': 'text/plain' }140 });141 await fetch(request).catch(() => {});142 assert_true(request.bodyUsed, "Body has been used");143}, "Request is still 'used' if signal is aborted before fetching");144for (const bodyMethod of BODY_METHODS) {145 promise_test(async t => {146 const controller = new AbortController();147 const signal = controller.signal;148 const log = [];149 const response = await fetch('../resources/data.json', { signal });150 controller.abort();151 const bodyPromise = response[bodyMethod]();152 await Promise.all([153 bodyPromise.catch(() => log.push(`${bodyMethod}-reject`)),154 Promise.resolve().then(() => log.push('next-microtask'))155 ]);156 await promise_rejects_dom(t, "AbortError", bodyPromise);157 assert_array_equals(log, [`${bodyMethod}-reject`, 'next-microtask']);158 }, `response.${bodyMethod}() rejects if already aborted`);159}160promise_test(async t => {161 await abortRequests();162 const controller = new AbortController();163 const signal = controller.signal;164 const stateKey = token();165 const abortKey = token();166 requestAbortKeys.push(abortKey);167 controller.abort();168 await fetch(`../resources/infinite-slow-response.py?stateKey=${stateKey}&abortKey=${abortKey}`, { signal }).catch(() => {});169 // I'm hoping this will give the browser enough time to (incorrectly) make the request170 // above, if it intends to.171 await fetch('../resources/data.json').then(r => r.json());172 const response = await fetch(`../resources/stash-take.py?key=${stateKey}`);173 const data = await response.json();174 assert_equals(data, null, "Request hasn't been made to the server");175}, "Already aborted signal does not make request");176promise_test(async t => {177 await abortRequests();178 const controller = new AbortController();179 const signal = controller.signal;180 controller.abort();181 const fetches = [];182 for (let i = 0; i < 3; i++) {183 const abortKey = token();184 requestAbortKeys.push(abortKey);185 fetches.push(186 fetch(`../resources/infinite-slow-response.py?${i}&abortKey=${abortKey}`, { signal })187 );188 }189 for (const fetchPromise of fetches) {190 await promise_rejects_dom(t, "AbortError", fetchPromise);191 }192}, "Already aborted signal can be used for many fetches");193promise_test(async t => {194 await abortRequests();195 const controller = new AbortController();196 const signal = controller.signal;197 await fetch('../resources/data.json', { signal }).then(r => r.json());198 controller.abort();199 const fetches = [];200 for (let i = 0; i < 3; i++) {201 const abortKey = token();202 requestAbortKeys.push(abortKey);203 fetches.push(204 fetch(`../resources/infinite-slow-response.py?${i}&abortKey=${abortKey}`, { signal })205 );206 }207 for (const fetchPromise of fetches) {208 await promise_rejects_dom(t, "AbortError", fetchPromise);209 }210}, "Signal can be used to abort other fetches, even if another fetch succeeded before aborting");211promise_test(async t => {212 await abortRequests();213 const controller = new AbortController();214 const signal = controller.signal;215 const stateKey = token();216 const abortKey = token();217 requestAbortKeys.push(abortKey);218 await fetch(`../resources/infinite-slow-response.py?stateKey=${stateKey}&abortKey=${abortKey}`, { signal });219 const beforeAbortResult = await fetch(`../resources/stash-take.py?key=${stateKey}`).then(r => r.json());220 assert_equals(beforeAbortResult, "open", "Connection is open");221 controller.abort();222 // The connection won't close immediately, but it should close at some point:223 const start = Date.now();224 while (true) {225 // Stop spinning if 10 seconds have passed226 if (Date.now() - start > 10000) throw Error('Timed out');227 const afterAbortResult = await fetch(`../resources/stash-take.py?key=${stateKey}`).then(r => r.json());228 if (afterAbortResult == 'closed') break;229 }230}, "Underlying connection is closed when aborting after receiving response");231promise_test(async t => {232 await abortRequests();233 const controller = new AbortController();234 const signal = controller.signal;235 const stateKey = token();236 const abortKey = token();237 requestAbortKeys.push(abortKey);238 const url = new URL(`../resources/infinite-slow-response.py?stateKey=${stateKey}&abortKey=${abortKey}`, location);239 url.hostname = urlHostname;240 await fetch(url, {241 signal,242 mode: 'no-cors'243 });244 const stashTakeURL = new URL(`../resources/stash-take.py?key=${stateKey}`, location);245 stashTakeURL.hostname = urlHostname;246 const beforeAbortResult = await fetch(stashTakeURL).then(r => r.json());247 assert_equals(beforeAbortResult, "open", "Connection is open");248 controller.abort();249 // The connection won't close immediately, but it should close at some point:250 const start = Date.now();251 while (true) {252 // Stop spinning if 10 seconds have passed253 if (Date.now() - start > 10000) throw Error('Timed out');254 const afterAbortResult = await fetch(stashTakeURL).then(r => r.json());255 if (afterAbortResult == 'closed') break;256 }257}, "Underlying connection is closed when aborting after receiving response - no-cors");258for (const bodyMethod of BODY_METHODS) {259 promise_test(async t => {260 await abortRequests();261 const controller = new AbortController();262 const signal = controller.signal;263 const stateKey = token();264 const abortKey = token();265 requestAbortKeys.push(abortKey);266 const response = await fetch(`../resources/infinite-slow-response.py?stateKey=${stateKey}&abortKey=${abortKey}`, { signal });267 const beforeAbortResult = await fetch(`../resources/stash-take.py?key=${stateKey}`).then(r => r.json());268 assert_equals(beforeAbortResult, "open", "Connection is open");269 const bodyPromise = response[bodyMethod]();270 controller.abort();271 await promise_rejects_dom(t, "AbortError", bodyPromise);272 const start = Date.now();273 while (true) {274 // Stop spinning if 10 seconds have passed275 if (Date.now() - start > 10000) throw Error('Timed out');276 const afterAbortResult = await fetch(`../resources/stash-take.py?key=${stateKey}`).then(r => r.json());277 if (afterAbortResult == 'closed') break;278 }279 }, `Fetch aborted & connection closed when aborted after calling response.${bodyMethod}()`);280}281promise_test(async t => {282 await abortRequests();283 const controller = new AbortController();284 const signal = controller.signal;285 const stateKey = token();286 const abortKey = token();287 requestAbortKeys.push(abortKey);288 const response = await fetch(`../resources/infinite-slow-response.py?stateKey=${stateKey}&abortKey=${abortKey}`, { signal });289 const reader = response.body.getReader();290 controller.abort();291 await promise_rejects_dom(t, "AbortError", reader.read());292 await promise_rejects_dom(t, "AbortError", reader.closed);293 // The connection won't close immediately, but it should close at some point:294 const start = Date.now();295 while (true) {296 // Stop spinning if 10 seconds have passed297 if (Date.now() - start > 10000) throw Error('Timed out');298 const afterAbortResult = await fetch(`../resources/stash-take.py?key=${stateKey}`).then(r => r.json());299 if (afterAbortResult == 'closed') break;300 }301}, "Stream errors once aborted. Underlying connection closed.");302promise_test(async t => {303 await abortRequests();304 const controller = new AbortController();305 const signal = controller.signal;306 const stateKey = token();307 const abortKey = token();308 requestAbortKeys.push(abortKey);309 const response = await fetch(`../resources/infinite-slow-response.py?stateKey=${stateKey}&abortKey=${abortKey}`, { signal });310 const reader = response.body.getReader();311 await reader.read();312 controller.abort();313 await promise_rejects_dom(t, "AbortError", reader.read());314 await promise_rejects_dom(t, "AbortError", reader.closed);315 // The connection won't close immediately, but it should close at some point:316 const start = Date.now();317 while (true) {318 // Stop spinning if 10 seconds have passed319 if (Date.now() - start > 10000) throw Error('Timed out');320 const afterAbortResult = await fetch(`../resources/stash-take.py?key=${stateKey}`).then(r => r.json());321 if (afterAbortResult == 'closed') break;322 }323}, "Stream errors once aborted, after reading. Underlying connection closed.");324promise_test(async t => {325 await abortRequests();326 const controller = new AbortController();327 const signal = controller.signal;328 const response = await fetch(`../resources/empty.txt`, { signal });329 // Read whole response to ensure close signal has sent.330 await response.clone().text();331 const reader = response.body.getReader();332 controller.abort();333 const item = await reader.read();334 assert_true(item.done, "Stream is done");335}, "Stream will not error if body is empty. It's closed with an empty queue before it errors.");336promise_test(async t => {337 const controller = new AbortController();338 const signal = controller.signal;339 controller.abort();...

Full Screen

Full Screen

task-manager.ts

Source:task-manager.ts Github

copy

Full Screen

1/**2 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.3 *4 * @author David Sehnal <david.sehnal@gmail.com>5 */6import { Task, Progress, RuntimeContext } from '../../mol-task';7import { RxEventHelper } from '../../mol-util/rx-event-helper';8import { now } from '../../mol-util/now';9import { CreateObservableCtx, ExecuteInContext } from '../../mol-task/execution/observable';10import { arrayRemoveInPlace } from '../../mol-util/array';11export { TaskManager };12class TaskManager {13 private ev = RxEventHelper.create();14 private id = 0;15 private runningTasks = new Set<number>();16 private abortRequests = new Map<number, string | undefined>();17 private options = new Map<number, { useOverlay: boolean }>();18 private currentContext: { ctx: RuntimeContext, refCount: number }[] = [];19 readonly events = {20 progress: this.ev<TaskManager.ProgressEvent>(),21 finished: this.ev<{ id: number }>()22 };23 private tryGetAbortTaskId(node: Progress.Node): number | undefined {24 if (this.abortRequests.has(node.progress.taskId)) return node.progress.taskId;25 for (const c of node.children) {26 const abort = this.tryGetAbortTaskId(c);27 if (abort !== void 0) return abort;28 }29 return void 0;30 }31 private track(internalId: number, taskId: number) {32 return (progress: Progress) => {33 if (progress.canAbort && progress.requestAbort) {34 const abortTaskId = this.tryGetAbortTaskId(progress.root);35 if (abortTaskId !== void 0) progress.requestAbort(this.abortRequests.get(abortTaskId));36 }37 const elapsed = now() - progress.root.progress.startedTime;38 this.events.progress.next({39 id: internalId,40 useOverlay: this.options.get(taskId)?.useOverlay,41 level: elapsed < 250 ? 'none' : 'background',42 progress43 });44 };45 }46 async run<T>(task: Task<T>, params?: { createNewContext?: boolean, useOverlay?: boolean }): Promise<T> {47 const id = this.id++;48 let ctx: TaskManager['currentContext'][0];49 if (params?.createNewContext || this.currentContext.length === 0) {50 ctx = { ctx: CreateObservableCtx(task, this.track(id, task.id), 100), refCount: 1 };51 } else {52 ctx = this.currentContext[this.currentContext.length - 1];53 ctx.refCount++;54 }55 try {56 this.options.set(task.id, { useOverlay: !!params?.useOverlay });57 this.runningTasks.add(task.id);58 const ret = await ExecuteInContext(ctx.ctx, task);59 return ret;60 } finally {61 this.options.delete(task.id);62 this.runningTasks.delete(task.id);63 this.events.finished.next({ id });64 this.abortRequests.delete(task.id);65 ctx.refCount--;66 if (ctx.refCount === 0) arrayRemoveInPlace(this.currentContext, ctx);67 }68 }69 requestAbortAll(reason?: string) {70 this.runningTasks.forEach(id => this.abortRequests.set(id, reason));71 }72 requestAbort(taskIdOrProgress: number | Progress, reason?: string) {73 const id = typeof taskIdOrProgress === 'number'74 ? taskIdOrProgress75 : taskIdOrProgress.root.progress.taskId;76 this.abortRequests.set(id, reason);77 }78 dispose() {79 this.ev.dispose();80 }81}82namespace TaskManager {83 export type ReportLevel = 'none' | 'background'84 export interface ProgressEvent {85 id: number,86 useOverlay?: boolean,87 level: ReportLevel,88 progress: Progress89 }90 function delay(time: number): Promise<void> {91 return new Promise(res => setTimeout(res, time));92 }93 export function testTask(N: number) {94 return Task.create('Test', async ctx => {95 let i = 0;96 while (i < N) {97 await delay(100 + Math.random() * 200);98 if (ctx.shouldUpdate) {99 await ctx.update({ message: 'Step ' + i, current: i, max: N, isIndeterminate: false });100 }101 i++;102 }103 });104 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 console.log(data);4});5var wpt = require('webpagetest');6var wpt = new WebPageTest('www.webpagetest.org');7 console.log(data);8});9var wpt = require('webpagetest');10var wpt = new WebPageTest('www.webpagetest.org');11 console.log(data);12});13var wpt = require('webpagetest');14var wpt = new WebPageTest('www.webpagetest.org');15 console.log(data);16});17var wpt = require('webpagetest');18var wpt = new WebPageTest('www.webpagetest.org');19 console.log(data);20});21var wpt = require('webpagetest');22var wpt = new WebPageTest('www.webpagetest.org');23 console.log(data);24});25var wpt = require('webpagetest');26var wpt = new WebPageTest('www.webpagetest.org');27 console.log(data);28});29var wpt = require('webpagetest');30var wpt = new WebPageTest('www.web

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.12345678901234567890123456789012');3 if (err) {4 console.log(err);5 } else {6 console.log(data);7 }8});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3});4var wpt = require('webpagetest');5var wpt = new WebPageTest('www.webpagetest.org');6wpt.getLocations(function(err, data) {7});8var wpt = require('webpagetest');9var wpt = new WebPageTest('www.webpagetest.org');10wpt.getTesters(function(err, data) {11});12var wpt = require('webpagetest');13var wpt = new WebPageTest('www.webpagetest.org');14wpt.getTesters(function(err, data) {15});16var wpt = require('webpagetest');17var wpt = new WebPageTest('www.webpagetest.org');18wpt.getTesters(function(err, data) {19});20var wpt = require('webpagetest');21var wpt = new WebPageTest('www.webpagetest.org');22wpt.getTesters(function(err, data) {23});24var wpt = require('webpagetest');25var wpt = new WebPageTest('www.webpagetest.org');26wpt.getTesters(function(err, data) {27});28var wpt = require('webpagetest');29var wpt = new WebPageTest('www.webpagetest.org');

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.1234567890abcdef1234567890abcdef');3 if (err)4 console.log(err);5 console.log(data);6});7var wpt = require('webpagetest');8var wpt = new WebPageTest('www.webpagetest.org', 'A.1234567890abcdef1234567890abcdef');9wpt.getLocations(function(err, data) {10 if (err)11 console.log(err);12 console.log(data);13});14var wpt = require('webpagetest');15var wpt = new WebPageTest('www.webpagetest.org', 'A.1234567890abcdef1234567890abcdef');16wpt.getTesters(function(err, data) {17 if (err)18 console.log(err);19 console.log(data);20});21var wpt = require('webpagetest');22var wpt = new WebPageTest('www.webpagetest.org', 'A.1234567890abcdef1234567890abcdef');23wpt.getTesters(function(err, data) {24 if (err)25 console.log(err);26 console.log(data);27});28var wpt = require('webpagetest');29var wpt = new WebPageTest('www.webpagetest.org', 'A.1234567890abcdef1234567890abcdef');30wpt.getTesters(function(err, data) {31 if (err)32 console.log(err);33 console.log(data);34});35var wpt = require('webpagetest');36var wpt = new WebPageTest('www.webpagetest.org', 'A.1234567890abcdef1234567890abcdef');37wpt.getTesters(function(err, data) {38 if (err)

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