Best JavaScript code snippet using best
trace.spec.ts
Source:trace.spec.ts
...36 aggregate: 0,37 results: [{ type: "benchmark", metrics: { script: 30 }, name: "foo", startedAt: 0, aggregate: 0 }]38 }39 const original = benchmarkResults;40 await mergeTracedMetrics(benchmarkResults, traceMetrics);41 expect(original).toEqual(benchmarkResults);42 })43 test('merges trace metrics at root level', async () => {44 const traceMetrics = { foo: { paint: 5 } }45 const benchmarkResults: BenchmarkResults = {46 benchmarkName: 'test',47 executedIterations: 0,48 aggregate: 0,49 results: [{ type: "benchmark", metrics: { script: 30 }, name: "foo", startedAt: 0, aggregate: 0 }]50 }51 const expectedResults: BenchmarkResults = {52 benchmarkName: 'test',53 executedIterations: 0,54 aggregate: 0,55 results: [{ type: "benchmark", metrics: { script: 30, paint: 5 }, name: "foo", startedAt: 0, aggregate: 0 }]56 }57 await mergeTracedMetrics(benchmarkResults, traceMetrics);58 expect(expectedResults).toEqual(benchmarkResults);59 })60 test('merges trace metrics at when embedded in group', async () => {61 const traceMetrics = {62 foo: { paint: 5 },63 bar: { paint: 20, layout: 100 }64 }65 const benchmarkResults: BenchmarkResults = {66 benchmarkName: 'test',67 executedIterations: 0,68 aggregate: 0,69 results: [{70 type: "group",71 name: "A",72 aggregate: 0,73 startedAt: 0,74 nodes: [75 { type: "benchmark", metrics: { script: 30 }, name: "foo", startedAt: 0, aggregate: 0 },76 { type: "benchmark", metrics: { script: 10 }, name: "bar", startedAt: 0, aggregate: 0 }77 ]78 }]79 }80 const expectedResults: BenchmarkResults = {81 benchmarkName: 'test',82 executedIterations: 0,83 aggregate: 0,84 results: [{85 type: "group",86 name: "A",87 aggregate: 0,88 startedAt: 0,89 nodes: [90 { type: "benchmark", metrics: { script: 30, paint: 5 }, name: "foo", startedAt: 0, aggregate: 0 },91 { type: "benchmark", metrics: { script: 10, paint: 20, layout: 100 }, name: "bar", startedAt: 0, aggregate: 0 }92 ]93 }]94 }95 await mergeTracedMetrics(benchmarkResults, traceMetrics);96 expect(benchmarkResults).toEqual(expectedResults);97 })98})99describe('parseTrace', () => {100 test('throws error when given path does not exist', async () => {101 expect(parseTrace('fake-path.json')).rejects.toThrow(/no such file/)102 })103 test('parses trace-simple.json to find paints and layouts', async () => {104 const tracePath = path.resolve(__dirname, 'fixtures', 'trace-simple.json');105 const tracedMetrics = await parseTrace(tracePath);106 const expectedResults = {107 foo: { paint: 50, layout: 20 }108 }109 expect(tracedMetrics).toEqual(expectedResults);...
trace.ts
Source:trace.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 fs from 'fs';8import { promisify } from 'util';9import { BenchmarkResults, BenchmarkMetrics, BenchmarkResultNode, BenchmarkMeasureType } from '@best/types';10const asyncReadFile = promisify(fs.readFile);11const asyncUnlink = promisify(fs.unlink);12const asyncExists = promisify(fs.exists);13const TRACED_METRIC_EVENTS = ['Paint', 'Layout', 'UpdateLayoutTree', 'UpdateLayerTree', 'CompositeLayers'];14const TRACED_EVENT_NAME_ALIAS: any = { 'UpdateLayoutTree': 'RecalculateStyles' };15interface TracedMetrics {16 [key: string]: BenchmarkMetrics17}18const isBeginPhase = (event: { ph: string }): boolean => {19 return event.ph.toLowerCase() === 'b';20}21const isEndPhase = (event: { ph: string }): boolean => {22 return event.ph.toLowerCase() === 'e';23}24const hasDurationPhased = (event: { ph: string }): boolean => {25 return isBeginPhase(event) || isEndPhase(event);26}27const sumPairedMetrics = (events: any[]): number => {28 let duration = 0;29 for (const event of events) {30 if (isBeginPhase(event)) {31 duration -= event.ts;32 } else if (isEndPhase(event)) {33 duration += event.ts;34 }35 }36 return duration;37}38// returns the total duration of all paints or layouts, etc in microseconds39const sumEventDurations = (events: any[]): number => {40 const pairedMetrics = events.filter(hasDurationPhased);41 if (pairedMetrics.length > 0 && pairedMetrics.length % 2 === 0) {42 return sumPairedMetrics(events);43 }44 return events.reduce((previous, current) => previous += current.dur, 0);45}46export const parseTrace = async (tracePath: string): Promise<TracedMetrics> => {47 const file = await asyncReadFile(tracePath, 'utf8');48 const trace = JSON.parse(file);49 const tracedMetricEvents = trace.traceEvents.filter((event: any) => TRACED_METRIC_EVENTS.includes(event.name) || event.name.includes((`${BenchmarkMeasureType.Execute}/`)));50 const sortedEvents = tracedMetricEvents.sort((a: any, b: any) => a.ts - b.ts);51 const groupedEvents: { [run: string]: { [event: string]: any[] } } = {};52 let currentRun: string | false = false;53 for (const event of sortedEvents) {54 if (currentRun && TRACED_METRIC_EVENTS.includes(event.name)) {55 if (groupedEvents[currentRun][event.name]) {56 groupedEvents[currentRun][event.name].push(event);57 } else {58 groupedEvents[currentRun][event.name] = [event];59 }60 } else if (event.name.includes(`${BenchmarkMeasureType.Execute}/`)) {61 if (isBeginPhase(event)) {62 currentRun = event.name;63 groupedEvents[event.name] = {};64 } else if (isEndPhase(event)) {65 currentRun = false;66 }67 }68 }69 const tracedMetrics = Object.keys(groupedEvents).reduce((allMetrics, key): TracedMetrics => {70 const runName = key.replace((`${BenchmarkMeasureType.Execute}/`), '');71 const metrics = Object.keys(groupedEvents[key]).reduce((acc, eventName): BenchmarkMetrics => {72 const aliasEventName = TRACED_EVENT_NAME_ALIAS[eventName] || eventName;73 const name = aliasEventName.toLowerCase();74 return {75 ...acc,76 [name]: (sumEventDurations(groupedEvents[key][eventName]) / 1000)77 }78 }, <BenchmarkMetrics>{})79 return {80 ...allMetrics,81 [runName]: metrics82 };83 }, <TracedMetrics>{})84 return tracedMetrics;85}86const mergeTracedMetricsIntoResultNode = (resultNode: BenchmarkResultNode, parsedTrace: TracedMetrics) => {87 if (resultNode.type === "group") {88 resultNode.nodes.forEach(node => {89 mergeTracedMetricsIntoResultNode(node, parsedTrace);90 })91 } else if (resultNode.type === "benchmark") {92 const nodeTraces = parsedTrace[resultNode.name];93 resultNode.metrics = {94 ...resultNode.metrics,95 ...nodeTraces96 }97 }98}99export const mergeTracedMetrics = (benchmarkResults: BenchmarkResults, parsedTrace: TracedMetrics) => {100 benchmarkResults.results.forEach(node => {101 mergeTracedMetricsIntoResultNode(node, parsedTrace);102 })103}104export const removeTrace = async (tracePath: string): Promise<void> => {105 const fileExists = await asyncExists(tracePath);106 if (fileExists) {107 await asyncUnlink(tracePath);108 }...
headless.ts
Source:headless.ts
...62 async processTrace(result: any) {63 if (! this.page) return result;64 if (this.tracingEnabled) {65 const traces = await parseTrace(this.tracePath);66 mergeTracedMetrics(result, traces);67 }68 return result;69 }70 async close() {71 if (this.tracingEnabled) await removeTrace(this.tracePath);72 if (this.browser) {73 try {74 await this.browser.close();75 } catch(err) {76 console.log('[pupeteer] - close error', err);77 }78 }79 }80 reloadPage() {...
Using AI Code Generation
1const BestMetrics = require('./BestMetrics');2const fs = require('fs');3let file1 = fs.readFileSync('./test1.json');4let file2 = fs.readFileSync('./test2.json');5let file3 = fs.readFileSync('./test3.json');6let bestMetrics = new BestMetrics();7let mergedMetrics = bestMetrics.mergeTracedMetrics(file1, file2, file3);8console.log(mergedMetrics);9{10 {11 },12 {13 },14 {15 },16 {17 }18}19This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details
Using AI Code Generation
1var BestPracticeMetric = require('../lib/metrics/BPMetric');2var fs = require('fs');3var metric1 = new BestPracticeMetric('test1');4var metric2 = new BestPracticeMetric('test2');5var metric1Data = fs.readFileSync(__dirname+'/test1.json');6var metric2Data = fs.readFileSync(__dirname+'/test2.json');7metric1.loadTracedMetricData(JSON.parse(metric1Data));8metric2.loadTracedMetricData(JSON.parse(metric2Data));9var mergedMetric = metric1.mergeTracedMetrics(metric2);10console.log(JSON.stringify(mergedMetric));
Using AI Code Generation
1var BestMetricsCalculator = require("../lib/BestMetricsCalculator.js");2var bestMetricsCalculator = new BestMetricsCalculator();3 {4 "metrics": {5 }6 },7 {8 "metrics": {9 }10 },11 {12 "metrics": {13 }14 }15];16 {17 "metrics": {18 }19 },20 {21 "metrics": {22 }23 },24 {25 "metrics": {26 }27 }28];29 {30 "metrics": {31 }32 },33 {34 "metrics": {35 }36 },37 {38 "metrics": {
Using AI Code Generation
1var b = require('./lib/BestPracticeMetrics.js');2var a = require('./lib/TracedMetrics.js');3var fs = require('fs');4var trace = require('./trace.json');5var metrics = require('./metrics.json');6var bestPracticeMetrics = new b.BestPracticeMetrics();7var tracedMetrics = new a.TracedMetrics(trace, metrics);8var mergedMetrics = bestPracticeMetrics.mergeTracedMetrics(tracedMetrics);9var str = JSON.stringify(mergedMetrics, null, 4);10fs.writeFile('mergedMetrics.json', str, function(err) {11 if (err) throw err;12 console.log('It\'s saved!');13});
Using AI Code Generation
1var fs = require('fs');2var BestMetrics = require('../lib/BestMetrics.js');3var bestMetrics = new BestMetrics();4var test4Metrics = JSON.parse(fs.readFileSync('test4.json', 'utf8'));5var test4TracedMetrics = JSON.parse(fs.readFileSync('test4Traced.json', 'utf8'));6var test4BestMetrics = bestMetrics.mergeTracedMetrics(test4Metrics, test4TracedMetrics);7console.log(JSON.stringify(test4BestMetrics, null, 2));
Using AI Code Generation
1var assert = require('assert');2var BestPractice = require('../lib/bestpractice');3var bestPractice = new BestPractice();4var metrics = require('../lib/metrics');5var metricName = "test";6var metricValue = 10;7var metricType = "traced";8var metric = new metrics(metricName, metricValue, metricType);9var metricName1 = "test1";10var metricValue1 = 10;11var metricType1 = "traced";12var metric1 = new metrics(metricName1, metricValue1, metricType1);13var metricName2 = "test2";14var metricValue2 = 10;15var metricType2 = "traced";16var metric2 = new metrics(metricName2, metricValue2, metricType2);17var metricName3 = "test3";18var metricValue3 = 10;19var metricType3 = "traced";20var metric3 = new metrics(metricName3, metricValue3, metricType3);21var metricName4 = "test4";22var metricValue4 = 10;23var metricType4 = "traced";24var metric4 = new metrics(metricName4, metricValue4, metricType4);25var metricName5 = "test5";26var metricValue5 = 10;27var metricType5 = "traced";28var metric5 = new metrics(metricName5, metricValue5, metricType5);29var metricName6 = "test6";30var metricValue6 = 10;31var metricType6 = "traced";32var metric6 = new metrics(metricName6, metricValue6, metricType6);33var metricName7 = "test7";34var metricValue7 = 10;35var metricType7 = "traced";36var metric7 = new metrics(metricName7, metricValue7, metricType7);37var metricName8 = "test8";38var metricValue8 = 10;39var metricType8 = "traced";
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!!