How to use checkException method in Playwright Internal

Best JavaScript code snippet using playwright-internal

grokible.check.js

Source:grokible.check.js Github

copy

Full Screen

1/**2 * A static library.3 * Check (library) is designed to provide foolproof, simple validation for4 * aspects of variables and arguments. A Check routine, by definition will5 * throw a CheckException if the check fails. Thus, a CheckException may6 * be thought of as a kind of true/false value. It's useful to throw7 * an exception when this is false, to program in the "fail fast" mode,8 * which catches errors early.9 *10 * Other exception types:11 * ----------------------12 * The other type of exception, besides CheckException, thrown by this13 * library is ArgTypeException, which means that a programming error14 * was made in calling this library (or there could be a bug in this library).15 * ArgTypeException means the true/false value is not legitimate because16 * the test couldn't be conducted properly. For example "inArray" test17 * will throw ArgTypeException if the second argument is not an array.18 * This is not a bona fide true/false value (CheckException) because19 * the second arg was not an array, and the test can't be carried out20 * (and this is, of course, a programming error).21 *22 * It is recommended that you convert CheckExceptions to your own23 * type. For example if you are checking arguments at the start of24 * a function call, you could convert the CheckException to25 * ArgTypeException. The following code does that, as well as26 * provides a better message in the exception.27 *28 * Check.isMap (mapArgument1, {29 * exception : ArgTypeException,30 * message : "Params.copy 3rd arg (options) must be a map."31 * });32 * 33 * Thus, if you follow this convention, a CheckException is really just34 * an "unwrapped failure". This is fine, but you may want to examine35 * the failure, and change exception and message to be more helpful.36 * 37 * About the checks:38 * -----------------39 * Some of the qualities we are checking for are defined in ways to make40 * coding less ambiguous. Thus, we take some liberties to slightly41 * change what might be considered a "native Javascript" check. A42 * perfect example of this is "null" being an Object (Check doesn't43 * consider this to be true).44 *45 * Note for the purpose of OOP, the prototype is considered the "class".46 * In calls with objects that have an argument named "constructor",47 * the intent is to pass the constructor, since that has a name that48 * can be used. Passing an object with a prototype will generate a49 * ArgTypeException.50 *51 * Making new checks:52 * ------------------53 * Can be done by writing a truthFunction. This returns no value, but54 * will throw a CheckException on a valid "false" value, and other55 * exceptions on some type of programming error (e.g. ArgTypeException).56 * The wrapper function Check.twoArgTruth () will examine the type of57 * the exception to decide what to do.58 */59var Options = require ('grokible.options.js');60var Describe = require ('grokible.describe.js');61var Exceptions = require ('grokible.exceptions.js');62var CheckException = Exceptions.CheckException;63var ArgTypeException = Exceptions.ArgTypeException;64var Check = {};65/**66 * Generic wrapper function for Check functions. truthFunction must67 * throw an exception if the test fails. If it fails on testing the68 * value, it must throw a CheckException, otherwise any other69 * exception thrown is considered a programming error and is passed out.70 * Thus, even if options = { throws : false }, we will always throw71 * programming exceptions out, but true/false results (which are72 * expressed as CheckExceptions), do not throw if throws = false.73 */74Check.twoArgTruth = function (obj, obj2, truthFunction, options) {75 if (options === undefined)76 options = {};77 // Is options a Map?78 try {79 Check._instanceOf (options, Object);80 } catch (e) {81 throw new ArgTypeException ("Fourth arg (options) must be a map. " +82 "It is a " + Describe.get (options) + ".");83 }84 try {85 Check._keysInArray (options, ['throws', 'exception', 'message']);86 } catch (e) {87 throw new ArgTypeException ("Fourth arg (options) must be a map. " +88 "It is a " + Describe.get (options) + ".");89 }90 var throws = Options.get ('throws', options, true);91 var exceptionCtor = Options.get ('exception', options);92 var message = Options.get ('message', options, "");93 var exc;94 try {95 truthFunction (obj, obj2);96 } catch (e) {97 exc = e;98 }99 // truthFunctions are expected to throw on false or error100 if (exc) {101 // We will still throw if this is a programming error (i.e.102 // truthFunction () throws something that is not a CheckException103 var excIsCheckException = Object.getPrototypeOf (exc) ===104 CheckException.prototype;105 var excCtorDefined = typeof (exceptionCtor) === "function";106 if (throws || ! excIsCheckException) {107 if (message.length == 0) {108 message = "" + exc;109 message += " ArgType=" + Describe.get (obj) + ".";110 }111 // If truthFunction throws a CheckException, we need to take112 // its message and enhance it (i.e. with the Arg description),113 // otherwise we rethrow.114 if (excIsCheckException) {115 if (excCtorDefined)116 throw new exceptionCtor (message);117 throw new CheckException (message);118 }119 // else rethrow120 throw exc;121 }122 return false;123 }124 return true;125}126/**127 * This is equivalent to saying something is the same "class"128 */129Check._hasSamePrototype = function (value, constructor) {130 if (value === undefined || value === null)131 throw new CheckException ("First arg (value) is undefined or null");132 if (constructor === undefined || constructor === null)133 throw new ArgTypeException ("Second arg (constructor) is " +134 "undefined or null");135 136 try {137 Check._isFunction (constructor);138 } catch (e) {139 throw new ArgTypeException ("Second arg (constructor) is not a " +140 "function");141 }142 if (constructor.prototype === null)143 throw new ArgTypeException ("Second arg (constructor), prototype " +144 "property is null");145 if (constructor.prototype === undefined)146 throw new ArgTypeException ("Second arg (constructor), prototype " +147 "property is undefined");148 var name = "(with no name)";149 if ( ! (constructor.name === undefined))150 name = constructor.name;151 var prototype1;152 try {153 prototype1 = Object.getPrototypeOf (value);154 } catch (e) {155 throw new CheckException (Describe.get (value) +156 " has no prototype (not an object) compared to constructor '" +157 name + "'"); 158 }159 if (prototype1 != constructor.prototype)160 throw new CheckException (Describe.get (value) +161 " has a different prototype than constructor '" + name + "'");162}163Check.hasSamePrototype = function (value, constructor, options) {164 return Check.twoArgTruth (value, constructor, Check._hasSamePrototype,165 options);166}167Check._isArray = function (value) {168 if ( ! Array.isArray (value))169 throw new CheckException ("The value is not an array.");170}171Check.isArray = function (value, options) {172 return Check.twoArgTruth (value, null, Check._isArray, options);173}174Check._inArray = function (value, arr) {175 if (arr.indexOf (value) < 0)176 throw new CheckException ("The value '" + value + "' is not " +177 "in the array.");178}179Check.inArray = function (value, arr, options) {180 return Check.twoArgTruth (value, arr, Check._inArray, options);181}182Check._keysInArray = function (value, arr) {183 var keys = Object.keys (value),184 len = keys.length;185 for (var i = 0 ; i < len ; i++) {186 var k = keys [i];187 if (arr.indexOf (k) < 0)188 throw new CheckException ("Key '" + k + "' not found in array.");189 }190}191Check.keysInArray = function (value, arr, options) {192 return Check.twoArgTruth (value, arr, Check._keysInArray, options);193}194Check._inMapAndNotEmpty = function (value, map) {195 try {196 Check._isMap (map);197 } catch (e) {198 throw new ArgTypeException ("Second arg is not a map.");199 }200 if ( ! (value in map))201 throw new CheckException ("Value (key) '" + value + "' is not in " +202 "map.");203 var v = map [value];204 if (v === undefined || v === null)205 throw new CheckException ("Value (key) '" + value + "' is in " +206 "map, but is empty (null or undefined).");207}208Check.inMapAndNotEmpty = function (value, map, options) {209 return Check.twoArgTruth (value, map, Check._inMapAndNotEmpty, options);210}211Check._isString = function (value) {212 if ((undefined === value) || (null === value))213 throw new CheckException ("Value '" + value + "' is not a string.");214 if ( ! (typeof value === 'string'))215 throw new CheckException ("Value '" + value + "' is not a string");216}217Check.isString = function (value, options) {218 return Check.twoArgTruth (value, undefined, Check._isString, options);219}220Check._isNumber = function (value) {221 if ((undefined === value) || (null === value))222 throw new CheckException ("Value '" + value + "' is not a number.");223 if ( ! (typeof value === 'number'))224 throw new CheckException ("Value '" + value + "' is not a number.");225 if (isNaN (value))226 throw new CheckException ("Value '" + value + "' is not a number " +227 "(NaN).");228}229Check.isNumber = function (value, options) {230 return Check.twoArgTruth (value, undefined, Check._isNumber, options);231}232Check._isInteger = function (value) {233 if ((undefined === value) || (null === value))234 throw new CheckException ("Value '" + value + "' is not an " +235 "integer.");236 if ( ! (value % 1 == 0))237 throw new CheckException ("Value '" + value + "' is not an " +238 "integer.");239}240Check.isInteger = function (value, options) {241 return Check.twoArgTruth (value, undefined, Check._isInteger, options);242}243Check._isUndefined = function (value) {244 if ( ! (undefined === value))245 throw new CheckException ("Value '" + value + "' is not undefined.");246}247Check.isUndefined = function (value, options) {248 return Check.twoArgTruth (value, undefined, Check._isUndefined, options);249}250Check._isDefined = function (value) {251 if (undefined === value)252 throw new CheckException ("Value '" + value + "' must be defined.");253}254Check.isDefined = function (value, options) {255 return Check.twoArgTruth (value, undefined, Check._isUndefined, options);256}257/**258 * Synonym for hasSamePrototype259 */260Check.hasClass = function (value, constructor, options) {261 return Check.hasSamePrototype (value, constructor, options);262}263/**264 * Determines whether the class is "Object" (e.g. {})265 */266Check.hasClassOfObject = function (value, options) {267 return Check.hasSamePrototype (value, Object, options);268}269Check._isFunction = function (value) {270 var isFunc = !! (value && value.constructor && value.call && value.apply);271 if ( ! isFunc)272 throw new CheckException ("Value is not a function.");273}274Check.isFunction = function (value, options) {275 return Check.twoArgTruth (value, undefined, Check._isFunction, options);276}277/**278 * Determines whether the class is "Object" (e.g. {})279 */280Check._instanceOf = function (value, constructor) {281 try {282 Check._isFunction (constructor);283 } catch (e) {284 throw new ArgTypeException ("Second arg (constructor) must be " +285 "a function");286 }287 if ( ! (value instanceof constructor))288 throw new CheckException ("Value '" + Describe.get (value) + "' is " +289 "not an instanceof constructor '" + Describe.get (constructor) +290 "'.");291}292Check.instanceOf = function (value, constructor, options) {293 return Check.twoArgTruth (value, constructor, Check._instanceOf, options);294}295/**296 * Synonym for instanceOf297 */298Check.isA = function (value, constructor, options) {299 return Check.instanceOf (value, constructor, options);300}301/**302 * Determines whether the class is "Object" (e.g. {})303 */304Check.isObject = function (value, options) {305 return Check.instanceOf (value, Object, options);306}307/**308 * A map is an object in Javascript. The intent here is to determine309 * whether something is an object literal.310 */311Check._isMap = function (value) {312 Check._instanceOf (value, Object);313}314Check.isMap = function (value, options) {315 return Check.twoArgTruth (value, Object, Check._isMap, options);316}...

Full Screen

Full Screen

test-inspector.js

Source:test-inspector.js Github

copy

Full Screen

...29 assert(err instanceof SyntaxError);30 assert(/Unexpected token/.test(err.message), err.message);31 assert(/WebSockets request was expected/.test(err.body), err.body);32}33function checkException(message) {34 assert.strictEqual(message.exceptionDetails, undefined);35}36function assertScopeValues({ result }, expected) {37 const unmatched = new Set(Object.keys(expected));38 for (const actual of result) {39 const value = expected[actual.name];40 if (value) {41 assert.strictEqual(42 actual.value.value,43 value,44 `Expected scope values to be ${actual.value.value} instead of ${value}.`45 );46 unmatched.delete(actual.name);47 }48 }49 if (unmatched.size)50 assert.fail(Array.from(unmatched.values()));51}52async function testBreakpointOnStart(session) {53 console.log('[test]',54 'Verifying debugger stops on start (--inspect-brk option)');55 const commands = [56 { 'method': 'Runtime.enable' },57 { 'method': 'Debugger.enable' },58 { 'method': 'Debugger.setPauseOnExceptions',59 'params': { 'state': 'none' } },60 { 'method': 'Debugger.setAsyncCallStackDepth',61 'params': { 'maxDepth': 0 } },62 { 'method': 'Profiler.enable' },63 { 'method': 'Profiler.setSamplingInterval',64 'params': { 'interval': 100 } },65 { 'method': 'Debugger.setBlackboxPatterns',66 'params': { 'patterns': [] } },67 { 'method': 'Runtime.runIfWaitingForDebugger' }68 ];69 await session.send(commands);70 await session.waitForBreakOnLine(0, session.scriptURL());71}72async function testBreakpoint(session) {73 console.log('[test]', 'Setting a breakpoint and verifying it is hit');74 const commands = [75 { 'method': 'Debugger.setBreakpointByUrl',76 'params': { 'lineNumber': 5,77 'url': session.scriptURL(),78 'columnNumber': 0,79 'condition': '' } },80 { 'method': 'Debugger.resume' },81 ];82 await session.send(commands);83 const { scriptSource } = await session.send({84 'method': 'Debugger.getScriptSource',85 'params': { 'scriptId': session.mainScriptId },86 });87 assert(scriptSource && (scriptSource.includes(session.script())),88 `Script source is wrong: ${scriptSource}`);89 await session.waitForConsoleOutput('log', ['A message', 5]);90 const paused = await session.waitForBreakOnLine(5, session.scriptURL());91 const scopeId = paused.params.callFrames[0].scopeChain[0].object.objectId;92 console.log('[test]', 'Verify we can read current application state');93 const response = await session.send({94 'method': 'Runtime.getProperties',95 'params': {96 'objectId': scopeId,97 'ownProperties': false,98 'accessorPropertiesOnly': false,99 'generatePreview': true100 }101 });102 assertScopeValues(response, { t: 1001, k: 1 });103 let { result } = await session.send({104 'method': 'Debugger.evaluateOnCallFrame', 'params': {105 'callFrameId': session.pausedDetails().callFrames[0].callFrameId,106 'expression': 'k + t',107 'objectGroup': 'console',108 'includeCommandLineAPI': true,109 'silent': false,110 'returnByValue': false,111 'generatePreview': true112 }113 });114 const expectedEvaluation = 1002;115 assert.strictEqual(116 result.value,117 expectedEvaluation,118 `Expected evaluation to be ${expectedEvaluation}, got ${result.value}.`119 );120 result = (await session.send({121 'method': 'Runtime.evaluate', 'params': {122 'expression': '5 * 5'123 }124 })).result;125 const expectedResult = 25;126 assert.strictEqual(127 result.value,128 expectedResult,129 `Expected Runtime.evaluate to be ${expectedResult}, got ${result.value}.`130 );131}132async function testI18NCharacters(session) {133 console.log('[test]', 'Verify sending and receiving UTF8 characters');134 const chars = 'טֶ字и';135 session.send({136 'method': 'Debugger.evaluateOnCallFrame', 'params': {137 'callFrameId': session.pausedDetails().callFrames[0].callFrameId,138 'expression': `console.log("${chars}")`,139 'objectGroup': 'console',140 'includeCommandLineAPI': true,141 'silent': false,142 'returnByValue': false,143 'generatePreview': true144 }145 });146 await session.waitForConsoleOutput('log', [chars]);147}148async function testCommandLineAPI(session) {149 const testModulePath = require.resolve('../fixtures/empty.js');150 const testModuleStr = JSON.stringify(testModulePath);151 const printAModulePath = require.resolve('../fixtures/printA.js');152 const printAModuleStr = JSON.stringify(printAModulePath);153 const printBModulePath = require.resolve('../fixtures/printB.js');154 const printBModuleStr = JSON.stringify(printBModulePath);155 // We can use `require` outside of a callframe with require in scope156 let result = await session.send(157 {158 'method': 'Runtime.evaluate', 'params': {159 'expression': 'typeof require("fs").readFile === "function"',160 'includeCommandLineAPI': true161 }162 });163 checkException(result);164 assert.strictEqual(result.result.value, true);165 // The global require has the same properties as a normal `require`166 result = await session.send(167 {168 'method': 'Runtime.evaluate', 'params': {169 'expression': [170 'typeof require.resolve === "function"',171 'typeof require.extensions === "object"',172 'typeof require.cache === "object"'173 ].join(' && '),174 'includeCommandLineAPI': true175 }176 });177 checkException(result);178 assert.strictEqual(result.result.value, true);179 // `require` twice returns the same value180 result = await session.send(181 {182 'method': 'Runtime.evaluate', 'params': {183 // 1. We require the same module twice184 // 2. We mutate the exports so we can compare it later on185 'expression': `186 Object.assign(187 require(${testModuleStr}),188 { old: 'yes' }189 ) === require(${testModuleStr})`,190 'includeCommandLineAPI': true191 }192 });193 checkException(result);194 assert.strictEqual(result.result.value, true);195 // After require the module appears in require.cache196 result = await session.send(197 {198 'method': 'Runtime.evaluate', 'params': {199 'expression': `JSON.stringify(200 require.cache[${testModuleStr}].exports201 )`,202 'includeCommandLineAPI': true203 }204 });205 checkException(result);206 assert.deepStrictEqual(JSON.parse(result.result.value),207 { old: 'yes' });208 // Remove module from require.cache209 result = await session.send(210 {211 'method': 'Runtime.evaluate', 'params': {212 'expression': `delete require.cache[${testModuleStr}]`,213 'includeCommandLineAPI': true214 }215 });216 checkException(result);217 assert.strictEqual(result.result.value, true);218 // Require again, should get fresh (empty) exports219 result = await session.send(220 {221 'method': 'Runtime.evaluate', 'params': {222 'expression': `JSON.stringify(require(${testModuleStr}))`,223 'includeCommandLineAPI': true224 }225 });226 checkException(result);227 assert.deepStrictEqual(JSON.parse(result.result.value), {});228 // require 2nd module, exports an empty object229 result = await session.send(230 {231 'method': 'Runtime.evaluate', 'params': {232 'expression': `JSON.stringify(require(${printAModuleStr}))`,233 'includeCommandLineAPI': true234 }235 });236 checkException(result);237 assert.deepStrictEqual(JSON.parse(result.result.value), {});238 // Both modules end up with the same module.parent239 result = await session.send(240 {241 'method': 'Runtime.evaluate', 'params': {242 'expression': `JSON.stringify({243 parentsEqual:244 require.cache[${testModuleStr}].parent ===245 require.cache[${printAModuleStr}].parent,246 parentId: require.cache[${testModuleStr}].parent.id,247 })`,248 'includeCommandLineAPI': true249 }250 });251 checkException(result);252 assert.deepStrictEqual(JSON.parse(result.result.value), {253 parentsEqual: true,254 parentId: '<inspector console>'255 });256 // The `require` in the module shadows the command line API's `require`257 result = await session.send(258 {259 'method': 'Debugger.evaluateOnCallFrame', 'params': {260 'callFrameId': session.pausedDetails().callFrames[0].callFrameId,261 'expression': `(262 require(${printBModuleStr}),263 require.cache[${printBModuleStr}].parent.id264 )`,265 'includeCommandLineAPI': true266 }267 });268 checkException(result);269 assert.notStrictEqual(result.result.value,270 '<inspector console>');271}272async function runTest() {273 const child = new NodeInstance();274 checkListResponse(await child.httpGet(null, '/json'));275 checkListResponse(await child.httpGet(null, '/json/list'));276 checkVersion(await child.httpGet(null, '/json/version'));277 await child.httpGet(null, '/json/activate').catch(checkBadPath);278 await child.httpGet(null, '/json/activate/boom').catch(checkBadPath);279 await child.httpGet(null, '/json/badpath').catch(checkBadPath);280 const session = await child.connectInspectorSession();281 await testBreakpointOnStart(session);282 await testBreakpoint(session);...

Full Screen

Full Screen

test_seizepower.js

Source:test_seizepower.js Github

copy

Full Screen

...18 srv.registerPathHandler("/seize-after-async", handleSeizeAfterAsync);19 srv.start(PORT);20 runRawTests(tests, testComplete(srv));21}22function checkException(fun, err, msg)23{24 try25 {26 fun();27 }28 catch (e)29 {30 if (e !== err && e.result !== err)31 do_throw(msg);32 return;33 }34 do_throw(msg);35}36function callASAPLater(fun)37{38 gThreadManager.currentThread.dispatch({39 run: function()40 {41 fun();42 }43 }, Ci.nsIThread.DISPATCH_NORMAL);44}45/*****************46 * PATH HANDLERS *47 *****************/48function handleRawData(request, response)49{50 response.seizePower();51 response.write("Raw data!");52 response.finish();53}54function handleTooLate(request, response)55{56 response.write("DO NOT WANT");57 var output = response.bodyOutputStream;58 response.seizePower();59 if (response.bodyOutputStream !== output)60 response.write("bodyOutputStream changed!");61 else62 response.write("too-late passed");63 response.finish();64}65function handleExceptions(request, response)66{67 response.seizePower();68 checkException(function() { response.setStatusLine("1.0", 500, "ISE"); },69 Cr.NS_ERROR_NOT_AVAILABLE,70 "setStatusLine should throw not-available after seizePower");71 checkException(function() { response.setHeader("X-Fail", "FAIL", false); },72 Cr.NS_ERROR_NOT_AVAILABLE,73 "setHeader should throw not-available after seizePower");74 checkException(function() { response.processAsync(); },75 Cr.NS_ERROR_NOT_AVAILABLE,76 "processAsync should throw not-available after seizePower");77 var out = response.bodyOutputStream;78 var data = "exceptions test passed";79 out.write(data, data.length);80 response.seizePower(); // idempotency test of seizePower81 response.finish();82 response.finish(); // idempotency test of finish after seizePower83 checkException(function() { response.seizePower(); },84 Cr.NS_ERROR_UNEXPECTED,85 "seizePower should throw unexpected after finish");86}87function handleAsyncSeizure(request, response)88{89 response.seizePower();90 callLater(1, function()91 {92 response.write("async seizure passed");93 response.bodyOutputStream.close();94 callLater(1, function()95 {96 response.finish();97 });98 });99}100function handleSeizeAfterAsync(request, response)101{102 response.setStatusLine(request.httpVersion, 200, "async seizure pass");103 response.processAsync();104 checkException(function() { response.seizePower(); },105 Cr.NS_ERROR_NOT_AVAILABLE,106 "seizePower should throw not-available after processAsync");107 callLater(1, function()108 {109 response.finish();110 });111}112/***************113 * BEGIN TESTS *114 ***************/115var test, data;116var tests = [];117data = "GET /raw-data HTTP/1.0\r\n" +118 "\r\n";...

Full Screen

Full Screen

checkplugin.js

Source:checkplugin.js Github

copy

Full Screen

1// (C) Copyright 2017 Hewlett Packard Enterprise Development LP2//3// Licensed under the Apache License, Version 2.0 (the "License"); you may4// not use this file except in compliance with the License. You may obtain5// a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the12// License for the specific language governing permissions and limitations13// under the License.14// @flow15import fs from 'fs-extra';16import * as util from '../util';17import { filterDirectories } from '../fs-util';18import type { ModuleDependency } from '../module';19import type Repository, { IntermediateModule } from '../repository/repository';20const EXCLUDE_DIRECTORIES: string[] = ['.git', '.idea'];21export class CheckException extends util.ExtendableError {22 constructor(m: string) {23 super(m);24 }25}26/**27 * Performs a local scan of the repository, returning a Module instance for28 * each non-blacklisted subdirectory under localPath.29 * @param {Repository} repository the repository instance to scan30 * @param {CheckPlugin} plugin the plugin to check against31 * @param {string} localPath path to a local mirror of the repository32 * 33 * @return {Promise} a Promise returning a list of Modules34 */35export function simpleScan<T: Repository>(36 repository: T,37 plugin: CheckPlugin<T>,38 localPath: string): Promise<IntermediateModule[]> {39 return fs.readdir(localPath)40 .then(filterDirectories(localPath, ...EXCLUDE_DIRECTORIES))41 .then(dirs => Promise.all(dirs.map(dir => {42 return plugin.matches(repository, dir).then(match => {43 if (match) {44 return { name: dir, type: plugin.type().module };45 } else {46 return null;47 }48 });49 })))50 .then(modules => modules.filter(m => m !== null));51}52export type CheckPluginType = {53 repository: string,54 module: string55};56export type CheckPluginResult = {57 versions: string[],58 current: string | null59};60export default class CheckPlugin<T: Repository> {61 constructor() {62 }63 type(): CheckPluginType {64 throw new CheckException('type() not implemented');65 }66 67 // eslint-disable-next-line no-unused-vars68 matches(repository: T, module: string): Promise<boolean> {69 throw new CheckException('matches() not implemented');70 }71 /**72 * Scans a local copy of a repository for modules. Since this requires a local73 * mirror it generally is only used with git repositories.74 * @param {Repository} repository 75 * @return {Promise} a promise returning detected Module instances76 */77 scan(repository: T,78 localPath: string): Promise<IntermediateModule[]> { // eslint-disable-line no-unused-vars79 throw new CheckException('scan() not implemented');80 }81 // eslint-disable-next-line no-unused-vars82 check(repository: T, module: string): Promise<CheckPluginResult> {83 throw new CheckException('check() not implemented');84 }85 // eslint-disable-next-line no-unused-vars86 dependencies(repository: T, module: string): Promise<ModuleDependency[]> {87 throw new CheckException('dependencies() not implemented');88 }89}90export function ensureReady(repository: Repository) {91 if (!repository.ready()) {92 throw new CheckException('repository must be checked out');93 }...

Full Screen

Full Screen

replacelink.js

Source:replacelink.js Github

copy

Full Screen

1 function extractDomain(url) {2 var hostname;3 if (url.indexOf("://") > -1) {hostname = url.split('/')[2];}4 else {hostname = url.split('/')[0];}5 hostname = hostname.split(':')[0];6 hostname = hostname.split('?')[0];7 return hostname;8 }9 function exception(){10 var exception = new Array(); 11 setting.pengecualian = setting.pengecualian;12 exception = setting.pengecualian.split(",");13 return exception;14 }15 function hanyauntuk(){16 var hanyauntuk = new Array(); 17 setting.hanyauntuk = setting.hanyauntuk;18 hanyauntuk = setting.hanyauntuk.split(",");19 return hanyauntuk;20 }21 function convertstr(str) {22 return str.replace(/^\s+/, '').replace(/\s+$/, '');23 }24 if (!setting.pengecualian) {25 setting.pengecualian = window.location.href;26 }else {27 setting.pengecualian += ","+window.location.href;28 }29 var exception = exception();30 var exceptionlength = exception.length;31 var hanyauntuk = hanyauntuk();32 var hanyauntuklength = hanyauntuk.length;33 var checklink = "";34 var checkexception = ""; 35 var linktag = document.getElementsByTagName("a");36 var blogpage = setting.pageurl; 37 if (setting.pengecualianstatus == false && setting.hanyauntukstatus == false) {38 alert('Silahkan pilih salah satu status agar auto link aktif !')39 }40 for (var i = 0; i < linktag.length; i++) { 41 checkpengecualian = true;42 checkhanyauntuk = false;43 no = 0;44 if (setting.pengecualianstatus) { 45 checkpengecualian = false;46 while (checkpengecualian == false && no < exceptionlength) {47 checklink = extractDomain(linktag[i].href);48 checkexception = extractDomain(exception[no]);49 if (checklink.match(checkexception)) {50 checkpengecualian = true;51 }52 no++;53 }54 }55 if (setting.hanyauntukstatus) { 56 checkhanyauntuk = false;57 while (checkhanyauntuk == false && no < hanyauntuklength) {58 checklink = extractDomain(linktag[i].href);59 checkexception = extractDomain(hanyauntuk[no]);60 if (checklink.match(checkexception)) {61 checkhanyauntuk = true;62 }63 no++;64 } 65 }66 if (checkpengecualian == false || checkhanyauntuk == true) { 67 linktag[i].href = blogpage + setting.path + aesCrypto.encrypt(convertstr(linktag[i].href),convertstr('root'));68 linktag[i].target = "_blank";69 }...

Full Screen

Full Screen

keys-spec.js

Source:keys-spec.js Github

copy

Full Screen

1var expect = require('expect.js');2var keys = require('../src/prfl').keys;3suite('keys()', function() {4 var checkException = function(e) {5 expect(e).to.be.a(TypeError);6 };7 test('throws a TypeError when receiving null', function() {8 expect(function() { keys(null); }).to.throwException(checkException);9 });10 test('does not throw an exception when calledf with an object', function() {11 expect(function() { keys({}); }).not.to.throwException();12 });13 test('throws a TypeError when receiving undefined', function() {14 expect(function() { keys(undefined); }).to.throwException(checkException);15 });16 test('throws a TypeError when receiving a boolean', function() {17 expect(function() { keys(true); }).to.throwException(checkException);18 });19 test('throws a TypeError when receiving a number', function() {20 expect(function() { keys(1); }).to.throwException(checkException);21 });22 test('throws a TypeError when receiving a string', function() {23 expect(function() { keys('abc'); }).to.throwException(checkException);24 });25 test('returns an empty array for an empty object', function() {26 expect(keys({})).to.eql([]);27 });28 test('returns all property names of an object', function() {29 expect(keys({a: 0, b: 1, c: 2})).to.eql(['a', 'b', 'c']);30 });31 test('returns the property name of an object with a single property', function() {32 expect(keys({a: 0})).to.eql(['a']);33 });34 test('returns all property names of an object', function() {35 expect(keys({foo: 0, bar: 1, baz: 2})).to.eql(['foo', 'bar', 'baz']);36 });37 test('does not return names of prototype properties', function() {38 function Constructor() {39 this.ownProperty1 = 1;40 this.ownProperty2 = 2;41 }42 Constructor.prototype = {43 prototypeProperty: 144 };45 expect(keys(new Constructor())).to.eql(['ownProperty1', 'ownProperty2'])46 })...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { checkException } = require('playwright/lib/server/trace/recorder');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.click('text=Google Search');8 await page.waitForTimeout(5000);9 await browser.close();10})();11const { checkException } = require('playwright/lib/server/trace/recorder');12const { chromium } = require('playwright');13(async () => {14 const browser = await chromium.launch();15 const context = await browser.newContext();16 const page = await context.newPage();17 await page.click('text=Google Search');18 await page.waitForTimeout(5000);19 await browser.close();20})();21const { checkException } = require('playwright/lib/server/trace/recorder');22const { chromium } = require('playwright');23(async () => {24 const browser = await chromium.launch();25 const context = await browser.newContext();26 const page = await context.newPage();27 await page.click('text=Google Search');28 await page.waitForTimeout(5000);29 await browser.close();30})();31const { checkException } = require('playwright/lib/server/trace/recorder');32const { chromium } = require('playwright');33(async () => {34 const browser = await chromium.launch();35 const context = await browser.newContext();36 const page = await context.newPage();37 await page.click('text=Google Search');38 await page.waitForTimeout(5000);39 await browser.close();40})();41const { checkException } = require('playwright/lib/server/trace/recorder');42const { chromium } = require('playwright');43(async () => {44 const browser = await chromium.launch();45 const context = await browser.newContext();46 const page = await context.newPage();47 await page.click('text=Google Search');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { checkException } = require('playwright-internal');2const { test } = require('@playwright/test');3test('test', async ({ page }) => {4 try {5 await page.click('text=Get started');6 } catch (e) {7 checkException(e, 'element is not visible');8 }9});10const express = require('express');11const router = express.Router();12const User = require('../models/user');13router.get('/', function(req, res, next) {14 res.render('index', { title: 'Express' });15});16router.post('/', function(req, res, next) {17 const { username, email, password } = req.body;18 const user = new User({ username, email, password });19 user.save()20 .then(result => {21 res.redirect('/');22 })23 .catch(err => {24 console.log(err);25 });26});27module.exports = router;28const express = require('express');29const path = require('path');30const cookieParser = require('cookie-parser');31const logger = require('morgan');32const mongoose = require('mongoose');33const indexRouter = require('./routes/index');34const usersRouter = require('./routes/users');35const app = express();36app.set('views', path.join(__dirname, 'views'));37app.set('view engine', 'pug');38app.use(logger('dev'));39app.use(express.json());40app.use(express.urlencoded({

Full Screen

Using AI Code Generation

copy

Full Screen

1const { checkException } = require('playwright-core/lib/internal/stackTrace');2const { test } = require('@playwright/test');3test('test', async ({ page }) => {4 try {5 } catch (e) {6 checkException(e);7 }8});9 > 1 | test('test', async ({ page }) => {10 2 | try {11 4 | } catch (e) {

Full Screen

Using AI Code Generation

copy

Full Screen

1const { checkException } = require('playwright/lib/server/trace/recorder');2const { AssertionError } = require('assert');3const assert = require('assert');4describe('My Test', () => {5 it('should pass', () => {6 assert.ok(true);7 });8 it('should fail', () => {9 assert.ok(false);10 });11});12(async () => {13 const exception = await checkException(new AssertionError({14 }));15 console.log(exception);16})();17{ name: 'AssertionError [ERR_ASSERTION]',18 message: 'Expected values to be strictly equal:\n\ntrue !== false\n\n' }19 at Object.<anonymous> (/Users/username/test.js:21:12)20 at Module._compile (internal/modules/cjs/loader.js:1063:30)21 at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)22 at Module.load (internal/modules/cjs/loader.js:928:32)23 at Function.Module._load (internal/modules/cjs/loader.js:769:14)24 at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)25import { checkException } from 'playwright/lib/server/trace/recorder';26import * as assert from 'assert';27const exception = await checkException(new assert.AssertionError({28}));29console.log(exception);

Full Screen

Using AI Code Generation

copy

Full Screen

1import { checkException } from 'playwright/lib/utils/stackTrace';2try {3} catch(e) {4 checkException(e);5}6import { checkException } from 'playwright/lib/utils/stackTrace';7try {8} catch(e) {9 checkException(e);10}11import { checkException } from 'playwright/lib/utils/stackTrace';12try {13} catch(e) {14 checkException(e);15}16import { checkException } from 'playwright/lib/utils/stackTrace';17try {18} catch(e) {19 checkException(e);20}21import { checkException } from 'playwright/lib/utils/stackTrace';22try {23} catch(e) {24 checkException(e);25}26import { checkException } from 'playwright/lib/utils/stackTrace';27try {28} catch(e) {29 checkException(e);30}31import { checkException } from 'playwright/lib/utils/stackTrace';32try {33} catch(e) {34 checkException(e);35}

Full Screen

Using AI Code Generation

copy

Full Screen

1const { checkException } = require('playwright/lib/utils/utils');2const exception = new Error('Some Exception');3if (checkException(exception)) {4 console.log('Exception is one of the following - TimeoutError, Error, TypeError, AssertionError, SyntaxError, RangeError');5} else {6 console.log('Exception is not one of the following - TimeoutError, Error, TypeError, AssertionError, SyntaxError, RangeError');7}

Full Screen

Playwright tutorial

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.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal 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