Skip to content

Commit

Permalink
Merge pull request #9 from GLMeece/master
Browse files Browse the repository at this point in the history
Documentation tweaks; disabled 'trying to go to'
  • Loading branch information
boakley authored Sep 5, 2017
2 parents 03a63d1 + f50e3b1 commit 89c417e
Show file tree
Hide file tree
Showing 6 changed files with 257 additions and 238 deletions.
61 changes: 30 additions & 31 deletions PageObjectLibrary/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,27 @@ class PageObjectLibrary(PageObjectLibraryKeywords):
[http://robotframework.org/Selenium2Library/doc/Selenium2Library.html|Selenium2Library].
This library does not replace Selenium2Library; rather, it
provides a framework around which to use Selenium2Library and the
lower-level [http://selenium-python.readthedocs.org/|python
bindings to selenium]
lower-level [http://selenium-python.readthedocs.org/|Python
bindings to Selenium]
This library provides the following keywords:
| =Keyword Name= | =Synopsis= |
| Go to page | goes to the given page in the browser |
| The current page should be | assert that the given page is displayed in the browser |
| Get page name | returns the name of the current page
| Go to page | Goes to the given page in the browser |
| The current page should be | Assert that the given page is displayed in the browser |
| Get page name | Returns the name of the current page |
PageObjectLibrary provides a PageObject class which should be used
as the base class for other page objects. By inheriting from this
class your keywords have access to the following pre-defined
attributes and methods:
| =Attribute/method= | =Description= |
| self.se2lib | A reference to the selenium2library instance |
| self.browser | A reference to the currently open browser |
| self.locator | A wrapper around the _locators dictionary |
| self.logger | A reference to the robot.api.logger instance |
| self._wait_for_page_refresh() | a context manager for doing work that causes a page refresh |
| ``self.se2lib`` | A reference to the Selenium2Library instance |
| ``self.browser`` | A reference to the currently open browser |
| ``self.locator`` | A wrapper around the ``_locators`` dictionary |
| ``self.logger`` | A reference to the ``robot.api.logger`` instance |
| ``self._wait_for_page_refresh()`` | a context manager for doing work that causes a page refresh |
= Using Selenium2Library Keywords =
Expand All @@ -45,11 +45,11 @@ class your keywords have access to the following pre-defined
| self.se2lib.capture_page_screenshot()
= Using Selenium methods =
= Using Selenium Methods =
The attribute ``self.browser`` is a reference to a selenium
The attribute ``self.browser`` is a reference to a Selenium
webdriver object. With this reference you can call any of the
standard selenium methods provided by the selenium library. The
standard Selenium methods provided by the Selenium library. The
following example shows how to find all link elements on a page:
| elements = self.browser,find_elements_by_tag_name("a")
Expand All @@ -60,9 +60,9 @@ class your keywords have access to the following pre-defined
the class should define the following attributes:
| =Attribute= | =Description= |
| PAGE_URL | The path to the current page, without the \
hostname and port (eg: /dashboard.html) |
| PAGE_TITLE | The web page title. This is used by the \
| ``PAGE_URL`` | The path to the current page, without the \
hostname and port (eg: ``/dashboard.html``) |
| ``PAGE_TITLE`` | The web page title. This is used by the \
default implementation of ``_is_current_page``. |
When using the keywords `Go To Page` or `The Current Page Should Be`, the
Expand All @@ -71,12 +71,12 @@ class your keywords have access to the following pre-defined
of the page. If you are working on a site where the page titles are not unique,
you can override this method to do any type of logic you need.
= Page Objects are normal robot libraries =
= Page Objects are Normal Robot Libraries =
All rules that apply to keyword libraries applies to page objects. For
example, the libraries must be on PYTHONPATH. You may also want to define
example, the libraries must be on ``PYTHONPATH``. You may also want to define
``ROBOT_LIBRARY_SCOPE``. Also, the filename and the classname must be identical (minus
the .py suffix on the file).
the ``.py`` suffix on the file).
= Locators =
Expand All @@ -88,9 +88,9 @@ class your keywords have access to the following pre-defined
the locators via dot notation within your keywords as ``self.locator.<name>``. The
``_locators`` dictionary may have nested dictionaries.
= Waiting for a page to be ready =
= Waiting for a Page to be Ready =
One difficulty with writing selenium tests is knowing when a page has refreshed.
One difficulty with writing Selenium tests is knowing when a page has refreshed.
PageObject provides a context manager named ``_wait_for_page_refresh()`` which can
be used to wrap a command that should result in a page refresh. It will get a
reference to the DOM, run the body of the context manager, and then wait for the
Expand Down Expand Up @@ -120,27 +120,26 @@ class your keywords have access to the following pre-defined
| with self._wait_for_page_refresh():
| self.click_the_submit_button()
= Using the page object in a test =
= Using the Page Object in a Test =
To use the above page object in a test, you must make sure that
robot can import it, just like with any other keyword
Robot can import it, just like with any other keyword
library. When you use the keyword `Go to page`, the keyword will
automatically load the keyword library and put it at the front of
the robot framework library search order (see
[http://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Set
Library Search Order|Set library search order])
the Robot Framework library search order (see
[http://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Set%20Library%20Search%20Order|Set Library Search Order])
In the following example it is assumed there is a second page
object named ``DashboardPage`` which the browser is expected to go to
if login is successful.
| *** Settings ***
| Library PageObjectLibrary
| Library Selenium2Library
| Suite Setup Open browser http://www.example.com
| ``*** Settings ***``
| Library PageObjectLibrary
| Library Selenium2Library
| Suite Setup Open browser http://www.example.com
| Suite Teardown Close all browsers
|
| *** Test Cases ***
| ``*** Test Cases ***``
| Log in to the application
| Go to page LoginPage
| Log in as a normal user
Expand Down
28 changes: 14 additions & 14 deletions PageObjectLibrary/keywords.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,10 @@ def se2lib(self):
def the_current_page_should_be(self, page_name):
"""Fails if the name of the current page is not the given page name
page_name is the name you would use to import the page
``page_name`` is the name you would use to import the page.
This keyword will import the given page object, put it at the
front of the robot library search order, then call the method
front of the Robot library search order, then call the method
``_is_current_page`` on the library. The default
implementation of this method will compare the page title to
the ``PAGE_TITLE`` attribute of the page object, but this
Expand All @@ -70,29 +70,29 @@ def the_current_page_should_be(self, page_name):
raise Exception("Expected page to be %s but it was not" % page_name)

def go_to_page(self, page_name, page_root = None):
"""Go to the url for the given page object
"""Go to the url for the given page object.
Unless explicitly provided, the URL root will be based on the
root of the current page. For example, if the current page is
http://www.example.com:8080 and the page object URL is
/login, the url will be http://www.example.com:8080/login
``/login``, the url will be http://www.example.com:8080/login
Example:
== Example ==
Given a page object named `ExampleLoginPage` with the URL
`/login`, and a browser open to `http://www.example.com`, the
following statement will go to `http://www.example.com/login`,
and place `ExampleLoginPage` at the front of robot's library
Given a page object named ``ExampleLoginPage`` with the URL
``/login``, and a browser open to ``http://www.example.com``, the
following statement will go to ``http://www.example.com/login``,
and place ``ExampleLoginPage`` at the front of Robot's library
search order.
| go to page ExampleLoginPage
| Go to Page ExampleLoginPage
The effect is the same as if you had called the following three
keywords
keywords:
| Selenium2Library.go to http://www.example.com/login
| Selenium2Library.Go To http://www.example.com/login
| Import Library ExampleLoginPage
| Set library search order ExampleLoginPage
| Set Library Search Order ExampleLoginPage
Tags: selenium, page-object
Expand All @@ -105,7 +105,7 @@ def go_to_page(self, page_name, page_root = None):
url = "%s://%s%s" % (scheme, netloc, page.PAGE_URL)

with page._wait_for_page_refresh():
self.logger.console("\ntrying to go to '%s'" % url)
# self.logger.console("\ntrying to go to '%s'" % url) # <-- Remove hashmark if you want this message on console
self.se2lib.go_to(url)
# should I be calling this keyword? Should this keyword return
# true/false, or should it throw an exception?
Expand Down
2 changes: 1 addition & 1 deletion PageObjectLibrary/version.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
__version__ = "1.0.0-beta.1"
__version__ = "1.0.0-beta.2"

125 changes: 125 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# PageObjectLibrary

## Overview

PageObjectLibrary is a lightweight [Robot Framework] keyword library that makes it possible to use the page object pattern when testing web pages with the keyword based approach of robot framework.

## Installing

```bash
pip install --upgrade robotframework-pageobjectlibrary
```

## Source code

The source code is hosted on github at the following url:

* https://github.com/boakley/robotframework-pageobjectlibrary.git

## Running the demo

In the github repository is a small demonstration suite that includes a self-contained webserver and web site.

For the demo to run you must have robotframework 2.9+ and Selenium2Library installed. You must also have cloned the github repository to have access to the demo files.

To run the demo, clone the github repository, cd to the folder that contains this file, and then run the following command: :

```bash
robot -d demo/results demo
```
### A simple tutorial

For a simple tutorial, see <https://github.com/boakley/robotframework-pageobjectlibrary/wiki/Tutorial>

## How it works

The page object library is quite simple. Page object classes are implemented as standard robot keyword libraries, and relies on robot frameworks built-in [Set library search order keyword].

The core concept is that when you use PageObjectLibrary keywords to go to a page or assert you are on a specific page, the keyword will automatically load the library for that page and put it at the front of the library search order, guaranteeing that the page object keywords are available to your test case.

## Why page objects makes writing tests easier

The purpose of the page object pattern is to encapsulate the knowledge of how a web page is constructed into an object. Your test uses the object as an interface to the application, isolating your test cases from the details of the implementation of a page.

With page objects, developers are free to modify web pages as much as they want, and the only thing they need to do to keep existing tests from failing is to update the page object class. Because test cases aren’t directly tied to the implementation, they become more stable and more resistent to change as the website matures.

## A typical test without page objects

With traditional testing using Selenium, a simple login test might look something like the following: (using the pipe-separated format for clarity):

```robotframework
*** Test Cases ***
| Login with valid credentials
| | Go to | ${ROOT}/Login.html
| | Wait for page to contain | id=id_username
| | Input text | id=id_username | ${USERNAME}
| | Input text | id=id_password | ${PASSWORD}
| | Click button | id=id_form_submit
| | Wait for page to contain | Your Dashboard
| | Location should be | ${ROOT}/dashboard.html
```

Notice how this test is tightly coupled to the implementation of the page. It has to know that the input field has an id of “id_username”, and the password field has an id of “id_password”. It also has to know the URL of the page being tested.

Of course, you can put those hard-coded values into variables and import them from a resource file or environment variables, which makes it easier to update tests when locators change. However, there’s still the overhead of additional keywords that are often required to make a test robust, such as waiting for a page to be reloaded. The provided PageObject superclass handles some of those details for you.

## The same test, using page objects

Using page objects, the same test could be written like this:

```robotframework
*** Test Cases ***
| Login with valid credentials
| | Go to page | LoginPage
| | Login as a normal user
| | The current page should be | DashboardPage
```

Notice how there are no URLs or element locators in the test whatsoever, and that we’ve been able to eliminate some keywords that typically are necessary for selenium to work but which aren’t part of the test logic *per se*. What we end up with is test case that is nearly indistinguishable from typical acceptance criteria of an agile story.

## Writing a Page Object class

Page objects are simple python classes that inherit from `PageObjectLibrary.PageObject`. There are only a couple of requirements for the class:

- The class should define a variable named PAGE\_TITLE
- The class should define a variable named PAGE\_URL which is a URI relative to the site root.

By inheriting from `PageObjectLibrary.PageObject`, methods have access to the folloing special object attributes:

- `self.se2lib` - a reference to an instance of Selenium2Library. With this you can call any of the Selenium2Library keywords via their python method names (eg: self.se2lib.input\_text)
- `self.browser` - a reference to the webdriver object created when a browser was opened by Selenium2Library. With this you can bypass Selenium2Library and directly call all of the functions provided by the core selenium library.
- `self.locator` - a wrapper around the `_locators` dictionary of the page. This dictionary can contain all of the locators used by the page object keywords. `self.locators` adds the ability to access the locators with dot notation rather than the slightly more verbose dictionary syntax (eg: `self.locator.username` vs `self._locators["username"]`.

## An example page object

A page object representing a login page might look like this:

```python
from PageObjectLibrary import PageObject

class LoginPage(PageObject):
PAGE_TITLE = "Login - PageObjectLibrary Demo"
PAGE_URL = "/login.html"

_locators = {
"username": "id=id_username",
"password": "id=id_password",
"submit_button": "id=id_submit",
}

def enter_username(self, username):
"""Enter the given string into the username field"""
self.se2lib.input_text(self.locator.username, username)

def enter_password(self,password):
"""Enter the given string into the password field"""
self.se2lib.input_text(self.locator.password, password)

def click_the_submit_button(self):
"""Click the submit button, and wait for the page to reload"""
with self._wait_for_page_refresh():
self.se2lib.click_button(self.locator.submit_button)
```

[robot framework]: http://www.robotframework.org
[Set library search order keyword]: http://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Set%20Library%20Search%20Order
Loading

0 comments on commit 89c417e

Please sign in to comment.