if(!reqAdSize.equalsIgnoreCase(hm.get("ad_size")))
{
Failure = true;
FailureMessage = "Ad Sizes Doesn't Match";
}
if(!reqCur.equalsIgnoreCase(resCur))
{
Failure = true;
FailureMessage = "Request & Responce Currency are NOT same";
}
if(!reqID.equalsIgnoreCase(resID))
{
Failure = true;
FailureMessage = "Request & Responce Id is NOT same";
}
In my jeMter here is my BeanShell Assertion Code all if conditions are satisfying.
In result it will showing the last FailureMessage. I need to stop the execution of code if first condition is true and it will not execute further.
I tried to use the System.exit(0);andexit();. But jMeter GUI is automatically closing.
What is the method to stop the execution at current line in BeanShell.
Add return keyword wherever you want to stop the execution of BeanShell code.
You have SampleResult pre-defined variable in the Beanshell Assertion, it is a shorthand for org.apache.jmeter.samplers.SampleResult class. Take a look into following methods:
SampleResult.setStopTest()
SampleResult.setStopTestNow()
Something like:
if (!reqAdSize.equalsIgnoreCase(hm.get("ad_size"))) {
Failure = true;
FailureMessage = "Ad Sizes Doesn't Match";
SampleResult.setStopTest(true);
}
Guide on Beanshell scripting in JMeter context: How to Use BeanShell: JMeter's Favorite Built-in Component
Related
I have a setup where I execute jython scripts from a Java application. The java application feed the jython script with variables, coming from the command line, so that a user can write the following code in it's jython script:
print("Hello, %s" % foobar)
And will call the java program with this:
$ java -jar myengine.jar script.py --foobar=baz
Hello, baz
My java application parse the command-line, and create a variable of that name with the given value to give to the jython scripting environment to consume. All is well so far.
My issue is that when the user does not provide the foobar command-line parameter, I'd like to be able to easily provide a fallback in my script. For now, the user needs to write that sort of code to handle the situation where the foobar parameter is missing from the command-line:
try: foobar
except NameError: foobar = "some default value"
But this is cumbersome, especially if the number of parameters is growing. Is there a way to handle that better from the script user point of view?
I was thinking of catching the jython NameError in the Java code, initializing the variable causing the exception to a default value if the variable causing the exception "looks like" a parameter (adding a naming convention is OK), and restarting where the exception occurred. Alternatively, I can require the script user to write code such as this:
parameter(foobar, "some default value")
Or something equivalent.
Well, this is one ugly workaround I found so far. Be careful, as this will call the script in loop many times, and is O(n^2).
private void callScriptLoop(String scriptfile) {
PythonInterpreter pi = new PythonInterpreter();
pi.set("env", someEnv);
int nloop = 0;
boolean shouldRestart;
do {
shouldRestart = false;
try {
pi.execfile(scriptfile);
} catch (Throwable e) {
if (e instanceof PyException) {
PyException pe = (PyException) e;
String typ = pe.type.toString();
String val = pe.value.toString();
Matcher m = Pattern.compile("^name '(.*)' is not defined")
.matcher(val);
if (typ.equals("<type 'exceptions.NameError'>")
&& m.find()) {
String varname = m.group(1);
pi.set(varname, Py.None);
System.out.println(
"Initializing missing parameter '"
+ varname + "' to default value (None).");
shouldRestart = true;
nloop++;
if (nloop > 100)
throw new RuntimeException(
"NameError handler infinite loop detected: bailing-out.");
}
}
if (!shouldRestart)
throw e;
}
} while (shouldRestart);
}
I want to write a gradle task that runs me this small application:
import java.lang.IllegalArgumentException
class TestApp{
companion object {
#JvmStatic
fun main(args:Array<String>){
val a = try{
args[0].toInt()
}catch (e:Exception) {throw argException}
val b = try{
args[1].toInt()
}catch (e:Exception) {throw argException}
print("$a + $b = ")
val answer = readLine()!!.toInt()
println(if(a+b == answer)"CORRECT" else "WRONG!")
}
private val argException:IllegalArgumentException by lazy { IllegalArgumentException("expecting two integers as args") }
}
}
If I run the application with, say, Intellij, the app will pause at the readline() and expect user input.
However, if I add a gradle task for it
task runTestApp(type:JavaExec){
main = "${javaMainTestApp}"
classpath = sourceSets.main.runtimeClasspath
}
and run, say,
gradle runTestApp --args="2 4"
Then I get
2 + 4 = Exception in thread "main" kotlin.KotlinNullPointerException
at [...].app.TestApp$Companion.main(TestApp.kt:19)
at [...].app.TestApp.main(TestApp.kt)
Why is that? And more importantly, how do I get the execution to wait for user input?
UPDATE
Thanks #tim_yates:
adding standardInput = System.in makes the app accept user input
but results in an output like:
3 + 5 =
<<==========---> 80% EXECUTING [20s]
> :runTestApp
8
where 8 is the user input.
consequently, when the app finishes, the output reads
3 + 5 =
<<======CORRECT> 80% EXECUTING [22s]
Maybe you could use the application plugin and do a gradle run. Or you could use the distribution plugin and run the script.
I have a groovy script that loops through each test step, in each test case, in each test suite in the project. Each test case in the project has two custom properties assigned it is, Test_Case_Response_Time and Test_Case_Response_Size. I am trying to get it so that when it loops through each test case it log.info those two custom property for each test case.
Groovy Script:
//Loop thru the suites, followed by cases in each suite
suites.each
{ suite ->
//For each test SUITE perform the following action
//------------------------------------------------
def tSuite = project.getTestSuiteByName(suite)
tSuite.testCaseList.each
{ kase ->
//For each test CASE perform the following action
//-----------------------------------------------
kase.testStepList.each
{
//For each test step perform the following action
//-----------------------------------------------
if(it.metaClass.hasProperty(it,'assertionStatus')){
def assertions = it.getAssertionList()
assertions.each
{ assertion ->
if(it.assertionStatus == AssertionStatus.VALID)
{
PassedTestCase += 1
}
else if(it.assertionStatus == AssertionStatus.FAILED)
{
FailedTestCase += 1
}
}
}
//-----------------------------------------------
}
log.info testRunner.testCase["Test_Case_00: Setup"].getPropertyValue("Test_Case_Response_Time")
log.info testRunner.testCase.testSuite.getTestCaseByName("Test_Case_00: Setup").getPropertyValue("Test_Case_Response_Time")
//-----------------------------------------------
}
//-----------------------------------------------
}
I have tried the following with no success:
log.info testRunner.testCase[kase.name].getPropertyValue("Test_Case_Response_Time")
log.info testRunner.testCase.testSuite.getTestCaseByName(kase.name).getPropertyValue("Test_Case_Response_Time")
The first line give me the following
groovy.lang.MissingPropertyException: No such property: Test_Case_00:
Setup for class: com.eviware.soapui.impl.wsdl.testcase.WsdlTestCase
error at line: 37
and the second line gives me the following error:
java.lang.NullPointerException: Cannot invoke method
getPropertyValue() on null object error at line:37
The below statement is not correct as testCase[kase.name] gives you property of testcase and not testcase itself
System is trying to search a property with the name"Test_Case_00: Setup" and hence giving error "No such property: Test_Case_00: Setup"
log.info testRunner.testCase[kase.name].getPropertyValue("Test_Case_Response_Time")
I was able to run the below code
log.info testRunner.testCase.testSuite.getTestCaseByName(kase.name).getPropertyValue("Test_Case_Response_Time")
In your actual code you have used the below line instead of kase.name
getTestCaseByName("**Test_Case_00: Setup**")
Looks like, testcase name is wrong, please copy the exact name and paste and it will work.
Below code worked for me. Its your code only.
def tSuite = testRunner.testCase.testSuite.project.getTestSuiteByName("TestSuite") // modified to run
tSuite.testCaseList.each
{ kase ->
//For each test CASE perform the following action
//-----------------------------------------------
kase.testStepList.each
{
//For each test step perform the following action
//-----------------------------------------------
}
//-----------------------------------------------
// log.info kase.name
// log.info testRunner.testCase[kase.name].getPropertyValue("Test_Case_Response_Time") <-- wrong syntax
log.info testRunner.testCase.testSuite.getTestCaseByName(kase.name).getPropertyValue("Test_Case_Response_Time")
}
I believe I was looking in the wrong Test Suite. Using the following i was able to get it to find the correct properties:
testRunner.testCase.testSuite.project.getTestSuiteByName(suite).getTestCaseByName(kase.name).getPropertyValue("Test_Case_Response_Time")
Forgive the beginner question. I have a Webdriver script (Java, JUnit4) which tests a number of very similar webpages for common elements.
Some of the webpages have dates on them, some do not. For those that do not, I want to the test result to print "The current date is not displayed" and then continue to run the remainder of the #Test's.
Code snippet I am using:
#Test
public void checkIfTodaysDateDisplayed(){
WebElement currentDate = driver.findElement(By.cssSelector(".currentDate"));
assertEquals("The current date is not displayed", currentDate.isDisplayed());
}
Currently, on those pages that don't contain the date, a NoSuchElementException is thrown and Jenkins test result simply shows: "Unable to locate element: {"method":"css selector","selector":".currentDate"}"
What I want to achieve is:
a) print a meaningful message
b) do not halt the test as there are 5 or 6 other #Test's I need to run for each page.
What is the best/optimal solution to fix the assertion and handle this? A Try/Catch block?
EDIT: updated code:
WebElement currentDate = null;
try {
currentDate = driver.findElement(By.cssSelector(".currentDate"));
} catch (NoSuchElementException e) {
Assert.fail("The current date is not displayed! " + e.getMessage());
}
Assert.assertNotNull(currentDate);
Assert.assertEquals("The current date is displayed", currentDate.isDisplayed());
If page DOES have a date, the console prints:
java.lang.AssertionError:
Expected :The current date is displayed
Actual :true
If page DOESN'T have a date, the console prints:
org.openqa.selenium.NoSuchElementException: Unable to locate element:
{"method":"css selector","selector":".currentDate"}
To A)
Yes, one solution is to wrap your first line into a try-catch block. Be sure to catch only the Exception you expect and no other as your test will contain holes then.
Your code might look like this:
#Test
public void checkIfTodaysDateDisplayed(){
WebElement currentDate = null;
try {
currentDate = driver.findElement(By.cssSelector(".currentDate"));
}
catch (NoSuchElementException e) {
Assert.fail("Web page is not properly set up! " + e.getMessage());
}
Assert.assertNotNull(currentDate);
Assert.assertEquals("The current date is not displayed", currentDate.isDisplayed());
}
You may want to append additional information to your Asserts, such as the exception stacktrace or whatever is needed for you to debug.
To B)
Write singular tests for each case you want to have tested. If you put everything in one monolithic test it'll be more difficult to chase the exact position where your test failed. Write tests that do not depend on each other.
It looks like your Assert on currentDate.IsDisplayed() is comparing a bool (true) against a String
Is it possible to listen to CTRL+C when a groovy script is run from the command line ?
I have a script that creates some files. If interrupted I want to delete them from disk and then terminate.
Possible?
UPDATE 1:
Derived from #tim_yates answer:
def withInteruptionListener = { Closure cloj, Closure onInterrupt ->
def thread = { onInterrupt?.call() } as Thread
Runtime.runtime.addShutdownHook (thread)
cloj();
Runtime.runtime.removeShutdownHook (thread)
}
withInteruptionListener ({
println "Do this"
sleep(3000)
throw new java.lang.RuntimeException("Just to see that this is also taken care of")
}, {
println "Interupted! Clean up!"
})
The following should work:
CLEANUP_REQUIRED = true
Runtime.runtime.addShutdownHook {
println "Shutting down..."
if( CLEANUP_REQUIRED ) {
println "Cleaning up..."
}
}
(1..10).each {
sleep( 1000 )
}
CLEANUP_REQUIRED = false
As you can see, (as #DaveNewton points out), "Shutting down..." will be printed when the user presses CTRL-C, or the process finishes normally, so you'd need some method of detecting whether cleanup is required
Update
For the sake of curiosity, here is how you would do it using the unsupported sun.misc classes:
import sun.misc.Signal
import sun.misc.SignalHandler
def oldHandler
oldHandler = Signal.handle( new Signal("INT"), [ handle:{ sig ->
println "Caught SIGINT"
if( oldHandler ) oldHandler.handle( sig )
} ] as SignalHandler );
(1..10).each {
sleep( 1000 )
}
But obviously, those classes can't be recommended as they might disappear/change/move
I am not much into groovy script but i have a link that have some examples and says catching ctrl+c.....hope that helps http://pleac.sourceforge.net/pleac_groovy/processmanagementetc.html