Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

extension(tests): Add extension smoketest #4640

Merged
merged 27 commits into from
Mar 20, 2018
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,28 @@ cache:
- lighthouse-viewer/node_modules
- /home/travis/.rvm/gems/
install:
# if our e2e tests fail in the future it might be that we are not compatible
# with the latest puppeteer api so we probably need to run on chromimum
# @see https://github.com/GoogleChrome/lighthouse/pull/4640/files#r171425004
- export PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=1
- yarn
# travis can't handle the parallel install (without caches)
- yarn run install-all:task:windows
before_script:
- export DISPLAY=:99.0
- export CHROME_PATH="$(pwd)/chrome-linux/chrome"
# see comment above about puppeteer
- export CHROME_PATH="$(which google-chrome-stable)"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if you skip the pptr chromium download, is this at least chrome 66. PPTR may need that version to work properly.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just thought it was a bit stupid to install it twice and we moved to chrome stable to test the lowest version we support. I could enable chromium again.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

well, it does appear to work fine with chrome stable.
I'm also fine with using the bundled Chromium, but yes it does seem wasteful to d/l each time.

If it works fine with chrome stable as of now, then moving forward (assuming we infrequently bump the pptr version), it shouldn't regress. So I'm +1 to using the stable.

- sh -e /etc/init.d/xvfb start
- yarn build-all
script:
- echo $TRAVIS_EVENT_TYPE;
- echo $TRAVIS_BRANCH
- yarn bundlesize
- yarn lint
- yarn unit
- yarn type-check
- yarn closure
- yarn smoke
- yarn smokehouse
- yarn test-extension
# _JAVA_OPTIONS is breaking parsing of compiler output. See #3338.
- unset _JAVA_OPTIONS
- yarn compile-devtools
Expand Down
3 changes: 2 additions & 1 deletion lighthouse-core/scripts/run-mocha.sh
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,6 @@ elif [ "$flag" == '--core' ]; then
else
echo "lighthouse-core tests" && _runmocha 'lighthouse-core' && \
echo "lighthouse-cli tests" && _runmocha 'lighthouse-cli' && \
echo "lighthouse-viewer tests" && _runmocha 'lighthouse-viewer'
echo "lighthouse-viewer tests" && _runmocha 'lighthouse-viewer' && \
echo "lighthouse-extension tests" && _runmocha 'lighthouse-extension'
fi
5 changes: 3 additions & 2 deletions lighthouse-extension/app/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
"permissions": [
"activeTab",
"debugger",
"storage"
"storage",
"tabs"
],
"browser_action": {
"default_icon": {
Expand All @@ -29,4 +30,4 @@
"default_popup": "popup.html"
},
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'none'"
}
}
3 changes: 2 additions & 1 deletion lighthouse-extension/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
},
"scripts": {
"watch": "gulp watch",
"build": "gulp build:production"
"build": "gulp build:production",
"test": "mocha test/extension-test.js"
},
"devDependencies": {
"brfs": "^1.5.0",
Expand Down
138 changes: 138 additions & 0 deletions lighthouse-extension/test/extension-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
/**
* @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';

/* eslint-env mocha */

const path = require('path');
const assert = require('assert');
const fs = require('fs');
const puppeteer = require('../../node_modules/puppeteer/index.js');

const lighthouseExtensionPath = path.resolve(__dirname, '../app');
const config = require(path.resolve(__dirname, '../../lighthouse-core/config/default.js'));

const getAuditsOfCategory = category => config.categories[category].audits;

describe('Lighthouse chrome extension', function() {
const manifestLocation = path.join(lighthouseExtensionPath, 'manifest.json');
const lighthouseCategories = Object.keys(config.categories);
let browser;
let extensionPage;
let originalManifest;

function getAuditElementsCount({category, selector}) {
return extensionPage.evaluate(({category, selector}) =>
document.querySelector(`#${category}`).parentNode.querySelectorAll(selector).length,
{category, selector}
);
}

before(async function() {
// eslint-disable-next-line
this.timeout(90 * 1000);

// read original manifest
originalManifest = fs.readFileSync(manifestLocation);

const manifest = JSON.parse(originalManifest);
// add tabs permision to the manifest
manifest.permissions.push('tabs');
// write new file to document
fs.writeFileSync(manifestLocation, JSON.stringify(manifest, null, 2));

// start puppeteer
browser = await puppeteer.launch({
headless: false,
executablePath: process.env.CHROME_PATH,
args: [
`--disable-extensions-except=${lighthouseExtensionPath}`,
`--load-extension=${lighthouseExtensionPath}`,
],
});

const page = await browser.newPage();
await page.goto('https://www.paulirish.com', {waitUntil: 'networkidle2'});
const targets = await browser.targets();
const extensionTarget = targets.find(({_targetInfo}) => {
return _targetInfo.title === 'Lighthouse' &&
_targetInfo.type === 'background_page';
});

if (!extensionTarget) {
return await browser.close();
}

const client = await extensionTarget.createCDPSession();
const lighthouseResult = await client.send(
'Runtime.evaluate',
{
expression: `runLighthouseInExtension({
restoreCleanState: true,
}, ${JSON.stringify(lighthouseCategories)})`,
awaitPromise: true,
returnByValue: true,
}
);

if (lighthouseResult.exceptionDetails) {
if (lighthouseResult.exceptionDetails.exception) {
throw new Error(lighthouseResult.exceptionDetails.exception.description);
}

throw new Error(lighthouseResult.exceptionDetails.text);
}

extensionPage = (await browser.pages())
.find(page => page.url().includes('blob:chrome-extension://'));
});

after(async () => {
// put the default manifest back
fs.writeFileSync(manifestLocation, originalManifest);

if (browser) {
await browser.close();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if the test throws, do we want this pulled out into after so that the browser always gets closed afterwards?

Copy link
Collaborator Author

@wardpeet wardpeet Mar 13, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we could also to the lighthouse run in before and do regular test cases

describe('lighthouse extension' () => {
before(() => {
// lighthouse run but keep chrome open at the end
})

it ('should contain all categories', () => {

});

it('should contain all audits of category performance', () => {
})

after(() => { await browser.close() })

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 let's do that!

}
});

it('should contain all categories', async () => {
const categories = await extensionPage.$$(`#${lighthouseCategories.join(',#')}`);
assert.equal(categories.length, lighthouseCategories.length,
`${categories.join(' ')} does not match ${lighthouseCategories.join(' ')}`);
});

it('should contain audits of all categories', async () => {
for (const category of lighthouseCategories) {
let selector = '.lh-audit';
let expected = getAuditsOfCategory(category).length;
if (category === 'performance') {
selector = '.lh-audit,.lh-timeline-metric,.lh-perf-hint';
expected = getAuditsOfCategory(category).filter(a => !!a.group).length;
}

const elementCount = await getAuditElementsCount({category, selector});

assert.equal(expected, elementCount,
`${category} does not have the correct amount of audits`);
}
});

it('should contain a filmstrip', async () => {
const filmstrip = await extensionPage.$('lh-filmstrip');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

missing a dot in the selector here?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think this sorts it out:

  it('should contain a filmstrip', async () => {
    const filmstrip = await extensionPage.$('.lh-filmstrip');
    assert.equal(true, !!filmstrip, `filmstrip is not available`);
  });


assert.equal(null, filmstrip,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wait a second... null != page contains a filmstrip... :p

`filmstrip is not available`);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this can probably be 1 line

});

it('should contain no failed audits', async () => {
const auditErrors = await extensionPage.$$('.lh-debug');
const failedAudits = auditErrors.filter(error =>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

heh. I ran into a similar API misunderstanding. I was doing $$eval(selector, el => ...) but its actually elems instead of just el. Whoopsie daisy.


try something like this out:

  it('should not have any audit errors', async () => {
    function getDebugStrings(elems) {
      return elems.map(el => ({
        debugString: el.textContent,
        title: el.closest('.lh-audit').querySelector('.lh-score__title').textContent,
      }));
    }

    const auditErrors = await extensionPage.$$eval('.lh-debug', getDebugStrings);
    const errors = auditErrors.filter(item => item.debugString.includes('Audit error:'));
    assert.deepStrictEqual(errors, [], 'Audit errors found within the report');
  });

gives a nice purdy error:
image

error.textContent.includes('Audit error')).length;

assert.ok(!failedAudits, `${failedAudits.length} audits failed to run`);
});
});
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"debug": "node --inspect-brk ./lighthouse-cli/index.js",
"start": "node ./lighthouse-cli/index.js",
"test": "yarn lint --quiet && yarn unit && yarn type-check && yarn closure",
"test-extension": "cd lighthouse-extension && yarn test",
"unit-core": "bash lighthouse-core/scripts/run-mocha.sh --core",
"unit-cli": "bash lighthouse-core/scripts/run-mocha.sh --cli",
"unit-viewer": "bash lighthouse-core/scripts/run-mocha.sh --viewer",
Expand Down Expand Up @@ -76,6 +77,7 @@
"jsdom": "^9.12.0",
"mocha": "^3.2.0",
"npm-run-posix-or-windows": "^2.0.2",
"puppeteer": "^1.1.1",
"sinon": "^2.3.5",
"typescript": "^2.8.0-rc",
"vscode-chrome-debug-core": "^3.23.8",
Expand Down
Loading