So right now I have my http request under a while controller and I have a user defined variable Failure set to true. I would like jmeter to keep trying this request until it succeeded (without returned 500).
My while loop condition is:
${__javaScript(${Failure})}
I also tried ${Failure} as while condition but getting the same result.
And I have a JSR223 Assertion after the result tree as following:
if (ResponseCode.equals("500") == true) {
vars.put("Failure", true)
}
else {
vars.put("Failure", false)
}
When I ran this, I got into infinite loop even my request succeeded. It seems the Failure value was never updated. Any suggestion on this would be appreciated.
This is because you're trying to add a Boolean object into a function which expects a String. In order to be able to store a Boolean value into a JMeter Variable you need to use vars.putObject() function instead like:
vars.putObject("Failure", true)
or surround true with quotation marks so it would look like a String to Groovy:
vars.put("Failure", "true");
Amend your JSR223 Assertion code to look like:
if (ResponseCode.equals("500")) {
vars.put("Failure", "true")
}
else {
vars.put("Failure", "false")
}
Amend your While Controller condition to be just ${Failure}. Using JavaScript is a form of a performance anti-pattern, if you need to perform some scripting - go for Groovy. In particular your case you can just use ${Failure} variable as the condition given it can be either true or false
I finally got it working. In my JSR233 assertion, I updated it to:
if (prev.getResponseCode().equals("500")) {
vars.put("Failure", "true")
}
else {
vars.put("Failure", "false")
}
And it works now.
Related
I want to use assertion for this checkbox. It depends on duration. If it's checked duration = forever, if not = a month.
cy.wrap(cy.get('span.ant-checkbox').should('have.class','ant-checkbox-checked')).then((a) => {
if a == true {
cy.log('Forever')
}
})
A few thoughts:
You don't need to cy.wrap() your entire statement. cy.wrap() would primarily be used to wrap a JQuery yielded from cy.get() or a similar command, and insert it back into the Cypress command chain.
Your assertion that the element has a certain class will fail and stop your test before even getting to the .then() part of the command if the element does not have the ant-checkbox-checked class.
Instead, if we get the element, we can use JQuery functions (in this case, .hasClass())to determine if it has the class we want.
cy.get('span.ant-checkbox').then(($el) => {
// cy.get yields a JQuery<HTMLElement>
if ($el.hasClass('ant-checkbox-checked')) {
cy.log('Forever');
} else {
cy.log('A month');
}
});
So, I have created a Controller within which I have a POST endpoint like so:
#PostMapping("/foo/{some-field}")
public CompletableFuture<ResponseEntity> foo() {
//Do some operations...
...
if(doesNotExist({some-field})) {
return CompletableFuture.completedFuture(ResponseEntity.notFound().build());
}
return CompletableFuture.completedFuture(ResponseEntity.ok().build());
}
Now I would expect that if doesNotExist({some-field}) == true, I'd be prompted with a NOT_FOUND status.
I however end up with a OK status every time around.
Are my expectations wrong in regards to how the ResponseEntity is returned?
Any suggestions how to get the NOT_FOUND status if doesNotExist({some-field}) == true would be much appreciated.
Edit/Update
From the comments I assume my initial question was a little to light, so let me explain when I see this failing, as it seems that my assumption of what the ResponseEntity.HttpStatus would be is correct.
I have made small adjustments to the code block above.
The situation where I receive an unexpected status is when I try to test the NOT_FOUND situation through Spring Cloud Contracts.
An example of the contract looks as follows:
Contract.make {
request {
method 'POST'
url "/foo/SomeNoneExistingField"
body("{}")
headers {
contentType applicationJson()
}
}
response {
status HttpStatus.NOT_FOUND.value()
}
}
So the {some-field} in this contract is set to a field which ensure that doesNotExist({some-field}) == true. I see it end up in this block if I am debugging my code as well.
Nonetheless, the Spring Cloud Contract test status that the response.status == OK i.o. NOT_FOUND.
Might I be using Spring Cloud Contracts incorrectly if my assumption on the HttpStatus returned from a CompletableFuture is correct?
Any help/advice is (again) much appreciated.
There is nothing complex here and it should work as expected.
It is happening may be because of {some-state} is not true so every time it is going to else block.
Ensure that {some-state} evaluation returns true and compiler enters into if block.
if({some-state}) {
return CompletableFuture.completedFuture(ResponseEntity.notFound().build());
}
Ok, I figured out the issue I was experiencing.
Credits to #Marcin Grzejszczak for putting me on the right track in regards to configuration.
What I was missing from my contracts to be able to handle async results, like a CompletableFuture, was that I needed to add async() to my result.
Thus, a contract like so:
Contract.make {
request {
method 'POST'
url "/foo/SomeNoneExistingField"
body("{}")
headers {
contentType applicationJson()
}
}
response {
status HttpStatus.NOT_FOUND.value()
async() // <---- This was it!
}
}
Did the trick.
I have created 2 BeanShell functions myFoo1 and myFoo2.
The first func should be executed with certain condition and the second function in different condition
The trouble is that in my JSR223Post Processor or BeanPost Processor
String code = ctx.getPreviousResult().getResponseCode();
if (code.contains("200") && (vars.get("abc1") != "Howdee")) {
${__BeanShell(myFoo1("print this"))}
}
else {
${__BeanShell(myFoo2("print this"))}
}
The problem is the beanShell functins myFoo1 and myFoo2 get called before the if/else evaluation.
In another words myFoo1 and myFoo2 they both get called one after another and if/else never has any effect, so it looks like Bean function calls are executed before any evaluation.
How do I get around that?
Remove ${__BeanShell( from the script and call it directly as myFoo2("print this):
String code = ctx.getPreviousResult().getResponseCode();
if (code.contains("200") && (vars.get("abc1") != "Howdee")) {
myFoo1("print this);
}
else {
myFoo2("print this);
}
I am trying to learn Scala using Spring framework. I have to implement conditional get logic in my code. I understand it could be done using etag or Last-Modified option.
Here is my piece of code:
var lastModifiedTime: Long = _;
#RequestMapping(value= Array("/users/{id}"),method=Array(RequestMethod.GET),headers = Array("Content-Type=application/json"))
#ResponseBody
def getmeth(request: User_details, web: WebRequest): User_details = {
if (web.checkNotModified(lastModifiedTime)) {
return null
} else {
lastModifiedTime = System.currentTimeMillis()
}
Could you please help me to fix this code?
Disclaimer: I don't know Spring Web.
But according to the documentation fist of all you should take action if request is modified so you should remove bang (!) from condition. Also lastModifiedTime should be computed from the outside of the getmeth method.
Notice that unlike in Java if statement is an expression and it returns value so you shouldn't use return statement.
As it was said in comment conditional code can be easy and safely done using Scala's Option. In Scala you should always avoid null, as it is hard to distinguish it from incorrect behavior of your code, and it is very easy to forget or don't know that it is required to write logic dealing with it - you must always read the javadoc (assuming it exists and it is up to date). When you use Option type compiler will force you to deal with "nullability".
def getmeth(request: User_details, web: WebRequest): Option[User_details] =
if (web.checkNotModified(lastModifiedTime)) {
None
} else {
val userDetails = yourLogic()
Some(userDetails)
}
Then you can perform an action when option is a Some instance. To do that you can use map method.
getmeth(req, web) map { userDetails =>
userDetails.getName
}
EDIT: #optimus Now when you gave wider scope I see that your method signature is forced by framework and yon can't wrap your value with Option. I think that your problem may be that you update lastModifiedTime on every request so it seems reasonable to me that checkNotModified is always false. I think that you should use that feature only on requests that not always update checkNotModified to current time. It becomes pointless otherwise.
Update lastModifiedTime once your resource has become outdated.
#ResponseStatus(HttpStatus.OK)
#RequestMapping(value = Array("/users/{user_id}"),method = Array(RequestMethod.GET))
def getUser(#PathVariable("user_id") user_id: String,
#Context req : Request ): Any = {
val u = hm.get(user_id).asInstanceOf[User]
val tag = u.hashCode().asInstanceOf[EntityTag]
if (req.getMethod().equals("GET")) {
val rb : Response.ResponseBuilder = req.evaluatePreconditions(tag);
if (rb != null)
{
rb
}
else
{
// val u = hm.get(user_id).asInstanceOf[User]
u
}
}
I am doing Selenium testing for the first time. On the homepage, I call some AJAX, and i want Selenium to wait for the element to load finish. I not sure it works, but i just type selenium and the waitForCondition are able to choose.
I not matter what I choose it always return "false". I do not now if the waitForCondition even work?
How can I test if it works?
And what am I doing wrong in this codes?
selenium.waitForCondition("//input[#name='Report'", "3000");
selenium.waitForCondition("//*[#id='MyTable']", "3000");
selenium.waitForCondition("css=.someClass2", "3000");
If I implement by own class - it return "true"
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
isElementPresent(By.xpath("//*[#id='MyTable']")) - return "true"
waitForCondition is for Javascript calls only, not for waiting for elements to load.
What you have in isElementPresent is fine. I would combine it with explicit waits to be a bit more accurate about when an element is actually loaded and present on the screen:
http://seleniumhq.org/docs/04_webdriver_advanced.html
C#
You can do it like this:
First of all you can set timeout value for the condition.
Then you can use the condition.
var Wait = new WebDriverWait(GlobalDriver, TimeSpan.FromMinutes(1));
Wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.XPath("xPath"))));
OR
Wait.Until(driver => driver.FindElement(By.XPath("xPath")));
Thats all.
You can do it like this :
selenium.waitForCondition("selenium.isElementPresent(\"//input[#name='Report']\")", "30000");
This will wait for the element to be loaded till 30 seconds.
Hope this works for you
new WebDriverWait(driver, 30).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
JavascriptExecutor js = (JavascriptExecutor) driver;
return (Boolean) js.executeScript("return jQuery.active == 0");
}
});
This will check if the jQuery library has any active AJAX requests for 30 seconds.
Aaran referred you to the correct documentation for Selenium WebDriver waits.
You can see that they also write about ExpectedConditions class. This contains several helpful implementation of ExpectedCondition classes, such at the "is element present one", which is ExpectedConditions.presenceOfElementLocated .
Here is an example of using it:
WebDriver driver = new ChromeDriver();
driver.get("http://www.degraeve.com/reference/simple-ajax-example.php");
driver.findElement(By.name("word")).sendKeys("bird is the word");;
driver.findElement(By.cssSelector("input[type='button']")).click();
WebDriverWait driverWait = new WebDriverWait(driver, 10);
WebElement dynamicElement = driverWait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#result p")));
System.out.println(dynamicElement.getText());
If you find it too verbose, why won't you just refactor it and extract a function which will accept the element locator and the webdriver, and returns you the element?
DriverWait.until() accepting an ExpectedCondition instance is like a way of passing a predicate function, just doing it through a class, or in the documentation example an anonymous nested class, since under Java you can't send a function.
The ExpectedCondition "function" you pass also returns a value, which can be useful in case you're waiting for a condition on some element (or some other value from the WebDriver), so returning it will save you an extra call.
Try this once:
await().atMost(10, SECONDS).until(() -> driver.findElements(By.id("elementId")).size() >1);