<commit_before>/**
 * @license Copyright 2016 The Lighthouse Authors. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 */

import {strict as assert} from 'assert';
import fs from 'fs';

import assetSaver from '../../lib/asset-saver.js';
import Metrics from '../../lib/traces/pwmetrics-events.js';
import LHError from '../../lib/lh-error.js';
import Audit from '../../audits/audit.js';
import {getModuleDirectory} from '../../../esm-utils.mjs';
import {readJson} from '../../../root.js';

const traceEvents = readJson('../fixtures/traces/progressive-app.json', import.meta);
const dbwTrace = readJson('../results/artifacts/defaultPass.trace.json', import.meta);
const dbwResults = readJson('../results/sample_v2.json', import.meta);
const fullTraceObj = readJson('../fixtures/traces/progressive-app-m60.json', import.meta);
const devtoolsLog = readJson('../fixtures/traces/progressive-app-m60.devtools.log.json', import.meta);

const moduleDir = getModuleDirectory(import.meta);

// deepStrictEqual can hang on a full trace, we assert trace same-ness like so
function assertTraceEventsEqual(traceEventsA, traceEventsB) {
  assert.equal(traceEventsA.length, traceEventsB.length);
  traceEventsA.forEach((evt, i) => {
    assert.deepStrictEqual(evt, traceEventsB[i]);
  });
}
describe('asset-saver helper', () => {
  describe('saves files', function() {
    beforeAll(() => {
      const artifacts = {
        devtoolsLogs: {
          [Audit.DEFAULT_PASS]: [{message: 'first'}, {message: 'second'}],
        },
        traces: {
          [Audit.DEFAULT_PASS]: {
            traceEvents,
          },
        },
      };

      return assetSaver.saveAssets(artifacts, dbwResults.audits, process.cwd() + '/the_file');
    });

    it('trace file saved to disk with trace events and extra fakeEvents', () => {
      const traceFilename = 'the_file-0.trace.json';
      const traceFileContents = fs.readFileSync(traceFilename, 'utf8');
      const traceEventsOnDisk = JSON.parse(traceFileContents).traceEvents;
      const traceEventsWithoutExtrasOnDisk = traceEventsOnDisk.slice(0, traceEvents.length);
      const traceEventsFake = traceEventsOnDisk.slice(traceEvents.length);
      assertTraceEventsEqual(traceEventsWithoutExtrasOnDisk, traceEvents);
      assert.equal(traceEventsFake.length, 18);
      fs.unlinkSync(traceFilename);
    });

    it('devtools log file saved to disk with data', () => {
      const filename = 'the_file-0.devtoolslog.json';
      const fileContents = fs.readFileSync(filename, 'utf8');
      assert.ok(fileContents.includes('"message": "first"'));
      fs.unlinkSync(filename);
    });
  });

  describe('prepareAssets', () => {
    it('adds fake events to trace', () => {
      const countEvents = trace => trace.traceEvents.length;
      const mockArtifacts = {
        devtoolsLogs: {},
        traces: {
          defaultPass: dbwTrace,
        },
      };
      const beforeCount = countEvents(dbwTrace);
      return assetSaver.prepareAssets(mockArtifacts, dbwResults.audits).then(preparedAssets => {
        const afterCount = countEvents(preparedAssets[0].traceData);
        const metricsMinusTimeOrigin = Metrics.metricsDefinitions.length - 1;
        assert.equal(afterCount, beforeCount + (2 * metricsMinusTimeOrigin));
      });
    });
  });

  describe('saveTrace', () => {
    const traceFilename = 'test-trace-0.json';

    afterEach(() => {
      fs.unlinkSync(traceFilename);
    });

    it('prints traces with an event per line', async () => {
      const trace = {
        traceEvents: [
          {args: {}, cat: 'devtools.timeline', pid: 1, ts: 2},
          {args: {}, cat: 'v8', pid: 1, ts: 3},
          {args: {IsMainFrame: true}, cat: 'v8', pid: 1, ts: 5},
          {args: {data: {encodedDataLength: 20, requestId: '1.22'}}, pid: 1, ts: 6},
        ],
        metadata: {'cpu-model': 9001, 'network-type': 'Unknown'},
      };
      await assetSaver.saveTrace(trace, traceFilename);

      const traceFileContents = fs.readFileSync(traceFilename, 'utf8');
      expect(traceFileContents).toEqual(
`{
"traceEvents": [
  {"args":{},"cat":"devtools.timeline","pid":1,"ts":2},
  {"args":{},"cat":"v8","pid":1,"ts":3},
  {"args":{"IsMainFrame":true},"cat":"v8","pid":1,"ts":5},
  {"args":{"data":{"encodedDataLength":20,"requestId":"1.22"}},"pid":1,"ts":6}
],
"metadata": {
  "cpu-model": 9001,
  "network-type": "Unknown"<commit_msg>tests(asset-saver): use .tmp instead of pwd for temp file (#14140)<commit_after>/**
 * @license Copyright 2016 The Lighthouse Authors. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 */

import {strict as assert} from 'assert';
import fs from 'fs';

import assetSaver from '../../lib/asset-saver.js';
import Metrics from '../../lib/traces/pwmetrics-events.js';
import LHError from '../../lib/lh-error.js';
import Audit from '../../audits/audit.js';
import {getModuleDirectory} from '../../../esm-utils.mjs';
import {LH_ROOT, readJson} from '../../../root.js';

const traceEvents = readJson('../fixtures/traces/progressive-app.json', import.meta);
const dbwTrace = readJson('../results/artifacts/defaultPass.trace.json', import.meta);
const dbwResults = readJson('../results/sample_v2.json', import.meta);
const fullTraceObj = readJson('../fixtures/traces/progressive-app-m60.json', import.meta);
const devtoolsLog = readJson('../fixtures/traces/progressive-app-m60.devtools.log.json', import.meta);

const moduleDir = getModuleDirectory(import.meta);

// deepStrictEqual can hang on a full trace, we assert trace same-ness like so
function assertTraceEventsEqual(traceEventsA, traceEventsB) {
  assert.equal(traceEventsA.length, traceEventsB.length);
  traceEventsA.forEach((evt, i) => {
    assert.deepStrictEqual(evt, traceEventsB[i]);
  });
}
describe('asset-saver helper', () => {
  describe('saves files', function() {
    const tmpDir = `${LH_ROOT}/.tmp/asset-saver-test`;

    beforeAll(() => {
      fs.mkdirSync(tmpDir, {recursive: true});
      const artifacts = {
        devtoolsLogs: {
          [Audit.DEFAULT_PASS]: [{message: 'first'}, {message: 'second'}],
        },
        traces: {
          [Audit.DEFAULT_PASS]: {
            traceEvents,
          },
        },
      };

      return assetSaver.saveAssets(artifacts, dbwResults.audits, `${tmpDir}/the_file`);
    });

    it('trace file saved to disk with trace events and extra fakeEvents', () => {
      const traceFilename = tmpDir + '/the_file-0.trace.json';
      const traceFileContents = fs.readFileSync(traceFilename, 'utf8');
      const traceEventsOnDisk = JSON.parse(traceFileContents).traceEvents;
      const traceEventsWithoutExtrasOnDisk = traceEventsOnDisk.slice(0, traceEvents.length);
      const traceEventsFake = traceEventsOnDisk.slice(traceEvents.length);
      assertTraceEventsEqual(traceEventsWithoutExtrasOnDisk, traceEvents);
      assert.equal(traceEventsFake.length, 18);
      fs.unlinkSync(traceFilename);
    });

    it('devtools log file saved to disk with data', () => {
      const filename = tmpDir + '/the_file-0.devtoolslog.json';
      const fileContents = fs.readFileSync(filename, 'utf8');
      assert.ok(fileContents.includes('"message": "first"'));
      fs.unlinkSync(filename);
    });
  });

  describe('prepareAssets', () => {
    it('adds fake events to trace', () => {
      const countEvents = trace => trace.traceEvents.length;
      const mockArtifacts = {
        devtoolsLogs: {},
        traces: {
          defaultPass: dbwTrace,
        },
      };
      const beforeCount = countEvents(dbwTrace);
      return assetSaver.prepareAssets(mockArtifacts, dbwResults.audits).then(preparedAssets => {
        const afterCount = countEvents(preparedAssets[0].traceData);
        const metricsMinusTimeOrigin = Metrics.metricsDefinitions.length - 1;
        assert.equal(afterCount, beforeCount + (2 * metricsMinusTimeOrigin));
      });
    });
  });

  describe('saveTrace', () => {
    const traceFilename = `${LH_ROOT}/.tmp/test-trace-0.json`;

    beforeAll(() => {
      fs.mkdirSync(`${LH_ROOT}/.tmp`, {recursive: true});
    });

    afterEach(() => {
      fs.unlinkSync(traceFilename);
    });

    it('prints traces with an event per line', async () => {
      const trace = {
        traceEvents: [
          {args: {}, cat: 'devtools.timeline', pid: 1, ts: 2},
          {args: {}, cat: 'v8', pid: 1, ts: 3},
          {args: {IsMainFrame: true}, cat: 'v8', pid: 1, ts: 5},
          {args: {data: {encodedDataLength: 20, requestId: '1.22'}}, pid: 1, ts: 6},
        ],
        metadata: {'cpu-model': 9001, 'network-type': 'Unknown'},
      };
      await assetSaver.saveTrace(trace, traceFilename);

      const traceFileContents = fs.readFileSync(traceFilename, 'utf8');
      expect(traceFileContents).toEqual(
`{
"traceEvents": [
  {"args":{},"cat":"devtools.timeline","pid":1,"ts":2},
  {"args":{},"cat":"v8","pid":1,"ts":3},
  {"args":{"IsMainFrame":true},"cat":"v8","pid":1,"ts":5},
  {"args":{"data":{"encodedDataLength":20,"requestId":"1.22"}},"pid":1,"ts":6}
],
"metadata": {
  "cpu-model": 9001,
  "network-type": "Unknown"
{'fraction_non_alphanumeric': 0.15982506709074645, 'fraction_numerical': 0.01302057449557698, 'mean_word_length': 3.5488245931283906, 'pattern_counts': {'":': 48, '<': 3, '<?xml version=': 0, '>': 28, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1205', 'n_tokens_mistral': 3113, 'n_tokens_neox': 3033, 'n_words': 712}