Best JavaScript code snippet using best
runner-stream.ts
Source:runner-stream.ts
1/*2 * Copyright (c) 2019, salesforce.com, inc.3 * All rights reserved.4 * SPDX-License-Identifier: MIT5 * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT6*/7import path from "path";8import { isInteractive as globaIsInteractive } from "@best/utils";9import chalk from "chalk";10import trimPath from "./utils/trim-path";11import countEOL from "./utils/count-eod";12import { ProxiedStream, proxyStream } from "./utils/proxy-stream";13import {14 BenchmarkRuntimeConfig,15 RunnerStream,16 BenchmarksBundle,17 BenchmarkUpdateState,18} from "@best/types";19enum State {20 QUEUED = 'QUEUED',21 RUNNING = 'RUNNING',22 DONE = 'DONE',23 ERROR = 'ERROR',24}25interface BenchmarkStatus { state: State; displayPath: string; projectName: string, progress?: BenchmarkProgress }26type AllBencharkRunnerState = Map<string, BenchmarkStatus>27interface BenchmarkProgress {28 executedIterations: number,29 estimated: number,30 runtime: number,31 avgIteration: number,32}33const STATE_ANSI = {34 RUNNING: chalk.reset.inverse.yellow.bold(` ${State.RUNNING} `),35 QUEUED: chalk.reset.inverse.gray.bold(` ${State.QUEUED} `),36 ERROR: chalk.reset.inverse.redBright.bold(` ${State.ERROR} `),37 DONE: chalk.reset.inverse.green.bold(` ${State.DONE} `),38};39const INIT_MSG = '\n Running benchmarks... \n\n';40const PROGRESS_TEXT = chalk.dim('Progress running: ');41const PROGRESS_BAR_WIDTH = 40;42const DEFAULT_TIMEOUT = 60;43function printState(state: State) {44 return STATE_ANSI[state];45}46function printDisplayName(displayPath: string, overflow: number) {47 const dirname = overflow ? trimPath(path.dirname(displayPath), overflow) : path.dirname(displayPath);48 const basename = path.basename(displayPath);49 return chalk.dim(dirname + path.sep) + chalk.bold(basename);50}51function printProjectName(projectName: string) {52 return ' ' + chalk.reset.cyan.dim(`(${projectName})`);53}54function calculateBenchmarkProgress(progress: BenchmarkUpdateState, { iterations, maxDuration, minSampleCount }: BenchmarkRuntimeConfig): BenchmarkProgress {55 const { executedIterations, executedTime } = progress;56 const avgIteration = executedTime / executedIterations;57 const runtime = parseInt((executedTime / 1000) + '', 10);58 let estimated: number;59 if (iterations) {60 estimated = Math.round(iterations * avgIteration / 1000) + 1;61 } else if (avgIteration * minSampleCount > maxDuration) {62 estimated = Math.round(minSampleCount * avgIteration / 1000) + 1;63 } else {64 estimated = maxDuration / 1000;65 }66 return {67 executedIterations,68 estimated,69 runtime,70 avgIteration,71 };72}73function printProgressBar(runTime: number, estimatedTime: number, width: number) {74 // If we are more than one second over the estimated time, highlight it.75 const renderedTime = estimatedTime && runTime >= estimatedTime + 1 ? chalk.bold.yellow(runTime + 's') : runTime + 's';76 let time = chalk.bold(`Time:`) + ` ${renderedTime}`;77 if (runTime < estimatedTime) {78 time += `, estimated ${estimatedTime}s`;79 }80 // Only show a progress bar if the test run is actually going to take some time81 if (estimatedTime > 2 && runTime < estimatedTime && width) {82 const availableWidth = Math.min(PROGRESS_BAR_WIDTH, width);83 const length = Math.min(Math.floor(runTime / estimatedTime * availableWidth), availableWidth);84 if (availableWidth >= 2) {85 time += '\n' + chalk.green('â').repeat(length) + chalk.white('â').repeat(availableWidth - length);86 }87 }88 return time;89}90export default class RunnerOutputStream implements RunnerStream {91 stdoutColumns: number;92 stdoutWrite: Function;93 isInteractive: boolean;94 _streamBuffer: string = '';95 _state: AllBencharkRunnerState;96 _innerLog: string = '';97 _scheduled: NodeJS.Timeout | null = null;98 _proxyStream: ProxiedStream;99 constructor(buildConfig: BenchmarksBundle[], stream: NodeJS.WriteStream, isInteractive?: boolean) {100 this.stdoutColumns = stream.columns || 80;101 this.stdoutWrite = stream.write.bind(stream);102 this.isInteractive = isInteractive !== undefined ? isInteractive : globaIsInteractive;103 this._state = this.initState(buildConfig);104 this._proxyStream = proxyStream(stream, this.isInteractive);105 }106 initState(buildConfigs: BenchmarksBundle[]): AllBencharkRunnerState {107 return buildConfigs.reduce((state: AllBencharkRunnerState, benchmarkBundle: BenchmarksBundle): AllBencharkRunnerState => {108 benchmarkBundle.benchmarkBuilds.forEach(({ benchmarkEntry, benchmarkSignature, projectConfig: { projectName }}) => {109 state.set(benchmarkSignature, {110 projectName,111 state: State.QUEUED,112 displayPath: benchmarkEntry,113 });114 });115 return state;116 }, new Map());117 }118 clearBufferStream() {119 let buffer = this._streamBuffer;120 const lines = countEOL(buffer);121 if (lines) {122 buffer = '\r\x1B[K\r\x1B[1A'.repeat(lines);123 }124 if (this.isInteractive) {125 // clear last line126 this.stdoutWrite('\x1b[999D\x1b[K');127 }128 this.stdoutWrite(buffer);129 this._streamBuffer = '';130 }131 writeBufferStream(str: string) {132 this._streamBuffer += str;133 this.stdoutWrite(str);134 }135 updateRunnerState(benchmarkSignature: string, state: State) {136 const stateConfig = this._state.get(benchmarkSignature);137 if (!stateConfig) {138 throw new Error(`Unknown benchmark build started (${benchmarkSignature})`);139 }140 if (stateConfig.state !== State.ERROR) {141 stateConfig.state = state;142 }143 }144 scheduleUpdate(time?: number, fn?: Function) {145 if (!this._scheduled) {146 this._scheduled = setTimeout(() => {147 fn ? fn() : this.updateStream();148 this._scheduled = null;149 }, time || DEFAULT_TIMEOUT);150 }151 }152 printBenchmarkState({ state, projectName, displayPath }: { state: State, projectName: string, displayPath: string }) {153 const columns = this.stdoutColumns;154 const overflow = columns - (state.length + projectName.length + displayPath.length + /* for padding */ 14);155 const hasOverflow = overflow < 0;156 const ansiState = printState(state);157 const ansiProjectName = printProjectName(projectName);158 const ansiDisplayname = printDisplayName(displayPath, hasOverflow ? Math.abs(overflow): 0);159 return `${ansiState} ${ansiProjectName} ${ansiDisplayname}\n`;160 }161 printProgress(progress: BenchmarkProgress, { displayPath }: BenchmarkStatus): string {162 const benchmarkName = chalk.bold.black(path.basename(displayPath));163 return [164 `\n${PROGRESS_TEXT} ${benchmarkName}`,165 chalk.bold.black('Avg iteration: ') + progress.avgIteration.toFixed(2) + 'ms',166 chalk.bold.black('Completed iterations: ') + progress.executedIterations,167 printProgressBar(progress.runtime, progress.estimated, 40)168 ].join('\n') + '\n\n';169 }170 updateStream() {171 let buffer = INIT_MSG;172 let progressStr: string = '';173 for (const benchmarkState of this._state.values()) {174 const { state, displayPath, projectName, progress } = benchmarkState;175 buffer += this.printBenchmarkState({ state, displayPath, projectName });176 if (state === State.RUNNING && progress) {177 progressStr += this.printProgress(progress, benchmarkState);178 }179 }180 const streamProxyBuffer = this._proxyStream.readBuffer();181 streamProxyBuffer ? `Buffered console logs:\n ${streamProxyBuffer}` : '';182 this.clearBufferStream();183 this.writeBufferStream(buffer + progressStr + streamProxyBuffer);184 }185 log(message: string) {186 this._innerLog = message;187 if (this.isInteractive) {188 this.scheduleUpdate();189 } else {190 this.stdoutWrite(` :: ${message}\n`);191 }192 }193 _clearTimeout() {194 if (this._scheduled) {195 clearTimeout(this._scheduled);196 this._scheduled = null;197 }198 }199 // -- Lifecycle200 onBenchmarkStart(benchmarkSignature: string) {201 this.updateRunnerState(benchmarkSignature, State.RUNNING);202 if (this.isInteractive) {203 this.scheduleUpdate();204 } else {205 const benchmarkState = this._state.get(benchmarkSignature);206 if (benchmarkState) {207 this.stdoutWrite(this.printBenchmarkState(benchmarkState));208 }209 }210 }211 onBenchmarkEnd(benchmarkSignature: string) {212 this.updateRunnerState(benchmarkSignature, State.DONE);213 this._innerLog = '';214 const benchmarkState = this._state.get(benchmarkSignature);215 if (benchmarkState) {216 if (this.isInteractive) {217 if (benchmarkState.state === State.ERROR) {218 this.updateStream();219 this.stdoutWrite('\n');220 } else {221 this.scheduleUpdate();222 }223 } else {224 this._clearTimeout();225 this.stdoutWrite(this.printBenchmarkState(benchmarkState) + '\n');226 }227 }228 }229 onBenchmarkError(benchmarkSignature: string) {230 this.updateRunnerState(benchmarkSignature, State.ERROR);231 }232 updateBenchmarkProgress(benchmarkSignature: string, updatedBenchmarkState: BenchmarkUpdateState, runtimeOpts: BenchmarkRuntimeConfig) {233 const progress = calculateBenchmarkProgress(updatedBenchmarkState, runtimeOpts);234 const benchmarkState = this._state.get(benchmarkSignature);235 benchmarkState!.progress = progress;236 const { executedIterations, avgIteration, estimated, runtime } = progress;237 const runIter = executedIterations.toString().padEnd(5, " ");238 const avgIter = `${avgIteration.toFixed(2)}ms`.padEnd(10, " ");239 const remaining = estimated - runtime;240 if (this.isInteractive) {241 this.scheduleUpdate();242 } else {243 this.scheduleUpdate(2500, () => {244 this.stdoutWrite(245 ` :: ${benchmarkState!.displayPath} > ran: ${runIter} | avg: ${avgIter} | remainingTime: ${remaining}s \n`246 );247 });248 }249 }250 init() {251 if (this.isInteractive) {252 this.updateStream();253 } else {254 this.stdoutWrite(INIT_MSG);255 }256 }257 finish() {258 this._clearTimeout();259 this._proxyStream.unproxyStream();260 if (this.isInteractive) {261 this.updateStream();262 } else {263 this.stdoutWrite('\n');264 }265 }...
build-stream.ts
Source:build-stream.ts
1/*2 * Copyright (c) 2019, salesforce.com, inc.3 * All rights reserved.4 * SPDX-License-Identifier: MIT5 * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT6*/7import path from "path";8import { isInteractive as globaIsInteractive } from "@best/utils";9import chalk from "chalk";10import trimPath from "./utils/trim-path";11import countEOL from "./utils/count-eod";12import { ProxiedStream, proxyStream } from "./utils/proxy-stream";13interface ProjectBenchmarkTests {14 config: { projectName: string; rootDir: string },15 matches: string[]16}17type ListProjectBenchmarkTests = ProjectBenchmarkTests[];18enum State {19 QUEUED = 'QUEUED',20 BUILDING = 'BUILDING',21 DONE = 'DONE',22}23interface BenchmarkState { state: State; displayPath: string; projectName: string }24type AllBencharkState = Map<string, BenchmarkState>25const STATE_ANSI = {26 BUILDING: chalk.reset.inverse.yellow.bold(` ${State.BUILDING} `),27 QUEUED: chalk.reset.inverse.gray.bold(` ${State.QUEUED} `),28 DONE: chalk.reset.inverse.green.bold(` ${State.DONE} `)29};30const INIT_MSG = '\n Building benchmarks... \n\n';31function printState(state: State) {32 return STATE_ANSI[state];33}34function printDisplayName(displayPath: string, overflow: number) {35 const dirname = overflow ? trimPath(path.dirname(displayPath), overflow) : path.dirname(displayPath);36 const basename = path.basename(displayPath);37 return chalk.dim(dirname + path.sep) + chalk.bold(basename);38}39function printProjectName(projectName: string) {40 return ' ' + chalk.reset.cyan.dim(`(${projectName})`);41}42export default class BuildOutputStream {43 stdoutColumns: number;44 stdoutWrite: Function;45 isInteractive: boolean;46 _streamBuffer: string = '';47 _state: AllBencharkState;48 _innerLog: string = '';49 _scheduled: NodeJS.Timeout | null = null;50 _proxiedStream: ProxiedStream;51 constructor(buildConfig: ListProjectBenchmarkTests, stream: NodeJS.WriteStream, isInteractive?: boolean) {52 this.stdoutColumns = stream.columns || 80;53 this.stdoutWrite = stream.write.bind(stream);54 this.isInteractive = isInteractive !== undefined ? isInteractive : globaIsInteractive;55 this._state = this.initState(buildConfig);56 this._proxiedStream = proxyStream(stream, this.isInteractive);57 }58 initState(buildConfig: ListProjectBenchmarkTests) {59 return buildConfig.reduce((state: AllBencharkState, { matches, config: { rootDir, projectName } }: ProjectBenchmarkTests) => {60 matches.forEach((benchmarkAbsPath) => {61 state.set(benchmarkAbsPath, {62 projectName,63 state: State.QUEUED,64 displayPath: path.relative(rootDir, benchmarkAbsPath),65 });66 });67 return state;68 }, new Map());69 }70 clearBufferStream() {71 let buffer = this._streamBuffer;72 const lines = countEOL(buffer);73 if (lines) {74 buffer = '\r\x1B[K\r\x1B[1A'.repeat(lines);75 }76 if (this.isInteractive) {77 // clear last line78 this.stdoutWrite('\x1b[999D\x1b[K');79 }80 this.stdoutWrite(buffer);81 this._streamBuffer = '';82 }83 writeBufferStream(str: string) {84 this._streamBuffer += str;85 this.stdoutWrite(str);86 }87 updateBenchmarkState(benchmarkPath: string, state: State) {88 const stateConfig = this._state.get(benchmarkPath);89 if (!stateConfig) {90 throw new Error(`Unknown benchmark build started (${benchmarkPath})`);91 }92 stateConfig.state = state;93 }94 onBenchmarkBuildStart(benchmarkPath: string) {95 this.updateBenchmarkState(benchmarkPath, State.BUILDING);96 if (this.isInteractive) {97 this.scheduleUpdate();98 } else {99 const benchmarkState = this._state.get(benchmarkPath);100 if (benchmarkState) {101 this.stdoutWrite(this.printBenchmark(benchmarkState));102 }103 }104 }105 scheduleUpdate() {106 if (!this._scheduled) {107 this._scheduled = setTimeout(() => {108 this.updateStream();109 this._scheduled = null;110 }, 10);111 }112 }113 printBenchmark({ state, projectName, displayPath }:{ state: State, projectName: string, displayPath: string }, streamProxyBuffer?: string) {114 const columns = this.stdoutColumns;115 const overflow = columns - (state.length + projectName.length + displayPath.length + /* for padding */ 14);116 const hasOverflow = overflow < 0;117 const ansiState = printState(state);118 const ansiProjectName = printProjectName(projectName);119 const ansiDisplayname = printDisplayName(displayPath, hasOverflow ? Math.abs(overflow): 0);120 const proxiedBuffer = streamProxyBuffer ? `Buffered console logs:\n ${streamProxyBuffer}` : '';121 return `${ansiState} ${ansiProjectName} ${ansiDisplayname}\n${proxiedBuffer}`;122 }123 updateStream() {124 const innerState = this._innerLog;125 let buffer = INIT_MSG;126 for (const { state, displayPath, projectName } of this._state.values()) {127 buffer += this.printBenchmark({ state, displayPath, projectName }, this._proxiedStream.readBuffer());128 }129 if (innerState) {130 buffer += `\n${innerState}\n`;131 }132 this.clearBufferStream();133 this.writeBufferStream(buffer);134 }135 onBenchmarkBuildEnd(benchmarkPath: string) {136 this.updateBenchmarkState(benchmarkPath, State.DONE);137 this._innerLog = '';138 if (this.isInteractive) {139 this.scheduleUpdate();140 } else {141 const benchmarkState = this._state.get(benchmarkPath);142 if (benchmarkState) {143 this.stdoutWrite(this.printBenchmark(benchmarkState, this._proxiedStream.readBuffer()) + '\n');144 }145 }146 }147 log(message: string) {148 this._innerLog = message;149 if (this.isInteractive) {150 this.scheduleUpdate();151 } else {152 this.stdoutWrite(` :: ${message}\n`);153 }154 }155 init() {156 if (this.isInteractive) {157 this.updateStream();158 } else {159 this.stdoutWrite(INIT_MSG);160 }161 }162 finish() {163 this._proxiedStream.unproxyStream();164 if (this._scheduled) {165 clearTimeout(this._scheduled);166 this._scheduled = null;167 }168 if (this.isInteractive) {169 this.updateStream();170 } else {171 this.stdoutWrite('\n');172 }173 }...
Using AI Code Generation
1var BestFitMapping = require('BestFitMapping');2var bfm = new BestFitMapping();3var ansiName = bfm.ansiDisplayname("日本語");4console.log(ansiName);5var BestFitMapping = require('BestFitMapping');6var bfm = new BestFitMapping();7var ansiName = bfm.ansiDisplayname("日本語", "UTF-8");8console.log(ansiName);9var BestFitMapping = require('BestFitMapping');10var bfm = new BestFitMapping();11var ansiName = bfm.ansiDisplayname("日本語", "UTF-8", "EUC-JP");12console.log(ansiName);13var BestFitMapping = require('BestFitMapping');14var bfm = new BestFitMapping();15var ansiName = bfm.ansiDisplayname("日本語", "UTF-8", "EUC-JP", "UTF-8");16console.log(ansiName);17var BestFitMapping = require('BestFitMapping');18var bfm = new BestFitMapping();19var ansiName = bfm.ansiDisplayname("日本語", "UTF-8", "EUC-JP", "UTF-8", 0);20console.log(ansiName);21var BestFitMapping = require('BestFitMapping');22var bfm = new BestFitMapping();23var ansiName = bfm.ansiDisplayname("日本語", "UTF-8", "EUC-JP", "UTF-8", 0, 0);24console.log(ansiName);25var BestFitMapping = require('BestFitMapping');26var bfm = new BestFitMapping();27var ansiName = bfm.ansiDisplayname("
Using AI Code Generation
1var BestNameResolver = require('./bestnameresolver');2var resolver = new BestNameResolver();3console.log(resolver.ansiDisplayname('D:\\test\\test1.js'));4console.log(resolver.ansiDisplayname('D:\\test\\test2.js'));5console.log(resolver.ansiDisplayname('D:\\test\\test3.js'));6console.log(resolver.ansiDisplayname('D:\\test\\test4.js'));7var BestNameResolver = require('./bestnameresolver');8var resolver = new BestNameResolver();9console.log(resolver.ansiDisplayname('D:\\test\\test1.js'));10console.log(resolver.ansiDisplayname('D:\\test\\test2.js'));11console.log(resolver.ansiDisplayname('D:\\test\\test3.js'));12console.log(resolver.ansiDisplayname('D:\\test\\test4.js'));13console.log(resolver.ansiDisplayname('D:\\test\\test5.js'));
Using AI Code Generation
1var BestName = require('bestname');2var bestName = new BestName();3var name = bestName.ansiDisplayname('A', 'B', 'C');4console.log('Name: ' + name);5var BestName = require('bestname');6var bestName = new BestName();7var name = bestName.ansiDisplayname('A', 'B', 'C');8console.log('Name: ' + name);9var BestName = require('bestname');10var bestName = new BestName();11var name = bestName.ansiDisplayname('A', 'B', 'C');12console.log('Name: ' + name);13var BestName = require('bestname');14var bestName = new BestName();15var name = bestName.ansiDisplayname('A', 'B', 'C');16console.log('Name: ' + name);17var BestName = require('bestname');18var bestName = new BestName();19var name = bestName.ansiDisplayname('A', 'B', 'C');20console.log('Name: ' + name);21var BestName = require('bestname');22var bestName = new BestName();23var name = bestName.ansiDisplayname('A', 'B', 'C');24console.log('Name: ' + name);25var BestName = require('bestname');26var bestName = new BestName();27var name = bestName.ansiDisplayname('A', 'B', 'C');28console.log('Name: ' + name);29var BestName = require('bestname');30var bestName = new BestName();31var name = bestName.ansiDisplayname('A', 'B', 'C');32console.log('Name: ' + name);
Using AI Code Generation
1var BestName = require(./bestName.js);2var bn = new BestName();3bn.setGivenName("John");4bn.setFamilyName("Doe");5bn.setDisplayName("John Doe");6var BestName = require(./bestName.js);7var bn = new BestName();8bn.setGivenName("John");9bn.setFamilyName("Doe");10bn.setDisplayName("John Doe");11var BestName = require(./bestName.js);12var bn = new BestName();13bn.setGivenName("John");14bn.setFamilyName("Doe");15bn.setDisplayName("John Doe");16var BestName = require(./bestName.js);17var bn = new BestName();18bn.setGivenName("John");19bn.setFamilyName("Doe");20bn.setDisplayName("John Doe");21var BestName = require(./bestName.js);22var bn = new BestName();23bn.setGivenName("John");24bn.setFamilyName("Doe");25bn.setDisplayName("John Doe");26var BestName = require(./bestName.js);27var bn = new BestName();28bn.setGivenName("John");29bn.setFamilyName("Doe");30bn.setDisplayName("John Doe");31var BestName = require(./bestName.js);32var bn = new BestName();33bn.setGivenName("John");34bn.setFamilyName("Doe");35bn.setDisplayName("John Doe");
Using AI Code Generation
1var BestName = require('bestname');2var bn = new BestName();3var name = bn.ansiDisplayname('John', 'Smith', 'III');4console.log('The name is: ' + name);5var BestName = require('bestname');6var bn = new BestName();7var name = bn.ansiDisplayname('John', 'Smith', 'III');8console.log('The name is: ' + name);9var BestName = require('bestname');10var bn = new BestName();11var name = bn.ansiDisplayname('John', 'Smith', 'III');12console.log('The name is: ' + name);13var BestName = require('bestname');14var bn = new BestName();15var name = bn.ansiDisplayname('John', 'Smith', 'III');16console.log('The name is: ' + name);17var BestName = require('bestname');18var bn = new BestName();19var name = bn.ansiDisplayname('John', 'Smith', 'III');20console.log('The name is: ' + name);21var BestName = require('bestname');22var bn = new BestName();23var name = bn.ansiDisplayname('John', 'Smith', 'III');24console.log('The name is: ' + name);25var BestName = require('bestname');26var bn = new BestName();27var name = bn.ansiDisplayname('John', 'Smith', 'III');28console.log('The name is: ' + name);29var BestName = require('bestname');30var bn = new BestName();31var name = bn.ansiDisplayname('John', 'Smith', 'III');32console.log('The name is: ' + name);
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!