How to use removeAnsiColors method in Playwright Internal

Best JavaScript code snippet using playwright-internal

TestReport.jsx

Source:TestReport.jsx Github

copy

Full Screen

...127 return "";128 }129 const [ text ] = msg,130 [ ex, filePos ] = text.split( "\n" ),131 errMessage = TestReport.removeAnsiColors( ex.length > 10 ? ex : text );132 filePos && this.parseReportFailureLocationLine( filePos.trim(), errMessage.substr( 0, 80 ) );133 return errMessage;134 }135 /**-136 * Parse report lines like:137 * "at Object.somecrpa (/tmp/.runtime-test/specs/react-html5-form-valid.spec.js:46:7)"138 * @param String filePos139 * @param String message140 */141 parseReportFailureLocationLine( filePos, message ) {142 const re = /\((.*):(\d+):(\d+)\)$/,143 match = filePos.match( re );144 if ( !match ) {145 return;146 }147 const file = match[ 1 ],148 line = match[ 2 ];149 if ( !( file in this.reportedFailures ) ) {150 this.reportedFailures[ file ] = [];151 }152 this.reportedFailures[ file ].push({153 line,154 message155 });156 }157 /*eslint no-control-regex: 0*/158 static removeAnsiColors( msg ) {159 const re = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;160 return msg.replace( re, "" );161 }162 getDetails( testResults ) {163 // report.results.testResults164 return testResults.reduce( ( payload, entry ) => {165 // testResultItem: { console, failureMessage, leaks, numFailingTests, numPassingTests, numPendingTests,166 // perfStats, skipped, snapshot, sourceMaps, testFilePath, testResults }167 const carry = entry.testResults.reduce( ( carry, test ) => {168 // test: { ancestorTitles, duration, failureMessages, fullName, location, numPassingAsserts, status, title }169 const [ suite, describe ] = test.ancestorTitles,170 suiteId = `${ suite } (${ path.parse( entry.testFilePath ).base })`;171 carry[ suiteId ] = suiteId in carry ? carry[ suiteId ] : {};172 carry[ suiteId ][ describe ] = describe in carry[ suiteId ] ? carry[ suiteId ][ describe ] : [];...

Full Screen

Full Screen

logger.test.js

Source:logger.test.js Github

copy

Full Screen

1'use strict';2const Taste = require('@jikurata/taste');3const Logger = require('../src/Logger.js');4const Record = require('../src/Record.js');5const Console = new Logger();6Console.printMessage = false;7Taste('Emitting record event')8.test('Emits record event when a record is created', (profile) => {9 Console.on('record', (record) => {10 profile['recordEventEmitted'] = true;11 profile['record'] = record;12 });13 Console.createRecord('info','foobar');14 Console.unregisterEvent('record');15})16.expect('recordEventEmitted').toBeTruthy()17.expect('record').toBeInstanceOf(Record);18Taste('Logger retains is record history')19.test('Logger creates a Record object and stores it in its history', (profile) => {20 Console.history.length = 0;21 Console.log('testing log history');22 Console.info('testing log history');23 Console.warn('testing log history');24 Console.error('testing log history');25 profile['logHistoryLength'] = Console.history.length;26})27.expect('logHistoryLength').toEqual(4);28 29Taste('Logger history limit')30.test('Logger deletes the oldest entries if past limit', (profile) => {31 Console.historyLimit = 3;32 for ( let i = 6; --i; ) Console.info(i);33 profile['restrictedHistoryLength'] = Console.history.length;34})35.expect('restrictedHistoryLength').toEqual(3);36Taste('Identifying data types')37.test(profile => {38 class Foo {39 constructor() {40 this.value = 'bar';41 }42 }43 profile.isNull = Console.getDataType(null);44 profile.isUndefined = Console.getDataType(undefined);45 profile.isBoolean = Console.getDataType(true);46 profile.isString = Console.getDataType('foobar');47 profile.isNumber = Console.getDataType(1);48 profile.isBigInt = Console.getDataType(1n);49 profile.isFunction = Console.getDataType(() => {});50 profile.isSymbol = Console.getDataType(Symbol('foo'));51 profile.isObject1 = Console.getDataType({1: 'foo', 2: 'bar'});52 profile.isObject2 = Console.getDataType([1,2,3]);53 profile.isObject3 = Console.getDataType(new Foo());54})55.expect('isNull').toEqual('null')56.expect('isUndefined').toEqual('undefined')57.expect('isBoolean').toEqual('boolean')58.expect('isString').toEqual('string')59.expect('isNumber').toEqual('number')60.expect('isBigInt').toEqual('bigint')61.expect('isFunction').toEqual('function')62.expect('isSymbol').toEqual('symbol')63.expect('isObject1').toEqual('object')64.expect('isObject2').toEqual('object')65.expect('isObject3').toEqual('object');66Taste('Formatting falsy inputs')67.test(profile => {68 profile.test1 = Console.removeANSIColors(Console.log(0).colored);69 profile.test2 = Console.removeANSIColors(Console.log(-1).colored);70 profile.test3 = Console.removeANSIColors(Console.log(null).colored);71 profile.test4 = Console.removeANSIColors(Console.log(undefined).colored);72 profile.test5 = Console.removeANSIColors(Console.log(false).colored);73})74.expect('test1').toEqual('0')75.expect('test2').toEqual('-1')76.expect('test3').toEqual('null')77.expect('test4').toEqual('undefined')78.expect('test5').toEqual('false');79Taste('Formatting string inputs')80.test(profile => {81 profile.test1 = Console.removeANSIColors(Console.log('foo', 'bar').colored);82 profile.test2 = Console.removeANSIColors(Console.log('foo\nbar').colored);83 profile.test3 = Console.removeANSIColors(Console.log('').colored);84 profile.test4 = Console.removeANSIColors(Console.log('', '').colored);85 profile.test5 = Console.removeANSIColors(Console.log(' ').colored);86 profile.test6 = Console.removeANSIColors(Console.log(' ').colored);87 profile.test7 = Console.removeANSIColors(Console.log('foo' + 'bar').colored);88 profile.test8 = Console.removeANSIColors(Console.log(typeof 42).colored);89})90.expect('test1').toEqual('foo bar')91.expect('test2').toEqual('foo\nbar')92.expect('test3').toEqual('')93.expect('test4').toEqual(' ')94.expect('test6').toEqual(' ')95.expect('test7').toEqual('foobar')96.expect('test8').toEqual('number');97Taste('Formatting number inputs')98.test(profile => {99 profile.test1 = Console.removeANSIColors(Console.log(0).colored);100 profile.test2 = Console.removeANSIColors(Console.log(1).colored);101 profile.test3 = Console.removeANSIColors(Console.log(1, 2, 3).colored);102 profile.test4 = Console.removeANSIColors(Console.log(-1).colored);103 profile.test5 = Console.removeANSIColors(Console.log(40 + 2).colored);104 profile.test6 = Console.removeANSIColors(Console.log(0n).colored);105 profile.test7 = Console.removeANSIColors(Console.log(1n).colored);106})107.expect('test1').toEqual('0')108.expect('test2').toEqual('1')109.expect('test3').toEqual('1 2 3')110.expect('test4').toEqual('-1')111.expect('test5').toEqual('42')112.expect('test6').toEqual('0n')113.expect('test7').toEqual('1n');114Taste('Formatting boolean inputs')115.test(profile => {116 profile.test1 = Console.removeANSIColors(Console.log(true).colored);117 profile.test2 = Console.removeANSIColors(Console.log(3 === 3).colored);118 profile.test3 = Console.removeANSIColors(Console.log(!true).colored);119 profile.test4 = Console.removeANSIColors(Console.log(true, false).colored);120})121.expect('test1').toEqual('true')122.expect('test2').toEqual('true')123.expect('test3').toEqual('false')124.expect('test4').toEqual('true false');125Taste('Formatting array inputs')126.test(profile => {127 profile.test1 = Console.removeANSIColors(Console.log([1, 2, 3]).colored);128 profile.test2 = Console.removeANSIColors(Console.log([1, 'foo']).colored);129 profile.test3 = Console.removeANSIColors(Console.log([['a', 'b'], [1,2]]).colored);130})131.expect('test1').toEqual('[ 1, 2, 3 ]')132.expect('test2').toEqual('[ 1, \'foo\' ]')133.expect('test3').toEqual('[ [ \'a\', \'b\' ], [ 1, 2 ] ]');134Taste('Formatting symbol inputs')135.test(profile => {136 profile.test1 = Console.removeANSIColors(Console.log(Symbol(null)).colored);137 profile.test2 = Console.removeANSIColors(Console.log(Symbol(undefined)).colored);138 profile.test3 = Console.removeANSIColors(Console.log(Symbol('')).colored);139 profile.test4 = Console.removeANSIColors(Console.log(Symbol('foo')).colored);140 profile.test5 = Console.removeANSIColors(Console.log(Symbol(1)).colored);141})142.expect('test1').toEqual('Symbol(null)')143.expect('test2').toEqual('Symbol()')144.expect('test3').toEqual('Symbol()')145.expect('test4').toEqual('Symbol(foo)')146.expect('test5').toEqual('Symbol(1)');147Taste('Formatting object inputs')148.test(profile => {149 class Foo {150 constructor() {151 this.a = 1;152 this.b = '2';153 }154 }155 class Bar extends Foo {156 constructor() {157 super();158 this.c = true;159 this.d = null;160 }161 }162 profile.test1 = Console.removeANSIColors(Console.log({}).colored);163 profile.test2 = Console.removeANSIColors(Console.log({1: 'foo', a: 'bar'}).colored);164 profile.test3 = Console.removeANSIColors(Console.log({a: [1,2], b: null}).colored);165 profile.test4 = Console.removeANSIColors(Console.log(Foo).colored);166 profile.test5 = Console.removeANSIColors(Console.log(Bar).colored);167 profile.test6 = Console.removeANSIColors(Console.log(new Foo()).colored);168 profile.test7 = Console.removeANSIColors(Console.log(new Bar()).colored);169})170.expect('test1').toEqual('{ }')171.expect('test2').toEqual('{ 1: \'foo\', a: \'bar\' }')172.expect('test3').toEqual('{ a: [ 1, 2 ], b: null }')173.expect('test4').toEqual('[class Foo]')174.expect('test5').toEqual('[class Bar extends Foo]')175.expect('test6').toEqual('Foo { a: 1, b: \'2\' }')176.expect('test7').toEqual('Bar { a: 1, b: \'2\', c: true, d: null }');177Taste('Formatting function inputs')178.test(profile => {179 function foo() {}180 const bar = () => {}181 profile.test1 = Console.removeANSIColors(Console.log(foo).colored);182 profile.test2 = Console.removeANSIColors(Console.log(bar).colored);183 profile.test3 = Console.removeANSIColors(Console.log(function() {}).colored);184 profile.test4 = Console.removeANSIColors(Console.log(() => { return 'test'; }).colored);185})186.expect('test1').toEqual('[Function: foo]')187.expect('test2').toEqual('[Function: bar]')188.expect('test3').toEqual('[Function (anonymous)]')189.expect('test4').toEqual('[Function (anonymous)]');190Taste('Formatting circular references')191.test(profile => {192 class A {193 constructor() {194 this.a = 1;195 this.obj = new B(this);196 }197 }198 class B {199 constructor(ref) {200 this.b = 1;201 this.ref = ref;202 }203 }204 const arrayC = [1, 2, 3];205 const arrayD = ['a', 'b', arrayC];206 arrayC.push(arrayD);207 profile.test1 = Console.removeANSIColors(Console.log(new A()).colored);208 profile.test2 = Console.removeANSIColors(Console.log(arrayD).colored);209})210.expect('test1').toEqual('A { a: 1, obj: B { b: 1, ref: [Circular A] } }')211.expect('test2').toEqual('[ \'a\', \'b\', [ 1, 2, 3, [Circular Array] ] ]');212Taste('Formatting arrays in a log')213.test('Prints [ 1,2 ]',(profile) => {214 const a = [1,2];215 profile['formattedArray'] = Console.info(a).message;216})217.expect('formattedArray').toMatch('[ 1, 2 ]');218Taste('Formatting objects in a log')219.test('Prints { foo: 1, bar: 2 }', (profile) => {220 const o = {foo: 1, bar: 2};221 profile['formattedObject'] = Console.info(o).message;222})223.expect('formattedObject').toMatch('{ foo: 1, bar: 2 }');224Taste('Formatting multiple arguments in a log')225.test('Prints 1 2 3 and a b c', (profile) => {226 const v1 = 1;227 const v2 = 2;228 const v3 = 3;229 const v4 = 'a';230 const v5 = 'b';231 const v6 = 'c';232 profile['formattedArgs'] = Console.info(v1, v2, v3, 'and', v4, v5, v6).message;233})...

Full Screen

Full Screen

Logger.js

Source:Logger.js Github

copy

Full Screen

1'use strict';2const EventEmitter = require('@jikurata/events');3const {format} = require('util');4const State = require('./State.js');5const Record = require('./Record.js');6let instance = null;7class Logger extends EventEmitter {8 constructor() {9 if ( instance ) return instance;10 super();11 instance = this;12 Object.defineProperty(this, 'state', {13 value: new State({14 'HISTORY_LIMIT': 50,15 'COLOR': {16 'default': '\x1b[0m',17 'boolean': '\x1b[38;5;27m',18 'number': '\x1b[38;5;64m',19 'string': '\x1b[38;5;130m',20 'text': '\x1b[38;5;250m',21 'array': '\x1b[38;5;248m',22 'object': '\x1b[38;5;248m',23 'function': '\x1b[38;5;30m',24 'bigint': '\x1b[38;5;179m', 25 'symbol': '\x1b[38;5;99m',26 'property': '\x1b[38;5;75m',27 'undefined': '\x1b[38;5;240m',28 'null': '\x1b[38;5;240m',29 'circular': '\x1b[38;5;171m',30 'info': '\x1b[38;5;28m',31 'warn': '\x1b[38;5;100m',32 'error': '\x1b[38;5;88m',33 'timestamp': '\x1b[38;5;240m'34 },35 'USE_COLORS': true,36 'PRINT_MESSAGE': true,37 'SHOW_TIMESTAMP': true,38 'SHOW_TIMEZONE': false,39 'EMIT_RECORD': true40 }),41 enumerable: true,42 writable: false,43 configurable: false44 });45 Object.defineProperty(this, 'history', {46 value: [],47 enumerable: true,48 writable: false,49 configurable: false50 });51 }52 /**53 * @param {String} type54 * @param {...Any} args 55 */56 _print(type, ...args) {57 const r = this.createRecord(type, ...args);58 this.printRecord(r);59 return r;60 }61 /**62 * @param {...Any} args63 * @returns {Record}64 */65 log(...args) {66 return this._print('info', ...args);67 }68 /**69 * @param {...Any} args70 * @returns {Record}71 */72 info(...args) {73 return this._print('info', ...args);74 }75 /**76 * @param {...Any} args77 * @returns {Record}78 */79 warn(...args) {80 return this._print('warn', ...args);81 }82 /**83 * @param {...Any} args84 * @returns {Record}85 */86 error(...args) {87 return this._print('error', ...args);88 }89 /**90 * Create a Record object91 * @param {String} type 92 * @param {...Any} args 93 * @returns {Record}94 */95 createRecord(type, ...args) {96 const t = Date.now();97 const s = this.formatColors(args);98 const record = new Record({99 type: type,100 timestamp: t,101 message: this.removeANSIColors(s),102 colored: s103 });104 // Add record to history105 this.history.push(record);106 // Remove the first entry while the current size exceeds the history limit107 let count = this.history.length - this.state.HISTORY_LIMIT;108 if ( count > 0 ) {109 for ( count; count--; ) {110 this.history.shift();111 }112 }113 if ( this.emitRecord ) {114 this.emit('record', record);115 }116 return record;117 }118 /**119 * Format a record to be printed in console120 * @param {Record} record 121 */122 printRecord(record) {123 if ( !this.printMessage ) {124 return;125 }126 let s = `# `;127 if ( this.showTimestamp ) {128 const ts = new Date(record.timestamp).toString().split(' ').slice(1, (this.showTimezone) ? 6 : 5).join(' ');129 s += `${this.getColor('timestamp')}[${ts}] `;130 }131 s += (this.useColors) ? record.colored : record.message + '\n';132 133 switch(record.type) {134 case 'info': 135 s = `${this.getColor('info')}${s}`;136 return console.info(s);137 case 'warn': 138 s = `${this.getColor('warn')}${s}`;139 return console.warn(s);140 case 'error': 141 s = `${this.getColor('error')}${s}`;142 return console.error(s);143 default: 144 s = `${this.getColor('default')}${s}`145 return console.log(s);146 }147 }148 /**149 * Stringify arguments and append color codes to data types150 * @param {Array<Any>} args151 * @returns {String} 152 */153 formatColors(args) {154 const objStack = [];155 const formatter = (arg) => {156 // Check arg's data type157 const type = this.getDataType(arg);158 const argStr = format(arg);159 if ( type === 'object' ) {160 const objectClass = (arg.constructor && arg.constructor.name) ? arg.constructor.name : '';161 // Check for cyclic references162 if ( objStack.indexOf(arg) === -1 ) {163 objStack.push(arg);164 let substr = '';165 // Format error objects166 if ( arg instanceof Error ) {167 if ( arg.stack ) {168 const split = arg.stack.split(':');169 for ( let i = 0; i < split.length; ++i ) {170 if ( i === 0 ) {171 substr += `${this.getColor('error')}`;172 }173 else if ( i === 1 ) {174 substr += `${this.getColor('text')}`;175 }176 substr += `${split[i]}:`;177 }178 }179 else {180 substr = `${this.getColor('error')}${arg.name}: ${this.getColor('text')}${arg.message}`;181 }182 }183 else if ( Array.isArray(arg) ) {184 // Format an array185 substr = `${this.getColor('array')}[ `;186 for ( let i = 0; i < arg.length; ++i ) {187 substr += `${formatter(arg[i])}`;188 substr += (i < arg.length - 1) ? `${this.getColor('array')}, ` : ' ';189 }190 substr += `${this.getColor('array')}]`;191 }192 else {193 // Format a generic object type194 substr = `${this.getColor('object')}${(objectClass && objectClass !== 'Object') ? objectClass + ' ' : ''}{ `;195 const keys = Object.keys(arg);196 for ( let i = 0; i < keys.length; ++i ) {197 const key = keys[i];198 const value = arg[key];199 substr += `${this.getColor('property')}${key}: ${formatter(value)}`;200 substr += (i < keys.length - 1) ? `${this.getColor('object')}, ` : ' ';201 }202 substr += `${this.getColor('object')}}`;203 }204 // Format complete for current object, remove from stack205 objStack.pop();206 return substr;207 }208 else {209 // Object is a cyclic reference210 return `${this.getColor('circular')}[Circular ${(objectClass)}]`;211 }212 }213 else if ( type === 'string' ) {214 // If the string is an object value, use the string color code215 if ( objStack.length ) {216 return `${this.getColor('string')}\'${argStr}${this.getColor('string')}\'`;217 }218 return `${this.getColor('text')}${argStr}`;219 }220 else {221 return `${this.getColor(type)}${argStr}`;222 }223 }224 let a = [];225 for ( let i = 0; i < args.length; ++i ) {226 a.push(formatter(args[i]));227 }228 return format(...a);229 }230 /**231 * Return the data type of arg232 * @param {Any} arg233 * @returns {String}234 */235 getDataType(arg) {236 if ( arg === null ) {237 return 'null';238 }239 else if ( arg === undefined ) {240 return 'undefined';241 }242 else if ( arg && typeof arg === 'object' ) {243 return 'object';244 }245 else {246 return typeof arg;247 }248 }249 /**250 * Get an ANSI color code for the corresponding type251 * @param {String} color 252 * @returns {String}253 */254 getColor(type) {255 return (this.state.COLOR.hasOwnProperty(type)) ? this.state.COLOR[type] : this.state.COLOR.text;256 }257 /**258 * Remove all ANSI escape attribute codes259 * @param {String} s 260 */261 removeANSIColors(s) {262 const matches = s.match(/\x1b\[[\d|;]*m/gmi);263 if ( matches ) {264 for ( let i = 0; i < matches.length; ++i ) {265 s = s.replace(matches[i], '');266 }267 }268 return s;269 }270 get historyLimit() {271 return this.state.HISTORY_LIMIT;272 }273 set historyLimit(num) {274 if ( num > -1 ) this.state.HISTORY_LIMIT = num;275 }276 get useColors() {277 return this.state.USE_COLORS;278 }279 set useColors(bool) {280 this.state.USE_COLORS = !!bool;281 }282 get printMessage() {283 return this.state.PRINT_MESSAGE;284 }285 set printMessage(bool) {286 this.state.PRINT_MESSAGE = !!bool;287 }288 get showTimestamp() {289 return this.state.SHOW_TIMESTAMP;290 }291 set showTimestamp(bool) {292 this.state.SHOW_TIMESTAMP = !!bool;293 }294 get showTimezone() {295 return this.state.SHOW_TIMEZONE;296 }297 set showTimezone(bool) {298 this.state.SHOW_TIMEZONE = !!bool;299 }300 get emitRecord() {301 return this.state.EMIT_RECORD;302 }303 set emitRecord(bool) {304 this.state.EMIT_RECORD = !!bool;305 }306}...

Full Screen

Full Screen

service.js

Source:service.js Github

copy

Full Screen

1const { Server } = require('socket.io');2const { createServer } = require("http");3const { spawn } = require('child_process');4const httpServer = createServer();5const fs = require('fs')6const { v4: uuidv4 } = require('uuid');7const dotenv = require('dotenv');8var path = require('path');9const local_dir = './resources/temp'10dotenv.config();11spawn(12 `cd ${process.env.ELIXIR_DIR} && 13 poetry run gradualelixir configure --working-dir ${path.resolve(__dirname)}/resources/temp`, 14 { shell: true }15);16const io = new Server(httpServer, {17 cors: {18 origin: "http://localhost:3000",19 credentials: true20 }21});22const removeANSIColors = (str) => {23 return str.replace(24 /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,25 ''26 );27}28const events = [29 {30 name: 'typecheck static',31 command: (filename) => `cd ${process.env.ELIXIR_DIR} && poetry run gradualelixir type_check --static ${filename}`32 },33 {34 name: 'typecheck',35 command: (filename) => `cd ${process.env.ELIXIR_DIR} && poetry run gradualelixir type_check ${filename}`36 },37 {38 name: 'annotate types',39 command: (filename) => `cd ${process.env.ELIXIR_DIR} && poetry run gradualelixir type_check --annotate types ${filename}`,40 fileSubfix: '_types.ex'41 },42 {43 name: 'annotate casts',44 command: (filename) => `cd ${process.env.ELIXIR_DIR} && poetry run gradualelixir type_check --annotate casts ${filename}`,45 fileSubfix: '_casts.ex'46 }47]48io.on('connection', socket => {49 events.forEach((ev) => {50 try { 51 socket.on(ev.name, (arg) => {52 socket.emit('lock')53 const uuid = uuidv4()54 const filename = `${uuid}.ex`55 const path = `${local_dir}/${filename}`56 fs.writeFileSync(path, arg, () => {})57 const command = spawn(ev.command(filename), { shell: true });58 command.stderr.on('data', (data) => {59 socket.emit('input', {60 code: removeANSIColors(data.toString()),61 isElixir: false62 })63 })64 command.stdout.on('data', (data) => {65 if(!fs.existsSync(`${local_dir}/${uuid}${ev.fileSubfix}`)) {66 socket.emit('input', {67 code: removeANSIColors(data.toString()),68 isElixir: false69 })70 }71 })72 command.stdout.on('close', () => {73 fs.unlink(path, () => {})74 if(ev.fileSubfix) {75 const auxFile = `${local_dir}/${uuid}${ev.fileSubfix}`76 if (fs.existsSync(auxFile)) {77 const content = fs.readFileSync(auxFile, {encoding:'utf8', flag:'r'});78 socket.emit('input', {79 code: content,80 isElixir: true81 })82 fs.unlink(auxFile, () => {})83 }84 }85 socket.emit('unlock')86 })87 })88 }89 catch (err) {90 io.emit('input', err)91 socket.emit('unlock')92 }93 })94});95io.on('disconnect', () => {96 console.log('bye')97})...

Full Screen

Full Screen

status.json.js

Source:status.json.js Github

copy

Full Screen

...23});24router.get('/', function (req, res) {25 shelljs.exec('grep "error" ' + __dirname + '/../logs/log | tail -n 1',26 function (exitcode, logOutput) {27 var lastError = utils.removeAnsiColors(logOutput);28 var lastErrorTimestamp = Math.round((new Date(lastError.split(' ')[0])).29 getTime()/1000);30 res.send(JSON.stringify({31 hostname: os.hostname(),32 uptime: os.uptime(),33 loadavg: os.loadavg(),34 totalmem: os.totalmem(),35 freemem: os.freemem(),36 processUptime: process.uptime(),37 mongoConnect: db.isConnect(),38 redisConnect: redis.status === "ready" ? true : false,39 lastError: lastError,40 lastErrorTimestamp: lastErrorTimestamp,41 gitShort: git.short,...

Full Screen

Full Screen

utils.js

Source:utils.js Github

copy

Full Screen

1var crypto = require('crypto');2function randomToken (len) {3 if (!len) {4 len = 16;5 }6 return crypto.randomBytes(Math.ceil(len * 3 / 4))7 .toString('base64') // convert to base64 format8 .slice(0, len) // return required number of characters9 .replace(/\+/g, '0') // replace '+' with '0'10 .replace(/\//g, '0'); // replace '/' with '0'11}12exports.randomToken = randomToken;13function getRandomItem (items) {14 return items[Math.floor(Math.random()*items.length)];15}16exports.getRandomItem = getRandomItem;17function removeAnsiColors (string) {18 return string.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '');19}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { removeAnsiColors } = require('playwright-core/lib/utils/terminal');2const { test, expect } = require('@playwright/test');3test('test', async ({ page }) => {4 const title = await page.innerText('.navbar__inner .navbar__title');5 expect(removeAnsiColors(title)).toBe('Playwright');6});7### `removeAnsiColors(str)`8### `removeAnsiColors.stripColor(str)`9### `removeAnsiColors.hasColor(str)`10### `removeAnsiColors.hasAnsi(str)`11### `removeAnsiColors.hasAnsiColors(str)`12### `removeAnsiColors.hasAnsiCodes(str)`13### `removeAnsiColors.hasAnsiCodesOrMarkup(str)`14### `removeAnsiColors.hasAnsiMarkup(str)`

Full Screen

Using AI Code Generation

copy

Full Screen

1const { removeAnsiColors } = require('playwright/lib/internal/util');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 const title = await page.title();8 console.log(`Title: ${removeAnsiColors(title)}`);9 await browser.close();10})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { removeAnsiColors } = require('@playwright/test/lib/utils/terminal');2const { test } = require('@playwright/test');3test('test', async ({ page }) => {4 const title = await page.textContent('text=The most reliable end-to-end testing tool');5 console.log(title);6 console.log(removeAnsiColors(title));7});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { removeAnsiColors } = require('@playwright/test/lib/utils/terminal');2const { test } = require('@playwright/test');3const assert = require('assert');4test('removeAnsiColors', async ({}) => {5 const str = '\u001b[32mHello World';6 const result = removeAnsiColors(str);7 assert.strictEqual(result, 'Hello World');8});9 at Object.toBe (test.js:11:18)

Full Screen

Using AI Code Generation

copy

Full Screen

1const { removeAnsiColors } = require('@playwright/test/lib/utils/terminal');2console.log(removeAnsiColors('\u001b[31mHello World!'));3### `isUnderTest()`4const { isUnderTest } = require('@playwright/test/lib/utils/utils');5console.log(isUnderTest());6### `setUnderTest()`7const { setUnderTest } = require('@playwright/test/lib/utils/utils');8setUnderTest();9### `createGuid()`10const { createGuid } = require('@playwright/test/lib/utils/utils');11console.log(createGuid());12### `createGuids()`13const { createGuids } = require('@playwright/test/lib/utils/utils');14console.log(createGuids(3));15### `isGuid()`16const { is

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