示例#1
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()
示例#2
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.")
def syn_test_script():

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


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


        driver.get("http://www.jared.com/en/jaredstore")

        log_output("Searching for Engagement")
        driver.find_element_by_id("SimpleSearchForm_SearchTerm").click()
        driver.find_element_by_id("SimpleSearchForm_SearchTerm").clear()
        driver.find_element_by_id("SimpleSearchForm_SearchTerm").send_keys("Engagement")
        driver.find_element_by_id("searchButton").click()

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

    finally:
        driver.quit()
        if not success:
            raise Exception("Test failed.")
示例#4
0
class RegisterTest(LiveServerTestCase):
    def setUp(self):
        self.browser = WebDriver()
        self.browser.implicitly_wait(5)
        create_user('john', '*****@*****.**', 'johnpassword')
        steps_to_login(self.browser, self.live_server_url, 'john',
                       'johnpassword')

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

    def test_title(self):
        open_page(self.browser, '/register/', self.live_server_url)
        self.assertIn('Register Supernova', self.browser.title)

    def steps_to_create_user(self, username, email, password):
        open_page(self.browser, '/register/', self.live_server_url)
        username_input = self.browser.find_element_by_name('username')
        username_input.send_keys(username)
        email_input = self.browser.find_element_by_name('email')
        email_input.send_keys(email)
        password_input = self.browser.find_element_by_name('password')
        password_input.send_keys(password)
        button_register = self.browser.find_element_by_name('submit')
        button_register.click()

    def test_register_correct(self):
        self.steps_to_create_user('teste_django',
                                  '*****@*****.**',
                                  'teste_django')
        register_correct_message = self.browser.find_element_by_tag_name(
            'strong')
        self.assertIn('thank you for registering!',
                      register_correct_message.text)

    def test_register_repeated_user(self):
        self.steps_to_create_user('testedjangorepeated',
                                  '*****@*****.**',
                                  'testedjangorepeated')
        self.steps_to_create_user('testedjangorepeated',
                                  '*****@*****.**',
                                  'testedjangorepeated')
        register_repeated_message = self.browser.find_element_by_tag_name('li')
        self.assertIn('User with this Username already exists.',
                      register_repeated_message.text)
示例#5
0
def test_start_page_with_files(browser: WebDriver, home_page):
    browser.get(home_page)
    assert browser.title == 'Feed files control - FFC'
    header_text = browser.find_element_by_tag_name('h1').text
    assert header_text == 'Feed files control - FFC'
    button = browser.find_element_by_id('id_new_manufacturers')
    button.click()
    form = browser.find_element_by_tag_name('form')
    assert form
    name_brand_field = browser.find_element_by_id('id_brand_name')
    file_field = browser.find_element_by_id("id_file_feed")
    name_brand_field.send_keys('Bosh')
    # TODO: change to pytest tmpfile
    file_field.send_keys(os.path.join(os.path.dirname(__file__),
                                      "example.txt"))
    form.submit()
    sleep(3)
    check_for_row_in_table_manufactured(browser, 'Bosh')
    check_for_row_in_table_manufactured(browser, 'example.txt')
示例#6
0
def get_backend_log(browser: webdriver.WebDriver):
    go_to_page(browser, wbm_cfg.logsite_url, wbm_cfg.iframe_logs_xpath)

    dd_view_log = Select(
        browser.find_element_by_tag_name(wbm_cfg.btn_dropdown_logview_name))
    dd_view_log.select_by_value(wbm_cfg.filename_backend_log)
    bt_dwnl_log = browser.find_element_by_name(
        wbm_cfg.btn_download_logfile_name)
    bt_dwnl_log.click()
    time.sleep(2)
    pyautogui.typewrite("\n")
    browser.switch_to.default_content()
示例#7
0
class RegisterTest(LiveServerTestCase):
    
    def setUp(self):
        self.browser = WebDriver()
        self.browser.implicitly_wait(5)
        create_user('john','*****@*****.**','johnpassword')
        steps_to_login(self.browser,self.live_server_url,'john','johnpassword')
        
    def tearDown(self):
        self.browser.quit()
           
    def test_title(self):
        open_page(self.browser, '/register/', self.live_server_url)
        self.assertIn('Register Supernova', self.browser.title)
    
    def steps_to_create_user(self,username,email,password):
        open_page(self.browser, '/register/', self.live_server_url)
        username_input = self.browser.find_element_by_name('username')
        username_input.send_keys(username)
        email_input = self.browser.find_element_by_name('email')
        email_input.send_keys(email)
        password_input = self.browser.find_element_by_name('password')
        password_input.send_keys(password)
        button_register = self.browser.find_element_by_name('submit')
        button_register.click()
    
    def test_register_correct(self):
        self.steps_to_create_user('teste_django','*****@*****.**','teste_django')
        register_correct_message = self.browser.find_element_by_tag_name('strong')
        self.assertIn('thank you for registering!', register_correct_message.text)
        
    def test_register_repeated_user(self):
        self.steps_to_create_user('testedjangorepeated','*****@*****.**','testedjangorepeated')
        self.steps_to_create_user('testedjangorepeated','*****@*****.**','testedjangorepeated')
        register_repeated_message = self.browser.find_element_by_tag_name('li')
        self.assertIn('User with this Username already exists.', register_repeated_message.text)
示例#8
0
class HomeTestCase(LiveServerTestCase):
    def setUp(self):
        self.browser = WebDriver()
        self.browser.implicitly_wait(3)

    def test_home(self):
        self.browser.get('{0}{1}'.format(self.live_server_url,reverse('index')))
        body = self.browser.find_element_by_tag_name('body')
        self.assertIn('username', body.text)
        user = ModelTestFactory.getUser(password='******')
        username_input = self.browser.find_element_by_name("username")
        username_input.send_keys(user.username)
        password_input = self.browser.find_element_by_name("password")
        password_input.send_keys('test')
        self.browser.find_element_by_id('loginBtn').click()
示例#9
0
文件: tests.py 项目: suzizi/niji
class VisitorTest(LiveServerTestCase):
    """
    Test as a visitor (unregistered user)
    """

    def setUp(self):
        self.browser = WebDriver()
        self.browser.implicitly_wait(3)
        self.n1 = Node.objects.create(
            title='TestNodeOne',
            description='The first test node'
        )
        self.u1 = User.objects.create_user(
            username='******', email='*****@*****.**', password='******'
        )
        self.u2 = User.objects.create_user(
            username='******', email='*****@*****.**', password='******'
        )

        # Create 99 topics
        for i in range(1, 100):
            setattr(
                self,
                't%s' % i,
                Topic.objects.create(
                    title='Test Topic %s' % i,
                    user=self.u1,
                    content_raw='This is test _topic __%s__' % i,
                    node=self.n1
                )
            )

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

    def test_index(self):
        self.browser.get(self.live_server_url+reverse('niji:index'))
        body = self.browser.find_element_by_tag_name('body')
        self.assertIn('niji', body)

    def test_topic_page(self):
        pass

    def test_node_page(self):
        pass

    def test_pagination(self):
        pass
示例#10
0
def get_middleware_log(browser: webdriver.WebDriver):
    go_to_page(browser, wbm_cfg.logsite_url, wbm_cfg.iframe_logs_xpath)

    dd_view_log = Select(
        browser.find_element_by_tag_name(wbm_cfg.btn_dropdown_logview_name))
    try:
        dd_view_log.select_by_value(wbm_cfg.filename_middleware_log)
        logging.info("Selected middleware log file")
    except NoSuchElementException:
        logging.error(str(dd_view_log) + " - No such dropdown element found")

    bt_dwnl_log = browser.find_element_by_name(
        wbm_cfg.btn_download_logfile_name)
    bt_dwnl_log.click()
    time.sleep(2)
    pyautogui.press("down")
    pyautogui.typewrite("\n")
    browser.switch_to.default_content()
示例#11
0
class LoginTest(LiveServerTestCase):
    def setUp(self):
        self.browser = WebDriver()
        self.browser.implicitly_wait(5)

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

    def test_title(self):
        open_page(self.browser, '/login/', self.live_server_url)
        self.assertIn('Login Supernova', self.browser.title)

    def test_login_correct(self):
        create_user('john', '*****@*****.**', 'johnpassword')
        steps_to_login(self.browser, self.live_server_url, 'john',
                       'johnpassword')
        self.assertIn('Index', self.browser.title)

    def test_login_incorrect(self):
        create_user('john', '*****@*****.**', 'johnpassword')
        steps_to_login(self.browser, self.live_server_url, 'john1',
                       'johnpassword1')
        login_incorrect = self.browser.find_element_by_tag_name('body')
        self.assertIn('Invalid login details supplied.', login_incorrect.text)

    def test_login_and_logout(self):
        create_user('john', '*****@*****.**', 'johnpassword')
        steps_to_login(self.browser, self.live_server_url, 'john',
                       'johnpassword')
        login_successful = self.browser.find_element_by_tag_name('strong')
        self.assertIn('Welcome to Supernova', login_successful.text)
        link_logout = self.browser.find_element_by_link_text('Logout')
        link_logout.click()
        logout_sucessful = self.browser.find_element_by_tag_name('h1')
        self.assertIn('Login to Supernova', logout_sucessful.text)

    def test_login_logout_and_login(self):
        create_user('john', '*****@*****.**', 'johnpassword')
        steps_to_login(self.browser, self.live_server_url, 'john',
                       'johnpassword')
        login_successful = self.browser.find_element_by_tag_name('strong')
        self.assertIn('Welcome to Supernova', login_successful.text)
        link_logout = self.browser.find_element_by_link_text('Logout')
        link_logout.click()
        logout_sucessful = self.browser.find_element_by_tag_name('h1')
        self.assertIn('Login to Supernova', logout_sucessful.text)
        steps_to_login(self.browser, self.live_server_url, 'john',
                       'johnpassword')
        login_successful = self.browser.find_element_by_tag_name('strong')
        self.assertIn('Welcome to Supernova', login_successful.text)
示例#12
0
文件: tests.py 项目: jw345654662/niji
class VisitorTest(LiveServerTestCase):
    """
    Test as a visitor (unregistered user)
    """
    def setUp(self):
        self.browser = WebDriver()
        self.browser.implicitly_wait(3)
        self.n1 = Node.objects.create(title='TestNodeOne',
                                      description='The first test node')
        self.u1 = User.objects.create_user(username='******',
                                           email='*****@*****.**',
                                           password='******')
        self.u2 = User.objects.create_user(username='******',
                                           email='*****@*****.**',
                                           password='******')

        # Create 99 topics
        for i in range(1, 100):
            setattr(
                self, 't%s' % i,
                Topic.objects.create(title='Test Topic %s' % i,
                                     user=self.u1,
                                     content_raw='This is test _topic __%s__' %
                                     i,
                                     node=self.n1))

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

    def test_index(self):
        self.browser.get(self.live_server_url + reverse('niji:index'))
        body = self.browser.find_element_by_tag_name('body')
        self.assertIn('niji', body)

    def test_topic_page(self):
        pass

    def test_node_page(self):
        pass

    def test_pagination(self):
        pass
示例#13
0
def syn_test_script():

    try:
        success = True
        driver = WebDriver()
        driver.implicitly_wait(60)
        log_output("Starting @ http://www.kay.com/en/kaystore")

        driver.get("http://www.kay.com/en/kaystore")
        driver.find_element_by_id("site-search__input").click()
        driver.find_element_by_id("site-search__input").clear()
        driver.find_element_by_id("site-search__input").send_keys("engagement")
        driver.find_element_by_id("searchButton").click()
        if not ("Engagement" in driver.find_element_by_tag_name("html").text):
            success = False
            print("verifyTextPresent failed")

    finally:
        driver.quit()
        if not success:
            raise Exception("Test failed.")
示例#14
0
class LoginTest(LiveServerTestCase):
    
    def setUp(self):
        self.browser = WebDriver()
        self.browser.implicitly_wait(5)

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

    def test_title(self):
        open_page(self.browser, '/login/', self.live_server_url)
        self.assertIn('Login Supernova', self.browser.title)
        
    def test_login_correct(self):
        create_user('john','*****@*****.**','johnpassword')
        steps_to_login(self.browser,self.live_server_url,'john','johnpassword')
        self.assertIn('Index', self.browser.title)
    
    def test_login_incorrect(self):
        create_user('john','*****@*****.**','johnpassword')
        steps_to_login(self.browser,self.live_server_url,'john1','johnpassword1')
        login_incorrect = self.browser.find_element_by_tag_name('body')
        self.assertIn('Invalid login details supplied.', login_incorrect.text)
        
    def test_login_and_logout(self): 
        create_user('john','*****@*****.**','johnpassword')
        steps_to_login(self.browser,self.live_server_url,'john','johnpassword')
        login_successful = self.browser.find_element_by_tag_name('strong')
        self.assertIn('Welcome to Supernova', login_successful.text)
        link_logout = self.browser.find_element_by_link_text('Logout')
        link_logout.click()
        logout_sucessful = self.browser.find_element_by_tag_name('h1')
        self.assertIn('Login to Supernova',logout_sucessful.text)
    
    def test_login_logout_and_login(self): 
        create_user('john','*****@*****.**','johnpassword')
        steps_to_login(self.browser,self.live_server_url,'john','johnpassword')
        login_successful = self.browser.find_element_by_tag_name('strong')
        self.assertIn('Welcome to Supernova', login_successful.text)
        link_logout = self.browser.find_element_by_link_text('Logout')
        link_logout.click()
        logout_sucessful = self.browser.find_element_by_tag_name('h1')
        self.assertIn('Login to Supernova',logout_sucessful.text)
        steps_to_login(self.browser,self.live_server_url,'john','johnpassword')
        login_successful = self.browser.find_element_by_tag_name('strong')
        self.assertIn('Welcome to Supernova', login_successful.text)
示例#15
0
class LiveServerTest(object):
    fixtures = ['rules.json']

    DOWNLOAD_DIRECTORY = '/tmp/work/downloads'


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

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

    def setUp(self):

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def submit_support_form(self):
        submit_button = self.selenium.find_element_by_css_selector('button[type="submit"]')
        submit_button.submit()
示例#16
0
def is_alert_present(wd):
    try:
        wd.switch_to_alert().text
        return True
    except:
        return False


#=======================================================================
# Starting the tile view script
#=======================================================================
try:
    FH.write("Starting the view a tile script\n\n")
    FH.write("Connecting to the website\n\n")
    wd.get(url)
    if not ("Login with LDAP" in wd.find_element_by_tag_name("html").text):
        success = False
        FH.write("Failed to connect to the website. Check your URL")
        raise Exception()
    time.sleep(1)
    wd.find_element_by_id("formLoginUser").click()
    time.sleep(1)
    wd.find_element_by_id("formLoginUser").clear()
    time.sleep(1)
    wd.find_element_by_id("formLoginUser").send_keys(viewer)
    time.sleep(1)
    wd.find_element_by_id("formLoginPassword").click()
    time.sleep(1)
    wd.find_element_by_id("formLoginPassword").clear()
    time.sleep(1)
    wd.find_element_by_id("formLoginPassword").send_keys(password1)
示例#17
0
class IntegrationTests(StaticLiveServerTestCase):
    """Integration tests by using the Selenium web drivers"""
    fixtures = ['test_data.json']

    def setUp(self):
        self.driver = WebDriver()

    def login_player(self):
        """Helper function for logging in as a player"""
        self.driver.get('%s%s' % (self.live_server_url, '/login'))

        username = self.driver.find_element_by_id('id_username')
        password = self.driver.find_element_by_id('id_password')
        submit = self.driver.find_element_by_tag_name('button')

        username.send_keys('player')
        password.send_keys('player')

        submit.click()

    def login_developer(self):
        """Helper function for logging in as a developer"""
        self.driver.get('%s%s' % (self.live_server_url, '/login'))

        username = self.driver.find_element_by_id('id_username')
        password = self.driver.find_element_by_id('id_password')
        submit = self.driver.find_element_by_tag_name('button')

        username.send_keys('developer')
        password.send_keys('developer')

        submit.click()

    def test_login(self):
        """Test that logging in works properly"""
        self.login_player()

        assert 'player Account' in self.driver.page_source

    def test_registration(self):
        """
        Test that registration completes, a verification email notification is sent and that
        verification works
        """
        self.driver.get('%s%s' % (self.live_server_url, '/register'))

        first_name = self.driver.find_element_by_id('id_first_name')
        last_name = self.driver.find_element_by_id('id_last_name')
        username = self.driver.find_element_by_id('id_username')
        email = self.driver.find_element_by_id('id_email')
        password1 = self.driver.find_element_by_id('id_password')
        password2 = self.driver.find_element_by_id('id_password1')
        submit = self.driver.find_element_by_tag_name('button')

        first_name.send_keys('Selenium')
        last_name.send_keys('Tester')
        username.send_keys('selenium')
        email.send_keys('*****@*****.**')
        password1.send_keys('qwerty')
        password2.send_keys('qwerty')

        submit.click()

        #Check that the user is not active but email is supposedly sent
        test_user = User.objects.get(username="******")
        assert 'User successfully created, verification email sent!' in self.driver.page_source
        self.assertEqual(test_user.is_active, False)

        #Enter verification bytes and check that the user has been activated
        verification_bytes = test_user.type.verification_bytes
        self.driver.get('%s%s%s' % (self.live_server_url, '/user_verification/',
                                    verification_bytes))
        assert 'User selenium has been verified. Please login.' in self.driver.page_source
        self.assertEqual(User.objects.get(username="******").is_active, True)

    def test_purchasing_game(self):
        """Tests that game can be purchased"""
        self.login_player()
        self.driver.get('%s%s' % (self.live_server_url, '/gamestorepage/3'))

        buy_button = self.driver.find_element_by_xpath("//input[@type='submit']")
        buy_button.click()

        confirm_button = self.driver.find_element_by_xpath("//button[text()='Pay']")
        confirm_button.click()

        assert 'has now been added to your game list!' in self.driver.page_source

    def test_editing_game(self):
        """Tests that game details can be edited by navigating through my games"""
        self.login_developer()
        self.driver.get('%s%s' % (self.live_server_url, '/mygames'))

        game_entry = self.driver.find_element_by_class_name('game-list-container')
        game_entry.click()

        edit_button = self.driver.find_element_by_link_text('Edit')
        edit_button.click()

        modify_button = self.driver.find_element_by_xpath("//button[text()='Modify']")
        game_name = self.driver.find_element_by_id('id_game_name')
        game_name.clear()
        game_name.send_keys('New game name')

        modify_button.click()

        assert 'New game name details have been updated.' in self.driver.page_source

    def test_playing_game(self):
        """Test playing, acquiring score, submitting the score and that score is saved"""
        self.login_player()
        self.driver.get('%s%s' % (self.live_server_url, '/boughtgames'))

        game_entry = self.driver.find_elements_by_class_name('game-list-container')[1]
        game_entry.click()

        play_button = self.driver.find_elements_by_link_text('Play')[1]
        play_button.click()

        assert 'Test Game' in self.driver.page_source

        self.driver.switch_to.frame(self.driver.find_element_by_id('gameFrame'))
        add_score_button = self.driver.find_element_by_id('add_points')

        #Click the button 5 times totaling 50 score
        add_score_button.click()
        add_score_button.click()
        add_score_button.click()
        add_score_button.click()
        add_score_button.click()

        submit_score_button = self.driver.find_element_by_id('submit_score')
        submit_score_button.click()

        self.driver.get('%s%s' % (self.live_server_url, '/boughtgames'))
        game_entry = self.driver.find_elements_by_class_name('game-list-container')[1]
        game_entry.click()

        game_table = self.driver.find_element_by_xpath(
            '(//table[@class="game-list-stats"])[2]//tr[2]')
        self.assertEqual(game_table.text, 'Personal highscore: 50')

    def tearDown(self):
        self.driver.quit()
示例#18
0
script, country = argv

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


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


try:
    wd.get("http://en.wikipedia.org/wiki/Main_Page")
    wd.find_element_by_id("searchInput").click()
    wd.find_element_by_id("searchInput").clear()
    wd.find_element_by_id("searchInput").send_keys(country)
    wd.find_element_by_id("searchButton").click()
    if not ("Malagasy" in wd.find_element_by_tag_name("html").text):
        success = False
        print("verifyTextPresent failed")

    print("Malagasy")
finally:
    wd.quit()
    if not success:
        raise Exception("Test failed.")
示例#19
0
class UserEventCreationTest(LiveServerTestCase, unittest.TestCase):
    '''
        class tests apps event related operations
        create instances and listing avaialable
    '''
    def setUp(self):
        self.selenium = WebDriver()

        self.event = {
            'title': 'My Title',
            'description': 'This should be a long description about an event\n'\
                                    'but am gonna keep it short',
            'state': 'Private',
            'date': '2021-12-22'

        }

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

    def register_user(self, username, email):
        '''
            submits a POST request to accounts/signup wiht user data
            before running login with user data
        '''
        self.client.post('/accounts/signup',
                         data={
                             'username': username,
                             'email': email,
                             'password1': "awdaw1234",
                             'password2': "awdaw1234",
                         })

    def login_user(self):
        '''
            logs in an user
        '''
        self.client.post('/accounts/login',
                         data={
                             'username': "******",
                             'password': "******",
                         })

    def navigateToLogin(self):
        '''
            navigates to signup form root url
        '''
        ## access website
        self.selenium.get('%s%s' % (self.live_server_url, '/'))
        login_link = self.selenium.find_element_by_id('sign_in')

        ## navigate to login page
        sign_in_link = login_link.get_attribute('href')
        self.selenium.get(sign_in_link)

    def submitSignInForm(self, username, password):
        '''
            submits data to sign up form
        '''
        ## find and fill input fields
        user_name_field = self.selenium.find_element_by_id('id_username')
        user_name_field.send_keys(username)
        password_field = self.selenium.find_element_by_id('id_password')
        password_field.send_keys(password)

        ## click the submit button
        submit_form = self.selenium.find_element_by_tag_name('form')
        submit_form.submit()

    def fill_event(self):
        user_name_field = self.selenium.find_element_by_id('id_title')
        user_name_field.send_keys(self.event['title'])

        description_field = self.selenium.find_element_by_id('id_description')
        description_field.send_keys(self.event['description'])

        date_field = self.selenium.find_element_by_id('id_date')
        date_field.send_keys(self.event['date'])

        state_field = self.selenium.find_element_by_id('id_state')
        select_object = Select(state_field)
        select_object.select_by_visible_text(self.event['state'])

        form = self.selenium.find_element_by_tag_name('form')
        form.submit()

    def test_logged_in_user_event_creation(self):
        '''
            tests a logged in user 
            can create events and view them after
        '''
        timeout = 2

        ## register user wait 1 sec
        self.register_user("my_user", "*****@*****.**")
        time.sleep(1)

        ## login user wait 1 sec
        self.navigateToLogin()

        self.submitSignInForm("my_user", "awdaw1234")

        WebDriverWait(self.selenium, timeout).until(
            lambda driver: driver.find_element_by_id('user_controls'))

        n = 1

        for _ in range(n):

            ## find the create button
            create_event_button = self.selenium.find_element_by_id(
                'create_event')
            create_event_button.click()

            WebDriverWait(self.selenium, timeout).until(
                lambda driver: driver.find_element_by_id('id_title'))

            ## fills the event form
            self.fill_event()

            ## waits for redirection, locates the events list
            WebDriverWait(self.selenium, timeout).until(
                lambda driver: driver.find_element_by_id('events_list'))

            ## checks if the displayed event
            ## matches submitted event
            card = self.selenium.find_element_by_class_name('card')
            field_state = card.find_element_by_id('event_state')
            field_author = card.find_element_by_id('event_author')
            field_date = card.find_element_by_id('event_date')
            self.assertEqual(field_state.get_attribute('innerHTML'),
                             self.event['state'])
            self.assertEqual(field_author.get_attribute('innerHTML'),
                             'Author:' + 'my_user')
            # formatting
            #self.assertEqual(field_date.get_attribute('innerHTML'),'Date:'+self.event['date'])

    def register_event(self):
        Event

    def test_loggedIn_user_subscribes_to_events(self):
        '''
            tests subscribing to event
        '''

        timeout = 2

        ## register user wait 1 sec
        self.register_user("my_user", "*****@*****.**")
        time.sleep(1)
        self.register_user("my_user1", "*****@*****.**")
        time.sleep(1)

        ## login user wait 1 sec
        self.navigateToLogin()

        self.submitSignInForm("my_user", "awdaw1234")

        WebDriverWait(self.selenium, timeout).until(
            lambda driver: driver.find_element_by_id('user_controls'))
success = True
wd = WebDriver()
wd.implicitly_wait(60)

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

try:
    wd.get("http://www.jared.com/en/jaredstore/")
    wd.find_element_by_link_text("Engagement").click()
    if not ("Engagement" in wd.find_element_by_tag_name("html").text):
        success = False
        print("verifyTextPresent failed")
    if not wd.find_element_by_id("facet_checkbox8").is_selected():
        wd.find_element_by_id("facet_checkbox8").click()
    wd.find_element_by_id("view-more").click()
    wd.find_element_by_link_text("VAULT VALUE
                        			
								
							
                        
							Vera Wang LOVE 1 Carat tw Diamonds 14K White Gold Ring 
								
							 
						
						
示例#21
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)
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()
示例#23
0
import time

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


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


try:
    driver.get(
        "http://www.jared.com/FindAStoreView?storeId=10451&catalogId=10001&langId=-1"
    )
    driver.find_element_by_id("input_location").click()
    driver.find_element_by_id("input_location").clear()
    driver.find_element_by_id("input_location").send_keys("44444")
    driver.find_element_by_id("findStoresBtn").click()
    if not ("Fashion Square" in driver.find_element_by_tag_name("html").text):
        success = False
        print("verifyTextPresent failed")
finally:
    driver.quit()
    if not success:
        raise Exception("Test failed.")
示例#24
0
import time

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

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

try:
    wd.get("http://www.jared.com/en/jaredstore/searchterm/732541000/true/732541000%20and%20confirm%20all%20objects%20load")
    if not ("items" in wd.find_element_by_tag_name("html").text):
        success = False
        print("verifyTextPresent failed")
    if not ("Men's Cufflinks Titanium" in wd.find_element_by_tag_name("html").text):
        success = False
        print("verifyTextPresent failed")
    wd.find_element_by_xpath("//div[@id='product-grid']/div[1]/div/a/img").click()
    wd.find_element_by_id("btnStartCustomizing").click()
    wd.find_element_by_id("e_1").click()
    wd.find_element_by_id("e_1").clear()
    wd.find_element_by_id("e_1").send_keys("App")
    wd.find_element_by_xpath("//div[@id='engr']//a[.='Next']").click()
    wd.find_element_by_id("addToCart").click()
    wd.find_element_by_link_text("CHECKOUT").click()
    if not ("Shopping Bag (1 Item)" in wd.find_element_by_tag_name("html").text):
        success = False
class PollsTest(LiveServerTestCase):

    def setUp(self):

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

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

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

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

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

        password_field.send_keys(Keys.RETURN)

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

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

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

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

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

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

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

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

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

        self.assertEquals(len(new_poll_links), 1)
示例#26
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)
示例#27
0
wd.implicitly_wait(60)


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


try:
    wd.get(
        "http://www.jared.com/en/jaredstore/searchterm/731434000/true/731434000"
    )
    if not ("items" in wd.find_element_by_tag_name("html").text):
        success = False
        print("verifyTextPresent failed")
    wd.find_element_by_partial_link_text(
        "Mother's Bracelet Round Birthstones Design in Silver").click()
    if not wd.find_element_by_xpath(
            "//select[@id='configSelect']//option[2]").is_selected():
        wd.find_element_by_xpath(
            "//select[@id='configSelect']//option[2]").click()
    wd.find_element_by_id("btnStartCustomizing").click()
    if not wd.find_element_by_xpath(
            "//select[@id='metalTypeSelect']//option[2]").is_selected():
        wd.find_element_by_xpath(
            "//select[@id='metalTypeSelect']//option[2]").click()
    wd.find_element_by_id("next-step").click()
    if not wd.find_element_by_xpath(
def syn_test_script():

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

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

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

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

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

        log_output("Start customizing Jewelery")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    finally:
        driver.quit()
        if not success:
            raise Exception("Test failed.")
class NoteCreationTest(LiveServerTestCase):
    @classmethod
    def setUpClass(self):
        self.selenium = WebDriver()
        super(NoteCreationTest, self).setUpClass()

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

    def test_a_registered_user_creates_a_note_with_title_paragraphs_and_summary(
            self):
        user = User.objects.create_user('elusuario', '*****@*****.**',
                                        '12345678')
        user.save()

        # Notes creatin requires user to login
        visit(self, reverse("index"))
        self.assertTrue("/accounts/login" in self.selenium.current_url)

        login(self, user)

        visit(self, reverse("index"))
        body = self.selenium.find_element_by_tag_name('body')
        self.assertTrue(has_content(body, "No existen notas"))

        click_on(body, "Nueva nota")

        # Content for the new note
        body = self.selenium.find_element_by_tag_name('body')
        fill_in(body, "title", "Pisos termicos")
        fill_in(body, "paragraphs-0-description",
                "Distintos tipos de cultivos")
        fill_in(body, "paragraphs-0-content",
                "se clasifican segun la altura sobre el nivel del mar")
        fill_in(
            body, "paragraphs-1-content",
            "los cultivos se producen segun la temperatura que se precesnta")
        fill_in(body, "paragraphs-2-content", "desiertos, llanos, paramos")
        fill_in(
            body, "summary",
            "Los pisos termicos permiten distintos tipos de cultivo segun la tepmeparuta"
        )

        click_on(body, "Guardar nota")

        body = self.selenium.find_element_by_tag_name('body')
        self.assertTrue(has_content(body, "Nota guardada"))
        note = Note.objects.latest('id')
        self.assertTrue(
            reverse('update', args=[note.id]) in self.selenium.current_url)
        self.assertEqual(3, note.paragraphs.count())

        # Editing a note
        body = self.selenium.find_element_by_tag_name('body')
        fill_in(body, "title", "Pisos termicos editados")
        fill_in(body, "paragraphs-0-description",
                "Distintos tipos de cultivos editados")
        fill_in(
            body, "paragraphs-0-content",
            "se clasifican segun la altura sobre el nivel del mar editados")
        fill_in(
            body, "paragraphs-1-content",
            "los cultivos se producen segun la temperatura que se precesnta editados"
        )
        fill_in(body, "paragraphs-2-content",
                "desiertos, llanos, paramos editados")
        fill_in(body, "paragraphs-3-description",
                "Importancia para el mercado")
        fill_in(body, "paragraphs-3-content",
                "Segun los cultivos se puede comercializar lo que se produce")
        fill_in(
            body, "summary",
            "Los pisos termicos permiten distintos tipos de cultivo segun la tepmeparuta editados"
        )

        click_on(body, "Guardar nota")

        body = self.selenium.find_element_by_tag_name('body')
        note = Note.objects.latest('id')
        self.assertEqual(4, note.paragraphs.count())

        # When returning to the index page the new note should be listed
        visit(self, reverse("index"))
        body = self.selenium.find_element_by_tag_name('body')
        self.assertTrue(has_content(body, "Pisos termicos editados"))
        self.assertFalse(has_content(body, "No existen notas"))

    def test_a_user_opens_an_existing_note_for_printing_or_sharing(self):
        """ An existing note can be open in a tab for printing or sharing via url.
            Viewing does not require login and the url contains a slug instead of the note id.
        """
        note = Note(
            title="Pisos termicos",
            summary=
            "Los pisos termicos permiten distintos tipos de cultivo segun la temperatura"
        )
        note.save()

        Paragraph(
            description="Distintos tipos de cultivos",
            content=
            "se clasifican segun la altura sobre el nivel del mar editados",
            note=note).save()

        visit(self, reverse("show", kwargs={'slug': note.slug}))

        body = self.selenium.find_element_by_tag_name('body')
        self.assertTrue(has_content(body, "Pisos termicos"))
        self.assertTrue(has_content(body, "Distintos tipos de cultivos"))
        self.assertTrue(
            has_content(
                body,
                "se clasifican segun la altura sobre el nivel del mar editados"
            ))
        self.assertTrue(
            has_content(
                body,
                "Los pisos termicos permiten distintos tipos de cultivo segun la temperatura"
            ))
示例#31
0
class NewVisitorTest(FunctionalTest):
    def test_can_start_list_for_one_user(self):
        self.browser.get(self.live_server_url)
        self.assertIn('To-Do list', self.browser.title)

        header_text = self.browser.find_element_by_tag_name('h2').text
        self.assertIn('To-Do', header_text)

        inputbox = self.get_item_input_box()
        self.assertEqual(inputbox.get_attribute('placeholder'),
                         'Enter a to-do item')

        inputbox.send_keys('Buy lambo')
        inputbox.send_keys(Keys.ENTER)

        self.wait_for_row_in_table('1: Buy lambo')

        inputbox = self.get_item_input_box()
        inputbox.send_keys('Make tattoo')
        inputbox.send_keys(Keys.ENTER)

        self.wait_for_row_in_table('1: Buy lambo')
        self.wait_for_row_in_table('2: Make tattoo')

        # self.fail('Finish the tests!')

    def test_multiple_users_lists_with_different_ulrs(self):
        # user Juliett
        self.browser.get(self.live_server_url)

        inputbox = self.get_item_input_box()
        inputbox.send_keys('Make tattoo for Juliett')
        inputbox.send_keys(Keys.ENTER)

        self.wait_for_row_in_table('1: Make tattoo for Juliett')

        julietts_lists_url = self.browser.current_url
        self.assertRegex(julietts_lists_url, r'/lists/.+')

        self.browser.quit()
        self.browser = WebDriver()

        # user Radoslaw
        self.browser.get(self.live_server_url)

        page_text = self.browser.find_element_by_tag_name('body').text
        self.assertNotIn('1: Make tattoo for Juliett', page_text)

        inputbox = self.get_item_input_box()
        inputbox.send_keys('Jump from plane')
        inputbox.send_keys(Keys.ENTER)
        self.wait_for_row_in_table('1: Jump from plane')

        radeks_lists_url = self.browser.current_url
        self.assertRegex(radeks_lists_url, r'/lists/.+')
        self.assertNotEqual(radeks_lists_url, julietts_lists_url)

        page_text = self.browser.find_element_by_tag_name('body').text
        self.assertNotIn('1: Make tattoo for Juliett', page_text)
        self.assertIn('1: Jump from plane', page_text)
        self.browser.quit()