Skip to content

Instantly share code, notes, and snippets.

@gabrielfalcao
Created January 29, 2011 03:15
Show Gist options
  • Save gabrielfalcao/801470 to your computer and use it in GitHub Desktop.
Save gabrielfalcao/801470 to your computer and use it in GitHub Desktop.
nice stuff, such as drag and drop for selenium2's webdriver
class SeleniumBrowser(object):
def __init__(self):
self.driver = WebDriver()
def _extract_error(self, exception):
regex = re.compile(ur'URL = (?P<url>\S+) Response_Code = (?P<status>\d+) Error_Message = (?P<message>.*)')
found = regex.search(unicode(exception))
if found:
return found.groupdict()
return {}
def goto_url(self, url):
if not url.startswith("/"):
url = reverse(url)
url = django_url(url)
try:
self.driver.get(url)
world.response = {
'status': 200,
'message': "sucesso",
'url': url
}
except Exception, e:
world.response = self._extract_error(e)
def goto_django_url(self, url, *args, **kwargs):
durl = reverse(url, args=args, kwargs=kwargs)
self.goto_url(durl)
def wait(self, seconds=5):
warnings.warn("Deprecation warning")
def cssselect(self, selector):
dom = self.get_dom()
return dom.cssselect(selector)
def xpath(self, selector):
dom = self.get_dom()
return dom.xpath(selector)
def get_dom(self):
return html.fromstring(self.get_source())
def get_json(self):
json = self.driver.find_element_by_tag_name("pre").get_text()
return simplejson.loads(json)
def get_attribute(self, selector, name):
element = self.find_by_css(selector)
return element.get_attribute(name)
def value_of(self, selector):
element = self.find_by_css(selector)
return element.get_value()
def get_source(self):
return self.driver.get_page_source()
def translate_css_to_xpath(self, selector):
if not selector.startswith("/"):
css = CSSSelector(selector)
selector = css.path.replace('descendant-or-self::', '//')
return selector
def select_combo_by_value(self, selector, value):
select = self.find_by_css(selector)
option = select.find_element_by_xpath('//option[@value="%s"' % value)
option.set_selected()
def select_combo_by_text(self, selector, label):
select = self.find_by_css(selector)
option = select.find_element_by_xpath('//option[text()="%s"]' % label)
option.set_selected()
def select_combo_by_index(self, selector, index):
select = self.find_by_css(selector)
option = select.find_element_by_xpath("//option")[index]
option.set_selected()
def select_combo_by_id(self, selector, id):
option = self.driver.find_element_by_id(id)
option.set_selected()
def click(self, selector):
element = self.find_by_css(selector)
element.click()
def find_by_xpath(self, selector):
try:
return self.driver.find_element_by_xpath(selector)
except NoSuchElementException:
raise AssertionError(u'não foi possível encontrar nenhum elemento através do xpath: %s' % selector)
def find_by_css(self, selector):
xpath = self.translate_css_to_xpath(selector)
try:
return self.find_by_xpath(xpath)
except NoSuchElementException:
raise AssertionError(u'não foi possível encontrar nenhum elemento através do css selector: %s' % selector)
def mouse_over(self, selector):
selector = self.translate_css_to_xpath(selector)
script = '''
var iterator = window.document.evaluate('%s', window.document, null, 9, null );
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent('mouseover', true, true, window, 0, 0, 0, 0, 0, false, false, true, false, 0, null);
var node = iterator.singleNodeValue;
return node.dispatchEvent(evObj);
''' % selector
try:
self.driver.execute_script(script)
except Exception:
pass
def blur(self, selector):
selector = self.translate_css_to_xpath(selector)
script = "return window.document.evaluate('%s',window.document,null,9,null).singleNodeValue.blur();" % selector
try:
self.driver.execute_script(script)
except Exception:
pass
def is_visible(self, selector, timeout=20):
old = selector
r = timeout * 10
element = self.find_by_css(selector)
for index in range(r):
time.sleep(0.1)
visible = element.is_displayed()
if visible:
break
assert index < r, '%s ainda está escondido, mesmo depois de %d segundos' % (old, timeout)
return visible
def wait_text_become_present(self, text, timeout=20):
r = timeout * 10
for index in range(r):
time.sleep(0.1)
present = text in self.get_source()
if present:
break
assert index < r, '%s ainda não existe, mesmo depois de %d segundos' % (text, timeout)
return present
def wait_text_vanish(self, text, timeout=10):
r = timeout * 10
for index in range(r):
time.sleep(0.1)
invisible = text not in self.get_source()
if invisible:
break
assert index < r, '%s ainda existe, mesmo depois de %d segundos' % (text, timeout)
return invisible
def wait_until_present(self, selector, timeout=10):
old = selector
selector = self.translate_css_to_xpath(selector)
r = timeout * 10
for index in range(r):
time.sleep(0.1)
present = self.xpath(selector)
if present:
break
assert index < r, '%s ainda não existe, mesmo depois de %d segundos' % (old, timeout)
return present
def wait_until_vanish(self, selector, timeout=10):
old = selector
selector = self.translate_css_to_xpath(selector)
r = timeout * 10
for index in range(r):
time.sleep(0.1)
invisible = not self.xpath(selector)
if invisible:
break
assert index < r, '%s ainda existe, mesmo depois de %d segundos' % (old, timeout)
return invisible
def is_hidden(self, selector, timeout=10):
old = selector
element = self.find_by_css(selector)
r = timeout * 10
for index in range(r):
time.sleep(0.1)
hidden = not element.is_displayed()
if hidden:
break
assert index < r-1, '%s ainda está visível, mesmo depois de %d segundos' % (old, timeout)
return hidden
def type(self, selector, text):
element = self.find_by_css(selector)
element.send_keys(text)
def empty(self, selector):
element = self.find_by_css(selector)
element.clear()
def drag_and_drop_to_object(self, obj_1, obj_2):
element_1 = self.find_by_css(obj_1)
element_2 = self.find_by_css(obj_2)
coordinates_1 = element_1._execute(SeleniumCommand.GET_ELEMENT_LOCATION)['value']
coordinates_2 = element_2._execute(SeleniumCommand.GET_ELEMENT_LOCATION)['value']
x = coordinates_2['x'] - coordinates_1['x']
y = coordinates_2['y'] - coordinates_1['y']
element_1._execute(SeleniumCommand.DRAG_ELEMENT, {'x':x, 'y':y})
def quit(self):
self.driver.quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment