Skip to main content

_python

Example

Our example application is available here on the-internet. It has a few avatars displayed in a grid layout. When you hover over each of them, they display additional user information and a link to view a full profile.

We're going to write a test that will hover over the first avatar and make sure that this additional information appears.

First we'll include our requisite libraries, declare the test class, and wire up some simple setUp and tearDown methods.

# filename: hovers.py
import unittest
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By


class Hovers(unittest.TestCase):

def setUp(self):
self.driver = webdriver.Firefox()

def tearDown(self):
self.driver.quit()

# ...

Now let's write our test.

# filename: hovers.py
# ...
def test_example_1(self):
driver = self.driver
driver.get('http://the-internet.herokuapp.com/hovers')
avatar = driver.find_element(By.CLASS_NAME, 'figure')
ActionChains(driver).move_to_element(avatar).perform()
avatar_caption = driver.find_element(By.CLASS_NAME, 'figcaption')
assert avatar_caption.is_displayed()

if __name__ == "__main__":
unittest.main()

After loading the page we find the first avatar and store it in a variable (avatar). We then use the .move_to_element method and feed it the avatar variable (which triggers the hover).

We then check to see if the additional user information is displayed with .is_displayed in our assertion.

Expected Behavior

When we save this file and run it (e.g., python hover.py from the command-line) here is what will happen:

  • Open the browser
  • Visit the page
  • Hover over the first avatar
  • Assert that the caption appeared on the page
  • Close the browser

Summary

Hopefully this will help you handle more complex user interactions like hovers.

Happy Testing!