def log_in(driver: WebDriver): print("Logging in...") global PASSWORD, USERNAME username = USERNAME password = PASSWORD sign_in_div: WebElement = driver.find_element_by_class_name("nav-user-sign-in") # type: ignore sign_in_buttons: list[WebElement] = sign_in_div.find_elements_by_class_name("nav-header-button") for button in sign_in_buttons: if button.text == "Log In": driver.execute_script("arguments[0].click();", button) email_input = driver.find_element_by_id("rec-acct-sign-in-email-address") password_input = driver.find_element_by_id("rec-acct-sign-in-password") email_input.send_keys(username) # type: ignore password_input.send_keys(password) # type: ignore # Press Log In Button log_in_btn = driver.find_element_by_class_name("rec-acct-sign-in-btn") driver.execute_script("arguments[0].click();", log_in_btn) print("Logged in.") # Wait till login page is gone. WebDriverWait(driver, 10).until(EC.invisibility_of_element((By.ID, "signInModalHeading")))
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)
class LoginTest(StaticLiveServerTestCase): fixtures = ['user_testdata.json'] def setUp(self): self.selenium = WebDriver() self.selenium.implicitly_wait(10) self.selenium.get('%s%s' % (self.live_server_url, '/account/login/')) def tearDown(self): self.selenium.quit() def __get_page(self): class LoginPage(object): def __init__(self, selenium): self.selenium = selenium self.username = self.selenium.find_element_by_id('id_username') self.password = self.selenium.find_element_by_id('id_password') self.button = WebDriverWait(self.selenium, 10).until( EC.presence_of_element_located((By.TAG_NAME, "button"))) return LoginPage(self.selenium) @staticmethod def __send_keys_scrolling(input_element, keys): _ = input_element.location_once_scrolled_into_view time.sleep(1) input_element.send_keys(keys) def test_successful_login(self): page = self.__get_page() self.__send_keys_scrolling(page.username, 'test') self.__send_keys_scrolling(page.password, 'kossarnajafi1') page.button = WebDriverWait(self.selenium, 10).until( EC.presence_of_element_located((By.TAG_NAME, "button"))) page.button.click() WebDriverWait( self.selenium, 10).until(lambda driver: driver.find_element_by_tag_name('body')) def test_wrong_email_login(self): page = self.__get_page() self.__send_keys_scrolling(page.username, 'soroush1') self.__send_keys_scrolling(page.password, '123') page.button.click() _ = self.selenium.find_element_by_class_name('alert-danger') def test_wrong_password_login(self): page = self.__get_page() self.__send_keys_scrolling(page.username, 'soroush') self.__send_keys_scrolling(page.password, 'xxx') page.button.click() _ = self.selenium.find_element_by_class_name('alert-danger')
def increase_quantity_to_two(driver: WebDriver): print("Attempting to increase quantity to two!") # Open quantity selection quantity_open_button = "guest-counter" WebDriverWait(driver, 5).until( EC.presence_of_element_located((By.ID, quantity_open_button))) open_quantity_button = driver.find_element_by_id(quantity_open_button) driver.execute_script("arguments[0].click();", open_quantity_button) # Find the div that holds the increase quantity button div_holder_of_increase_button = "rec-guest-counter-row" WebDriverWait(driver, 5).until( EC.presence_of_element_located( (By.CLASS_NAME, div_holder_of_increase_button))) open_div_holder_of_increase_button: WebElement = driver.find_element_by_class_name( div_holder_of_increase_button) # Get the button we want from within this element plus_and_minus_button_class_name = "sarsa-button-subtle" buttons = open_div_holder_of_increase_button.find_elements_by_class_name( plus_and_minus_button_class_name) select_plus_button = buttons[1] driver.execute_script("arguments[0].click();", select_plus_button) # # Hit close and continue (probably not needed) # close_button_selector = "sarsa-button-link" # button = open_div_holder_of_increase_button.find_element_by_class_name(close_button_selector) # driver.execute_script("arguments[0].click();", button) print("Successful at increasing quantity to two!")
def _parse_caption_with_js(driver: WebDriver, language_code: str, page_id: str, img_id: str, icons: Set[str], debug_info: bool) -> Optional[str]: caption = None if img_id in _KNOWN_ICONS or img_id in icons: if debug_info: print('Skipping known icon', img_id) return caption url = 'https://{}.wikipedia.org/wiki/{}#/media/{}{}'.format( language_code, page_id, _get_translated_file_label(language_code), img_id) if debug_info: print('Downloading captions for', url) driver.get(url) sleep_time = 1 retry_count = 2 time.sleep(sleep_time) # reqired for JS to load content for k in range(retry_count): try: # TODO: there is a bug when trying to parse noviewer thum. Driver returns caption from previous page # Currently not reproducible when invalidate_cache=False and caption already exists caption = driver.find_element_by_class_name("mw-mmv-title").text if caption == "": caption = None raise Exception else: break except: time.sleep(sleep_time) # reqired for JS to load content print("RETRY", k, " ||| ", img_id) # closing the tab so that we won't read it again if next page fails to load default_url = 'https://www.wikipedia.org/' driver.get(default_url) return caption
class Selenium_old_lwt(StaticLiveServerTestCase): ''' it tests with the fixture from "old_lwt' (the non opensource version)''' fixtures = ['lwt/fixtures/old_lwt.json'] def setUp(self): self.pwd = '12345' self.user_1 = User.objects.get(username='******') self.language_1 = Languages.objects.get(name='Italian') Settings_currentlang_idFactory(owner=self.user_1, stvalue=self.language_1.id) super(Selenium_old_lwt, self).setUpClass() self.selenium = WebDriver() self.selenium.get('{}/accounts/login/'.format(self.live_server_url)) self.selenium.implicitly_wait(10) login = self.selenium.find_element_by_name('login') login.send_keys(self.user_1.username) pw = self.selenium.find_element_by_name('password') pw.send_keys(self.pwd) self.selenium.find_element_by_class_name('primaryAction').click() def test_loggout(self): self.selenium.get(self.live_server_url) # return 'localhost:8000 self.selenium.find_element_by_name('logout').click() self.selenium.get('{}/accounts/logout/'.format(self.live_server_url)) self.selenium.find_element_by_xpath('//button[@type="submit"]').click() def tearDown(self): # self.selenium.quit() super(Selenium_old_lwt, self).tearDown() def test_go_to_homepage(self): self.selenium.get(self.live_server_url) # return 'localhost:8000 def test_go_to_text_list(self): self.selenium.get('{}/text_list/'.format(self.live_server_url)) def test_go_to_text_read(self): self.selenium.get('{}/text_read/{}'.format(self.live_server_url, self.text1.id))
def add_campsite_to_cart( driver: WebDriver, rows: list[WebElement], desired_date: str, prefer_sites=set(range(107, 125)), reserved_count: int = 0, ): global curr_site, url_of_site for row in rows: campsite: list[WebElement] = row.find_elements_by_class_name("rec-availability-item") assert len(campsite) == 1 campsite_num = campsite[0].text matched: list[WebElement] = row.find_elements_by_class_name("rec-availability-date") for element in matched: aria_label: str = element.get_attribute("aria-label") date_from_aria = aria_label.split(" - ")[0] availability = element.text # print( # f"Campsite {campsite_num} at Date {date_from_aria} is currently: {'available' if availability not in ['R', 'X'] else 'reserved'}" # ) parsed_date = parse_dates(desired_date) if date_from_aria != parsed_date: continue if availability not in ["R", "X"]: driver.execute_script("arguments[0].click();", element) print(f"Pressed Button on {desired_date} for campsite: {campsite_num}") add_to_cart = driver.find_element_by_class_name("availability-page-book-now-button-tracker") driver.execute_script("arguments[0].click();", add_to_cart) print(f"Pressed add to cart for campsite {campsite_num} at date {desired_date}") send_discord_notification( f"Campsite {campsite_num} available at date: {parsed_date}!", curr_site, url_of_site ) # for _ in range(5): # playsound('beep-01a.mp3') time.sleep(2) check_availability_and_reserve(driver, url_of_site, reserved_count + 1) return print("No available sites. Nothing has been added to cart.")
def navigate_to_date(driver: WebDriver, desired_date: str, date_picker_element, id=True): print(f"Navigating to intended date. {desired_date}") if id: select_date: WebElement = driver.find_element_by_id(date_picker_element) # type: ignore else: select_date: WebElement = driver.find_element_by_class_name(date_picker_element) # type: ignore select_date.click() select_date.send_keys(Keys.CONTROL, "a") select_date.send_keys(desired_date) print(f"Navigated to date: {desired_date}")
def test(self): # Setup driver = WebDriver() db = {'plane': [], 'crew': [], 'flight': []} for i in range(5): a = Airplane(registerNumber=i + 10000, places=20) a.save() db['plane'].append(a) b = AirplaneCrew(captainsName="X{}".format(i + 10000), captainsSurname="Z{}".format(i + 1)) b.save() db['crew'].append(b) db['flight'].append(Flight.objects.create(startAirport="A", endAirport="B", airplane=a, crew=b, startTime=self.date, endTime=self.date + timedelta(hours=4))) User.objects.create_user(username='******', password='******') # Log in driver.get("{}/".format(self.live_server_url)) driver.find_element_by_id("login_dropdown").click() driver.find_element_by_id("login_username").send_keys("d") driver.find_element_by_id("login_password").send_keys("d") driver.find_element_by_id("login_button").click() # Buying ticket driver.get("{}/flight/1".format(self.live_server_url)) driver.find_element_by_id("name").send_keys("A") driver.find_element_by_id("surname").send_keys("B") driver.find_element_by_id("buy_ticket_button").click() # Check if bought correctly counter = 0 expected_results = ["A", "B", "1"] for td in driver.find_elements_by_tag_name("td"): self.assertEqual(td.text, expected_results[counter]) counter += 1 # Assigning incorrect crews driver.get("{}/static/crews.html".format(self.live_server_url)) driver.find_element_by_id("change_crew_assignment").click() Select(driver.find_element_by_id("flight_select")).select_by_index(1) driver.find_element_by_id("change_crew_assignment").click() try: WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "error_alert")) ) finally: error_message = "Error - couldn't assign crew! You have to be logged in!" self.assertEqual(driver.find_element_by_class_name("alert").text, error_message) driver.close()
def get_balance(browser: WebDriver, url: str, card_number: str) -> str: input_field_id = 'ean' balance_field_class = 'history_header_amount' browser.get(url) time.sleep(0.5) # num_form = WebDriverWait(browser, 5).until( # expected_conditions.presence_of_element_located( # (By.ID, input_field_id) # ) # ) num_form = browser.find_element_by_name(input_field_id) num_form.send_keys(card_number) num_form.submit() try: balance_field = WebDriverWait(browser, 5).until( expected_conditions.presence_of_element_located( (By.CLASS_NAME, balance_field_class))) balance = balance_field.text except TimeoutException: error = browser.find_element_by_class_name( 'form-messages_message__error') errors = [ 'Проверьте корректность введенных данных', 'Введите корректный номер штрих-кода карты', ] if error.text in errors: balance = 'Карта не найдена' else: balance = error.text finally: browser.close() return balance
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 RegistrationSeleniumTestCase(LiveServerTestCase): """ """ fixtures = ['test_data.json', 'test_schedule.json'] @classmethod def setUpClass(self): """ Start Selenium. """ # start Firefox websdriver self.selenium = WebDriver() # call super setup method super(RegistrationSeleniumTestCase, self).setUpClass() def setUp(self): # change the language to english for language-based assertations self.branch = Branch.objects.all()[0] self.branch.language = 'en' self.branch.save() # approve a scheduled class so it appears on the website self.schedule = Schedule.objects.filter(course__branch=self.branch)[0] self.schedule.course_status = 3 self.schedule.save() self.timeout = 2 def test_registration_toggle_button(self): """ Tests that clicking the title of a scheduled class on the website expands the div. """ # construct server url schedule_list_url = reverse('schedule-list', kwargs={ 'branch_slug' : self.branch.slug }) live_url = "%s%s" % (self.live_server_url, schedule_list_url) # load page self.selenium.get(live_url) # find a scheduled class title and click on it toggle_button = self.selenium.find_element_by_class_name('toggle') self.assertTrue(toggle_button.is_displayed()) toggle_button.click() def test_registration_join_button(self): """ Tests that clicking on the join button sends an ajax request. """ # construct server url schedule_register_url = reverse('schedule-register', kwargs={ 'branch_slug' : self.branch.slug, 'schedule_slug' : self.schedule.slug }) live_url = "%s%s" % (self.live_server_url, schedule_register_url) # load page self.selenium.get(live_url) # find a scheduled class join button join_button = self.selenium.find_element_by_class_name('join') self.assertTrue(join_button.is_displayed()) join_button.click() def tearDown(self): """ Delete Branch files. """ # delete branches' files for branch in Branch.objects.all(): branch.delete_files() @classmethod def tearDownClass(self): # stop selenium self.selenium.quit() # call super teardown method super(RegistrationSeleniumTestCase, self).tearDownClass()
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()
class SeleniumTests(LiveServerTestCase): """Base class for all Selenium test classes to inherit from""" @classmethod def setUpClass(self): self.selenium = WebDriver() self.selenium.implicitly_wait(3) super(SeleniumTests, self).setUpClass() @classmethod def tearDownClass(self): self.selenium.quit() super(SeleniumTests, self).tearDownClass() def setUp(self): # Create a test user and admin account self.user_name = 'SeleniumTestUser' self.user_pass = '******' if User.objects.filter(username=self.user_name).count() == 0: User.objects.create_user(self.user_name, '', self.user_pass).save() self.admin_name = 'SeleniumAdministrativeUser' self.admin_pass = '******' if User.objects.filter(username=self.admin_name).count() == 0: User.objects.create_superuser(self.admin_name, '', self.admin_pass).save() def tearDown(self): self.selenium.delete_all_cookies() def link_text_exists(self, link_text): try: self.selenium.find_element_by_link_text(link_text) except NoSuchElementException: return False return True def xpath_exists(self, xpath): try: self.selenium.find_element_by_xpath(xpath) except NoSuchElementException: return False return True def element_with_selector_exists(self, selector): try: self.selenium.find_element_by_css_selector(selector) except NoSuchElementException: return False return True def text_exists(self, text, xpath="//body"): try: element = self.selenium.find_element_by_xpath(xpath) except NoSuchElementException: return False if text in element.text: return True else: return False def login(self, username, password): # Go to the login page and try logging in with the provided credentials self.selenium.get('%s' % self.live_server_url) self.selenium.find_element_by_link_text('Log in').click() username_input = self.selenium.find_element_by_name('username') username_input.send_keys(username) password_input = self.selenium.find_element_by_name('password') password_input.send_keys(password) self.selenium.find_element_by_class_name('submit').click() def create_items_and_requests(self, x): # Creates x number of items and requests for i in xrange(x): self.item = G(Item) self.request = G(Request, item=self.item) def create_generic_item(self): # Quick helper in the absence of fixtures item = G(Item, local_num=9999, part_class='parts class', location='cart 8', description='test item', cfi='never', company='A Business', part_num='X9X9', serial_num='8A', asset_num='sample_num', notes='Testing') return item
class FlightSeleniumTestCase(StaticLiveServerTestCase): fixtures = ['flights_tests.json'] def setUp(self): user = User.objects.create_user( username='******', email='*****@*****.**', password='******', ) user.first_name = 'Bruce' user.last_name = 'Wayne' user.save() flight = Flight(plane=Plane.objects.get(pk='Batman'), start_date=datetime(2020, 1, 1, 1, 0, 0, tzinfo=pytz.UTC), end_date=datetime(2020, 1, 1, 6, 0, 0, tzinfo=pytz.UTC), src_airport=Airport.objects.get(pk='WAW'), dest_airport=Airport.objects.get(pk='TXL')) flight.save() flight = Flight(plane=Plane.objects.get(pk='Superman'), start_date=datetime(2020, 1, 1, 1, 30, 0, tzinfo=pytz.UTC), end_date=datetime(2020, 1, 1, 6, 30, 0, tzinfo=pytz.UTC), src_airport=Airport.objects.get(pk='TXL'), dest_airport=Airport.objects.get(pk='WAW')) flight.save() self.selenium = WebDriver() super(FlightSeleniumTestCase, self).setUp() def tearDown(self): self.selenium.quit() super(FlightSeleniumTestCase, self).tearDown() def test_add_passenger(self): self.selenium.get(self.live_server_url) # login first self.selenium.find_element_by_name('username').send_keys('user') self.selenium.find_element_by_name('password').send_keys('pass') self.selenium.find_element_by_css_selector( 'input[type="submit"]').click() alert = self.selenium.find_element_by_class_name('alert') self.assertIn('alert-success', alert.get_attribute('class')) # move to flights menu and select first one self.selenium.find_element_by_link_text('Flights').click() self.selenium.find_element_by_link_text('1').click() # click 'Buy ticket' button and check if user shows up on list self.selenium.find_element_by_css_selector( 'input[value="Buy ticket"]').click() self.selenium.find_element_by_xpath( '//*[@id="headingOne"]/button').click() name_td = self.selenium.find_element_by_xpath( '//*[@id="collapseOne"]/div/table/tbody/tr/td[2]') self.assertEquals('Bruce Wayne', name_td.text) def test_crew_add(self): crew = Crew(captain_firstname='Bruce', captain_lastname='Wayne') crew.save() cm = CrewMember(firstname='Clark', lastname='Kent') cm.save() crew.members.add(cm) crew.save() action_chains = ActionChains(self.selenium) self.selenium.get(self.live_server_url) # login first self.selenium.find_element_by_link_text('Crews').click() self.selenium.find_element_by_name('username').send_keys('user') self.selenium.find_element_by_name('password').send_keys('pass') self.selenium.find_element_by_xpath( '//*[@id="login-form"]/input[3]').click() WebDriverWait( self.selenium, 3).until(lambda driver: driver.find_element_by_class_name('alert')) alert = self.selenium.find_element_by_class_name('alert') self.assertIn('alert-success', alert.get_attribute('class')) # setup date of flights self.selenium.find_element_by_id('choose-date').send_keys('2020-01-01') WebDriverWait(self.selenium, 3).until(lambda driver: driver.find_element_by_xpath( '//*[@id="flights"]/tr[1]')) # double click on first flight row = self.selenium.find_element_by_xpath('//*[@id="flights"]/tr[1]') action_chains.double_click(row).perform() # choose first crew WebDriverWait(self.selenium, 3).until(lambda driver: driver.find_element_by_xpath( '//*[@id="select-crew"]/option[2]')) self.selenium.find_element_by_xpath( '//*[@id="select-crew"]/option[2]').click() # send 'Change crew' and wait for change query to end self.selenium.find_element_by_xpath( '//*[@id="crew-form"]/div[7]/input').click() WebDriverWait( self.selenium, 3).until(lambda driver: driver.find_element_by_class_name('alert')) alert = self.selenium.find_element_by_class_name('alert') self.assertIn('alert-success', alert.get_attribute('class')) # refresh page and check if crew changed self.selenium.refresh() action_chains = ActionChains(self.selenium) self.selenium.find_element_by_id('choose-date').send_keys('2020-01-01') WebDriverWait(self.selenium, 3).until(lambda driver: driver.find_element_by_xpath( '//*[@id="flights"]/tr[1]')) new_crew = self.selenium.find_element_by_xpath( '//*[@id="flights"]/tr[1]/td[6]/span[@class="captain"]') self.assertEquals('Bruce Wayne', new_crew.text) # double click on second flight row2 = self.selenium.find_element_by_xpath('//*[@id="flights"]/tr[2]') action_chains.double_click(row2).perform() # choose first crew WebDriverWait(self.selenium, 3).until(lambda driver: driver.find_element_by_xpath( '//*[@id="select-crew"]/option[2]')) self.selenium.find_element_by_xpath( '//*[@id="select-crew"]/option[2]').click() # send 'Change crew' and wait for change query to end self.selenium.find_element_by_xpath( '//*[@id="crew-form"]/div[7]/input').click() WebDriverWait( self.selenium, 3).until(lambda driver: driver.find_element_by_class_name('alert')) alert = self.selenium.find_element_by_class_name('alert') self.assertIn('alert-danger', alert.get_attribute('class')) # check if crews didn't change self.selenium.refresh() self.selenium.find_element_by_id('choose-date').send_keys('2020-01-01') WebDriverWait(self.selenium, 3).until(lambda driver: driver.find_element_by_xpath( '//*[@id="flights"]/tr[1]')) crew1 = self.selenium.find_element_by_xpath( '//*[@id="flights"]/tr[1]/td[6]/span[@class="captain"]') crew2 = self.selenium.find_element_by_xpath( '//*[@id="flights"]/tr[2]/td[6]/span[@class="captain"]') self.assertEquals('Bruce Wayne', crew1.text) self.assertEquals('None', crew2.text)
class EntrySeleleniumTests(StaticLiveServerTestCase): """Selenium tests for the entry form""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not settings.DEBUG: settings.DEBUG = True def setUp(self): """Handles login and things""" call_command('flush', interactive=False, verbosity=0) # Clears db call_command('loaddata', 'groups', commit=False, verbosity=0) call_command('loaddata', 'school', commit=False, verbosity=0) call_command('loaddata', 'permissions', commit=False, verbosity=0) call_command('loaddata', 'auth_users', commit=False, verbosity=0) call_command('loaddata', 'student', commit=False, verbosity=0) call_command('loaddata', 'advisor', commit=False, verbosity=0) call_command('loaddata', 'coordinator', commit=False, verbosity=0) call_command('loaddata', 'activityoptions', commit=False, verbosity=0) call_command('loaddata', 'learningobjectiveoptions', commit=False, verbosity=0) call_command('loaddata', 'sample_entries', commit=False, verbosity=0) self.selenium = WebDriver() self.selenium.set_window_size(1024, 800) self.selenium.get('{0}/{1}'.format(self.live_server_url, '')) self.selenium.find_element_by_xpath( '//*[@id="djHideToolBarButton"]').click() self.selenium.implicitly_wait(10) self.selenium.find_element_by_link_text('Login').click() # Click on the student button in the gateway self.selenium.find_element_by_xpath( '/html/body/center/md-content/div/div/div[1]/a').click() self.selenium\ .find_element_by_xpath("//img[@src='/static/journal/activities/img" "/journal_sign.png']") super() def tearDown(self): self.selenium.quit() super() def test_text_entry(self): """Test to ensure that a student can add a text entry""" # Click on the first activity box: Walking around the block self.selenium.find_element_by_xpath( '/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click() self.selenium.find_element_by_link_text('Add an entry').click() # The following has 2 matching: Just walking and Adding entry...block header_text = self.selenium.find_elements_by_tag_name('h3')[1].text self.assertTrue( 'Adding entry for Walking around the block!' in header_text) # Switching to iframe focus self.selenium.switch_to_frame( self.selenium.find_element_by_id('id_entry_iframe')) # Insert text entry = 'I think I will bring my cat out next time.' self.selenium.find_element_by_class_name('note-editable')\ .send_keys(entry) # Switch back out of the iframe. self.selenium.switch_to_default_content() # Click on the submit button self.selenium.find_element_by_class_name('btn-success').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') # Ensure that entry exists as the first box on the page. box_text = self.selenium.find_element_by_xpath( '/html/body/div[1]/div[2]/div[2]/div[1]/a/div').text self.assertTrue(entry in box_text) def test_image_entry(self): """Test to ensure that a student can add an image entry""" # Click on the first activity box: Walking around the block self.selenium.find_element_by_xpath( '/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click() self.selenium.find_element_by_link_text('Add an entry').click() # The following has 2 matching: Just walking and Adding entry...block header_text = self.selenium.find_elements_by_tag_name('h3')[1].text self.assertTrue( 'Adding entry for Walking around the block!' in header_text) # Switching to iframe focus self.selenium.switch_to_frame( self.selenium.find_element_by_id('id_entry_iframe')) self.selenium.find_element_by_xpath( '/html/body/div[2]/div[5]/div[3]/button[2]').click() entry = 'http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/input')\ .send_keys(entry) # click on the inset image button self.selenium.find_element_by_xpath( '/html/body/div[2]/div[2]/div[1]/div/div/div[3]/button').click() # Switch back out of the iframe. self.selenium.switch_to_default_content() # Click on the submit button self.selenium.implicitly_wait(10) self.selenium.find_element_by_class_name('btn-success').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') # Ensure that entry exists on the page. self.selenium.find_element_by_xpath( "//img[@src='http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg']" ) def test_video_entry(self): """Test to ensure that a student can add a video entry""" # Click on the first activity box: Walking around the block self.selenium.find_element_by_xpath( '/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click() self.selenium.find_element_by_link_text('Add an entry').click() # The following has 2 matching: Just walking and Adding entry...block header_text = self.selenium.find_elements_by_tag_name('h3')[1].text self.assertTrue( 'Adding entry for Walking around the block!' in header_text) # Switching to iframe focus self.selenium.switch_to_frame( self.selenium.find_element_by_id('id_entry_iframe')) # Insert video self.selenium.find_element_by_xpath( '/html/body/div[2]/div[5]/div[3]/button[3]').click() entry = 'https://www.youtube.com/watch?v=Rk_bV0RJRhs&index=20&list=PLJU_WCB1rA2SFwFy3lEvY_NH23ql1-Cgi' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[2]/div/input')\ .send_keys(entry) # click on the insert video button self.selenium.find_element_by_xpath( '/html/body/div[2]/div[2]/div[4]/div/div/div[3]/button').click() # Switch back out of the iframe. self.selenium.switch_to_default_content() # Click on the submit button self.selenium.implicitly_wait(10) self.selenium.find_element_by_class_name('btn-success').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') self.selenium.find_element_by_xpath( '//iframe[@src="//www.youtube.com/embed/Rk_bV0RJRhs"]') def test_image_text_entry(self): """Test to ensure that a student can add image+text entries""" # Click on the first activity box: Walking around the block self.selenium.find_element_by_xpath( '/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click() self.selenium.find_element_by_link_text('Add an entry').click() # The following has 2 matching: Just walking and Adding entry...block header_text = self.selenium.find_elements_by_tag_name('h3')[1].text self.assertTrue( 'Adding entry for Walking around the block!' in header_text) # Switching to iframe focus self.selenium.switch_to_frame( self.selenium.find_element_by_id('id_entry_iframe')) # Insert text entry = 'I think I will bring my cat out next time with a flower.' self.selenium.find_element_by_class_name('note-editable')\ .send_keys(entry) # Insert the image self.selenium.find_element_by_xpath( '/html/body/div[2]/div[5]/div[3]/button[2]').click() image_entry = 'http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/input')\ .send_keys(image_entry) # Click on the insert image button self.selenium.find_element_by_xpath( '/html/body/div[2]/div[2]/div[1]/div/div/div[3]/button').click() # Switch back out of the iframe. self.selenium.switch_to_default_content() # Click on the submit button self.selenium.implicitly_wait(10) self.selenium.find_element_by_class_name('btn-success').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') # Ensure the text is on the entries page box_text = self.selenium.find_element_by_xpath( '/html/body/div[1]/div[2]/div[2]/div[1]/a/div').text self.assertTrue(entry in box_text) # Ensure the image is on the entries page self.selenium.find_element_by_xpath( "//img[@src='http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg']" ) def test_video_text_entry(self): """Test to ensure that a student can add an text+video entry""" # Click on the first activity box: Walking around the block self.selenium.find_element_by_xpath( '/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click() self.selenium.find_element_by_link_text('Add an entry').click() # The following has 2 matching: Just walking and Adding entry...block header_text = self.selenium.find_elements_by_tag_name('h3')[1].text self.assertTrue( 'Adding entry for Walking around the block!' in header_text) # Switching to iframe focus self.selenium.switch_to_frame( self.selenium.find_element_by_id('id_entry_iframe')) # Insert text entry = 'I think I will bring my cat out next time.' self.selenium.find_element_by_class_name('note-editable')\ .send_keys(entry) # Insert video self.selenium.find_element_by_xpath( '/html/body/div[2]/div[5]/div[3]/button[3]').click() video_entry = 'https://www.youtube.com/watch?v=Rk_bV0RJRhs&index=20&list=PLJU_WCB1rA2SFwFy3lEvY_NH23ql1-Cgi' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[2]/div/input')\ .send_keys(video_entry) # Click on the insert video button self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[3]/button')\ .click() # Switch back out of the iframe. self.selenium.switch_to_default_content() # Click on the submit button self.selenium.find_element_by_class_name('btn-success').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') # Ensure that entry exists as the first box on the page. box_text = self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[1]/a/div')\ .text self.assertTrue(entry in box_text) self.selenium.find_element_by_xpath( '//iframe[@src="//www.youtube.com/embed/Rk_bV0RJRhs"]') def test_text_image_video_entry(self): """Test to ensure that a student can add an text+image+video entry""" # Click on the first activity box: Walking around the block self.selenium.find_element_by_xpath( '/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click() self.selenium.find_element_by_link_text('Add an entry').click() # The following has 2 matching: Just walking and Adding entry...block header_text = self.selenium.find_elements_by_tag_name('h3')[1].text self.assertTrue( 'Adding entry for Walking around the block!' in header_text) # Switching to iframe focus self.selenium.switch_to_frame( self.selenium.find_element_by_id('id_entry_iframe')) # Insert text text_entry = 'I think I will bring my cat out next time.' self.selenium.find_element_by_class_name('note-editable')\ .send_keys(text_entry) # Insert image button self.selenium.find_element_by_xpath( '/html/body/div[2]/div[5]/div[3]/button[2]').click() image_entry = 'http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/input')\ .send_keys(image_entry) # Click on the inset image button self.selenium.find_element_by_xpath( '/html/body/div[2]/div[2]/div[1]/div/div/div[3]/button').click() # Insert video button self.selenium.find_element_by_xpath( '/html/body/div[2]/div[5]/div[3]/button[3]').click() video_entry = 'https://www.youtube.com/watch?v=Rk_bV0RJRhs&index=20&list=PLJU_WCB1rA2SFwFy3lEvY_NH23ql1-Cgi' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[2]/div/input')\ .send_keys(video_entry) # Click on the insert video button self.selenium.find_element_by_xpath( '/html/body/div[2]/div[2]/div[4]/div/div/div[3]/button').click() # Switch back out of the iframe. self.selenium.switch_to_default_content() # Click on the submit button self.selenium.find_element_by_class_name('btn-success').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') # Ensure that entry exists as the first box on the page. box_text = self.selenium.find_element_by_xpath( '/html/body/div[1]/div[2]/div[2]/div[1]/a/div').text self.assertTrue(text_entry in box_text) self.selenium.find_element_by_xpath( "//img[@src='http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg']" ) self.selenium.find_element_by_xpath( '//iframe[@src="//www.youtube.com/embed/Rk_bV0RJRhs"]') def test_delete_entry(self): """Test to ensure that a student can delete an entry""" # Click on the first activity box: Walking around the block self.selenium.find_element_by_xpath( '/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click() self.selenium.find_element_by_link_text('Add an entry').click() # The following has 2 matching: Just walking and Adding entry...block header_text = self.selenium.find_elements_by_tag_name('h3')[1].text self.assertTrue( 'Adding entry for Walking around the block!' in header_text) # Switching to iframe focus self.selenium.switch_to_frame( self.selenium.find_element_by_id('id_entry_iframe')) # Insert text text_entry = 'I think I will bring my cat out next time.' self.selenium.find_element_by_class_name('note-editable')\ .send_keys(text_entry) # Insert image button self.selenium.find_element_by_xpath( '/html/body/div[2]/div[5]/div[3]/button[2]').click() image_entry = 'http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/input')\ .send_keys(image_entry) # Click on the inset image button self.selenium.find_element_by_xpath( '/html/body/div[2]/div[2]/div[1]/div/div/div[3]/button').click() # Insert video button self.selenium.find_element_by_xpath( '/html/body/div[2]/div[5]/div[3]/button[3]').click() video_entry = 'https://www.youtube.com/watch?v=Rk_bV0RJRhs&index=20&list=PLJU_WCB1rA2SFwFy3lEvY_NH23ql1-Cgi' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[2]/div/input')\ .send_keys(video_entry) # Click on the insert video button self.selenium.find_element_by_xpath( '/html/body/div[2]/div[2]/div[4]/div/div/div[3]/button').click() # Switch back out of the iframe. self.selenium.switch_to_default_content() # Click on the submit button self.selenium.find_element_by_class_name('btn-success').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') # Ensure that entry exists as the first box on the page. box_text = self.selenium.find_element_by_xpath( '/html/body/div[1]/div[2]/div[2]/div[1]/a/div').text self.assertTrue(text_entry in box_text) self.selenium.find_element_by_xpath( "//img[@src='http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg']" ) self.selenium.find_element_by_xpath( '//iframe[@src="//www.youtube.com/embed/Rk_bV0RJRhs"]') # Click on the entry that was created self.selenium.find_element_by_xpath( '/html/body/div[1]/div[2]/div[2]/div[1]/a').click() # Click on the delete button self.selenium.find_element_by_class_name('btn-danger').click() self.selenium.find_element_by_xpath( '//*[@id="delete-modal"]/div/div/div[3]/a').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') # Ensure that the entry created is no longer on the entries page main_text = self.selenium.find_element_by_class_name('main').text # Check for text self.assertFalse(text_entry in main_text) # Check for image image_entry_xpath = "//img[@src='http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg']" self.assertFalse(image_entry_xpath in main_text) # Check for video video_entry_xpath = '//iframe[@src="//www.youtube.com/embed/Rk_bV0RJRhs"]' self.assertFalse(video_entry_xpath in main_text)
class EntrySeleleniumTests(StaticLiveServerTestCase): """Selenium tests for the entry form""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not settings.DEBUG: settings.DEBUG = True def setUp(self): """Handles login and things""" call_command('flush', interactive=False, verbosity=0) # Clears db call_command('loaddata', 'groups', commit=False, verbosity=0) call_command('loaddata', 'school', commit=False, verbosity=0) call_command('loaddata', 'permissions', commit=False, verbosity=0) call_command('loaddata', 'auth_users', commit=False, verbosity=0) call_command('loaddata', 'student', commit=False, verbosity=0) call_command('loaddata', 'advisor', commit=False, verbosity=0) call_command('loaddata', 'coordinator', commit=False, verbosity=0) call_command('loaddata', 'activityoptions', commit=False, verbosity=0) call_command('loaddata', 'learningobjectiveoptions', commit=False, verbosity=0) call_command('loaddata', 'sample_entries', commit=False, verbosity=0) self.selenium = WebDriver() self.selenium.set_window_size(1024, 800) self.selenium.get('{0}/{1}'.format(self.live_server_url, '')) self.selenium.find_element_by_xpath('//*[@id="djHideToolBarButton"]').click() self.selenium.implicitly_wait(10) self.selenium.find_element_by_link_text('Login').click() # Click on the student button in the gateway self.selenium.find_element_by_xpath('/html/body/center/md-content/div/div/div[1]/a').click() self.selenium\ .find_element_by_xpath("//img[@src='/static/journal/activities/img" "/journal_sign.png']") super() def tearDown(self): self.selenium.quit() super() def test_text_entry(self): """Test to ensure that a student can add a text entry""" # Click on the first activity box: Walking around the block self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click() self.selenium.find_element_by_link_text('Add an entry').click() # The following has 2 matching: Just walking and Adding entry...block header_text = self.selenium.find_elements_by_tag_name('h3')[1].text self.assertTrue('Adding entry for Walking around the block!' in header_text) # Switching to iframe focus self.selenium.switch_to_frame(self.selenium.find_element_by_id('id_entry_iframe')) # Insert text entry = 'I think I will bring my cat out next time.' self.selenium.find_element_by_class_name('note-editable')\ .send_keys(entry) # Switch back out of the iframe. self.selenium.switch_to_default_content() # Click on the submit button self.selenium.find_element_by_class_name('btn-success').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') # Ensure that entry exists as the first box on the page. box_text = self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[1]/a/div').text self.assertTrue(entry in box_text) def test_image_entry(self): """Test to ensure that a student can add an image entry""" # Click on the first activity box: Walking around the block self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click() self.selenium.find_element_by_link_text('Add an entry').click() # The following has 2 matching: Just walking and Adding entry...block header_text = self.selenium.find_elements_by_tag_name('h3')[1].text self.assertTrue('Adding entry for Walking around the block!' in header_text) # Switching to iframe focus self.selenium.switch_to_frame(self.selenium.find_element_by_id('id_entry_iframe')) self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[2]').click() entry = 'http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/input')\ .send_keys(entry) # click on the inset image button self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[3]/button').click() # Switch back out of the iframe. self.selenium.switch_to_default_content() # Click on the submit button self.selenium.implicitly_wait(10) self.selenium.find_element_by_class_name('btn-success').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') # Ensure that entry exists on the page. self.selenium.find_element_by_xpath("//img[@src='http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg']") def test_video_entry(self): """Test to ensure that a student can add a video entry""" # Click on the first activity box: Walking around the block self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click() self.selenium.find_element_by_link_text('Add an entry').click() # The following has 2 matching: Just walking and Adding entry...block header_text = self.selenium.find_elements_by_tag_name('h3')[1].text self.assertTrue('Adding entry for Walking around the block!' in header_text) # Switching to iframe focus self.selenium.switch_to_frame(self.selenium.find_element_by_id('id_entry_iframe')) # Insert video self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[3]').click() entry = 'https://www.youtube.com/watch?v=Rk_bV0RJRhs&index=20&list=PLJU_WCB1rA2SFwFy3lEvY_NH23ql1-Cgi' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[2]/div/input')\ .send_keys(entry) # click on the insert video button self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[3]/button').click() # Switch back out of the iframe. self.selenium.switch_to_default_content() # Click on the submit button self.selenium.implicitly_wait(10) self.selenium.find_element_by_class_name('btn-success').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') self.selenium.find_element_by_xpath('//iframe[@src="//www.youtube.com/embed/Rk_bV0RJRhs"]') def test_image_text_entry(self): """Test to ensure that a student can add image+text entries""" # Click on the first activity box: Walking around the block self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click() self.selenium.find_element_by_link_text('Add an entry').click() # The following has 2 matching: Just walking and Adding entry...block header_text = self.selenium.find_elements_by_tag_name('h3')[1].text self.assertTrue('Adding entry for Walking around the block!' in header_text) # Switching to iframe focus self.selenium.switch_to_frame(self.selenium.find_element_by_id('id_entry_iframe')) # Insert text entry = 'I think I will bring my cat out next time with a flower.' self.selenium.find_element_by_class_name('note-editable')\ .send_keys(entry) # Insert the image self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[2]').click() image_entry = 'http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/input')\ .send_keys(image_entry) # Click on the insert image button self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[3]/button').click() # Switch back out of the iframe. self.selenium.switch_to_default_content() # Click on the submit button self.selenium.implicitly_wait(10) self.selenium.find_element_by_class_name('btn-success').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') # Ensure the text is on the entries page box_text = self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[1]/a/div').text self.assertTrue(entry in box_text) # Ensure the image is on the entries page self.selenium.find_element_by_xpath("//img[@src='http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg']") def test_video_text_entry(self): """Test to ensure that a student can add an text+video entry""" # Click on the first activity box: Walking around the block self.selenium.find_element_by_xpath( '/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click() self.selenium.find_element_by_link_text('Add an entry').click() # The following has 2 matching: Just walking and Adding entry...block header_text = self.selenium.find_elements_by_tag_name('h3')[1].text self.assertTrue('Adding entry for Walking around the block!' in header_text) # Switching to iframe focus self.selenium.switch_to_frame(self.selenium.find_element_by_id('id_entry_iframe')) # Insert text entry = 'I think I will bring my cat out next time.' self.selenium.find_element_by_class_name('note-editable')\ .send_keys(entry) # Insert video self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[3]').click() video_entry = 'https://www.youtube.com/watch?v=Rk_bV0RJRhs&index=20&list=PLJU_WCB1rA2SFwFy3lEvY_NH23ql1-Cgi' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[2]/div/input')\ .send_keys(video_entry) # Click on the insert video button self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[3]/button')\ .click() # Switch back out of the iframe. self.selenium.switch_to_default_content() # Click on the submit button self.selenium.find_element_by_class_name('btn-success').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') # Ensure that entry exists as the first box on the page. box_text = self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[1]/a/div')\ .text self.assertTrue(entry in box_text) self.selenium.find_element_by_xpath('//iframe[@src="//www.youtube.com/embed/Rk_bV0RJRhs"]') def test_text_image_video_entry(self): """Test to ensure that a student can add an text+image+video entry""" # Click on the first activity box: Walking around the block self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click() self.selenium.find_element_by_link_text('Add an entry').click() # The following has 2 matching: Just walking and Adding entry...block header_text = self.selenium.find_elements_by_tag_name('h3')[1].text self.assertTrue('Adding entry for Walking around the block!' in header_text) # Switching to iframe focus self.selenium.switch_to_frame(self.selenium.find_element_by_id('id_entry_iframe')) # Insert text text_entry = 'I think I will bring my cat out next time.' self.selenium.find_element_by_class_name('note-editable')\ .send_keys(text_entry) # Insert image button self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[2]').click() image_entry = 'http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/input')\ .send_keys(image_entry) # Click on the inset image button self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[3]/button').click() # Insert video button self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[3]').click() video_entry = 'https://www.youtube.com/watch?v=Rk_bV0RJRhs&index=20&list=PLJU_WCB1rA2SFwFy3lEvY_NH23ql1-Cgi' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[2]/div/input')\ .send_keys(video_entry) # Click on the insert video button self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[3]/button').click() # Switch back out of the iframe. self.selenium.switch_to_default_content() # Click on the submit button self.selenium.find_element_by_class_name('btn-success').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') # Ensure that entry exists as the first box on the page. box_text = self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[1]/a/div').text self.assertTrue(text_entry in box_text) self.selenium.find_element_by_xpath("//img[@src='http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg']") self.selenium.find_element_by_xpath('//iframe[@src="//www.youtube.com/embed/Rk_bV0RJRhs"]') def test_delete_entry(self): """Test to ensure that a student can delete an entry""" # Click on the first activity box: Walking around the block self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click() self.selenium.find_element_by_link_text('Add an entry').click() # The following has 2 matching: Just walking and Adding entry...block header_text = self.selenium.find_elements_by_tag_name('h3')[1].text self.assertTrue('Adding entry for Walking around the block!' in header_text) # Switching to iframe focus self.selenium.switch_to_frame(self.selenium.find_element_by_id('id_entry_iframe')) # Insert text text_entry = 'I think I will bring my cat out next time.' self.selenium.find_element_by_class_name('note-editable')\ .send_keys(text_entry) # Insert image button self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[2]').click() image_entry = 'http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/input')\ .send_keys(image_entry) # Click on the inset image button self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[3]/button').click() # Insert video button self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[3]').click() video_entry = 'https://www.youtube.com/watch?v=Rk_bV0RJRhs&index=20&list=PLJU_WCB1rA2SFwFy3lEvY_NH23ql1-Cgi' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[2]/div/input')\ .send_keys(video_entry) # Click on the insert video button self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[3]/button').click() # Switch back out of the iframe. self.selenium.switch_to_default_content() # Click on the submit button self.selenium.find_element_by_class_name('btn-success').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') # Ensure that entry exists as the first box on the page. box_text = self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[1]/a/div').text self.assertTrue(text_entry in box_text) self.selenium.find_element_by_xpath("//img[@src='http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg']") self.selenium.find_element_by_xpath('//iframe[@src="//www.youtube.com/embed/Rk_bV0RJRhs"]') # Click on the entry that was created self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[1]/a').click() # Click on the delete button self.selenium.find_element_by_class_name('btn-danger').click() self.selenium.find_element_by_xpath('//*[@id="delete-modal"]/div/div/div[3]/a').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') # Ensure that the entry created is no longer on the entries page main_text = self.selenium.find_element_by_class_name('main').text # Check for text self.assertFalse(text_entry in main_text) # Check for image image_entry_xpath = "//img[@src='http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg']" self.assertFalse(image_entry_xpath in main_text) # Check for video video_entry_xpath = '//iframe[@src="//www.youtube.com/embed/Rk_bV0RJRhs"]' self.assertFalse(video_entry_xpath in main_text)
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( '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 TopicOrderingTest(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='******' ) # 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_default_ordering_without_settings(self): self.browser.get(self.live_server_url+reverse("niji:index")) first_topic_title = self.browser.find_element_by_class_name( "entry-link" ).text self.assertEqual(first_topic_title, self.t99.title) Post.objects.create( topic=self.t1, content_raw='reply to post __1__', user=self.u1, ) self.browser.get(self.browser.current_url) first_topic_title = self.browser.find_element_by_class_name( "entry-link" ).text self.assertEqual(first_topic_title, self.t1.title) @override_settings(NIJI_DEFAULT_TOPIC_ORDERING="-pub_date") def test_default_ordering_with_settings(self): self.browser.get(self.live_server_url+reverse("niji:index")) first_topic_title = self.browser.find_element_by_class_name( "entry-link" ).text self.assertEqual(first_topic_title, self.t99.title) Post.objects.create( topic=self.t1, content_raw='reply to post __1__', user=self.u1, ) self.browser.get(self.browser.current_url) first_topic_title = self.browser.find_element_by_class_name( "entry-link" ).text self.assertEqual(first_topic_title, self.t99.title) def test_user_specified_ordering_last_replied(self): self.browser.get(self.live_server_url+reverse("niji:index")) self.browser.find_element_by_link_text( "Last Replied" ).click() first_topic_title = self.browser.find_element_by_class_name( "entry-link" ).text self.assertEqual(first_topic_title, self.t99.title) def test_user_specified_ordering_pub_date(self): Post.objects.create( topic=self.t1, content_raw='reply to post __1__', user=self.u1, ) self.browser.get(self.live_server_url+reverse("niji:index")) self.browser.find_element_by_link_text( "Topic Date" ).click() first_topic_title = self.browser.find_element_by_class_name( "entry-link" ).text self.assertEqual(first_topic_title, self.t99.title) def test_user_specified_ordering_last_replied_pagination(self): self.browser.get(self.live_server_url+reverse("niji:index")) self.browser.find_element_by_link_text( "Last Replied" ).click() res = self.client.get(self.browser.current_url) request = res.wsgi_request self.assertEqual(request.GET.get("order"), "-last_replied") self.browser.find_element_by_link_text("»").click() res = self.client.get(self.browser.current_url) request = res.wsgi_request self.assertEqual(request.GET.get("order"), "-last_replied") def test_user_specified_ordering_node_view(self): Post.objects.create( topic=self.t1, content_raw='reply to post __1__', user=self.u1, ) self.browser.get( self.live_server_url+reverse( "niji:node", kwargs={"pk": self.n1.pk} ) ) self.browser.find_element_by_link_text( "Topic Date" ).click() first_topic_title = self.browser.find_element_by_class_name( "entry-link" ).text self.assertEqual(first_topic_title, self.t99.title) def test_user_specified_ordering_search_view(self): Post.objects.create( topic=self.t1, content_raw='reply to post __1__', user=self.u1, ) self.browser.get( self.live_server_url+reverse( "niji:search", kwargs={"keyword": "test"} ) ) self.browser.find_element_by_link_text( "Topic Date" ).click() first_topic_title = self.browser.find_element_by_class_name( "entry-link" ).text self.assertEqual(first_topic_title, self.t99.title)
class SeleniumTestCase(StaticLiveServerTestCase): def create_flights(self): c1 = Crew.objects.create(captain_name="Anna", captain_surname="Kramarska") c2 = Crew.objects.create(captain_name="Bartosz", captain_surname="Wojno") c3 = Crew.objects.create(captain_name="Ola", captain_surname="Grzyb") a1 = Airport.objects.create(name="Warsaw") a2 = Airport.objects.create(name="Modlin") air1 = Airplane.objects.create(licenseChars="ak385833", capacity=100) air2 = Airplane.objects.create(licenseChars="bw386385", capacity=50) Flight.objects.create(startingAirport=a1, landingAirport=a2, startingTime=datetime.now(), landingTime=datetime.now() + timedelta(hours=12), airplane=air1, crew=c1) Flight.objects.create(startingAirport=a2, landingAirport=a1, startingTime=datetime.now(), landingTime=datetime.now() + timedelta(hours=6), airplane=air2, crew=c2) def create_users(self): get_user_model().objects.create_user('temp', '*****@*****.**', 'temporary') get_user_model().objects.create_user('temp2', '*****@*****.**', 'temporary') def setUp(self): self.selenium = WebDriver() self.selenium.implicitly_wait(10) self.create_users() self.create_flights() def tearDown(self): self.selenium.quit() def test_login(self): self.selenium.get('%s%s' % (self.live_server_url, '/auth/login/')) username_input = self.selenium.find_element_by_name("username") username_input.send_keys('temp') password_input = self.selenium.find_element_by_name("password") password_input.send_keys('temporary') self.selenium.find_element_by_xpath('//button[@type="submit"]').click() self.selenium.find_element_by_class_name("data") def test_add_passenger(self): self.test_login() self.selenium.get('%s%s' % (self.live_server_url, '/flight/1/')) name_input = self.selenium.find_element_by_id('id_name') name_input.send_keys("Anna") surname_input = self.selenium.find_element_by_id('id_surname') surname_input.send_keys("Kramarska") tickets_input = self.selenium.find_element_by_name('nrOfTickets') tickets_input.send_keys(10) self.selenium.find_element_by_id('buy').click() def test_assign_crew(self): self.selenium.get('%s%s' % (self.live_server_url, '/')) self.selenium.find_element_by_id('crews-link').click() # login user_input = self.selenium.find_element_by_id('user') user_input.send_keys('temp') pass_input = self.selenium.find_element_by_id('password') pass_input.send_keys('temporary') self.selenium.find_element_by_id('log').click() self.selenium.find_element_by_xpath('//button[text()="Logout"]') # assigning crew flight = self.selenium.find_element_by_id('flight') flight.send_keys(1) crew = self.selenium.find_element_by_id('crew') crew.send_keys('1') self.selenium.find_element_by_id('assign').click()
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'))
class TopicOrderingTest(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='******') # 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_default_ordering_without_settings(self): self.browser.get(self.live_server_url + reverse("index")) first_topic_title = self.browser.find_element_by_class_name( "entry-link").text self.assertEqual(first_topic_title, self.t99.title) Post.objects.create( topic=self.t1, content_raw='reply to post __1__', user=self.u1, ) self.browser.get(self.browser.current_url) first_topic_title = self.browser.find_element_by_class_name( "entry-link").text self.assertEqual(first_topic_title, self.t1.title) @override_settings(NIJI_DEFAULT_TOPIC_ORDERING="-pub_date") def test_default_ordering_with_settings(self): self.browser.get(self.live_server_url + reverse("index")) first_topic_title = self.browser.find_element_by_class_name( "entry-link").text self.assertEqual(first_topic_title, self.t99.title) Post.objects.create( topic=self.t1, content_raw='reply to post __1__', user=self.u1, ) self.browser.get(self.browser.current_url) first_topic_title = self.browser.find_element_by_class_name( "entry-link").text self.assertEqual(first_topic_title, self.t99.title) def test_user_specified_ordering_last_replied(self): self.browser.get(self.live_server_url + reverse("index")) self.browser.find_element_by_link_text("Last Replied").click() first_topic_title = self.browser.find_element_by_class_name( "entry-link").text self.assertEqual(first_topic_title, self.t99.title) def test_user_specified_ordering_pub_date(self): Post.objects.create( topic=self.t1, content_raw='reply to post __1__', user=self.u1, ) self.browser.get(self.live_server_url + reverse("index")) self.browser.find_element_by_link_text("Topic Date").click() first_topic_title = self.browser.find_element_by_class_name( "entry-link").text self.assertEqual(first_topic_title, self.t99.title) def test_user_specified_ordering_last_replied_pagination(self): self.browser.get(self.live_server_url + reverse("index")) self.browser.find_element_by_link_text("Last Replied").click() res = self.client.get(self.browser.current_url) request = res.wsgi_request self.assertEqual(request.GET.get("order"), "-last_replied") self.browser.find_element_by_link_text("»").click() res = self.client.get(self.browser.current_url) request = res.wsgi_request self.assertEqual(request.GET.get("order"), "-last_replied") def test_user_specified_ordering_node_view(self): Post.objects.create( topic=self.t1, content_raw='reply to post __1__', user=self.u1, ) self.browser.get(self.live_server_url + reverse("node", kwargs={"pk": self.n1.pk})) self.browser.find_element_by_link_text("Topic Date").click() first_topic_title = self.browser.find_element_by_class_name( "entry-link").text self.assertEqual(first_topic_title, self.t99.title) def test_user_specified_ordering_search_view(self): Post.objects.create( topic=self.t1, content_raw='reply to post __1__', user=self.u1, ) self.browser.get(self.live_server_url + reverse("search", kwargs={"keyword": "test"})) self.browser.find_element_by_link_text("Topic Date").click() first_topic_title = self.browser.find_element_by_class_name( "entry-link").text self.assertEqual(first_topic_title, self.t99.title)
class MySeleniumTests(LiveServerTestCase): def setUp(self): """ """ # self.selenium = WebDriver(executable_path='C:/geckodriver.exe') self.selenium = WebDriver() self.selenium.implicitly_wait(10) self.profile = Profile.objects.create_user( username='******', first_name='wafi', last_name='mameri', email='*****@*****.**', password='******', adress1='12 rue', adress2='Alger centre', ville='Alger centre', codezip='16000', contry='Algerie', phone='2131234', discriptions='Bonjour', picture='/media/picture/papy.jpeg', ) self.categorie = Categorie.objects.create(name='Vente') self.annonce_create = Annonce.objects.create( title='Jeux avendre', product='Loisirs', type_annonce='Jeux video', price=20.00, categories=self.categorie, description='super jeux', owner=self.profile, ) self.images_annonce = Image.objects.create( annonce_images=self.annonce_create, image='/media/picture/papy.jpeg', ) def tearDown(self): self.selenium.quit() def test_login(self): """ Test login form """ self.selenium.get('%s%s' % (self.live_server_url, '/accounts/login/')) self.selenium.find_element_by_id("id_login").send_keys('wafistos6') self.selenium.find_element_by_id("id_password").send_keys('djamel2013') self.selenium.find_element_by_id('submitBtn').click() time.sleep(7) self.assertEquals(self.selenium.title, 'Yatach Home') def test_search(self): """ Test search form """ self.selenium.get('%s%s' % (self.live_server_url, '/')) query = self.selenium.find_element_by_name("q") query.send_keys('console') self.selenium.find_element_by_id('searchBtn').click() self.assertEquals(self.selenium.title, 'Yatach Home') def test_add_annonce(self): url_add_annonce = "/annonce/add" profile = Profile.objects.all().first() print(profile.is_active) profile.is_active = True profile.save() print(profile.password) self.selenium.get('%s%s' % (self.live_server_url, url_add_annonce)) self.selenium.find_element_by_id("id_login").send_keys('wafistos6') self.selenium.find_element_by_id("id_password").send_keys('djamel2013') self.selenium.find_element_by_id('submitBtn').click() self.selenium.find_element_by_id("id_title").send_keys('Jeux a vendre') self.selenium.find_element_by_id("id_product").send_keys('console') self.selenium.find_element_by_id("id_price").send_keys(200) self.selenium.find_element_by_id("id_type_annonce").send_keys('Vente') self.selenium.find_element_by_id("id_categories").send_keys('LOISIRS') self.selenium.find_element_by_id("id_description").send_keys( 'Jeux occasion') self.selenium.find_element_by_class_name('site-btn').click()