def refresh_table(driver: WebDriver): # Be wary of the booking notification block after hitting add to cart. # need to navigate around it. It's class name is: booking-notification-block buttons: list[WebElement] = driver.find_elements_by_class_name("sarsa-button-sm") # type: ignore smart_sleep() print("Looking for refresh table button.") for button in buttons: span_contents: list[WebElement] = driver.find_elements_by_class_name("sarsa-button-content") # type: ignore for content in span_contents: if content.text == "Refresh Table": print("Refreshing table.") driver.execute_script("arguments[0].click();", button) return
class StickToTopTest(LiveServerTestCase): 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.super_user = User.objects.create_user( username='******', email='*****@*****.**', password='******' ) self.super_user.is_superuser = True self.super_user.is_staff = True self.super_user.save() # 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_stick_to_top_admin(self): self.browser.get(self.live_server_url + reverse("niji:index")) login(self.browser, 'super', '123') self.assertIn("Log out", self.browser.page_source) lucky_topic1 = getattr(self, 't%s' % random.randint(1, 50)) self.browser.get(self.live_server_url+reverse('niji:topic', kwargs={"pk": lucky_topic1.pk})) self.browser.find_element_by_class_name('move-topic-up').click() up_level = WebDriverWait( self.browser, 10 ).until( expected_conditions.presence_of_element_located( (By.NAME, 'move-topic-up-level') ) ) up_level = Select(up_level) up_level.select_by_visible_text('1') time.sleep(1) self.browser.execute_script("$('.modal-confirm').click()") self.browser.get(self.live_server_url+reverse('niji:index')) first_topic_title = self.browser.find_elements_by_class_name('entry-link')[0].text self.assertEqual(first_topic_title, lucky_topic1.title)
def check_availability_and_reserve(driver: WebDriver, url: str, reserved_count: int = -1): # desired_date = (date.today() + datetime.timedelta(days=14)).strftime("%b %d, %Y") # desired_date="May 22, 2021" global desired_date_global desired_date = desired_date_global if reserved_count == 5: return try: while True: driver.get(url) # Only log in the first attempt if reserved_count == -1: wait_for_login_screen_or_refresh_till_success(driver, "rec-availability-date", runner, sys.argv[1]) log_in(driver) reserved_count += 1 print("\nWaiting for page to load...") WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "rec-availability-date"))) WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CLASS_NAME, "SingleDatePickerInput_calendarIcon")) ) print("Page has loaded!") navigate_to_date(driver, desired_date, "single-date-picker-1") WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "rec-availability-date"))) rows: list[WebElement] = driver.find_elements_by_class_name("undefined") # type: ignore add_campsite_to_cart(driver, rows, desired_date, reserved_count) print("Refreshing page to try to find available dates for criteria...\n") refresh_table(driver) print("Table is refreshed.") except Exception as e: print(e) # win32api.MessageBox(0, "Failure.", "Failure", 0x00001000) finally: # print('Attempting to restart script') # runner(sys.argv[1]) pass
def enter_solution(driver: WebDriver, sudoku: KillerSudoku): first_cell = driver.find_elements_by_class_name('cell')[0] ActionChains(driver).move_to_element(first_cell).click().perform() time.sleep(1) def press_key(key): ActionChains(driver).send_keys(key).perform() for row in range(9): for column in range(9): press_key(str(int(sudoku.grid[row, column]))) time.sleep(0.03) press_key(Keys.ARROW_RIGHT) time.sleep(0.03) press_key(Keys.ARROW_DOWN) time.sleep(0.03) time.sleep(2) driver.find_element(By.XPATH, '//button[.="Back to the puzzles"]').click()
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()
class WStoreSeleniumTestCase(TestCase, LiveServerTestCase): fixtures = ['selenium_basic.json'] @classmethod def setUpClass(cls): super(WStoreSeleniumTestCase, cls).setUpClass() def setUp(self): # Open the page self.driver = WebDriver() self.driver.implicitly_wait(5) self.driver.set_window_size(1024, 768) self.driver.get(self.live_server_url) TestCase.setUp(self) def _check_container(self, container, offering_names): # Check offerings container container = self.driver.find_element_by_class_name(container) offering_elems = container.find_elements_by_class_name('menu-offering') self.assertEquals(len(offering_elems), len(offering_names)) for off_elem in offering_elems: title = off_elem.find_element_by_css_selector('h2') self.assertTrue(title.text in offering_names) def login(self, username='******'): # Set username username_elem = self.driver.find_element_by_name('username') username_elem.send_keys(username) # Set password password_elem = self.driver.find_element_by_name('password') password_elem.send_keys('admin') # Click login self.driver.find_element_by_css_selector('#login-form button').click() def oauth2_login(self, username='******'): from wstore.selenium_tests.tests import TESTING_PORT self.driver.get(self.live_server_url + '/oauth2/auth?response_type=code&client_id=test_app&redirect_uri=http://localhost:' + unicode(TESTING_PORT)) self.login(username) self.driver.find_element_by_class_name('btn-blue').click() time.sleep(1) # Get authorization code while self._server.call_received() < 1: pass code = self._server.get_path().split('=')[1] # Get access token opener = urllib2.build_opener() url = self.live_server_url + '/oauth2/token' data = 'client_id=test_app' data += '&client_secret=secret' data += '&grant_type=authorization_code' data += '&code=' + code data += '&redirect_uri=' + 'http://localhost:' + unicode(TESTING_PORT) headers = { 'content-type': 'application/form-url-encoded', } request = MethodRequest('POST', url, data, headers) response = opener.open(request) token = json.loads(response.read())['access_token'] return token def logout(self): self.driver.find_element_by_class_name('arrow-down-settings').click() options = self.driver.find_elements_by_css_selector('#settings-menu > li') options[-1].click() def tearDown(self): self.driver.quit() TestCase.tearDown(self) def back(self): self.driver.find_element_by_id('back').click() def view_all(self): self.driver.find_element_by_css_selector('#all').click() def search_keyword(self, keyword, id_='#text-search', btn='#search'): # Set search field search_elem = self.driver.find_element_by_css_selector(id_) search_elem.send_keys(keyword) # Click search button self.driver.find_element_by_css_selector(btn).click() def open_offering_details(self, offering_name): elements = self.driver.find_elements_by_class_name('menu-offering') for element in elements: if element.find_element_by_css_selector('h2').text == offering_name: element.click() break def _get_navs(self): submenu = self.driver.find_element_by_class_name('store-sub-menu') # Get first element return submenu.find_elements_by_css_selector('li') def click_first_cat(self): self.driver.find_element_by_id('menu-first-text').click() def click_second_cat(self): self.driver.find_element_by_id('menu-second-text').click() def click_third_cat(self): self.driver.find_element_by_id('menu-third-text').click() def click_first_nav(self): self._get_navs()[0].click() def click_second_nav(self): self._get_navs()[1].click() def _open_provider_option(self, option): self.driver.find_element_by_css_selector('#provider-options a.btn').click() self.driver.find_element_by_id(option).click() def create_offering_menu(self): self._open_provider_option('create-app') def fill_basic_offering_info(self, offering_info): # Name and version self.driver.find_element_by_css_selector('[name="app-name"]').send_keys(offering_info['name']) self.driver.find_element_by_css_selector('[name="app-version"]').send_keys(offering_info['version']) # Select the notification URL option if not offering_info['notification']: self.driver.find_element_by_css_selector('input[type="radio"][value="none"]').click() elif offering_info['notification'] == 'default': self.driver.find_element_by_css_selector('input[type="radio"][value="default"]').click() else: self.driver.find_element_by_css_selector('input[type="radio"][value="new"]').click() self.driver.find_element_by_id('notify').send_keys(offering_info['notification']) # Add the logo logo_path = os.path.join(settings.BASEDIR, 'wstore/ui/fiware/defaulttheme/static/assets/img/noimage.png') self.driver.find_element_by_id('img-logo').send_keys(logo_path) # Mark as open if needed if offering_info['open']: self.driver.find_element_by_id('open-offering').click() def _fill_usdl_form(self, usdl_info): # Fill description field self.driver.find_element_by_id('description').send_keys(usdl_info['description']) # Fill pricing info if needed if 'price' in usdl_info: self.driver.find_element_by_css_selector('#pricing-select option[value="single_payment"]').click() self.driver.find_element_by_id('price-input').send_keys(usdl_info['price']) if 'legal' in usdl_info: self.driver.find_element_by_id('legal-title').send_keys(usdl_info['legal']['title']) self.driver.find_element_by_id('legal-text').send_keys(usdl_info['legal']['text']) def _fill_usdl_upload(self, usdl_info): pass def _fill_usdl_url(self, usdl_info): pass def fill_usdl_info(self, usdl_info): # Select the correct method methods = { 'form': self._fill_usdl_form, 'upload': self._fill_usdl_upload, 'url': self._fill_usdl_url } methods[usdl_info['type']](usdl_info) def register_resource(self, resource_info): pass def click_tag(self, tag): tag_elems = self.driver.find_elements_by_class_name('tag') for te in tag_elems: if te.text == tag: te.click() break def fill_tax_address(self, tax): self.driver.find_element_by_id('street').send_keys(tax['street']) self.driver.find_element_by_id('postal').send_keys(tax['postal']) self.driver.find_element_by_id('city').send_keys(tax['city']) self.driver.find_element_by_id('country').send_keys(tax['country'])
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()
def check_availability_and_reserve(driver: WebDriver, url: str, reserved_count=[-1]): desired_date = date.today().strftime("%m-%Y") does_discord_want_stop = check_if_need_to_stop_from_discord() if does_discord_want_stop: print("Stopping from discord command after running") driver.close() driver.quit() return check_if_need_to_short_circuit() global desired_date_global if desired_date_global != "": date_split = desired_date.split("-") desired_date = f"{date_split[0]}/{desired_date_global}/{date_split[1]}" else: desired_date = date.today().strftime("%m/%d/%Y") print(desired_date) if reserved_count[0] == 5: global wait_global wait_global = True return runner() try: while True: driver.get(url) # Only log in the first attempt if reserved_count[0] == -1: wait_for_login_screen_or_refresh_till_success( driver, "SingleDatePickerInput_calendarIcon", runner, None) log_in(driver) reserved_count[0] += 1 print("\nWaiting for page to load...") WebDriverWait(driver, 10).until( EC.presence_of_element_located( (By.CLASS_NAME, "SingleDatePickerInput_calendarIcon"))) print("Page has loaded!") increase_quantity_to_two(driver) navigate_to_date(driver, desired_date, "DateInput_input_1", False) check_if_shuttle_times_are_available(driver, url, reserved_count) WebDriverWait(driver, 5).until( EC.presence_of_element_located( (By.CLASS_NAME, "ti-radio-pill-available"))) intended_times: list[ WebElement] = driver.find_elements_by_class_name( "ti-radio-pill-time") add_shuttle_to_cart(driver, intended_times, desired_date, reserved_count) print("Restarting checking process.\n") smart_sleep() return check_availability_and_reserve(driver, url, reserved_count) print("Page is refreshed.") except Exception as e: print(e) finally: # print('Attempting to restart script') # runner(sys.argv[1]) pass
class WStoreSeleniumTestCase(TestCase, LiveServerTestCase): fixtures = ['selenium_basic.json'] @classmethod def setUpClass(cls): super(WStoreSeleniumTestCase, cls).setUpClass() def setUp(self): # Open the page self.driver = WebDriver() self.driver.implicitly_wait(5) self.driver.set_window_size(1024, 768) self.driver.get(self.live_server_url) TestCase.setUp(self) def _check_container(self, container, offering_names): # Check offerings container container = self.driver.find_element_by_class_name(container) offering_elems = container.find_elements_by_class_name('menu-offering') self.assertEquals(len(offering_elems), len(offering_names)) for off_elem in offering_elems: title = off_elem.find_element_by_css_selector('h2') self.assertTrue(title.text in offering_names) def login(self, username='******'): # Set username username_elem = self.driver.find_element_by_name('username') username_elem.send_keys(username) # Set password password_elem = self.driver.find_element_by_name('password') password_elem.send_keys('admin') # Click login self.driver.find_element_by_css_selector('#login-form button').click() def oauth2_login(self, username='******'): from wstore.selenium_tests.tests import TESTING_PORT self.driver.get( self.live_server_url + '/oauth2/auth?response_type=code&client_id=test_app&redirect_uri=http://localhost:' + unicode(TESTING_PORT)) self.login(username) self.driver.find_element_by_class_name('btn-blue').click() time.sleep(1) # Get authorization code while self._server.call_received() < 1: pass code = self._server.get_path().split('=')[1] # Get access token opener = urllib2.build_opener() url = self.live_server_url + '/oauth2/token' data = 'client_id=test_app' data += '&client_secret=secret' data += '&grant_type=authorization_code' data += '&code=' + code data += '&redirect_uri=' + 'http://localhost:' + unicode(TESTING_PORT) headers = { 'content-type': 'application/form-url-encoded', } request = MethodRequest('POST', url, data, headers) response = opener.open(request) token = json.loads(response.read())['access_token'] return token def logout(self): self.driver.find_element_by_class_name( 'icon-double-angle-down').click() options = self.driver.find_elements_by_css_selector( '#settings-menu > li') options[-1].click() def tearDown(self): self.driver.quit() TestCase.tearDown(self) def back(self): self.driver.find_element_by_id('back').click() def view_all(self): self.driver.find_element_by_css_selector('#all').click() def search_keyword(self, keyword, id_='#text-search', btn='#search'): # Set search field search_elem = self.driver.find_element_by_css_selector(id_) search_elem.send_keys(keyword) # Click search button self.driver.find_element_by_css_selector(btn).click() def open_offering_details(self, offering_name): elements = self.driver.find_elements_by_class_name('menu-offering') for element in elements: if element.find_element_by_css_selector( 'h2').text == offering_name: element.click() break def _get_navs(self): submenu = self.driver.find_element_by_class_name('store-sub-menu') # Get first element return submenu.find_elements_by_css_selector('li') def click_first_cat(self): self.driver.find_element_by_id('menu-first-text').click() def click_second_cat(self): self.driver.find_element_by_id('menu-second-text').click() def click_third_cat(self): self.driver.find_element_by_id('menu-third-text').click() def click_first_nav(self): self._get_navs()[0].click() def click_second_nav(self): self._get_navs()[1].click() def _open_provider_option(self, option): self.driver.find_element_by_css_selector( '#provider-options a.btn').click() self.driver.find_element_by_id(option).click() def create_offering_menu(self): self._open_provider_option('create-app') def fill_basic_offering_info(self, offering_info): # Name and version self.driver.find_element_by_css_selector( '[name="app-name"]').send_keys(offering_info['name']) self.driver.find_element_by_css_selector( '[name="app-version"]').send_keys(offering_info['version']) # Select the notification URL option if not offering_info['notification']: self.driver.find_element_by_css_selector( 'input[type="radio"][value="none"]').click() elif offering_info['notification'] == 'default': self.driver.find_element_by_css_selector( 'input[type="radio"][value="default"]').click() else: self.driver.find_element_by_css_selector( 'input[type="radio"][value="new"]').click() self.driver.find_element_by_id('notify').send_keys( offering_info['notification']) # Add the logo logo_path = os.path.join( settings.BASEDIR, 'wstore/defaulttheme/static/assets/img/noimage.png') self.driver.find_element_by_id('img-logo').send_keys(logo_path) # Mark as open if needed if offering_info['open']: self.driver.find_element_by_id('open-offering').click() def fill_usdl_info(self, usdl_info): # Fill description field self.driver.find_element_by_id('description').send_keys( usdl_info['description']) self.driver.find_element_by_id('abstract').send_keys( usdl_info['abstract']) if 'legal' in usdl_info: self.driver.find_element_by_id('legal-title').send_keys( usdl_info['legal']['title']) self.driver.find_element_by_id('legal-text').send_keys( usdl_info['legal']['text']) def register_resource(self, resource_info): pass def click_tag(self, tag): tag_elems = self.driver.find_elements_by_class_name('tag') for te in tag_elems: if te.text == tag: te.click() break def select_plan(self, plan): element = WebDriverWait(self.driver, 5).until( EC.presence_of_element_located((By.ID, plan))) element.click() def accept_conditions(self): element = WebDriverWait(self.driver, 5).until( EC.presence_of_element_located((By.ID, "conditions-accepted"))) element.click() def fill_tax_address(self, tax): # Wait until the form is loaded element = WebDriverWait(self.driver, 5).until( EC.presence_of_element_located((By.ID, "street"))) element.send_keys(tax['street']) self.driver.find_element_by_id('postal').send_keys(tax['postal']) self.driver.find_element_by_id('city').send_keys(tax['city']) self.driver.find_element_by_id('country').send_keys(tax['country'])
class AJAXSchedulingModuleUITest(AJAXSchedulingModuleTestBase, LiveServerTestCase): def setUp(self, *args, **kwargs): super(AJAXSchedulingModuleUITest, self).setUp(*args, **kwargs) self.browser = WebDriver() self.update_interval = 4 self.filter_interval = 5 def tearDown(self): self.browser.quit() def loginAdminBrowser(self, uname, pword): uname_el_id = "user" pword_el_id = "pass" submit_el_id = "gologin" self.browser.get(self.live_server_url) e = WebDriverWait(self.browser, 10).until( lambda driver: self.browser.find_element_by_id(uname_el_id)) e.send_keys(uname) e = WebDriverWait(self.browser, 10).until( lambda driver: self.browser.find_element_by_id(pword_el_id)) e.send_keys(pword) e = WebDriverWait(self.browser, 60).until( lambda driver: self.browser.find_element_by_id(submit_el_id)) e.click() def loadAjax(self): self.loginAdminBrowser(self.admins[0].username, "password") url = self.live_server_url + self.ajax_url_base + "ajax_scheduling" self.browser.get(url) #wait for ajax to load before we go on time.sleep(30) def hasCSSClass(self, el, class_name): css_classes = el.get_attribute("class").split() return class_name in css_classes def isScheduled(self, section_id): elements = self.browser.find_elements_by_class_name('CLS_id_' + str(section_id)) for el in elements: self.failIf(self.hasCSSClass(el, "class-entry"), "Scheduled class appears in directory") self.failUnless( True in [self.hasCSSClass(el, "matrix-cell") for el in elements], "Scheduled class does not appear in matrix") def isInDirectory(self, section_id): elements = self.browser.find_elements_by_class_name('CLS_id_' + str(section_id)) self.failUnless( True in [self.hasCSSClass(el, "class-entry") for el in elements], "Class does not appear in directory.") def isNotInDirectory(self, section_id): elements = self.browser.find_elements_by_class_name('CLS_id_' + str(section_id)) for el in elements: self.failIf(self.hasCSSClass(el, "class-entry"), "Class appears in directory") def isNotScheduled(self, section_id): elements = self.browser.find_elements_by_class_name('CLS_id_' + str(section_id)) for el in elements: self.failIf(self.hasCSSClass(el, "matrix-cell"), "Unscheduled class appears in matrix") self.failUnless( True in [self.hasCSSClass(el, "class-entry") for el in elements], "Unscheduled class does not appear in directory.") #mostly exists as sanity on testing framework def testAjaxLoads(self): self.loadAjax() self.failUnless(self.browser.title == "ESP Scheduling Application", "Did not find AJAX: " + self.browser.title) def testUpdateScheduledClass(self): self.loadAjax() self.clearScheduleAvailability() (section, rooms, times) = self.scheduleClass() #section turns up in the browser time.sleep(self.update_interval) self.isScheduled(section.id) def testUpdateUnscheduledClass(self): self.loadAjax() self.clearScheduleAvailability() #schedule and unschedule a class (section, rooms, times) = self.scheduleClass() #wait for class to appear time.sleep(self.update_interval) self.unschedule_class(section.id) time.sleep(self.update_interval) self.isNotScheduled(section.id) def testUpdateScheduleUnscheduleClass(self): #if a class is scheduled and unscheduled in the same log, make sure it doesn't show up self.loadAjax() self.clearScheduleAvailability() #schedule and unschedule a class (section, rooms, times) = self.scheduleClass() self.unschedule_class(section.id) time.sleep(self.update_interval) self.isNotScheduled(section.id) # test basic drag-and-drop scheduling # this test does not seem to work correctly # # def testScheduleClass(self): # self.loadAjax() # self.clearScheduleAvailability() # (section, room, times) = self.getClassToSchedule() # source_el = self.browser.find_element_by_class_name('CLS_id_'+str(section.id)) # #any matrix cell will work # target_el = self.browser.find_element_by_class_name('matrix-cell') # ac = ActionChains(self.browser) # ac.drag_and_drop(source_el, target_el).perform() # time.sleep(5) # self.isScheduled(section.id) ##################################################################################### # # FILTERING TESTS # ##################################################################################### def filter_directory(self, label, value): # Expand the filtering accordiion self.browser.find_element_by_id("filtering_header").click() time.sleep(1.0) # Type into the desired filtering element f = self.browser.find_element_by_id("filter_" + label) f.send_keys(value + "\n") time.sleep(self.filter_interval) def testTitleFilter(self): self.loadAjax() section = self.program.sections()[0] self.filter_directory("Title", section.title()) for s in self.program.sections(): if (s == section): self.isInDirectory(s.id) else: self.isNotInDirectory(s.id) #TODO: none of the classes have teachers with names def testTeacherFilter(self): self.loadAjax() self.clearScheduleAvailability() teacher = self.teachers[0] self.filter_directory("Teacher", teacher.name()) for s in self.program.sections(): if teacher in s.teachers: self.isInDirectory(s.id) else: self.isNotInDirectory(s.id) def testFilterUnscheduledClass(self): self.loadAjax() self.clearScheduleAvailability() (section, rooms, times) = self.scheduleClass() self.browser.find_element_by_id("filtering_header").click() title_filter = self.browser.find_element_by_id("filter_ID") title_filter.send_keys( "xuoeahtuoeathsnuoeathns\n" ) #something I'm pretty sure won't appear in an id time.sleep(self.update_interval) self.unschedule_class(section.id) time.sleep(self.update_interval) self.isNotInDirectory(section.id) #TODO: change some class length so we see it not filtering some stuff def testLengthFilter(self): self.loadAjax() self.clearScheduleAvailability() self.filter_directory("Min-length", "1") self.filter_directory("Max-length", "1") for s in self.program.sections(): #all classes have length 2 in test data self.isNotInDirectory(s.id)