Skip to content

Commit

Permalink
Initial implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Rynat Sibahatau committed Jun 9, 2019
1 parent 0e221e5 commit 5a8b8ce
Show file tree
Hide file tree
Showing 9 changed files with 118 additions and 13 deletions.
15 changes: 15 additions & 0 deletions lighthouse-cli/bin.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,21 @@ async function begin() {
cliFlags.extraHeaders = JSON.parse(extraHeadersStr);
}

if (cliFlags.extraCookies) {
// TODO: LH.Flags.extraCookies is actually a string at this point, but needs to be
// copied over to LH.Settings.extraCookies, which is LH.Crdp.Network.Cookies. Force
// the conversion here, but long term either the CLI flag or the setting should have
// a different name.
// @ts-ignore
let extraCookiesStr = /** @type {string} */ (cliFlags.extraCookies);
// If not a JSON array, assume it's a path to a JSON file.
if (extraCookiesStr.substr(0, 1) !== '[') {
extraCookiesStr = fs.readFileSync(extraCookiesStr, 'utf-8');
}

cliFlags.extraCookies = JSON.parse(extraCookiesStr);
}

if (cliFlags.precomputedLanternDataPath) {
const lanternDataStr = fs.readFileSync(cliFlags.precomputedLanternDataPath, 'utf8');
/** @type {LH.PrecomputedLanternData} */
Expand Down
10 changes: 9 additions & 1 deletion lighthouse-cli/cli-flags.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,17 @@ function getFlags(manualArgv) {
'lighthouse <url> --quiet --chrome-flags="--headless"',
'Launch Headless Chrome, turn off logging')
.example(
'lighthouse <url> --extra-headers "{\\"Cookie\\":\\"monster=blue\\", \\"x-men\\":\\"wolverine\\"}"',
'lighthouse <url> --extra-headers "{\\"x-men\\":\\"wolverine\\"}"',
'Stringify\'d JSON HTTP Header key/value pairs to send in requests')
.example(
'lighthouse <url> --extra-headers=./path/to/file.json',
'Path to JSON file of HTTP Header key/value pairs to send in requests')
.example(
'lighthouse <url> --extra-cookies "[{\\"name\\":\\"session_id\\",\\"value\\":\\"x-men\\" }]"',
'Stringify\'d JSON array of HTTP Cookies to send in requests')
.example(
'lighthouse <url> --extra-cookies=./path/to/file.json',
'Path to JSON file of HTTP Cookies to send in requests')
.example(
'lighthouse <url> --only-categories=performance,pwa',
'Only run specific categories.')
Expand Down Expand Up @@ -126,6 +132,7 @@ function getFlags(manualArgv) {
'max-wait-for-load':
'The timeout (in milliseconds) to wait before the page is considered done loading and the run should continue. WARNING: Very high values can lead to large traces and instability',
'extra-headers': 'Set extra HTTP Headers to pass with request',
'extra-cookies': 'Set extra HTTP Cookies to pass with request',
'precomputed-lantern-data-path': 'Path to the file where lantern simulation data should be read from, overwriting the lantern observed estimates for RTT and server latency.',
'lantern-data-output-path': 'Path to the file where lantern simulation data should be written to, can be used in a future run with the `precomputed-lantern-data-path` flag.',
'only-audits': 'Only run the specified audits',
Expand Down Expand Up @@ -166,6 +173,7 @@ function getFlags(manualArgv) {
.array('output')
.array('plugins')
.string('extraHeaders')
.string('extraCookies')
.string('channel')
.string('precomputedLanternDataPath')
.string('lanternDataOutputPath')
Expand Down
13 changes: 13 additions & 0 deletions lighthouse-cli/test/fixtures/static-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,19 @@ function requestHandler(request, response) {
}
}

if (params.has('extra_cookie')) {
const extraCookies = new URLSearchParams(params.get('extra_cookie'));
const cookeString = '';
for (const [cookieName, cookieValue] of extraCookies) {
cookeString += cookieName+'='+cookieName+';'
}

// Extra cookie we allways override possible 'Set-Cookie' header
// which may be already present in request by extra_header
headers['Set-Cookie'].push(cookeString);
}


if (params.has('gzip')) {
useGzip = Boolean(params.get('gzip'));
}
Expand Down
1 change: 1 addition & 0 deletions lighthouse-core/config/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ const defaultSettings = {
blockedUrlPatterns: null,
additionalTraceCategories: null,
extraHeaders: null,
extraCookies: null,
precomputedLanternData: null,
onlyAudits: null,
onlyCategories: null,
Expand Down
13 changes: 13 additions & 0 deletions lighthouse-core/gather/driver.js
Original file line number Diff line number Diff line change
Expand Up @@ -1487,6 +1487,19 @@ class Driver {
return this.sendCommand('Network.setExtraHTTPHeaders', {headers});
}

/**
* @param {LH.Crdp.Network.Cookies|null} cookies key/value pairs of HTTP Cookies.
* @return {Promise<void>}
*/
async setCookies(cookies) {
if (!cookies) {
return;
}

return this.sendCommand('Network.setCookies', {cookies});
}


/**
* @param {string} url
* @return {Promise<void>}
Expand Down
1 change: 1 addition & 0 deletions lighthouse-core/gather/gather-runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,7 @@ class GatherRunner {
// neccessary at the beginning of the next pass.
await passContext.driver.blockUrlPatterns(blockedUrls);
await passContext.driver.setExtraHTTPHeaders(passContext.settings.extraHeaders);
await passContext.driver.setCookies(passContext.settings.extraCookies);

log.timeEnd(status);
}
Expand Down
29 changes: 28 additions & 1 deletion lighthouse-core/test/gather/driver-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -412,14 +412,41 @@ describe('.setExtraHTTPHeaders', () => {
);
});

it('should Network.setExtraHTTPHeaders when there are extra-headers', async () => {
it('should not Network.setExtraHTTPHeaders when there are extra-headers', async () => {
connectionStub.sendCommand = createMockSendCommandFn();
await driver.setExtraHTTPHeaders();

expect(connectionStub.sendCommand).not.toHaveBeenCalled();
});
});

describe('.setCookies', () => {
it('should call Network.setCookies when there are extra-cookies', async () => {
connectionStub.sendCommand = createMockSendCommandFn().mockResponse(
'Network.setCookies',
{}
);

await driver.setCookies([{
'name': 'cookie1',
'value': 'monster',
}]);

expect(connectionStub.sendCommand).toHaveBeenCalledWith(
'Network.setCookies',
expect.anything()
);
});

it('should not call Network.setCookies when there are extra-headers', async () => {
connectionStub.sendCommand = createMockSendCommandFn();
await driver.setCookies();

expect(connectionStub.sendCommand).not.toHaveBeenCalled();
});
});


describe('.getAppManifest', () => {
it('should return null when no manifest', async () => {
connectionStub.sendCommand = createMockSendCommandFn().mockResponse(
Expand Down
27 changes: 26 additions & 1 deletion lighthouse-core/test/gather/gather-runner-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const fakeDriver = require('./fake-driver.js');
const fakeDriverUsingRealMobileDevice = fakeDriver.fakeDriverUsingRealMobileDevice;

function getMockedEmulationDriver(emulationFn, netThrottleFn, cpuThrottleFn,
blockUrlFn, extraHeadersFn) {
blockUrlFn, extraHeadersFn, extraCookiesFn) {
const Driver = require('../../gather/driver.js');
const Connection = require('../../gather/connections/connection.js');
const EmulationDriver = class extends Driver {
Expand Down Expand Up @@ -81,6 +81,9 @@ function getMockedEmulationDriver(emulationFn, netThrottleFn, cpuThrottleFn,
case 'Network.setExtraHTTPHeaders':
fn = extraHeadersFn;
break;
case 'Network.setCookies':
fn = extraCookiesFn;
break;
default:
fn = null;
break;
Expand Down Expand Up @@ -578,6 +581,28 @@ describe('GatherRunner', function() {
));
});

it('tells the driver to set additional cookies when extraCookies flag is given', () => {
let receivedCookies = null;
const driver = getMockedEmulationDriver(null, null, null, null, null, params => {
receivedCookies = params.cookies;
});
const cookies = [{
'name': 'cookie1',
'value': 'monster'
}];

return GatherRunner.setupPassNetwork({
driver,
settings: {
extraCookies: cookies,
},
passConfig: {gatherers: []},
}).then(() => assert.deepStrictEqual(
receivedCookies,
cookies
));
});

it('tells the driver to begin tracing', async () => {
let calledTrace = false;
const driver = {
Expand Down
22 changes: 12 additions & 10 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,18 +101,20 @@ Options:
--throttling.uploadThroughputKbps Controls emulated network upload throughput
--throttling.cpuSlowdownMultiplier Controls simulated + emulated CPU throttling
--extra-headers Set extra HTTP Headers to pass with request [string]
--extra-cookies Set extra HTTP Cookies to pass with request [string]
Examples:
lighthouse <url> --view Opens the HTML report in a browser after the run completes
lighthouse <url> --config-path=./myconfig.js Runs Lighthouse with your own configuration: custom audits, report
generation, etc.
lighthouse <url> --output=json --output-path=./report.json --save-assets Save trace, devtoolslog, and named JSON report.
lighthouse <url> --emulated-form-factor=none Disable device emulation and all throttling.
--throttling-method=provided
lighthouse <url> --chrome-flags="--window-size=412,660" Launch Chrome with a specific window size
lighthouse <url> --quiet --chrome-flags="--headless" Launch Headless Chrome, turn off logging
lighthouse <url> --extra-headers "{\"Cookie\":\"monster=blue\"}" Stringify\'d JSON HTTP Header key/value pairs to send in requests
lighthouse <url> --extra-headers=./path/to/file.json Path to JSON file of HTTP Header key/value pairs to send in requests
lighthouse <url> --view Opens the HTML report in a browser after the run completes
lighthouse <url> --config-path=./myconfig.js Runs Lighthouse with your own configuration: custom audits, report generation, etc.
lighthouse <url> --output=json --output-path=./report.json --save-assets Save trace, screenshots, and named JSON report.
lighthouse <url> --emulated-form-factor=none --throttling-method=provided Disable device emulation and all throttling
lighthouse <url> --chrome-flags="--window-size=412,660" Launch Chrome with a specific window size
lighthouse <url> --quiet --chrome-flags="--headless" Launch Headless Chrome, turn off logging
lighthouse <url> --extra-headers "{\"x-men\":\"wolverine\"}" Stringify'd JSON HTTP Header key/value pairs to send in requests
lighthouse <url> --extra-headers=./path/to/file.json Path to JSON file of HTTP Header key/value pairs to send in requests
lighthouse <url> --extra-cookies "[{\"name\":\"session_id\",\"value\":\"x-men\" }]" Stringify'd JSON array of HTTP Cookies to send in requests
lighthouse <url> --extra-cookies=./path/to/file.json Path to JSON file of HTTP Cookies to send in requests
lighthouse <url> --only-categories=performance,pwa Only run specific categories.
For more information on Lighthouse, see https://developers.google.com/web/tools/lighthouse/.
```
Expand Down

0 comments on commit 5a8b8ce

Please sign in to comment.