示例#1
0
def _continue_shopping(browser: webdriver.WebDriver, task_data: TaskData,
                       product_name: str):
    wait(
    )  # Wait a little longer to ensure the product is added and popup is presented

    logging.info("Clicking on \"Continue Shopping\" button")
    continue_shopping_button_xpath = "//div[contains(@class, 'modal_container')] " \
                                     "//a[(contains(translate(text(), " \
                                     "'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), " \
                                     "'continue shopping'))]"
    wait()  # Wait a little longer to ensure the popup is presented
    WebDriverWait(browser, 10).until(
        ec.presence_of_element_located(
            (By.XPATH, continue_shopping_button_xpath)))
    WebDriverWait(browser, 10).until(
        ec.element_to_be_clickable((By.XPATH, continue_shopping_button_xpath)))
    browser.find_element_by_xpath(continue_shopping_button_xpath).click()
    wait()

    logging.info(
        "Adding product {} to list and closing the Product Details Page".
        format(product_name))
    task_data.products.append(product_name)

    if len(task_data.products) >= 3:
        _receive_reward(browser, task_data)

    close_current_tab(browser)
示例#2
0
class BaseLiveServerTestCase(LiveServerTestCase):
    def setUp(self):
        get_or_create_test_admin()
        self.browser = WebDriver()
        self.do_admin_login('test', 'test')

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

    def do_admin_login(self, username, password):
        self.browser.get('%s%s' % (self.live_server_url, '/admin/'))
        username_input = self.browser.find_element_by_name("username")
        username_input.send_keys(username)
        password_input = self.browser.find_element_by_name("password")
        password_input.send_keys(password)
        self.browser.find_element_by_xpath('//input[@value="Log in"]').click()

    def new_window(self, name='other'):
        self.browser.execute_script('window.open("/admin/", "'+ name +'")')
        self.browser.switch_to_window(self.browser.window_handles[1])
        while self.warning_element() is False:
            time.sleep(0.1)
        self.browser.switch_to_window(self.browser.window_handles[0])

    def press_space(self):
        a = ActionChains(self.browser)
        a.key_down(Keys.SPACE)
        a.perform()

    def wait_for_pages_loaded(self):
        for win in self.browser.window_handles:
            while self.warning_element() is False:
                time.sleep(0.1)
示例#3
0
class BasicViewTests(unittest.TestCase):
    """
    Just visit all the views and make sure they look okay
    """

    def setUp(self):

        self.selenium = WebDriver()
        self.live_server_url = LIVE_SERVER_URL

        # login boilerplate blah
        self.selenium.get(self.live_server_url + '/login')
        username_input = self.selenium.find_element_by_name("username_or_email")
        username_input.send_keys(ADMIN_USERNAME)
        password_input = self.selenium.find_element_by_name("password")
        password_input.send_keys(ADMIN_PASSWORD)
        self.selenium.find_element_by_xpath('//button[@type="submit"]').click()

    def test_home(self):

        self.selenium.get(self.live_server_url + '/')

        # two project links are there
        self.selenium.find_element_by_link_text('1000 Genomes')

    def test_project_home(self):

        self.selenium.get(self.live_server_url + '/project/1kg')

    def test_family_home(self):

        self.selenium.get(self.live_server_url + '/project/1kg/family/HG1')

    def tearDown(self):
        self.selenium.quit()
示例#4
0
def _remove_one_product_from_wish_list(browser: webdriver.WebDriver,
                                       product: str):
    delete_core_xpath = "//div[contains(@class, 'wishlist-product')]" \
                        "//div[contains(@class, 'product-cnt')]" \
                        "//ul[contains(@class, 'product-list') and contains(@class, 'cf')]"
    delete_button_xpath = f"{delete_core_xpath}" \
                          f"//span[contains(@class, 'options')]//span[contains(@class, 'options-remove')]//i"
    delete_popup_yes_xpath = f"{delete_core_xpath}" \
                             f"//span[contains(@class, 'remove-pop')]//p[contains(@class, 'p-btn')]" \
                             f"//span[contains(@class, 'p-btn-yes')]"

    product_element = browser.find_element_by_xpath(f"{delete_core_xpath}//li")
    scroll_to_and_hover_over_element(browser, product_element)

    logging.info("Clicking on delete button")
    WebDriverWait(browser, 10).until(
        ec.presence_of_element_located((By.XPATH, delete_button_xpath)))
    WebDriverWait(browser, 10).until(
        ec.element_to_be_clickable((By.XPATH, delete_button_xpath)))
    browser.find_element_by_xpath(delete_button_xpath).click()
    wait()

    logging.info("Confirming deletion")
    WebDriverWait(browser, 10).until(
        ec.presence_of_element_located((By.XPATH, delete_popup_yes_xpath)))
    WebDriverWait(browser, 10).until(
        ec.element_to_be_clickable((By.XPATH, delete_popup_yes_xpath)))
    browser.find_element_by_xpath(delete_popup_yes_xpath).click()
    wait()

    logging.info(f"Product {product} deleted successfully from the wish list")
示例#5
0
def check_if_element_exist(driver: WebDriver, xpath: str) -> bool:
    try:
        driver.find_element_by_xpath(xpath)

    except NoSuchElementException:
        return False

    return True
示例#6
0
def process_search(d: WebDriver, email: str) -> int:
    d.get(url=leakedsource_url)
    submit = d.find_element_by_xpath('/html/body/center[2]/div/form/div/div[2]/center/input')
    email_field = d.find_element_by_xpath('/html/body/center[2]/div[1]/form/div/div[2]/div[1]/div/input')
    email_field.send_keys(email)
    submit.click()
    result = WebDriverWait(d, 10).until(
        ec.presence_of_element_located((By.XPATH, '/html/body/center[2]/div[2]'))
    )
    return 'no results found.' not in result.text.lower()
示例#7
0
def process_search(d: WebDriver, email: str) -> int:
    d.get(url=firefox_url)
    form = d.find_element_by_xpath('//*[@id="scan-user-email"]')
    email_field = d.find_element_by_xpath('//*[@id="scan-email"]')
    email_field.send_keys(email)
    form.submit()
    results_count = WebDriverWait(d, 10).until(
        ec.presence_of_element_located(
            (By.XPATH, '/html/body/main/div[1]/div/h2/span')))
    return int(results_count.text)
示例#8
0
def syn_test_script():

    try:
        success = True
        driver = WebDriver()
        driver.implicitly_wait(30)


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

        log_output("Navigating to Engagement Rings")
        ActionChains(driver).move_to_element(driver.find_element_by_xpath("//div[3]/div[2]/div/div/div[3]/nav/div/ul/li[4]/a[2]")).perform()
        driver.find_element_by_xpath("//div[3]/div[2]/div/div/div[3]/nav/div/ul/li[4]/ul/li[2]/div/div/div[2]/ul/li[2]/ul/li/ul/li[1]/a").click()

        time.sleep(2)
        if not ("Engagement" in driver.find_element_by_tag_name("html").text):
            success = False
            print("Did not find word engagement on page in reasonable time")

        log_output("Changing price range to 3rd facet")
        if not driver.find_element_by_id("facet_checkbox7").is_selected():
            driver.find_element_by_id("facet_checkbox7").click()
        time.sleep(3)

        log_output("Viewing more rings")
        driver.find_element_by_id("view-more").click()

        log_output("Select a nice ring")
        driver.find_element_by_xpath("//div[3]/div[2]/div/div/div[4]/div[7]/div[2]/div[2]/div[7]/div[37]/div/a/img").click()

        #log_output("starting timer")
        #time.sleep(5)
        log_output("Add Ring to bag")
        # There is a bit of funkiness with this Product page and the overlay when you add an item to Cart
        # Sometimes the addToCartBtn is not immediately available and can time out or error out
        # The 5 second sleep timer above is disabled, but if we see issues this may need re-anabled
        # or use WebDriverWait
        ActionChains(driver).move_to_element(driver.find_element_by_xpath("//a[@id='addToCartBtn']")).perform()
        driver.find_element_by_xpath("//a[@id='addToCartBtn']")
        driver.find_element_by_xpath("//a[@id='addToCartBtn']").click()

        log_output("Adding coverage")
        driver.find_element_by_link_text("ADD TO BAG").click()

        log_output("Checking out with a beautiful ring!")
        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")

    finally:
        driver.quit()
        if not success:
            raise Exception("Test failed.")
示例#9
0
class Base:
    @classmethod
    def __init__(self, p_live_server_url):
        self.live_server_url = p_live_server_url
        self.driver = WebDriver()

    @classmethod
    def pause(self, p_seconds):
        try:
            WebDriverWait(self.driver, p_seconds).until(EC.title_is('pause'))
        except:
            pass

    @classmethod
    def grid_cell_doubleclick(self, p_element):
        ActionChains(self.driver).double_click(p_element).perform()

    @classmethod
    def grid_cell_input(self, p_element, p_text):
        self.grid_cell_doubleclick(p_element)
        for k in range(0, len(p_element.text)):
            p_element.send_keys(Keys.BACKSPACE)
        p_element.send_keys(p_text)

    @classmethod
    def action_login(self, p_username, p_password, p_expectsuccess=True):
        self.driver.get('{0}{1}'.format(self.live_server_url, '/login/'))
        WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, 'body')))
        username_input = self.driver.find_element_by_id('txt_user')
        username_input.send_keys(p_username)
        password_input = self.driver.find_element_by_id('txt_pwd')
        password_input.send_keys(p_password)
        self.driver.find_element_by_xpath("//button[. = 'Sign in']").click()
        if p_expectsuccess:
            try:
                WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, 'header')))
            except:
                WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located((By.CLASS_NAME, 'div_alert_text')))
        else:
            try:
                WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located((By.CLASS_NAME, 'div_alert_text')))
            except:
                WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, 'header')))

    @classmethod
    def action_create_user(self, p_username, p_password, p_superuser):
        self.driver.get('{0}{1}'.format(self.live_server_url, '/users/'))
        WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, 'body')))
        assert 'OmniDB' in self.driver.title
        self.driver.find_element_by_xpath("//button[. = 'New User']").click()
        username_cell = self.driver.find_element_by_xpath("//tbody/tr[last()]/td[1]")
        self.grid_cell_input(username_cell, p_username)
        password_cell = self.driver.find_element_by_xpath("//tbody/tr[last()]/td[2]")
        self.grid_cell_input(password_cell, p_password)
        if p_superuser:
            superuser_cell = self.driver.find_element_by_xpath("//tbody/tr[last()]/td[3]")
            self.grid_cell_doubleclick(superuser_cell)
        self.driver.find_element_by_tag_name('body').click()
        self.driver.find_element_by_xpath("//button[. = 'Save Data']").click()
示例#10
0
def pass_xing_login(driver: WebDriver, xing_login: str,
                    xing_pass: str) -> bool:
    """
    pass login on XING using driver and login/password
    :Returns:
        * True - login successfull
        * False - can't login
    """
    url = 'https://loginix.com/'
    driver.get(url)
    sleep(3)
    try:
        permission_accept: WebElement = driver.find_element_by_xpath(
            '//*[@id="consent-accept-button"]')
        permission_accept.click()
    except NoSuchElementException:
        # no question about privacy
        pass

    try:
        driver.find_element_by_name("username").send_keys(xing_login)
    except NoSuchElementException:
        print("no element by name: username")
        return False

    try:
        driver.find_element_by_name("password").send_keys(xing_pass)
    except NoSuchElementException:
        print("no element by name: password")
        return False

    try:
        driver.find_element_by_xpath(
            "/html/body/div[1]/div[2]/div/div[2]/section/div/main/div/div/div/div/div/form/div[5]/button/div"
        ).click()
    except NoSuchElementException:
        print("no element button login ")
        return False
    sleep(2)

    try:
        driver.find_element_by_xpath(
            "/html/body/div[1]/div[2]/div/div[2]/section/div/main/div/div/div/div/div[2]/div[2]/button[1]/div/span"
        ).click()
        sleep(2)
    except NoSuchElementException:
        # no element 'Try two factor authentication' with button Skip
        pass

    return True
示例#11
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()
示例#12
0
def add_product_to_cart(browser: webdriver.WebDriver, li_element,
                        task_data: TaskData):
    product_name = _open_product_details_page_and_get_product_name(
        browser, li_element)

    logging.info("Finding the add to cart button")
    add_to_cart_button_xpath = "/html/body/div[8]/div/div[2]/form/div[5]/div[1]/a[1]"
    WebDriverWait(browser, 10).until(
        ec.presence_of_element_located((By.XPATH, add_to_cart_button_xpath)))
    wait()
    logging.info("Clicking the add to cart button")
    browser.find_element_by_xpath(add_to_cart_button_xpath).click()
    wait()

    _continue_shopping(browser, task_data, product_name)
示例#13
0
def add_product_to_wish_list(browser: webdriver.WebDriver, li_element,
                             task_data: TaskData):
    product_name = _open_product_details_page_and_get_product_name(
        browser, li_element)

    logging.info("Finding the add to wish list button")
    add_to_wish_list_button_xpath = "//span[contains(@class, 'wish_text')]" \
                                    "/ancestor::div[contains(@class, 'addToWish')]"

    WebDriverWait(browser, 10).until(
        ec.presence_of_element_located(
            (By.XPATH, add_to_wish_list_button_xpath)))
    wait()
    add_to_wish_list_button_element = browser.find_element_by_xpath(
        add_to_wish_list_button_xpath)
    logging.info("Checking if the product is already in the wish list")
    if "add to wishlist" in add_to_wish_list_button_element.text.lower():
        logging.info("Clicking the add to wish list button")
        add_to_wish_list_button_element.click()
        wait()
        _continue_shopping(browser, task_data, product_name)
    else:
        logging.info(
            "{} is already added to the wish list".format(product_name))
        logging.warning(
            "Raising an exception. This is OK. By raising the exception this product will be skipped"
        )
        raise ProductAlreadyInWishListException(product_name)
示例#14
0
文件: base.py 项目: ilyash/appstore
class BaseStoreTest(StaticLiveServerTestCase):
    def by_id(self, id):
        return self.selenium.find_element_by_id(id)

    def by_css(self, selector):
        return self.selenium.find_element_by_css_selector(selector)

    def by_name(self, name: str):
        return self.selenium.find_element_by_name(name)

    def setUp(self):
        self.selenium = WebDriver()
        self.selenium.implicitly_wait(SELENIUM_WAIT_SEC)
        create_user(TEST_USER, TEST_PASSWORD, TEST_EMAIL)

    def tearDown(self):
        delete_user(TEST_USER)
        self.selenium.quit()
        super().tearDown()

    def go_to(self, url_name: str, kwargs: Dict[str, str] = None) -> None:
        app_url = reverse(url_name, kwargs=kwargs)
        self.selenium.get('%s%s' % (self.live_server_url, app_url))

    def go_to_app(self, app_id):
        self.go_to('app-detail', {'id': app_id})

    def go_to_app_register(self):
        self.go_to('app-register')

    def go_to_app_upload(self):
        self.go_to('app-upload')

    def login(self, user: str = TEST_USER, password: str = TEST_PASSWORD):
        self.selenium.get('%s%s' % (self.live_server_url, '/login/'))
        user_input = self.selenium.find_element_by_name("login")
        user_input.send_keys(user)
        pass_input = self.selenium.find_element_by_name("password")
        pass_input.send_keys(password)
        self.selenium.find_element_by_xpath('//button[@type="submit"]').click()

    def wait_for(self, selector: str, then: Callable[[WebElement],
                                                     None]) -> None:
        element = WebDriverWait(self.selenium, SELENIUM_WAIT_SEC).until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, selector)))
        then(element)
示例#15
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()
示例#16
0
def get_current_amount_of_points(browser: webdriver.WebDriver,
                                 is_tasks_finished: bool):
    available_points_div_xpath = "//div[contains(@class, 'myaccount-points-total')]" \
                                 "//ul//li//div[contains(@class, 'number')]"
    points_xpath = f"{available_points_div_xpath}//p[contains(@class, 'num-p')]"
    cash_xpath = f"{available_points_div_xpath}//span[contains(@class, 'cash')]"

    when = "before"
    if is_tasks_finished:
        when = "after"

    points = int(browser.find_element_by_xpath(points_xpath).text)
    cash = browser.find_element_by_xpath(cash_xpath).text
    logging.info("\n\n")
    logging.info(f"\n\nPoints {when} all tasks are completed: {points}")
    logging.info(f"Cash {when} all tasks are completed: {cash}\n")

    return points
示例#17
0
def _search_for_product_in_wish_list_and_get_input_field_element(
        browser: webdriver.WebDriver, product: str) -> WebElement:
    logging.info("Finding the search button and clicking on it.")

    if "+" in product:
        logging.info("Invalid character '+' detected.")
        product = product.split("+")[0]
        logging.warning(
            f"Using {product} in the search. Potentially the wrong product can be returned..."
        )
        logging.info(
            f"This hack was necessary as Banggood search on wish lists does not allow '+' character"
        )

    search_component_xpath = "//li[contains(@class, 'wishlist-nav-search')]"
    search_span_xpath = f"{search_component_xpath}//span[contains(@class, 'search-inner')]"
    search_button_xpath = f"{search_span_xpath}" \
                          f"//span[contains(@class, 'icon-search_new') and contains(@class, 'search-btn')]"
    search_input_field_xpath = f"{search_span_xpath}//input[contains(@class, 'search-text')]"

    logging.info("Clicking on a search button to activate the input field")
    WebDriverWait(browser, 10).until(
        ec.presence_of_element_located((By.XPATH, search_button_xpath)))
    WebDriverWait(browser, 10).until(
        ec.element_to_be_clickable((By.XPATH, search_button_xpath)))
    search_button_element = browser.find_element_by_xpath(search_button_xpath)
    scroll_to_and_hover_over_element(browser, search_button_element)
    search_button_element.click()

    logging.info("Filling out the input field")
    WebDriverWait(browser, 10).until(
        ec.presence_of_element_located((By.XPATH, search_input_field_xpath)))
    WebDriverWait(browser, 10).until(
        ec.element_to_be_clickable((By.XPATH, search_input_field_xpath)))
    search_input_field_element = browser.find_element_by_xpath(
        search_input_field_xpath)
    search_input_field_element.send_keys(product)

    logging.info("Clicking on a search button again to perform the search")
    browser.find_element_by_xpath(search_button_xpath).click()
    wait()

    return search_input_field_element
示例#18
0
class CoreTestIndexPage(StaticLiveServerTestCase):
    def setUp(self):
        self.url = "{}{}".format(self.live_server_url, reverse('core:index'))
        self.driver = WebDriver()
        self.driver.implicitly_wait(5)

    def test_index_page_is_working_message(self):
        self.driver.get(self.url)
        working_message = self.driver.find_element_by_xpath('//h1').text

        self.assertEquals('Django Boilerplate is working !', working_message)
示例#19
0
class AnonymousUseCaseTests(LiveServerTestCase):
    fixtures = ['user']

    @classmethod
    def setUpClass(self):
        self.selenium = WebDriver()
        super(AnonymousUseCaseTests, self).setUpClass()
        self.timeout = 10

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

    def test_login(self):
        self.selenium.get('%s%s' % (self.live_server_url, '/login/'))
        self.assertEquals(self.selenium.title, "Squire Learning Application")
        username_input = self.selenium.find_element_by_name("username")
        username_input.send_keys('super')
        password_input = self.selenium.find_element_by_name("password")
        password_input.send_keys('super')
        self.selenium.find_element_by_xpath('//input[@value="Login"]').click()
        WebDriverWait(self.selenium, self.timeout).until(
            lambda driver: driver.find_element_by_tag_name('body'))
        self.assertEquals(self.selenium.current_url,
                '%s%s' % (self.live_server_url, '/hr/profile/'))

    def test_unsuccessful_login(self):
        self.selenium.get('%s%s' % (self.live_server_url, '/login/'))
        self.assertEquals(self.selenium.title, "Squire Learning Application")
        username_input = self.selenium.find_element_by_name("username")
        username_input.send_keys('super')
        password_input = self.selenium.find_element_by_name("password")
        password_input.send_keys('duper')
        self.selenium.find_element_by_xpath('//input[@value="Login"]').click()
        WebDriverWait(self.selenium, self.timeout).until(
            lambda driver: driver.find_element_by_tag_name('body'))
        self.assertEquals(self.selenium.current_url,
                '%s%s' % (self.live_server_url, '/login/'))
        self.assertTrue(
                self.selenium.page_source.find("Please try again.") > 0)
示例#20
0
class Selenium_old_lwt(StaticLiveServerTestCase):
    ''' it tests with the fixture from "old_lwt' (the non opensource version)'''

    fixtures = ['lwt/fixtures/old_lwt.json']

    def setUp(self):
        self.pwd = '12345'
        self.user_1 = User.objects.get(username='******')
        self.language_1 = Languages.objects.get(name='Italian')

        Settings_currentlang_idFactory(owner=self.user_1,
                                       stvalue=self.language_1.id)
        super(Selenium_old_lwt, self).setUpClass()
        self.selenium = WebDriver()
        self.selenium.get('{}/accounts/login/'.format(self.live_server_url))
        self.selenium.implicitly_wait(10)
        login = self.selenium.find_element_by_name('login')
        login.send_keys(self.user_1.username)
        pw = self.selenium.find_element_by_name('password')
        pw.send_keys(self.pwd)
        self.selenium.find_element_by_class_name('primaryAction').click()

    def test_loggout(self):
        self.selenium.get(self.live_server_url)  # return 'localhost:8000
        self.selenium.find_element_by_name('logout').click()
        self.selenium.get('{}/accounts/logout/'.format(self.live_server_url))
        self.selenium.find_element_by_xpath('//button[@type="submit"]').click()

    def tearDown(self):
        #         self.selenium.quit()
        super(Selenium_old_lwt, self).tearDown()

    def test_go_to_homepage(self):
        self.selenium.get(self.live_server_url)  # return 'localhost:8000

    def test_go_to_text_list(self):
        self.selenium.get('{}/text_list/'.format(self.live_server_url))

    def test_go_to_text_read(self):
        self.selenium.get('{}/text_read/{}'.format(self.live_server_url,
                                                   self.text1.id))
示例#21
0
def get_report(browser: webdriver.WebDriver):
    browser.set_page_load_timeout(10)

    elv_mngmnt_drpdwn = browser.find_element_by_xpath(
        wbm_cfg.drpdwn_elvr_mngmnt_xpath)
    elv_mngmnt_drpdwn.click()
    element = WebDriverWait(browser, 5).until(
        EC.element_to_be_clickable((By.XPATH, wbm_cfg.btn_downl_report_xpath)))
    element.click()

    time.sleep(5)
    logging.info("Report file download is started")
示例#22
0
def log_in(browser: webdriver.WebDriver):
    try:
        logging.info("Getting email input field in the login form")
        email_login_input_field = browser.find_element_by_xpath(
            "/html/body/div[1]/div/form[1]/ul/li[1]/label/div/input")

        logging.info("Getting password input field in the login form")
        password_login_input_field = browser.find_element_by_xpath(
            "/html/body/div[1]/div/form[1]/ul/li[2]/label/div/input")

        logging.info("Filling out the login form")
        email_login_input_field.send_keys(get_username())
        password_login_input_field.send_keys(get_password())

        logging.info("Performing login (getting the button and clicking it)")
        browser.find_element_by_xpath(
            "/html/body/div[1]/div/form[1]/ul/li[3]/input").click()

        wait()
    except WebDriverException:
        logging.error(f"Something went wrong while executing the task")
        logging.error(traceback.format_exc())
示例#23
0
def perform_check_in(browser: webdriver.WebDriver):
    try:
        logging.info("Hovering over the check-in button (in sidebar)")
        sidebar_check_in_div_xpath = "//div[contains(@class, 'aside-wrap')]" \
                                     "//div[contains(@class, 'aside') and contains(@class, 'check-in')]"
        sidebar_check_in_button_xpath = f"{sidebar_check_in_div_xpath}//p[contains(text(), 'Check-in')]"
        sidebar_check_in_div_element = browser.find_element_by_xpath(
            sidebar_check_in_div_xpath)
        sidebar_check_in_button_element = browser.find_element_by_xpath(
            sidebar_check_in_button_xpath)
        scroll_to_and_hover_over_element(browser,
                                         sidebar_check_in_button_element)

        logging.info("Getting the button from the popup")
        check_in_button_xpath = "//div[contains(@class, 'check-btn') and contains(@class, 'J-check-in')]"
        check_in_button_element = sidebar_check_in_div_element.find_element_by_xpath(
            check_in_button_xpath)
        if check_in_button_element.text.lower() == "check-in":
            logging.info("Clicking the check-in button")
            check_in_button_element.click()
            sleep(
                2
            )  # The get_sleep_time() method is not used as it always needs ~2 seconds here to view the popup
            # # Click on the button on popup to close it
            # browser.find_element_by_xpath("//*[contains(text(), 'OK, I know')]").click()
            # logging.info("Check-in was successful")
        else:
            # Get time left for the next check-in
            logging.info(
                f"Not clicking a button. The text in the button was {check_in_button_element.text}. Moving on"
            )
            next_check_in = sidebar_check_in_div_element.find_element_by_class_name(
                "countdown").text
            logging.info(
                f"Next check-in in: {re.search('(Restart In: )(.*)', next_check_in).group(2)}"
            )
    except WebDriverException:
        logging.error(f"Something went wrong while executing the task")
        logging.error(traceback.format_exc())
    def test_Selenium_Unit_Test(self):
        #         chrome_driver_path = "/var/lib/jenkins/workspace/rasa pipeline/Selenium_Webdriver/chromedriver"
        # create a new Chrome session
        # from pyvirtualdisplay import Display
        # display = Display(visible=0, size=(800, 600))
        # display.start()
        #         options = webdriver.FirefoxOptions()
        #         options.add_argument('-headless')
        # Last I checked this was necessary.

        #         driver = webdriver.Chrome(chrome_driver_path, options=options1)
        from selenium.webdriver.firefox.options import Options as FirefoxOptions
        from selenium.webdriver.firefox.webdriver import WebDriver

        options1 = FirefoxOptions()
        options1.add_argument("-headless")
        driver = WebDriver(options=options1)
        driver.implicitly_wait(30)
        time.sleep(12)
        driver.get(
            'http://sidwebpage.s3.us-east-2.amazonaws.com/website/index.html')
        print(driver.current_url)
        time.sleep(5)
        driver.refresh()
        time.sleep(5)
        # chatbot testing simulation
        driver.find_element_by_xpath('//*[@id="webchat"]/div/button ').click()
        time.sleep(5)
        Mousepointer = driver.find_element_by_xpath(
            '//*[@id="webchat"]/div/div/form/input')
        Mousepointer.send_keys("Hi")
        Mousepointer.send_keys(Keys.ENTER)
        ExpectedReply = "Hey! How are you Muthu?"
        Reply = driver.find_element_by_xpath(
            '//*[@id="messages"]/div/following::span').text
        print(Reply)
        self.assertEqual(Reply, ExpectedReply)
        print("Success")
        driver.quit()
示例#25
0
def wait_for_page(browser: webdriver.WebDriver, url, test_element_xpath):
    try:
        wait_element = WebDriverWait(browser, 10).until(
            EC.presence_of_element_located((By.XPATH, test_element_xpath)))
    except TimeoutException:
        logging.error(str(url) + " could not be successfully loaded")

    finally:
        if "iframe" in test_element_xpath:
            browser.switch_to.frame(
                browser.find_element_by_xpath(test_element_xpath))
            logging.info("Selected iFrame")

        return
示例#26
0
def run(*, driver: WebDriver, url: str, opt: int):
    driver.get(url)
    try:
        main_node = driver.find_element_by_xpath("/html/body/form/div[1]")
        els: list = main_node.find_elements_by_tag_name("input")
        el = els[int(opt) - 1]
        driver.execute_script("arguments[0].click();", el)
        # delay
        time.sleep(3)
        logger.info("ok")
    except:  # noqa
        logger.info("ko")
    finally:
        driver.close()
示例#27
0
def _remove_one_product_from_cart(browser: webdriver.WebDriver,
                                  task_data: TaskData, product_row_xpath: str,
                                  product: str):
    product_quantity_xpath = ".//li[contains(@class, 'newcart_quantity')]//div[contains(@class, 'quantity_item')]"
    product_quantity_minus_xpath = ".//a[contains(text(), '-')]"
    product_options_xpath = ".//li[contains(@class, 'newcart_options')]"
    product_remove_button_xpath = f"{product_options_xpath}//span[contains(@data-title, 'Remove')]"
    product_remove_modal_xpath = f"{product_options_xpath}//div[contains(@class, 'item_remove_mask')]"
    product_remove_modal_yes_button_xpath = ".//a[contains(@class, 'item_mask_yes')]"
    target_product_link_xpath = f"{product_row_xpath}//li[contains(@class, 'newcart_product')]" \
                                f"//a[contains(@class, 'title') and contains(text(), '{product}')]"
    target_product_link_element = browser.find_element_by_xpath(
        target_product_link_xpath)
    product_row_ancestor_xpath = ".//ancestor::ul[contains(@class, 'newcart_list_items')]"
    product_row_element = target_product_link_element.find_element_by_xpath(
        product_row_ancestor_xpath)

    scroll_to_and_hover_over_element(browser, product_row_element)

    if product in task_data.products:
        logging.info(f"Product found! It's {product}")
        qty_element = product_row_element.find_element_by_xpath(
            product_quantity_xpath)
        quantity = int(
            qty_element.find_element_by_tag_name("input").get_attribute(
                "value"))
        if quantity > 1:
            logging.info(
                f"Decreasing qty for product {product} from {quantity} to {quantity - 1}"
            )
            qty_element.find_element_by_xpath(
                product_quantity_minus_xpath).click()
            wait()
        else:
            logging.info(f"Removing product {product} from cart.")
            WebDriverWait(browser, 10). \
                until(ec.presence_of_element_located((By.XPATH, product_remove_button_xpath)))
            WebDriverWait(browser, 10). \
                until(ec.element_to_be_clickable((By.XPATH, product_remove_button_xpath)))
            product_row_element.find_element_by_xpath(
                product_remove_button_xpath).click()
            wait()
            product_row_element.find_element_by_xpath(product_remove_modal_xpath) \
                .find_element_by_xpath(product_remove_modal_yes_button_xpath) \
                .click()
            wait()
        task_data.products.remove(product)
示例#28
0
def _receive_reward(browser: webdriver.WebDriver, task_data: TaskData):
    wait()

    logging.info("Clicking on \"Receive it\" button")
    receive_it_button_xpath = f"//div[contains(@class, '{task_data.modal_css_class}')] " \
                              "//a[(contains(" \
                              "translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), " \
                              "'receive it'))]"
    WebDriverWait(browser, 10).until(
        ec.presence_of_element_located((By.XPATH, receive_it_button_xpath)))
    receive_it_button_element = browser.find_element_by_xpath(
        receive_it_button_xpath)
    if receive_it_button_element.is_displayed():
        receive_it_button_element.click()
        logging.info("Receiving points for completing the task")
    else:
        logging.info(
            "The \"Receive it\" button is not displayed. Not clicking on anything..."
        )
示例#29
0
def find_task_button_and_click_it(browser: webdriver.WebDriver,
                                  task_data: TaskData):
    logging.info(
        "Finding the div element containing task description and the \"Complete task\" button"
    )
    task_div = browser.find_element_by_xpath(task_data.xpath)

    logging.info("Finding the button inside div element")
    task_button = task_div.find_element_by_class_name("item-btn")

    logging.info("Button text is: {}".format(task_button.text))
    if task_button.text.lower() == "received" or task_button.text.lower(
    ) == 'claim reward':
        logging.info("Reward already received")
        is_reward_received = True
    else:
        logging.info("Reward not yet received")
        is_reward_received = False

    logging.info("Click the button")
    task_button.click()
    return is_reward_received
示例#30
0
class webHelper():
    def __init__(self):
        self.success = True
        self.wd = WebDriver()
        self.wd.implicitly_wait(60)
        
    def setText(self, locator, text):
        self.wd.find_element_by_xpath(locator).click()
        self.wd.find_element_by_xpath(locator).clear()
        self.wd.find_element_by_xpath(locator).send_keys(text)
        
    def selectCheckbox(self, locator):
        if not self.wd.find_element_by_xpath(locator).is_selected():
            self.wd.find_element_by_xpath(locator).click()
        
    def unselectCheckBox(self, locator):
        if self.wd.find_element_by_xpath(locator).is_selected():
            self.wd.find_element_by_xpath(locator).click()
        
    def clickButton(self, locator):
        self.wd.find_element_by_xpath(locator).click()    
        
    def open(self,locator):
        self.wd.get(locator)     
            
def is_alert_present(wd):
    try:
        wd.switch_to_alert().text
        return True
    except:
        return False

try:
    wd.get("http://localhost/addressbook/index.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_name("pass").click()
    wd.find_element_by_name("pass").clear()
    wd.find_element_by_name("pass").send_keys("secret")
    wd.find_element_by_xpath("//form[@id='LoginForm']/input[3]").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("adfadf")
    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("adfadfadf")
    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("adfadfdf")
    wd.find_element_by_name("submit").click()
    wd.find_element_by_link_text("groups").click()
    wd.find_element_by_link_text("Logout").click()
    wd.find_element_by_name("user").click()
示例#32
0
class ScriptTestCase(LiveServerTestCase):
    def setUp(self):
        self.browser = WebDriver()
        self.do_admin_login('test', 'test')

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

    def do_admin_login(self, username, password):
        self.browser.get('%s%s' % (self.live_server_url, '/admin/'))
        username_input = self.browser.find_element_by_name("username")
        username_input.send_keys(username)
        password_input = self.browser.find_element_by_name("password")
        password_input.send_keys(password)
        self.browser.find_element_by_xpath('//input[@value="Log in"]').click()

    def new_window(self, name='other'):
        self.browser.execute_script('window.open("/admin/", "'+ name +'")')
        self.browser.switch_to_window(self.browser.window_handles[1])
        while self.warning_element() is False:
            time.sleep(0.1)
        self.browser.switch_to_window(self.browser.window_handles[0])

    def press_space(self):
        a = ActionChains(self.browser)
        a.key_down(Keys.SPACE)
        a.perform()

    def warning_element(self):
        try:
            return self.browser.find_elements_by_css_selector(
                '#session_security_warning')[0]
        except IndexError:
            return False

    def wait_for_pages_loaded(self):
        for win in self.browser.window_handles:
            while self.warning_element() is False:
                time.sleep(0.1)

    def deadline_passed(self, now, deadline):
        return (datetime.now() - now).seconds > deadline

    def assertWarningShows(self, max_seconds):
        now = datetime.now()

        for win in self.browser.window_handles:
            self.browser.switch_to_window(win)

            while self.warning_element() is False:
                time.sleep(0.1)

                if self.deadline_passed(now, max_seconds):
                    self.fail('Warning did not make it into DOM')

        for win in self.browser.window_handles:
            self.browser.switch_to_window(win)

            while self.warning_element().is_displayed() is False:
                time.sleep(0.1)

                if self.deadline_passed(now, max_seconds):
                    self.fail('Warning did not make it into DOM')

    def assertWarningHides(self, max_seconds):
        now = datetime.now()

        for win in self.browser.window_handles:
            self.browser.switch_to_window(win)

            while self.warning_element().is_displayed() is not False:
                time.sleep(0.1)

                if self.deadline_passed(now, max_seconds):
                    self.fail('Warning did not hide')

    def assertExpires(self, max_seconds):
        now = datetime.now()

        for win in self.browser.window_handles:
            self.browser.switch_to_window(win)

            while self.warning_element() is not False:
                time.sleep(0.1)

                if self.deadline_passed(now, max_seconds):
                    self.fail('Warning did not make it out of DOM')

    def assertWarningShown(self):
        for win in self.browser.window_handles:
            self.browser.switch_to_window(win)
            self.assertTrue(self.warning_element().is_displayed())

    def assertWarningHidden(self):
        for win in self.browser.window_handles:
            self.browser.switch_to_window(win)
            self.assertFalse(self.warning_element().is_displayed())

    def assertWarningNotInPage(self):
        for win in self.browser.window_handles:
            self.browser.switch_to_window(win)
            self.assertTrue(self.warning_element() is False)


    def test_single_window_inactivity(self):
        self.wait_for_pages_loaded()
        self.assertWarningHidden()
        self.assertWarningShows(9)
        self.assertExpires(9)

    def test_single_dont_show_warning(self):
        self.wait_for_pages_loaded()
        self.assertWarningHidden()
        time.sleep(3.5)
        self.press_space()
        self.assertWarningHidden()
        time.sleep(4)
        self.assertWarningHidden()

    def test_single_hide_warning(self):
        self.assertWarningShows(9)
        self.press_space()
        self.assertWarningHides(2)

    def test_double_window_inactivity(self):
        self.new_window()
        self.wait_for_pages_loaded()
        self.assertWarningHidden()
        self.assertWarningShows(9)
        self.assertExpires(9)

    def test_double_dont_show_warning(self):
        self.new_window()
        self.wait_for_pages_loaded()
        self.assertWarningHidden()
        time.sleep(3.5)
        self.press_space()
        self.assertWarningHidden()
        time.sleep(4)
        self.assertWarningHidden()

    def test_double_hide_warning(self):
        self.new_window()
        self.assertWarningShows(9)
        self.press_space()
        self.assertWarningHides(6)
示例#33
0
class ExampleCommunityLiveTests(StaticLiveServerTestCase):
    @classmethod
    def setUpClass(cls):
        super(ExampleCommunityLiveTests, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        # cls.selenium.quit()
        super(ExampleCommunityLiveTests, cls).tearDownClass()

    def tearDown(self):
        self.selenium.get(self.full_url(reverse('logout')))
        self.selenium.quit()

    def setUp(self):
        self.community = Community.objects.create(
            name="Kibbutz Broken Dream",
        )
        self.users_details = dict()
        for i in range(NUM_OF_USERS):
            name = silly.name(slugify=True)
            email = silly.email()
            self.users_details[name] = OCUser.objects.create_superuser(email, name, DEFAULT_PASS)
        self.committee = Committee.objects.create(name="Culture", slug="culture", community=self.community)
        self.selenium = WebDriver()

    def full_url(self, s):
        if s.startswith(self.live_server_url):
            return s
        else:
            return self.live_server_url + s

    def get_current_path(self):
        return urlparse.urlsplit(self.selenium.current_url).path

    def assert_current_path(self, path):
        self.assertEqual(self.full_url(path), self.full_url(self.get_current_path()))

    def selenium_get_and_assert(self, url):
        """
        Tries to go url (as is) and then asserts that current_path == url
        """
        self.selenium.get(url)
        self.assert_current_path(url)

    def login(self, goto_login, name, pswd=DEFAULT_PASS):
        if goto_login is True:
            self.selenium.get(self.full_url(reverse('login')))
        self.assert_current_path(reverse('login'))
        username_input = self.selenium.find_element_by_id("id_username")
        username_input.send_keys(self.users_details[name].email)
        password_input = self.selenium.find_element_by_id("id_password")
        password_input.send_keys(pswd)
        self.selenium.find_element_by_xpath('//input[@type="submit"]').click()

    def test_redirect_and_login(self):
        url = self.full_url(self.community.get_absolute_url())
        # from IPython import embed
        # embed()
        self.selenium.get(url)
        name = random.choice(self.users_details.keys())
        self.login(False,
                   name)  # False since the community we created is private - it should automatically redircet to login

    def test_create_meeting(self):
        name = random.choice(self.users_details.keys())
        self.login(True, name)
        """
        TODO - after login goto the community page, locate the relevant html element for the committee - and 'click()' it
        (The below code didn't work because click didn't work for me - idk y
        url = self.full_url(self.community.get_absolute_url())
        self.selenium_get_and_assert(url)
        self.selenium.find_element_by_class_name(
            "panel-heading").click()  # goto "Next meeting" (TODO: check if this works if we have single \ multiple meetings in the system)
        self.assert_current_path(
            self.committee.get_absolute_url())  # note: we're seeing a new meeting in progress - hence its' url is the committees'
        """
        url = self.full_url(self.committee.get_absolute_url())
        self.selenium_get_and_assert(url)
        # TODO: assert that we're seeing all the communities we're a member of
        new_subject_input = self.selenium.find_element_by_id("quick-issue-title")
        new_subject_input.send_keys("dummy-subject1")

        self.selenium.find_element_by_xpath(
            '//button[@type="submit"]').click()  # should behave exactly like: self.selenium.find_element_by_id("quick-issue-add").click()
        # Create a new committee & assert what's needed
示例#34
0
from selenium.webdriver.firefox.webdriver import WebDriver
wd = WebDriver()
wd.implicitly_wait(60)
wd.get("https://encrypted.google.com/")
wd.find_element_by_id("gbqfq").click()
wd.find_element_by_id("gbqfq").clear()
wd.find_element_by_id("gbqfq").send_keys("santiago suarez ordoñez")
wd.find_element_by_xpath("//ol[@id='rso']//em[.='Santiago Suarez Ordoñez']").click()
wd.close()
class FamilyBrowseVariantFilterTests(unittest.TestCase):
    """
    Test the same recessive search with the more granular variant filters
    """
    def setUp(self):

        self.selenium = WebDriver()
        self.live_server_url = LIVE_SERVER_URL

        # login boilerplate blah
        self.selenium.get(self.live_server_url + '/login')
        username_input = self.selenium.find_element_by_name("username_or_email")
        username_input.send_keys(ADMIN_USERNAME)
        password_input = self.selenium.find_element_by_name("password")
        password_input.send_keys(ADMIN_PASSWORD)
        self.selenium.find_element_by_xpath('//button[@type="submit"]').click()

        # visit the family browse page
        self.selenium.get(self.live_server_url + '/project/1kg/family/1/mendelian-variant-search')

        # set inheritance
        self.selenium.find_element_by_xpath('//li[@class="inheritance-pill-li"][@data-search_mode="all_variants"]/a').click()

    def test_genes_filter(self):

        self.selenium.find_element_by_xpath('//a[@href="#collapse-region"]').click()
        time.sleep(.4)
        genes_input = self.selenium.find_element_by_id("region-genes")
        genes_input.send_keys('cdcp2\nmpv17')

        self.selenium.find_element_by_xpath('//a[@id="run-search"]').click()
        wait_for_xpath(self.selenium, '//div[@id="summary-container"]')

        stats_content = self.selenium.find_element_by_id('variant-stats-container').text
        self.assertTrue("9 variants" in stats_content)

    def test_region_filter(self):

        choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact')

        self.selenium.find_element_by_xpath('//a[@href="#collapse-region"]').click()
        time.sleep(.4)
        choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact')
        genes_input = self.selenium.find_element_by_id("region-coords")
        genes_input.send_keys('chr6:31000000-33000000')

        self.selenium.find_element_by_xpath('//a[@id="run-search"]').click()
        wait_for_xpath(self.selenium, '//div[@id="summary-container"]')

        stats_content = self.selenium.find_element_by_id('variant-stats-container').text
        self.assertTrue("8 variants" in stats_content)

    def test_region_filter_full_chr(self):

        choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact')

        self.selenium.find_element_by_xpath('//a[@href="#collapse-region"]').click()
        time.sleep(.4)

        choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact')
        genes_input = self.selenium.find_element_by_id("region-coords")
        genes_input.send_keys('chr6')

        self.selenium.find_element_by_xpath('//a[@id="run-search"]').click()
        wait_for_xpath(self.selenium, '//div[@id="summary-container"]')

        stats_content = self.selenium.find_element_by_id('variant-stats-container').text
        self.assertTrue("92 variants" in stats_content)

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

# class CohortGeneSearchTests(unittest.TestCase):
#     """
#     Test all the different views you can go to on the cohort browse page
#     """
#     def setUp(self):
#
#         #self.selenium = webdriver.Chrome()
#         self.selenium = WebDriver()
#         self.live_server_url = 'http://*****:*****@type="submit"]').click()
#
#         # visit the cohort browse page
#         self.selenium.get(self.live_server_url + '/project/g1k/cohort/random_cohort/cohort-gene-search')
#
#     def test_recessive_basic(self):
#         self.selenium.find_element_by_xpath('//input[@name="cohort_inheritance"][@value="recessive"]').click()
#         choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact')
#         choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality')
#
#         self.selenium.find_element_by_xpath('//a[@id="run-search"]').click()
#         wait_for_xpath(self.selenium, '//div[@id="summary-container"]')
#
#         results_content = self.selenium.find_element_by_id('resultsContainer').text
#         self.assertTrue("Returned 60 genes" in results_content)
#
#     def test_homozygous_recessive_basic(self):
#
#         self.selenium.find_element_by_xpath('//input[@name="cohort_inheritance"][@value="homozygous_recessive"]').click()
#         choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact')
#         choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality')
#
#         self.selenium.find_element_by_xpath('//a[@id="run-search"]').click()
#         wait_for_xpath(self.selenium, '//div[@id="summary-container"]')
#
#         results_content = self.selenium.find_element_by_id('resultsContainer').text
#         self.assertTrue("Returned 53 genes" in results_content)
#
#     def test_x_linked_recessive_basic(self):
#
#         self.selenium.find_element_by_xpath('//input[@name="cohort_inheritance"][@value="x_linked_recessive"]').click()
#         choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact')
#         choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality')
#
#         self.selenium.find_element_by_xpath('//a[@id="run-search"]').click()
#         wait_for_xpath(self.selenium, '//div[@id="summary-container"]')
#
#         results_content = self.selenium.find_element_by_id('resultsContainer').text
#         self.assertTrue("Returned 2 genes" in results_content)
#
#     def test_compound_het_basic(self):
#
#         self.selenium.find_element_by_xpath('//input[@name="cohort_inheritance"][@value="compound_het"]').click()
#         choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact')
#         choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality')
#
#         self.selenium.find_element_by_xpath('//a[@id="run-search"]').click()
#         wait_for_xpath(self.selenium, '//div[@id="summary-container"]')
#
#         results_content = self.selenium.find_element_by_id('resultsContainer').text
#         self.assertTrue("Returned 6 genes" in results_content)
#
#     def test_dominant_basic(self):
#
#         self.selenium.find_element_by_xpath('//input[@name="cohort_inheritance"][@value="dominant"]').click()
#         choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'high_impact')
#         choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality')
#
#         self.selenium.find_element_by_xpath('//a[@id="run-search"]').click()
#         wait_for_xpath(self.selenium, '//div[@id="summary-container"]')
#
#         results_content = self.selenium.find_element_by_id('resultsContainer').text
#         self.assertTrue("Returned 6 genes" in results_content)

    def tearDown(self):
        self.selenium.quit()
示例#36
0
class EntrySeleleniumTests(StaticLiveServerTestCase):
    """Selenium tests for the entry form"""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if not settings.DEBUG:
            settings.DEBUG = True

    def setUp(self):
        """Handles login and things"""
        call_command('flush', interactive=False, verbosity=0)  # Clears db
        call_command('loaddata', 'groups', commit=False, verbosity=0)
        call_command('loaddata', 'school', commit=False, verbosity=0)
        call_command('loaddata', 'permissions', commit=False, verbosity=0)
        call_command('loaddata', 'auth_users', commit=False, verbosity=0)
        call_command('loaddata', 'student', commit=False, verbosity=0)
        call_command('loaddata', 'advisor', commit=False, verbosity=0)
        call_command('loaddata', 'coordinator', commit=False, verbosity=0)
        call_command('loaddata', 'activityoptions', commit=False, verbosity=0)
        call_command('loaddata', 'learningobjectiveoptions', commit=False, verbosity=0)
        call_command('loaddata', 'sample_entries', commit=False, verbosity=0)
        self.selenium = WebDriver()
        self.selenium.set_window_size(1024, 800)
        self.selenium.get('{0}/{1}'.format(self.live_server_url, ''))
        self.selenium.find_element_by_xpath('//*[@id="djHideToolBarButton"]').click()
        self.selenium.implicitly_wait(10)
        self.selenium.find_element_by_link_text('Login').click()
        # Click on the student button in the gateway
        self.selenium.find_element_by_xpath('/html/body/center/md-content/div/div/div[1]/a').click()
        self.selenium\
            .find_element_by_xpath("//img[@src='/static/journal/activities/img"
                                   "/journal_sign.png']")
        super()

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

    def test_text_entry(self):
        """Test to ensure that a student can add a text entry"""
        # Click on the first activity box: Walking around the block
        self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click()
        self.selenium.find_element_by_link_text('Add an entry').click()
        # The following has 2 matching: Just walking and Adding entry...block
        header_text = self.selenium.find_elements_by_tag_name('h3')[1].text
        self.assertTrue('Adding entry for Walking around the block!' in header_text)
        # Switching to iframe focus
        self.selenium.switch_to_frame(self.selenium.find_element_by_id('id_entry_iframe'))
        # Insert text
        entry = 'I think I will bring my cat out next time.'
        self.selenium.find_element_by_class_name('note-editable')\
            .send_keys(entry)
        # Switch back out of the iframe.
        self.selenium.switch_to_default_content()
        # Click on the submit button
        self.selenium.find_element_by_class_name('btn-success').click()
        # Ensure that we are back on the entries page.
        self.selenium.find_element_by_link_text('Add an entry')
        # Ensure that entry exists as the first box on the page.
        box_text = self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[1]/a/div').text
        self.assertTrue(entry in box_text)

    def test_image_entry(self):
        """Test to ensure that a student can add an image entry"""
        # Click on the first activity box: Walking around the block
        self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click()
        self.selenium.find_element_by_link_text('Add an entry').click()
        # The following has 2 matching: Just walking and Adding entry...block
        header_text = self.selenium.find_elements_by_tag_name('h3')[1].text
        self.assertTrue('Adding entry for Walking around the block!' in header_text)
        # Switching to iframe focus
        self.selenium.switch_to_frame(self.selenium.find_element_by_id('id_entry_iframe'))
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[2]').click()
        entry = 'http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg'
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/input')\
            .send_keys(entry)
        # click on the inset image button
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[3]/button').click()
        # Switch back out of the iframe.
        self.selenium.switch_to_default_content()
        # Click on the submit button
        self.selenium.implicitly_wait(10)
        self.selenium.find_element_by_class_name('btn-success').click()
        # Ensure that we are back on the entries page.
        self.selenium.find_element_by_link_text('Add an entry')
        # Ensure that entry exists on the page.
        self.selenium.find_element_by_xpath("//img[@src='http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg']")

    def test_video_entry(self):
        """Test to ensure that a student can add a video entry"""
        # Click on the first activity box: Walking around the block
        self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click()
        self.selenium.find_element_by_link_text('Add an entry').click()
        # The following has 2 matching: Just walking and Adding entry...block
        header_text = self.selenium.find_elements_by_tag_name('h3')[1].text
        self.assertTrue('Adding entry for Walking around the block!' in header_text)
        # Switching to iframe focus
        self.selenium.switch_to_frame(self.selenium.find_element_by_id('id_entry_iframe'))
        # Insert video
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[3]').click()
        entry = 'https://www.youtube.com/watch?v=Rk_bV0RJRhs&index=20&list=PLJU_WCB1rA2SFwFy3lEvY_NH23ql1-Cgi'
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[2]/div/input')\
            .send_keys(entry)
        # click on the insert video button
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[3]/button').click()
        # Switch back out of the iframe.
        self.selenium.switch_to_default_content()
        # Click on the submit button
        self.selenium.implicitly_wait(10)
        self.selenium.find_element_by_class_name('btn-success').click()
        # Ensure that we are back on the entries page.
        self.selenium.find_element_by_link_text('Add an entry')
        self.selenium.find_element_by_xpath('//iframe[@src="//www.youtube.com/embed/Rk_bV0RJRhs"]')

    def test_image_text_entry(self):
        """Test to ensure that a student can add image+text entries"""
        # Click on the first activity box: Walking around the block
        self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click()
        self.selenium.find_element_by_link_text('Add an entry').click()
        # The following has 2 matching: Just walking and Adding entry...block
        header_text = self.selenium.find_elements_by_tag_name('h3')[1].text
        self.assertTrue('Adding entry for Walking around the block!' in header_text)
        # Switching to iframe focus
        self.selenium.switch_to_frame(self.selenium.find_element_by_id('id_entry_iframe'))
        # Insert text
        entry = 'I think I will bring my cat out next time with a flower.'
        self.selenium.find_element_by_class_name('note-editable')\
            .send_keys(entry)
        # Insert the image
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[2]').click()
        image_entry = 'http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg'
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/input')\
            .send_keys(image_entry)
        # Click on the insert image button
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[3]/button').click()
        # Switch back out of the iframe.
        self.selenium.switch_to_default_content()
        # Click on the submit button
        self.selenium.implicitly_wait(10)
        self.selenium.find_element_by_class_name('btn-success').click()
        # Ensure that we are back on the entries page.
        self.selenium.find_element_by_link_text('Add an entry')
        # Ensure the text is on the entries page
        box_text = self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[1]/a/div').text
        self.assertTrue(entry in box_text)
        # Ensure the image is on the entries page
        self.selenium.find_element_by_xpath("//img[@src='http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg']")

    def test_video_text_entry(self):
        """Test to ensure that a student can add an text+video entry"""
        # Click on the first activity box: Walking around the block
        self.selenium.find_element_by_xpath(
            '/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click()
        self.selenium.find_element_by_link_text('Add an entry').click()
        # The following has 2 matching: Just walking and Adding entry...block
        header_text = self.selenium.find_elements_by_tag_name('h3')[1].text
        self.assertTrue('Adding entry for Walking around the block!' in header_text)
        # Switching to iframe focus
        self.selenium.switch_to_frame(self.selenium.find_element_by_id('id_entry_iframe'))
        # Insert text
        entry = 'I think I will bring my cat out next time.'
        self.selenium.find_element_by_class_name('note-editable')\
            .send_keys(entry)
        # Insert video
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[3]').click()
        video_entry = 'https://www.youtube.com/watch?v=Rk_bV0RJRhs&index=20&list=PLJU_WCB1rA2SFwFy3lEvY_NH23ql1-Cgi'
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[2]/div/input')\
            .send_keys(video_entry)
        # Click on the insert video button
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[3]/button')\
            .click()
        # Switch back out of the iframe.
        self.selenium.switch_to_default_content()
        # Click on the submit button
        self.selenium.find_element_by_class_name('btn-success').click()
        # Ensure that we are back on the entries page.
        self.selenium.find_element_by_link_text('Add an entry')
        # Ensure that entry exists as the first box on the page.
        box_text = self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[1]/a/div')\
            .text
        self.assertTrue(entry in box_text)
        self.selenium.find_element_by_xpath('//iframe[@src="//www.youtube.com/embed/Rk_bV0RJRhs"]')

    def test_text_image_video_entry(self):
        """Test to ensure that a student can add an text+image+video entry"""
        # Click on the first activity box: Walking around the block
        self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click()
        self.selenium.find_element_by_link_text('Add an entry').click()
        # The following has 2 matching: Just walking and Adding entry...block
        header_text = self.selenium.find_elements_by_tag_name('h3')[1].text
        self.assertTrue('Adding entry for Walking around the block!' in header_text)
        # Switching to iframe focus
        self.selenium.switch_to_frame(self.selenium.find_element_by_id('id_entry_iframe'))
        # Insert text
        text_entry = 'I think I will bring my cat out next time.'
        self.selenium.find_element_by_class_name('note-editable')\
            .send_keys(text_entry)
        # Insert image button
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[2]').click()
        image_entry = 'http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg'
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/input')\
            .send_keys(image_entry)
        # Click on the inset image button
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[3]/button').click()
        # Insert video button
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[3]').click()
        video_entry = 'https://www.youtube.com/watch?v=Rk_bV0RJRhs&index=20&list=PLJU_WCB1rA2SFwFy3lEvY_NH23ql1-Cgi'
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[2]/div/input')\
            .send_keys(video_entry)
        # Click on the insert video button
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[3]/button').click()
        # Switch back out of the iframe.
        self.selenium.switch_to_default_content()
        # Click on the submit button
        self.selenium.find_element_by_class_name('btn-success').click()
        # Ensure that we are back on the entries page.
        self.selenium.find_element_by_link_text('Add an entry')
        # Ensure that entry exists as the first box on the page.
        box_text = self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[1]/a/div').text
        self.assertTrue(text_entry in box_text)
        self.selenium.find_element_by_xpath("//img[@src='http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg']")
        self.selenium.find_element_by_xpath('//iframe[@src="//www.youtube.com/embed/Rk_bV0RJRhs"]')

    def test_delete_entry(self):
        """Test to ensure that a student can delete an entry"""
        # Click on the first activity box: Walking around the block
        self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click()
        self.selenium.find_element_by_link_text('Add an entry').click()
        # The following has 2 matching: Just walking and Adding entry...block
        header_text = self.selenium.find_elements_by_tag_name('h3')[1].text
        self.assertTrue('Adding entry for Walking around the block!' in header_text)
        # Switching to iframe focus
        self.selenium.switch_to_frame(self.selenium.find_element_by_id('id_entry_iframe'))
        # Insert text
        text_entry = 'I think I will bring my cat out next time.'
        self.selenium.find_element_by_class_name('note-editable')\
            .send_keys(text_entry)
        # Insert image button
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[2]').click()
        image_entry = 'http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg'
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/input')\
            .send_keys(image_entry)
        # Click on the inset image button
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[3]/button').click()
        # Insert video button
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[3]').click()
        video_entry = 'https://www.youtube.com/watch?v=Rk_bV0RJRhs&index=20&list=PLJU_WCB1rA2SFwFy3lEvY_NH23ql1-Cgi'
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[2]/div/input')\
            .send_keys(video_entry)
        # Click on the insert video button
        self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[3]/button').click()
        # Switch back out of the iframe.
        self.selenium.switch_to_default_content()
        # Click on the submit button
        self.selenium.find_element_by_class_name('btn-success').click()
        # Ensure that we are back on the entries page.
        self.selenium.find_element_by_link_text('Add an entry')
        # Ensure that entry exists as the first box on the page.
        box_text = self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[1]/a/div').text
        self.assertTrue(text_entry in box_text)
        self.selenium.find_element_by_xpath("//img[@src='http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg']")
        self.selenium.find_element_by_xpath('//iframe[@src="//www.youtube.com/embed/Rk_bV0RJRhs"]')
        # Click on the entry that was created
        self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[1]/a').click()
        # Click on the delete button
        self.selenium.find_element_by_class_name('btn-danger').click()
        self.selenium.find_element_by_xpath('//*[@id="delete-modal"]/div/div/div[3]/a').click()
        # Ensure that we are back on the entries page.
        self.selenium.find_element_by_link_text('Add an entry')
        # Ensure that the entry created is no longer on the entries page
        main_text = self.selenium.find_element_by_class_name('main').text
        # Check for text
        self.assertFalse(text_entry in main_text)
        # Check for image
        image_entry_xpath = "//img[@src='http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg']"
        self.assertFalse(image_entry_xpath in main_text)
        # Check for video
        video_entry_xpath = '//iframe[@src="//www.youtube.com/embed/Rk_bV0RJRhs"]'
        self.assertFalse(video_entry_xpath in main_text)
示例#37
0
def is_alert_present(wd):
    try:
        wd.switch_to_alert().text
        return True
    except:
        return False

try:
    wd.get("http://*****:*****@class='form-signin']/button").click()
    wd.find_element_by_xpath("//div/div[1]/div[2]/div/div[2]/div/ul/li[1]/a").click()
    wd.find_element_by_xpath("//div/div[1]/div[2]/div/div[2]/div/ul/li[1]/ul/li[2]/a").click()
    wd.find_element_by_xpath("//div[2]/div[1]/div[2]/div/div[2]/div/ul/li[1]/a").click()
    wd.find_element_by_xpath("//div[2]/div[1]/div[2]/div/div[2]/div/ul/li[1]/ul/li[1]/a").click()
    wd.find_element_by_id("id_nombre_usuario").click()
    wd.find_element_by_id("id_nombre_usuario").clear()
    wd.find_element_by_id("id_nombre_usuario").send_keys("Nuevo Usuario2")
    wd.find_element_by_id("id_password").click()
    wd.find_element_by_id("id_password").clear()
    wd.find_element_by_id("id_password").send_keys("12345")
    wd.find_element_by_id("id_password_repeat").click()
    wd.find_element_by_id("id_password_repeat").clear()
    wd.find_element_by_id("id_password_repeat").send_keys("12345")
    wd.find_element_by_id("id_nombre").click()
    wd.find_element_by_id("id_nombre").clear()
示例#38
0
from selenium.webdriver.firefox.webdriver import WebDriver as Firefox
from selenium.webdriver.support.select import Select
import os
from selenium.webdriver.support.ui import WebDriverWait
import time
driver = Firefox()
driver.get('http://console.ezparking.com.cn/console/a?login')
title = driver.title
print(title)
#selector = Select(driver.find_element_by_id("selectdemo"))
#selector.select_by_index("2")

driver.find_element_by_id('username').send_keys('15123532344')
driver.find_element_by_id('password').send_keys('Luobo123')
driver.find_element_by_xpath(
    ".//*[@id='normal_login']/div/div/div[3]/button").click()
'''
driver.find_element_by_xpath(".//*[@id='main-sidebar']/section/ul/li[2]/a/span[1]").click()  #停车场管理
driver.find_element_by_xpath(".//*[@id='main-sidebar']/section/ul/li[2]/ul/li[1]/a").click()
driver.switch_to_frame('mainFrame')
print('iFrame切换成功')

a=WebDriverWait(driver,10,1).until(lambda x:x.find_element_by_xpath(".//*[@id='searchForm']/div[1]/div[2]/div/div/span/span[1]/span/span[2]"))
print('1111111111')
a.click()
driver.find_elements_by_css_selector('[role="treeitem"]')[2].click()
driver.find_element_by_xpath(".//*[@id='btnSubmit']").click()
a=driver.find_element_by_xpath(".//*[@id='contentTable']/tbody/tr[2]/td[8]")
print(a.text)

driver.find_element_by_xpath(".//*[@id='main-sidebar']/section/ul/li[4]/a/span").click()
    driver.find_element_by_link_text("Shop Repair Parts Now »").click()

    # This try statement is used to detect the Foresee overlay that pops up at this point in FF
    # Without this, Chrome will not continue to next step as it will error out while waiting
    try:
        wait = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.LINK_TEXT, "No, thanks")))
        driver.find_element_by_link_text("No, thanks").click()
    except Exception, e:
        print("Foresee not seen here")

    WebDriverWait(driver, 10).until_not(EC.presence_of_element_located((By.ID, "fsrOverlay")))

    driver.find_element_by_id("aarisearch_brands_jl").click()
    wait = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, "//ul[@class='ari-caused-spacer-expand']/li[3]")))
    driver.find_element_by_xpath("//ul[@class='ari-caused-spacer-expand']/li[3]").click()
    driver.find_element_by_id("arisearch_txtSearch").click()
    driver.find_element_by_id("arisearch_txtSearch").clear()
    driver.find_element_by_id("arisearch_txtSearch").send_keys("209617GS")
    driver.find_element_by_id("arisearch_btnLookup").click()

    # The following div classes get in the way of our user click as seen in errors
    # and we must change the css with javascript to allow the button click without a sleep statement
    # <div class="blockUI blockOverlay" ... wait; position: absolute;"></div>

    try:
        hideElement = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "blockUI")))
    except Exception, e:
        print("BlockUI not found")
    try:
        driver.execute_script("document.getElementsByClassName('blockUI blockOverlay')[0].style.height = '1px';")
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
示例#41
0
class FieldPrintingTest(LiveServerTestCase):
    """
    Testing TagFields objects printing functions
    """

    def setUp(self):
        self.mymetadata = TestMetadata()
        self.mymetadata.view_name = 'template_test'
        self.mymetadata.title = TitleTag(tag_value='Title Test')
        self.mymetadata.author = MetaTag(meta_name='author', meta_content='Test Author')
        self.mymetadata.description = MetaTag(meta_name='description', meta_content='Test Description')
        self.mymetadata.keywords = KeywordsTag(meta_name='keywords', meta_content='test, author')
        # Attr name and class attribute name are not equals, let's do it by setattr
        setattr(self.mymetadata, 'og:title', MetaTag(meta_name='og:title'))
        setattr(self.mymetadata, 'twitter:title', MetaTag(meta_name='twitter:title'))
        setattr(self.mymetadata, 'og:description', MetaTag(meta_name='og:description'))
        setattr(self.mymetadata, 'twitter:description', MetaTag(meta_name='twitter:description'))
        setattr(self.mymetadata, 'og:url', MetaTag(meta_name='og:url', meta_content='http://infantium.com'))
        setattr(self.mymetadata, 'twitter:url', MetaTag(meta_name='twitter:url'))
        setattr(self.mymetadata, 'og:type', MetaTag(meta_name='og:type', meta_content='type'))
        setattr(self.mymetadata, 'twitter:card', MetaTag(meta_name='twitter:card', meta_content='card'))
        setattr(self.mymetadata, 'og:image', ImageMetaTag(meta_name='og:image', meta_content='img/partners/animation2/base.png'))
        setattr(self.mymetadata, 'twitter:image', ImageMetaTag(meta_name='twitter:image'))

        self.mymetadata.save()

        self.firefox = FirefoxDriver()

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

    def test_title_rendering(self):
        self.firefox.get('%s%s' % (self.live_server_url, '/test/'))
        title_element = self.firefox.title
        self.assertIsNotNone(title_element)
        self.assertEqual(title_element, 'Title Test')

    def test_metatags_rendering(self):
        self.firefox.get('%s%s' % (self.live_server_url, '/test/'))

        author_element = self.firefox.find_element_by_xpath('/html/head/meta[@name=\'author\']')
        self.assertIsNotNone(author_element)
        self.assertEqual(author_element.get_attribute('content'), 'Test Author')

        description_element = self.firefox.find_element_by_xpath('/html/head/meta[@name=\'description\']')
        self.assertIsNotNone(description_element)
        self.assertEqual(description_element.get_attribute('content'), 'Test Description')

        keywords_element = self.firefox.find_element_by_xpath('/html/head/meta[@name=\'keywords\']')
        self.assertIsNotNone(keywords_element)
        self.assertEqual(keywords_element.get_attribute('content'), 'test, author')

        og_title_element = self.firefox.find_element_by_xpath('/html/head/meta[@name=\'og:title\']')
        self.assertIsNotNone(og_title_element)
        self.assertEqual(og_title_element.get_attribute('content'), self.firefox.title)  # Should be equal to titleTag
        twitter_title_element = self.firefox.find_element_by_xpath('/html/head/meta[@name=\'twitter:title\']')
        self.assertIsNotNone(twitter_title_element)
        self.assertEqual(twitter_title_element.get_attribute('content'), og_title_element.get_attribute('content'))

        og_description_element = self.firefox.find_element_by_xpath('/html/head/meta[@name=\'og:description\']')
        self.assertIsNotNone(og_description_element)
        self.assertEqual(og_description_element.get_attribute('content'), description_element.get_attribute('content'))
        twitter_description_element = self.firefox.find_element_by_xpath('/html/head/meta[@name=\'twitter:description\']')
        self.assertIsNotNone(twitter_description_element)
        self.assertEqual(twitter_description_element.get_attribute('content'), og_description_element.get_attribute('content'))

        og_url_element = self.firefox.find_element_by_xpath('/html/head/meta[@name=\'og:url\']')
        self.assertIsNotNone(og_url_element)
        self.assertEqual(og_url_element.get_attribute('content'), 'http://infantium.com')
        twitter_url_element = self.firefox.find_element_by_xpath('/html/head/meta[@name=\'twitter:url\']')
        self.assertIsNotNone(twitter_url_element)
        self.assertEqual(twitter_url_element.get_attribute('content'), og_url_element.get_attribute('content'))

        og_image_element = self.firefox.find_element_by_xpath('/html/head/meta[@name=\'og:image\']')
        self.assertIsNotNone(og_image_element)
        self.assertEqual(og_image_element.get_attribute('content'), '/static/img/partners/animation2/base.png')
        twitter_image_element = self.firefox.find_element_by_xpath('/html/head/meta[@name=\'twitter:image\']')
        self.assertIsNotNone(twitter_image_element)
        self.assertEqual(twitter_image_element.get_attribute('content'), og_image_element.get_attribute('content'))
示例#42
0
class BaseStoreTest(StaticLiveServerTestCase):
    def by_id(self, id):
        return self.selenium.find_element_by_id(id)

    def by_css(self, selector: str, multiple: bool = False):
        if multiple:
            return self.selenium.find_elements_by_css_selector(selector)
        else:
            return self.selenium.find_element_by_css_selector(selector)

    def setUp(self):
        self.selenium = WebDriver()
        self.selenium.implicitly_wait(SELENIUM_WAIT_SEC)
        user = create_user(TEST_USER, TEST_PASSWORD, TEST_EMAIL)
        user.firstname = 'live'
        user.lastname = 'test'
        user.save()

    def tearDown(self):
        try:
            delete_user(TEST_USER)
        except Exception:
            pass
        super().tearDown()
        self.selenium.quit()

    def go_to(self, url_name: str, kwargs: Dict[str, str] = None) -> None:
        app_url = reverse(url_name, kwargs=kwargs)
        self.selenium.get('%s%s' % (self.live_server_url, app_url))

    def go_to_app(self, app_id):
        self.go_to('app-detail', {'id': app_id})

    def go_to_app_register(self):
        self.go_to('app-register')

    def go_to_app_upload(self):
        self.go_to('app-upload')

    def go_to_login(self):
        self.selenium.get('%s%s' % (self.live_server_url, '/login/'))

    def login(self, user: str = TEST_USER, password: str = TEST_PASSWORD):
        self.go_to_login()
        user_input = self.selenium.find_element_by_name("login")
        user_input.send_keys(user)
        pass_input = self.selenium.find_element_by_name("password")
        pass_input.send_keys(password)
        self.selenium.find_element_by_xpath('//button[@type="submit"]').click()

    def assert_can_not_login(self):
        self.go_to('home')
        self.go_to_login()
        self.by_id('id_login').clear()
        self.by_id('id_login').send_keys('livetest')
        self.by_id('id_password').clear()
        self.by_id('id_password').send_keys('livetest')
        self.by_css('.auth-form button[type="submit"]').click()

        error = self.by_css('.auth-form .text-danger')
        self.assertTrue(error.is_displayed())
        self.assertOnPage('account_login')

    def logout(self):
        self.findNavigationLink('account_logout').click()

    def wait_for(self, selector: str,
                 then: Callable[[WebElement], None]) -> Any:
        element = WebDriverWait(self.selenium, SELENIUM_WAIT_SEC).until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, selector)))
        return then(element)

    def wait_for_url(self, url: str) -> Any:
        WebDriverWait(self.selenium, SELENIUM_WAIT_SEC).until(
            EC.url_contains(url)
        )

    def assertOnPage(self, url_name: str,
                     kwargs: Dict[str, str] = None) -> None:
        parsed = urlparse(self.selenium.current_url)
        url = reverse(url_name, kwargs=kwargs)
        self.assertEqual(url, parsed.path)

    def findNavigationLink(self, url_name: str,
                           kwargs: Dict[str, str] = None):
        route = reverse(url_name, kwargs=kwargs)
        return self.by_css('#navbar a[href="%s"]' % route)
示例#43
0
class ActivitySeleleniumTests(StaticLiveServerTestCase):
    """Selenium tests for the activity page"""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if not settings.DEBUG:
            settings.DEBUG = True
        if not settings.TESTING:
            settings.TESTING = True

    def setUp(self):
        """Handles login and things"""
        call_command('flush', interactive=False, verbosity=0)  # Clears db
        call_command('loaddata', 'groups', commit=False, verbosity=0)
        call_command('loaddata', 'school', commit=False, verbosity=0)
        call_command('loaddata', 'permissions', commit=False, verbosity=0)
        call_command('loaddata', 'auth_users', commit=False, verbosity=0)
        call_command('loaddata', 'student', commit=False, verbosity=0)
        call_command('loaddata', 'advisor', commit=False, verbosity=0)
        call_command('loaddata', 'coordinator', commit=False, verbosity=0)
        call_command('loaddata', 'activityoptions', commit=False, verbosity=0)
        call_command('loaddata', 'learningobjectiveoptions', commit=False, verbosity=0)
        call_command('loaddata', 'sample_entries', commit=False, verbosity=0)
        self.selenium = WebDriver()
        self.selenium.set_window_size(1024, 800)
        self.selenium.get('{0}/{1}'.format(self.live_server_url, ''))
        self.selenium.find_element_by_xpath('//*[@id="djHideToolBarButton"]').click()
        self.selenium.implicitly_wait(10)
        self.selenium.find_element_by_link_text('Login').click()
        # Click on the student button in the gateway
        self.selenium.find_element_by_xpath('/html/body/center/md-content/div/div/div[1]/a').click()
        self.selenium\
            .find_element_by_xpath("//img[@src='/static/journal/activities/img"
                                   "/journal_sign.png']")
        super()

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

    def test_activity_form_back(self):
        """make sure the back button works"""
        self.selenium.find_element_by_xpath("/html/body/div[1]/div[2]/div/div[1]/div/div[2]/div/a").click()
        self.selenium.find_element_by_name('activity_name').send_keys('Walking the cat')
        self.selenium.find_element_by_name('activity_description').send_keys('Walking the cat around the neighborhood')
        self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[1]/form/div[2]/div[2]/input').send_keys('02/07/1990')
        self.selenium.find_element_by_xpath('//*[@id="id_activity_type"]/li[2]/label').click()
        self.selenium.find_element_by_xpath('//*[@id="id_activity_type"]/li[3]/label').click()
        self.selenium.find_element_by_xpath('//*[@id="id_learned_objective"]/li[6]/label').click()
        self.selenium.find_element_by_name('activity_adviser').send_keys('Cat')
        self.selenium.find_element_by_name('advisor_phone').send_keys('1234567890')
        self.selenium.find_element_by_name('advisor_email').send_keys('*****@*****.**')
        self.selenium.find_element_by_link_text('Back').click()
        self.selenium\
            .find_element_by_xpath("//img[@src='/static/journal/activities/img"
                                   "/journal_sign.png']")

    def test_activity_form_error(self):
        """Tests to check errors on the activity form"""
        self.selenium.find_element_by_xpath("/html/body/div[1]/div[2]/div/div[1]/div/div[2]/div/a").click()
        # self.selenium.find_element_by_name('activity_name').send_keys('')
        self.selenium.find_element_by_name('activity_description').send_keys('Walking with huahua around the neighborhood')
        self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[1]/form/div[2]/div[2]/input').send_keys('02/07/1990')
        self.selenium.find_element_by_xpath('//*[@id="id_activity_type"]/li[2]/label').click()
        self.selenium.find_element_by_xpath('//*[@id="id_activity_type"]/li[3]/label').click()
        self.selenium.find_element_by_xpath('//*[@id="id_learned_objective"]/li[6]/label').click()
        self.selenium.find_element_by_name('activity_adviser').send_keys('Cat')
        self.selenium.find_element_by_name('advisor_phone').send_keys('1234567890')
        self.selenium.find_element_by_name('advisor_email').send_keys('*****@*****.**')
        self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[1]/form/div[6]/div/input').click()
        self.selenium.find_element_by_name('activity_description').text

    def test_activity_form(self):
        """Tests to ensure that activities page has all necessary elements."""
        self.selenium.find_element_by_xpath("/html/body/div[1]/div[2]/div/div[1]/div/div[2]/div/a").click()
        self.selenium.find_element_by_name('activity_name').send_keys('Walking the cat')
        self.selenium.find_element_by_name('activity_description').send_keys('Walking the cat around the neighborhood')
        self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[1]/form/div[2]/div[2]/input').send_keys('02/07/1990')
        self.selenium.find_element_by_xpath('//*[@id="id_activity_type"]/li[2]/label').click()
        self.selenium.find_element_by_xpath('//*[@id="id_activity_type"]/li[3]/label').click()
        self.selenium.find_element_by_xpath('//*[@id="id_learned_objective"]/li[6]/label').click()
        self.selenium.find_element_by_name('activity_adviser').send_keys('Cat')
        self.selenium.find_element_by_name('advisor_phone').send_keys('1234567890')
        self.selenium.find_element_by_name('advisor_email').send_keys('*****@*****.**')
        self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[1]/form/div[6]/div/input').click()
        self.selenium\
            .find_element_by_xpath("//img[@src='/static/journal/activities/img"
                                   "/journal_sign.png']")
        body_text = self.selenium.find_element_by_tag_name('body').text
        self.assertTrue('Walking the cat' in body_text)
        self.assertTrue('Walking the cat around the neighborhood' in body_text)
示例#44
0
    wd.find_element_by_id("lname").clear()
    wd.find_element_by_id("lname").send_keys("Vijay")
    wd.find_element_by_id("email").click()
    wd.find_element_by_id("email").clear()
    wd.find_element_by_id("email").send_keys("*****@*****.**")
    wd.find_element_by_id("company").click()
    wd.find_element_by_id("company").clear()
    wd.find_element_by_id("company").send_keys("Apptimize Candidate")
    wd.find_element_by_id("phone").click()
    wd.find_element_by_id("phone").clear()
    wd.find_element_by_id("phone").send_keys("7194935219")
    wd.find_element_by_id("jobtitle").click()
    wd.find_element_by_id("jobtitle").clear()
    wd.find_element_by_id("jobtitle").send_keys("*****@*****.**")
    wd.find_element_by_id("password").click()
    wd.find_element_by_id("password").clear()
    wd.find_element_by_id("password").send_keys("vamsaV1234@")
    if not wd.find_element_by_xpath("//div[@class='form_main']/div[2]/div[6]/div[2]/input[2]").is_selected():
        wd.find_element_by_xpath("//div[@class='form_main']/div[2]/div[6]/div[2]/input[2]").click()
    if not wd.find_element_by_id("eula").is_selected():
        wd.find_element_by_id("eula").click()
    wd.find_element_by_id("submit").click()
    wd.find_element_by_id("zet-login-email").click()
    wd.find_element_by_id("zet-login-email").send_keys("\\undefined")
    wd.find_element_by_id("zet-login-password").click()
    wd.find_element_by_id("zet-login-password").send_keys("\\undefined")
finally:
    wd.quit()
    if not success:
        raise Exception("Test failed.")
class FamilyBrowseTests(unittest.TestCase):
    """
    Test all the different views you can go to on the family test page
    """
    def setUp(self):

        self.selenium = WebDriver()
        self.live_server_url = LIVE_SERVER_URL

        # login boilerplate blah
        self.selenium.get(self.live_server_url + '/login')
        username_input = self.selenium.find_element_by_name("username_or_email")
        username_input.send_keys(ADMIN_USERNAME)
        password_input = self.selenium.find_element_by_name("password")
        password_input.send_keys(ADMIN_PASSWORD)
        self.selenium.find_element_by_xpath('//button[@type="submit"]').click()

        # visit the family browse page
        self.selenium.get(self.live_server_url + '/project/1kg/family/1/mendelian-variant-search')

    def test_recessive_basic(self):

        self.selenium.find_element_by_xpath('//input[@name="standard_inheritance"][@value="recessive"]').click()
        choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact')
        choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality')

        self.selenium.find_element_by_xpath('//a[@id="run-search"]').click()
        wait_for_xpath(self.selenium, '//div[@id="summary-container"]')

        stats_content = self.selenium.find_element_by_id('variant-stats-container').text
        self.assertTrue("7 variants" in stats_content)

    def test_homozygous_recessive_basic(self):

        self.selenium.find_element_by_xpath('//input[@name="standard_inheritance"][@value="homozygous_recessive"]').click()
        choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact')
        choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality')

        self.selenium.find_element_by_xpath('//a[@id="run-search"]').click()
        wait_for_xpath(self.selenium, '//div[@id="summary-container"]')

        stats_content = self.selenium.find_element_by_id('variant-stats-container').text
        self.assertTrue("1 variants" in stats_content)

    def test_x_linked_recessive_basic(self):

        self.selenium.find_element_by_xpath('//input[@name="standard_inheritance"][@value="x_linked_recessive"]').click()
        choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact')
        choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality')

        self.selenium.find_element_by_xpath('//a[@id="run-search"]').click()
        wait_for_xpath(self.selenium, '//div[@id="summary-container"]')

        stats_content = self.selenium.find_element_by_id('variant-stats-container').text
        self.assertTrue("No variants" in stats_content)

    def test_compound_het_basic(self):

        self.selenium.find_element_by_xpath('//input[@name="standard_inheritance"][@value="compound_het"]').click()
        choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact')
        choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality')

        self.selenium.find_element_by_xpath('//a[@id="run-search"]').click()
        wait_for_xpath(self.selenium, '//div[@id="summary-container"]')

        stats_content = self.selenium.find_element_by_id('variant-stats-container').text
        self.assertTrue("6 variants" in stats_content)

    def test_dominant_basic(self):

        self.selenium.find_element_by_xpath('//input[@name="standard_inheritance"][@value="dominant"]').click()
        choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact')
        choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality')

        self.selenium.find_element_by_xpath('//a[@id="run-search"]').click()
        wait_for_xpath(self.selenium, '//div[@id="summary-container"]')

        stats_content = self.selenium.find_element_by_id('variant-stats-container').text
        self.assertTrue("21 variants" in stats_content)

    def test_de_novo_basic(self):

        self.selenium.find_element_by_xpath('//input[@name="standard_inheritance"][@value="de_novo"]').click()
        choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact')
        choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality')

        self.selenium.find_element_by_xpath('//a[@id="run-search"]').click()
        wait_for_xpath(self.selenium, '//div[@id="summary-container"]')

        stats_content = self.selenium.find_element_by_id('variant-stats-container').text
        self.assertTrue("6 variants" in stats_content)

    def test_custom_inheritance(self):
        self.selenium.find_element_by_xpath('//li[@class="inheritance-pill-li"][@data-search_mode="custom_inheritance"]/a').click()
        time.sleep(.5)
        choose_select(self.selenium, '//select[@class="col-md-2 select-genotype form-control"][@data-indiv_id="NA19675"]', 'alt_alt')
        choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact')
        choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality')

        self.selenium.find_element_by_xpath('//a[@id="run-search"]').click()
        wait_for_xpath(self.selenium, '//div[@id="summary-container"]')

        stats_content = self.selenium.find_element_by_id('variant-stats-container').text
        self.assertTrue("21 variants" in stats_content)

    def tearDown(self):
        self.selenium.quit()
示例#46
0
class Tests():
    loged = False
    username = None
    selenium = None

    def __init__(self):
        # crea driver
        self.selenium = WebDriver()
        self.selenium.implicitly_wait(3)

    def backend_login(self, usuari, contrasenya):
        # accedeix a URL
        self.selenium.get('%s%s' % ("http://*****:*****@value="Iniciar sessió"]').click()
        try:
            boto_logout = self.selenium.find_element_by_xpath(
                '//a[text()="Finalitzar sessió"]')
        except NoSuchElementException as e:
            raise Exception("ERROR en login de l'usuari: " + usuari)
        self.logat = True
        self.username = usuari

    def backend_logout(self):
        self.selenium.find_element_by_xpath(
            '//a[text()="Finalitzar sessió"]').click()

    def ves_al_menu_principal(self):
        # anar a menu principal
        self.selenium.find_element_by_xpath('//a[@href="/admin/"]').click()

    # aqui va la "chicha"
    def crea_empresa(self, nom):
        self.ves_al_menu_principal()
        # afegim empresa
        self.selenium.find_element_by_xpath(
            '//a[@href="/admin/borsApp/empresa/add/"]').click()
        self.selenium.find_element_by_name('nom').send_keys(nom)
        # accedir dins iframe direcció
        self.selenium.switch_to_frame("id_direccio_ifr")
        self.selenium.find_element_by_xpath('//body').send_keys("c. Tal, 1")
        # tornar al main frame
        self.selenium.switch_to_default_content()
        self.selenium.find_element_by_name('poblacio').send_keys("Cornellà")
        self.selenium.find_element_by_name('cp').send_keys("08940")
        self.selenium.find_element_by_name('telefon').send_keys("931112233")
        nom2 = nom.replace(' ', '_')
        self.selenium.find_element_by_name('email').send_keys("info@" + nom2 +
                                                              ".com")
        self.selenium.find_element_by_xpath('//input[@value="Desar"]').click()
        # check
        self.selenium.find_element_by_xpath('//li[@class="success"]')

    def ajusta_usuari_empresa(self, usuari, contrasenya):
        # se suposa que estem logats com a admin_centre
        self.ves_al_menu_principal()
        # menu usuaris
        self.selenium.find_element_by_xpath('//a[text()="Usuaris"]').click()
        # accedim a l'usuari de l'empresa acabada de crear
        # el nom de l'usuari és igual al de l'empresa, al menys pels tests
        self.selenium.find_element_by_xpath('//a[text()="' + usuari +
                                            '"]').click()
        # anem a canvi de contasenya
        self.selenium.find_element_by_xpath(
            '//a[@href="../password/"]').click()
        self.selenium.find_element_by_name('password1').send_keys(contrasenya)
        self.selenium.find_element_by_name('password2').send_keys(contrasenya)

        self.selenium.find_element_by_xpath(
            '//input[@value="Canviar contrasenya"]').click()
        # comprovem usuari creat OK
        # TODO: millorar test (comprovar no errors/warnings)
        #self.selenium.find_element_by_xpath('//li[@class="success" and contains(text(),"fou afegit amb èxit")]')
        self.selenium.find_element_by_xpath('//li[@class="success"]')

    def crea_oferta_caducada(self):
        self.ves_al_menu_principal()
        # menu ofertes
        self.selenium.find_element_by_xpath(
            '//a[@href="/admin/borsApp/oferta/add/"]').click()
        # omplim form
        self.selenium.find_element_by_name('inici_0').clear()
        self.selenium.find_element_by_name('inici_1').clear()
        self.selenium.find_element_by_name('final_0').clear()
        self.selenium.find_element_by_name('final_1').clear()
        self.selenium.find_element_by_name('inici_0').send_keys("01/01/2019")
        self.selenium.find_element_by_name('inici_1').send_keys("10:30:00")
        self.selenium.find_element_by_name('final_0').send_keys("10/02/2019")
        self.selenium.find_element_by_name('final_1').send_keys("10:30:00")
        self.selenium.find_element_by_name('titol').send_keys(
            "oferta test caducada 1")
        # select2 empresa (FK)
        self.selenium.find_element_by_xpath(
            '//span[@id="select2-id_empresa-container"]').click()
        self.selenium.find_element_by_xpath('//li[text()="' + self.username +
                                            '"]').click()
        # select2 cicles (m2m)
        self.selenium.find_element_by_xpath(
            '//div[@class="form-row field-cicles"]').click()
        self.selenium.find_element_by_xpath(
            '//input[@class="select2-search__field"]').send_keys("web\n")
        # direccio té el RichTextField amb un iframe pel mig
        # accedir dins iframe direcció
        self.selenium.switch_to_frame("id_descripcio_ifr")
        self.selenium.find_element_by_xpath('//body').send_keys(
            "oferta test caducada.\nbla bla...")
        # tornar al main frame
        self.selenium.switch_to_default_content()
        # submit
        self.selenium.find_element_by_xpath('//input[@value="Desar"]').click()
        # comprovem oferta creada OK
        self.selenium.find_element_by_xpath('//li[@class="success"]')

    def veu_oferta_caducada1(self):
        self.ves_al_menu_principal()
        self.selenium.find_element_by_xpath('//a[text()="Ofertes"]').click()
        self.selenium.find_element_by_xpath(
            '//a[text()="oferta test caducada 1"]').click()

    def no_veu_oferta_caducada1(self):
        self.ves_al_menu_principal()
        try:
            self.selenium.find_element_by_xpath(
                '//a[text()="Ofertes"]').click()
            self.selenium.find_element_by_xpath(
                '//a[text()="oferta test caducada 1"]').click()
            raise Exception(
                "ERROR: l'usuari no autoritzat '%s' pot veure les ofertes de l'empresa 1"
                % (self.username, ))
        except NoSuchElementException as e:
            # si no el troba, esta OK
            pass
        except Exception as e:
            raise e
示例#47
0
def is_alert_present(wd):
    try:
        wd.switch_to_alert().text
        return True
    except:
        return False

try:
    wd.get("https://rippletrade.com/")
    wd.find_element_by_link_text("Sign Up").click()
    wd.find_element_by_id("register_username").click()
    wd.find_element_by_id("register_username").clear()
    wd.find_element_by_id("register_username").send_keys("yuiyoxoq")
    wd.find_element_by_id("register_password").click()
    wd.find_element_by_id("register_password").clear()
    wd.find_element_by_id("register_password").send_keys("b1zd3vf0r3v3r")
    wd.find_element_by_id("register_password2").click()
    wd.find_element_by_id("register_password2").clear()
    wd.find_element_by_id("register_password2").send_keys("b1zd3vf0r3v3r")
    wd.find_element_by_id("register_email").click()
    wd.find_element_by_id("register_email").clear()
    wd.find_element_by_id("register_email").send_keys("*****@*****.**")
    if not wd.find_element_by_id("terms").is_selected():
        wd.find_element_by_id("terms").click()
    wd.find_element_by_xpath("//div[@id='t-register']//button[.='Sign UpMigrate Account']").click()
    wd.find_element_by_xpath("//div[@id='t-register']/section/div[4]/div[2]/div[5]/button").click()
finally:
    wd.quit()
    if not success:
        raise Exception("Test failed.")
示例#48
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()
class CalculatorTests(StaticLiveServerTestCase):


    @classmethod
    def setUpClass(cls):
        super(CalculatorTests, cls).setUpClass()
        User.objects.create_superuser(username='******',
                                      password='******',
                                      email='*****@*****.**')


    @classmethod
    def tearDownClass(cls):

        super(CalculatorTests, cls).tearDownClass()

    def setUp(self):
        self.selenium = WebDriver(executable_path='/usr/local/bin/geckodriver')
        self.selenium.implicitly_wait(10)
        print('<<<< SETUP')

    def tearDown(self):
        #self.selenium.quit()
        print('<<<< TD')

    def test_calculator(self):
        """
        Django Admin login test
        """
        # Open the admin index page
        self.selenium.get(self.live_server_url + reverse('calendar:calculator'))
        # Selenium knows it has to wait for page loads (except for AJAX requests)
        # so we don't need to do anything about that, and can just
        # call find_css. Since we can chain methods, we can
        # call the built-in send_keys method right away to change the
        # value of the field
        self.selenium.find_element_by_xpath('//*[@id="id_start_date"]').send_keys(4 * Keys.BACKSPACE)
        self.selenium.find_element_by_xpath('//*[@id="id_start_date"]').send_keys("2017-10-01")
        # for the password, we can now just call find_css since we know the page
        # has been rendered
        self.selenium.find_element_by_xpath('//*[@id="id_end_date"]').send_keys(4 * Keys.BACKSPACE)
        self.selenium.find_element_by_xpath('//*[@id="id_end_date"]').send_keys('2017-10-31')
        # You're not limited to CSS selectors only, check
        # http://seleniumhq.org/docs/03_webdriver.html for
        # a more compreehensive documentation.
        self.selenium.find_element_by_xpath('/html/body/div[2]/form/input[2]').click()
        # /html/body/div[2]/form/input[2]
        element = self.selenium.find_element_by_xpath('/html/body/div[2]/h3')  # /html/body/div[2]/form/input[2]
        message = '22 working days'
        self.assertEqual(element.text, message)