Repository: GoogleChrome/lighthouse
Pull request #6332 (2018-10-17 22:52:45)

misc(proto): convert int32's into DoubleValue in proto
**Summary**
Benchmark index is actually a double!  Not an int!

**Related Issues/PRs**
fixes: #6331 


brendankenny: I like @patrickhulce's idea better if the slowest devices really are more on the order of 10-100

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/lh-error.js b/lighthouse-core/lib/lh-error.js
index e392c6f08..557fcc746 100644
--- a/lighthouse-core/lib/lh-error.js
+++ b/lighthouse-core/lib/lh-error.js
@@ -59,8 +59,8 @@ class LighthouseError extends Error {
     }
 
     // otherwise fallback to building a generic Error
-    let errMsg = `(${method}): ${JSON.stringify(protocolError.message)}`;
-    if (protocolError.data) errMsg += ` (${JSON.stringify(protocolError.data)})`;
+    let errMsg = `(${method}): ${protocolError.message}`;
+    if (protocolError.data) errMsg += ` (${protocolError.data})`;
     const error = new Error(`Protocol error ${errMsg}`);
     return Object.assign(error, {protocolMethod: method, protocolError: protocolError.message});
   }
diff --git a/lighthouse-core/lib/page-functions.js b/lighthouse-core/lib/page-functions.js
index b674e0d60..d3be4d512 100644
--- a/lighthouse-core/lib/page-functions.js
+++ b/lighthouse-core/lib/page-functions.js
@@ -149,7 +149,7 @@ function ultradumbBenchmark() {
   }
 
   const durationInSeconds = (Date.now() - start) / 1000;
-  return iterations / durationInSeconds;
+  return Math.round(iterations / durationInSeconds);
 }
 
 module.exports = {
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/proto/lighthouse-result.proto b/proto/lighthouse-result.proto
index 73c0c536e..98049b2e3 100644
--- a/proto/lighthouse-result.proto
+++ b/proto/lighthouse-result.proto
@@ -69,7 +69,7 @@ message LighthouseResult {
     string host_user_agent = 2;
 
     // The benchmark index that indicates rough device class
-    int32 benchmark_index = 3;
+    google.protobuf.DoubleValue benchmark_index = 3;
   }
 
   // The environment that the audit was run in
@@ -110,7 +110,7 @@ message LighthouseResult {
     repeated string output = 1;
 
     // The maximum amount of time to wait for loading in ms
-    int32 max_wait_for_load = 2;
+    google.protobuf.DoubleValue max_wait_for_load = 2;
 
     // Network throttling options
     enum ThrottlingMethod {
@@ -133,7 +133,7 @@ message LighthouseResult {
     // Message containing the throttling settings used in an LH configuration
     message Throttling {
       // The round trip time in ms
-      int32 rtt_ms = 1;
+      google.protobuf.DoubleValue rtt_ms = 1;
 
       // The throughput in kilobytes per second
       google.protobuf.DoubleValue throughput_kbps = 2;
@@ -148,7 +148,7 @@ message LighthouseResult {
       google.protobuf.DoubleValue upload_throughput_kbps = 5;
 
       // The amount of slowdown to apply to the cpu
-      int32 cpu_slowdown_multiplier = 6;
+      google.protobuf.DoubleValue cpu_slowdown_multiplier = 6;
     }
 
     // The throttling settings used
diff --git a/proto/sample_v2_round_trip.json b/proto/sample_v2_round_trip.json
index 9f844dfc8..8542cf721 100644
--- a/proto/sample_v2_round_trip.json
+++ b/proto/sample_v2_round_trip.json
@@ -3244,7 +3244,7 @@
         "extraHeaders": null, 
         "gatherMode": false, 
         "locale": "en-US", 
-        "maxWaitForLoad": 45000, 
+        "maxWaitForLoad": 45000.0, 
         "onlyAudits": null, 
         "onlyCategories": null, 
         "output": [
@@ -3252,17 +3252,17 @@
         ], 
         "skipAudits": null, 
         "throttling": {
-            "cpuSlowdownMultiplier": 4, 
+            "cpuSlowdownMultiplier": 4.0, 
             "downloadThroughputKbps": 1474.5600000000002, 
             "requestLatencyMs": 562.5, 
-            "rttMs": 150, 
+            "rttMs": 150.0, 
             "throughputKbps": 1638.4, 
             "uploadThroughputKbps": 675.0
         }, 
         "throttlingMethod": "devtools"
     }, 
     "environment": {
-        "benchmarkIndex": 1000, 
+        "benchmarkIndex": 1000.0, 
         "hostUserAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3358.0 Safari/537.36", 
         "networkUserAgent": "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5 Build/MRA58N) AppleWebKit/537.36(KHTML, like Gecko) Chrome/66.0.3359.30 Mobile Safari/537.36"
     }, 
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);
+    });
+  });
+});