Ejemplo n.º 1
0
    def handle(self, *args, **options):
        xvfb = Xvfb(width=1600, height=720)
        xvfb.start()
        browser = WebDriver()
        browser.get(settings.DOMAIN)
        sleep(1)
        browser.find_element_by_css_selector("#disclaimer button").click()
        sleep(0.7)
        browser.find_elements_by_css_selector(".officer .checkmark")[4].click()
        sleep(2)
        browser.find_element_by_css_selector(
            ".complaint-row .col-md-3").click()
        sleep(1)
        content = browser.get_screenshot_as_png()
        now = datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S")
        file_name = "{now}.png".format(now=now)
        file_path = os.path.join(settings.BASE_DIR, 'static', file_name)
        with open(file_path, "wb") as f:
            f.write(content)
        browser.quit()

        email = EmailMessage(subject='CPDB Homepage screenshot %s' % now,
                             body='FYI',
                             to=['*****@*****.**'])
        email.attach_file(file_path)
        email.send()
        xvfb.stop()
Ejemplo n.º 2
0
 def _open_otp_assistant(webdriver: WebDriver):
     """
     Open the OTP Assistant
     """
     webdriver.find_element_by_css_selector(
         'div#id_get_totp_secret_length a[data-assistant-id="otp-assistant"]'
     ).click()
     webdriver.switch_to.window('otpAssistant')
Ejemplo n.º 3
0
 def _open_new_user_form(self, webdriver: WebDriver):
     """
     Click to the new user form
     """
     self.assertEqual(
         '{}/admin/hub_app/hubuser/'.format(self.live_server_url),
         webdriver.current_url)
     webdriver.find_element_by_css_selector(
         'ul.object-tools li a.addlink').click()
Ejemplo n.º 4
0
 def _navigate_to_user_overview(self, webdriver: WebDriver):
     """
     Go to the User Model Overview Page
     """
     self.assertEqual('{}/admin/'.format(self.live_server_url),
                      webdriver.current_url)
     webdriver.find_element_by_css_selector(
         'table caption a[href="/admin/hub_app/"]').click()
     webdriver.find_element_by_css_selector(
         'table tr td a[href="/admin/hub_app/hubuser/"]').click()
Ejemplo n.º 5
0
 def _fill_new_user_form(self, webdriver: WebDriver):
     """
     Fill the new user form
     """
     self.assertEqual(
         '{}/admin/hub_app/hubuser/add/'.format(self.live_server_url),
         webdriver.current_url)
     webdriver.find_element_by_id('id_username').send_keys(self.test_user)
     webdriver.find_element_by_id('id_password1').send_keys(
         self.test_password)
     webdriver.find_element_by_id('id_password2').send_keys(
         self.test_password)
     webdriver.find_element_by_css_selector(
         'input[type="submit"][name="_continue"]').click()
Ejemplo n.º 6
0
def decline_offer(offer_reference):
    driver = WebDriver()

    # Login
    selenium_login(webdriver=driver)

    # Decline offer
    driver.get('https://www.odesk.com/applications/%s' % offer_reference)
    driver.find_element_by_id("declineButton").click()
    driver.find_element_by_css_selector("option[value=\"146\"]").click()
    driver.find_element_by_id("otherReason").clear()
    driver.find_element_by_id("otherReason").send_keys("Test")
    driver.find_element_by_xpath("(//a[contains(text(),'Decline')])[2]").click()

    driver.close()
Ejemplo n.º 7
0
def test_can_mark_todo_as_not_complete(driver: WebDriver, app_with_temp_db):
    driver.get('http://localhost:5000/')
    click_todo_checkbox(driver, todo_name="test")

    is_checked = driver.find_element_by_css_selector(f'[aria-label="todo test checkbox"]').is_selected()

    assert is_checked == False
Ejemplo n.º 8
0
def test_add_todo(driver: WebDriver, app_with_temp_db):
    driver.get('http://localhost:5000/')
    add_todo(driver, todo_name="test")

    new_todo = driver.find_element_by_css_selector('[aria-label="todo test label"]')
    assert new_todo.text == 'test'
    assert driver.title == 'To-Do App'
Ejemplo n.º 9
0
class TestGroup(unittest.TestCase):

    def setUp(self):
        self.wd = WebDriver()
        self.wd.implicitly_wait(60)
    
    def test_create_group(self):
        """Validation of correct create test group"""
        success = True
        wd = self.wd
        wd.get("http://localhost/addressbook/group.php")
        wd.find_element_by_name("user").click()
        wd.find_element_by_name("user").clear()
        wd.find_element_by_name("user").send_keys("admin")
        wd.find_element_by_id("LoginForm").click()
        wd.find_element_by_name("pass").click()
        wd.find_element_by_name("pass").clear()
        wd.find_element_by_name("pass").send_keys("secret")
        wd.find_element_by_css_selector("input[type=\"submit\"]").click()
        wd.find_element_by_name("new").click()
        wd.find_element_by_name("group_name").click()
        wd.find_element_by_name("group_name").clear()
        wd.find_element_by_name("group_name").send_keys("test")
        wd.find_element_by_name("group_header").click()
        wd.find_element_by_name("group_header").clear()
        wd.find_element_by_name("group_header").send_keys("test")
        wd.find_element_by_name("group_footer").click()
        wd.find_element_by_name("group_footer").clear()
        wd.find_element_by_name("group_footer").send_keys("test")
        wd.find_element_by_name("submit").click()
        wd.find_element_by_css_selector("div.msgbox").click()
        wd.find_element_by_link_text("group page").click()
        self.assertTrue(success)
    
    def tearDown(self):
        success = True
        # We should delete all created test form
        self.wd.find_element_by_link_text("groups").click()
        self.wd.find_element_by_css_selector("span.group").click()
        if not self.wd.find_element_by_name("selected[]").is_selected():
            self.wd.find_element_by_name("selected[]").click()
        self.wd.find_element_by_xpath("//div[@id='content']/form/input[5]").click()
        self.wd.find_element_by_link_text("Logout").click()
        self.assertTrue(success)
        self.wd.quit()
Ejemplo n.º 10
0
def add_odesk_teams(user):
    """
        Creates oDesk teams that will be used for our jobs.
    """
    driver = WebDriver()
    driver.implicitly_wait(time_to_wait=10)

    selenium_login(webdriver=driver)
    account = user.get_profile()

    # Gain access to settings
    driver.find_element_by_css_selector("a.oNavIcon.oNavIconSettings").click()
    driver.find_element_by_id("answer").clear()
    driver.find_element_by_id("answer").send_keys(settings.ODESK_TEST_ACC_ANSWER)
    driver.find_element_by_id("submitButton").click()

    sg_name = SAMPLE_GATHERING_TEAM % TEAM_PREFIX
    v_name = VOTING_TEAM % TEAM_PREFIX
    btmg_name = BTM_GATHERING_TEAM % TEAM_PREFIX
    btmv_name = BTM_VOTING_TEAM % TEAM_PREFIX

    sg_res = add_odesk_team(webdriver=driver, name=sg_name)
    v_res = add_odesk_team(webdriver=driver, name=v_name)
    btmg_res = add_odesk_team(webdriver=driver, name=btmg_name)
    btmv_res = add_odesk_team(webdriver=driver, name=btmv_name)

    if not all([sg_res, v_res, btmg_res, btmv_res]):
        log.warning('[oDesk] Failed to create oDesk teams.')
        return False

    client = make_client_from_account(account)
    teams = client.hr.get_teams()

    for team in teams:
        if team['name'] == sg_name:
            account.odesk_teams[JOB_SAMPLE_GATHERING_KEY] = team['reference']
        elif team['name'] == v_name:
            account.odesk_teams[JOB_VOTING_KEY] = team['reference']
        elif team['name'] == btmg_name:
            account.odesk_teams[JOB_BTM_GATHERING_KEY] = team['reference']
        elif team['name'] == btmv_name:
            account.odesk_teams[JOB_BTM_VOTING_KEY] = team['reference']
    account.save()
    return True
Ejemplo n.º 11
0
class UITestCase(LiveServerTestCase):
    def use_xvfb(self):
        from pyvirtualdisplay import Display
        self.display = Display('xvfb',
                               visible=1,
                               size=(1280, 1024))
        self.display.start()
        self.driver = WebDriver()

    def setUp(self):
        try:
            self.driver = WebDriver()
            ui_is_not_available = False
        except WebDriverException:
            ui_is_not_available = True

        if ui_is_not_available:
            self.use_xvfb()

        self.driver.implicitly_wait(10)
        super(UITestCase, self).setUp()

    def tearDown(self):
        self.driver.quit()
        if hasattr(self, 'display'):
            self.display.stop()

        super(UITestCase, self).tearDown()

    def _process_login_form(self, username, password):
        username_elmt = self.driver.find_element_by_name('username')
        password_elmt = self.driver.find_element_by_name('password')

        username_elmt.send_keys(username)
        password_elmt.send_keys(password)

        submit = self.driver.find_element_by_css_selector('form * button')
        submit.click()

    def _browse_to_url(self, url):
        self.driver.get(self.live_server_url + url)

    def find_anchor_by_url(self, url):
        return self.driver.find_element_by_css_selector("[href='%s']" % url)
Ejemplo n.º 12
0
 def _check_current_secret(self, webdriver: WebDriver, equal: bool):
     """
     Check the Secret that is stored in DB
     """
     assistant_field = webdriver.find_element_by_css_selector(
         'div[data-user-field="secret"]')
     code = assistant_field.find_element_by_tag_name('code')
     if equal:
         self.assertEqual(self.test_secret, b32decode(code.text))
     else:
         self.assertNotEqual(self.test_secret, b32decode(code.text))
def get_links_on_mobile_website(driver: WebDriver) -> List[str]:
    page_num = 0
    outer_html = ""
    driver.get(mobile_website_url)

    try:
        while True:
            driver.find_element_by_css_selector('#btn_showmore').click()
            page_num += 1
            print(f'getting page number {str(page_num)}')
            time.sleep(1)
            outer_html_new = driver.execute_script("return document.documentElement.outerHTML")
            if outer_html == outer_html_new:
                break
            outer_html = outer_html_new
    except Exception as e:
        print('Aborting page load:', e)
    new_links = get_links_from_driver(driver)
    print(f'Found {len(new_links)} links on mobile')
    return new_links
Ejemplo n.º 14
0
 def _login_to_admin(self, webdriver: WebDriver):
     """
     Login to admin
     """
     webdriver.get('{}/admin/'.format(self.live_server_url))
     form = webdriver.find_element_by_css_selector(
         'form[data-ui-relevance="main-login"]')
     form.find_element_by_css_selector('input[name="username"]').send_keys(
         self.admin_username)
     form.find_element_by_css_selector('input[name="password"]').send_keys(
         self.admin_password)
     form.find_element_by_css_selector('input[name="otp"]').send_keys(
         str(get_otp(self.admin_secret)))
     form.find_element_by_css_selector('button[type="submit"]').click()
Ejemplo n.º 15
0
class Fox(object):
    '''
    Fox is an abstraction around Selenium web testing
    '''
    def __init__(self):
        try:
            self.fox = WebDriver()
        except:
            print "No web server detected; skipping web tests"
            self.fox = None

    def login(self, page='/login', name='josh', password='******', t=5):
        self.get(page)
        WebDriverWait(self.fox, t).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[name=username]'))).send_keys(name)
        WebDriverWait(self.fox, t).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[name=password]'))).send_keys(password)
        WebDriverWait(self.fox, t).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'input'))).click()

    def get(self, i):
        return self.fox.get(i)

    def click(self, css, t=5):
        return WebDriverWait(self.fox, t).until(EC.element_to_be_clickable((By.CSS_SELECTOR, css))).click()

    def clickx(self, xpath, t=5):
        return WebDriverWait(self.fox, t).until(EC.element_to_be_clickable((By.XPATH, xpath))).click()

    def click_last(self, css):
        e = self.fox.find_elements_by_css_selector('.modal-open .btn-primary')[-1]
        return e.click()

    def val(self, css, val, t=5):
        return WebDriverWait(self.fox, t).until(EC.element_to_be_clickable((By.CSS_SELECTOR, css))).send_keys(val)

    def fill(self, form, field, value):
        css = '#{} [name={}]'.format(form, field)
        return self.val(css, value)

    def form(self, form, values):
        for k, v in values:
            self.fill(form, k, v)

    def wait_for_destroy(self, css, t=5):
        element = self.fox.find_element_by_css_selector(css)
        return WebDriverWait(self.fox, t).until(EC.staleness_of(element))

    def close(self):
        if not self.fox:
            return
        self.fox.quit()
Ejemplo n.º 16
0
def send_offer(cipher, job_reference, client, buyer_reference,
        worker_reference):
    driver = WebDriver()
    driver.implicitly_wait(time_to_wait=10)

    # Login
    selenium_login(webdriver=driver)

    # Worker's page
    driver.get('https:/www.odesk.com/users/%s' % cipher)
    driver.find_element_by_link_text("Contact").click()

    # Make an offer link
    driver.find_element_by_id("jsMakeOfferLink").click()
    el = driver.find_element_by_css_selector("#jsTeamSelector > select")
    el.find_element_by_css_selector("option[value=\"%s\"]" % buyer_reference).\
        click()
    driver.find_element_by_id("jsMakeOfferProceed").click()

    # Sign in to make an offer
    driver.find_element_by_id("password").clear()
    driver.find_element_by_id("password").send_keys(settings.ODESK_TEST_ACC_PASS)
    try:
        driver.find_element_by_id("answer").clear()
        driver.find_element_by_id("answer").send_keys(settings.ODESK_TEST_ACC_ANSWER)
    except selenium.exceptions.NoSuchElementException:
        pass
    driver.find_element_by_id("submitButton").click()

    # Make an offer form
    driver.find_element_by_id("useExistingJob-yes").click()
    el = driver.find_element_by_id("jobPosting")
    el.find_element_by_css_selector("option[value=\"%s\"]" % job_reference).\
        click()
    driver.find_element_by_id("employerRate").clear()
    driver.find_element_by_id("employerRate").send_keys("0.01")
    driver.find_element_by_id("setLimit-yes").click()
    driver.find_element_by_id("limit").clear()
    driver.find_element_by_id("limit").send_keys("0")
    driver.find_element_by_id("submitButton").click()

    # Agreement
    driver.find_element_by_id("agreement").click()
    driver.find_element_by_id("submitButton").click()

    driver.close()
Ejemplo n.º 17
0
class JavaScriptTestCase(unittest.TestCase):

    def setUp(self):
        self.selenium = WebDriver()
        self.selenium.implicitly_wait(1) # wait one second before failing to find

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

    def test_catalogue_extender_required(self):
        self.selenium.get(self._load('test_catalogue_extender_required'))
        self.assert_zero_failures()

    def _load(self, page):
        return 'file://' + opath.join(opath.dirname(__file__), 'qunit', page+'.html')

    def assert_zero_failures(self):
        elem = self.selenium.find_element_by_css_selector('#qunit-testresult span.failed')
        self.assertTrue(int(elem.text) == 0, "Failures found: " + elem.text)
def syn_test_script():

    try:
        success = True
        driver = WebDriver()
        driver.implicitly_wait(30)
        # Disabled page sizing and instead used action chains to move mouse around
        #driver.set_window_size(1920, 1080)

        # Use Action chains to navigate page when there is an issue with the selection menus
        # If the menu item does not appear to select, it means there was a page movement that happened
        # out of sync with the action.

        log_output(
            "Starting @ http://www.kay.com/en/kaystore/searchterm/731434000/true/731434000"
        )
        driver.get(
            "http://www.kay.com/en/kaystore/searchterm/731434000/true/731434000"
        )

        log_output("Click on first item to customize a ring - don't use /div")
        driver.find_element_by_partial_link_text(
            "Family/Mother's Ring Round Birthstones Design in Silver or Gold"
        ).click()

        log_output("Start customizing ring")
        driver.find_element_by_xpath(
            "//div[@class='m-vcb-content-html-modifier']//button[.='Start Customizing']"
        ).click()
        if not driver.find_element_by_xpath(
                "//select[@id='configSelect']//option[2]").is_selected():
            driver.find_element_by_xpath(
                "//select[@id='configSelect']//option[2]").click()
        driver.find_element_by_id("btnStartCustomizing").click()

        log_output("Step - Select Metal Type")
        if not driver.find_element_by_xpath(
                "//select[@id='metalTypeSelect']//option[2]").is_selected():
            driver.find_element_by_xpath(
                "//select[@id='metalTypeSelect']//option[2]").click()
        driver.find_element_by_id("next-step").click()

        log_output("Step - Stelect Stone Type")
        ActionChains(driver).move_to_element(
            driver.find_element_by_xpath(
                "//select[@id='stoneTypeSelect']")).perform()
        if not driver.find_element_by_xpath(
                "//select[@id='stoneTypeSelect']//option[2]").is_selected():
            driver.find_element_by_xpath(
                "//select[@id='stoneTypeSelect']//option[2]").click()

        log_output("Step - Click Next")
        ActionChains(driver).move_to_element(
            driver.find_element_by_xpath(
                "//div[@id='tab-stoneType']//a[.='Next']")).perform()
        driver.find_element_by_xpath("//div[@id='tab-stoneType']//a[.='Next']")
        driver.find_element_by_xpath(
            "//div[@id='tab-stoneType']//a[.='Next']").click()

        log_output("Step - Select Birth Stone")
        driver.find_element_by_css_selector("span.month_text").click()
        driver.find_element_by_xpath(
            "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/span[2]").click()
        driver.find_element_by_xpath(
            "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/span[1]").click()
        driver.find_element_by_xpath(
            "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/input").click()
        driver.find_element_by_xpath(
            "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/span[1]").click()
        if not driver.find_element_by_xpath(
                "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/input"
        ).is_selected():
            driver.find_element_by_xpath(
                "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/input").click(
                )
        driver.find_element_by_link_text("SELECT").click()
        driver.find_element_by_xpath(
            "//a[@id='tab-index-2']//span[.='Select a Stone']").click()
        driver.find_element_by_xpath(
            "//div[@id='tab-stones-2']/div/ul[2]/li[2]/label/span[2]").click()
        driver.find_element_by_xpath(
            "//div[@id='tab-stones-2']/div/ul[2]/li[2]/label/span[1]").click()
        driver.find_element_by_xpath(
            "//div[@id='tab-stones-2']/div/ul[2]/li[2]/label/input").click()
        driver.find_element_by_xpath(
            "//div[@id='tab-stones-2']/div/ul[2]/li[2]/label/span[1]").click()
        if not driver.find_element_by_xpath(
                "//div[@id='tab-stones-2']/div/ul[2]/li[2]/label/input"
        ).is_selected():
            driver.find_element_by_xpath(
                "//div[@id='tab-stones-2']/div/ul[2]/li[2]/label/input").click(
                )
        driver.find_element_by_link_text("SELECT").click()
        driver.find_element_by_xpath(
            "//div[@id='tab-stones']//a[.='Next']").click()

        log_output("Step - Select Ring Size")
        if not driver.find_element_by_xpath(
                "//select[@id='sizeSelect']//option[7]").is_selected():
            driver.find_element_by_xpath(
                "//select[@id='sizeSelect']//option[7]").click()
        driver.find_element_by_xpath(
            "//div[@id='tab-sizes']//a[.='Next']").click()

        log_output("Add to Cart and Checkout")
        driver.find_element_by_id("addToCart").click()
        driver.find_element_by_link_text("CHECKOUT").click()

    finally:
        driver.quit()
        if not success:
            raise Exception("Test failed.")
Ejemplo n.º 19
0
def syn_test_script():
    try:
        success = True
        driver = WebDriver()
        driver.implicitly_wait(30)
        # Disabled page sizing and instead used action chains to move mouse around
        # driver.set_window_size(1920, 1080)

        # Use Action chains to navigate page when there is an issue with the selection menus
        # If the menu item does not appear to select, it means there was a page movement that happened
        # out of sync with the action.

        log_output(
            "Starting @ http://www.kay.com/en/kaystore/searchterm/732541000/true/732541000"
        )
        driver.get(
            "http://www.kay.com/en/kaystore/searchterm/732541000/true/732541000"
        )

        log_output("Verify Search Results on page")
        html_text = driver.find_element_by_tag_name("html").text
        if not ("Home Search Results" in html_text):
            success = False
            print("verifyTextPresent failed")

        log_output("Click on first item - using div tag")
        driver.find_element_by_xpath(
            "//div[@id='product-grid']/div[1]/div/a/h3").click()

        log_output("Start customizing ring")
        driver.find_element_by_xpath(
            "//div[@class='m-vcb-content-html-modifier']//button[.='Start Customizing']"
        ).click()

        log_output("Choose number of stones and birth Stone")

        if not driver.find_element_by_xpath(
                "//select[@id='birthStoneSelect']//option[2]").is_selected():
            driver.find_element_by_xpath(
                "//select[@id='birthStoneSelect']//option[2]").click()
        driver.find_element_by_id("btnStartCustomizing").click()

        log_output("Step - Select Stone Type")
        ActionChains(driver).move_to_element(
            driver.find_element_by_css_selector("span.month_text")).perform()
        driver.find_element_by_css_selector("span.month_text").click()
        driver.find_element_by_xpath(
            "//div[@id='tab-stones-1']/div/ul/li[1]/label").click()
        if not driver.find_element_by_name("stoneId1").is_selected():
            driver.find_element_by_name("stoneId1").click()
        driver.find_element_by_link_text("SELECT").click()
        driver.find_element_by_xpath("//div[@id='cs']//a[.='Next']").click()

        log_output("Step - Select Metal Type")
        if not driver.find_element_by_xpath(
                "//select[@id='metalTypeSelect']//option[2]").is_selected():
            driver.find_element_by_xpath(
                "//select[@id='metalTypeSelect']//option[2]").click()
        log_output("clicking next")
        driver.find_element_by_xpath("//div[@id='m']//a[.='Next']").click()

        log_output("Step - Select ring size")
        if not driver.find_element_by_xpath(
                "//select[@id='sizeSelect']//option[2]").is_selected():
            driver.find_element_by_xpath(
                "//select[@id='sizeSelect']//option[2]").click()
        ActionChains(driver).move_to_element(
            driver.find_element_by_xpath(
                "//div[@id='rs']//a[.='Next']")).perform()
        next_click = driver.find_element_by_xpath(
            "//div[@id='rs']//a[.='Next']")
        next_click.click()
        ActionChains(driver).move_to_element(
            driver.find_element_by_xpath(
                "//div[@id='engr']//a[.='Next']")).perform()
        driver.find_element_by_xpath("//div[@id='engr']//a[.='Next']").click()

        log_output("Step - Add item to bag")
        driver.find_element_by_id("addToCart").click()
        # driver.find_element_by_link_text("ADD TO BAG").click()

        log_output("Step - Goto Checkout")
        driver.find_element_by_link_text("CHECKOUT").click()

        log_output("Verify text on page - Shopping Bag")
        html_text = driver.find_element_by_tag_name("html").text
        if not ("Shopping Bag" in html_text):
            success = False
            print("verifyTextPresent failed")

    finally:
        driver.quit()
        if not success:
            raise Exception("Test failed.")
Ejemplo n.º 20
0
def add_todo(driver: WebDriver, todo_name: str):
    todo_input = driver.find_element_by_css_selector('[aria-label="todo input box"]')
    todo_input.send_keys(todo_name)
    add_todo_button = driver.find_element_by_css_selector('[aria-label="add todo"]')
    add_todo_button.click()
Ejemplo n.º 21
0
class SeleniumRunner:
    """
    A runner that upload and download Icomoon resources using Selenium.
    The WebDriver will use Firefox.
    """

    """
    The long wait time for the driver in seconds.
    """
    LONG_WAIT_IN_SEC = 25

    """
    The medium wait time for the driver in seconds.
    """
    MED_WAIT_IN_SEC = 6

    """
    The short wait time for the driver in seconds.
    """
    SHORT_WAIT_IN_SEC = 0.6

    """
    The Icomoon Url.
    """
    ICOMOON_URL = "https://icomoon.io/app/#/select"

    def __init__(self, icomoon_json_path: str, download_path: str,
                 geckodriver_path: str, headless):
        """
        Create a SeleniumRunner object.
        :param icomoon_json_path: a path to the iconmoon.json.
        :param download_path: the location where you want to download
        the icomoon.zip to.
        :param geckodriver_path: the path to the firefox executable.
        :param headless: whether to run browser in headless (no UI) mode.
        """
        self.icomoon_json_path = icomoon_json_path
        self.download_path = download_path
        self.driver = None
        self.set_options(geckodriver_path, headless)

    def set_options(self, geckodriver_path: str, headless: bool):
        """
        Build the WebDriver with Firefox Options allowing downloads and
        set download to download_path.
        :param geckodriver_path: the path to the firefox executable.
        :param headless: whether to run browser in headless (no UI) mode.

        :raises AssertionError: if the page title does not contain
        "IcoMoon App".
        """
        options = Options()
        allowed_mime_types = "application/zip, application/gzip, application/octet-stream"
        # disable prompt to download from Firefox
        options.set_preference("browser.helperApps.neverAsk.saveToDisk", allowed_mime_types)
        options.set_preference("browser.helperApps.neverAsk.openFile", allowed_mime_types)

        # set the default download path to downloadPath
        options.set_preference("browser.download.folderList", 2)
        options.set_preference("browser.download.dir", self.download_path)
        options.headless = headless

        self.driver = WebDriver(options=options, executable_path=geckodriver_path)
        self.driver.get(self.ICOMOON_URL)
        assert "IcoMoon App" in self.driver.title

    def upload_icomoon(self):
        """
        Upload the icomoon.json to icomoon.io.
        :raises TimeoutException: happens when elements are not found.
        """
        print("Uploading icomoon.json file...")
        try:
            # find the file input and enter the file path
            import_btn = WebDriverWait(self.driver, SeleniumRunner.LONG_WAIT_IN_SEC).until(
                ec.presence_of_element_located((By.CSS_SELECTOR, "div#file input"))
            )
            import_btn.send_keys(self.icomoon_json_path)
        except Exception as e:
            self.close()
            raise e

        try:
            confirm_btn = WebDriverWait(self.driver, SeleniumRunner.MED_WAIT_IN_SEC).until(
                ec.element_to_be_clickable((By.XPATH, "//div[@class='overlay']//button[text()='Yes']"))
            )
            confirm_btn.click()
        except SeleniumTimeoutException as e:
            print(e.stacktrace)
            print("Cannot find the confirm button when uploading the icomoon.json",
                  "Ensure that the icomoon.json is in the correct format for Icomoon.io",
                  sep='\n')
            self.close()

        print("JSON file uploaded.")

    def upload_svgs(self, svgs: List[str]):
        """
        Upload the SVGs provided in folder_info
        :param svgs: a list of svg Paths that we'll upload to icomoon.
        """
        try:
            print("Uploading SVGs...")

            edit_mode_btn = self.driver.find_element_by_css_selector(
                "div.btnBar button i.icon-edit"
            )
            edit_mode_btn.click()

            self.click_hamburger_input()

            for svg in svgs:
                import_btn = self.driver.find_element_by_css_selector(
                    "li.file input[type=file]"
                )
                import_btn.send_keys(svg)
                print(f"Uploaded {svg}")
                self.test_for_possible_alert(self.SHORT_WAIT_IN_SEC, "Dismiss")
                self.remove_color_from_icon()

            self.click_hamburger_input()
            select_all_button = WebDriverWait(self.driver, self.LONG_WAIT_IN_SEC).until(
                ec.element_to_be_clickable((By.XPATH, "//button[text()='Select All']"))
            )
            select_all_button.click()
        except Exception as e:
            self.close()
            raise e

    def click_hamburger_input(self):
        """
        Click the hamburger input until the pop up menu appears. This
        method is needed because sometimes, we need to click the hamburger
        input two times before the menu appears.
        :return: None.
        """
        try:
            hamburger_input = self.driver.find_element_by_css_selector(
                "button.btn5.lh-def.transparent i.icon-menu"
            )

            menu_appear_callback = ec.element_to_be_clickable(
                (By.CSS_SELECTOR, "h1#setH2 ul")
            )

            while not menu_appear_callback(self.driver):
                hamburger_input.click()
        except Exception as e:
            self.close()
            raise e

    def test_for_possible_alert(self, wait_period: float, btn_text: str):
        """
        Test for the possible alert when we upload the svgs.
        :param wait_period: the wait period for the possible alert
        in seconds.
        :param btn_text: the text that the alert's button will have.
        :return: None.
        """
        try:
            dismiss_btn = WebDriverWait(self.driver, wait_period, 0.15).until(
                ec.element_to_be_clickable(
                    (By.XPATH, f"//div[@class='overlay']//button[text()='{btn_text}']"))
            )
            dismiss_btn.click()
        except SeleniumTimeoutException:
            pass

    def remove_color_from_icon(self):
        """
        Remove the color from the most recent uploaded icon.
        :return: None.
        """
        try:
            recently_uploaded_icon = WebDriverWait(self.driver, self.LONG_WAIT_IN_SEC).until(
                ec.element_to_be_clickable((By.XPATH, "//div[@id='set0']//mi-box[1]//div"))
            )
            recently_uploaded_icon.click()
        except Exception as e:
            self.close()
            raise e

        try:
            color_tab = WebDriverWait(self.driver, self.SHORT_WAIT_IN_SEC).until(
                ec.element_to_be_clickable((By.CSS_SELECTOR, "div.overlayWindow i.icon-droplet"))
            )
            color_tab.click()

            remove_color_btn = self.driver \
                .find_element_by_css_selector("div.overlayWindow i.icon-droplet-cross")
            remove_color_btn.click()
        except SeleniumTimeoutException:
            pass
        except Exception as e:
            self.close()
            raise e

        try:
            close_btn = self.driver \
                .find_element_by_css_selector("div.overlayWindow i.icon-close")
            close_btn.click()
        except Exception as e:
            self.close()
            raise e

    def download_icomoon_fonts(self, zip_path: Path):
        """
        Download the icomoon.zip from icomoon.io.
        :param zip_path: the path to the zip file after it's downloaded.
        """
        try:
            print("Downloading Font files...")
            self.driver.find_element_by_css_selector(
                "a[href='#/select/font']"
            ).click()

            self.test_for_possible_alert(self.MED_WAIT_IN_SEC, "Continue")
            download_btn = WebDriverWait(self.driver, SeleniumRunner.LONG_WAIT_IN_SEC).until(
                ec.presence_of_element_located((By.CSS_SELECTOR, "button.btn4 span"))
            )
            download_btn.click()
            if self.wait_for_zip(zip_path):
                print("Font files downloaded.")
            else:
                raise TimeoutError(f"Couldn't find {zip_path} after download button was clicked.")
        except Exception as e:
            self.close()
            raise e

    def wait_for_zip(self, zip_path: Path) -> bool:
        """
        Wait for the zip file to be downloaded by checking for its existence
        in the download path. Wait time is self.LONG_WAIT_IN_SEC and check time
        is 1 sec.
        :param zip_path: the path to the zip file after it's
        downloaded.
        :return: True if the file is found within the allotted time, else
        False.
        """
        end_time = time.time() + self.LONG_WAIT_IN_SEC
        while time.time() <= end_time:
            if zip_path.exists():
                return True
            time.sleep(1)    
        return False

    def close(self):
        """
        Close the SeleniumRunner instance.
        """
        print("Closing down SeleniumRunner...")
        self.driver.quit()
Ejemplo n.º 22
0
class WStoreSeleniumTestCase(TestCase, LiveServerTestCase):

    fixtures = ['selenium_basic.json']

    @classmethod
    def setUpClass(cls):
        super(WStoreSeleniumTestCase, cls).setUpClass()

    def setUp(self):
        # Open the page
        self.driver = WebDriver()
        self.driver.implicitly_wait(5)
        self.driver.set_window_size(1024, 768)
        self.driver.get(self.live_server_url)
        TestCase.setUp(self)

    def _check_container(self, container, offering_names):
        # Check offerings container
        container = self.driver.find_element_by_class_name(container)
        offering_elems = container.find_elements_by_class_name('menu-offering')
        self.assertEquals(len(offering_elems), len(offering_names))

        for off_elem in offering_elems:
            title = off_elem.find_element_by_css_selector('h2')
            self.assertTrue(title.text in offering_names)

    def login(self, username='******'):
        # Set username
        username_elem = self.driver.find_element_by_name('username')
        username_elem.send_keys(username)

        # Set password
        password_elem = self.driver.find_element_by_name('password')
        password_elem.send_keys('admin')

        # Click login
        self.driver.find_element_by_css_selector('#login-form button').click()

    def oauth2_login(self, username='******'):
        from wstore.selenium_tests.tests import TESTING_PORT
        self.driver.get(
            self.live_server_url +
            '/oauth2/auth?response_type=code&client_id=test_app&redirect_uri=http://localhost:'
            + unicode(TESTING_PORT))

        self.login(username)

        self.driver.find_element_by_class_name('btn-blue').click()
        time.sleep(1)

        # Get authorization code
        while self._server.call_received() < 1:
            pass

        code = self._server.get_path().split('=')[1]

        # Get access token
        opener = urllib2.build_opener()

        url = self.live_server_url + '/oauth2/token'

        data = 'client_id=test_app'
        data += '&client_secret=secret'
        data += '&grant_type=authorization_code'
        data += '&code=' + code
        data += '&redirect_uri=' + 'http://localhost:' + unicode(TESTING_PORT)

        headers = {
            'content-type': 'application/form-url-encoded',
        }
        request = MethodRequest('POST', url, data, headers)

        response = opener.open(request)

        token = json.loads(response.read())['access_token']

        return token

    def logout(self):
        self.driver.find_element_by_class_name(
            'icon-double-angle-down').click()
        options = self.driver.find_elements_by_css_selector(
            '#settings-menu > li')

        options[-1].click()

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

    def back(self):
        self.driver.find_element_by_id('back').click()

    def view_all(self):
        self.driver.find_element_by_css_selector('#all').click()

    def search_keyword(self, keyword, id_='#text-search', btn='#search'):
        # Set search field
        search_elem = self.driver.find_element_by_css_selector(id_)
        search_elem.send_keys(keyword)

        # Click search button
        self.driver.find_element_by_css_selector(btn).click()

    def open_offering_details(self, offering_name):

        elements = self.driver.find_elements_by_class_name('menu-offering')

        for element in elements:
            if element.find_element_by_css_selector(
                    'h2').text == offering_name:
                element.click()
                break

    def _get_navs(self):
        submenu = self.driver.find_element_by_class_name('store-sub-menu')
        # Get first element
        return submenu.find_elements_by_css_selector('li')

    def click_first_cat(self):
        self.driver.find_element_by_id('menu-first-text').click()

    def click_second_cat(self):
        self.driver.find_element_by_id('menu-second-text').click()

    def click_third_cat(self):
        self.driver.find_element_by_id('menu-third-text').click()

    def click_first_nav(self):
        self._get_navs()[0].click()

    def click_second_nav(self):
        self._get_navs()[1].click()

    def _open_provider_option(self, option):
        self.driver.find_element_by_css_selector(
            '#provider-options a.btn').click()
        self.driver.find_element_by_id(option).click()

    def create_offering_menu(self):
        self._open_provider_option('create-app')

    def fill_basic_offering_info(self, offering_info):
        # Name and version
        self.driver.find_element_by_css_selector(
            '[name="app-name"]').send_keys(offering_info['name'])
        self.driver.find_element_by_css_selector(
            '[name="app-version"]').send_keys(offering_info['version'])

        # Select the notification URL option
        if not offering_info['notification']:
            self.driver.find_element_by_css_selector(
                'input[type="radio"][value="none"]').click()
        elif offering_info['notification'] == 'default':
            self.driver.find_element_by_css_selector(
                'input[type="radio"][value="default"]').click()
        else:
            self.driver.find_element_by_css_selector(
                'input[type="radio"][value="new"]').click()
            self.driver.find_element_by_id('notify').send_keys(
                offering_info['notification'])

        # Add the logo
        logo_path = os.path.join(
            settings.BASEDIR,
            'wstore/defaulttheme/static/assets/img/noimage.png')
        self.driver.find_element_by_id('img-logo').send_keys(logo_path)

        # Mark as open if needed
        if offering_info['open']:
            self.driver.find_element_by_id('open-offering').click()

    def fill_usdl_info(self, usdl_info):
        # Fill description field
        self.driver.find_element_by_id('description').send_keys(
            usdl_info['description'])
        self.driver.find_element_by_id('abstract').send_keys(
            usdl_info['abstract'])

        if 'legal' in usdl_info:
            self.driver.find_element_by_id('legal-title').send_keys(
                usdl_info['legal']['title'])
            self.driver.find_element_by_id('legal-text').send_keys(
                usdl_info['legal']['text'])

    def register_resource(self, resource_info):
        pass

    def click_tag(self, tag):
        tag_elems = self.driver.find_elements_by_class_name('tag')

        for te in tag_elems:
            if te.text == tag:
                te.click()
                break

    def select_plan(self, plan):
        element = WebDriverWait(self.driver, 5).until(
            EC.presence_of_element_located((By.ID, plan)))
        element.click()

    def accept_conditions(self):
        element = WebDriverWait(self.driver, 5).until(
            EC.presence_of_element_located((By.ID, "conditions-accepted")))
        element.click()

    def fill_tax_address(self, tax):
        # Wait until the form is loaded
        element = WebDriverWait(self.driver, 5).until(
            EC.presence_of_element_located((By.ID, "street")))
        element.send_keys(tax['street'])
        self.driver.find_element_by_id('postal').send_keys(tax['postal'])
        self.driver.find_element_by_id('city').send_keys(tax['city'])
        self.driver.find_element_by_id('country').send_keys(tax['country'])
Ejemplo n.º 23
0
class LiveServerTest(object):
    fixtures = ['rules.json']

    DOWNLOAD_DIRECTORY = '/tmp/work/downloads'


    ## List all ajax enabled pages that have initialization code and must wait
    AJAX_WAIT = ['mock_galaxy_factory', 'view_job']
    SUMMARY_INDEX = str(len(MODULE_INDICES)+1)
    OUTPUT_FORMATS = [
        {'value':'csv', 'text':'CSV (Text)', 'extension':'csv'},
        {'value':'hdf5', 'text':'HDF5', 'extension':'hdf5'},
        {'value': 'fits', 'text': 'FITS', 'extension': 'fits'},
        {'value': 'votable', 'text': 'VOTable', 'extension': 'xml'}
    ]

    def wait(self, secs=1):
        time.sleep(secs * 1.0)

    def setUp(self):

        from selenium.webdriver.firefox.webdriver import FirefoxProfile
        fp = FirefoxProfile()
        fp.set_preference("browser.download.folderList", 2)
        fp.set_preference("browser.download.dir", self.DOWNLOAD_DIRECTORY)
        fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/html, application/zip, text/plain, application/force-download, application/x-tar")
        
        self.selenium = WebDriver(firefox_profile=fp)
        self.selenium.implicitly_wait(1) # wait one second before failing to find

        # create the download dir
        if not os.path.exists(self.DOWNLOAD_DIRECTORY):
            os.makedirs(self.DOWNLOAD_DIRECTORY)

    def tearDown(self):
        self.selenium.quit()
        # remove the download dir
        for root, dirs, files in os.walk(self.DOWNLOAD_DIRECTORY, topdown=False):
            for name in files:
                os.remove(os.path.join(root, name))
            for name in dirs:
                os.rmdir(os.path.join(root, name))

    def lc_id(self, bare_field):
        return '#id_light_cone-%s' % bare_field

    def lc_2select(self, bare_field):
        return 'id_light_cone-output_properties_%s' % bare_field

    def rf_id(self, bare_field):
        return '#id_record_filter-%s' % bare_field

    def sed(self, bare_field):
        return 'id_sed-%s' % bare_field

    def mi_id(self, bare_field):
        return 'id_mock_image-%s' % bare_field

    def sed_id(self, bare_field):
        return '#%s' % self.sed(bare_field)

    def sed_2select(self, bare_field):
        return 'id_sed-band_pass_filters_%s' % bare_field

    def job_select(self, bare_field):
        return 'id-job_%s' % bare_field

    def job_id(self, bare_field):
        return '#%s' % self.job_select(bare_field)

    def get_parent_element(self, element):
        return self.selenium.execute_script('return arguments[0].parentNode;', element)

    def get_element_css_classes(self, element):
        list = []
        found = element.get_attribute('class')
        if found is not None: list = found.split()
        return list

    def get_closest_by_class(self, element, css_class):
        while css_class not in self.get_element_css_classes(element):
            element = self.get_parent_element(element)
        return element

    def get_summary_selector(self, form_name, field_name):
        return 'div.summary_%s .%s' % (form_name, field_name)

    def get_summary_field(self, form_name, field_name):
        summary_selector = self.get_summary_selector(form_name, field_name)
        return self.selenium.find_element_by_css_selector(summary_selector)

    def get_summary_field_text(self, form_name, field_name):
        return self.get_summary_field(form_name, field_name).text

    def get_info_field(self, section, field):
        elem = self.selenium.find_element_by_css_selector("div.%(section)s-info .%(field)s" % {'section': section, 'field': field})
        return elem.text

    def find_element_by_css_selector(self, selector):
        retries = 3
        while retries > 0:
            try:
                elem = self.selenium.find_element_by_css_selector(selector)
                return elem
            except NoSuchElementException:
                retries -= 1
                self.wait(1)
        # If it hasn't been found by now, try one more time and let the exception through
        return self.selenium.find_element_by_css_selector(selector)

    def find_element_by_id(self, elem_id):
        retries = 3
        while retries > 0:
            try:
                elem = self.selenium.find_element_by_id(elem_id)
                return elem
            except NoSuchElementException:
                retries -= 1
                self.wait(1)
        # If it hasn't been found by now, try one more time and let the exception through
        return self.selenium.find_element_by_id(elem_id)

    def assert_email_body_contains(self, email, text):
        pattern = re.escape(text)
        matches = re.search(pattern, email.body)
        self.assertTrue(matches, "Email does not contain " + text)

    def get_page_source(self):
        try:
            return self.selenium.page_source
        except:
            while True:
                self.wait(0.2)
                try:
                    self.selenium.switch_to_alert().accept()
                except:
                    return self.selenium.page_source

    def assertTrue(self, value, msg):
        if not value:
            raise AssertionError(msg)
        return

    def assertEqual(self, vala, valb):
        if vala != valb:
            msg = 'FAIL: "{0}" != "{1}"'.format(vala, valb)
            raise AssertionError(msg)
        return


    def assert_page_has_content(self, string):
        page_source = self.get_page_source()
        pattern = re.escape(string)
        self.assertTrue((string in page_source) or re.search(pattern, page_source), "page source did not contain %s" % pattern)
        
    def assert_page_does_not_contain(self, string):
        page_source = self.get_page_source()
        
        pattern = re.escape(string)
        self.assertFalse(re.search(pattern, page_source), "page source contained %s" % pattern)
        
    def assert_element_text_equals(self, selector, expected_value):
        text = self.find_visible_element(selector).text.strip()
        self.assertEqual(expected_value.strip(), text.strip())

    def assert_element_value_equals(self, selector, expected_value):
        text = self.find_visible_element(selector).get_attribute('value')
        self.assertEqual(expected_value.strip(), text.strip())

    def assert_selector_texts_equals_expected_values(self, selector_value):
        # selector_value is a dict of selectors to expected text values
        for selector, expected_value in selector_value.items():
            self.assert_element_text_equals(selector, unicode(expected_value))
    
    def assert_attribute_equals(self, attribute, selector_values):
        # selector_values is a dict of selectors to attribute values
        for selector, expected_value in selector_values.items():
            element = self.find_visible_element(selector)
            actual_value = element.get_attribute(attribute)
            self.assertEqual(expected_value, actual_value)

    def assert_is_checked(self, selector):
        field = self.selenium.find_element_by_css_selector(selector)
        self.assertEqual('true', field.get_attribute('checked'))

    def assert_is_unchecked(self, selector):
        field = self.selenium.find_element_by_css_selector(selector)
        self.assertIsNone(field.get_attribute('checked'))

    def assert_is_enabled(self, selector):
        field = self.selenium.find_element_by_css_selector(selector)
        self.assertIsNone(field.get_attribute('disabled'))
        
    def assert_is_disabled(self, selector):
        field = self.selenium.find_element_by_css_selector(selector)
        self.assertEqual('true', field.get_attribute('disabled'))

    def assert_are_displayed(self, name):
        fields = self.selenium.find_elements_by_name(name)
        self.assertTrue([field.is_displayed() for field in fields])

    def assert_are_displayed_by_class_name(self, name):
        fields = self.selenium.find_elements_by_class_name(name)
        self.assertTrue([field.is_displayed() for field in fields])

    def assert_are_not_displayed(self, name):
        fields = self.selenium.find_elements_by_name(name)
        self.assertFalse(all([field.is_displayed() for field in fields]))

    def assert_is_displayed(self, selector):
        field = self.selenium.find_element_by_css_selector(selector)
        self.assertTrue(field.is_displayed())
        
    def assert_not_displayed(self, selector):
        field = self.selenium.find_element_by_css_selector(selector)
        self.assertFalse(field.is_displayed())

    def assert_not_in_page(self, selector):
        "Assert that the supplied selector is not part of the page content"
        elements = self.selenium.find_elements_by_css_selector(selector)
        self.assertTrue(len(elements) == 0)

    def assert_on_page(self, url_name, ignore_query_string=False):
        retries = 30
        while retries > 0:
            try:
                self._assert_on_page(url_name, ignore_query_string)
                return
            except AssertionError:
                retries -= 1
                print "assert_on_page: retry"
                self.wait(1)
        self._assert_on_page(url_name, ignore_query_string)

    def _assert_on_page(self, url_name, ignore_query_string=False):
        if not ignore_query_string:
            self.assertEqual(self.selenium.current_url, self.get_full_url(url_name))
        else:
            split_url = self.selenium.current_url.split('?')
            url = split_url[0]
            self.assertEqual(url, self.get_full_url(url_name))

    def assert_multi_selected_text_equals(self, id_of_select, expected):
        actual = self.get_multi_selected_option_text(id_of_select)
        remaining = []
        for value in expected:
            if value not in actual:
                remaining.append(value)
            else:
                actual.remove(value)
        self.assertTrue(not actual and not remaining)

    def assert_summary_field_correctly_shown(self, expected_value, form_name, field_name):
        value_displayed = self.get_summary_field_text(form_name, field_name)
        self.assertEqual(expected_value, strip_tags(value_displayed))

    def fill_in_fields(self, field_data, id_wrap=None, clear=False):
        for selector, text_to_input in field_data.items():
            if id_wrap:
                selector = id_wrap(selector)
            elem = self.selenium.find_element_by_css_selector(selector)
            if elem.tag_name == 'select':
                self.select(selector, str(text_to_input))
            else:
                if clear:
                    elem.clear()
                elem.send_keys(str(text_to_input))
        self.wait(0.5)

    def clear(self, selector):
        elem = self.selenium.find_element_by_css_selector(selector)
        elem.clear()

    def click(self, elem_id):
        elem = self.find_element_by_id(elem_id)
        elem.click()
        self.wait(0.5)

    def click_by_css(self, element_css):
        elem = self.selenium.find_element_by_css_selector(element_css)
        elem.click()
        self.wait(0.5)

    def click_by_class_name(self, class_name):
        elem = self.selenium.find_element_by_class_name(class_name)
        elem.click()
        self.wait(0.5)

    def login(self, username, password):
        self.visit('accounts/login')

        username_input = self.selenium.find_element_by_id('id_username')
        password_input = self.selenium.find_element_by_id('id_password')
        submit_button = self.selenium.find_element_by_tag_name('button')  # TODO make this more specific

        username_input.send_keys(username)
        password_input.send_keys(password)

        submit_button.submit()
        
    def visit(self, url_name, *args, **kwargs):
        """ self.visit(name_of_url_as_defined_in_your_urlconf) """
        self.selenium.get(self.get_full_url(url_name, *args, **kwargs))
        if url_name in LiveServerTest.AJAX_WAIT:
            self.wait(2)
            self.assertTrue(self.selenium.execute_script('return (window.catalogue !== undefined ? catalogue._loaded : true)'),
                            'catalogue.js loading error')

    def get_actual_filter_options(self):
        option_selector = '%s option' % self.rf_id('filter')
        return [x.get_attribute('value').encode('ascii') for x in self.selenium.find_elements_by_css_selector(option_selector)]
    
    def get_expected_filter_options(self, data_set):
        def gen_bp_pairs(objs):
            for obj in objs:
                yield ('B-' + str(obj.id) + '_apparent')
                yield ('B-' + str(obj.id) + '_absolute')
        normal_parameters = datasets.filter_choices(data_set.simulation.id, data_set.galaxy_model.id)
        bandpass_parameters = datasets.band_pass_filters_objects()
        return ['D-' + str(x.id) for x in normal_parameters] + [pair for pair in gen_bp_pairs(bandpass_parameters)]

    def get_actual_snapshot_options(self):
        option_selector = '%s option' % self.lc_id('snapshot')
        return [x.get_attribute("innerHTML") for x in self.selenium.find_elements_by_css_selector(option_selector)]

    def get_expected_snapshot_options(self, snapshots):
        return [str("%.5g" % snapshot.redshift) for snapshot in snapshots]
        
    def get_full_url(self, url_name, *args, **kwargs):
        return "%s%s" % (self.job_params.BASE_URL, url_name)
    
    def get_selected_option_text(self, id_of_select):
        select = self.selenium.find_element_by_css_selector(id_of_select)
        options = select.find_elements_by_css_selector('option')
        selected_option = None
        for option in options:
            if option.get_attribute('selected'):
                selected_option = option
        return selected_option.text

    def get_multi_selected_option_text(self, id_of_select):
        select = self.selenium.find_element_by_css_selector(id_of_select)
        options = select.find_elements_by_css_selector('option')
        return [option.text for option in options]

        
    def get_selector_value(self, selector): 
        return self.selenium.find_element_by_css_selector(selector).get_attribute('value')
    
    def select(self, selector, value):
        from selenium.webdriver.support.ui import Select

        elem = self.selenium.find_element_by_css_selector(selector)
        select = Select(elem)

        select.select_by_visible_text(value)
        
    def find_visible_elements(self, css_selector):
        elements = self.selenium.find_elements_by_css_selector(css_selector)
        return [elem for elem in elements if elem.is_displayed()]
    
    def find_visible_element(self, css_selector):
        elements = self.find_visible_elements(css_selector)
        num_elements = len(elements)
        if num_elements != 1:
            raise Exception("Found %s elements for selector %s" % (num_elements, css_selector))
        return elements[0]
    
    def select_dark_matter_simulation(self, simulation):
        self.select(self.lc_id('dark_matter_simulation'), simulation.name)
        self.wait(0.5)
        
    def select_galaxy_model(self, galaxy_model):
        self.select(self.lc_id('galaxy_model'), galaxy_model.name)
        self.wait(0.5)

    def select_stellar_model(self, stellar_model):
        self.select(self.sed_id('single_stellar_population_model'), stellar_model.label)
        self.wait(0.5)

    def select_record_filter(self, filter, extension=None):
        text = ''
        if isinstance(filter, DataSetProperty):
            units_str = ''
            if filter.units is not None and len(filter.units) > 0:
                units_str = ' (' + filter.units + ')'
            text = filter.label + units_str
        elif isinstance(filter, BandPassFilter):
            text = filter.label
            if extension is not None:
                text += ' (' + extension.capitalize() + ')'
        else:
            raise TypeError("Unknown filter type")
        self.select(self.rf_id('filter'), text)
        
    #a function to make a list of list of text inside the table
    def table_as_text_rows(self, selector):
        table = self.selenium.find_element_by_css_selector(selector)
        rows = table.find_elements_by_css_selector('tr')
        cells = [[cell.text for cell in row.find_elements_by_css_selector('th, td')] for row in rows]
        return cells

    def submit_support_form(self):
        submit_button = self.selenium.find_element_by_css_selector('button[type="submit"]')
        submit_button.submit()
Ejemplo n.º 24
0
class UITestCase(LiveServerTestCase):
    def use_xvfb(self):
        from pyvirtualdisplay import Display
        self.display = Display('xvfb',
                               visible=1,
                               size=(1280, 1024))
        self.display.start()
        self.driver = WebDriver()

    def setUp(self):
        try:
            self.driver = WebDriver()
            ui_is_not_available = False
        except WebDriverException:
            ui_is_not_available = True

        if ui_is_not_available:
            self.use_xvfb()

        self.driver.implicitly_wait(10)
        super(UITestCase, self).setUp()

    def tearDown(self):
        self.driver.quit()
        if hasattr(self, 'display'):
            self.display.stop()

        # The super.tearDown sometimes hangs when truncating tables
        # because of lingering pending transactions with locks on those tables.
        # Kill them to avoid deadlock!
        try:
            dbname = settings.DATABASES['default']['NAME']
            sql = "select pg_terminate_backend(procpid)" + \
                " from pg_stat_activity where datname='%s'" % dbname + \
                " and current_query='<IDLE> in transaction';"
            connection.cursor().execute(sql)
        except InterfaceError:
            # Sometimes we get "connection already closed"
            pass

        super(UITestCase, self).tearDown()

    def click(self, selector):
        self.find(selector).click()

    def click_when_visible(self, selector):
        element = self.find(selector)
        self.wait_until_visible(element)
        element.click()

    def find(self, selector):
        return self.driver.find_element_by_css_selector(selector)

    def find_name(self, name):
        return self.driver.find_element_by_name(name)

    def find_id(self, id):
        return self.driver.find_element_by_id(id)

    def process_login_form(self, username, password):
        username_elmt = self.find_name('username')
        password_elmt = self.find_name('password')

        username_elmt.send_keys(username)
        password_elmt.send_keys(password)

        self.click('form * button')

    def browse_to_url(self, url):
        self.driver.get(self.live_server_url + url)

    def find_anchor_by_url(self, url):
        return self.find("[href='%s']" % url)

    def wait_until_enabled(self, element, timeout=10):
        def isPresentAndEnabled(driver):
            return element.get_attribute("disabled") is None
        WebDriverWait(self.driver, timeout).until(isPresentAndEnabled)

    def wait_until_visible(self, element, timeout=10):
        def isVisible(driver):
            return element.is_displayed()
        WebDriverWait(self.driver, timeout).until(isVisible)
Ejemplo n.º 25
0
 if not wd.find_element_by_xpath(
         "//select[@id='configSelect']//option[2]").is_selected():
     wd.find_element_by_xpath(
         "//select[@id='configSelect']//option[2]").click()
 wd.find_element_by_id("btnStartCustomizing").click()
 if not wd.find_element_by_xpath(
         "//select[@id='metalTypeSelect']//option[2]").is_selected():
     wd.find_element_by_xpath(
         "//select[@id='metalTypeSelect']//option[2]").click()
 wd.find_element_by_id("next-step").click()
 if not wd.find_element_by_xpath(
         "//select[@id='stoneTypeSelect']//option[2]").is_selected():
     wd.find_element_by_xpath(
         "//select[@id='stoneTypeSelect']//option[2]").click()
 wd.find_element_by_xpath("//div[@id='tab-stoneType']//a[.='Next']").click()
 wd.find_element_by_css_selector("span.month_text").click()
 wd.find_element_by_xpath(
     "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/span[2]").click()
 wd.find_element_by_xpath(
     "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/span[1]").click()
 wd.find_element_by_xpath(
     "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/input").click()
 wd.find_element_by_xpath(
     "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/span[1]").click()
 if not wd.find_element_by_xpath(
         "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/input"
 ).is_selected():
     wd.find_element_by_xpath(
         "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/input").click()
 wd.find_element_by_link_text("SELECT").click()
 wd.find_element_by_xpath("//div[@id='tab-stones']//a[.='Next']").click()
Ejemplo n.º 26
0
#script, country = argv

success = True
wd = WebDriver()
wd.implicitly_wait(2)


def is_alert_present(wd):
    try:
        wd.switch_to_alert().text
        return True
    except:
        return False


try:
    wd.get("http://en.wikipedia.org/wiki/Main_Page")
    wd.find_element_by_id("searchInput").click()
    wd.find_element_by_id("searchInput").clear()
    wd.find_element_by_id("searchInput").send_keys("madagascar")
    wd.find_element_by_id("searchButton").click()
    if not ("Malagasy" in wd.find_element_by_css_selector(
            "a[title=\"Malagasy people\"]").txt):
        success = False
        print("verifyTextPresent failed")
    print("Malagasy")
finally:
    wd.quit()
    if not success:
        raise Exception("Test failed.")
Ejemplo n.º 27
0
def is_alert_present(wd):
    try:
        wd.switch_to_alert().text
        return True
    except:
        return False

try:
    wd.get("http://localhost/addressbook/")
    wd.find_element_by_name("pass").click()
    wd.find_element_by_name("pass").clear()
    wd.find_element_by_name("pass").send_keys("secret")
    wd.find_element_by_name("user").click()
    wd.find_element_by_name("user").clear()
    wd.find_element_by_name("user").send_keys("admin")
    wd.find_element_by_css_selector("input[type=\"submit\"]").click()
    wd.find_element_by_link_text("groups").click()
    wd.find_element_by_name("new").click()
    wd.find_element_by_name("group_name").click()
    wd.find_element_by_name("group_name").clear()
    wd.find_element_by_name("group_name").send_keys("new froup")
    wd.find_element_by_name("group_header").click()
    wd.find_element_by_name("group_header").clear()
    wd.find_element_by_name("group_header").send_keys("new grope")
    wd.find_element_by_name("group_footer").click()
    wd.find_element_by_name("group_footer").clear()
    wd.find_element_by_name("group_footer").send_keys("new grpi")
    wd.find_element_by_name("submit").click()
    wd.find_element_by_link_text("group page").click()
    wd.find_element_by_link_text("Logout").click()
    wd.find_element_by_name("user").click()
Ejemplo n.º 28
0
 def _hit_renew_button(webdriver: WebDriver):
     webdriver.find_element_by_css_selector(
         'a[data-ui-relevance="renew-action"]').click()
Ejemplo n.º 29
0
class UITestCase(LiveServerTestCase):
    def use_xvfb(self):
        from pyvirtualdisplay import Display
        self.display = Display('xvfb', visible=1, size=(1280, 1024))
        self.display.start()
        self.driver = WebDriver()

    def setUp(self):
        try:
            self.driver = WebDriver()
            ui_is_not_available = False
        except WebDriverException:
            ui_is_not_available = True

        if ui_is_not_available:
            self.use_xvfb()

        self.driver.implicitly_wait(10)

        clear_caches()
        setup_for_ui_test()

        super(UITestCase, self).setUp()

    def tearDown(self):
        self.driver.quit()
        if hasattr(self, 'display'):
            self.display.stop()

        ContentType.objects.clear_cache()

        super(UITestCase, self).tearDown()

    def click(self, selector):
        self.find(selector).click()

    def click_when_visible(self, selector):
        element = self.find(selector)
        self.wait_until_visible(element)
        element.click()

    def find(self, selector):
        return self.driver.find_element_by_css_selector(selector)

    def find_name(self, name):
        return self.driver.find_element_by_name(name)

    def find_id(self, id):
        return self.driver.find_element_by_id(id)

    def process_login_form(self, username, password):
        username_elmt = self.wait_until_present('[name="username"]')
        password_elmt = self.find_name('password')

        username_elmt.send_keys(username)
        password_elmt.send_keys(password)

        self.click('form * button')

    def browse_to_url(self, url):
        self.driver.get(self.live_server_url + url)

    def browse_to_instance_url(self, url, instance=None):
        instance = instance if instance is not None else self.instance
        self.driver.get('%s/%s/%s' %
                        (self.live_server_url, self.instance.url_name, url))

    def find_anchor_by_url(self, url):
        return self.find("[href='%s']" % url)

    def wait_until_present(self, selector, timeout=10):
        """
        Wait until an element with CSS 'selector' exists on the page.
        Useful for detecting that an operation loads the page you're expecting.
        """
        element = [None]  # use list so it can be set by inner scope

        def is_present(driver):
            element[0] = self.find(selector)
            return element[0] is not None

        WebDriverWait(self.driver, timeout).until(is_present)
        return element[0]

    def wait_until_text_present(self, text, timeout=10):
        """
        Wait until 'text' exists on the page.
        Useful for detecting that an operation loads the page you're expecting.
        """
        WebDriverWait(self.driver,
                      timeout).until(lambda driver: text in driver.page_source)

    def wait_until_enabled(self, element_or_selector, timeout=10):
        """
        Wait until 'element_or_selector' is enabled.
        """
        element = self._get_element(element_or_selector)
        WebDriverWait(self.driver, timeout).until(
            lambda driver: element.get_attribute("disabled") is None)
        return element

    def wait_until_visible(self, element_or_selector, timeout=10):
        """
        Wait until 'element_or_selector' (known to already exist on the page)
        is displayed.
        """
        element = self._get_element(element_or_selector)
        WebDriverWait(self.driver,
                      timeout).until(lambda driver: element.is_displayed())
        return element

    def wait_until_invisible(self, element_or_selector, timeout=10):
        """
        Wait until 'element_or_selector' (known to already exist on the page)
        is not displayed.
        """
        element = self._get_element(element_or_selector)

        def is_invisible(driver):
            try:
                return not element.is_displayed()
            except StaleElementReferenceException:
                return True

        WebDriverWait(self.driver, timeout).until(is_invisible)
        return element

    def _get_element(self, element_or_selector):
        if isinstance(element_or_selector, basestring):
            return self.find(element_or_selector)
        else:
            return element_or_selector
Ejemplo n.º 30
0
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.common.action_chains import ActionChains
import time

success = True
wd = WebDriver()
wd.implicitly_wait(5)


def is_alert_present(wd):
    try:
        wd.switch_to_alert().text
        return True
    except:
        return False


try:
    wd.get("http://en.wikipedia.org/wiki/Main_Page")
    wd.find_element_by_id("searchInput").click()
    wd.find_element_by_id("searchInput").clear()
    wd.find_element_by_id("searchInput").send_keys("madagascar")
    wd.find_element_by_id("searchButton").click()
    wd.find_element_by_css_selector("a[title=\"Malagasy people\"]").click()
    val = wd.find_element_by_css_selector("a[title=\"Malagasy people\"]").txt
    print(val)
finally:
    wd.quit()
    if not success:
        raise Exception("Test failed.")
Ejemplo n.º 31
0
class UITestCase(LiveServerTestCase):
    def use_xvfb(self):
        from pyvirtualdisplay import Display
        self.display = Display('xvfb',
                               visible=1,
                               size=(1280, 1024))
        self.display.start()
        self.driver = WebDriver()

    def setUp(self):
        try:
            self.driver = WebDriver()
            ui_is_not_available = False
        except WebDriverException:
            ui_is_not_available = True

        if ui_is_not_available:
            self.use_xvfb()

        self.driver.implicitly_wait(10)
        super(UITestCase, self).setUp()

    def tearDown(self):
        self.driver.quit()
        if hasattr(self, 'display'):
            self.display.stop()

        # I believe this line is no longer necessary, but I'm leaving it here
        # until the UI tests have run many times without deadlocking.
        # -RM 20140522
        #self.kill_pending_transactions()

        super(UITestCase, self).tearDown()

    def kill_pending_transactions(self):
        # The super.tearDown sometimes hangs when truncating tables
        # because of lingering pending transactions with locks on those tables.
        # Kill them to avoid deadlock!
        try:
            dbname = settings.DATABASES['default']['NAME']
            sql = "select pg_terminate_backend(procpid)" + \
                " from pg_stat_activity where datname='%s'" % dbname + \
                " and current_query='<IDLE> in transaction';"
            connection.cursor().execute(sql)
        except InterfaceError:
            # Sometimes we get "connection already closed"
            pass

    def click(self, selector):
        self.find(selector).click()

    def click_when_visible(self, selector):
        element = self.find(selector)
        self.wait_until_visible(element)
        element.click()

    def find(self, selector):
        return self.driver.find_element_by_css_selector(selector)

    def find_name(self, name):
        return self.driver.find_element_by_name(name)

    def find_id(self, id):
        return self.driver.find_element_by_id(id)

    def process_login_form(self, username, password):
        username_elmt = self.wait_until_present('[name="username"]')
        password_elmt = self.find_name('password')

        username_elmt.send_keys(username)
        password_elmt.send_keys(password)

        self.click('form * button')

    def browse_to_url(self, url):
        self.driver.get(self.live_server_url + url)

    def find_anchor_by_url(self, url):
        return self.find("[href='%s']" % url)

    def wait_until_present(self, selector, timeout=10):
        """
        Wait until an element with CSS 'selector' exists on the page.
        Useful for detecting that an operation loads the page you're expecting.
        """
        element = [None]  # use list so it can be set by inner scope

        def is_present(driver):
            element[0] = self.find(selector)
            return element[0] is not None

        WebDriverWait(self.driver, timeout).until(is_present)
        return element[0]

    def wait_until_text_present(self, text, timeout=10):
        """
        Wait until 'text' exists on the page.
        Useful for detecting that an operation loads the page you're expecting.
        """
        WebDriverWait(self.driver, timeout).until(
            lambda driver: text in driver.page_source)

    def wait_until_enabled(self, element_or_selector, timeout=10):
        """
        Wait until 'element_or_selector' is enabled.
        """
        element = self._get_element(element_or_selector)
        WebDriverWait(self.driver, timeout).until(
            lambda driver: element.get_attribute("disabled") is None)
        return element

    def wait_until_visible(self, element_or_selector, timeout=10):
        """
        Wait until 'element_or_selector' (known to already exist on the page)
        is displayed.
        """
        element = self._get_element(element_or_selector)
        WebDriverWait(self.driver, timeout).until(
            lambda driver: element.is_displayed())
        return element

    def wait_until_invisible(self, element_or_selector, timeout=10):
        """
        Wait until 'element_or_selector' (known to already exist on the page)
        is not displayed.
        """
        element = self._get_element(element_or_selector)

        def is_invisible(driver):
            try:
                return not element.is_displayed()
            except StaleElementReferenceException:
                return True

        WebDriverWait(self.driver, timeout).until(is_invisible)
        return element

    def _get_element(self, element_or_selector):
        if isinstance(element_or_selector, basestring):
            return self.find(element_or_selector)
        else:
            return element_or_selector
Ejemplo n.º 32
0
class SeleniumTests(LiveServerTestCase):
    """Base class for all Selenium test classes to inherit from"""

    @classmethod
    def setUpClass(self):
        self.selenium = WebDriver()
        self.selenium.implicitly_wait(3)
        super(SeleniumTests, self).setUpClass()

    @classmethod
    def tearDownClass(self):
        self.selenium.quit()
        super(SeleniumTests, self).tearDownClass()

    def setUp(self):
        # Create a test user and admin account
        self.user_name = 'SeleniumTestUser'
        self.user_pass = '******'
        if User.objects.filter(username=self.user_name).count() == 0:
            User.objects.create_user(self.user_name, '', self.user_pass).save()

        self.admin_name = 'SeleniumAdministrativeUser'
        self.admin_pass = '******'
        if User.objects.filter(username=self.admin_name).count() == 0:
            User.objects.create_superuser(self.admin_name, '', self.admin_pass).save()

    def tearDown(self):
        self.selenium.delete_all_cookies()

    def link_text_exists(self, link_text):
        try:
            self.selenium.find_element_by_link_text(link_text)
        except NoSuchElementException:
            return False
        return True

    def xpath_exists(self, xpath):
        try:
            self.selenium.find_element_by_xpath(xpath)
        except NoSuchElementException:
            return False
        return True

    def element_with_selector_exists(self, selector):
        try:
            self.selenium.find_element_by_css_selector(selector)
        except NoSuchElementException:
            return False
        return True

    def text_exists(self, text, xpath="//body"):
        try:
            element = self.selenium.find_element_by_xpath(xpath)
        except NoSuchElementException:
            return False

        if text in element.text:
            return True
        else:
            return False

    def login(self, username, password):
        # Go to the login page and try logging in with the provided credentials
        self.selenium.get('%s' % self.live_server_url)
        self.selenium.find_element_by_link_text('Log in').click()
        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)
        self.selenium.find_element_by_class_name('submit').click()

    def create_items_and_requests(self, x):
        # Creates x number of items and requests
        for i in xrange(x):
            self.item = G(Item)
            self.request = G(Request, item=self.item)

    def create_generic_item(self):
        # Quick helper in the absence of fixtures
        item = G(Item, local_num=9999, part_class='parts class',
                 location='cart 8', description='test item', cfi='never',
                 company='A Business', part_num='X9X9', serial_num='8A',
                 asset_num='sample_num', notes='Testing')
        return item
Ejemplo n.º 33
0
def is_alert_present(wd):
    try:
        wd.switch_to_alert().text
        return True
    except:
        return False

try:
    wd.get("http://b11test4a.mentoringmindsonline.com/mysdb_m3_test4/_design/mys/mmloginw.html")
    wd.find_element_by_id("loginUserID").click()
    wd.find_element_by_id("loginUserID").clear()
    wd.find_element_by_id("loginUserID").send_keys("113177")
    wd.find_element_by_id("userPasswd").click()
    wd.find_element_by_id("userPasswd").clear()
    wd.find_element_by_id("userPasswd").send_keys("Ctfl*5258")
    wd.find_element_by_id("sign-in").click()
    wd.find_element_by_id("reportsBigBtnBtn").click()
    wd.find_element_by_id("selectReportTypeW").click()
    wd.find_element_by_id("dijit_MenuItem_30_text").click()
    wd.find_element_by_id("dijit_MenuItem_39_text").click()
    wd.find_element_by_id("dijit_MenuItem_92_text").click()
    wd.find_element_by_id("generateReportBtn").click()
    wd.find_element_by_css_selector("#dojox_mobile_ToolBarButton_34 > span.mblToolBarButtonBody.mblColorDefault > table.mblToolBarButtonText > tbody > tr > td.mblToolBarButtonLabel").click()
    wd.find_element_by_css_selector("#dojox_mobile_ToolBarButton_4 > span.mblToolBarButtonBody.mblColorDefault > table.mblToolBarButtonText > tbody > tr > td.mblToolBarButtonLabel").click()
    wd.find_element_by_css_selector("td.mblToolBarButtonLabel").click()
finally:
    wd.quit()
    if not success:
        raise Exception("Test failed.")
Ejemplo n.º 34
0
class WStoreSeleniumTestCase(TestCase, LiveServerTestCase):

    fixtures = ['selenium_basic.json']

    @classmethod
    def setUpClass(cls):
        super(WStoreSeleniumTestCase, cls).setUpClass()

    def setUp(self):
        # Open the page
        self.driver = WebDriver()
        self.driver.implicitly_wait(5)
        self.driver.set_window_size(1024, 768)
        self.driver.get(self.live_server_url)
        TestCase.setUp(self)

    def _check_container(self, container, offering_names):
        # Check offerings container
        container = self.driver.find_element_by_class_name(container)
        offering_elems = container.find_elements_by_class_name('menu-offering')
        self.assertEquals(len(offering_elems), len(offering_names))

        for off_elem in offering_elems:
            title = off_elem.find_element_by_css_selector('h2')
            self.assertTrue(title.text in offering_names)

    def login(self, username='******'):
        # Set username
        username_elem = self.driver.find_element_by_name('username')
        username_elem.send_keys(username)

        # Set password
        password_elem = self.driver.find_element_by_name('password')
        password_elem.send_keys('admin')

        # Click login
        self.driver.find_element_by_css_selector('#login-form button').click()

    def oauth2_login(self, username='******'):
        from wstore.selenium_tests.tests import TESTING_PORT
        self.driver.get(self.live_server_url + '/oauth2/auth?response_type=code&client_id=test_app&redirect_uri=http://localhost:' + unicode(TESTING_PORT))

        self.login(username)

        self.driver.find_element_by_class_name('btn-blue').click()
        time.sleep(1)

        # Get authorization code
        while self._server.call_received() < 1:
            pass

        code = self._server.get_path().split('=')[1]

        # Get access token
        opener = urllib2.build_opener()

        url = self.live_server_url + '/oauth2/token'

        data = 'client_id=test_app'
        data += '&client_secret=secret'
        data += '&grant_type=authorization_code'
        data += '&code=' + code
        data += '&redirect_uri=' + 'http://localhost:' + unicode(TESTING_PORT)

        headers = {
            'content-type': 'application/form-url-encoded',
        }
        request = MethodRequest('POST', url, data, headers)

        response = opener.open(request)

        token = json.loads(response.read())['access_token']

        return token


    def logout(self):
        self.driver.find_element_by_class_name('arrow-down-settings').click()
        options = self.driver.find_elements_by_css_selector('#settings-menu > li')

        options[-1].click()

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

    def back(self):
        self.driver.find_element_by_id('back').click()

    def view_all(self):
        self.driver.find_element_by_css_selector('#all').click()

    def search_keyword(self, keyword, id_='#text-search', btn='#search'):
        # Set search field
        search_elem = self.driver.find_element_by_css_selector(id_)
        search_elem.send_keys(keyword)

        # Click search button
        self.driver.find_element_by_css_selector(btn).click()

    def open_offering_details(self, offering_name):

        elements = self.driver.find_elements_by_class_name('menu-offering')

        for element in elements:
            if element.find_element_by_css_selector('h2').text == offering_name:
                element.click()
                break

    def _get_navs(self):
        submenu = self.driver.find_element_by_class_name('store-sub-menu')
        # Get first element
        return submenu.find_elements_by_css_selector('li')

    def click_first_cat(self):
        self.driver.find_element_by_id('menu-first-text').click()

    def click_second_cat(self):
        self.driver.find_element_by_id('menu-second-text').click()

    def click_third_cat(self):
        self.driver.find_element_by_id('menu-third-text').click()

    def click_first_nav(self):
        self._get_navs()[0].click()

    def click_second_nav(self):
        self._get_navs()[1].click()

    def _open_provider_option(self, option):
        self.driver.find_element_by_css_selector('#provider-options a.btn').click()
        self.driver.find_element_by_id(option).click()

    def create_offering_menu(self):
        self._open_provider_option('create-app')

    def fill_basic_offering_info(self, offering_info):
        # Name and version
        self.driver.find_element_by_css_selector('[name="app-name"]').send_keys(offering_info['name'])
        self.driver.find_element_by_css_selector('[name="app-version"]').send_keys(offering_info['version'])

        # Select the notification URL option
        if not offering_info['notification']:
            self.driver.find_element_by_css_selector('input[type="radio"][value="none"]').click()
        elif offering_info['notification'] == 'default':
            self.driver.find_element_by_css_selector('input[type="radio"][value="default"]').click()
        else:
            self.driver.find_element_by_css_selector('input[type="radio"][value="new"]').click()
            self.driver.find_element_by_id('notify').send_keys(offering_info['notification'])

        # Add the logo
        logo_path = os.path.join(settings.BASEDIR, 'wstore/ui/fiware/defaulttheme/static/assets/img/noimage.png')
        self.driver.find_element_by_id('img-logo').send_keys(logo_path)

        # Mark as open if needed
        if offering_info['open']:
            self.driver.find_element_by_id('open-offering').click()

    def _fill_usdl_form(self, usdl_info):
        # Fill description field
        self.driver.find_element_by_id('description').send_keys(usdl_info['description'])

        # Fill pricing info if needed
        if 'price' in usdl_info:
            self.driver.find_element_by_css_selector('#pricing-select option[value="single_payment"]').click()
            self.driver.find_element_by_id('price-input').send_keys(usdl_info['price'])

        if 'legal' in usdl_info:
            self.driver.find_element_by_id('legal-title').send_keys(usdl_info['legal']['title'])
            self.driver.find_element_by_id('legal-text').send_keys(usdl_info['legal']['text'])

    def _fill_usdl_upload(self, usdl_info):
        pass

    def _fill_usdl_url(self, usdl_info):
        pass

    def fill_usdl_info(self, usdl_info):
        # Select the correct method
        methods = {
            'form': self._fill_usdl_form,
            'upload': self._fill_usdl_upload,
            'url': self._fill_usdl_url
        }
        methods[usdl_info['type']](usdl_info)
        
    def register_resource(self, resource_info):
        pass

    def click_tag(self, tag):
        tag_elems = self.driver.find_elements_by_class_name('tag')

        for te in tag_elems:
            if te.text == tag:
                te.click()
                break

    def fill_tax_address(self, tax):
        self.driver.find_element_by_id('street').send_keys(tax['street'])
        self.driver.find_element_by_id('postal').send_keys(tax['postal'])
        self.driver.find_element_by_id('city').send_keys(tax['city'])
        self.driver.find_element_by_id('country').send_keys(tax['country'])
Ejemplo n.º 35
0
class SeleniumRunner:
    """
    A runner that upload and download Icomoon resources using Selenium.
    The WebDriver will use Firefox.
    """

    """
    The long wait time for the driver in seconds.
    """
    LONG_WAIT_IN_SEC = 25

    """
    The medium wait time for the driver in seconds.
    """
    MED_WAIT_IN_SEC = 6

    """
    The short wait time for the driver in seconds.
    """
    SHORT_WAIT_IN_SEC = 0.6

    """
    The Icomoon Url.
    """
    ICOMOON_URL = "https://icomoon.io/app/#/select"

    def __init__(self, download_path: str,
                 geckodriver_path: str, headless: bool):
        """
        Create a SeleniumRunner object.
        :param download_path: the location where you want to download
        the icomoon.zip to.
        :param geckodriver_path: the path to the firefox executable.
        :param headless: whether to run browser in headless (no UI) mode.
        """
        self.driver = None
        self.set_options(download_path, geckodriver_path, headless)

    def set_options(self, download_path: str, geckodriver_path: str,
        headless: bool):
        """
        Build the WebDriver with Firefox Options allowing downloads and
        set download to download_path.
        :param download_path: the location where you want to download
        :param geckodriver_path: the path to the firefox executable.
        the icomoon.zip to.
        :param headless: whether to run browser in headless (no UI) mode.

        :raises AssertionError: if the page title does not contain
        "IcoMoon App".
        """
        options = Options()
        allowed_mime_types = "application/zip, application/gzip, application/octet-stream"
        # disable prompt to download from Firefox
        options.set_preference("browser.helperApps.neverAsk.saveToDisk", allowed_mime_types)
        options.set_preference("browser.helperApps.neverAsk.openFile", allowed_mime_types)

        # set the default download path to downloadPath
        options.set_preference("browser.download.folderList", 2)
        options.set_preference("browser.download.dir", download_path)
        options.headless = headless

        self.driver = WebDriver(options=options, executable_path=geckodriver_path)
        self.driver.get(self.ICOMOON_URL)
        assert "IcoMoon App" in self.driver.title
        # wait until the whole web page is loaded by testing the hamburger input
        WebDriverWait(self.driver, self.LONG_WAIT_IN_SEC).until(
            ec.element_to_be_clickable((By.XPATH, "(//i[@class='icon-menu'])[2]"))
        )
        print("Accessed icomoon.io")
        

    def upload_icomoon(self, icomoon_json_path: str):
        """
        Upload the icomoon.json to icomoon.io.
        :param icomoon_json_path: a path to the iconmoon.json.
        :raises TimeoutException: happens when elements are not found.
        """
        print("Uploading icomoon.json file...")
        self.click_hamburger_input()
        
        # find the file input and enter the file path
        import_btn = self.driver.find_element(By.XPATH, "(//li[@class='file'])[1]//input")
        import_btn.send_keys(icomoon_json_path)

        try:
            confirm_btn = WebDriverWait(self.driver, SeleniumRunner.MED_WAIT_IN_SEC).until(
                ec.element_to_be_clickable((By.XPATH, "//div[@class='overlay']//button[text()='Yes']"))
            )
            confirm_btn.click()
        except SeleniumTimeoutException as e:
            raise Exception("Cannot find the confirm button when uploading the icomoon.json" \
                  "Ensure that the icomoon.json is in the correct format for Icomoon.io")

        print("JSON file uploaded.")

    def upload_svgs(self, svgs: List[str], screenshot_folder: str=""):
        """
        Upload the SVGs provided in folder_info
        :param svgs: a list of svg Paths that we'll upload to icomoon.
        :param screenshot_folder: the name of the screenshot_folder. If
        the value is provided, it means the user want to take a screenshot
        of each icon.
        """
        print("Uploading SVGs...")

        edit_mode_btn = self.driver.find_element_by_css_selector(
            "div.btnBar button i.icon-edit"
        )
        edit_mode_btn.click()

        self.click_hamburger_input()

        for i in range(len(svgs)):
            import_btn = self.driver.find_element_by_css_selector(
                "li.file input[type=file]"
            )
            import_btn.send_keys(svgs[i])
            print(f"Uploaded {svgs[i]}")
            self.test_for_possible_alert(self.SHORT_WAIT_IN_SEC, "Dismiss")
            self.click_on_just_added_icon(screenshot_folder, i)

        # take a screenshot of the icons that were just added
        new_icons_path = str(Path(screenshot_folder, "new_icons.png").resolve())
        self.driver.save_screenshot(new_icons_path);

        print("Finished uploading the svgs...")

    def click_hamburger_input(self):
        """
        Click the hamburger input until the pop up menu appears. This
        method is needed because sometimes, we need to click the hamburger
        input two times before the menu appears.
        :return: None.
        """
        hamburger_input = self.driver.find_element_by_xpath(
            "(//i[@class='icon-menu'])[2]"
        )

        menu_appear_callback = ec.element_to_be_clickable(
            (By.CSS_SELECTOR, "h1 ul.menuList2")
        )

        while not menu_appear_callback(self.driver):
            hamburger_input.click()

    def test_for_possible_alert(self, wait_period: float, btn_text: str):
        """
        Test for the possible alert when we upload the svgs.
        :param wait_period: the wait period for the possible alert
        in seconds.
        :param btn_text: the text that the alert's button will have.
        :return: None.
        """
        try:
            dismiss_btn = WebDriverWait(self.driver, wait_period, 0.15).until(
                ec.element_to_be_clickable(
                    (By.XPATH, f"//div[@class='overlay']//button[text()='{btn_text}']"))
            )
            dismiss_btn.click()
        except SeleniumTimeoutException:
            pass  # nothing found => everything is good

    def click_on_just_added_icon(self, screenshot_folder: str, index: int):
        """
        Click on the most recently added icon so we can remove the colors
        and take a snapshot if needed.
        """
        recently_uploaded_icon = WebDriverWait(self.driver, self.LONG_WAIT_IN_SEC).until(
            ec.element_to_be_clickable((By.XPATH, "//div[@id='set0']//mi-box[1]//div"))
        )
        recently_uploaded_icon.click()

        self.remove_color_from_icon()

        if screenshot_folder:
            screenshot_path = str(Path(screenshot_folder, f"screenshot_{index}.png").resolve())
            self.driver.save_screenshot(screenshot_path)
            print("Took screenshot and saved it at " + screenshot_path)

        close_btn = self.driver \
            .find_element_by_css_selector("div.overlayWindow i.icon-close")
        close_btn.click()

    def remove_color_from_icon(self):
        """
        Remove the color from the most recent uploaded icon.
        This is because some SVG have colors in them and we don't want to
        force contributors to remove them in case people want the colored SVGs.
        The color removal is also necessary so that the Icomoon-generated
        icons fit within one font symbol/ligiature.
        """
        try:
            color_tab = WebDriverWait(self.driver, self.SHORT_WAIT_IN_SEC).until(
                ec.element_to_be_clickable((By.CSS_SELECTOR, "div.overlayWindow i.icon-droplet"))
            )
            color_tab.click()

            remove_color_btn = self.driver \
                .find_element_by_css_selector("div.overlayWindow i.icon-droplet-cross")
            remove_color_btn.click()
        except SeleniumTimeoutException:
            pass # do nothing cause sometimes, the color tab doesn't appear in the site

    def download_icomoon_fonts(self, zip_path: Path):
        """
        Download the icomoon.zip from icomoon.io.
        :param zip_path: the path to the zip file after it's downloaded.
        """
        # select all the svgs so that the newly added svg are part of the collection
        self.click_hamburger_input()
        select_all_button = WebDriverWait(self.driver, self.LONG_WAIT_IN_SEC).until(
            ec.element_to_be_clickable((By.XPATH, "//button[text()='Select All']"))
        )
        select_all_button.click()

        print("Downloading Font files...")
        font_tab = self.driver.find_element_by_css_selector(
            "a[href='#/select/font']"
        )
        font_tab.click()

        self.test_for_possible_alert(self.MED_WAIT_IN_SEC, "Continue")
        download_btn = WebDriverWait(self.driver, SeleniumRunner.LONG_WAIT_IN_SEC).until(
            ec.presence_of_element_located((By.CSS_SELECTOR, "button.btn4 span"))
        )
        download_btn.click()
        if self.wait_for_zip(zip_path):
            print("Font files downloaded.")
        else:
            raise TimeoutError(f"Couldn't find {zip_path} after download button was clicked.")

    def wait_for_zip(self, zip_path: Path) -> bool:
        """
        Wait for the zip file to be downloaded by checking for its existence
        in the download path. Wait time is self.LONG_WAIT_IN_SEC and check time
        is 1 sec.
        :param zip_path: the path to the zip file after it's
        downloaded.
        :return: True if the file is found within the allotted time, else
        False.
        """
        end_time = time.time() + self.LONG_WAIT_IN_SEC
        while time.time() <= end_time:
            if zip_path.exists():
                return True
            time.sleep(1)    
        return False

    def close(self):
        """
        Close the SeleniumRunner instance.
        """
        print("Closing down SeleniumRunner...")
        self.driver.quit()
Ejemplo n.º 36
0
success = True
wd = WebDriver()
wd.implicitly_wait(60)


def is_alert_present(wd):
    try:
        wd.switch_to_alert().text
        return True
    except:
        return False


try:
    wd.get("https://dev.vetmedical.ru/")
    wd.find_element_by_css_selector("#sign_in").click()
    wd.find_element_by_css_selector("#ips_username").click()
    wd.find_element_by_css_selector("#ips_username").clear()
    wd.find_element_by_css_selector("#ips_username").send_keys(
        "Alexander Podobulkin")
    wd.find_element_by_css_selector("#ips_password").click()
    wd.find_element_by_css_selector("#ips_password").clear()
    wd.find_element_by_css_selector("#ips_password").send_keys("210785ap")
    wd.find_element_by_css_selector("#b-login__submit-form").click()
    wd.refresh()
    wd.get(
        "https://dev.vetmedical.ru/index.php?/forum/9-%D0%BE%D0%B1%D1%89%D0%B8%D0%B5-%D0%BE%D0%B1%D1%81%D1%83%D0%B6%D0%B4%D0%B5%D0%BD%D0%B8%D1%8F/"
    )
    wd.find_element_by_css_selector(
        "#tabs-container > header > div.b-control-buttons > a").click()
    if wd.find_element_by_css_selector(
Ejemplo n.º 37
0
# -*- coding: utf-8 -*-
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time

success = True
wd = WebDriver()
wd.implicitly_wait(60)

def is_alert_present(wd):
    try:
        wd.switch_to_alert().text
        return True
    except:
        return False

try:
    wd.get("https://www.google.com/")
    wd.find_element_by_id("lst-ib").click()
    wd.find_element_by_id("lst-ib").click()
    wd.find_element_by_id("lst-ib").clear()
    wd.find_element_by_id("lst-ib").send_keys("x")
    wd.find_element_by_xpath("//div[@id='sbse1']//b[.='iaomi redmi note 5']").click()
    ActionChains(wd).double_click(wd.find_element_by_css_selector("center")).perform()
finally:
    wd.quit()
    if not success:
        raise Exception("Test failed.")
def syn_test_script():

    try:
        success = True
        driver = WebDriver()
        driver.implicitly_wait(30)
        # Disabled page sizing and instead used action chains to move mouse around
        #driver.set_window_size(1920, 1080)

        # Use Action chains to navigate page when there is an issue with the selection menus
        # If the menu item does not appear to select, it means there was a page movement that happened
        # out of sync with the action.

        #------Insert Script between these lines-----#
        driver.get(
            "http://www.jared.com/en/jaredstore/searchterm/731434000/true/731434000"
        )

        # Search HTML for text to verify page
        log_output("Step - Verify Search worked")
        if not ("items" in driver.find_element_by_tag_name("html").text):
            success = False
            print("verifyTextPresent failed")

        log_output("Step - Select item via partial link text")
        driver.find_element_by_partial_link_text(
            "Mother's Bracelet Round Birthstones Design in Silver").click()

        log_output("Start customizing Jewelery")

        log_output("    Select Number of stones (1)")
        if not driver.find_element_by_xpath(
                "//select[@id='configSelect']//option[2]").is_selected():
            driver.find_element_by_xpath(
                "//select[@id='configSelect']//option[2]").click()
        driver.find_element_by_id("btnStartCustomizing").click()

        log_output("    Select metal type")
        if not driver.find_element_by_xpath(
                "//select[@id='metalTypeSelect']//option[2]").is_selected():
            driver.find_element_by_xpath(
                "//select[@id='metalTypeSelect']//option[2]").click()
        driver.find_element_by_id("next-step").click()

        log_output("    Select stone type")
        if not driver.find_element_by_xpath(
                "//select[@id='stoneTypeSelect']//option[2]").is_selected():
            driver.find_element_by_xpath(
                "//select[@id='stoneTypeSelect']//option[2]").click()
        driver.find_element_by_xpath(
            "//div[@id='tab-stoneType']//a[.='Next']").click()

        log_output("    Select birthstone")
        driver.find_element_by_css_selector("span.month_text").click()
        driver.find_element_by_xpath(
            "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/span[2]").click()
        driver.find_element_by_xpath(
            "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/span[1]").click()
        driver.find_element_by_xpath(
            "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/input").click()
        driver.find_element_by_xpath(
            "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/span[1]").click()
        if not driver.find_element_by_xpath(
                "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/input"
        ).is_selected():
            driver.find_element_by_xpath(
                "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/input").click(
                )
        driver.find_element_by_link_text("SELECT").click()
        driver.find_element_by_xpath(
            "//div[@id='tab-stones']//a[.='Next']").click()
        driver.find_element_by_id("addToCart").click()
        driver.find_element_by_link_text("CHECKOUT").click()
        if not ("Shopping Bag (1 Item)"
                in driver.find_element_by_tag_name("html").text):
            success = False
            print("verifyTextPresent failed")

        #------Insert Script between these lines-----#

    finally:
        driver.quit()
        if not success:
            raise Exception("Test failed.")
Ejemplo n.º 39
0
# -*- coding: utf-8 -*-
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.common.action_chains import ActionChains
import time

success = True
wd = WebDriver()
wd.implicitly_wait(60)


def is_alert_present(wd):
    try:
        wd.switch_to_alert().text
        return True
    except:
        return False


try:
    wd.get("https://investor.vanguard.com/corporate-portal/")
    wd.find_element_by_css_selector("span.linkStyle").click()
    wd.find_element_by_link_text("Open an IRA in minutes").click()
finally:
    wd.quit()
    if not success:
        raise Exception("Test failed.")
Ejemplo n.º 40
0
class UITestCase(LiveServerTestCase):
    def use_xvfb(self):
        from pyvirtualdisplay import Display
        self.display = Display('xvfb',
                               visible=1,
                               size=(1280, 1024))
        self.display.start()
        self.driver = WebDriver()

    def setUp(self):
        try:
            self.driver = WebDriver()
            ui_is_not_available = False
        except WebDriverException:
            ui_is_not_available = True

        if ui_is_not_available:
            self.use_xvfb()

        self.driver.implicitly_wait(10)
        super(UITestCase, self).setUp()

    def tearDown(self):
        self.driver.quit()
        if hasattr(self, 'display'):
            self.display.stop()

        super(UITestCase, self).tearDown()

    def click(self, selector):
        self.find(selector).click()

    def find(self, selector):
        return self.driver.find_element_by_css_selector(selector)

    def find_name(self, name):
        return self.driver.find_element_by_name(name)

    def find_id(self, id):
        return self.driver.find_element_by_id(id)

    def process_login_form(self, username, password):
        username_elmt = self.find_name('username')
        password_elmt = self.find_name('password')

        username_elmt.send_keys(username)
        password_elmt.send_keys(password)

        self.click('form * button')

    def browse_to_url(self, url):
        self.driver.get(self.live_server_url + url)

    def find_anchor_by_url(self, url):
        return self.find("[href='%s']" % url)

    def wait_until_enabled(self, element, timeout=10):
        def isPresentAndEnabled(driver):
            return element.get_attribute("disabled") is None
        WebDriverWait(self.driver, timeout).until(isPresentAndEnabled)

    def wait_until_visible(self, element, timeout=10):
        def isPresentAndEnabled(driver):
            return element.is_displayed()
        WebDriverWait(self.driver, timeout).until(isPresentAndEnabled)
class PollsTest(LiveServerTestCase):

    def setUp(self):

        user = User()
        user.username = "******"
        user.email = "*****@*****.**"
        user.set_password("adm1n")
        user.is_active = True
        user.is_superuser = True
        user.is_staff = True
        user.save()
        
        self.browser = WebDriver()
        self.browser.implicitly_wait(3)
    
    def tearDown(self):
        self.browser.quit()

    def test_can_create_new_poll_via_admin_site(self):
        # Gertrude opens her web browser, and goes to the admin page
        self.browser.get(self.live_server_url + '/admin/')

        # She sees the familiar 'Django administration' heading
        body = self.browser.find_element_by_tag_name('body')
        self.assertIn('Django administration', \
                          body.find_element_by_id("header").text)

        # She types in her username and passwords and hits return
        username_field = self.browser.find_element_by_name('username')
        username_field.send_keys('admin')

        password_field = self.browser.find_element_by_name('password')
        password_field.send_keys('adm1n')

        password_field.send_keys(Keys.RETURN)

        # her username and password are accepted, and she is taken to
        # the Site Administration page
        body = self.browser.find_element_by_tag_name('body')
        self.assertIn('Site administration', body.text)

        # She now sees a couple of hyperlink that says "Polls"
        polls_links = self.browser.find_elements_by_link_text('Polls')
        self.assertEquals(len(polls_links), 2)

        # The second one looks more exciting, so she clicks it
        polls_links[1].click()

        # She is taken to the polls listing page, which shows she has
        # no polls yet
        body = self.browser.find_element_by_tag_name('body')
        self.assertIn('0 polls', body.text)

        # She sees a link to 'add' a new poll, so she clicks it
        new_poll_link = self.browser.find_element_by_link_text('Add poll')
        new_poll_link.click()

        # She sees some input fields for "Question" and "Date published"
        body = self.browser.find_element_by_tag_name('body')
        self.assertIn('Question:', body.text)
        self.assertIn('Date published:', body.text)

        # She types in an interesting question for the Poll
        question_field = self.browser.find_element_by_name('question')
        question_field.send_keys("How awesome is Test-Driven Development?")

        # She sets the date and time of publication - it'll be a new year's
        # poll!
        date_field = self.browser.find_element_by_name('pub_date_0')
        date_field.send_keys('01/01/12')
        time_field = self.browser.find_element_by_name('pub_date_1')
        time_field.send_keys('00:00')

        # Gertrude clicks the save button
        save_button = self.browser.find_element_by_css_selector("input[value='Save']")
        save_button.click()
            
        # She is returned to the "Polls" listing, where she can see her
        # new poll, listed as a clickable link
        new_poll_links = self.browser.find_elements_by_link_text(
                "How awesome is Test-Driven Development?"
        )

        self.assertEquals(len(new_poll_links), 1)
Ejemplo n.º 42
0
class UITestCase(StaticLiveServerTestCase):
    def use_xvfb(self):
        from pyvirtualdisplay import Display
        self.display = Display('xvfb',
                               visible=1,
                               size=(DISPLAY_WIDTH, DISPLAY_HEIGHT))
        self.display.start()
        self.driver = WebDriver()

    def setUp(self):
        try:
            self.driver = WebDriver()
            ui_is_not_available = False
        except WebDriverException:
            ui_is_not_available = True

        if ui_is_not_available:
            self.use_xvfb()

        self.driver.set_window_size(DISPLAY_WIDTH, DISPLAY_HEIGHT)

        self.driver.implicitly_wait(10)

        clear_caches()
        setup_for_ui_test()

        super(UITestCase, self).setUp()

    def tearDown(self):
        self.driver.quit()
        if hasattr(self, 'display'):
            self.display.stop()

        ContentType.objects.clear_cache()

        super(UITestCase, self).tearDown()

    def click(self, selector):
        self.find(selector).click()

    def click_when_visible(self, selector):
        element = self.find(selector)
        self.wait_until_visible(element)
        element.click()

    def find(self, selector):
        return self.driver.find_element_by_css_selector(selector)

    def find_name(self, name):
        return self.driver.find_element_by_name(name)

    def find_id(self, id):
        return self.driver.find_element_by_id(id)

    def is_visible(self, selector):
        element = self.find(selector)
        return element is not None and element.is_displayed()

    def process_login_form(self, username, password):
        username_elmt = self.wait_until_present('[name="username"]')
        password_elmt = self.find_name('password')

        username_elmt.send_keys(username)
        password_elmt.send_keys(password)

        self.click('form * button')

    def browse_to_url(self, url):
        self.driver.get(self.live_server_url + url)

    def browse_to_instance_url(self, url, instance=None):
        instance = instance if instance is not None else self.instance
        self.driver.get('%s/%s/%s' % (self.live_server_url,
                                      instance.url_name,
                                      url))

    def find_anchor_by_url(self, url):
        return self.find("[href='%s']" % url)

    def wait_until_present(self, selector, timeout=10):
        """
        Wait until an element with CSS 'selector' exists on the page.
        Useful for detecting that an operation loads the page you're expecting.
        """
        element = [None]  # use list so it can be set by inner scope

        def is_present(driver):
            element[0] = self.find(selector)
            return element[0] is not None and element[0].is_displayed()

        WebDriverWait(self.driver, timeout).until(is_present)
        return element[0]

    def wait_until_text_present(self, text, timeout=10):
        """
        Wait until 'text' exists on the page.
        Useful for detecting that an operation loads the page you're expecting.
        """
        WebDriverWait(self.driver, timeout).until(
            lambda driver: text in driver.page_source)

    def wait_until_enabled(self, element_or_selector, timeout=10):
        """
        Wait until 'element_or_selector' is enabled.
        """
        element = self._get_element(element_or_selector)
        WebDriverWait(self.driver, timeout).until(
            lambda driver: element.get_attribute("disabled") is None)
        return element

    def wait_until_visible(self, element_or_selector, timeout=10):
        """
        Wait until 'element_or_selector' (known to already exist on the page)
        is displayed.
        """
        element = self._get_element(element_or_selector)
        WebDriverWait(self.driver, timeout).until(
            lambda driver: element.is_displayed())
        return element

    def wait_until_invisible(self, element_or_selector, timeout=10):
        """
        Wait until 'element_or_selector' (known to already exist on the page)
        is not displayed.
        """
        element = self._get_element(element_or_selector)

        def is_invisible(driver):
            try:
                return not element.is_displayed()
            except StaleElementReferenceException:
                return True

        WebDriverWait(self.driver, timeout).until(is_invisible)
        return element

    def wait_for_input_value(self, element_or_selector, value, timeout=10):
        """
        Wait until 'element_or_selector' input has the specified value
        """
        element = self._get_element(element_or_selector)
        WebDriverWait(self.driver, timeout).until(
            # It seems wrong, but selenium fetches the value of an input
            # element using get_attribute('value')
            lambda driver: element.get_attribute('value') == value)
        return element

    def _get_element(self, element_or_selector):
        if isinstance(element_or_selector, basestring):
            return self.find(element_or_selector)
        else:
            return element_or_selector
Ejemplo n.º 43
0
def click_todo_checkbox(driver: WebDriver, todo_name: str):
    driver.find_element_by_css_selector(f'[aria-label="todo {todo_name} checkbox"]').click()
Ejemplo n.º 44
0
class TunesFunctionalTestCase(LiveServerTestCase):

    @classmethod
    def setUpClass(self):
        self.user = User.objects.create(email="*****@*****.**")
        self.user.set_password("password")
        self.user.save()
        
        self.selenium = WebDriver()
        super(TunesFunctionalTestCase, self).setUpClass()

    @classmethod
    def tearDownClass(self):
        self.selenium.quit()
        super(TunesFunctionalTestCase, self).tearDownClass()
    
    def test_login_and_add_tune_info(self):
        """
        Log in to the site, find a tune by name, and add some
        info about it.
        """

        # Jill goes to the home page of the site and logs in
        self.selenium.get(self.live_server_url)
        self.selenium.find_element_by_css_selector("a#tuw-login").click()
        username_input = self.selenium.find_element_by_name("username")
        username_input.send_keys('*****@*****.**')
        password_input = self.selenium.find_element_by_name("password")
        password_input.send_keys('password')
        self.selenium.find_element_by_css_selector('form#tuw-login button#tuw-submit-login').click()

        # she clicks the "Tunes" nav button
        self.selenium.find_element_by_css_selector('a#tuw-tunes').click()

        # and then clicks "Add a New Tune"
        self.selenium.find_element_by_css_selector('a#tuw-new-tune').click()

        # she searches for the word "Night"
        search_form = self.selenium.find_element_by_name("search")
        search_form.send_keys("Night")
        self.selenium.find_element_by_css_selector('form#tuw-login input#tuw-submit-search') 

        # and sees a few options
        #   "The Night Has a Thousand Eyes"
        #   "Night in Tunisia"
        #   "Night Train"
        
        # She selects "Night Train, and since we already have some info
        # about this tune in the database, she sees and partially
        # filled form

        # She adds what data she can about "Night Train" and 
        # saves the form

        # She wants to add another tune to the database, so she clicks
        # "Edit Another Tune"

        # She searches for the word "Mood"

        # and sees a few options
        #   "Mood Indigo"
        #   "In a Sentimental Mood"

        # She selects "In a Sentimental Mood", and since there's no 
        # info in the database about this tune yet, she see's a 
        # completely empty form

        # She enters all the information she knows about this tune in
        # in the form and clicks save.

        # When shes's done, she goes to the home page to the home page
        # and sees the newly added tunes

        self.fail("FINISH THE TEST")
Ejemplo n.º 45
0
class SeleniumRunner:
    """
    A runner that upload and download Icomoon resources using Selenium.
    The WebDriver will use Firefox.
    """

    """
    The long wait time for the driver in seconds.
    """
    LONG_WAIT_IN_SEC = 25

    """
    The medium wait time for the driver in seconds.
    """
    MED_WAIT_IN_SEC = 6

    """
    The short wait time for the driver in seconds.
    """
    SHORT_WAIT_IN_SEC = 2.5

    """
    The short wait time for the driver in seconds.
    """
    BRIEF_WAIT_IN_SEC = 0.6

    """
    The Icomoon Url.
    """
    ICOMOON_URL = "https://icomoon.io/app/#/select"

    """
    General import button CSS for Icomoon site.
    """
    GENERAL_IMPORT_BUTTON_CSS = "div#file input[type=file]"

    """
    Set import button CSS for Icomoon site.
    """
    SET_IMPORT_BUTTON_CSS = "li.file input[type=file]"

    """
    The CSS of the tool bar options. There are more but
    these are the ones that we actually use.
    """
    TOOLBAR_OPTIONS_CSS = {
        IcomoonOptionState.SELECT: "div.btnBar button i.icon-select",
        IcomoonOptionState.EDIT: "div.btnBar button i.icon-edit"
    }

    """
    The URL to go to different pages within the Icomoon domain. 
    There are more but these are the ones that we actually use.
    """
    PAGES_URL = {
        IcomoonPage.SELECTION: ICOMOON_URL,
        IcomoonPage.GENERATE_FONT: ICOMOON_URL + "/font"
    }

    """
    The different types of alerts that this workflow will encounter.
    It contains part of the text in the actual alert and buttons
    available to press. It's up to the user to know what button to 
    press for which alert.
    """
    ALERTS = {
        IcomoonAlerts.STROKES_GET_IGNORED_WARNING: {
            "text": "Strokes get ignored when generating fonts or CSH files.",
            "buttons": {
                "DISMISS": "Dismiss",
            }
        },
        IcomoonAlerts.REPLACE_OR_REIMPORT_ICON : {
            "text": "Replace existing icons?",
            "buttons": {
                "REPLACE": "Replace",
                "REIMPORT": "Reimport"
            }
        },
        IcomoonAlerts.DESELECT_ICONS_CONTAINING_STROKES: {
            "text": "Strokes get ignored when generating fonts.",
            "buttons": {
                "DESELECT": "Deselect",
                "CONTINUE": "Continue"
            }
        }
    }

    def __init__(self, download_path: str,
                 geckodriver_path: str, headless: bool):
        """
        Create a SeleniumRunner object.
        :param download_path: the location where you want to download
        the icomoon.zip to.
        :param geckodriver_path: the path to the firefox executable.
        :param headless: whether to run browser in headless (no UI) mode.
        """
        self.driver = None
        # default values when we open Icomoon
        self.current_option_state = IcomoonOptionState.SELECT
        self.current_page = IcomoonPage.SELECTION
        self.set_browser_options(download_path, geckodriver_path, headless)

    def set_browser_options(self, download_path: str, geckodriver_path: str,
        headless: bool):
        """
        Build the WebDriver with Firefox Options allowing downloads and
        set download to download_path.
        :param download_path: the location where you want to download
        :param geckodriver_path: the path to the firefox executable.
        the icomoon.zip to.
        :param headless: whether to run browser in headless (no UI) mode.

        :raises AssertionError: if the page title does not contain
        "IcoMoon App".
        """
        options = Options()
        allowed_mime_types = "application/zip, application/gzip, application/octet-stream"
        # disable prompt to download from Firefox
        options.set_preference("browser.helperApps.neverAsk.saveToDisk", allowed_mime_types)
        options.set_preference("browser.helperApps.neverAsk.openFile", allowed_mime_types)

        # set the default download path to downloadPath
        options.set_preference("browser.download.folderList", 2)
        options.set_preference("browser.download.dir", download_path)
        options.headless = headless

        print("Activating browser client...")
        self.driver = WebDriver(options=options, executable_path=geckodriver_path)
        self.driver.get(self.ICOMOON_URL)
        assert "IcoMoon App" in self.driver.title
        # wait until the whole web page is loaded by testing the hamburger input
        WebDriverWait(self.driver, self.LONG_WAIT_IN_SEC).until(
            ec.element_to_be_clickable((By.XPATH, "(//i[@class='icon-menu'])[2]"))
        )
        print("Accessed icomoon.io")

    def switch_toolbar_option(self, option: IcomoonOptionState):
        """
        Switch the toolbar option to the option argument.
        :param option: an option from the toolbar of Icomoon.
        """
        if self.current_option_state == option:
            return

        option_btn = self.driver.find_element_by_css_selector(
            SeleniumRunner.TOOLBAR_OPTIONS_CSS[option]
        )
        option_btn.click()
        self.current_option_state = option

    def click_hamburger_input(self):
        """
        Click the hamburger input until the pop up menu appears. This
        method is needed because sometimes, we need to click the hamburger
        input two times before the menu appears.
        :return: None.
        """
        top_set_hamburger_input_xpath = '//*[@id="setH2"]/button[1]/i' 
        hamburger_input = self.driver.find_element_by_xpath(
            top_set_hamburger_input_xpath
        )

        menu_appear_callback = ec.element_to_be_clickable(
            (By.CSS_SELECTOR, "h1 ul.menuList2")
        )

        while not menu_appear_callback(self.driver):
            hamburger_input.click()

    def test_for_possible_alert(self, wait_period: float) -> IcomoonAlerts:
        """
        Test for the possible alerts that might appear. Return the 
        type of alert if one shows up.
        :param wait_period: the wait period for the possible alert
        in seconds.
        :return: an IcomoonAlerts enum representing the alert that was found.
        Else, return None.
        """
        try:
            overlay_div = WebDriverWait(self.driver, wait_period, 0.15).until(
                ec.element_to_be_clickable(
                    (By.XPATH, "//div[@class='overlay']"))
            )
            alert_message = overlay_div.text
            for alert in self.ALERTS.keys():
                if self.ALERTS[alert]["text"] in alert_message:
                    return alert

            return IcomoonAlerts.UNKNOWN
        except SeleniumTimeoutException:
            return None  # nothing found => everything is good

    def click_alert_button(self, btn_text: str):
        """
        Click the button in the alert that matches the button text.
        :param btn_text: the text that the alert's button will have.
        """
        try:
            button = WebDriverWait(self.driver, self.BRIEF_WAIT_IN_SEC, 0.15).until(
                ec.element_to_be_clickable(
                    (By.XPATH, f"//div[@class='overlay']//button[text()='{btn_text}']"))
            )
            button.click()
        except SeleniumTimeoutException:
            return None  # nothing found => everything is good

    def edit_svg(self, screenshot_folder: str=None, index: int=None):
        """
        Edit the SVG. This include removing the colors and take a
        snapshot if needed.
        :param screenshot_folder: a string or Path object. Point to 
        where we store the screenshots. If truthy, take a screenshot 
        and save it here.
        :param index: the index of the icon in its containing list. 
        Used to differentiate the screenshots. Must be truthy if 
        screenshot_folder is a truthy value.
        """
        self.switch_toolbar_option(IcomoonOptionState.EDIT)
        self.click_latest_icons_in_top_set(1)

        # strip the colors from the SVG.
        # This is because some SVG have colors in them and we don't want to
        # force contributors to remove them in case people want the colored SVGs.
        # The color removal is also necessary so that the Icomoon-generated
        # icons fit within one font symbol/ligiature.
        try:
            color_tab = WebDriverWait(self.driver, self.BRIEF_WAIT_IN_SEC).until(
                ec.element_to_be_clickable((By.CSS_SELECTOR, "div.overlayWindow i.icon-droplet"))
            )
            color_tab.click()

            remove_color_btn = self.driver \
                .find_element_by_css_selector("div.overlayWindow i.icon-droplet-cross")
            remove_color_btn.click()
        except SeleniumTimeoutException:
            pass # do nothing cause sometimes, the color tab doesn't appear in the site

        if screenshot_folder != None and index != None:
            edit_screen_selector = "div.overlay div.overlayWindow"
            screenshot_path = str(
                Path(screenshot_folder, f"new_svg_{index}.png").resolve()
            )
            edit_screen = self.driver.find_element_by_css_selector(
                edit_screen_selector)
            edit_screen.screenshot(screenshot_path)
            print("Took screenshot of svg and saved it at " + screenshot_path)

        close_btn = self.driver \
            .find_element_by_css_selector("div.overlayWindow i.icon-close")
        close_btn.click()

    def click_latest_icons_in_top_set(self, amount: int):
        """
        Click on the latest icons in the top set based on the amount passed in.
        This is state option agnostic (doesn't care if it's in SELECT or EDIT mode).
        :param amount: the amount of icons to click on from top left of the top
        set. Must be > 0.
        """
        icon_base_xpath = '//div[@id="set0"]//mi-box[{}]//div'
        for i in range(1, amount + 1):
            icon_xpath = icon_base_xpath.format(i)
            latest_icon = self.driver.find_element_by_xpath(icon_xpath)
            latest_icon.click()

    def select_all_icons_in_top_set(self):
        """
        Select all the svgs in the top most (latest) set.
        """
        self.click_hamburger_input()
        select_all_button = WebDriverWait(self.driver, self.LONG_WAIT_IN_SEC).until(
            ec.element_to_be_clickable((By.XPATH, "//button[text()='Select All']"))
        )
        select_all_button.click()

    def deselect_all_icons_in_top_set(self):
        """
        Select all the svgs in the top most (latest) set.
        """
        self.click_hamburger_input()
        select_all_button = WebDriverWait(self.driver, self.LONG_WAIT_IN_SEC).until(
            ec.element_to_be_clickable((By.XPATH, "//button[text()='Deselect']"))
        )
        select_all_button.click()

    def go_to_page(self, page: IcomoonPage):
        """
        Go to the specified page in Icomoon. This used the URL rather than UI 
        elements due to the inconsistent UI rendering.
        :param page: a valid page that can be accessed in Icomoon.
        """
        if self.current_page == page:
            return

        self.driver.get(self.PAGES_URL[page])
        self.current_page = page

    def close(self):
        """
        Close the SeleniumRunner instance.
        """
        print("Closing down SeleniumRunner...")
        self.driver.quit()