Советы от компании Sauce Labs по написанию Selenium тестов


(Mykhailo Poliarush) #1

Запись вебинара в рамках программы "Test Like A Ninja Webinar Series". Santiago Suarez делится своими tips & trick по работе с Selenium и WebDriver.

Неявное ожидание для Selenium 1:

{syntaxhighlighter brush: bash;fontsize: 100; first-line: 1; }import time, re from selenium import selenium

class implicitWaitSelenium(selenium):
“”"
Extending the regular selenium class to add implicit waits
“”"

def __init__(self, *args):
    self.implicit_wait = 30
    super(implicitWaitSelenium, self).__init__(*args)

def do_command(self, verb, args, implicit_wait=None):
    if implicit_wait is None:
        implicit_wait = self.implicit_wait

    try:
        return super(implicitWaitSelenium, self).do_command(verb, args)
    except Exception, e:
        if (re.match("ERROR: Element .* not found", str(e))
            and implicit_wait > 0):
            time.sleep(1)
            return self.do_command(verb, args, implicit_wait-1)
        raise Exception(e)

{/syntaxhighlighter}

Игнорирование Open и waitForPageToLoad ошибок:

{syntaxhighlighter brush: python;fontsize: 100; first-line: 1; }class SeleniumTestCase(TestCase):

# Let us just call self.click or self.type instead of self.selenium.type
def __getattr__(self, name):
    if hasattr(self, 'selenium'):
        return getattr(self.selenium, name)
    raise AttributeError(name)

# Ignore open commands that fail (same needs to be don for wait_for_page_to_load)
def open(self, url, ignoreResponseCode=True):
    try:
        self.selenium.open(url, ignoreResponseCode)
    except Exception, e:
        print "Open failed on %s. Exception: %s" % (url, str(e))
        pass #sometimes open appears to work fine but flakes out. ignore those

# Report pass/fail status to Sauce Labs
def tearDown(self):
    passed = {'passed': self._exc_info() == (None, None, None)}
    self.set_context("sauce: job-info=%s" % json.dumps(passed))
    self.stop(){/syntaxhighlighter}</p><p>Репортинг pass/fail статусов автоматически для Selenium 2:</p><p>{syntaxhighlighter brush: python;fontsize: 100; first-line: 1; }class Selenium2TestCase(TestCase):

def report_pass_fail(self):
    base64string = base64.encodestring('%s:%s' % (config['username'],
                                                  config['access-key']))[:-1]
    result = json.dumps({'passed': self._exc_info() == (None, None, None)})
    connection =  httplib.HTTPConnection(self.config['host'])
    connection.request('PUT', '/rest/v1/%s/jobs/%s' % (self.config['username'],
                                                       self.driver.session_id),
                       result,
                       headers={"Authorization": "Basic %s" % base64string})
    result = connection.getresponse()
    return result.status == 200

def tearDown(self):
    self.report_pass_fail()
    self.driver.quit(){/syntaxhighlighter}</p><p>Источник: <a href="http://saucelabs.com/blog/index.php/2011/07/tips-from-our-codebase-to-help-you-write-reliable-selenium-tests/">Tips From Our Codebase To Help You Write Reliable Selenium Tests</a></p>