コード例 #1
0
 def test_grid(self):
     hub_url = 'http://127.0.0.1:4444/wd/hub'
     capability = DesiredCapabilities.CHROME.copy()
     for i in range(1,5):
         # 利用Remote远程连接hub,hub将脚本分发给了不同的node
         driver = Remote(command_executor=hub_url, desired_capabilities=capability)
         driver.get('https://home.testing-studio.com/')
def run_test2(host, desired_capabilities):
    driver = Remote(command_executor=host, desired_capabilities=desired_capabilities)
    driver.get('https://www.baidu.com')
    time.sleep(2)
    driver.find_element_by_id("kw").send_keys("remote")
    driver.find_element_by_id("su").click()
    time.sleep(2)
コード例 #3
0
def main():

    if len(sys.argv) != 2 or sys.argv[1] not in ('proxy', 'node'):
        exit('usage: driver_test.py <proxy|node>')

    is_proxy = sys.argv[1] == 'proxy'

    if is_proxy:
        setup_proxy_mode()
        base_url = 'http://' + PROXY_IP + ':5000/driver'
    else:
        setup_node_mode()
        base_url = 'http://' + NODE_IP + ':5555'

    time.sleep(7)

    driver = Remote(base_url + '/wd/hub', desired_capabilities=CAPABILITIES)
    driver.get('http://soas.ac.uk')
    links = driver.find_elements_by_xpath('//a')
    curr_link = links[1]
    outer_html = curr_link.get_attribute('outerHTML')
    import pdb
    pdb.set_trace()
    print('result:')
    print(outer_html)
コード例 #4
0
def setup_login(base_url, selenium: Remote):
    selenium.get(base_url)
    selenium.delete_all_cookies()
    file = join(dirname(dirname(__file__)), 'cookies.pkl')
    cookies = load(open(file, "rb"))
    for cookie in cookies:
        selenium.add_cookie(cookie)
コード例 #5
0
def test_removing(browser: webdriver.Remote):
    browser.get('https://the-internet.herokuapp.com/add_remove_elements/')
    btn_add = browser.find_element_by_xpath('//button[text()="Add Element"]')
    max_add = random.randint(2, 15)
    print(f"will add button for {max_add} times ")
    for x in range(0, max_add):
        btn_add.click()
        time.sleep(
            0.1
        )  # make little bit visible ahaha :D believe me you wont see it, try to remark

    btns_delete = browser.find_elements_by_css_selector('#elements button')
    print('total btns_delete: ', len(btns_delete))
    print(btns_delete)

    for btn_delete in btns_delete:
        btn_delete.click()
        time.sleep(
            0.1
        )  # make little bit visible ahaha :D believe me you wont see it, try to remark

    # before getting not found items, we should reduce implicit time to make selenium wait shorter
    browser.implicitly_wait(1)
    btns_delete = browser.find_elements_by_css_selector('#elements button')
    assert len(btns_delete) == 0
コード例 #6
0
def _load_family_urls(driver: Remote, url: str):
    page_url_pattern = url + "?page={}"

    result = []
    page_number = 1
    page_count = 1

    while page_number <= page_count:
        page_url = page_url_pattern.format(page_number)

        driver.get(page_url)

        div_element = driver.find_element_by_css_selector(
            "div.breadcrumb-collection div.breadcrumb_text")
        page_count = int(
            re.match(".*Page \d+ of (?P<page_count>\d+)$",
                     div_element.get_property("innerText"),
                     re.IGNORECASE).group("page_count"))

        a_elements = driver.find_elements_by_css_selector(
            "div.product-list div.product-wrap a.product-info__caption")
        for a_element in a_elements:
            result.append(a_element.get_attribute("href"))

        logger.debug("Loaded %d products family URLs from '%s'",
                     len(a_elements), page_url)

        page_number += 1

    return result
コード例 #7
0
class Page(object):
    BASE_URL = 'http://ftest.stud.tech-mail.ru'
    PATH = ''

    def __init__(self, driver=None):
        if driver is None:
            browser = os.environ.get('TTHA2BROWSER', 'CHROME')
            self.driver = Remote(
                command_executor='http://127.0.0.1:4444/wd/hub',
                desired_capabilities=getattr(DesiredCapabilities, browser)
            )
        else:
            self.driver = driver

    def get_driver(self):
        return self.driver

    def open(self):
        url = urlparse.urljoin(self.BASE_URL, self.PATH)
        self.driver.get(url)
        self.driver.maximize_window()

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

    def login(self):
        auth_form = AuthForm(self.driver)
        auth_form.open_form()
        auth_form.set_login(conf.USEREMAIL)
        auth_form.set_password(conf.PASSWORD)
        auth_form.submit()
        return self.find_username()

    def find_username(self):
        return TopMenu(self.driver).get_username()
コード例 #8
0
ファイル: driver.py プロジェクト: hiram-labs/startup_in_a_box
class Driver:
    # TODO:
    # move user defined variables to central location
    def __init__(
        self,
        targetUrl="http://google.com",
        hubUrl="http://selenium-hub:4444/wd/hub",
        browser="chrome",
    ):
        self.targetUrl = targetUrl
        self.hubUrl = hubUrl
        self.browser = browser
        self.driver = None

    def start_driver(self):
        self.driver = Remote(
            command_executor=self.hubUrl,
            desired_capabilities={
                "browserName": self.browser,
                "javascriptEnabled": True,
            },
        )
        self.driver.get(self.targetUrl)

    def quit_driver(self):
        if self.driver is not None:
            self.driver.quit()
コード例 #9
0
def open_url(host, browser):
    dc = {"browserName": browser}
    driver = Remote(command_executor=host, desired_capabilities=dc)
    driver.get("https://www.baidu.com/")
    driver.find_element(By.CSS_SELECTOR, ".s_ipt").send_keys("selenium")
    driver.find_element(By.CSS_SELECTOR, "span>input#su").click()
    driver.close()
コード例 #10
0
 def test_grid(self):
     selenium_grid_url = 'http://127.0.0.1:4444/wd/hub'
     capability = DesiredCapabilities.CHROME.copy()
     for i in range(1, 5):
         driver = Remote(command_executor=selenium_grid_url,
                         desired_capabilities=capability)
         driver.get('https://www.baidu.com')
コード例 #11
0
 def test_grid(self):
     hub_url = "http://127.0.0.1:4444/wd/hub"
     capability = DesiredCapabilities.CHROME.copy()
     for i in range(1, 5):
         driver = Remote(command_executor=hub_url,
                         desired_capabilities=capability)
         driver.get("https://www.sanxiaod.com/")
コード例 #12
0
    def _send_answer(remote: Remote, link: str, answer_to_send: str) -> None:
        def wait_textarea(_remote: Remote):
            return _remote.find_element_by_css_selector("textarea.textarea")

        def wait_textarea_enabled(_remote: Remote):
            return _remote.find_element_by_tag_name("textarea").is_enabled()

        def wait_correct(_remote: Remote):
            return _remote.find_element_by_class_name("correct")

        remote.get(link)
        WebDriverWait(remote, 3).until(wait_textarea)

        try:
            remote.find_element_by_class_name("again-btn").click()
            WebDriverWait(remote, 3).until(wait_textarea_enabled)
        except NoSuchElementException:
            pass

        remote.find_element_by_css_selector("textarea.textarea").send_keys(
            answer_to_send)
        remote.find_element_by_class_name("submit-submission").click()

        try:
            WebDriverWait(remote, 3).until(wait_correct)
            expected = "Correct!"
            result = remote.find_element_by_class_name(
                "smart-hints__hint").text
            assert result == expected, f"{expected} != {result}"
        except NoSuchElementException:
            assert False, "No smart-hints__hint element on the page after submission"
コード例 #13
0
def login_succeed(ip, browser):
    driver = Remote(command_executor=ip,
                    desired_capabilities={'platform': 'ANY',
                                          'browserName': browser,
                                          'version': '',
                                          'javascriptEnabled': True,
                                          })
    url = "http://192.168.117.9:8080/jforum/forums/list.page"
    driver.get(url)

    try:
        driver.find_element_by_name('username').send_keys('admin')
        driver.find_element_by_name('password').send_keys('admin')
        driver.find_element_by_name('login').click()

        request = driver.find_element(By.ID, 'myprofile').text
        print(request)

        find_digit = driver.find_element_by_xpath("//table[@cellpadding='2']/tbody/tr[4]/td[4]").text
        print(find_digit)

        """截图"""
        driver.save_screenshot(filename='loginSucceed.png')


    except NoSuchElementException as e:
        print(e)

    finally:
        sleep(2)
        driver.quit()
コード例 #14
0
def stepik_send_answer(remote: webdriver.Remote, answer: str):
    remote.get(LINK_LESSON)
    WebDriverWait(remote,
                  3).until(lambda x: x.find_element_by_tag_name("textarea"))
    remote.find_element_by_tag_name("textarea").send_keys(answer)
    remote.find_element_by_class_name("submit-submission").click()
    WebDriverWait(remote, 3).until(lambda x: x.find_element_by_id("correct"))
コード例 #15
0
class BuyPageTest(unittest.TestCase):
    def setUp(self):
        browser = os.environ.get('TTHA2BROWSER', 'CHROME')

        self.driver = Remote(
            command_executor='http://127.0.0.1:4444/wd/hub',
            desired_capabilities=getattr(DesiredCapabilities, browser).copy()
        )

        self.driver.get("https://cars.mail.ru/sale/msk/all/")

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

    def test_price_sort(self):
        page = BuyPage(self.driver)
        page.price_sort_btn.click()

        cards = page.read_cards()
        prices = [x.price for x in cards]
        for i in range(0, len(prices) - 1):
            self.assertTrue(prices[i] <= prices[i + 1])

    def test_region(self):
        page = BuyPage(self.driver)
        page.region_btn.click()
        page.region_input.send_keys(u'Казань')
        page.city_first_result.click()
        page.submit_region_btn.click()
        page.apply_filter_lnk.click()
        cards = page.read_cards()
        for x in cards:
            self.assertTrue(x.region == u'Казань')
コード例 #16
0
def stepik_send_answer(remote: webdriver.Remote, answer: str):
    remote.get("https://stepik.org/lesson/184253/step/4?unit=158843")
    WebDriverWait(remote,
                  3).until(lambda x: x.find_element_by_tag_name("textarea"))
    remote.find_element_by_tag_name("textarea").send_keys(answer)
    remote.find_element_by_class_name("submit-submission").click()
    WebDriverWait(remote, 3).until(lambda x: x.find_element_by_id("correct"))
コード例 #17
0
    def get_sso_session(
            self,
            selenium: webdriver.Remote,
            impersonate_user=settings.TEST_IMPERSONATE_USER
    ) -> webdriver.Remote:

        cookies = self.keycloak.impersonate(impersonate_user).cookies
        # Note(knikolla): We must open a page in order to set cookies.
        # Doesn't have to exist, but must be in same domain as SSO.
        selenium.get(f'{settings.KEYCLOAK_URL}/auth/test')
        for k in [x for x in cookies.keys() if 'KEYCLOAK' in x]:
            selenium.add_cookie({
                'name':
                k,
                'value':
                cookies[k],
                'domain':
                parse.urlparse(settings.KEYCLOAK_URL).netloc.split(':')[0],
            })

        selenium.get(f'{settings.KEYCLOAK_URL}/auth/realms/master/account/')

        selenium.implicitly_wait(5)
        username = selenium.find_element_by_xpath('//*[@id="username"]')
        assert username.get_attribute('value') == impersonate_user
        return selenium
コード例 #18
0
def navigate(driver: Remote):
    """
    目的のページに遷移する。
    """
    logging.info('Navigating...')
    driver.get('https://note.mu/')  # noteのトップページを開く。
    assert 'note' in driver.title  # タイトルに'note'が含まれていることを確認する。
コード例 #19
0
def _load_family(driver: Remote, url: str) -> Bundle:
    builder = Bundle.builder()

    driver.get(url)

    # todo: compare with store currency
    currency = driver.execute_script("return Currency.currentCurrency;")

    meta = driver.execute_script("return window.ShopifyAnalytics.meta;")
    element = driver.find_element_by_id("product-form-{}".format(
        meta["page"]["resourceId"]))

    family_json = ujson.loads(element.get_attribute("data-product"))
    family = _new_family(url, family_json)
    builder.family(family)

    for product_json in family_json["variants"]:
        product = _new_product(family.id, product_json)
        builder.product(product)

        image_json = product_json["featured_image"]
        if image_json:
            builder.image(_new_product_image(family.id, product.id,
                                             image_json))

    bundle = builder.build()

    logger.debug(
        "Loaded product family '%s' with %d products and %d images from '%s'",
        bundle.family.name, len(bundle.products), len(bundle.images),
        bundle.family.url)

    return bundle
コード例 #20
0
def test_default_state(browser: webdriver.Remote):
    browser.get('https://the-internet.herokuapp.com/checkboxes')

    first_checkbox = browser.find_element_by_xpath('//input[1]')
    second_checkbox = browser.find_element_by_xpath('//input[2]')
    assert not first_checkbox.is_selected()
    assert second_checkbox.is_selected()
コード例 #21
0
 def test_grid(self):
     hub_url = "http://127.0.0.1:4444/wd/hub"
     capability = DesiredCapabilities.CHROME.copy()
     for i in range(1, 5):
         # 根据capability和node匹配
         driver = Remote(command_executor=hub_url,
                         desired_capabilities=capability)
         driver.get("https://home.testing-studio.com/")
コード例 #22
0
def test_send_screenshot() -> None:
    chrome = Remote(command_executor="http://localhost:4444/wd/hub/",
                    desired_capabilities={"browserName": "chrome"})
    chrome.get("https://www.google.com")
    chrome.save_screenshot("google.png")
    attach_test_screenshot("google.png")
    chrome.quit()
    assert True
コード例 #23
0
 def test_grid(self):
     hub_url = 'http://127.0.0.1:4444/wd/hub'
     capability = DesiredCapabilities.CHROME.copy()  #字典的深拷贝,不改变原来的
     capability['platform'] = 'windows'
     for i in range(1, 5):
         driver = Remote(command_executor=hub_url,
                         desired_capabilities=capability)
         driver.get('https://www.selenium.dev/downloads/')
コード例 #24
0
def test_send_artifact() -> None:
    firefox = Remote(command_executor="http://localhost:4444/wd/hub/",
                     desired_capabilities={"browserName": "firefox"})
    firefox.get("https://www.google.com")
    firefox.quit()
    attach_test_artifact("geckodriver.log")
    attach_test_run_artifact("geckodriver.log")
    attach_test_artifact_reference("name", "reference")
    assert True
コード例 #25
0
    def test_grid(self):

        hub_url = 'http://127.0.0.1:4444/wd/hub'
        capability = DesiredCapabilities.CHROME.copy()
        # 使用多线程实现并发
        for i in range(1, 5):
            driver = Remote(command_executor=hub_url,
                            desired_capabilities=capability)
            driver.get("https://www.baidu.com")
コード例 #26
0
 def test_grid(self):
     hub_url = "http://127.0.0.1:4444/wd/hub"
     # copy:对它的拷贝不影响原来的字典;官网的使用方式
     capability = DesiredCapabilities.CHROME.copy()
     for i in range(1, 5):
         # 倒入remote之后,可以远程连接hub;desired_capabilities 根据参数进行匹配node,hub就把脚本发送到node上
         driver = Remote(command_executor=hub_url, desired_capabilities=capability)
         # 因为循环写在一个线程中,所以会等待第一个get打开完成后才会进入下一次的循环
         driver.get("http://home.testing-studio.com/")
コード例 #27
0
ファイル: lesson2_3_5.py プロジェクト: lion0k/stepik_selenuim
def stepik_auth(remote: webdriver.Remote):
    remote.get(LINK_TO_STEPIK)
    WebDriverWait(remote, 3).until(lambda x: x.find_element_by_name("login"))
    remote.find_element_by_name("login").send_keys(LOGIN)
    remote.find_element_by_name("password").send_keys(PASSWORD)
    remote.find_element_by_class_name("sign-form__btn").click()
    WebDriverWait(
        remote,
        3).until(lambda x: x.find_element_by_class_name("navbar__profile-img"))
コード例 #28
0
def test_baidu(host, browser):
    print('当前浏览器是%s,启动时间是%s' % (browser, time.ctime()))
    dc = {'browserName': browser}
    driver = Remote(command_executor=host, desired_capabilities=dc)
    driver.get('https://www.baidu.com/')
    driver.find_element_by_id('kw').send_keys('selenium')
    driver.find_element_by_id('su').click()
    time.sleep(3)
    driver.close()
    print('%s结束时间是%s' % (browser, time.ctime()))
コード例 #29
0
ファイル: test_yahoo.py プロジェクト: FachrulCH/ngulik-pytest
 def test_search_fachrul(self, browser: webdriver.Remote):
     browser.get('https://id.yahoo.com')
     browser.find_element_by_id('header-search-input').send_keys(
         'github Fachrul Choliluddin' + Keys.ENTER)
     time.sleep(3)
     results = browser.find_elements_by_css_selector('h3.title')
     target = random.choice(results)
     print(target.text)
     target.click()
     time.sleep(3)
     assert 'fachrul' in str(browser.title).lower()
コード例 #30
0
def test_state_after_checked(browser: webdriver.Remote):
    browser.get('https://the-internet.herokuapp.com/checkboxes')

    first_checkbox = browser.find_element_by_xpath(
        '//input[@type="checkbox"][1]')
    second_checkbox = browser.find_element_by_xpath(
        '//input[@type="checkbox"][2]')
    first_checkbox.click()
    second_checkbox.click()
    assert first_checkbox.is_selected()
    assert not second_checkbox.is_selected()
コード例 #31
0
def stepik_auth(remote: webdriver.Remote):
    remote.get(auth_link)
    WebDriverWait(remote, 3).until(lambda x: x.find_element_by_name("login"))
    auth_elems = ("login", "password")

    for auth_elem in auth_elems:
        remote.find_element_by_name(auth_elem).send_keys(os.getenv(auth_elem))
    remote.find_element_by_class_name("sign-form__btn").click()
    WebDriverWait(
        remote,
        3).until(lambda x: x.find_element_by_class_name("navbar__profile-img"))
コード例 #32
0
ファイル: _initDriver.py プロジェクト: isomper/testIsomp
    def test_open_driver(self,host,brower):
        driver = Remote(command_executor=host,
                        desired_capabilities=brower
                        )
#        fileList = fileRead().get_ip_address()
#        ipAdd = fileList[0].strip('\n')
        driver.maximize_window()
        driver.get("https://" + ipAdd + "/fort")
        
        if brower == DesiredCapabilities.INTERNETEXPLORER:
            #https访问时弹出安全警告页面后点击继续,0代表有安全警告,1代表没有安全警告            
            driver.get("javascript:document.getElementById('overridelink').click();")
            #获取浏览器版本
            #brower_name = DesiredCapabilities.INTERNETEXPLORER.get('browserName')
        
        return driver
コード例 #33
0
ファイル: _initDriver.py プロジェクト: isomper/testIsomp
    def remote_open_driver(self,host,brower):
        driver = Remote(command_executor=host,
                        desired_capabilities={'platform':'ANY',
                                                'browserName':brower,
#                                                'version':'',
                                                'javascriptEnabled':True,
                                                'marionette':False
                                            }
                        )
        ipAdd = jsonTranscoding().get_app_ip().strip()
        driver.maximize_window()
        driver.get("https://" + ipAdd + "/fort")
        
        if brower == "internet explorer":
            #https访问时弹出安全警告页面后点击继续,0代表有安全警告,1代表没有安全警告            
            driver.get("javascript:document.getElementById('overridelink').click();")
        return driver
コード例 #34
0
 def test_baidu_search_english(self):
     u'''搜索英文'''
     for host,browser in self.browser_list.items():
         print host,browser
         driver = Remote(
             command_executor=host,
             desired_capabilities={
                 'platform':'ANY',
                 'browserName':browser,
                 'version':'',
                 'javascriptEnabled':True
             }
         )
         driver.get(self.baseurl)  #访问url
         driver.find_element_by_id("kw").send_keys(u"selenium")    #搜索框输入
         driver.find_element_by_id("su").click()    #点击搜索按钮
         time.sleep(1)
         assert(u"selenium_百度搜索" == driver.title),'Test Rusult:Fail'     #断言结果
         driver.quit()
         print time.ctime()
コード例 #35
0
ファイル: browser.py プロジェクト: chasehd/browsertrix
class Browser(object):
    def __init__(self, host_name=None, readlog=False):
        self.readlog = readlog
        self.host_name = host_name

        self.caps = self._init_caps()
        self._init_driver()

    def _init_local(self):
        raise NotImplemented()

    def _init_driver(self):
        self.driver = None

        if not self.host_name:
            self.driver = self._init_local()
            return

        while True:
            try:
                self.driver = Remote(command_executor='http://{0}:4444/wd/hub'.format(self.host_name),
                                     desired_capabilities=self.caps)
                break
            except:
                import traceback
                traceback.print_exc()
                print('RETRY CONN')

    def close(self):
        if self.driver:
            self.driver.quit()

    def visit(self, url):
        try:
            self.driver.get(url)
        except:
            self._init_driver()
            self.driver.get(url)

        results = {}
        return results
コード例 #36
0
ファイル: tests.py プロジェクト: santiycr/django
class AdminSeleniumWebDriverTestCase(LiveServerTestCase):

    available_apps = [
        "django.contrib.admin",
        "django.contrib.auth",
        "django.contrib.contenttypes",
        "django.contrib.sessions",
        "django.contrib.sites",
    ]

    def _get_remote_capabilities(self, specs):
        platforms = {
            "s": "Windows 2008",
            "x": "Windows 2003",
            "e": "Windows 2012",
            "l": "Linux",
            "m": "Mac 10.6",
            "i": "Mac 10.8",
        }
        browsers = {
            "ff": "firefox",
            "op": "opera",
            "ie": "internet explorer",
            "sa": "safari",
            "ip": "ipad",
            "ih": "iphone",
            "an": "android",
            "gc": "chrome",
        }
        browser = browsers[specs[:2]]
        if specs[-1] in platforms:
            platform = platforms.get(specs[-1])
            version = specs[2:-1]
        else:
            platform = None
            version = specs[2:]
        caps = {"browserName": browser, "version": version, "platform": platform, "public": "public"}
        if "BUILD_NUMBER" in os.environ:
            caps["build"] = os.environ["BUILD_NUMBER"]
        elif "TRAVIS_BUILD_NUMBER" in os.environ:
            caps["build"] = os.environ["TRAVIS_BUILD_NUMBER"]
        return caps

    def _get_local_webdriver_class(self, specs):
        browsers = {
            "ff": "selenium.webdriver.Firefox",
            "op": "selenium.webdriver.Opera",
            "ie": "selenium.webdriver.Ie",
            "gc": "selenium.webdriver.Chrome",
        }
        return import_by_path(browsers[specs[:2]])

    def setUp(self):
        test_method = getattr(self, self._testMethodName)
        if not hasattr(test_method, "spec"):
            raise SkipTest("Please make sure your test class is decorated with @browserize")
        elif not test_method.spec:
            raise SkipTest("Selenium tests not requested")
        try:
            selenium_specs = test_method.spec
            if os.environ.get("DJANGO_SELENIUM_REMOTE", False):
                webdriver_class = import_by_path("selenium.webdriver.Remote")
            else:
                webdriver_class = self._get_local_webdriver_class(selenium_specs)
        except Exception as e:
            raise SkipTest(
                'Selenium specifications "%s" not valid or '
                "corresponding WebDriver not installed: %s" % (selenium_specs, str(e))
            )

        from selenium.webdriver import Remote

        if webdriver_class is Remote:
            if not (os.environ.get("REMOTE_USER") and os.environ.get("REMOTE_KEY")):
                raise self.failureException(
                    "Both REMOTE_USER and REMOTE_KEY environment variables are required for remote tests."
                )
            capabilities = self._get_remote_capabilities(selenium_specs)
            capabilities["name"] = self.id()
            auth = "%(REMOTE_USER)s:%(REMOTE_KEY)s" % os.environ
            hub = os.environ.get("REMOTE_HUB", "ondemand.saucelabs.com:80")
            self.selenium = Remote(
                command_executor="http://%s@%s/wd/hub" % (auth, hub), desired_capabilities=capabilities
            )
        else:
            self.selenium = webdriver_class()

        super(AdminSeleniumWebDriverTestCase, self).setUp()

    def tearDown(self):
        if hasattr(self, "selenium"):
            from selenium.webdriver import Remote

            if isinstance(self.selenium, Remote):
                self._report_sauce_pass_fail()
            self.selenium.quit()
        super(AdminSeleniumWebDriverTestCase, self).tearDown()

    def _report_sauce_pass_fail(self):
        # Sauce Labs has no way of knowing if the test passed or failed, so we
        # let it know.
        base64string = base64.encodestring("%s:%s" % (os.environ.get("REMOTE_USER"), os.environ.get("REMOTE_KEY")))[:-1]
        result = json.dumps({"passed": sys.exc_info() == (None, None, None)})
        url = "/rest/v1/%s/jobs/%s" % (os.environ.get("REMOTE_USER"), self.selenium.session_id)
        connection = httplib.HTTPConnection("saucelabs.com")
        connection.request("PUT", url, result, headers={"Authorization": "Basic %s" % base64string})
        result = connection.getresponse()
        return result.status == 200

    def wait_until(self, callback, timeout=10):
        """
        Helper function that blocks the execution of the tests until the
        specified callback returns a value that is not falsy. This function can
        be called, for example, after clicking a link or submitting a form.
        See the other public methods that call this function for more details.
        """
        from selenium.webdriver.support.wait import WebDriverWait

        WebDriverWait(self.selenium, timeout).until(callback)

    def wait_loaded_tag(self, tag_name, timeout=10):
        """
        Helper function that blocks until the element with the given tag name
        is found on the page.
        """
        self.wait_until(lambda driver: driver.find_element_by_tag_name(tag_name), timeout)

    def wait_page_loaded(self):
        """
        Block until page has started to load.
        """
        from selenium.common.exceptions import TimeoutException

        try:
            # Wait for the next page to be loaded
            self.wait_loaded_tag("body")
        except TimeoutException:
            # IE7 occasionnally returns an error "Internet Explorer cannot
            # display the webpage" and doesn't load the next page. We just
            # ignore it.
            pass

    def admin_login(self, username, password, login_url="/admin/"):
        """
        Helper function to log into the admin.
        """
        self.selenium.get("%s%s" % (self.live_server_url, login_url))
        username_input = self.selenium.find_element_by_name("username")
        username_input.send_keys(username)
        password_input = self.selenium.find_element_by_name("password")
        password_input.send_keys(password)
        login_text = _("Log in")
        self.selenium.find_element_by_xpath('//input[@value="%s"]' % login_text).click()
        self.wait_page_loaded()

    def get_css_value(self, selector, attribute):
        """
        Helper function that returns the value for the CSS attribute of an
        DOM element specified by the given selector. Uses the jQuery that ships
        with Django.
        """
        return self.selenium.execute_script('return django.jQuery("%s").css("%s")' % (selector, attribute))

    def get_select_option(self, selector, value):
        """
        Returns the <OPTION> with the value `value` inside the <SELECT> widget
        identified by the CSS selector `selector`.
        """
        from selenium.common.exceptions import NoSuchElementException

        options = self.selenium.find_elements_by_css_selector("%s > option" % selector)
        for option in options:
            if option.get_attribute("value") == value:
                return option
        raise NoSuchElementException('Option "%s" not found in "%s"' % (value, selector))

    def assertSelectOptions(self, selector, values):
        """
        Asserts that the <SELECT> widget identified by `selector` has the
        options with the given `values`.
        """
        options = self.selenium.find_elements_by_css_selector("%s > option" % selector)
        actual_values = []
        for option in options:
            actual_values.append(option.get_attribute("value"))
        self.assertEqual(values, actual_values)

    def has_css_class(self, selector, klass):
        """
        Returns True if the element identified by `selector` has the CSS class
        `klass`.
        """
        return self.selenium.find_element_by_css_selector(selector).get_attribute("class").find(klass) != -1
コード例 #37
0
class TakeScreenshotScenarioTestCase(BrowserTestCase):
    def setUp(self):
        self.current_directory = os.path.dirname(os.path.abspath(__file__))

        super(TakeScreenshotScenarioTestCase, self).setUp()

    def tearDown(self):
        self.driver.quit()
        try:
            os.remove(self.screenshot1)
        except (OSError, AttributeError):
            pass

        try:
            os.remove(self.screenshot2)
        except (OSError, AttributeError):
            pass

        super(TakeScreenshotScenarioTestCase, self).tearDown()

    def test_scenario_firefox(self):
        self.driver = Remote(
            desired_capabilities=DesiredCapabilities.FIREFOX,
            command_executor="http://{host}:{port}/wd/hub".format(host=Config.server, port=Config.port),
        )
        dali = Dali(self.driver)

        # driver can navigate through himself
        self.driver.get(self.page_url("colored"))
        self.screenshot1 = dali.take_screenshot(resolution="800x600", path_to_save=self.current_directory)

        # and we can use scenario with preset resolution
        def scenario(driver):
            driver.get(self.page_url("colored"))

        self.screenshot2 = dali.take_screenshot(
            resolution="800x600", scenario=scenario, scenario_args=self.driver, path_to_save=self.current_directory
        )

        self.assertTrue(os.path.exists(self.screenshot1))
        self.assertTrue(os.path.exists(self.screenshot2))

        image1 = Image.open(self.screenshot1)
        image2 = Image.open(self.screenshot2)

        matrix1 = numpy.asarray(image1)
        matrix2 = numpy.asarray(image2)

        numpy.testing.assert_array_equal(matrix1, matrix2)

    def test_scenario_chrome(self):
        self.driver = Remote(
            desired_capabilities=DesiredCapabilities.CHROME,
            command_executor="http://{host}:{port}/wd/hub".format(host=Config.server, port=Config.port),
        )
        dali = Dali(self.driver)

        # driver can navigate through himself
        self.driver.get(self.page_url("colored"))
        self.screenshot1 = dali.take_screenshot(resolution="800x600", path_to_save=self.current_directory)

        # and we can use scenario with preset resolution
        def scenario(driver):
            driver.get(self.page_url("colored"))

        self.screenshot2 = dali.take_screenshot(
            resolution="800x600", scenario=scenario, scenario_args=self.driver, path_to_save=self.current_directory
        )

        self.assertTrue(os.path.exists(self.screenshot1))
        self.assertTrue(os.path.exists(self.screenshot2))

        image1 = Image.open(self.screenshot1)
        image2 = Image.open(self.screenshot2)

        matrix1 = numpy.asarray(image1)
        matrix2 = numpy.asarray(image2)

        numpy.testing.assert_array_equal(matrix1, matrix2)

    @unittest.expectedFailure
    def test_scenario_opera(self):
        self.driver = Remote(
            desired_capabilities=DesiredCapabilities.OPERA,
            command_executor="http://{host}:{port}/wd/hub".format(host=Config.server, port=Config.port),
        )
        dali = Dali(self.driver)

        # driver can navigate through himself
        self.driver.get(self.page_url("colored"))
        self.screenshot1 = dali.take_screenshot(resolution="800x600", path_to_save=self.current_directory)

        # and we can use scenario with preset resolution
        def scenario(driver):
            driver.get(self.page_url("colored"))

        self.screenshot2 = dali.take_screenshot(
            resolution="800x600", scenario=scenario, scenario_args=self.driver, path_to_save=self.current_directory
        )

        self.assertTrue(os.path.exists(self.screenshot1))
        self.assertTrue(os.path.exists(self.screenshot2))

        image1 = Image.open(self.screenshot1)
        image2 = Image.open(self.screenshot2)

        matrix1 = numpy.asarray(image1)
        matrix2 = numpy.asarray(image2)

        numpy.testing.assert_array_equal(matrix1, matrix2)

    def test_scenario_internetexplorer(self):
        self.driver = Remote(
            desired_capabilities=DesiredCapabilities.INTERNETEXPLORER,
            command_executor="http://{host}:{port}/wd/hub".format(host=Config.server, port=Config.port),
        )
        dali = Dali(self.driver)

        # driver can navigate through himself
        self.driver.get(self.page_url("colored"))
        self.screenshot1 = dali.take_screenshot(resolution="800x600", path_to_save=self.current_directory)

        # and we can use scenario with preset resolution
        def scenario(driver):
            driver.get(self.page_url("colored"))

        self.screenshot2 = dali.take_screenshot(
            resolution="800x600", scenario=scenario, scenario_args=self.driver, path_to_save=self.current_directory
        )

        self.assertTrue(os.path.exists(self.screenshot1))
        self.assertTrue(os.path.exists(self.screenshot2))

        image1 = Image.open(self.screenshot1)
        image2 = Image.open(self.screenshot2)

        matrix1 = numpy.asarray(image1)
        matrix2 = numpy.asarray(image2)

        numpy.testing.assert_array_equal(matrix1, matrix2)
コード例 #38
0
ファイル: browser.py プロジェクト: shoptime/trex
class Browser(object):
    def __init__(self, harness, selenium_server_url, selenium_browser, width=1024, height=600):
        self.harness = harness
        self.selenium_server_url = selenium_server_url
        self.selenium_browser = selenium_browser
        self.width = width
        self.height = height

        self.selenium = Remote(
            self.selenium_server_url.encode('ascii'),
            desired_capabilities = {
                'browserName': self.selenium_browser,
            },
        )
        self.selenium.set_window_size(width, height)

    def __enter__(self):
        self.harness.browser_stack.append(self)
        return self

    def __exit__(self, type, value, traceback):
        if self.harness.browser_stack[-1] != self:
            raise Exception("Unexpected browser on the top of the stack")
        self.harness.browser_stack.pop()
        return

    def shutdown(self):
        self.selenium.quit()

    def back(self):
        self.selenium.back()

    def refresh(self):
        self.selenium.refresh()

    def title(self):
        return self.selenium.title

    def source(self):
        return self.selenium.page_source

    def get(self, uri):
        self.selenium.get(uri)

    def find(self, selector):
        return WebElementSet(self, elements=self.selenium).find(selector)

    def add_cookie(self, cookie_dict):
        self.selenium.add_cookie(cookie_dict)

    def get_cookie(self, name):
        return self.selenium.get_cookie(name)

    def endpoint(self):
        return self.find('html').attr('id').replace('endpoint-', '').replace('-', '.')

    def endpoint_is(self, endpoint):
        is_equal(self.endpoint(), endpoint, "Endpoint is correct")

    def wait_for_bootstrap_modal(self):
        last = [None]

        def inner_wait(driver):
            value = self.find('.modal')[-1].css('top')
            if last[0] and last[0] == value:
                return True
            last[0] = value
            return False
        WebDriverWait(self.selenium, 3).until(inner_wait)
        return self

    def url(self):
        return furl(self.selenium.current_url)

    def execute_script(self, script):
        return self.selenium.execute_script(script)

    def wait_for_ajax(self):
        WebDriverWait(self.selenium, 10).until_not(lambda x: x.execute_script('return jQuery.active'))
        return self

    def wait_for_jquery(self):
        WebDriverWait(self.selenium, 10).until(lambda x: x.execute_script('return window.jQuery ? true : false'))
        return self

    def screenshot(self, message="Screenshot: "):
        if 's3_access_key' not in app.settings.options('test'):
            print "No screenshot S3 instance configured - skipping screenshot"
            return

        if not hasattr(self, 's3_connection'):
            if 's3_host' in app.settings.options('test'):
                self.s3_connection = boto.s3.connection.S3Connection(
                    app.settings.get('test', 's3_access_key'),
                    app.settings.get('test', 's3_secret_key'),
                    host = app.settings.get('test', 's3_host'),
                )
            else:
                self.s3_connection = boto.s3.connection.S3Connection(
                    app.settings.get('test', 's3_access_key'),
                    app.settings.get('test', 's3_secret_key'),
                )

        bucket = self.s3_connection.get_bucket(app.settings.get('test', 's3_bucket'))
        filename = "%s-%s.png" % (token.create_url_token(), self.harness.current_test_object.__class__.__name__)

        key = bucket.new_key(filename)
        key.metadata['Content-Type'] = 'image/png'
        key.metadata['Cache-Control'] = 'public, max-age=86400'
        key.set_contents_from_string(self.selenium.get_screenshot_as_png())
        key.make_public()
        print "%s%s" % (message, key.generate_url(expires_in=0, query_auth=False))
コード例 #39
0
#coding=utf-8
from selenium.webdriver import Remote
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

driver = Remote(
    command_executor='http://127.0.0.1:4444/wd/hub',
    #desired_capabilities=DesiredCapabilities.CHROME
    desired_capabilities={
                    'platform':'ANY',
                    'browserName':'chrome',
                    'version':'',
                    'javascriptEnabled':True
                }
                
    )
driver.get('http://www.baidu.com')
driver.quit()
コード例 #40
0
class selenium_scaner():
    links = dict()

    current_page = ""
    current_submit_button = 0
    current_submit_input = 0

    def __init__(self):
        browser = os.environ.get('TTHA2BROWSER', 'CHROME')

        self.driver = Remote(
            command_executor='http://127.0.0.1:4444/wd/hub',
            desired_capabilities=getattr(DesiredCapabilities, browser).copy()
        )
        self.driver.maximize_window()

    def check_xss(self):
        problems_found = False
        problems = self.wait_and_find_many(XSS_SELECTOR)
        for i in problems:
            problems_found = True
            file_logger().trace("Most likely XSS found.\n"+
                        "Xss script was found in page\n"+
                        "Outputing page source code to file", LOG_XSS)
            file_logger().print_to_file(self.current_page + "\n" + self.driver.page_source + "\n\n")
            break
        if not problems_found:
            if self.driver.page_source.find(XSS_BLOCK) >= 0:
                file_logger().trace("Potential XSS found.\n"+
                            "Xss script was found in page\n"+
                            "Outputing page source code to file", LOG_XSS)
                file_logger().print_to_file(self.current_page + "\n" + self.driver.page_source + "\n\n")

        pass


    def check_page(self):
        self.current_submit_button = -1
        self.current_submit_input = -1

        inputs_checked = False
        submits_checked = False

        while ((not inputs_checked) or (not submits_checked)):
            text_input_fields = self.wait_and_find_many('input[type="text"]')
            password_input_fields = self.wait_and_find_many('input[type="password"]')
            text_areas = self.wait_and_find_many('textarea')
            submit_inputs = self.wait_and_find_many('input[type="submit"]')
            submit_buttons = self.wait_and_find_many('button[type="submit"]')

            for i in text_input_fields:
                i.send_keys(XSS_BLOCK)

            for i in password_input_fields:
                i.send_keys(XSS_BLOCK)

            for i in text_areas:
                i.send_keys(XSS_BLOCK)

            inputs_checked = True
            for i in submit_inputs:
                if i > self.current_submit_input:
                    self.current_submit_input = i
                    inputs_checked = False
                    i.click()

            if inputs_checked == True:
                submits_checked = True
                for i in submit_buttons:
                    if i >= self.current_submit_button:
                        self.current_submit_button = i
                        submits_checked = False
                        i.click()

            self.check_xss()
            self.driver.get(self.current_page)



    def visit_page(self, target):
        found_new_page = False
        file_logger().trace("visit " + target, LOG_PROGRESS)
        self.current_page = target
        self.driver.get(target)
        results = self.wait_and_find_many("a[href]")

        for i in results:
            link = i.get_attribute("href")
            if not (link in self.links):
                found_new_page = True
                self.links[link] = False

        self.check_page()

        self.links[target] = True
        return found_new_page


    def scan_site_with_selenium(self, target):
        self.target = target
        self.visit_page(target)

        not_all_links_checked = True
        while not_all_links_checked:
            not_all_links_checked = False
            for i in self.links:
                if self.links[i] == False:
                    not_all_links_checked = True
                    if self.visit_page(i):
                        break
        self.stop_selenium()

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


    def wait_and_find_many(self, targetName):
        try:
            results =  WebDriverWait(self.driver, 0.1, 0.1).until(
               lambda d: d.find_elements_by_css_selector(targetName)
            )
        except Exception as exc:
            results = []
        return results