Skip to main content

_python

Example

Let's start by pulling in our requisite libraries, declare the test class, and wire up some simple setUp and tearDown methods.

# filename: right_click.py
import unittest
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By


class RightClick(unittest.TestCase):

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

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

Now we're ready to write our test.

We'll use an example from the-internet that will render a custom context menu when we right-click on a specific area of the page (link). Clicking the context menu will trigger a JavaScript alert which will say You selected a context menu. We'll grab this text and use it to assert that the menu was actually triggered.

# filename: right_click.py
# ...
def test_example_1(self):
driver = self.driver
driver.get('http://the-internet.herokuapp.com/context_menu')
menu_area = driver.find_element(By.ID,'hot-spot')
ActionChains(driver).context_click(
menu_area).send_keys(
Keys.ARROW_DOWN).send_keys(
Keys.ARROW_DOWN).send_keys(
Keys.ARROW_DOWN).send_keys(
Keys.ENTER).perform()
alert = driver.switch_to.alert
assert alert.text == 'You selected a context menu'

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

Expected Behavior

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

  • Open the browser and visit the page
  • Find and right-click the area which will render a custom context menu
  • Select the context menu option with keyboard keys
  • JavaScript alert appears
  • Grab the text of the JavaScript alert
  • Assert that the text from the alert is what we expect
  • Close the browser

Summary

To learn more about context menus, you can read this write-up from the Tree House blog.

Happy Testing!