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

Move network-related commands to .network namespace. #3797

Merged
merged 17 commits into from
Jul 19, 2023
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
17 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
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const ClientCommand = require('./_base-command.js');
const {Logger} = require('../../utils');
const ClientCommand = require('../_base-command.js');
const {Logger} = require('../../../utils');

/**
* Capture outgoing network calls from the browser.
Expand All @@ -9,7 +9,7 @@ const {Logger} = require('../../utils');
* it('captures and logs network requests as they occur', function(this: ExtendDescribeThis<{requestCount: number}>) {
* this.requestCount = 1;
* browser
* .captureNetworkRequests((requestParams) => {
* .network.captureRequests((requestParams) => {
* console.log('Request Number:', this.requestCount!++);
* console.log('Request URL:', requestParams.request.url);
* console.log('Request method:', requestParams.request.method);
Expand All @@ -19,15 +19,20 @@ const {Logger} = require('../../utils');
* });
* });
*
* @method captureNetworkRequests
* @method network.captureRequests
* @syntax .captureNetworkRequests(onRequestCallback)
* @syntax .network.captureRequests(onRequestCallback)
* @param {function} onRequestCallback Callback function called whenever a new outgoing network request is made.
* @api protocol.cdp
* @since 2.2.0
* @moreinfo nightwatchjs.org/guide/network-requests/capture-network-calls.html
*/
class CaptureNetworkCalls extends ClientCommand {

static get namespacedAliases() {
return 'captureNetworkRequests';
}

performAction(callback) {

if (!this.api.isChrome() && !this.api.isEdge()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const ClientCommand = require('./_base-command.js');
const {Logger} = require('../../utils');
const ClientCommand = require('../_base-command.js');
const {Logger} = require('../../../utils');

/**
* Intercept the request made on a particular URL and mock the response.
Expand All @@ -8,7 +8,7 @@ const {Logger} = require('../../utils');
* describe('mock network response', function() {
* it('intercepts the request made to Google search and mocks its response', function() {
* browser
* .mockNetworkResponse('https://www.google.com/', {
* .network.mockResponse('https://www.google.com/', {
* status: 200,
* headers: {
* 'Content-Type': 'UTF-8'
Expand All @@ -20,8 +20,9 @@ const {Logger} = require('../../utils');
* });
* });
*
* @method mockNetworkResponse
* @method network.mockResponse
* @syntax .mockNetworkResponse(urlToIntercept, {status, headers, body}, [callback])
garg3133 marked this conversation as resolved.
Show resolved Hide resolved
* @syntax .network.mockResponse(urlToIntercept, {status, headers, body}, [callback])
* @param {string} urlToIntercept URL to intercept and mock the response from.
* @param {object} response Response to return. Defaults: `{status: 200, headers: {}, body: ''}`.
* @param {function} [callback] Callback function to be called when the command finishes.
Expand All @@ -31,6 +32,10 @@ const {Logger} = require('../../utils');
*/
class MockNetworkResponse extends ClientCommand {

static get namespacedAliases() {
return 'mockNetworkResponse';
}

performAction(callback) {

if (!this.api.isChrome() && !this.api.isEdge()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,28 +1,36 @@
const ClientCommand = require('./_base-command.js');
const {Logger} = require('../../utils');
const ClientCommand = require('../_base-command.js');
const {Logger} = require('../../../utils');

/**
*
* Command to set Chrome network emulation settings.
*
* @example
* this.demoTest = function (browser) {
* browser.setNetworkConditions({
* describe('set network conditions', function() {
* it('sets the network conditions',function() {
* browser
* .network.setConditions({
* offline: false,
* latency: 50000,
* download_throughput: 450 * 1024,
* upload_throughput: 150 * 1024
* latency: 3000,
* download_throughput: 500 * 1024,
* upload_throughput: 500 * 1024
* });
* };
* });
* });
*
*
* @method setNetworkConditions
* @method network.setConditions
* @syntax .setNetworkConditions(spec, [callback])
* @syntax .network.setConditions(spec, [callback])
* @param {object} spec
* @param {function} [callback] Optional callback function to be called when the command finishes.
* @api protocol.sessions
*/
class SetNetworkConditions extends ClientCommand {

static get namespacedAliases() {
return 'setNetworkConditions';
}

performAction(callback) {
if (!this.api.isChrome() && !this.api.isEdge()) {
const error = new Error('SetNetworkConditions is not supported while using this driver');
Expand Down
67 changes: 67 additions & 0 deletions test/src/api/commands/client/testCaptureNetworkRequests.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,73 @@ describe('.captureNetworkRequests()', function () {
});
});

it('browser.network.captureRequests()', function (done) {

MockServer.addMock({
url: '/session',
response: {
value: {
sessionId: '13521-10219-202',
capabilities: {
browserName: 'chrome',
browserVersion: '92.0'
}
}
},
method: 'POST',
statusCode: 201
}, true);

Nightwatch.initW3CClient({
desiredCapabilities: {
browserName: 'chrome',
'goog:chromeOptions': {}
},
output: process.env.VERBOSE === '1',
silent: false
}).then(client => {
const expected = {};

const cdpNetworkEvent = JSON.stringify({
method: 'Network.requestWillBeSent',
params: {
request: {
url: 'https://www.google.com',
method: 'GET',
headers: []
}
}
});

cdp.resetConnection();
client.transport.driver.createCDPConnection = function() {
return Promise.resolve({
_wsConnection: {
on: (event, callback) => {
expected['wsEvent'] = event;
callback(cdpNetworkEvent);
}
},
execute: function(command, params) {
expected['cdpCommand'] = command;
expected['cdpParams'] = params;
}
});
};

const userCallback = (requestParams) => {
expected['requestParams'] = requestParams;
};
client.api.network.captureRequests(userCallback, function () {
assert.deepEqual(expected.cdpCommand, 'Network.enable');
assert.deepEqual(expected.cdpParams, {});
assert.strictEqual(expected.wsEvent, 'message');
assert.deepEqual(expected.requestParams, JSON.parse(cdpNetworkEvent).params);
});
client.start(done);
});
});

it('throws error without callback', function (done) {

MockServer.addMock({
Expand Down
80 changes: 80 additions & 0 deletions test/src/api/commands/client/testMockNetworkResponse.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,86 @@ describe('.mockNetworkResponse()', function () {
});
});

it('browser.network.mockResponse(urlToIntercept, {status, headers, body}) with url match', function (done) {
MockServer.addMock({
url: '/session',
response: {
value: {
sessionId: '13521-10219-202',
capabilities: {
browserName: 'chrome',
browserVersion: '92.0'
}
}
},
method: 'POST',
statusCode: 201
}, true);

Nightwatch.initW3CClient({
desiredCapabilities: {
browserName: 'chrome',
'goog:chromeOptions': {}
},
output: process.env.VERBOSE === '1',
silent: false
}).then(client => {
const expected = {
cdpCommands: []
};

// Parameters of actual request made by browser
const cdpFetchRequestPauseEvent = JSON.stringify({
method: 'Fetch.requestPaused',
params: {
requestId: '123',
request: {
url: 'https://www.google.com/'
}
}
});

cdp.resetConnection();
client.transport.driver.createCDPConnection = function() {
return Promise.resolve({
_wsConnection: {
on: (event, callback) => {
expected['wsEvent'] = event;
callback(cdpFetchRequestPauseEvent);
}
},
execute: function(command, params) {
expected.cdpCommands.push(command);
if (command === 'Fetch.fulfillRequest') {
expected['requestId'] = params.requestId;
expected['responseCode'] = params.responseCode;
expected['responseHeaders'] = params.responseHeaders;
expected['responseBody'] = params.body;
}
}
});
};

const response = {
status: 200,
headers: {'Content-Type': 'UTF-8'},
body: 'Hey there!'
};
client.api.network.mockResponse('https://www.google.com/', response, function () {
// Assert final response with response passed
assert.strictEqual(expected.responseCode, response.status);
assert.deepEqual(expected.responseHeaders, [{name: 'Content-Type', value: 'UTF-8'}]);
assert.strictEqual(expected.responseBody, Buffer.from(response.body, 'utf-8').toString('base64'));

assert.strictEqual(expected.requestId, JSON.parse(cdpFetchRequestPauseEvent).params.requestId);
assert.strictEqual(expected.wsEvent, 'message');
assert.deepEqual(expected.cdpCommands, ['Fetch.fulfillRequest', 'Fetch.enable', 'Network.setCacheDisabled']);
});

client.start(done);
});
});

it('browser.mockNetworkResponse(urlToIntercept, {status, headers, body}) with multiple mocks', function (done) {
MockServer.addMock({
url: '/session',
Expand Down
70 changes: 69 additions & 1 deletion test/src/api/commands/client/testSetNetworkConditions.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ const Nightwatch = require('../../../../lib/nightwatch.js');

describe('.setNetworkConditions()', function () {
beforeEach(function (done) {
CommandGlobals.beforeEach.call(this, done);
this.server = MockServer.init();

this.server.on('listening', () => {
done();
});
});

afterEach(function (done) {
Expand Down Expand Up @@ -59,6 +63,70 @@ describe('.setNetworkConditions()', function () {
});
});


it('browser.network.setConditions()', function (done) {
MockServer.addMock(
{
url: '/session',
response: {
value: {
sessionId: '13521-10219-202',
capabilities: {
browserName: 'chrome',
browserVersion: '92.0'
}
}
},
method: 'POST',
statusCode: 201
},
true
);

Nightwatch.initW3CClient({
desiredCapabilities: {
browserName: 'chrome',
'goog:chromeOptions': {}
},
output: process.env.VERBOSE === '1',
silent: false
}).then((client) => {
const expected = {};
client.transport.driver.setNetworkConditions = function (spec) {
expected['download_throughput'] = spec.download_throughput;
expected['latency'] = spec.latency;
expected['offline'] = spec.offline;
expected['upload_throughput'] = spec.upload_throughput;

return Promise.resolve();
};

client.api.network.setConditions({
offline: false,
latency: 50000,
download_throughput: 450 * 1024,
upload_throughput: 150 * 1024
},
function (result) {
expected['callback_result'] = result.value;
});

client.start(function (err) {
try {
assert.strictEqual(err, undefined);
assert.strictEqual(expected.callback_result, null);
assert.strictEqual(expected.download_throughput, 460800);
assert.strictEqual(expected.latency, 50000);
assert.strictEqual(expected.offline, false);
assert.strictEqual(expected.upload_throughput, 153600);
done();
} catch (e){
done(e);
}
});
});
});

it('browser.setNetworkConditions - driver not supported', function (done) {
Nightwatch.initW3CClient({
desiredCapabilities: {
Expand Down
Loading