UI Testing
Selenium
- Selenium automates browsers!!!
Features
- navigate (windows, frames, links)
- find elements and parse attributes
- interact and trigger events (click, type, ...)
- capture screenshots
- run javascript
- let the browser take care of the hard stuff(cookies, javascript, sessions, profiles, DOM)
Parts of Selenium
- Selenium Webdriver
- Selenium IDE
- Selenium Server
- Selenium-Grid
Commands
find
- find_element_by_id
- find_element_by_name
- find_element_by_xpath
- find_element_by_link_text
- find_element_by_partial_link_text
- find_element_by_tag_name
- find_element_by_class_name
- find_element_by_css_selector
def login_field(self):
return self.wait.until(EC.element_to_be_clickable((By.NAME, 'Login')))
def password_field(self):
return self.wait.until(EC.element_to_be_clickable((By.NAME, 'Password')))
def login_button(self):
return self.wait.until(EC.element_to_be_clickable((By.XPATH, "//button[@type='submit']")))
def error_message(self):
return self.wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@class='error-text']")))
def login_username(self):
return self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "username")))
def logout_button(self):
return self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "logout")))
interact
def login(self, name, password):
self.login_field().send_keys(name)
self.password_field().send_keys(password)
self.login_button().click()
Actions
actions = ActionChains(driver)
test_plan = wait.until(EC.presence_of_element_located((By.XPATH, ".//ul/li[1]"))) actions.move_to_element(test_plan)
actions.click(test_plan)
actions.perform()
Asserts
- assertEqual(a, b)
- assertNotEqual(a, b)
- assertTrue(x)
- assertFalse(x)
General Recipe
- Install requirements
$ pip install selenium pyvirtualdisplay
- Start up Firefox and Selenium IDE or You can create a test code in your editor.
- Record a 'test' run through site.
- Export test as python script
- Hack from there
- Loops
- Image/data extraction
- Wrangling data into a database
Running Selenium Server
$ java -jar selenium-server-standalone-2.x.x.jar
Selenium Script Example
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class PythonOrgSearch(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def test_search_in_python_org(self):
driver = self.driver
driver.get("http://www.python.org")
self.assertIn("Python", driver.title)
elem = driver.find_element_by_name("q")
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main()