All posts by Mindful tester

Fast Forwarding Slow Down

On the day of my talk about TDD in Test Automation the meetup was postponed.

Painting

One month later I was still exploring Test Driven Development or TDD. The talk is still available. In this blog post I will write about my latest experiences.

Test automation is about programming and TDD is about programming. In a talk Kent Beck told about crazy ideas, which would bring him laughter. TDD in Test Automation made me laugh. What was holding me back?

“What is holding me back?”
Kent Beck about Explore at YOW! Conference 2018.

In TDD there is a continuous loop of Red, Green, and Refactor. Red is writing a failing test. Green is writing enough code to let the test pass. Refactor is clean up the code.

Refactor is like something like “Let me put that recurring piece of code in 1 method”. This sounds easy, but it is still tempting to optimise during coding or Green. I already made the optimised code, so why should I spend more time on refactoring? There might be a chance that I miss 2 out of 3 improvements.

A post it with the text Red posing to the post it with the text Green, pointing to the post it to the post it "Refactor". The Refactor post it points to the Red post it!

Myself

A common pattern in test automation is Arrange, Act, and Assert. The first phase is to arrange that everything is ready for testing. E.g. I am logged in with the right user name and password on the right website. The second phase is to act or do something, which must be checked. E.g. I have to press on this button, so a dialog will pop up. The third and last phase is to assert or check, whether the result is right. E.g. I can see a dialog.

At that moment I had two patterns to work with:

  1. Arrange Act Assert
  2. Red Green Refactor

On a high level I used Arrange, Act, and Assert for the general structure. On a low level I used the Red Green Refactor cycle to make the code. So the Assert block contained several Red Green Refactor cycles. A cycle can also be shown as a serie of actions.

In the upper part there is a rectangle "Assert". Under this rectangle there are two groups rectangles "Red", "Green", "Refactor". The left group is lower than the right group!

In the next image I add Arrange and Act. For my convenience I abbreviated to “Red, Green, Refactor” to “RGR”.

There are 3 rectangles, Arrange, Act, and Assert. Under the rectangle Assert RGR is written twice. The left RGR is lower than the right RGR!
In order to improve my skills I used the Selenium WebDriver with Java course of Angie Jones. It was very free, very good, and filled with useful code.

My deliberate practice exercise was to see, whether I could log in via the link Form Authentication on https://the-internet.herokuapp.com/.  See chapter 4.2 of the course.

In the corner

Maybe you noticed that I started with Assert. But why did I start with the Assert?
Frankly I cannot remember it. Maybe Assert was my final destination for my test script. Or perhaps I used Red Green Refactor on the wrong level. Any way I had a starting point for my test automation script.

public class LoginTests {
SecureAreaPage secureAreaPage = new SecureAreaPage();

@Test
public void testSuccesfulLogin(){
  Assert.assertEquals(secureAreaPage.getMessage(),
    "You logged into a secure area!",
    "Alert text is incorrect.");
}

In SecureAreaPage.java I made a method for the class SecureAreaPage:

public String getMessage(){
  return "ran394594";
}

So I made my failing test. Red.

Now I could easily pass this test by changing the return value in SecureAreaPage.java. Green.

public String getAlertText(){
  return "You logged into a secure area!";
}

At this moment I had a problem. There was no connection with the website. The test would always pass regardless of the correctness of the form authentication.

Looking back I could even use the code to test pizzas. The test results would be of no value. What about testing that gravity is pulling me sideways? Same story. I must have been sleeping on my right side. The wrong side.

I needed to make some code to connect the website and Assert.
In the next blog post I will start with Arrange.

Test Automation is a quick way to check items in a web site. Fast Forwarding.
Coding is an activity which still needs consideration. Slow Down.

Find That Thing In The Room

80 % is not good enough.

A lot of readers might wonder about this statement. 80 % is quite good. Unless your boss does not accept any mistakes. But Agile is the new norm, so learn and adapt. Errors are some great and uncomfortable way to learn.

On the other hand a test automation result should not be right in 80 % of the cases. Especially when it was executed several times within 15 minutes. It is difficult for me to interpret these results.

My draft FAQ for test automation

This one is not perfect, but it will be better at the end of this blog post.

Q: What to do, if I always have a No Such Element Exception?
A: There is a good chance, that the web element cannot be found. So my way to locate the web element is bad. There are several ways to find a web element.

A: What to do, if I always have a Stale Element Exception?
A: There is a high chance, that TestNG is used. The element to be used cannot be found any more. In this can use a findElement as late as possible.

Q: What to do, if I have a No Such Element Exception once in a while?
A: My solution was to retry the required action. After an exception I would wait and try again.

Boolean individualOrderNotFound = false;
For (int i = 0; i < 3 && !individualOrderNotFound; i++){
  try {
      findElement(xpath).click();
      individualOrderNotFound = true;
  }
  catch(NoSuchElementException e){
      Thread.sleep(2000);
  }
}

Q: What to do, if I have a Stale Element Exception once in a while?
A: See the answer on the previous question.

Q: Would you like to write a blog post about it?
A: You are reading one of the blog post serie.

Q: Do you have anything to add?
A: Sure. How about from 80 % to 100% reliability?

Q: Why is 80 % not good enough?
A: If you perform a test, then the result cannot be trusted.

Q: I would just execute the test several times. 80 % of the results would point in the right direction.
A: So you take extra test execution for granted. And what if 90% of the test results are the same. Do you still execute tests until you get to 80 %?

Q: This is supposed to be a frequently asked questions.
A: You are right. Now it is a dialogue. Does it matter?

Q: I am the person who should be posing the question.
A: Why?

Pretty sure

The morale of the following story is that statistics should be used carefully to help your customers. So you can go straight to the next chapter with more Java and Selenium stuff.

Content warning: the following story contains a scene about a date with an unfortunate ending.

Imaginary situation in the cinema more than 2 decades ago. I am recognized by one of the employees.

Me: “I want to have a Cola.”
Employee: “Here you are. And the nachos and the hot sauce.”
Me: [puzzled] “How did you know that?”

Employee: “You always have the Nachos, if you order the Cola.”
Me: “Yes, you are right. I also want to order a Lemonade.”
Employee: “With a chance of 80 % …”
Employee: [Writes something on the cup and places the drink with a wink] “Here you are.”

Me: [Surprised] “What did you write??”
Brunette: [Walks to the counter] “Amy! Who is Amy?”
Me [Turning to the lady with a cramped smile.]
Employee: “Hi Amy.”

Me [Turning to the blond lady with a cramped smile.]
Brunette [Turning to the blond lady] “I am 5 minutes away and …”
Brunette: [Picks up my drink and throws it over me. Walks away angrily.]

Me: “And Amy, did you figure out the situation with the pointers?”
Young man [Approaches counter]: “So, that’s why you are interested in programming.”
Young man [Picks up the drink of Amy and pours over me. Walks away angry]

Amy: [Sighs] “I finally found a young man, who wants to talk about programming.”
Amy: [Picks up my hot sauce and pours it over me. Followed by the nachos]
Amy [Walks away angrily]

Employee: “If this get worse, I pay you bill. 100 % chance of no way.”
A TV crew pops up. A woman with a microphone: “People do the strangest things to stand the desert heat of the desert scene of Monsters Unlimited. More at 9. What is the cooling effect of Nachos and the hot sauce?”

Employee: [Shows receipt with a message: the receiver gets a lifetime membership of Cinema Hype VIP.]
[The sound of a paper being shredded.]

[The end]

Say it again Sam

Back to reality.
In my office I had the following quality check of my automation scripts. If a script would pass in 4 out of 5 cases, then it would be good. OK next test.

Now I had my honour to make my test results 100 % reliable.

The biggest advantage of the Cinema Hype VIP application was the two stage order. First an order could be placed for the movie tickets, so the seats were reserved. On the day of the movie drinks and snacks could be added to the order.

Let me try to remember what happened.
On first sight the actions were not that complicated:

  • Select a day.
  • Select a movie.
  • Select a time slot.

What did I see on screen?
There were 7 buttons to select a day. I implemented this step flawlessly.

The next step was to select the right movie in a combo box. I really liked Outside In, which would be shown from Thursday.

 
WebElement moviesComboBox = driver.findElement(By.xpath(contains(@id,
                                     “moviesComboBox”));
filterCombobox.click();
selectMovieOption();
filterField.sendKeys(“Outside In”);
filterField.sendKeys(Keys.ENTER);

The selection in the combo box went wrong: Stale Element Exception.

Maybe a loop might solve this problem.

Boolean individualOrderNotFound = false;
For (int i = 0; i < 3 && !individualOrderNotFound; i++){
  try {
      WebElement moviesComboBox = driver.findElement(By.xpath(contains(@id,
                                     “moviesComboBox”));
      filterCombobox.click();
      selectMovieOption();
      filterField.sendKeys(“Outside In”);
      filterField.sendKeys(Keys.ENTER);
      individualOrderNotFound = true;
  }
  catch(StaleElementException e){
      Thread.sleep(2000);
  }
}

After some tweaking I got No Such Element Exception. I also added this exception, but it did not help.

 
Boolean individualOrderNotFound = false;
For (int i = 0; i < 3 && !individualOrderNotFound; i++){
  try {
      WebElement moviesComboBox = driver.findElement(By.xpath(contains(@id,
                                     “moviesComboBox”));
      filterCombobox.click();
      selectMovieOption();
      filterField.sendKeys(“Outside In”);
      filterField.sendKeys(Keys.ENTER);
      individualOrderNotFound = true;
  }
  catch(StaleElementException e){
      Thread.sleep(2000);
  }
  catch(NoSuchElementException e){
      Thread.sleep(2000);
  }
}

I found my monster in the room. So I asked for help.

A tester from another team replaced the loop for the movie selection by a couple of sleeps.

Thread.sleep(2000);
filterCombobox.click();
Thread.sleep(2000);

selectMovieOption();
filterField.sendKeys(“Outside In”);
filterField.sendKeys(Keys.ENTER);

The code was a bit slower, but more reliable. 5 out of 5 passed. I better got used to this.

Hypothetical causes

Retrospecting my coding was not pleasant. I did not stick to my own FAQ. And this can happen.

Now let me focus on the working code.
My fellow tester gave me the tip to use sleep. This way any delays would be handled.

There were two statements “filterCombobox.click();” and “selectMovieOption();”, which were preceded with sleeps. Therefore there were two places where exceptions could occur. In my loop I assumed that there was only one place for exceptions. The worst part was that I picked the wrong action.

Let me illustrate, what would happen, if I handle exceptions by starting over at the wrong spot.
I have a recipe for baking. I have enough flour and more than enough eggs. First I find the flour. Everything goes right: there is no exception. Then I put 200 gram of flour into a bowl.

For the second step I pick an egg. I break the egg and the smell is bad. That is an exception. The egg goes into the wastebin. So I start all over. I empty the bowl.

First step I have to weigh the flour, but there is no flour any more. Now I have an exception and I cannot finish the recipe.

A much better way to find a good egg without throwing away the flour.

This is something I need to research.

Final Fantast I C Assert

At the end of every regression test there should be one final check. A simple yes or no would indicate, whether the test has passed. For the cinema reservation system this was quite simple. Has the order for the tickets, drinks, and snacks sent to the cinema?

I let Selenium set the search field to Order Id and enter the Order id. I saw a Stale Element Exception. Time for my FAQ. I used findElement at the latest moment. Stale Element Exception.

I let Selenium switch to another menu and back to the right page to continue.
Stale Element Exception.

Which other steps were possible?
I let Selenium log off and log on. A search of the Order Id followed.
The order was not found, so it was sent. Test passed.

Another look at Continuous Delivery

[Update author: my opinion is not the same as the author of the referred characters, but I believe in the goodness of the good characters.]

It was like delivering a message. If one way did not work out, another way was explored. What had a mail delivery person, a milk delivery person, and a mail delivery teacher in common?

They all wanted to deliver a letter to Mr. H. Potter. Persistence paid off. And be nice to the messenger. The delivery story had a nasty tail.

Deliberate Practice

Of course this post should end with some smart code.

While blogging I was going through the chapters of the free course about Selenium WebDriver and Java of Angie Jones on the Test Automation University. In Chapter 9 about Wait Strategies I found FluentWait. One of the cool things about this command, that it could ignore exceptions.

A part of the solution was:

Thread.sleep(2000);

selectMovieOption();

This code was not optimal. If the environment or network is changed, then the sleep time might be adopted each time. A FluentWait would provide a robust and fast solution in this case.

FluentWait wait = new FluentWait(driver)
  .withTimeout(Duration.ofSeconds(8))
  .pollingEvery(Duration.ofSeconds(1))
  .ignoring(NoSuchElementexception.class);
wait.until(ExpectedConditions.visibilityOf(
  driver.findelement(filterCombobox)));
selectMovieOption();

Also Alan Richardson released a paid course about test automation on LinkedIn: Advanced Selenium: 3 Synchronization Strategies. If I need more tricks, I consider to have a close look.

My improved FAQ for test automation

Q: What to do, if I always have a No Such Element Exception?
A: There is a good chance, that the web element cannot be found. So my way for to locate the web element is bad. There are several ways to find a web element.

Q: What to do, if I always have a Stale Element Exception?
A: There is a high chance, that TestNG is used. The element to be used cannot be found any more. In this case I use a findElement as late as possible.  Another option is to add some additional steps like logging out and logging in.

Q: What to do, if I have a No Such Element Exception once in a while?
A: Use a FluentWait.

Q: What to do, if I have a Stale Element Exception once in a while?
A: See the answer on the previous question.

Q: Do you have anything to add?
A: Have a look at Deliberate Practice. I mean the way of learning and not the previous chapter.

Selenium, I think this is the beginning of a beautiful friendship.

Find The Button Sometimes In The Room

Small recap also known as cliff hanger

At the end of the sprint I demonstrated my automated regression tests. An unknown dialog popped up and interrupted the normal flow of the tests.

An unexpected dialog

After the demo one of my team mates asked the standard routine questions:
“Did you test before the demo?”
“Yes, of course”
“Did everything go right?”
“Yes”

I had done all the standard actions and still this dialog popped up. I studied it. Something went wrong with saving a file. This neat feature offered the user to add a personalised picture with a text like “Happy birthday, Cap. Loves from Dom, Sam, and George.” This way nicknames “Captain Marvel” or “Captain America” can be used or even abbreviated to Cap.

So the first attempt to save the file failed. I pressed the OK button to upload the picture again. After two other attempts, an error dialog popped up. It was not possible.

Of course I tried to reproduce this error manually, but all uploading went just fine. Hmm. Another attempt with the automated test showed the file upload problem straight away. The computer was too fast with testing.

The Need For Brakes

Imaginary scene in a shop in a cinema. I am recognised by one of the employees.

Employee: “Good evening, what do you want to drink?”
Me: “Well.”
Employee: “Here is your favourite drink, Cola.”
Me: “I was thinking about .. ”

Employee: “Here is your second favourite drink, Lemonade.”
Me: “Actually ….”
Employee: “This is the last drink we offer: Sparkling Orange.”

Me: “This was not in my mind.”
Employee: “You are going to watch Monsters Unlimited with the famous desert scene. Right?”
Me: [Nods]
Employee: “Excuse me for being so rude.”
Employee [Removes the 3 drinks from the counter and places a bucket on the counter.]
Employee: “This will take a few seconds.”
Employee: [Places a thick tube into the bucket.]
[The sound of 1 gallon of Sparkling Orange being pumped into the bucket.]
Employee [Removes the tube and smiles at me]

Me: “And …”
Employee: “You are going to the 5D experience with the real desert temperature.”
Me [Nods slightly]
Employee: [Empties a box of ice cubes into the bucket.]
[The sound of overflowing Sparkling Orange, followed by dripping sounds on the floor.]

Me: “I am trying to tell you …”
Employee: “I got it. Drinking out of a bucket is a drinking hazard, so you get this special straw.”
Employee [Pulls out a mini submarine with a tube on top and places it on the drink.]
[Again the sound of dripping Sparkling Orange on the floor]

Me; “I want ..”
Employee [Shows receipt of 100 Euro.]
Me: “nothing to drink.”
[The end]

This story describes a timing issue. The employee is way too fast. And guess what? Programs are also very fast. For example a test automation tool.

Wait a few seconds

Something had been changed in the program and a dialog popped up. There should be a way to let the test automation tool wait. I picked Thread.sleep(2000). This command let the tool wait for 2000 milliseconds or 2 seconds.

I started the tests again. This time no problems with the Error dialog were encountered.

Next stop was to ponder whether this was a proper solution. I was actually hiding a performance issue. My team lead had already given me a hint about this kind of cases.

Personally I never had any problems with the upload of the file. So this should not happen with other human beings. Waiting for 2 seconds was not that bad.

The Untouchable

On my screen I had a nice combo box. I wanted to select an option. This was not that difficult I thought.

My test failed. Wait, this cannot be true. All the time the combo box was in full view and my test automation tool Selenium web driver could find it until that very moment. I opened the console to look at the problem: it was a Stale Element Reference Exception.

On the internet I read about a situation that a web element was somehow disconnected with the element on the screen. This read quite cryptic. I tried to imagine what happened.

There was a combo box with movies to be shown, Monsters Unlimited and Finding Marlin. After the selection of a new date a new movie would be shown, the combo box was updated with the latest movie, Outside In.

What actually happens was that the old combo box was replaced by another combo box. So the old combo box did not exist anymore. Small courtesy of the low code development tool. Not really helpful.

But why did this error happen right now?
The code of the website was not changed. But. I had changed the structure of my tests.
How can a restructuring of my tests cause this problem? Give me a few paragraphs to explain.

A popular design pattern for test automation is the Page Object Model. A design pattern is an experience based way of working, which saves a lot of time and frustration. Using Page Object Model or POM I put all the old code associated with a page like Select Movie Page in one single class.

The class contains the following useful information:

  • Constructor (how can I make this page object?)
  • Methods (which actions can I do on this particular page?)
  • Fields (which web elements are contained on this page? What other relevant information is used by this page?)

A movie combo box can be coded like:

@FindBy(contains(@id, “moviesComboBox”))
WebElement moviesComboBox ;

This is an abbreviation of TestNG, a test framework, for

WebElement moviesComboBox = driver.findElement(By.xpath(contains(@id,“moviesComboBox”))

For the reader wondering about the word contains, there is an explanation about this construction.

What I set up, was an administration, which connects moviesComboBox to the movie combo box with the movies Monsters Unlimited and Finding Marlin on screen.
The program replaced the combo box with the two movies by the movie combo box with Monsters Unlimited, Finding Marlin, and Outside In.
Now my web element moviesComboBox was referencing nothing.

My solution was to make the connection between the web element moviesComboBox and the combo box on screen as last as possible. Just before selecting a movie I placed the following code:

WebElement moviesComboBox = driver.findElement(By.xpath(contains(@id,
                                     “moviesComboBox”));

I got a Stale Element Reference Exception. No worries, I use a sleep.

Thread.sleep(100);
WebElement moviesComboBox = driver.findElement(By.xpath(contains(@id,
                                     “moviesComboBox”));

This was a flaky test. I could tweak my number of milliseconds of sleep, but a reliable test was slipping out of my hands.

The Unfindable

Now I had a situation that in 60 % of the cases my tests would execute with Passed. This was quite disturbing for me, because the website was not changed. Same test, same unpredictable result.

I focused on my latest test automation challenge: finding the right order identity often abbreviated to order id. Users were allowed to use an order Name like “Cap 13”. This is short for the 13th birthday of Captain Marvel or Captain America.

But this could hurt the handling of orders. Suppose a parent of Cap had made two reservations with the same name. If this persons calls the cinema, which order must be deleted by the customer agent? Cap 13 or Cap 13? So an order id was introduced.

For test automation this was really helpful. The organizer or parent placed the order for the movie visit. And she or he got an order id. In turn all attendees or kids could use this order id to order a snack and a drink.

If I automated my manual steps, then everything would be okay.
My steps were:

  • Search for the order name.
  • Determine the first row in the table.
  • Determine the order id in this row.

The code was ready, but the test did not pass. Another fail on my record. I better got used to this.

This time I saw a No Such Element Exception in my console. This meant, that the first row could not be found. Then I got a déjà vu. The test automation tool was too fast, so I built in a sleep. This did not solve the problem completely.

Sent until accepted

[Update author: my opinion is not the same as the author of the referred characters, but I believe in the goodness of the good characters.]

Suppose there is a character, who wants to reach someone else. Let me pick an arbitrary person called M. McGonagall. Her employer does not receive a response on her letter.

So every responseless day she resends a letter and also slowly increases the number from 1 via 3 via 12 via 24 via 30 – 40 to some 100. Until a pink umbrella wielding bloke delivers the long awaited letter to Mr. H. Potter.

The Multiple

In the meantime I was tweaking my sleep time in milliseconds. It looks that a response time was between the 2 and 6 seconds. If I only used the worst case scenario time, then this would lead to an increased execution time of my regression tests. Because the low code tool automatically made the code for the website, there was no way to tweak this code.

I got an idea. What about trying to find the first row 3 times instead of once?

Boolean individualOrderNotFound = false;
For (int i = 0; i < 3 && !individualOrderNotFound; i++){
  try {
      findElement(xpath).click();
      individualOrderNotFound = true;
  }
  catch(NoSuchElementException e){
      Thread.sleep(2000);
  }
}

While blogging I fully realise that this is not the best piece of code to be shown. But things in the past cannot be changed.

I performed my test 5 times in a row. There was 1 fail. I felt relieved, that my tests were more reliable than before. Less fails on my record. I better got used to it.

There was still one more thing to check.

Time for another blog post.