wait until angular 2+ has finished loading issue - java

I recently posted a question about an issue I have white testing an angular based application (ref: wait until Angular has finished loading issue )
Turns out that the check done was valid for angular 1.x apps, while our application runs on angular 6.x.
I've then found out that post: Detecting that Angular 2 is done running
which explains how to do a similar check but for angular 2+ apps. I've set up the check in a similar fashion to "Michal Filip" explained.
I've also tried to use the ngWebdriver solution proposed further down in the post.
Both suffers of the same problem: the check will always return true as in its done loading which isn't true.
tried to inverse the check, it didn't help (state never changed)
// Will check if Angular still has pending http_requests ongoing and wait if required
public void untilAngular2HasFinishedProcessing()
{
until(() ->
{
log.info("Waiting on angular 2+ to finish processing");
final boolean isReady = ((JavascriptExecutor) driver).executeAsyncScript(
"var callback = arguments[arguments.length - 1];" +
"if (document.readyState !== 'complete') {" +
" callback('document not ready');" +
"} else {" +
" try {" +
" var testabilities = window.getAllAngularTestabilities();" +
" var count = testabilities.length;" +
" var decrement = function() {" +
" count--;" +
" if (count === 0) {" +
" callback('complete');" +
" }" +
" };" +
" testabilities.forEach(function(testability) {" +
" testability.whenStable(decrement);" +
" });" +
" } catch (err) {" +
" callback(err.message);" +
" }" +
"}"
).toString().equals("complete");
log.info("Is angular 2+ ready? " + isReady);
return isReady;
}
);
}
// sample call would be
untilAngular2HasFinishedProcessing();
Excpected: the test would wait until Angular is done loading before returning true
Actual: Returns true from the start, which I know isn't the case.
Possible duplicate? No, because this is a problem question based on the implementation proposed in the linked question.

Here's the solution I ended up using:
public boolean untilAngular2HasFinishedProcessing()
{
until(() ->
{
log.info("Waiting on angular 2+ to finish processing");
final boolean isReady = (Boolean.valueOf(((JavascriptExecutor) driver)
.executeScript(
"try{" +
"return (window.getAllAngularTestabilities()[0]._ngZone.hasPendingMicrotasks == " +
"false && " +
"window.getAllAngularTestabilities()[0]._ngZone.hasPendingMacrotasks == false && " +
"window.getAllAngularTestabilities()[0]._ngZone._nesting == 0 &&" +
"window.getAllAngularTestabilities()[0]._ngZone.isStable == true)" +
"}" +
"catch(err) {" +
"if (err.message == ('window.getAllAngularTestabilities is not a function'))" +
"{" +
"return true" +
"}" +
"}")
.toString()));
log.info("Is Angular 2+ ready? " + isReady);
return isReady;
}
);
return true;
}
That worked on a consistent fashion so far.

Related

How to fill in empty double value in test DTO, Java, Spring

So I am testing the controller of my application and I stumbled upon a problem.
This is the Json I use in my testcode:
String bike = "{" +
" \"bikeNumber\" : \"E2\"," +
" \"brand\" : \"Gazelle\"," +
" \"frameNumber\" : \"HA1234568\"," +
" \"retailPrice\" : 1200," +
" \"basePrice\" : 20.0," +
" \"electric\" : true" +
"}";
I want to test when the user doesn't fill in one of the values, it throws an exception. In other words I want to test the #NotNull, #NotBlank annotations.
I have done this for bikeNumber and frameNumber, these are string types and I can leave them open. The problem I get if I leave the basePrice open and run my test, I get an error saying:
java.lang.AssertionError: No value at JSON path "$.basePrice"
I know that it's a null value because I haven't filled it in, but that is part of the plan. So my question is, how do I leave a long, double or int value empty without getting a test error.
My full code block is here:
#Test
void whenPostRequestNoBasePrice_thenBadRequestResponse() throws Exception {
String bike = "{" +
" \"bikeNumber\" : \"E1\"," +
" \"brand\" : \"Gazelle\"," +
" \"frameNumber\" : \"HA1234568\"," +
" \"retailPrice\" : 1200," +
" \"basePrice\" : \"\" " +
" \"electric\" : true" +
"}";
mockMvc.perform(MockMvcRequestBuilders.post("/createbike")
.content(bike)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.basePrice", Is.is( "Base price is mandatory.")))
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)).andReturn().getResponse().getContentAsString();
}
I tried multiple things, also with and without the comma: "basePrice" : "" ," +
Also I can't seem to find this anywhere on stackoverflow.

Java Selenium with Angular 5

I am trying to work with Selenium in Java with Angular 5 based website.
Selenium does not support it directly, but JavascriptExecutor can help validating the page components finished loading.
The problem is, I do not know how to implement the JavaScript to validate this.
I am using:
return window.getAngularTestability === undefined
to validate Angular 5 exists in the current page, but the next part of the implementation is a mystery to me.
I know I have to use return window.getAngularTestability somehow.
You can create a generic java method for running any javascript within your Java code. Refer below block of code:-
public void executeJavascript(String script) {
((JavascriptExecutor) driver).executeScript(script);
}
You can pass your return javascript statements as parameters to this method.
I found an answer after a lot of research and searching the web.
The solution is not mine, so i do not deserve the credit.
ExpectedCondition<Boolean> expectation = driver -> ((JavascriptExecutor) driver).executeAsyncScript(
"var callback = arguments[arguments.length - 1];" +
"if (document.readyState !== 'complete') {" +
" callback('document not ready');" +
"} else {" +
" try {" +
" var testabilities = window.getAllAngularTestabilities();" +
" var count = testabilities.length;" +
" var decrement = function() {" +
" count--;" +
" if (count === 0) {" +
" callback('complete');" +
" }" +
" };" +
" testabilities.forEach(function(testability) {" +
" testability.whenStable(decrement);" +
" });" +
" } catch (err) {" +
" callback(err.message);" +
" }" +
"}"
).toString().equals("complete");
try {
WebDriverWait wait = new WebDriverWait(webDriver(), 15);
wait.until(expectation);
} catch (Throwable error) {
new Exception("Timeout waiting for Page Load Request to complete.");
}

play framework 2.1 accees log

I'm writing a play framework 2.1.5 access log, code like this
class AccessLog extends Filter {
def apply(next: (RequestHeader) => Result)(rh: RequestHeader) = {
val start = System.currentTimeMillis
def logTime(result: PlainResult): Result = {
val time = System.currentTimeMillis - start
val contentLength: String = result.header.headers getOrElse("Content-Length", "-")
play.Logger.info("" + rh.method +" " + rh.uri + " took " + " " + time + " ms and returned " + result.header.status + " " + contentLength)
result
}
next(rh) match {
case plain: PlainResult => logTime(plain)
case async: AsyncResult => async.transform(logTime)
}
}
}
I found that many people found an access log for the play framework and this works any way with an issue that
it can always get the response size, when you press CTRL + F5, if you just press F5, you cannot get the "Content-Length" even the "Content-Length" does not exist in the map.
any one konw this?

Regular Expression to identify Cobol EVALUATE block with JAVA

I want a regular expression to extract text between EVALUATE and END-EVALAUTE or . which ever comes first.
Presently i am using regular expression:
EVALUATE\\s*(((?!EVALUATE|(END-EVALUATE|\\.)).)+)\\s*(END-EVALUATE|\\.)
But my problem is i do not want to consider . if it comes within double quotes.
Please suggest any better regular expression or correct the one i have mentioned above.
Thanks in advance.
You could try this:
EVALUATE("[^"]*"|((?!EVALUATE|END-EVALUATE)[^."])+)*(END-EVALUATE|\.)
A Java demo:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) throws Exception {
String src =
" EVALUATE WS-ADDITIONAL-FILE-WORK \n" +
" WHEN \"ACCNT\" \n" +
" IF LINK-TRIG-FILE-NAME NOT = \"ACTMSTR \" \n" +
" PERFORM 04510-GET-ACCOUNT-MASTER \n" +
" ELSE \n" +
" MOVE \"0106H\" TO WS-ERROR-CODE \n" +
" PERFORM 09000-PROCESS-ABORT-ERROR \n" +
" END-IF \n" +
" WHEN \"ADDRM\" \n" +
" IF LINK-TRIG-FILE-NAME NOT = \"ADDRMSTR \" \n" +
" IF PROGRAM-HBMS-RELEASE (1:3) > \"5.0\" \n" +
" PERFORM 04520-GET-ADDRESS-MASTER \n" +
" END-IF \n" +
" ELSE \n" +
" MOVE \"0106H\" TO WS-ERROR-CODE \n" +
" PERFORM 09000-PROCESS-ABORT-ERROR \n" +
" END-IF \n" +
" WHEN OTHER \n" +
" MOVE \"0106F\" TO WS-ERROR-CODE \n" +
" PERFORM 09000-PROCESS-ABORT-ERROR \n" +
" END-EVALUATE. ";
Matcher m = Pattern.compile("EVALUATE(\"[^\"]*\"|((?!EVALUATE|END-EVALUATE)[^.\"])+)*(END-EVALUATE|\\.)").matcher(src);
while(m.find()) {
System.out.println(m.group());
}
}
}
which prints:
EVALUATE WS-ADDITIONAL-FILE-WORK
WHEN "ACCNT"
IF LINK-TRIG-FILE-NAME NOT = "ACTMSTR "
PERFORM 04510-GET-ACCOUNT-MASTER
ELSE
MOVE "0106H" TO WS-ERROR-CODE
PERFORM 09000-PROCESS-ABORT-ERROR
END-IF
WHEN "ADDRM"
IF LINK-TRIG-FILE-NAME NOT = "ADDRMSTR "
IF PROGRAM-HBMS-RELEASE (1:3) > "5.0"
PERFORM 04520-GET-ADDRESS-MASTER
END-IF
ELSE
MOVE "0106H" TO WS-ERROR-CODE
PERFORM 09000-PROCESS-ABORT-ERROR
END-IF
WHEN OTHER
MOVE "0106F" TO WS-ERROR-CODE
PERFORM 09000-PROCESS-ABORT-ERROR
END-EVALUATE
Just thought I'd point out that the regex given by Bart will match a basic, single-level EVALUATE block, however it will NOT cope with nested EVALUATEs.
For instance, try the regex on the following example:
EVALAUTE TRUE
WHEN FILE-ERROR
EVALUATE ERROR-CODE
WHEN FILE-NOT-FOUND
DISPLAY "File Not Found!"
WHEN ACCESS-DENIED
DISPLAY "Access Denied!"
END-EVALUATE
WHEN OTHER
DISPLAY "Success!"
END-EVALUATE
Another approach would be to read through the Cobol source line-by-line and for each EVALUATE you find on a line (that's not inside quotes), increment an evaluate 'level'. That way you can keep track of where you are in the nested levels.
Also, the OP said he was looking for a way to get the text "between" the EVALUATE and END-EVALUATE, which seems to imply that they should not be included. Maybe I misinterpreted that one, but if that is the requirement, then the regex is including the keywords incorrectly.

Threads in Java, states? Also what is the right way to use them?

I'm up for my exame presentation the day after tomorrow, so i need to get some straight before it which i hope you guys can help me with.
First i do know that there are 4 states of Threads (i.e Running, Ready, Blocked, Terminated), however i'm not quite sure how it works in Java. In my code i use the thread.sleep(3000) to do some waiting in the program, does this make the thread Blocked or Ready?
Also it have come to my attention that i might not have used the threads the right way, let me show you some code
public class BattleHandler implements Runnable {
private Player player;
private Monster enemyMonster;
private Dungeon dungeon;
private JTextArea log;
private GameScreen gScreen;
public void run() {
try {
runBattle();
}
catch(Exception e) { System.out.println(e);}
}
public BattleHandler(Player AttackingPlayer, JTextArea log, GameScreen gScreen) {
this.player = AttackingPlayer;
this.log = log;
this.gScreen = gScreen;
}
public void setDungeon(Dungeon dungeon) {
this.dungeon = dungeon;
}
public Dungeon getDungeon() {
return dungeon;
}
public Monster getEnemyMonster() {
return enemyMonster;
}
public void setMonster() {
// First check if dungeon have been init, if not we can't generate the mob
if(dungeon != null) {
enemyMonster = new Monster();
// Generate monster stats
enemyMonster.generateStats(dungeon);
}else {
System.out.println("Dungeon was not initialized");
}
}
public void runBattle() throws InterruptedException {
// Start battle, and run until a contester is dead.
while(player.getHealth() > 0 && enemyMonster.getHealth() > 0) {
int playerStrikeDmg = player.strike();
if(enemyMonster.blockDefend()) {
log.setText( log.getText() + "\n" + player.getName() +" tried to strike " + enemyMonster.getName()+ ", but " + enemyMonster.getName() + " Blocked.");
}else if(enemyMonster.dodgeDefend()) {
log.setText( log.getText() + "\n" + player.getName() +" tried to strike " + enemyMonster.getName()+ ", but " + enemyMonster.getName() + " Blocked.");
}else {
enemyMonster.defend(playerStrikeDmg);
log.setText( log.getText() + "\n" + player.getName() +" strikes " + enemyMonster.getName()+ " for: " + playerStrikeDmg + " left: "+ enemyMonster.getHealth());
}
if(enemyMonster.getHealth() < 1) break;
Thread.sleep(3000);
// Monster Turn
int monsterDmg = enemyMonster.strike();
if(player.blockDefend()) {
log.setText( log.getText() + "\n" + enemyMonster.getName() +" tried to strike " + player.getName()+ ", but " + player.getName()+ " Blocked.");
}else if(player.dodgeDefend()) {
log.setText( log.getText() + "\n" + enemyMonster.getName() +" tried to strike " + player.getName()+ ", but " + player.getName()+ " Dodged.");
}else {
player.defend(monsterDmg);
log.setText( log.getText() + "\n" + enemyMonster.getName() +" strikes " + player.getName()+ " for: " + monsterDmg + " left: "+ player.getHealth());
}
gScreen.updateBot();
Thread.sleep(3000);
}
When i coded this i thought it was cool, but i have seen some make a class just for controlling the Thread itself. I have just made the class who uses the Sleep runable(Which is not shown in the code, but its a big class).
Would be good to get this straight, so i can point i out before they ask me about it, you know take away there ammunition. :D
Hope you guys can help me :).
Thx
Threads have more than 4 states. Also, I recommend reading Lesson: Concurrency for more information regarding threads.
Note that if you're looking to execute a task at a set interval, I highly recommend using the Executors framework.
Blocked - it will not run at all until timeout. Ready is 'runnable now but there is no processor available to run it - will run as soon as a processor becomes available'.
As all the other guys state, there are more than those, here's a simple listing:
Running - Guess what, it's running
Waiting - It waits for another thread to complete its calculation (that's the wait() method in Java). Basically such a thread can also be run by the scheduler, like the "ready" state threads.
Ready - Means that the Thread is ready for execution, once the OS-Scheduler turns to this Thread, it will execute it
Blocked - Means that there is another operation, blocking this threads execution, such as IO.
Terminated - Guess what, it's done and will be removed by the OS-Scheduler.
For a complete listing, look at the famous Wikipedia ;)
http://en.wikipedia.org/wiki/Process_state

Categories