This is the P2PU Archive. If you want the current site, go to www.p2pu.org!

Learning Web UI Automation

Week 4 - Pattern Matching

David Burns's picture
Fri, 2011-02-18 18:11

This week we are going to have a look at doing pattern matching within our tests. This is extremely useful since Selenium's major use is to test web applications. Pattern Matching is the use of regular expressions or globbing to validate and verify information on the page.

We can also make sure that the exact text is avaiable to be used.

Exact checks

In testing there are times that we want to make sure that we have the exact text in the right place at the right time. An example of this may be that you want to check the EULA of a site or you want to check that user name is correct. To do this is as simple as asserting text against get_text(locator).

An example of this may look like the python below.

 self.assertEqual("I love pattern matching", self.selenium.get_text("myLocator")

This is a very strict way to do testing and can be a little too strict, especially if you want to test that something is nearly the same.

The next way to check something is to apply regular expressions.

Regular Expressions

Regular expressions can be a bit tricky to understand so let's concentrate on a few of the basics of regular
expressions.

  • ^ indicates that you want to test from the beginning of the string
  • $ indicates up to the end of the string
  • . means anything in the string and should be accompanied by a multiplier
  • * is a multiplier meaning between 0 and n times
  • + is a multiplier meaning at least once
  • \d is used to check for numbers
  • \w is to check for word characters
  • | is an or. Eg. x|X will check for either case of x
  • There are more but they can

Python has a library called re that allows us to do pattern matching.

There are 2 ways that we can use re, the first is with match(). This will search a string from the beginning of the string. It is like putting a ^ in the beginning of the string.

For Example, from the Python Documentation

>>> re.match("c", "abcdef")  # No match
>>> re.match("c", "cdef") # Match

If it finds something it will return a Match Object otherwise you will be left with a None(null in other languages)

The other way to do this is to use search().

This will search through a string until it finds a match. So if we take the example from above and modify it

>>> re.search("c", "abcdef")  # match
>>> re.match("^c", "abcdef") # No Match but Note that its looking from the front of the string

I suggest reading up more about python regular expressions at

http://docs.python.org/library/re.html

Task

This week's task is to take week 2 task and augment it to check the amount of downloads.

You will have to get the text back from the page about the downloads and then do the assert using a regular expression.

As always if you have any questions, email me and I will try help!