Skip to content

Update API call for checking local binary running or not #249

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

Merged
merged 5 commits into from
Feb 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 1 addition & 2 deletions bin/commands/runs.js
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,6 @@ module.exports = function run(args, rawArgs) {
}).finally(() =>{
let terminalWidth = (process.stdout.columns) * 0.9;
let lineSeparator = "\n" + "-".repeat(terminalWidth);
console.log(lineSeparator)
logger.info(Constants.userMessages.BUILD_FAILED_ERROR)
process.exitCode = Constants.BUILD_FAILED_EXIT_CODE;
});
Expand Down Expand Up @@ -258,7 +257,7 @@ module.exports = function run(args, rawArgs) {
utils.sendUsageReport(bsConfig, args, `${message}\n${dashboardLink}`, Constants.messageTypes.SUCCESS, null, buildReportData, rawArgs);
return;
}).catch(async function (err) {
if (err && err.includes('browserstack.geoLocation')) {
if (err && err.toString().includes('browserstack.geoLocation')) {
err = err.replace(/browserstack.geoLocation/g, 'geolocation');
}
// Build creation failed
Expand Down
36 changes: 22 additions & 14 deletions bin/helpers/capabilityHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,21 +71,31 @@ const caps = (bsConfig, zip) => {
obj.local = true;
}

obj.localMode = null;
// Local Mode
if (obj.local === true && bsConfig.connection_settings.local_mode) {
obj.localMode = bsConfig.connection_settings.local_mode;
if (bsConfig.connection_settings.user_defined_local_mode_warning) {
logger.warn(Constants.userMessages.INVALID_LOCAL_MODE_WARNING);
// binary was spawned locally
if(obj.local === true) {
if (!Utils.isUndefined(process.env.BSTACK_CYPRESS_LOCAL_BINARY_RUNNING) && process.env.BSTACK_CYPRESS_LOCAL_BINARY_RUNNING == "true") {
obj.localMode = null;

// Local Mode
if (bsConfig.connection_settings.local_mode) {
obj.localMode = bsConfig.connection_settings.local_mode;
if (bsConfig.connection_settings.user_defined_local_mode_warning) {
logger.warn(Constants.userMessages.INVALID_LOCAL_MODE_WARNING);
}
logger.info(`Local testing set up in ${obj.localMode} mode.`);
}

// Local Identifier
obj.localIdentifier = null;
if (bsConfig.connection_settings.localIdentifier || bsConfig.connection_settings.local_identifier) {
obj.localIdentifier = bsConfig.connection_settings.localIdentifier || bsConfig.connection_settings.local_identifier;
logger.info(`Local testing identifier: ${obj.localIdentifier}`);
}
}
logger.info(`Local testing set up in ${obj.localMode} mode.`);
}

// Local Identifier
obj.localIdentifier = null;
if (obj.local === true && (bsConfig.connection_settings.localIdentifier || bsConfig.connection_settings.local_identifier)) {
obj.localIdentifier = bsConfig.connection_settings.localIdentifier || bsConfig.connection_settings.local_identifier;
logger.info(`Local testing identifier: ${obj.localIdentifier}`);
if (!Utils.isUndefined(process.env.BSTACK_CYPRESS_LOCAL_BINARY_ALREADY_RUNNING) && process.env.BSTACK_CYPRESS_LOCAL_BINARY_ALREADY_RUNNING == "true") {
logger.info(Constants.userMessages.LOCAL_BINARY_ALREADY_RUNNING);
}

logger.info(`Local is set to: ${obj.local} (${obj.local ? Constants.userMessages.LOCAL_TRUE : Constants.userMessages.LOCAL_FALSE})`);
Expand Down Expand Up @@ -164,8 +174,6 @@ const validate = (bsConfig, args) => {
// validate local args i.e --local-mode and --local-identifier

if( Utils.searchForOption('--local-identifier') && (Utils.isUndefined(args.localIdentifier) || (!Utils.isUndefined(args.localIdentifier) && !args.localIdentifier.trim()))) reject(Constants.validationMessages.INVALID_CLI_LOCAL_IDENTIFIER);

if( Utils.getLocalFlag(bsConfig.connection_settings) && (Utils.isUndefined(bsConfig["connection_settings"]["local_identifier"]) || ( !Utils.isUndefined(bsConfig["connection_settings"]["local_identifier"]) && !bsConfig["connection_settings"]["local_identifier"].trim()))) reject(Constants.validationMessages.INVALID_LOCAL_IDENTIFIER);

if( Utils.searchForOption('--local-mode') && ( Utils.isUndefined(args.localMode) || (!Utils.isUndefined(args.localMode) && !["always-on","on-demand"].includes(args.localMode)))) reject(Constants.validationMessages.INVALID_LOCAL_MODE);

Expand Down
1 change: 1 addition & 0 deletions bin/helpers/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ const userMessages = {
LOCAL_START_FAILED: "Local Testing setup failed.",
LOCAL_STOP_FAILED: "Local Binary stop failed.",
INVALID_LOCAL_MODE_WARNING: "Invalid value specified for local_mode. local_mode: (\"always-on\" | \"on-demand\"). For more info, check out https://www.browserstack.com/docs/automate/cypress/cli-reference",
LOCAL_BINARY_ALREADY_RUNNING: "We found an existing BrowserStack Local connection running from your account. Using the existing connection for this build. If you wish to use a new Local connection for your build, please specify a value for 'local_identifier' within 'connection_settings' in your browserstack.json config.",
SPEC_LIMIT_WARNING: "You might not see all your results on the dashboard because of high spec count, please consider reducing the number of spec files in this folder.",
DOWNLOAD_BUILD_ARTIFACTS_FAILED: "Downloading build artifacts for the build <build-id> failed for <machine-count> machines.",
ASYNC_DOWNLOADS: "Test artifacts as specified under 'downloads' can be downloaded after the build has completed its run, using 'browserstack-cypress generate-downloads <build-id>'",
Expand Down
59 changes: 19 additions & 40 deletions bin/helpers/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -593,11 +593,6 @@ exports.setLocalIdentifier = (bsConfig, args) => {
!this.isUndefined(bsConfig["connection_settings"]["local_identifier"])
){
bsConfig['connection_settings']['local_mode'] = 'always-on';
} else if (
bsConfig['connection_settings']['local'] &&
this.isUndefined(bsConfig["connection_settings"]["local_identifier"])
){
bsConfig["connection_settings"]["local_identifier"] = this.generateLocalIdentifier(bsConfig['connection_settings']['local_mode']);
}
};

Expand Down Expand Up @@ -637,9 +632,18 @@ exports.setLocalMode = (bsConfig, args) => {
exports.setupLocalTesting = (bsConfig, args, rawArgs) => {
return new Promise(async (resolve, reject) => {
if( bsConfig['connection_settings'] && bsConfig['connection_settings']['local'] && String(bsConfig['connection_settings']['local']) === "true" ){
let localIdentifierRunning = await this.checkLocalIdentifierRunning(
bsConfig, bsConfig['connection_settings']['local_identifier']
);
let localBinaryRunning = await this.checkLocalBinaryRunning(bsConfig, bsConfig['connection_settings']['local_identifier']);
let localIdentifierRunning;
if (localBinaryRunning['should_spawn_binary'] == true) {
localIdentifierRunning = false;
if(this.isUndefined(bsConfig["connection_settings"]["local_identifier"])) {
bsConfig["connection_settings"]["local_identifier"] = this.generateLocalIdentifier(bsConfig['connection_settings']['local_mode']);
}
} else {
localIdentifierRunning = true;
process.env.BSTACK_CYPRESS_LOCAL_BINARY_ALREADY_RUNNING = "true"; // shows message when binary is not spawned by the CLI process
process.env.BSTACK_CYPRESS_LOCAL_BINARY_RUNNING = "true";
}
if (!localIdentifierRunning){
bsConfig.connection_settings.usedAutoLocal = true;
var bs_local = this.getLocalBinary();
Expand All @@ -648,6 +652,7 @@ exports.setupLocalTesting = (bsConfig, args, rawArgs) => {
logger.info('Setting up Local testing...');
bs_local.start(bs_local_args, function (localStartError) {
if (that.isUndefined(localStartError)) {
process.env.BSTACK_CYPRESS_LOCAL_BINARY_RUNNING = "true";
resolve(bs_local);
} else {
let message = `name: ${localStartError.name}, message: ${localStartError.message}, extra: ${localStartError.extra}`,
Expand Down Expand Up @@ -675,22 +680,6 @@ exports.setupLocalTesting = (bsConfig, args, rawArgs) => {

exports.stopLocalBinary = (bsConfig, bs_local, args, rawArgs) => {
return new Promise(async (resolve, reject) => {
if(bsConfig['connection_settings'] && bsConfig['connection_settings']['local']){
let localIdentifierRunning = await this.checkLocalIdentifierRunning(bsConfig,bsConfig["connection_settings"]["local_identifier"]);
if(!localIdentifierRunning){
let message = `Local Binary not running.`,
errorCode = 'local_identifier_error';
this.sendUsageReport(
bsConfig,
args,
message,
Constants.messageTypes.ERROR,
errorCode,
null,
rawArgs
);
}
}
if (!this.isUndefined(bs_local) && bs_local.isRunning() && bsConfig['connection_settings'] && bsConfig['connection_settings']['local_mode'].toLowerCase() != "always-on") {
let that = this;
bs_local.stop(function (localStopError) {
Expand Down Expand Up @@ -744,35 +733,26 @@ exports.generateLocalIdentifier = (mode) => {
return Buffer.from(local_identifier).toString("base64");
};

exports.checkLocalIdentifierRunning = (bsConfig, localIdentifier) => {
exports.checkLocalBinaryRunning = (bsConfig, localIdentifier) => {
let options = {
url: `${config.localTestingListUrl}?auth_token=${bsConfig.auth.access_key}&state=running`,
url: `${config.cypress_v1}/local_binary_running_check`,
auth: {
user: bsConfig.auth.username,
password: bsConfig.auth.access_key,
},
headers: {
'Content-Type': 'application/json',
'User-Agent': this.getUserAgent(),
},
body: JSON.stringify({ localIdentifier: localIdentifier}),
};
let that = this;
return new Promise ( function(resolve, reject) {
request.get(options, function (err, resp, body) {
request.post(options, function (err, resp, body) {
if(err){
reject(err);
}
let response = JSON.parse(body);
let localInstances = [];
if(!that.isUndefined(response['instances'])){
localInstances = response['instances'];
}
let localIdentifiers = [];

localInstances.forEach(function(instance){
localIdentifiers.push(instance['localIdentifier']);
});

resolve(localIdentifiers.includes(localIdentifier));
resolve(response);
});
});
};
Expand Down Expand Up @@ -1047,7 +1027,6 @@ exports.stopBrowserStackBuild = async (bsConfig, args, buildId, rawArgs) => {
logger.info(message);
}
} catch(err) {
console.log(err);
message = Constants.userMessages.BUILD_STOP_FAILED;
messageType = Constants.messageTypes.ERROR;
errorCode = 'api_failed_build_stop';
Expand Down
70 changes: 40 additions & 30 deletions test/unit/bin/helpers/capabilityHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,37 +162,47 @@ describe("capabilityHelper.js", () => {
});
});

it("handle local_identifier set", () => {
let zip_url = "bs://<random>";
let bsConfig = {
auth: {
username: "random",
access_key: "random",
},
browsers: [
{
browser: "chrome",
os: "Windows 10",
versions: ["78", "77"],
context("handle local_identifier set when local binary spawned", () => {
beforeEach(() => {
process.env.BSTACK_CYPRESS_LOCAL_BINARY_RUNNING = "true";
});

afterEach(() => {
delete process.env.BSTACK_CYPRESS_LOCAL_BINARY_RUNNING;
});

it("handle local_identifier set", () => {
let zip_url = "bs://<random>";
let bsConfig = {
auth: {
username: "random",
access_key: "random",
},
],
connection_settings: {
local: true,
local_identifier: "abc"
},
run_settings: {
}
};
return capabilityHelper
.caps(bsConfig, { zip_url: zip_url })
.then(function (data) {
let parsed_data = JSON.parse(data);
chai.assert.equal(parsed_data.local, true);
chai.assert.equal(parsed_data.localIdentifier, "abc");
})
.catch((error) => {
chai.assert.fail("Promise error");
});
browsers: [
{
browser: "chrome",
os: "Windows 10",
versions: ["78", "77"],
},
],
connection_settings: {
local: true,
local_identifier: "abc"
},
run_settings: {
}
};
return capabilityHelper
.caps(bsConfig, { zip_url: zip_url })
.then(function (data) {
let parsed_data = JSON.parse(data);
chai.assert.equal(parsed_data.local, true);
chai.assert.equal(parsed_data.localIdentifier, "abc");
})
.catch((error) => {
chai.assert.fail("Promise error");
});
});
});

it("handle local_identifier not set", () => {
Expand Down
Loading