How to use tracedMetrics method in Best

Best JavaScript code snippet using best

trace.spec.ts

Source: trace.spec.ts Github

copy

Full Screen

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 os from 'os';8import fs from 'fs';9import path from 'path';10import { parseTrace, removeTrace, mergeTracedMetrics } from '../​trace';11import { BenchmarkResults } from '@best/​types';12const TEMP_DIR_PREFIX = 'best-test-';13function tempDir() {14 return fs.mkdtempSync(path.join(os.tmpdir(), TEMP_DIR_PREFIX));15}16describe('removeTrace', () => {17 test('does not throw when file does not exist', async () => {18 const tracePath = path.resolve(tempDir(), 'trace.json');19 await removeTrace(tracePath)20 })21 test('deletes file when it is present', async () => {22 const tracePath = path.resolve(tempDir(), 'trace.json');23 const data = JSON.stringify({test: true});24 fs.writeFileSync(tracePath, data);25 await removeTrace(tracePath)26 const existsAfter = fs.existsSync(tracePath);27 expect(existsAfter).toBeFalsy();28 })29})30describe('mergeTracedMetrics', () => {31 test('does not alter benchmarkResults when trace metrics are empty', async () => {32 const traceMetrics = {};33 const benchmarkResults: BenchmarkResults = {34 benchmarkName: 'test',35 executedIterations: 0,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);110 })111 test('parses trace-complex.json to find paints and layouts', async () => {112 const tracePath = path.resolve(__dirname, 'fixtures', 'trace-complex.json');113 const tracedMetrics = await parseTrace(tracePath);114 const expectedResults = {115 foo: { paint: 50, layout: 20 },116 bar: { paint: 50, layout: 10.5 }117 }118 expect(tracedMetrics).toEqual(expectedResults);119 })...

Full Screen

Full Screen

trace.ts

Source: trace.ts Github

copy

Full Screen

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 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var BestPractices = require('newrelic');2var fs = require('fs');3var now = new Date();4var then = new Date(now.getTime() - 24*60*60*1000);5BestPractices.tracedMetrics(then, now, function(err, data) {6 if (err) {7 console.log(err);8 } else {9 fs.writeFile("tracedMetrics.json", JSON.stringify(data), function(err) {10 if (err) {11 console.log(err);12 } else {13 console.log("The file was saved!");14 }15 });16 }17});

Full Screen

Blogs

Check out the latest blogs from LambdaTest on this topic:

LambdaTest Receives Top Distinctions for Test Management Software from Leading Business Software Directory

LambdaTest has recently received two notable awards from the leading business software directory FinancesOnline after their experts were impressed with our test platform’s capabilities in accelerating one’s development process.

Some Common Layout Ideas For Web Pages

The layout of a web page is one of the most important features of a web page. It can affect the traffic inflow by a significant margin. At times, a designer may come up with numerous layout ideas and sometimes he/she may struggle the entire day to come up with one. Moreover, design becomes even more important when it comes to ensuring cross browser compatibility.

16 Best Chrome Extensions For Developers

Chrome is hands down the most used browsers by developers and users alike. It is the primary reason why there is such a solid chrome community and why there is a huge list of Chrome Extensions targeted at developers.

Why Your Startup Needs Test Management?

In a startup, the major strength of the people is that they are multitaskers. Be it anything, the founders and the core team wears multiple hats and takes complete responsibilities to get the ball rolling. From designing to deploying, from development to testing, everything takes place under the hawk eyes of founders and the core members.

Making A Mobile-Friendly Website: The Why And How?

We are in the era of the ‘Heads down’ generation. Ever wondered how much time you spend on your smartphone? Well, let us give you an estimate. With over 2.5 billion smartphone users, an average human spends approximately 2 Hours 51 minutes on their phone every day as per ComScore’s 2017 report. The number increases by an hour if we include the tab users as well!

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Best 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