How to set args from chromeOptions in beforeSession webdriverIO+Cucumber - selenium-chromedriver

I need to install args before the session. On a specific tag must be transmitted a specific screen resolution. I tried to implement beforeSession, but the necessary arg is not in chromeOptions.args when starting the session.
I tried two version:
1.
beforeSession:
beforeSession: function(){
if(argv.tags ===("#virtualFront")){
exports.config.capabilities[0].chromeOptions.args.push('--window-size=1080,1920');
} else{
exports.config.capabilities[0].chromeOptions.args.push(' --start-maximized');
}
console.log("it is from config beforeSession: "+exports.config.capabilities[0].chromeOptions.args);
},
suite.cucumber.wdio.conf:
browserName: 'chrome',
chromeOptions: {
args: ['--incognito',],
binary: '/Program Files (x86)/Google/Chrome/Application/chrome.exe'
},
BeforeSession:
beforeSession: function(){
if(argv.tags ===("#virtualFront")){
argv.optionChrome = '--window-size=1080,1920';
} else{
argv.optionChrome=' --start-maximized';
}
console.log("it is from config beforeSession: "+exports.config.capabilities[0].chromeOptions.args);
},
suite.cucumber.wdio.conf:
{
browserName: 'chrome',
chromeOptions: {
args: ['--incognito',argv.optionChrome, ],
binary: '/Program Files (x86)/Google/Chrome/Application/chrome.exe'
},
When I use 2 version args asigned to null

The solution was to add the script to the beginning of suite.cucumber.wdio.conf:
let chromeOpts = ['--incognito'];
if (argv.tags ==="#virtualFont"){
chromeOpts +=` --window-size=1080,1920`
}else chromeOpts +=` --start-maximized`;
and:
chromeOptions: {
args: [ chromeOpts, ],
binary: '/Program Files (x86)/Google/Chrome/Application/chrome.exe'
//for windows7
},

Related

Create JSON file from Groovy variables in Pipeline - jenkins job

i am new to jenkins, i have a pipline job with parameters.
I want to create a JSON file and write my parameters there.
(and then let my jar file read that JSON file and run according to it)
how can i do this in groovy?
this is my jenkins file:
pipeline {
agent {
label "create_pass_criteria"
}
parameters {
string(name: 'IP', description: 'Please enter your ip')
password(name: 'PASSWORD',description: 'Please enter your mx password')
string(name: 'NAME', description: 'Please enter the name ')
}
tools {
maven 'maven-3.3.9'
}
options
{
buildDiscarder(logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '20'))
gitLabConnection('gitlab')
}
stages {
stage('Git Clone') {
steps {
updateGitlabCommitStatus name: 'Build', state: 'running'
checkout([
$class : 'GitSCM',
branches : [[name: '*/master']],
doGenerateSubmoduleConfigurations: false,
extensions : [],
submoduleCfg : [],
userRemoteConfigs : [[credentialsId: GIT_CRED, url: GIT_PATH]]
])
}
}
stage('Build') {
steps {
sh 'mvn install'
}
}
stage('run') {
steps {
sh 'java -jar /var/lib/jenkins/workspace/create_pass_criteria/target/create_pass_criteria-8.0.125-SNAPSHOT.jar'
}
}
}
post {
success {
updateGitlabCommitStatus name: 'Build', state: 'success'
emailext(
to: EMAIL_ADDR,
subject: "Success Pipeline: ${currentBuild.fullDisplayName}",
body: "Pipeline URL: ${env.BUILD_URL}",
mimeType: 'text/html'
)
}
failure {
updateGitlabCommitStatus name: 'Build', state: 'failed'
emailext(
to: EMAIL_ADDR,
subject: "Failed Pipeline: ${currentBuild.fullDisplayName}",
body: "Pipeline URL: ${env.BUILD_URL}",
mimeType: 'text/html'
)
}
}
} // pipeline
i don't know if it is correct but this is what i need to add to my Jenkins file?:
node{
//to create json declare a sequence of maps/arrays in groovy
//here is the data according to your sample
def data = [
attachments:[
[
mxIp : params.MX_IP,
mxPassword : params.MX_PASSWORD,
policyName : params.POLICY_NAME,
]
]
]
writeJSON(file: 'parameters.json', json: data)
}
if yes, at which part does it is has to be?
You could put this code in a script block like this:
stage('run') {
steps {
script {
def data = [
attachments:[
[
mxIp : params.MX_IP,
mxPassword : params.MX_PASSWORD,
policyName : params.POLICY_NAME,
]
]
]
writeJSON(file: 'parameters.json', json: data)
}
sh 'java -jar /var/lib/jenkins/workspace/create_pass_criteria/target/create_pass_criteria-8.0.125-SNAPSHOT.jar'
}
}
In complex pipelines I try to create clean code by adhering to the single level of abstraction principle. In this case I would extract the script and sh steps into a separate function, which could then be called from the pipeline section as a single step:
stage('run') {
steps {
createPassCriteria()
}
}
Define the function after the closing } of the pipeline section:
void createPassCriteria() {
def data = [
attachments:[
[
mxIp : params.MX_IP,
mxPassword : params.MX_PASSWORD,
policyName : params.POLICY_NAME,
]
]
]
writeJSON(file: 'parameters.json', json: data)
sh 'java -jar /var/lib/jenkins/workspace/create_pass_criteria/target/create_pass_criteria-8.0.125-SNAPSHOT.jar'
}

Using an variable object inside a Gruntfile

I'm trying to avoid duplicate code by using a variable object inside a Gruntfile with a set of specified parameters. I apologize if this is declared incorrectly, as I'm not entirely sure how to create an object variable in gruntjs. The goal is to use sonarProperties inside the sonarRunner config. In the if block, add some additional lines, and the else block, just use sonarProperties. Unfortunately my syntax is incorrect. Is this even possible? I'm basing it off of a gulpfile and would like to do something similar.
Sample gulpfile:
const packageName = require('./package.json').name;
gulp.task('sonar', callback => {
let sonarProperties = {
// #################################################
// # General Configuration
// #################################################
'sonar.projectKey': `microservice:${packageName}`,
'sonar.sourceEncoding': 'UTF-8',
'sonar.login': process.env.SONAR_TOKEN,
// #################################################
// # Javascript Configuration
// #################################################
'sonar.language': 'javascript',
'sonar.sources': 'src',
'sonar.tests': 'test',
'sonar.javascript.lcov.reportPaths': 'coverage/lcov.info',
'sonar.coverage.exclusions': 'src/**/*.spec.js',
};
if (process.env.SONAR_ANALYSIS_TYPE === 'pr') {
sonarProperties = {
...sonarProperties, // #################################################
// # Github Configuration
// #################################################
'sonar.pullrequest.provider': 'github',
'sonar.pullrequest.branch': process.env.branch,
'sonar.pullrequest.key': process.env.pr_numbers,
'sonar.pullrequest.base': process.env.base_branch,
'sonar.pullrequest.github.repository': process.env.repo,
'sonar.scm.revision': process.env.sha,
};
}
Here's the pertinent points of my gruntfile:
sonarProperties: [{
projectKey: 'microservice:<%= pkg.name %>',
projectName: 'Microservice - <%= pkg.name %>',
sourceEncoding: 'UTF-8',
login: 'admin',
password: 'admin',
host: {
url: 'http://localhost:9000/'
},
language: 'js',
sources: 'js',
tests: 'test',
testExecutionReportPaths: 'test_coverage_reporter/report.xml',
javascript: {
lcov: {
reportPaths: 'test_coverage/lcov.info'
}
},
}],
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
sonarRunner: {
analysis: {
options: {
debug: true,
separator: '\n',
sonar: (function() {
if (process.env.SONAR_ANALYSIS_TYPE === 'pr') {
return {
...sonarProperties
moreParams: someData,
};
} else {
return {
// use just sonarProperties
};
}
}())
}
}
}
});
I was able to create the function with the following:
grunt.registerTask('sonar', function () {
let sonarProperties = {
// #################################################
// # General Configuration
// #################################################
..
}
And declaring it as a callback from the beginning as a grunt task.

How to prevent duplicates being added to JSON object

Using Electron and electron-store to add files' simplified executable names and their full paths from showOpenDialog to config.json. Selecting the same file causes repeating entries in config.json. For some reason (or rather missing code), app thinks they're different paths.
function addTool() {
dialog.showOpenDialog({
title: 'Select tool executable.',
filters: [{
name: 'Tool start file',
extensions: ['exe', 'jar']
}],
properties: ['openFile']
},
(exeFromDialog) => {
var var_exeToolPath = exeFromDialog.join(); //removes square brackets
var var_toolName = path.basename(var_exeToolPath).split(/[/._-]/g)[0];
//path.basename removes path until file, split+regex takes only first part until first character (one of ._/)
const tools = appConfig.get('tools');
const newTool = [...(tools || []), {
"toolName": var_toolName,
"toolPath": var_exeToolPath
}];
appConfig.set('tools', newTool);
})
}
This is how config.json looks when you open the same file few times:
{
"winPosition": {
"x": 1497,
"y": 410,
"width": 203,
"height": 603
},
"exePOEPath": [
"C:\\Program Files (x86)\\Grinding Gear Games\\Path of Exile\\PathOfExile_x64.exe"
],
"tools": [
{
"toolName": "tool1",
"toolPath": "D:\\tool1.exe"
},
{
"toolName": "tool1",
"toolPath": "D:\\tool1.exe"
},
{
"toolName": "tool1",
"toolPath": "D:\\tool1.exe"
}
]
}
Ultimately it comes to the question How to remove duplicates from your array
This part of your code will always add the new value, it doesn't check for duplicates
const newTool = [...(tools || []), {
toolName: var_toolName,
toolPath: var_exeToolPath
}]
So it should be improved to something like the following:
newTool = newTool.filter((item, pos, self) =>
self.find(other => other.toolName === item.toolName) === item
)
I would prefer using [...new Set([newTool])] but you store Objects which are compared by reference thus duplicates cannot be eliminated by Set

Winston log format

i am using Winston ^3.0.0-rc6 as below :
var options = {
file: {
level: 'info',
filename: `${appRoot}/logs/app.log`,
handleExceptions: true,
json: true,
prettyPrint: true,
maxsize: 5242880, // 5MB
maxFiles: 5,
colorize: true,
}
};
const jsonFormatter = (logEntry) => {
if (logEntry.type) {
const base = {
timestamp: new Date()
};
const json = Object.assign(base, logEntry);
logEntry[MESSAGE] = JSON.stringify(json);
} else {
logEntry = "";
}
return logEntry;
}
const logger = winston.createLogger({
format: winston.format(jsonFormatter)(),
transports: [
new winston.transports.File(options.file)
],
exceptionHandlers: [
new winston.transports.File(options.uncaughtExceptions)
]
});
my log output :
{"timestamp":"2018-06-10T07:41:03.387Z","type":"Authentication","status":"failed","level":"error","message":"Incorrect password"}
but i want them to be like :
{
"timestamp": "2018-06-10T07:41:03.387Z",
"type": "Authentication",
"status": "failed",
"level": "error",
"message": "Incorrect password"
}
i tried to play around with json : true , and prettyPrint but it did not do the trick .
Can any one help please
Thanks.
I noticed in your code that on the line
logEntry[MESSAGE] = JSON.stringify(json);
you're using JSON.stringify() which takes two more optional arguments
JSON.stringify(value[, replacer[, space]])
If you set space to the amount of spaces you'd like you'll get the output you're looking for. So change the initial line to be:
logEntry[MESSAGE] = JSON.stringify(json, null, 2); // or 4 ;)
(The replacer argument is null because we don't want to change the default behavior.)
This is deprecated: You can check the link here.
I tried to play around with json: true, and prettyPrint but it did not do the trick.
Simple code like this work for you:
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
//
// - Write to all logs with level `info` and below to `combined.log`
// - Write all logs error (and below) to `error.log`.
//
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
If this does not work, let me know so that I can improvise.

typeahead / filter / JSON parse?

Trying to 'parse/read' an external .json file on my typeahead code, but the .json file (which I cannot modify) looks like:
{"**cms_countries**":
[{"**cms_country**":
[{"**countrydisplayname**":"Afghanistan"}
,{"countrydisplayname":"Albania"} ,{"countrydisplayname":"Algeria"}
... ... ... ,{"countrydisplayname":"Zimbabwe"} ] } ,{"TotalRecords":
[ {"TotalRecords":"246"} ] } ] }
So, I think my problem is to know how to parse/read/assimilate/integrate/adopt this .json file, having
cms_countries ,
cms_country ,
and then, my countrydisplayname field on it. (have you seen the tree here ?)
This is my code:
$(document).ready(function() {
var searchablePlaces = new Bloodhound({
datumTokenizer : Bloodhound.tokenizers.obj.whitespace("countrydisplayname"),
queryTokenizer : Bloodhound.tokenizers.whitespace,
prefetch : 'countries.json',
remote : {
url : 'countries/%QUERY.json',
wildcard : '%QUERY',
filter : function(response) { return response.cms_country; }
},
limit : 10
});
searchablePlaces.initialize();
$('#remote .typeahead').typeahead(
{
hint : true,
highlight : true,
minLength : 2
},
{
name : 'countrydisplayname',
displayKey : "countrydisplayname",
source : searchablePlaces.ttAdapter()
})
});
But of course, it is not working:
ANY hint on how to organize my filter... ? or how to do to overcome my nested .json wrappers....
OK, I've got my code working now:
$(window).load(function(){
var movies = new Bloodhound({
limit: 10,
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: 'countries.json',
filter: function (movies) {
return $.map(movies.cms_countries[0].cms_country, function (paises) {
return {
value: paises.countrydisplayname
};
});
}
}
});
// Initialize the Bloodhound suggestion engine
movies.initialize();
// Instantiate the Typeahead UI
$('.typeahead').typeahead(
{
hint: true,
highlight: true,
minLength: 1
},
{
//displayKey: 'value',
displayKey: function (toto) {
return toto.value;
},
source: movies.ttAdapter()
});
});