How to Duplicate file using JMeter - jmeter

I am trying to duplicate a file using JMeter,
The scenario:
Loading a JSON file. For example, {"name":"John","age":"$age_place"}
Modify one property - age_place from 1 to 20
Save each modified iteration into a separate file
I have tried to do that with Simple Data Writer but it didn't work.

You have JSR223 Elements as Sampler or Pre processor which you can add powerful script,
The easiest is to replace age_place with your value, for example if saved in variable age_place:
f = new FileOutputStream("c:\\temp\\template.json", false);
p = new PrintStream(f);
this.interpreter.setOut(p);
print("{\"name\":\"John\",\"age\":\"age_place\"}".replaceAll("age_place", vars.get("age_place")));
f.close();

If you need to generate 20 files with different age you can do it using any of JSR223 Test Elements. Example Groovy code would look like:
def json = new groovy.json.JsonSlurper().parseText("{\"name\":\"John\",\"age\":\"\"}")
def builder = new groovy.json.JsonBuilder(json)
1.upto(20, {
builder.content.age= "${it}"
def writer = new File('file' + "${it}" + ".json").newWriter()
writer << builder.toPrettyString()
writer.close()
})
Once you execute your test it will create the following files in the "bin" folder of your JMeter installation:
file1.json - with the age of 1
file2.json - with the age of 2
...
file20.json - with the age of 20
References:
Groovy For Loop Examples
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

Related

Can we retrieve a file name in run time in jmeter and pass the name in other place

During the jmeter run,a log file is created and stored in a location with timestamp. i want to refer the same filename in the next postprocessor. how do we achieve it
You want to get the name of the .jtl results file in JMeter script?
Something like:
?
If yes, you can use a suitable JSR223 Test Element and the following Groovy code:
import org.apache.jmeter.reporters.ResultCollector
import org.apache.jorphan.collections.SearchByClass
def engine = engine = ctx.getEngine()
def test = engine.getClass().getDeclaredField('test')
test.setAccessible(true)
def testPlanTree = test.get(engine)
SearchByClass<ResultCollector> resultCollectorSearch = new SearchByClass<>(ResultCollector.class)
testPlanTree.traverse(resultCollectorSearch)
ResultCollector resultCollector = resultCollectorSearch.getSearchResults().first()
println('Current .jtl file name: ' + resultCollector.getFilename())

my access token is getting overwritten every time

import java.io.*;
import com.opencsv.CSVWriter;
File f= new File("C:\\Users\\Web\\Desktop\\Tokenss.csv");
FileWriter fw= new FileWriter(f);
BufferedWriter bw= new BufferedWriter(fw);
//var rc = prev.getResponseCode();
//ctx.getPreviousResult().getResponseHeaders();
String tok = vars.get("Token");
bw.write(tok);
bw.newLine();
bw.close();
fw.close();
Question: how to write access_token in CSV always in a new row? It overwrites my access token every time.
You're overwriting the whole file each time you call your script, in order to write new line at the end of the file you need change this:
FileWriter fw= new FileWriter(f);
to this:
FileWriter fw= new FileWriter(f, true);
where second argument is the switch for the "append" mode
In general since JMeter 3.1 you should be using JSR223 Test Elements and Groovy language so consider migrating to Groovy on next available opportunity. You will either be able to re-use your existing code or simplify it to something like:
new File('C:\\Users\\Web\\Desktop\\Tokenss.csv') << vars.get('Token') << System.getProperty('line.separator')
See Apache Groovy - Why and How You Should Use It article for more information on Groovy scripting in JMeter

Writing Variables using Beanshell Sampler in JMeter into a txt/csv file

My requirement is to write two values using 2 Beanshell Samplers used in different steps, in a single line and separated by a comma
But the second variable is written on a new line
I have two different Beanshell Samplers at different steps.
First one captures Variable 1 and writes it in a file
Second one captures Variable 2 and writes it in the file
First Code:
String path= FileServer.getFileServer().getBaseDir() + "//P_IssuePolicy.txt";
SubmissionNum= vars.get("CP_SubmissionNumber");
EMailID= vars.get("P_emailID");
f = new FileOutputStream(path, true);
p = new PrintStream(f);
this.interpreter.setOut(p);
p.println(EMailID+","+SubmissionNum);
f.close();
Second Code:
String path= FileServer.getFileServer().getBaseDir() + "//P_IssuePolicy.txt";
Policynumber= vars.get("CP_Policynumber");
f = new FileOutputStream(path, true);
p = new PrintStream(f);
this.interpreter.setOut(p);
p.println(","+Policynumber);
f.close();
Expected Result:
abc#email.com,12345601,12345602
Actual Result:
abc#email.com,12345601
,12345602
Instead of println which adds new line use print
p.print(EMailID+","+SubmissionNum);
String path= FileServer.getFileServer().getBaseDir() + "//P_IssuePolicy.txt";
SubmissionNum= vars.get("CP_SubmissionNumber");
EMailID= vars.get("P_emailID");
Policynumber= vars.get("CP_Policynumber");
f = new FileOutputStream(path, true);
p = new PrintStream(f);
this.interpreter.setOut(p);
p.println(EMailID+","+SubmissionNum+","+Policynumber);
f.close();
Give it a try with above.
First of all, are you aware of Sample Variables property and Flexible File Writer? If you run your script with multiple virtual users most probably you will suffer from a form of a race condition when multiple threads will be simultaneously writing into the same file resulting in garbage data
Since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for any scripting tasks, the reasons are in:
Groovy is compatible with modern Java versions and with Beanshell you're stuck at Java 5 language level
Groovy has much better performance than Beanshell
Groovy has a lot of enhancements making your life easier
For example your code can be shortened as:
First:
def file = new File(org.apache.jmeter.services.FileServer.getFileServer().getBaseDir() + "//P_IssuePolicy.txt")
file << vars.get("P_emailID") << "," << vars.get("CP_SubmissionNumber") << ","
Second:
def file = new File(org.apache.jmeter.services.FileServer.getFileServer().getBaseDir() + "//P_IssuePolicy.txt")
file << vars.get("CP_Policynumber") << System.getProperty("line.separator")

Unable to write extracted data from regular expression to excel file

I am new to performance testing, I am trying to write extracted data from boundary extractor to an excel file using BeanShell scripting. The outcome is that my CSV file is getting updated but data is not showing in the file. instead of data is mentioned as "Null" in the CSV file
Extracted data from boundary extractor is :-Chris Evans,Robert Downey Jr.,Chris Hemsworth,Brie Larson,Josh Brolin,Scarlett Johansson,Benedict Wong,Paul Rudd,Mark Ruffalo,Karen Gillan,Jeremy Renner,Jon Favreau,Gwyneth Paltrow,Evangeline Lilly,Michelle Pfeiffer,Elizabeth Olsen,Chadwick Boseman,Sebastian Stan,Tom Holland,Pom Klementieff,Tilda Swinton,Benedict Cumberbatch,Katherine Langford,Dave Bautista,Letitia Wright,Frank Grillo,Tessa Thompson,Don Cheadle,Ty Simpkins,Terry Notary,Danai Gurira,Bradley Cooper
USed below code:
CastCrew = vars.get("CastCrew");
f = new FileOutputStream("C:\Users\Vikas Dhiman\Downloads\apache-jmeter-4.0\apache-jmeter-4.0\bin\examples\argList1.csv");
p = new PrintStream(f);
this.interpreter.setOut(p);
print("Cast and Crew are," + CastCrew);
f.close();
Use two backslash in beanshell in directory path as shown below. I am sharing the config sample for your requirement:-
Hope this helps.

Jmeter write out to a file

I have a selenium script which is running in Jmeter using JUnit sampler. My selenium program has a few system.pritnln statements which I see it in console when Jmeter runs, how can I write them to a file?
I would go for Sample Variables instead so you could get Username included into .jtl results file, add the code like:
In JUnit:
JUnitSampler sampler = new JUnitSampler();
JMeterVariables vars = sampler.getThreadContext().getVariables();
vars.put("username", your_username_variable);
vars.put("elapsed", your_total_time_variable);
sampler.getThreadContext().setVariables(vars);
In JMeter's user.properties file:
sample_variables=username,elapsed
If you want a separate file - just replace all your System.out.println(""); with:
FileUtils.writeStringToFile(new File("/path/to/file"),"what you need to write", true);
See How to Use JUnit With JMeter article for more information on running your JUnit tests with JMeter
If you do not want to create a separate file and you can use log file then below statement will do to write in a log file
log.info(" TEXT ");
If you want to create a separate file, then
import org.apache.jmeter.services.FileServer;
f = new FileOutputStream("c:/output/result.txt", true);
p = new PrintStream(f);
p.println(" Hello World "); // update here what you want to write
p.close();
f.close();
1: Add JSR223 Sampler to yoour test plan
2: Write below code:
FileWriter fstream = new FileWriter("D:\\subid.csv",true); //Create New file with name "subid"
BufferedWriter out = new BufferedWriter(fstream);
out.write(vars.get("variable1"));//write value of variable 1
out.write(",");
out.write(vars.get("variable2"));//write value of variable 2
out.write(System.getProperty("line.separator"));//insert new line
out.close();
fstream.close();

Resources