How to execute JMeter test case from Java code - eclipse

How do I run a JMeter test case from Java code?
I have followed the example Here from Blazemeter.com
My code is as follows:
public class BasicSampler {
public static void main(String[] argv) throws Exception {
// JMeter Engine
StandardJMeterEngine jmeter = new StandardJMeterEngine();
// Initialize Properties, logging, locale, etc.
JMeterUtils.loadJMeterProperties("/home/stone/Workbench/automated-testing/apache-jmeter-2.11/bin/jmeter.properties");
JMeterUtils.setJMeterHome("/home/stone/Workbench/automated-testing/apache-jmeter-2.11");
JMeterUtils.initLogging();// you can comment this line out to see extra log messages of i.e. DEBUG level
JMeterUtils.initLocale();
// Initialize JMeter SaveService
SaveService.loadProperties();
// Load existing .jmx Test Plan
FileInputStream in = new FileInputStream("/home/stone/Workbench/automated-testing/apache-jmeter-2.11/bin/examples/CSVSample.jmx");
HashTree testPlanTree = SaveService.loadTree(in);
in.close();
// Run JMeter Test
jmeter.configure(testPlanTree);
jmeter.run();
}
}
but I keep getting the following messages in the console and my test never executes.
INFO 2014-09-23 12:04:40.492 [jmeter.e] (): Listeners will be started after enabling running version
INFO 2014-09-23 12:04:40.511 [jmeter.e] (): To revert to the earlier behaviour, define jmeterengine.startlistenerslater=false
I have also tried uncommented jmeterengine.startlistenerslater=false from jmeter.properties file

How do you know that your "test never executes"?
What is in jmeter.log file (it should be in the root of your project). Or alternatively comment JMeterUtils.initLogging() line to see the full output in STDOUT
Have you changed relative path CSVSample_user.csv in "Get user details" CSV Data Set Config as it may resolve into a different location as it recommended in Using CSV DATA SET CONFIG
Is CSVSample.jtl file generated anywhere (again it should be in the root of your project by default)? What is in it?
The code looks good and I'm pretty sure that the problem is with the path to CSVSample_user.csv file and you have something like java.io.FileNotFoundException in your log. Please double check that CSVSample.jmx file contains valid full path to CSVSample_user.csv.
UPDATE TO ANSWER QUESTIONS IN COMMENTS
jmeter.log file should be under your Eclipse workspace folder by default
Looking into CSVSample.jmx there is a View Resulst in Table listener which is configured to store results under ~/CSVSample.jtl
If you want to see summarizer messages and "classic" .jtl reporting add next few lines before jmeter.configure(testPlanTree); stanza
Summariser summer = null;
String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");
if (summariserName.length() > 0) {
summer = new Summariser(summariserName);
}
String logFile = "/path/to/jtl/results/file.jtl";
ResultCollector logger = new ResultCollector(summer);
logger.setFilename(logFile);
testPlanTree.add(testPlanTree.getArray()[0], logger);

Try using library - https://github.com/abstracta/jmeter-java-dsl.
It supports implementing JMeter test as java code.
Below example shows how to implement and execute test for REST API. Same approach could be applied to other type of tests as well.
#Test
public void testPerformance() throws IOException {
TestPlanStats stats = testPlan(
threadGroup(2, 10,
httpSampler("http://my.service")
.post("{\"name\": \"test\"}", Type.APPLICATION_JSON)
),
//this is just to log details of each request stats
jtlWriter("test" + Instant.now().toString().replace(":", "-") + ".jtl")
).run();
assertThat(stats.overall().elapsedTimePercentile99()).isLessThan(Duration.ofSeconds(5));
}

Related

Could not load file or assembly(dll file path+name) or one of its dependencies. An attempt was made to load a program with an incorrect format

When trying to perform-
Import-Module 'C:\\Program Files\\Nimble Storage\\bin\\Nimble.Powershell.dll'
through program, I am receiving below error:
Could not load file or assembly 'file:///C:\Program Files\Nimble
Storage\bin\Nimble.Powershell.dll' or one of its dependencies. An
attempt was made to load a program with an incorrect format.
The same works when ran directly from Powershell but in the above case, facing issue.
C# program used and have used statement:
Collection< PSObject > resultCollection = runspaceInvoke.Invoke("Import-Module 'C:\\Program Files\\Nimble Storage\\bin\\Nimble.Powershell.dll'", null, out errors);
EBGreen is right. Need to see your code bro. In absence of that, something like the following should work:
using System.Management.Automation;
using System.Management.Automation.Runspaces;
class foo {
static void Main(string[] args) {
InitialSessionState initial = InitialSessionState.CreateDefault();
initial.ImportPSModule(new string[] {"'C:\\Program Files\\Nimble Storage\\bin\\Nimble.Powershell.dll'"} );
...
}
}
Check out Creating an InitialSessionState for more information.

The driver executable does not exist: C:\geckodriver.exe issue in Eclipse IDE

Please help me with this issue that is recurring every time I run my code.
I have extracted Geckodriver files in C Drive but when I run my code, the error that comes up is 'Exception in thread "main" java.lang.IllegalStateException: The driver executable does not exist: C:\geckodriver.exe'.
My code is given below:
package Basics;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Browserinvocation {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();//FirefoxDriver class is used to implement methods present in Webdriver-Invocation of browser
driver.get("https://www.amazon.in/");// Get method to hit the url in browser
}
}
Error in console :
Exception in thread "main" java.lang.IllegalStateException: The driver
executable does not exist: C:\geckodriver.exe at
com.google.common.base.Preconditions.checkState(Preconditions.java:534)
at
org.openqa.selenium.remote.service.DriverService.checkExecutable(DriverService.java:136)
at
org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:131)
at
org.openqa.selenium.firefox.GeckoDriverService.access$100(GeckoDriverService.java:41)
at
org.openqa.selenium.firefox.GeckoDriverService$Builder.findDefaultExecutable(GeckoDriverService.java:141)
at
org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:339)
at
org.openqa.selenium.firefox.FirefoxDriver.toExecutor(FirefoxDriver.java:158)
at
org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:120)
at
org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:98)
at Basics.Browserinvocation.main(Browserinvocation.java:13)
Above exception occurs whenever Precondition does not find path of relevant driver mentioned in System.setProperty() method by any reason like below:
if path mentioned have different/wrong/single slashes.
Driver file itself is not present at mentioned location.
If path is mentioned in properties file or config file with double quotes.
Just check once before execution.
You should add the path to geckodriver.exe using / rather than \\. Change your line
System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
to the following
System.setProperty("webdriver.gecko.driver","C:/geckodriver.exe");
Your code is running at my side, might be you are not extracting the gecko driver.
Change the path and try it once, it should worked
Please let me know selenium jars version and your firefox browser version
System.setProperty("webdriver.gecko.driver", "C:/Users/sankalp.gupta/Desktop/JAVASEL/geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.get("https://www.amazon.in");
System.out.println(driver.getCurrentUrl());
driver.close();
System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
Here remove . in between gecko and driver
Just download geckodriver.exe and move it to drive C:

Can't load a jks file from classpath

I've created a JKS file with public and private RSA keys. When I load this file using external path (like c:/file.jks), the program executes like a charm. However, if I try load this same file from classpath, I got this exception:
java.io.IOException: Invalid keystore format
This is the code used to load the jks:
KeyStore keyStore = KeyStore.getInstance("JKS");
InputStream stream=this.getClass().getResourceAsStream("/lutum.jks") ;
keyStore.load(stream,passe);
the only difference is that I use FileInputStream with full path when loading externally.
What I'm doing wrong?
In general your solution should work, provisionally.
What are those provisions? Make sure that your resource folder is in your classpath. If you aren't sure, add it to the -cp flag passed to java when executing your program, or if you are using Eclipse or some other IDE, make sure it is listed as a member of the classpath for that project.
Next, check out this stackoverflow that relates to your question. While the way you are using the class's getResourceAsStream() method is valid (including the / at the start of the filename causes the class resource loader to defer to the ClassLoader's method) it is perhaps less confusing to use the ClassLoader directly. Another good example is found here.
So, first, check that your resources folder is explicitly part of the classpath. Second, prefer the following construction for finding the resource:
InputStream stream= this.class.getClassLoader().getResourceAsStream("lutum.jks");
Note the missing / from the filename. This is because the ClassLoader will automatically start searching at "project root", and the slash will likely just cause issues (if you deploy to JBoss or Tomcat, for instance, that will probably get interpreted by the classloader as an absolute file system path instead of a relative path).
I hope this helps. If not, comment me with more details on your project and I'll alter my answer accordingly.
I suspect that the two keystores are in fact not the same, and that the keystore on the classpath are somehow corrupt.
Try comparing the two keystores. Just read the files into a byte array with something like this:
public static byte[] streamToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream tmp = new ByteArrayOutputStream();
int b = is.read();
while (b > -1) {
tmp.write(b);
b = is.read();
}
tmp.flush();
return tmp.toByteArray();
}
And then compare them like this:
InputStream cpStream = this.getClass().getResourceAsStream("/lutum.jks");
InputStream fileStream = new FileInputStream("c:/file.jks");
byte[] cpBytes = streamToByteArray(cpStream);
byte[] fileBytes = streamToByteArray(fileStream);
if (Arrays.equals(cpBytes, fileBytes)) {
System.out.println("They are the same.");
} else {
System.out.println("They are NOT the same.");
// print the file content ...
}

Do I need to enable javascript for PhantomJS when using Selenium Webdriver?

I have a testsuite in NUnit running on both IE and Chrome webdrivers. But when I wanted to try headerless PhantomJS (Ghostdriver) I can't get it to excute the actions I want to perform.
Having issues with easy stuff like
[TestFixture]
class PhantomJSTest{
protected IWebDriver driver;
[SetUp]
public void Setup() {
driver = new PhantomJSDriver(#"..\..\..\..");
}
[Test]
public void PhantomTest() {
driver.Navigate().GoToUrl(adress);
driver.FindElement(selector).Click();
}
[TearDown]
public void Teardown() {
driver.Close();
driver.Quit();
}
}
When the click is performed something should be set in my db, so when going back to that page manually I should be able to see it. The NUnit test itself is set to succeeded, but the action never happens. This is especially apparent when trying to do something based on the earlier action. Any help would be appreciated! =)
I would recommend you following activities:
1) try to relaunch your selenium hub with node(-s) based on phantomJs.
2) try to use instead of
driver.Navigate().GoToUrl(adress);
this one:
driver.get(URL);
driver.findElement(selector).click();
3) also see phantomJs documentation to get all phantomJs capabilities:
GhostDriver extra Capabilities
phantomjs.page.settings.SETTING = VALUE - Configure page.settings on
PhantomJS internal page objects (windows in WebDriver context) . Reference
phantomjs.page.customHeaders.HEADER = VALUE - Add extra HTTP Headers
when loading a URL . Reference
PhantomJSDriver (Java-binding) Capabilities
phantomjs.binary.path - Specify path to PhantomJS executable to use
phantomjs.ghostdriver.path - Specify path to GhostDriver main/src.js
script to use; allows to use a different version of GhostDriver then
the one embed in PhantomJS
phantomjs.cli.args - Specify command line arguments to pass to the
PhantomJS executable
phantomjs.ghostdriver.cli.args - Specify command line argument to
pass to GhostDriver (works only in tandem with
phantomjs.ghostdriver.path)
More details one can get at GhostDriver page
Also look through phantomJs command line options . This info might be helpful for you as well.
Hope this helps you.

How to create NTEventlogAppender.dll as required for logging event in the eventlog using log4cplus

First, Let me thank for the log4cplus source code.
I am facing one issue as follows:
What I am trying to do?
I want to log the messages to event log on windows.
What did I do?
I could get the event logging enabled by in including following .h
#include <log4cplus/nteventlogappender.h>
And creating the appender as follows:
SharedAppenderPtr append_3(new NTEventLogAppender(LOG4CPLUS_TEXT("127.0.0.1"), LOG4CPLUS_TEXT("log"), LOG4CPLUS_TEXT("source")));
append_3->setName(LOG4CPLUS_TEXT("ToEventlog"));
Logger to_eventlog = Logger::getInstance(LOG4CPLUS_TEXT("to_eventlog"));
to_eventlog.addAppender(append_3);
to_eventlog.setLogLevel(log4cplus::ALL_LOG_LEVEL);
And logging as
Logger to_eventlog = Logger::getInstance(LOG4CPLUS_TEXT("to_eventlog"));
LOG4CPLUS_FATAL(to_eventlog, “Test Message.”);
When I log the message, I get following in the event log:
The description for Event ID 4096 from source source cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.
If the event originated on another computer, the display information had to be saved with the event.
The following information was included with the event:
Test Message.
the message resource is present but the message is not found in the string/message table
I tried to create a dll with name NTEventLogAppender.dll with string table resource and a string with id 4096 (as hardcoded in the nteventlogappender.cxx file in log4cplus) and compiled it with resource only dll (/NOENTRY) but I still keep getting above error.
I already tried question to log4cplus-devel#lists.sourceforge.net but did not get any answer yet.
Any help on how to create this dll would be greatly appreciated.
Thanks.
This is how I resolved this issue:
comipiled NTEventLogAppender.mc file using commands:
mc -U NTEventLogAppender.mc
rc -r NTEventLogAppender.rc
link -dll -noentry -out:NTEventLogAppender.dll NTEventLogAppender.res
where NTEventLogAppender.mc has following contents
MessageIdTypedef=DWORD
SeverityNames=(Success=0x0:STATUS_SEVERITY_SUCCESS
Informational=0x1:STATUS_SEVERITY_INFORMATIONAL
Warning=0x2:STATUS_SEVERITY_WARNING
Error=0x3:STATUS_SEVERITY_ERROR
)
FacilityNames=(System=0x0:FACILITY_SYSTEM
Runtime=0x2:FACILITY_RUNTIME
Stubs=0x3:FACILITY_STUBS
Io=0x4:FACILITY_IO_ERROR_CODE
)
LanguageNames=(English=0x409:MSG00409)
; // The following are message definitions.
MessageId=0x1000
SymbolicName=SVC_TEST
Language=English
A message for something.
.
; // A message file must end with a period on its own line
; // followed by a blank line.
copied the NTEventLogAppender.dll to c:\windows\system32
and ran the above mentioned test program and found that event log found the message resource correctly.
you need to register this dll by copying following in .reg file and running the same
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\log\source]
"EventMessageFile"="C:\\windows\\system32\\NTEventLogAppender.dll"
"CategoryMessageFile"="C:\\windows\\system32\\NTEventLogAppender.dll"
"TypesSupported"=dword:00000007
"CategoryCount"=dword:00000005