enter image description here
1: https://i.stack.imgur.com/sRx3n.jpg**strong text**##
I am trying to write the Java program to get the input something like this for multiple rows and process it by creating concurrency thread group which can generate number of threads from tstfeedback function and complete the execution.enter image description here
Here is an example of creating an empty Test Plan with the Throughput Shaping Timer configured like at your first image via JMeter API:
import kg.apc.jmeter.JMeterPluginsUtils;
import kg.apc.jmeter.timers.VariableThroughputTimer;
import kg.apc.jmeter.timers.VariableThroughputTimerGui;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.config.gui.ArgumentsPanel;
import org.apache.jmeter.control.gui.TestPlanGui;
import org.apache.jmeter.gui.util.PowerTableModel;
import org.apache.jmeter.save.SaveService;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.TestPlan;
import org.apache.jmeter.testelement.property.CollectionProperty;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.HashTree;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ThroughputShapingTImer {
public static void main(String[] args) throws IOException {
File jmeterHome = new File("c:/apps/jmeter");
String slash = System.getProperty("file.separator");
File jmeterProperties = new File(jmeterHome.getPath() + slash + "bin" + slash + "jmeter.properties");
//JMeter initialization (properties, log levels, locale, etc)
JMeterUtils.setJMeterHome(jmeterHome.getPath());
JMeterUtils.loadJMeterProperties(jmeterProperties.getPath());
JMeterUtils.initLocale();
// JMeter Test Plan, basically JOrphan HashTree
HashTree testPlanTree = new HashTree();
//Throughput Shaping Timer
VariableThroughputTimer throughputShapingTimer = new VariableThroughputTimer();
throughputShapingTimer.setName("Timer");
PowerTableModel load_profile = new PowerTableModel(new String[]{"Start RPS", "End RPS", "Duration, sec"}, new Class[]{String.class, String.class, String.class});
load_profile.addRow(new Integer[]{0, 10, 20});
load_profile.addRow(new Integer[]{10, 10, 20});
CollectionProperty data = JMeterPluginsUtils.tableModelRowsToCollectionProperty(load_profile, VariableThroughputTimer.DATA_PROPERTY);
throughputShapingTimer.setData(data);
throughputShapingTimer.setProperty(TestElement.TEST_CLASS, VariableThroughputTimer.class.getName());
throughputShapingTimer.setProperty(TestElement.GUI_CLASS, VariableThroughputTimerGui.class.getName());
// Test Plan
TestPlan testPlan = new TestPlan("Create JMeter Script From Java Code");
testPlan.setProperty(TestElement.TEST_CLASS, TestPlan.class.getName());
testPlan.setProperty(TestElement.GUI_CLASS, TestPlanGui.class.getName());
testPlan.setUserDefinedVariables((Arguments) new ArgumentsPanel().createTestElement());
// Construct Test Plan from previously initialized elements
testPlanTree.add(testPlan);
HashTree threadGroupHashTree = testPlanTree.add(testPlan);
threadGroupHashTree.add(throughputShapingTimer);
// save generated test plan to JMeter's .jmx file format
SaveService.saveTree(testPlanTree, Files.newOutputStream(Paths.get("example.jmx")));
}
}
The resulting .jmx test plan will be stored in the current folder.
More information: Five Ways To Launch a JMeter Test without Using the JMeter GUI
Related
I know how to use two runner classes to rerun failed scenarios, but I want this feature only for one test.
Let's say that I have 100 scenarios and I only want to rerun scenario 40 when it fails, but if any other scenaria fails, I don't want it to rerun. Is there a way to implement this for one test in particular?
To see how to rerun all failed scenarios, check out this question:
How to rerun the failed scenarios using Cucumber?
You'll have to write custom code for this. Fortunately this is relatively easy with the JUnit Platform API (JUnit 5).
https://github.com/cucumber/cucumber-jvm/tree/main/cucumber-junit-platform-engine#rerunning-failed-scenarios
package com.example;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.engine.discovery.UniqueIdSelector;
import org.junit.platform.launcher.Launcher;
import org.junit.platform.launcher.LauncherDiscoveryRequest;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherFactory;
import org.junit.platform.launcher.listeners.SummaryGeneratingListener;
import org.junit.platform.launcher.listeners.TestExecutionSummary.Failure;
import java.util.List;
import java.util.stream.Collectors;
import static org.junit.platform.engine.discovery.DiscoverySelectors.selectDirectory;
import static org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder.request;
public class RunCucumber {
public static void main(String[] args) {
LauncherDiscoveryRequest request = request()
.selectors(
selectDirectory("path/to/features")
)
.build();
Launcher launcher = LauncherFactory.create();
SummaryGeneratingListener listener = new SummaryGeneratingListener();
launcher.registerTestExecutionListeners(listener);
launcher.execute(request);
TestExecutionSummary summary = listener.getSummary();
// Do something with summary
List<UniqueIdSelector> failures = summary.getFailures().stream()
.map(Failure::getTestIdentifier)
.filter(TestIdentifier::isTest)
// Filter more to select scenarios to rerun
.map(TestIdentifier::getUniqueId)
.map(DiscoverySelectors::selectUniqueId)
.collect(Collectors.toList());
LauncherDiscoveryRequest rerunRequest = request()
.selectors(failures)
.build();
launcher.execute(rerunRequest);
TestExecutionSummary rerunSummary = listener.getSummary();
// Do something with rerunSummary
}
}
I'm interested in Tekton these days.
However there are some issue when I implement Task with java fabric8.tekton apis.
There exist api which is adding steps in spec in units of container(withContainer) in TaskBuilder class.
However I got error message in rune time like below,
Can I get some advices?
Tekton version - v0.10.1
I used packages like below:
io.fabric8:kubernetes-client:4.7.1
io.fabric8:tekton-client:4.7.1
Here is my complete test code.
package com.example.tekton;
import java.util.ArrayList;
import java.util.List;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.ContainerBuilder;
import io.fabric8.kubernetes.client.BaseClient;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.ConfigBuilder;
import io.fabric8.tekton.client.TektonClient;
import io.fabric8.tekton.client.DefaultTektonClient;
import io.fabric8.tekton.client.handlers.TaskHandler;
import io.fabric8.tekton.client.handlers.TaskRunHandler;
import io.fabric8.tekton.pipeline.v1alpha1.ArrayOrString;
import io.fabric8.tekton.pipeline.v1alpha1.Task;
import io.fabric8.tekton.pipeline.v1alpha1.TaskBuilder;
import io.fabric8.tekton.pipeline.v1alpha1.TaskRun;
import io.fabric8.tekton.pipeline.v1alpha1.TaskRunBuilder;
import io.fabric8.tekton.pipeline.v1alpha1.TaskRefBuilder;
public class DefaultKubernetesTest {
public Task getTask() {
Container con = new ContainerBuilder()
.withNewImage("ubuntu")
.withNewName("echo-hello-world")
.addNewCommand("echo")
.addNewArg("hello jinwon world")
.build();
Task task = new TaskBuilder()
.withApiVersion("tekton.dev/v1alpha1")
.withKind("Task")
.withNewMetadata()
.withName("echo-hello-world-test")
.endMetadata()
.withNewSpec()
.addNewStep()
.withContainer(con)
.endStep()
.endSpec()
.build();
return task;
}
public TaskRun getTaskRun() {
TaskRun taskRun = new TaskRunBuilder()
.withNewMetadata()
.withName("taskrun")
.endMetadata()
.withNewSpec()
.withTaskRef(new TaskRefBuilder().withName("echo-hello-world-test").withApiVersion("tekton.dev/v1alpha1").withKind("Task").build())
.endSpec().build();
return taskRun;
}
public static void main(String[] args) {
ConfigBuilder config = new ConfigBuilder();
DefaultKubernetesTest kubeTest = new DefaultKubernetesTest();
String username = "testUser";
String password = "testPwd";
config = config.withMasterUrl("https://192.168.6.236:6443");
config = config.withUsername(username);
config = config.withPassword(password);
Config kubeConfig = config.build();
try (DefaultTektonClient test = new DefaultTektonClient(kubeConfig)) {
Task task = kubeTest.getTask();
TaskRun taskRun = kubeTest.getTaskRun();
test.tasks().inNamespace("test").create(task);
test.taskRuns().inNamespace("test").create(taskRun);
test.close();
}
}
}
Tekton ships with an admission controller, which validates the CRD specs before allowing them into the cluster. Because the project is still in alpha, its moving quite fast. Fabric8 may be templating out K8s objects against a different spec from what has been installed on your cluster. You should be able to validate the spec version used in Fabric8 and remove all the Tekton objects in your cluster and re-apply them at a specific version.
I am trying to run a JMeter MS SQL database test plan from Java code through my Spring Boot app but it's showing the following errors:
I have loaded the plugin manager in JMeter and put that in jmeter/lib/ext folder and installed all required plugins.
Java code to run JMeter test case:
package com.example.demofin;
import java.io.File;
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.reporters.ResultCollector;
import org.apache.jmeter.reporters.Summariser;
import org.apache.jmeter.save.SaveService;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.HashTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import com.example.demofin.config.Properties;
#Component
public class Demofin implements CommandLineRunner {
#Autowired
private Properties properties;
private Summariser result;
#Override
public void run(String... args) throws Exception {
for(String i : args)
System.out.println(i);
// String j = properties.getPropertyByKey("JMETER_HOME");
String j="D:\\apache-jmeter-4.0";
// System.out.println(j);
//System.out.println("Jmeter home path: " + properties.getPropertyByKey("JMETER_HOME"));
StandardJMeterEngine jmeter = new StandardJMeterEngine();
// // Initialize Properties, logging, locale, etc.
JMeterUtils.setJMeterHome(j);
JMeterUtils.loadJMeterProperties(j+"/bin/jmeter.properties");
//
// // you can comment this line out to see extra log messages of i.e. DEBUG level
JMeterUtils.initLogging();
JMeterUtils.initLocale();
// Initialize JMeter SaveService
SaveService.loadProperties();
// Load existing .jmx Test Plan
HashTree testPlanTree = SaveService.loadTree(new File("D:\\apache-jmeter-4.0\\" + "bin\\JDBC Connection Configuration.jmx"));
Summariser summer = null;
String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");
if (summariserName.length() > 0) {
summer = new Summariser(summariserName);
}
ResultCollector logger = new ResultCollector(summer);
testPlanTree.add(testPlanTree.getArray()[0], logger);
// Run JMeter Test
jmeter.configure(testPlanTree);
jmeter.run();
result = summer;
}
}
Usually, we compile java code to jar and push it to jmeter/lib/ext and use it in Jmeter.
If you attempt to using Jmeter in java, I suggest downloading source code of JMeter and merge to your project.
This is a Jmeter POST request in the form of a java code. I run this code to get no errors but I also get no response because my method of acting the request body data appears to be wrong.
import java.io.FileOutputStream;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.config.gui.ArgumentsPanel;
import org.apache.jmeter.control.LoopController;
import org.apache.jmeter.control.gui.LoopControlPanel;
import org.apache.jmeter.control.gui.TestPlanGui;
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.protocol.http.control.Header;
import org.apache.jmeter.protocol.http.control.HeaderManager;
import org.apache.jmeter.protocol.http.control.gui.HttpTestSampleGui;
import org.apache.jmeter.protocol.http.gui.HeaderPanel;
//import org.apache.jmeter.protocol.http.sampler.HTTPSampler;
import org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy;
import org.apache.jmeter.reporters.ResultCollector;
import org.apache.jmeter.reporters.Summariser;
//import org.apache.jmeter.samplers.SampleEvent;
//import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.SampleSaveConfiguration;
import org.apache.jmeter.save.SaveService;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.TestPlan;
import org.apache.jmeter.threads.ThreadGroup;
import org.apache.jmeter.threads.gui.ThreadGroupGui;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.HashTree;
import org.apache.jmeter.protocol.http.util.HTTPArgument;
public class PostRequest {
public static void main(String[] argv) throws Exception {
//JMeter Engine
StandardJMeterEngine jmeter = new StandardJMeterEngine();
//JMeter initialization (properties, log levels, locale, etc)
JMeterUtils.setJMeterHome("/C:/Users/xxx");
JMeterUtils.loadJMeterProperties("/C:/xxx");
JMeterUtils.initLogging();
JMeterUtils.initLocale();
//JMeter Test Plan, basically JOrphan HashTree
HashTree testPlanTree = new HashTree();
//HTTP Sampler
HTTPSamplerProxy httpSampler = new HTTPSamplerProxy();
httpSampler.setDomain("100.100.100.100");
httpSampler.setPort(1111);
httpSampler.setPath("/");
httpSampler.setMethod("POST");
httpSampler.addNonEncodedArgument("","{data:{ \"email\" :
\"xx#gmail.com\",there are more values in the body"}]}","" );
httpSampler.setPostBodyRaw(true);
httpSampler.setFollowRedirects(true);
httpSampler.setAutoRedirects(false);
httpSampler.setUseKeepAlive(true);
httpSampler.setDoMultipartPost(false);
httpSampler.setProperty(TestElement.TEST_CLASS,
HTTPSamplerProxy.class.getName());
httpSampler.setProperty(TestElement.GUI_CLASS,
HttpTestSampleGui.class.getName());
//Header Manager
HeaderManager headerManager = new HeaderManager();
headerManager.setName(JMeterUtils.getResString("header_manager_title"));
headerManager.add(new Header("abcs", "asdasd"));
headerManager.add(new Header("dsferdg", "ertret"));
headerManager.setProperty(TestElement.TEST_CLASS,
HeaderManager.class.getName());
headerManager.setProperty(TestElement.GUI_CLASS,
HeaderPanel.class.getName());
httpSampler.setHeaderManager(headerManager);
//Loop Controller
LoopController loopController = new LoopController();
loopController.setLoops(1);
loopController.setFirst(true);
loopController.addTestElement(httpSampler);
loopController.setProperty(TestElement.TEST_CLASS,
LoopController.class.getName());
loopController.setProperty(TestElement.GUI_CLASS,
LoopControlPanel.class.getName());
loopController.initialize();
//Thread Group
ThreadGroup threadGroup = new ThreadGroup();
threadGroup.setName("Sample Thread Group");
threadGroup.setNumThreads(1);
threadGroup.setRampUp(1);
threadGroup.setSamplerController(loopController);
threadGroup.setProperty(TestElement.TEST_CLASS,
ThreadGroup.class.getName());
threadGroup.setProperty(TestElement.GUI_CLASS,
ThreadGroupGui.class.getName());
//Test Plan
TestPlan testPlan = new TestPlan("Create JMeter Script From Java Code");
testPlan.setProperty(TestElement.TEST_CLASS, TestPlan.class.getName());
testPlan.setProperty(TestElement.GUI_CLASS,
TestPlanGui.class.getName());
testPlan.setUserDefinedVariables((Arguments) new
ArgumentsPanel().createTestElement());
HashTree threadGroupHashTree = testPlanTree.add(testPlan, threadGroup);
threadGroupHashTree.add(httpSampler,headerManager);
//Construct Test Plan from previously initialized elements
testPlanTree.add("testPlan", testPlan);
testPlanTree.add("loopController", loopController);
testPlanTree.add("threadGroup", threadGroup);
testPlanTree.add("httpSampler", httpSampler);
testPlanTree.add("headerManager", headerManager);
Summariser summer = null;
String summariserName = JMeterUtils.getPropDefault("summariser.name",
"summary");
if (summariserName.length() > 0) {
summer = new Summariser(summariserName);
}
ResultCollector resultcoll = new ResultCollector();
testPlanTree.add("resultcoll", resultcoll);
resultcoll.setFilename("C:/Users/xxx");
SampleSaveConfiguration saveConfiguration = new
SampleSaveConfiguration();
saveConfiguration.setAsXml(true);
saveConfiguration.setCode(true);
saveConfiguration.setLatency(true);
saveConfiguration.setTime(true);
saveConfiguration.setTimestamp(true);
resultcoll.setSaveConfig(saveConfiguration);
//Store execution results into a .jtl file, we can save file as csv also
String reportFile = "C:/Users/xxx.jtl";
String csvFile = "C:/Users/xxx.csv";
ResultCollector logger = new ResultCollector(summer);
logger.setFilename(reportFile);
ResultCollector csvlogger = new ResultCollector(summer);
csvlogger.setFilename(csvFile);
testPlanTree.add(testPlanTree.getArray()[0], logger);
testPlanTree.add(testPlanTree.getArray()[0], csvlogger);
//save generated test plan to JMeter's .jmx file format
SaveService.saveTree(threadGroupHashTree, new
FileOutputStream("C:\\Users\read.jmx"));
// Run Test Plan
jmeter.configure(testPlanTree);
jmeter.run();
/*System.out.println("Test completed. See " + JMeterHome + slash +
"report.jtl file for results");
System.out.println("JMeter .jmx script is available at " + jmeterHome +
slash + "jmeter_api_sample.jmx");*/
System.exit(0);
}
}
I have used this code to configure the jmeter POST request and to add the body data but the request body appears to be null when I check the response.
Maybe you should be adding arguments to httpSampler, and not to the sampler, something like:
HTTPSamplerProxy httpSampler = new HTTPSamplerProxy();
httpSampler.setDomain(xx);
httpSampler.setPort(xx);
httpSampler.setPath("xx");
httpSampler.setMethod("xx");
httpSampler.addNonEncodedArgument("body", body, "");
If you are building JMeter test from Java code using JMeter API check out Five Ways To Launch a JMeter Test without Using the JMeter GUI and jmeter-from-code repository for some snippets you could re-use.
I am working on a test automation framework using testNG, Selenium and Jenkins. The code is working fine, it reads one or more csv files and uses that as test data. I run the test from Jenkins.
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
public class runTest {
private WebDriver myDriver = null;
#BeforeTest
public void openBrowser(){
System.out.println("This test automation framework is created by --- for ---");
//Set browser
//System.setProperty("webdriver.chrome.driver", "C://Temp//chromedriver.exe");
//System.setProperty("webdriver.ie.driver", "C://Temp//IEDriverServer.exe");
//Instantiate new WebDriver object with browser of choice
myDriver = new FirefoxDriver();
//myDriver = new InternetExplorerDriver();
//myDriver = new ChromeDriver();
myDriver.get("http://localhost/tests/");
}
#Test (dataProvider="provideData")
public void csvTest(String stepNr, String timeWaitMil, String waitForElement, String clickOnCssNameXpathLink,
String valueInTextBox, String backspaceText, String assertReturnTrueFalse,
String assertBy, String getUrl,
String deleteCookie, String snapshot, String specialSnapshot){
// Click on a something based on css, name xpath or link
if (!"-".equals(clickOnCssNameXpathLink)){
myDriver.findElement(By.name(clickOnCssNameXpathLink)).click();
}
// Enter value in textbox
if (!"-".equals(valueInTextBox)){
myDriver.findElement(By.name(clickOnCssNameXpathLink)).sendKeys(valueInTextBox);
}
// Delete cookies
if (!"-".equals(deleteCookie)){
myDriver.manage().deleteAllCookies();
}
// Make snapshot of whole page
if (snapshot.equalsIgnoreCase("true")){
// take the screenshot of full page
File scrFile = ((TakesScreenshot)myDriver).getScreenshotAs(OutputType.FILE);
// prepare date to use in filename
Date d = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss");
// Save screenshot
try {
FileUtils.copyFile(scrFile, new File("c:\\Temp\\screenshots\\full_page_" +dateFormat.format(d)+ ".png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Could not make screenshot");
}
}
}
#DataProvider
public Iterator<Object []> provideData() throws InterruptedException, IOException
{
//Array with multiple csv's
String csvFiles[] = {"C:/Users/---/Desktop/JES2.0/testingSelenium/testNG/data.csv", "C:/Users/---/Desktop/JES2.0/testingSelenium/testNG/data2.csv"};
List<Object []> testCases = new ArrayList<>();
//loop through csv files
for(String csvFile:csvFiles){
String[] data= null;
//read csv file
BufferedReader br = new BufferedReader(new FileReader(csvFile));
//Skip first line in the csv file, because that only contains the column names
String line = br.readLine();
//loop through csv and split parameters by comma sign ,
while ((line = br.readLine()) != null) {
// use comma as separator
data= line.split(",");
testCases.add(data);
}//end of while loop
}// end of for loop
return testCases.iterator();
}
#AfterTest
public void closeBrowser(){
//close browser
myDriver.quit();
}
}
As you can see, the browser, the url and the CSV files are hardcoded. I want to be able to pass these as parameters. What is the best way to do this? Is it possible to pass them through Jenkins?
I am thinking of building a dashboard where I can specify what tests (csv files) to run using which browser.
This is the Jenkins batch command I am running
java -cp C:\Users\---\Desktop\JES2.0\testingSelenium\testNG\libs\selenium-server-standalone-2.43.1.jar;C:\Users\---\Desktop\JES2.0\testingSelenium\testNG\bin org.testng.TestNG testng.xml
Jenkins have a built-in parameters handling, which is quite flexible in it's own way. But in this case, since you want to pass a filename as parameter, you can easily combine that functionality with a Filesystem List Parameter, which can build the list based on a regexp that will parse list of files.
If you use Maven or Ant, you can embed that parameter within your build process, in a form similar to this:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<environment>${env.PARAM}</environment>
</systemPropertyVariables>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
With this you can read the parameter that was passed on to Maven - in Jenkins using it's internal caller, and on command line with:
mvn install -Denv.PARAM=VALUE
So it should work either way...