Repository: GoogleChrome/lighthouse
Pull request #6310 (2018-10-17 19:31:45)

misc(proto): adjust configSetting.output in preprocessor
**Summary**
Adds configSettings.output processing.

**Related Issues/PRs**
preprocessing for: #6309 



Patch:
diff --git a/lighthouse-core/gather/driver.js b/lighthouse-core/gather/driver.js
index 3e7b7ebda..5da3e6322 100644
--- a/lighthouse-core/gather/driver.js
+++ b/lighthouse-core/gather/driver.js
@@ -1196,17 +1196,16 @@ class Driver {
    * @return {Promise<void>}
    */
   async dismissJavaScriptDialogs() {
-    await this.sendCommand('Page.enable');
-
     this.on('Page.javascriptDialogOpening', data => {
       log.warn('Driver', `${data.type} dialog opened by the page automatically suppressed.`);
 
-      // rejection intentionally unhandled
       this.sendCommand('Page.handleJavaScriptDialog', {
         accept: true,
         promptText: 'Lighthouse prompt response',
-      });
+      }).catch(err => log.warn('Driver', err));
     });
+
+    await this.sendCommand('Page.enable');
   }
 }
 
diff --git a/lighthouse-core/lib/proto-preprocessor.js b/lighthouse-core/lib/proto-preprocessor.js
index 6e9f85331..a23d1d660 100644
--- a/lighthouse-core/lib/proto-preprocessor.js
+++ b/lighthouse-core/lib/proto-preprocessor.js
@@ -22,13 +22,23 @@ function processForProto(result) {
   /** @type {LH.Result} */
   const reportJson = JSON.parse(result);
 
+  // Clean up the configSettings
+  if (reportJson.configSettings) {
+    // make sure the 'output' field is an array
+    if (reportJson.configSettings.output) {
+      if (!Array.isArray(reportJson.configSettings.output)) {
+        reportJson.configSettings.output = [reportJson.configSettings.output];
+      }
+    }
+  }
+
   // Clean up actions that require 'audits' to exist
-  if ('audits' in reportJson) {
+  if (reportJson.audits) {
     Object.keys(reportJson.audits).forEach(auditName => {
       const audit = reportJson.audits[auditName];
 
       // Rewrite the 'not-applicable' scoreDisplayMode to 'not_applicable'. #6201
-      if ('scoreDisplayMode' in audit) {
+      if (audit.scoreDisplayMode) {
         if (audit.scoreDisplayMode === 'not-applicable') {
           // @ts-ignore Breaking the LH.Result type
           audit.scoreDisplayMode = 'not_applicable';
@@ -52,7 +62,7 @@ function processForProto(result) {
   }
 
   // Drop the i18n icuMessagePaths. Painful in proto, and low priority to expose currently.
-  if ('i18n' in reportJson && 'icuMessagePaths' in reportJson.i18n) {
+  if (reportJson.i18n && reportJson.i18n.icuMessagePaths) {
     delete reportJson.i18n.icuMessagePaths;
   }
 
diff --git a/lighthouse-core/lib/sentry.js b/lighthouse-core/lib/sentry.js
index a36ad25b7..9f49aae51 100644
--- a/lighthouse-core/lib/sentry.js
+++ b/lighthouse-core/lib/sentry.js
@@ -37,6 +37,9 @@ const sentryDelegate = {
   getContext: noop,
   /** @type {(error: Error, options?: CaptureOptions) => Promise<void>} */
   captureException: async () => {},
+  _shouldSample() {
+    return SAMPLE_RATE >= Math.random();
+  },
 };
 
 /**
@@ -50,7 +53,7 @@ function init(opts) {
   }
 
   // If not selected for samping, leave the functions as a noop.
-  if (SAMPLE_RATE <= Math.random()) {
+  if (!sentryDelegate._shouldSample()) {
     return;
   }
 
diff --git a/readme.md b/readme.md
index 0c7532d76..937f88d9a 100644
--- a/readme.md
+++ b/readme.md
@@ -36,7 +36,7 @@ By default, Lighthouse writes the report to an HTML file. You can control the ou
 
 ### CLI options
 
-```sh
+```
 $ lighthouse --help
 
 lighthouse <url>


Test patch:
diff --git a/lighthouse-core/test/lib/proto-preprocessor-test.js b/lighthouse-core/test/lib/proto-preprocessor-test.js
index 3b2b33c13..b35982970 100644
--- a/lighthouse-core/test/lib/proto-preprocessor-test.js
+++ b/lighthouse-core/test/lib/proto-preprocessor-test.js
@@ -9,6 +9,24 @@ const processForProto = require('../../lib/proto-preprocessor').processForProto;
 
 /* eslint-env jest */
 describe('processing for proto', () => {
+  it('cleans up configSettings', () => {
+    const input = {
+      'configSettings': {
+        'output': 'json',
+      },
+    };
+    const expectation = {
+      'configSettings': {
+        'output': [
+          'json',
+        ],
+      },
+    };
+    const output = processForProto(JSON.stringify(input));
+
+    expect(JSON.parse(output)).toMatchObject(expectation);
+  });
+
   it('cleans up audits', () => {
     const input = {
       'audits': {
diff --git a/lighthouse-core/test/lib/sentry-test.js b/lighthouse-core/test/lib/sentry-test.js
new file mode 100644
index 000000000..4c11e2215
--- /dev/null
+++ b/lighthouse-core/test/lib/sentry-test.js
@@ -0,0 +1,126 @@
+/**
+ * @license Copyright 2018 Google Inc. 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.
+ */
+'use strict';
+
+jest.mock('raven');
+
+const raven = require('raven');
+const Sentry = require('../../lib/sentry');
+
+/* eslint-env jest */
+
+describe('Sentry', () => {
+  let configPayload;
+  let originalSentry;
+
+  beforeEach(() => {
+    configPayload = {
+      url: 'http://example.com',
+      flags: {enableErrorReporting: true},
+      environmentData: {},
+    };
+
+    // We need to save the Sentry delegate object because every call to `.init` mutates the methods.
+    // We want to have a fresh state for every test.
+    originalSentry = {...Sentry};
+
+    raven.config = jest.fn().mockReturnValue({install: jest.fn()});
+    raven.mergeContext = jest.fn();
+    raven.captureException = jest.fn().mockImplementation((err, opts, cb) => cb());
+    Sentry._shouldSample = jest.fn().mockReturnValue(true);
+  });
+
+  afterEach(() => {
+    // Reset the methods on the Sentry object, see note above.
+    Object.assign(Sentry, originalSentry);
+  });
+
+  describe('.init', () => {
+    it('should noop when !enableErrorReporting', () => {
+      Sentry.init({url: 'http://example.com', flags: {}});
+      expect(raven.config).not.toHaveBeenCalled();
+      Sentry.init({url: 'http://example.com', flags: {enableErrorReporting: false}});
+      expect(raven.config).not.toHaveBeenCalled();
+    });
+
+    it('should noop when not picked for sampling', () => {
+      Sentry._shouldSample.mockReturnValue(false);
+      Sentry.init({url: 'http://example.com', flags: {enableErrorReporting: true}});
+      expect(raven.config).not.toHaveBeenCalled();
+    });
+
+    it('should initialize the raven client when enableErrorReporting', () => {
+      Sentry.init({
+        url: 'http://example.com',
+        flags: {
+          enableErrorReporting: true,
+          emulatedFormFactor: 'desktop',
+          throttlingMethod: 'devtools',
+        },
+        environmentData: {},
+      });
+
+      expect(raven.config).toHaveBeenCalled();
+      expect(raven.mergeContext).toHaveBeenCalled();
+      expect(raven.mergeContext.mock.calls[0][0]).toEqual({
+        extra: {
+          url: 'http://example.com',
+          deviceEmulation: true,
+          emulatedFormFactor: 'desktop',
+          throttlingMethod: 'devtools',
+        },
+      });
+    });
+  });
+
+  describe('.captureException', () => {
+    it('should forward exceptions to raven client', async () => {
+      Sentry.init(configPayload);
+      const error = new Error('oops');
+      await Sentry.captureException(error);
+
+      expect(raven.captureException).toHaveBeenCalled();
+      expect(raven.captureException.mock.calls[0][0]).toBe(error);
+    });
+
+    it('should skip expected errors', async () => {
+      Sentry.init(configPayload);
+      const error = new Error('oops');
+      error.expected = true;
+      await Sentry.captureException(error);
+
+      expect(raven.captureException).not.toHaveBeenCalled();
+    });
+
+    it('should skip duplicate audit errors', async () => {
+      Sentry.init(configPayload);
+      const error = new Error('A');
+      await Sentry.captureException(error, {tags: {audit: 'my-audit'}});
+      await Sentry.captureException(error, {tags: {audit: 'my-audit'}});
+
+      expect(raven.captureException).toHaveBeenCalledTimes(1);
+    });
+
+    it('should still allow different audit errors', async () => {
+      Sentry.init(configPayload);
+      const errorA = new Error('A');
+      const errorB = new Error('B');
+      await Sentry.captureException(errorA, {tags: {audit: 'my-audit'}});
+      await Sentry.captureException(errorB, {tags: {audit: 'my-audit'}});
+
+      expect(raven.captureException).toHaveBeenCalledTimes(2);
+    });
+
+    it('should skip duplicate gatherer errors', async () => {
+      Sentry.init(configPayload);
+      const error = new Error('A');
+      await Sentry.captureException(error, {tags: {gatherer: 'my-gatherer'}});
+      await Sentry.captureException(error, {tags: {gatherer: 'my-gatherer'}});
+
+      expect(raven.captureException).toHaveBeenCalledTimes(1);
+    });
+  });
+});