String Expansion with Variables - string

I have a config file, that contains strings used within my scripts. The config file is read via a C# class using this Syntax:
$final = $PropMgr.GetValue($section, $property)
$final = $ExecutionContext.InvokeCommand.ExpandString($final)
This returns the string from the config file. Afterwards the returned string gets expanded because it may contain objects that need expansion
Everything works fine but for one thing. One of my strings in the config file looks like this:
Found $($scripts.Length) scripts to execute in the config file
$scripts is array, so the expanded string should look like this:
Found 6 scripts to execute in the config file
But using my code avove I receive an exception:
Exception calling "ExpandString" with "1" argument(s): "Object reference not set to an instance of an object."
If I debug the script and execute this code in a commandline:
$ExecutionContext.InvokeCommand.ExpandString("Found $($scripts.Length) scripts to execute in the config file")
Everything is fine, but using the $final variable instead of the string itself, I receive the exception again.
What do I have to do to achieve what I was looking for?

Related

JDBC variable names when called in the groovy script not giving the correct value for a CSV parameterization

I have a JMeter test where a CSV file containing multiple rows of comma separated values example:- internalID,drivername, usreg,canadareg. I am basically using the CSV file to compare the values with the database table values. To compare the values to database values, I am adding a JDBC request with a query 'select internalID,drivername,usreg,canadareg from data where internalid ='${internalID'}' and providing the variables names to store the column data result. I use the groovy JSR233 and call the variables names in the script by declaring String a = vars.get("dintID_${counter}") where dintID is the variable name provided in the JDBC . The issue is when I run the script the first line of data in CSV files gets executed successfully, then the second line data in CSV file is passed to SQL statement correct, however the vars.get("dintid_${counter}") always stays at previous record meaning it does not go to next internalid(dintID). I have checked that my counter is incrementing. No idea how to resolve the issue. Does anyone know what mistake I am doing.
If you take a look at JSR223 Sampler documentation you will see that:
The JSR223 test elements have a feature (compilation) that can significantly increase performance. To benefit from this feature:
Use Script files instead of inlining them. This will make JMeter compile them if this feature is available on ScriptEngine and cache them.
Or Use Script Text and check Cache compiled script if available property.
When using this feature, ensure your script code does not use JMeter variables or JMeter function calls directly in script code as caching would only cache first replacement. Instead use script parameters.
So if the counter is a JMeter Variable - it will always be the initial value and it won't increment on subsequent iterations.
So you need to change the line to:
String a = vars.get('dintID_' + vars.get('counter'))
More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It

Jenkins Pipeline - Active Choice Reactive Parameter

The following script reads all file names from a directory and displays them to the user as parameters (without extension)
import groovy.io.FileType
def list = []
def dir = new File("/var/lib/jenkins/workspace/grookins/folderx")
dir.eachFileRecurse (FileType.FILES) { file ->
list.add(file.getName().split("\\.", 2)[0])
}
return list
It works fine if I paste the code into the Groovy Script area in the UI right here
Now if I paste the script into a Jenkinsfile,
for some reason, the backslashes are turning into a simple backslash in the UI after running the script from scm
and the parameters are gone
Can someone help me to find the reason for this behavior?
By try and error i found out that the regex in the split function is interpreted differently in the UI than in the Jenkinsfile. In the Jenkinsfile 4 backslashes are required to escape the dot in the UI.
This is how the entry in the Jenkinsfile looks like:
list.add(file.getName().split("\\\\.", 2)[0])

Return a String from a Windows Batch file

I want to find the target branch when a pull request is submitted on GitHub, in my Jenkins pipeline. To achieve this I am doing the following:
I am invoking a windows batch file from my Jenkinsfile, which in turn invokes a nodejs script. This script internally invokes GitHub APIs to get the target branch which is to be set on some variable in Jenkinsfile(code snippet given below):
Jenkinsfile
env.TARGET_BRANCH = bat "GetTargetBranchFromGit.bat ${env.BRANCH_NAME}"
BatchFile:
node getTargetBranchForPR.js %1
But unfortunately, the variable env.TARGET_BRANCH is not getting set to the target branch even though the nodejs script gets the right value. I am in fact not able to return the value from the batch file. Could someone please help me here?
#npocmaka mention is the right way: How to do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?
Accodring to Jenkins' documentation.
returnStdout (optional) If checked, standard output from the task is
returned as the step value as a String, rather than being printed to
the build log. (Standard error, if any, will still be printed to the
log.) You will often want to call .trim() on the result to strip off a
trailing newline.
So your code should look like
env.TARGET_BRANCH = bat( script: "GetTargetBranchFromGit.bat ${env.BRANCH_NAME}",
returnStdout: true
).trim()
If you get back more than expected you probably need to parse it.

Throws error when passing argument with space in JAVA_OPTS in Linux

I am passing command line parameters to gatling script.
This works and executes my test in Windows operating system:
set JAVA_OPTS="-DuserCount=2 -DflowRepeatCount=3 -DdefinitionId=102168 -DtestServerUrl=https://someURL -DenvAuthenticationHeaderFromPostman="Basic UWRZm9aGwsxFsB1V7RXK0OlB5cmZvcm1hbmNldGVzdDE="
It works and takes input which is passed
**********************INPUT*************************************
User Count ====>> 2
Repeat Count ====>> 3
Definition ID ====>> 102168
Environment URL ====>> https://someURL
Authentication Header ====>> Basic UWRZm9aGwsxFsB1V7RXK0OlB5cmZvcm1hbmNldGVzdDE=
***********************************************************
I want to do this same thing on Linux System.
While if I use this command in Linux then it throws error or takes Null or Binary values as input
(Passing arguments with ./gatling.sh)
JAVA_OPTS="-DuserCount=2 -DflowRepeatCount=3 -DdefinitionId=102168 -DtestServerUrl='https://someURL' -DenvAuthenticationHeaderFromPostman='Basic UWRZm9aGwsxFsB1V7RXK0OlB5cmZvcm1hbmNldGVzdDE='" ./gatling.sh
Gives this error,
GATLING_HOME is set to /opt/gatling-charts-highcharts-2.0.3 Error:
Could not find or load main class
UWRZm9aGwsxFsB1V7RXK0OlB5cmZvcm1hbmNldGVzdDE='
Here the problem is the space given in argument of -DenvAuthenticationHeaderFromPostman='Basic UWRZm9aGwsxFsB1V7RXK0OlB5cmZvcm1hbm='.
What is the solution?
The problem is that the $JAVA_OPTS variable is probably not surrounded by quotes. See this question: Passing a space-separated System Property via a shell script doesn't work
The gatling guys clearly forgot to do that.
I would file a bug and/or just edit gatling.sh.
Ideally though you might just want to consider seeing if Gatling takes a properties file or some other way to configure.

echo of var to file in SConscript

In an SConscript file I have a env variable BUILDID_STR
that contains a C string that I wish to output to a file.
bstr = env['BUILDID_STR']
print(bstr)
which when printed, print(bstr) correctly shows this:
//this file is automatically generated
static char* build_str="0|0.1.0|2014-05-29_16:16:51";
However, I can't get the var expanded/exported correctly, just the literal string is output instead of the above text:
cat src/log/src/version.c
env[BUILDID_STR]
Here's the pertinent part of my SConscript file
env.Command(target='#/src/log/src/version.c',
source=libSrcfiles,
action="echo env['BUILDID_STR'] > $TARGET")
env.SharedLibrary('log', [libSrcfiles, '#/src/log/src/version.c'])
I've also tried the code in a function and also passing to a shell script, all with the same result.
The reason I have .../version.c in the SharedLibrary is that my goal is to have the .c file generated only when on of the libSrcfiles is built, thereby version.c is compiled-in.
The "textfile" Tool offers two Builders Textfile() and Substfile() for cases like this. You probably want to use the first:
env = Environment(tools=['textfile'])
env['BUILDID_STR'] = 'A test'
env.Textfile('test.txt', ['$BUILDID_STR'])
As you have seen, the action is not expanding the env variable. In the action, you can refer to env variables with the $VAR syntax (just like referring to the $SOURCE and $TARGET variables provided by SCons):
env.Command(target='#/src/log/src/version.c',
source=libSrcfiles,
action="echo $BUILDID_STR > $TARGET")
This solution may not handle a BUILDID_STR containing multiple lines.
You may want to investigate a system that builds your source file from a template (instead of constructing the file contents entirely within a string). The Substfile Builder referenced in this previous question might be a good starting point -- you can provide a list of (key, value) pairs to be substituted in an input file. The Substfile Builder is built into recent versions of SCons.

Resources