JMeter - Pause (and resume) execution on demand - jmeter

I'm executing JMeter task for a few hours on a server,
I want to be able to pause execution for a few seconds/minutes and resume when server finish restarted
Is there a way to signal JMeter to pause and resume its execution?
I saw similar question, but it doesn't fit my issue

As of current JMeter version 5.3 there is no way to accomplish your "issue" with built-in JMeter components.
The easiest solution I can think if is: given you're restarting your server it should be not available for some time and when it becomes available - it should respond with a HTML page containing some text.
So you can "wait" for the server to be up and running as follows:
Add JSR223 Sampler to the appropriate place in the Test Plan where you need to "wait' for the server to be up and running
Put the following code into "Script" area:
import org.apache.http.client.config.RequestConfig
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.HttpClientBuilder
import org.apache.http.util.EntityUtils
SampleResult.setIgnore()
def retry = true
def requestConfig = RequestConfig.custom().setConnectTimeout(1000).setSocketTimeout(1000).build()
def httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build()
while (retry) {
def httpGet = new HttpGet('http://jmeter.apache.org')
try {
def entity = httpClient.execute(httpGet).getEntity()
if (EntityUtils.toString(entity).contains('Apache JMeter')) {
log.info('Application is up, proceeding')
retry = false
} else {
log.info('Application is still down, waiting for 5 seconds before retry')
sleep(5000)
}
}
catch (Throwable ex) {
sleep(5000)
ex.printStackTrace()
}
}
That's it, the code will try to open the web page and look for some text in it, if the page doesn't open and/or text is not present - it will wait for 5 seconds and retry
More information:
HttpClient Quick Start
Apache Groovy - Why and How You Should Use It

Related

Wait time issue in JMeter Webdriver sampler

I am using JMeter Webdriver sampler for the application UI response time measurement. I am facing issue with the wait function. For example the login page loads between 10 to 120 secs. So I have the following code for the login page in Webdriver sampler for the page load check.
var ui=JavaImporter(org.openqa.selenium.support.ui)
var wait=new support_ui.WebDriverWait(WDS.browser,120)
wait.until(ui.ExpectedConditions.visibilityOfElementLocated(pkg.By.className('logout-btn-hover')))
The issue is even after the page load completely, JMeter is still waiting to perform the next action. This waiting time will reduce if I reduce the 120 secs.But sometimes the application will take 120 secs to load also so I need to keep 120 secs.
I am writing the time to a log file once the sampler completes its action. Because of the wait time issue I am not able to calculate time properly.
There are at least 2 errors in your script, it should look something like:
var ui=JavaImporter(org.openqa.selenium.support.ui)
var wait=new ui.WebDriverWait(WDS.browser,120)
wait.until(ui.ExpectedConditions.visibilityOfElementLocated(org.openqa.selenium.By.className('logout-btn-hover')))
Check out jmeter.log file for any suspicious entries, in particular for something like:
ERROR c.g.j.p.w.s.WebDriverSampler: Expected condition failed: waiting for visibility of element located by By.className: logout-btn-hover (tried for 120 second(s) with 500 milliseconds interval)
Double check your CSS selector
Consider refactoring your code to look for the logout button(?) in a loop with verbose logging for each step. Sample code:
var pkg = JavaImporter(org.openqa.selenium)
WDS.sampleResult.sampleStart()
WDS.browser.get('http://example.com')
var start = new Date().getTime()
var attempt = 1
while (new Date().getTime() - start < 5000) {
try {
var logout = WDS.browser.findElement(pkg.By.className('logout-btn-hover'))
WDS.log.info('Element found')
break
}
catch (err) {
WDS.log.info('Attempt # ' + attempt + ', Element not found')
java.lang.Thread.sleep(1000)
attempt++
}
}
WDS.sampleResult.sampleEnd()
Example output when the element is not found:
Example output when the element is found:
Check out The WebDriver Sampler: Your Top 10 Questions Answered article for more information on using WebDriver sampler in JMeter scripts.

Jmeter clear resultFile for each run

I have a test plan, where i have two thread groups, first thread group will run and will log the result into a file, the logged file will be the input to the second thread group.
Now, for doing this in thread group one i added BeanShell PostProcessor script as follows, but it works as follows
open jmeter and run the test plan (log file "testing.csv" will be created as fresh)
For first time "isHeaderWritten" property is false.
No without closing and reopening the jmeter, run the script again. i expect the log file "testing.csv" must be truncated and add the values freshly. But what acually happening is "testing.csv" file is appended with the new values.
Now, close the jmeter and open again, this time log file "testing.csv" will be truncated and fresh new values are added.
How to clear the file and re-write the records for each run (without closing the jemeter)
import org.apache.jmeter.util.JMeterUtils;
threadName=ctx.getThread().getThreadName();
log.info("threadName: "+threadName);
isHeaderWritten = JMeterUtils.getPropDefault("isHeaderWritten","false");
fileName="C:\\response\\testing.csv";
log.info("isHeaderWritten: "+isHeaderWritten);
if(isHeaderWritten == "true"){
f = new FileOutputStream(fileName, true);
fileHeader = "requestStatus,cNumber,pId,id,token";
}else{
log.error("isHeaderWritten:"+isHeaderWritten);
f = new FileOutputStream(fileName, false);
fileHeader = "requestStatus,cNumber,pId,id,token";
}
p = new PrintStream(f);
this.interpreter.setOut(p);
if(isHeaderWritten == "false"){
print(fileHeader);
JMeterUtils.setProperty("isHeaderWritten", "true");
}
log.info("Test results will be written to file "+fileName);
cNumber=vars.get("cNumber");
log.info("cNumber"+cNumber);
pId = vars.get("pId");
log.info("pId"+pId);
pmId = vars.get("pmId");
log.info("pmId"+pmId);
tTxt = vars.get("tTxt");
log.info("tTxt"+tTxt);
responseCode=prev.getResponseCode();
log.info("responseCode of "+requestString+ " is "+responseCode);
requestStatus = "Success";
if(!"201".equals(responseCode)){
requestStatus = "Failure"+","+cNumber+","+pId+","+pmId+","+tTxt;
}
result = requestStatus;
if("Success".equals(requestStatus)){
responseData=new String(data);
log.info("responseData of "+requestString+ " is "+responseData);
requestString=requestStatus+","+cNumber+","+pId+","+pmId+","+tTxt;
result = requestString;
log.info("result"+result);
}
log.debug(result);
print(result);
f.close();
According to JMeter Documentation:
Properties are global to JMeter, so can be used to communicate between threads and thread groups
Properties are not the same as variables. Variables are local to a thread; properties are common to all threads
So once you execute this line:
JMeterUtils.setProperty("isHeaderWritten", "true");
the property isHeaderWritten will become true and will remain true until you restart JMeter.
The easiest solution would be adding a tearDown Thread Group to your test plan (this Thread Group is being executed after any other thread group(s)) and add a JSR223 Sampler with the following code:
SampleResult.setIgnore();
org.apache.jmeter.util.JMeterUtils.setProperty("isHeaderWritten", "false");
Since JMeter 3.1 users are encouraged to switch to JSR223 Test Elements and Groovy language for any form of scripting mainly because Groovy performance is much better than Beanshell so consider migrating to JSR223 PostProcessor and Groovy language on next available opportunity

dynamics crm 365 plugin delay between execution pipeline stages

Our plugin is running slow on the "Retrieve" message, so I placed a few timestamps in the code to determine where the bottle neck is. I realized there is a 7 second delay which happens intermittently between the end of the pre-operation stage and the start of the post operation stage.
END PRE - 3/22/2018 11:57:55 AM
POST STAGE START - 3/22/2018 11:58:02 AM
protected virtual void RetrievePreOperation()
{
var message = $"END PRE - {DateTime.Now}";
PluginExecutionContext.SharedVariables.Add("message", message);
}
protected virtual void RetrievePostOperation()
{
// Stop recursive calls
if (PluginExecutionContext.Depth > 1) return;
if (PluginExecutionContext.MessageName.ToLower() != Retrieve ||
!PluginExecutionContext.InputParameters.Contains("Target") ||
PluginExecutionContext.Stage != (int)PipelineStages.PostOperation)
return;
var entity = (Entity)PluginExecutionContext.OutputParameters["BusinessEntity"];
string message = PluginExecutionContext.SharedVariables["message"].ToString();
message += $"POST STAGE START - {DateTime.Now}";
}
Any ideas on how to minimize this delay would be appreciated. Thanks
If your plugin step is registered on Asynchronous execution mode, this delay totally depends on Async service load & pipeline of waiting calls/jobs. You can switch it to Synchronous.
If its registered in Synchronous mode but still delay is there intermittently, it depends on many things like which entity, query & complex logic if any.

http_listener cpprestsdk how to handle multiple POST requests

I have developed a client server application with casablanca cpprestskd.
Every 5 minutes a client send informations from his task manager (processes,cpu usage etc) to server via POST method.
The project should be able to manage about 100 clients.
Every time that server receives a POST request he opens an output file stream ("uploaded.txt") ,extract some initial infos from client (login,password),manage this infos, save all infos in a file with the same name of client (for example: client1.txt, client2.txt) in append mode and finally reply to client with a status code.
This is basically my POST handle code from server side:
void Server::handle_post(http_request request)
{
auto fileBuffer =
std::make_shared<Concurrency::streams::basic_ostream<uint8_t>>();
try
{
auto stream = concurrency::streams::fstream::open_ostream(
U("uploaded.txt"),
std::ios_base::out | std::ios_base::binary).then([request, fileBuffer](pplx::task<Concurrency::streams::basic_ostream<unsigned char>> Previous_task)
{
*fileBuffer = Previous_task.get();
try
{
request.body().read_to_end(fileBuffer->streambuf()).get();
}
catch (const exception&)
{
wcout << L"<exception>" << std::endl;
//return pplx::task_from_result();
}
//Previous_task.get().close();
}).then([=](pplx::task<void> Previous_task)
{
fileBuffer->close();
//Previous_task.get();
}).then([](task<void> previousTask)
{
// This continuation is run because it is value-based.
try
{
// The call to task::get rethrows the exception.
previousTask.get();
}
catch (const exception& e)
{
wcout << e.what() << endl;
}
});
//stream.get().close();
}
catch (const exception& e)
{
wcout << e.what() << endl;
}
ManageClient();
request.reply(status_codes::OK, U("Hello, World!")).then([](pplx::task<void> t) { handle_error(t); });
return;
}
Basically it works but if i try to send info from due clients at the same time sometimes it works sometimes it doen't work.
Obviously the problem if when i open "uploaded.txt" stream file.
Questions:
1)Is CASABLANCA http_listener real multitasking?how many task it's able to handle?
2)I didn't found in documentation ax example similar to mine,the only one who is approaching to mine is "Casalence120" Project but he uses Concurrency::Reader_writer_lock class (it seems a mutex method).
What can i do in order to manage multiple POST?
3)Is it possible to read some client infos before starting to open uploaded.txt?
I could open an output file stream directly with the name of the client.
4)If i lock access via mutex on uploaded.txt file, Server become sequential and i think this is not a good way to use cpprestsdk.
I'm still approaching cpprestskd so any suggestions would be helpful.
Yes, the REST sdk processes every request on a different thread
I confirm there are not many examples using the listener.
The official sample using the listener can be found here:
https://github.com/Microsoft/cpprestsdk/blob/master/Release/samples/CasaLens/casalens.cpp
I see you are working with VS. I would strongly suggest to move to VC++2015 or better VC++2017 because the most recent compiler supports co-routines.
Using co_await dramatically simplify the readability of the code.
Substantially every time you 'co_await' a function, the compiler will refactor the code in a "continuation" avoiding the penalty to freeze the threads executing the function itself. This way, you get rid of the ".then" statements.
The file problem is a different story than the REST sdk. Accessing the file system concurrently is something that you should test in a separate project. You can probably cache the first read and share the content with the other threads instead of accessing the disk every time.

JMeter BeanShell Assertion Custom Output Messages

I was asked to enhance my assertions to provide some better log messaging within my JMeter test plan that tests APIs using basic CRUD methodology. The test plan is being checked into Jenkins and being run automatically. When something goes wrong, the level of messaging is not adequate for the support team.
Within the first thread group, I have an HTTP Request to create a new record within the database based on the payload being passed in. Under this request, I have a BeanShell Assertion as follows:
if (ResponseCode.equals("200") == true)
{
SampleResult.setResponseOK();
}
I'm now trying to enhance this to account for 409, and 500 responses.
I've attempted the, but it does not seem to work:
if (ResponseCode.equals("200") == true)
{
SampleResult.setResponseOK();
}
else if (ResponseCode.equals("409") == true)
{
FailureMessage = "Creation of a new CAE record failed: Attempting to create a duplicate record.";
}
else (ResponseCode.equals("500") == true)
{
FailureMessage = "Creation of a new CAE record failed: Unable to connect to server";
}
Additionally, if the ResponseCode is not 200, then I need to drop out of the entire thread group and go to the next thread group.
I've read several questions on this site, as well as How to Use BeanShell: JMeter's Favorite Built-in Component and How to Use JMeter Assertions in Three Easy Steps, but I'm still confused. Not being a developer and still new to JMeter, I'm in need of guidance.
Any and all help is much appreciated.
Selecting 'Stop Thread' in the Thread Group would help you to stop the thread group in case of any error - assuming you have other thread groups to execute consecutively. if not, the test will stop.
In the beanshell assetion include
else if (ResponseCode.equals("409") == true)
{
Failure = true;
FailureMessage = "Creation of a new CAE record failed: Attempting to create a duplicate record.";
}

Resources