def __init__(self, executable_path=None, port=0, options=None, service_args=None, desired_capabilities=None, service_log_path=None, opera_options=None): """ Creates a new instance of the operadriver. Starts the service and then creates new instance of operadriver. :Args: - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH - port - port you would like the service to run, if left as 0, a free port will be found. - desired_capabilities: Dictionary object with non-browser specific capabilities only, such as "proxy" or "loggingPref". - options: this takes an instance of ChromeOptions """ if opera_options: warnings.warn('use options instead of opera_options', DeprecationWarning) options = opera_options executable_path = (executable_path if executable_path is not None else "operadriver") ChromiumDriver.__init__(self, executable_path=executable_path, port=port, options=options, service_args=service_args, desired_capabilities=desired_capabilities, service_log_path=service_log_path)
def __init__(self, executable_path=None, port=0, options=None, service_args=None, desired_capabilities=None, service_log_path=None, opera_options=None, keep_alive=True): """ Creates a new instance of the operadriver. Starts the service and then creates new instance of operadriver. :Args: - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH - port - port you would like the service to run, if left as 0, a free port will be found. - options: this takes an instance of OperaOptions - service_args - List of args to pass to the driver service - desired_capabilities: Dictionary object with non-browser specific - service_log_path - Where to log information from the driver. capabilities only, such as "proxy" or "loggingPref". """ executable_path = (executable_path if executable_path is not None else "operadriver") ChromiumDriver.__init__(self, executable_path=executable_path, port=port, options=options, service_args=service_args, desired_capabilities=desired_capabilities, service_log_path=service_log_path, keep_alive=keep_alive)
class MyLiveServerTestCase(LiveServerTestCase): def setUp(self): self.driver = WebDriver() self.url = self.live_server_url def tearDown(self): self.driver.quit()
def testCalc(self): driver = WebDriver() bmi_calc = bmicalcpage(driver) bmi_calc.open() self.assertEqual(True, bmi_calc.is_loaded) bmi_calc.calculate('181','80') self.assertEqual('24.4', bmi_calc.bmi) self.assertEqual('Normal', bmi_calc.bmi_category) driver.close()
class Application: def __init__(self): self.wd = WebDriver() self.wd.implicitly_wait(5) self.session = SessionHelper(self) self.group = GroupHelper(self) self.contact = ContactHelper(self) def open_home_page(self): wd = self.wd if not (wd.current_url.endswith("/addressbook/") and len(wd.find_elements_by_name("searchstring")) > 0): wd.get("http://localhost/addressbook/") def destroy(self): self.wd.quit()
def setUp(self): self.browser = WebDriver() self.browser.implicitly_wait(3) self.n1 = Node.objects.create( title='TestNodeOne', description='The first test node' ) self.u1 = User.objects.create_user( username='******', email='*****@*****.**', password='******' ) self.u2 = User.objects.create_user( username='******', email='*****@*****.**', password='******' ) # Create 99 topics for i in range(1, 100): setattr( self, 't%s' % i, Topic.objects.create( title='Test Topic %s' % i, user=self.u1, content_raw='This is test topic __%s__' % i, node=self.n1 ) )
def setUp(self): self.driver = WebDriver() self.url = self.live_server_url user = UserFactory.create(username = "******", password = "******", is_active = True) g = Group.objects.get_or_create(name=u'therapist') user.groups.add(g[0].pk) CustomerFactory.create_batch(3)
def setUp(self): self.driver = WebDriver() self.url = self.live_server_url user = UserFactory.create(username = "******", password = "******", is_active = True) g = Group.objects.get_or_create(name=u'therapist') user.groups.add(g[0].pk) CompanyProfileFactory.create_batch(1) KelaContactProfileFactory.create_batch(1) SessionDoneFactory.create_batch(1)
def test_browse(self): # print [m for m in dir(WebDriver) if not m.startswith('_')] # help() # home'u çağır... self.selenium.get('%s%s' % (self.live_server_url, reverse("home"))) self.assertEqual(self.selenium.title, "Blog Sitesi") # ekran görüntüsü al... WebDriver.get_screenshot_as_file(self.selenium, "%s/Desktop/stest_home.png" % os.environ['HOME']) # self.selenium.implicitly_wait(20) # sleep(2) # <ul id="posts"> var mı? ul_posts = self.selenium.find_element_by_id("posts") self.assertGreater(len(ul_posts.text), 0) # <a href="/blog/post/15/">Merhaba Dünya 15</a> linki bul first_link = self.selenium.find_element_by_xpath('//a[@href="/blog/post/15/"]') first_link_text = first_link.text.encode('utf-8') # Texti "Merhaba Dünya 15"? self.assertEqual(first_link_text, "Merhaba D\xc3\xbcnya 15") # Linke tıkla... first_link.click() self.assertEqual(self.selenium.title.encode('utf-8'), "Blog Sitesi | Merhaba D\xc3\xbcnya 15") WebDriver.get_screenshot_as_file(self.selenium, "%s/Desktop/stest_detial.png" % os.environ['HOME']) # sleep(2) # gelen sayfadaki <h1> i bul, texti "Detay" mı? self.assertEqual(self.selenium.find_element_by_tag_name('h1').text, "Detay") # username_input = self.selenium.find_element_by_name("username") # username_input.send_keys('myuser') # password_input = self.selenium.find_element_by_name("password") # password_input.send_keys('secret') # self.selenium.find_element_by_xpath('//input[@value="Log in"]').click()
def login(email, password): browser = Browser() browser.get('http://tagbrand.com/login') WebDriverWait(browser, timeout=10).until(readystate_complete) form = browser.find_element_by_xpath('//*[@id="form-register"]') if form: email_field = browser.find_element_by_xpath('//*[@id="login-email"]') email_field.send_keys(email) pwd_field = browser.find_element_by_xpath( '//*[@id="LoginForm_password"]' ) pwd_field.send_keys(password) submit_btn = browser.find_element_by_xpath( '//*[@id="form-register"]/div[3]/a' ) submit_btn.click() return browser
def execute(self, driver: WebDriver): self.logger.debug('[OpenPage] %s', self.url) driver.get(self.url)
def setUpClass(cls): super().setUpClass() cls.selenium = WebDriver( executable_path='C:\Drivers\chromedriver\chromedriver.exe')
class SessionFunctionalTest(MyLiveServerTestCase): def setUp(self): self.driver = WebDriver() self.url = self.live_server_url user = UserFactory.create(username = "******", password = "******", is_active = True) g = Group.objects.get_or_create(name=u'therapist') user.groups.add(g[0].pk) CustomerFactory.create_batch(3) def test_can_create_session(self): testcustomers = [] testcustomers.extend(CustomerFactory.create_batch(3)) testcustomer = testcustomers.pop() testcustomersearchtext = testcustomer.lastName + ', ' + testcustomer.firstName testsessions = [] testsessions.extend(SessionFactory.create_batch(3, customer=testcustomer)) self.driver.get(self.url) #login testuser mainpageanonymous = MainPageAnonymousUsers(self.driver) assert mainpageanonymous.is_menu_dropdown_visible(), "menu dropdown is not visible" mainpageanonymous.click_menu_dropdown() assert mainpageanonymous.is_login_navitem_visible(), "login navitem is not visible" mainpageanonymous.click_login_navitem() login_page = LoginPage(self.driver) assert login_page.is_username_field(), "username field is not visible" assert login_page.is_password_field(), "password field is not visible" assert login_page.is_signin_button(), "signin button is not visible" login_page.set_username_password() login_page.click_signin_button() mainpageloggedin = MainPageLoggedInUsers(self.driver) assert mainpageloggedin.is_menu_dropdown_visible(), "menu dropdown is not visible" mainpageloggedin.click_menu_dropdown() assert mainpageloggedin.is_customer_navitem_visible(), "customer link is not visible" mainpageloggedin.click_customer_navitem() # customer_list page customerlist_page = CustomerListPage(self.driver) assert customerlist_page.is_menu_dropdown_visible(), "menu dropdown is not visible" customerlist_page.click_menu_dropdown() assert customerlist_page.is_customer_navitem_visible(), "customer link is not visible" assert customerlist_page.is_createcustomer_navitem_visible(), "customer create link is not visible" # Open customer_detail page assert customerlist_page.is_created_testcustomer(testcustomersearchtext), "generated test customer is not visible" customerlist_page.click_created_testcustomer(testcustomersearchtext) customerdetail_page = CustomerDetailPage(self.driver) assert customerdetail_page.is_customer_update_button_visible() assert customerdetail_page.is_customer_list_button_visible() assert customerdetail_page.is_session_create_button_visible() customerdetail_page.click_session_create_button() #Create session sessionform_page = SessionFormPage(self.driver) assert sessionform_page.is_date_field_visible() assert sessionform_page.is_time_field_visible() assert sessionform_page.is_sessioninvoicetype_field_visible() assert sessionform_page.is_kelainvoicetype_field_visible() assert sessionform_page.is_sessiontype_field_visible() assert sessionform_page.is_sessiondone_field_visible() assert sessionform_page.is_sessionprice_field_visible() assert sessionform_page.is_sessionpricekelarefund_field_visible() sessionform_page.click_sessionsave_button() # returned to customer_detail page customerdetail_page.is_customer_update_button_visible() def test_can_update_session(self): testcustomers = [] testcustomers.extend(CustomerFactory.create_batch(3)) testcustomer = testcustomers.pop() testcustomersearchtext = testcustomer.lastName + ', ' + testcustomer.firstName testsessions = [] testsessions.extend(SessionFactory.create_batch(10, customer=testcustomer)) testsession = testsessions.pop() self.driver.get(self.url) #login testuser mainpageanonymous = MainPageAnonymousUsers(self.driver) assert mainpageanonymous.is_menu_dropdown_visible(), "menu dropdown is not visible" mainpageanonymous.click_menu_dropdown() assert mainpageanonymous.is_login_navitem_visible(), "login navitem is not visible" mainpageanonymous.click_login_navitem() login_page = LoginPage(self.driver) assert login_page.is_username_field(), "username field is not visible" assert login_page.is_password_field(), "password field is not visible" assert login_page.is_signin_button(), "signin button is not visible" login_page.set_username_password() login_page.click_signin_button() mainpageloggedin = MainPageLoggedInUsers(self.driver) assert mainpageloggedin.is_menu_dropdown_visible(), "menu dropdown is not visible" mainpageloggedin.click_menu_dropdown() assert mainpageloggedin.is_customer_navitem_visible(), "customer link is not visible" mainpageloggedin.click_customer_navitem() # customer_list page customerlist_page = CustomerListPage(self.driver) assert customerlist_page.is_menu_dropdown_visible(), "menu dropdown is not visible" customerlist_page.click_menu_dropdown() assert customerlist_page.is_customer_navitem_visible(), "customer link is not visible" assert customerlist_page.is_createcustomer_navitem_visible(), "customer create link is not visible" # Open customer_detail page assert customerlist_page.is_created_testcustomer(testcustomersearchtext), "generated test customer is not visible" customerlist_page.click_created_testcustomer(testcustomersearchtext) customerdetail_page = CustomerDetailPage(self.driver) assert customerdetail_page.is_customer_update_button_visible() assert customerdetail_page.is_customer_list_button_visible() #assert customerdetail_page.is_one_session_date_changed() assert customerdetail_page.is_session_update_link_visible() customerdetail_page.click_session_update_link() sessionform_page = SessionFormPage(self.driver) assert sessionform_page.is_date_field_visible() assert sessionform_page.is_time_field_visible() assert sessionform_page.is_sessioninvoicetype_field_visible() assert sessionform_page.is_kelainvoicetype_field_visible() assert sessionform_page.is_sessiontype_field_visible() assert sessionform_page.is_sessiondone_field_visible() assert sessionform_page.is_sessionprice_field_visible() assert sessionform_page.is_sessionpricekelarefund_field_visible() #sessionform_page.set_session_fields() sessionform_page.change_date_field() sessionform_page.click_sessionsave_button() # returned to customer_detail page and check if one of sessions has new date 31.12.2039 customerdetail_page.is_one_session_date_changed() def test_can_delete_session(self): testcustomers = [] testcustomers.extend(CustomerFactory.create_batch(3)) testcustomer = testcustomers.pop() testcustomersearchtext = testcustomer.lastName + ', ' + testcustomer.firstName testsessions = [] testsessions.extend(SessionFactory.create_batch(1, customer=testcustomer)) testsession = testsessions.pop() self.driver.get(self.url) #login testuser mainpageanonymous = MainPageAnonymousUsers(self.driver) assert mainpageanonymous.is_menu_dropdown_visible(), "menu dropdown is not visible" mainpageanonymous.click_menu_dropdown() assert mainpageanonymous.is_login_navitem_visible(), "login navitem is not visible" mainpageanonymous.click_login_navitem() login_page = LoginPage(self.driver) assert login_page.is_username_field(), "username field is not visible" assert login_page.is_password_field(), "password field is not visible" assert login_page.is_signin_button(), "signin button is not visible" login_page.set_username_password() login_page.click_signin_button() mainpageloggedin = MainPageLoggedInUsers(self.driver) assert mainpageloggedin.is_menu_dropdown_visible(), "menu dropdown is not visible" mainpageloggedin.click_menu_dropdown() assert mainpageloggedin.is_customer_navitem_visible(), "customer link is not visible" mainpageloggedin.click_customer_navitem() # customer_list page customerlist_page = CustomerListPage(self.driver) assert customerlist_page.is_menu_dropdown_visible(), "menu dropdown is not visible" customerlist_page.click_menu_dropdown() assert customerlist_page.is_customer_navitem_visible(), "customer link is not visible" assert customerlist_page.is_createcustomer_navitem_visible(), "customer create link is not visible" customerlist_page.click_menu_dropdown() # Open customer_detail page assert customerlist_page.is_created_testcustomer(testcustomersearchtext), "generated test customer is not visible" customerlist_page.click_created_testcustomer(testcustomersearchtext) customerdetail_page = CustomerDetailPage(self.driver) assert customerdetail_page.is_customer_update_button_visible(), "customer update button is not visible" assert customerdetail_page.is_customer_list_button_visible(), "link to customer list is not visible" assert customerdetail_page.is_session_delete_button_visible(), "no sessions visible at customer detail page" customerdetail_page.click_session_delete_button() sessiondelete_page = SessionDeletePage(self.driver) assert sessiondelete_page.is_sessiondeleteconfirmation_button_visible(), "session delete confirmation button is not visible" sessiondelete_page.click_sessiondeleteconfirmation_button() assert not customerdetail_page.is_session_delete_button_visible(), "only session was not deleted"
def setUpClass(cls): super().setUpClass() cls.selenium = WebDriver(executable_path=settings.CHROMEDRIVER) cls.selenium.implicitly_wait(10)
def setUpClass(cls): super().setUpClass() cls.selenium = WebDriver() # Wait 10 seconds for elements to appear, always cls.selenium.implicitly_wait(10)
def get_recordings( driver: WebDriver, end_date: str, cookies_file: str, username: str, password: str, info_file: str, user_agent: str, path_where_recordings_are_saved: str, download_duplicates: bool = False, system: str = "linux", ) -> None: """ Logs in, searches for recordings, makes recording metadata, and downloads recordings. This function is the heart of the program. :param driver: The WebDriver. :param end_date: The earliest date to search for recordings from. The date range of recordings will be from this date to the date the script is ran on. :param cookies_file: The file location of the previous cookies (if any). :param username: Username of the user. :param password: Password of the user. :param info_file: The file where the recording metadata will be saved. :param download_duplicates: Whether the script should find the metadata for recordings that already exist within the config file or not. :param user_agent: The user agent of the driver. :param path_where_recordings_are_saved: Directory path of where the recordings will be saved. :param system: The OS where the script is running. :return: None. """ print_log("Starting metadata extraction.") enter_username_and_password(driver, username, password, slow=True, remember_me=True) captcha(driver, username, password) email_verification(driver) print_log("Loading old cookies.") cookies = driver.get_cookies() dump_cookies(cookies_file, cookies) try: search_for_recordings(driver, end_date, system=system) reveal_all_recordings(driver) except (WebDriverException, NoSuchElementException, ProtocolError, RemoteDisconnected, TimeoutException): driver.implicitly_wait(5) print_log( "WARNING: Finding the recordings errored out. Trying to search again." ) search_for_recordings(driver, end_date, system=system) driver.implicitly_wait(5) reveal_all_recordings(driver) driver.implicitly_wait(5) except ProtocolError as e: print_log( "ERROR. Amazon has closed this connection, likely because it has identified this script " "and will stop it. This can happen from time to time. Please run this script again." ) raise e recording_boxes = driver.find_elements_by_class_name("apd-content-box") previous_path = find_last_recording_folder(path_where_recordings_are_saved) old_recording_metadata = get_old_metadata( os.path.join(previous_path, info_file)) recording_metadata, indices_to_download = extract_recording_metadata( recording_boxes, driver, old_recording_metadata, download_duplicates) extract_uid_from_recordings(driver, sorted(indices_to_download), recording_metadata) metadata_file_name = info_file.split("/")[-1] save_metadata( metadata=recording_metadata, recording_path=path_where_recordings_are_saved, metadata_file_name=metadata_file_name, ) recording_ids = get_audio_ids(recording_metadata) formatted_cookies = format_cookies_for_request(cookies) download_wav_files( audio_ids=recording_ids, user_agent=user_agent, cookies=formatted_cookies, recording_path=path_where_recordings_are_saved, ) print_log(f"Finished downloading all recordings for user {username}.")
class KelaStatementFunctionalTest(MyLiveServerTestCase): def setUp(self): self.driver = WebDriver() self.url = self.live_server_url user = UserFactory.create(username = "******", password = "******", is_active = True) g = Group.objects.get_or_create(name=u'therapist') user.groups.add(g[0].pk) CompanyProfileFactory.create_batch(1) SessionDoneFactory.create_batch(1) def test_user_can_login(self): # load the customer list page self.driver.get(self.url) mainpage = MainPageAnonymousUsers(self.driver) assert mainpage.is_menu_dropdown_visible(), "menu dropdown is not visible" mainpage.click_menu_dropdown() assert mainpage.is_login_navitem_visible(), "login navitem is not visible" mainpage.click_login_navitem() #login user login_page = LoginPage(self.driver) assert login_page.is_username_field(), "username field is not visible" assert login_page.is_password_field(), "password field is not visible" assert login_page.is_signin_button(), "signin button is not visible" login_page.set_username_password() login_page.click_signin_button() def test_can_create_invoice(self): self.driver.get(self.url) #login testuser mainpageanonymous = MainPageAnonymousUsers(self.driver) assert mainpageanonymous.is_menu_dropdown_visible(), "menu dropdown is not visible" mainpageanonymous.click_menu_dropdown() assert mainpageanonymous.is_login_navitem_visible(), "login navitem is not visible" mainpageanonymous.click_login_navitem() login_page = LoginPage(self.driver) assert login_page.is_username_field(), "username field is not visible" assert login_page.is_password_field(), "password field is not visible" assert login_page.is_signin_button(), "signin button is not visible" login_page.set_username_password() login_page.click_signin_button() mainpageloggedin = MainPageLoggedInUsers(self.driver) assert mainpageloggedin.is_menu_dropdown_visible(), "menu dropdown is not visible" mainpageloggedin.click_menu_dropdown() assert mainpageloggedin.is_customerinvoicing_navitem_visible(), "customerinvoicing link is not visible" mainpageloggedin.click_customerinvoicing_navitem() # invoice_list page invoicelist_page = InvoiceListPage(self.driver) assert invoicelist_page.is_invoice_create_button_visible(), "invoice create button is not visible" invoicelist_page.click_invoice_create_button() # invoice_generator_confirm page generateinvoice_page = GenerateInvoicePage(self.driver) assert generateinvoice_page.is_invoice_generate_confirm_button_visible(), "invoice generate button is not visible" generateinvoice_page.click_invoice_generate_confirm_button() # invoice_list page invoicelist_page = InvoiceListPage(self.driver) assert invoicelist_page.is_invoice_detail_link_visible(), "invoice detail link is not hidden"
class VisitorTest(LiveServerTestCase): """ Test as a visitor (unregistered user) """ def setUp(self): self.browser = WebDriver() self.browser.implicitly_wait(3) self.n1 = Node.objects.create( title='TestNodeOne', description='The first test node' ) self.u1 = User.objects.create_user( username='******', email='*****@*****.**', password='******' ) self.u2 = User.objects.create_user( username='******', email='*****@*****.**', password='******' ) # Create 99 topics for i in range(1, 100): setattr( self, 't%s' % i, Topic.objects.create( title='Test Topic %s' % i, user=self.u1, content_raw='This is test topic __%s__' % i, node=self.n1 ) ) def tearDown(self): self.browser.quit() def test_index(self): self.browser.get(self.live_server_url+reverse('niji:index')) self.assertIn('niji', self.browser.page_source.lower()) def test_topic_page_content(self): self.browser.get(self.live_server_url+reverse('niji:topic', kwargs={'pk': self.t88.pk})) self.assertIn('This is test topic <strong>88</strong>', self.browser.page_source) def test_node_page(self): self.browser.get(self.live_server_url+reverse('niji:node', kwargs={'pk': self.n1.pk})) topics = self.browser.find_elements_by_css_selector('ul.topic-list > li') self.assertEqual(len(topics), 30)
def start(self, browser_type=None, browser_version='', browser_platform='ANY', session_name='', javascript_disabled=False, assume_trusted_cert_issuer=False, webdriver_remote=None): """ Starts Browser with a new session. Called for you at the start of each test script. """ if browser_type is None: browser_type = 'Firefox' if logger.isEnabledFor(logging.DEBUG): # We print a new line because otherwise the first debug message # will be printed on the same line as the name of the test. This is # hacky, I know. print logger.debug('Starting browser: %s' % browser_type) from selenium import webdriver if webdriver_remote is None: if browser_type == 'Firefox': # profile features are FF only import getpass import os ,platform path = "" profileFile = "" profile = "" if platform.system()== "Windows": path = r'C:\Users\%s\AppData\Roaming\Mozilla\Firefox\Profiles' % getpass.getuser() profileFile = os.listdir(path) profile = webdriver.FirefoxProfile('%s\%s' % (path , profileFile[0])) else : from selenium import webdriver cmd = "chflags unhidden ~/Library" os.system(cmd) users = os.listdir('/Users') username = platform.node() uname = "" profileFile = "" for i in users: count = username.split(i) if count[0] == "": check = count[1] uname = username.split(check) path = r"/Users/%s/Library/Application Support/Firefox/Profiles"% uname[0] files = os.listdir(path) print files for i in files : if not i in ['.DS_Store']: profileFile = i profile = webdriver.FirefoxProfile('%s/%s' % (path , profileFile)) print profileFile print profile #profile = webdriver.FirefoxProfile('%s\%s' % (path , profileFile)) # profile = getattr(webdriver, '%sProfile' % browser_type)() profile.set_preference('intl.accept_languages', 'en') ################################################################# # Changes by Test Mile import os profile.set_preference("browser.download.folderList",2) profile.set_preference("browser.download.dir", "/Downloads") profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/zip,text/plain,audio/mpeg3,audio/x-mpeg-3,video/mpeg,video/x-mpeg,image/jpeg,image/pjpeg,video/x-ms-wmv,audio/x-ms-wmv,application/txt, browser/internal, text/anytext, widetext/plain, widetext/paragraph, application/notepad,video/mp4,text/csv,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") ################################################################# if config.ProxySettings.ProxyIP and config.ProxySettings.ProxyPort != "": print '------------ Proxy IP is ------------ %s' % str(config.ProxySettings.ProxyIP) profile.set_preference("network.proxy.type",1) profile.set_preference("network.proxy.ssl", config.ProxySettings.ProxyIP) profile.set_preference("network.proxy.ssl_port", config.ProxySettings.ProxyPort) else: print '------------ Proxy IP/Port is Empty ------------' if assume_trusted_cert_issuer: profile.set_preference( 'webdriver_assume_untrusted_issuer', False) profile.setPreference( 'capability.policy.default.Window.QueryInterface', 'allAccess') profile.setPreference( 'capability.policy.default.Window.frameElement.get', 'allAccess') if javascript_disabled: profile.set_preference('javascript.enabled', False) print '------------ Proxy IP/Port is Empty ------------' self.driver = getattr(webdriver, browser_type)(profile) elif browser_type == 'Chrome': #chrome_options = webdriver.ChromeOptions() #chrome_options.add_argument('--proxy-server=localhost:9191') import getpass import os ,platform import json from selenium.webdriver.chrome.options import Options chrome_options_obj = Options() path_manifest = '' add_on_name = 'site advisor' if platform.system()== "Windows": extension_path = r'C:\Users\%s\AppData\Local\Google\Chrome\User Data\Default\Extensions'% getpass.getuser() else: cmd = "chflags unhidden ~/Library" os.system(cmd) extension_path = r'/Users/%s/Library/Application Support/Google/Chrome/Default/Extensions'% getpass.getuser() for r,d,f in os.walk(extension_path): for files in f: if files in 'manifest.json': if platform.system()== "Windows": path_manifest = os.path.join(r+'\\%s'%files) else: path_manifest = os.path.join(r+'//%s'%files) json_data=open(r'%s'% path_manifest) data = json.load(json_data) if data['description'] not in ['__MSG_appDesc__'] and data['description'].replace(' ','').lower() in [add_on_name.replace(' ','').lower()]: json_data.close() path_manifest = os.path.dirname(path_manifest) chrome_options_obj.add_argument(r"--load-extension=%s" %path_manifest) else: json_data.close() desired_capabilities = { "platform": browser_platform.upper(), "version": browser_version, "javascriptEnabled": not javascript_disabled, "name": session_name, "proxy" : { "proxyType" : "direct", } } if config.ProxySettings.ProxyIP and config.ProxySettings.ProxyPort != "": proxy_string = "%s:%s" % (config.ProxySettings.ProxyIP, config.ProxySettings.ProxyPort) desired_capabilities["proxy"] = { "proxyType" : "manual", "ftpProxy" : proxy_string, "httpProxy" : proxy_string, "sslProxy" : proxy_string } from selenium.webdriver.chrome.webdriver import WebDriver as ChromeDriver self.driver = ChromeDriver(desired_capabilities=desired_capabilities) #self.driver = webdriver.Chrome(service_log_path='chromedriver.log', desired_capabilities=desired_capabilities) elif browser_type == 'Safari': from selenium import webdriver import os import subprocess desired_capabilities = {"browserName": browser_type.lower(), "platform": browser_platform.upper(), "version": browser_version, "javascriptEnabled": not javascript_disabled, "name": session_name} subprocess.Popen(["java","-jar", os.environ["SELENIUM_SERVER_JAR"]]) self.driver = webdriver.Remote(desired_capabilities={'browserName':'safari'}) #self.driver = webdriver.Safari() elif browser_type == 'Ie': # Create a copy of desired capabilities object. desired_capabilities = webdriver.DesiredCapabilities.INTERNETEXPLORER.copy() # Change the proxy properties of that copy. desired_capabilities = { "platform": browser_platform.upper(), "version": browser_version, "javascriptEnabled": not javascript_disabled, "name": session_name, "proxy" : { "proxyType" : "direct", } } if config.ProxySettings.ProxyIP and config.ProxySettings.ProxyPort != "": proxy_string = "%s:%s" % (config.ProxySettings.ProxyIP, config.ProxySettings.ProxyPort) desired_capabilities["proxy"] = { "proxyType" : "MANUAL", "ftpProxy" : proxy_string, "httpProxy" : proxy_string, "sslProxy" : proxy_string } self.driver = webdriver.Ie() self.driver.maximize_window() else: desired_capabilities = {"browserName": browser_type.lower(), "platform": browser_platform.upper(), "version": browser_version, "javascriptEnabled": not javascript_disabled, "name": session_name} self.driver = webdriver.Remote(desired_capabilities=desired_capabilities, command_executor=webdriver_remote)
class CustomerFunctionalTest(MyLiveServerTestCase): def setUp(self): self.driver = WebDriver() self.url = self.live_server_url user = UserFactory.create(username = "******", password = "******", is_active = True) g = Group.objects.get_or_create(name=u'therapist') user.groups.add(g[0].pk) CustomerFactory.create_batch(3) def test_user_can_login(self): # load the customer list page self.driver.get(self.url) mainpage = MainPageAnonymousUsers(self.driver) assert mainpage.is_menu_dropdown_visible(), "menu dropdown is not visible" mainpage.click_menu_dropdown() assert mainpage.is_login_navitem_visible(), "login navitem is not visible" mainpage.click_login_navitem() #login user login_page = LoginPage(self.driver) assert login_page.is_username_field(), "username field is not visible" assert login_page.is_password_field(), "password field is not visible" assert login_page.is_signin_button(), "signin button is not visible" login_page.set_username_password() login_page.click_signin_button() def test_can_create_customer(self): """ Test creating new customer :return: """ self.driver.get(self.url) #login testuser mainpageanonymous = MainPageAnonymousUsers(self.driver) assert mainpageanonymous.is_menu_dropdown_visible(), "menu dropdown is not visible" mainpageanonymous.click_menu_dropdown() assert mainpageanonymous.is_login_navitem_visible(), "login navitem is not visible" mainpageanonymous.click_login_navitem() login_page = LoginPage(self.driver) assert login_page.is_username_field(), "username field is not visible" assert login_page.is_password_field(), "password field is not visible" assert login_page.is_signin_button(), "signin button is not visible" login_page.set_username_password() login_page.click_signin_button() mainpageloggedin = MainPageLoggedInUsers(self.driver) assert mainpageloggedin.is_menu_dropdown_visible(), "menu dropdown is not visible" mainpageloggedin.click_menu_dropdown() assert mainpageloggedin.is_customer_navitem_visible(), "customer link is not visible" mainpageloggedin.click_customer_navitem() # customer_list page customerlist_page = CustomerListPage(self.driver) assert customerlist_page.is_menu_dropdown_visible(), "menu dropdown is not visible" customerlist_page.click_menu_dropdown() assert customerlist_page.is_customer_navitem_visible(), "customer link is not visible" customerlist_page.click_menu_dropdown() assert customerlist_page.is_createcustomer_navitem_visible(), "customer create link is not visible" customerlist_page.click_createcustomer_link() # customer_form page customercreate_page = CustomerFormPage(self.driver) assert customercreate_page.is_firstname_field_visible(), "firstname field is not visible" assert customercreate_page.is_lastname_field_visible(), "lastname field is not visible" assert customercreate_page.is_additionalname_field_visible(), "additionalname field is not visible" assert customercreate_page.is_ssn_field_visible(), "ssn field is not visible" assert customercreate_page.is_address_field_visible(), "address field is not visible" assert customercreate_page.is_zipcode_field_visible(), "zipcode field is not visible" assert customercreate_page.is_city_field_visible(), "city field is not visible" assert customercreate_page.is_telephone_field_visible(), "telephone field is not visible" assert customercreate_page.is_email_field_visible(), "email field is not visible" assert customercreate_page.is_status_field_visible(), "status field is not visible" assert customercreate_page.is_sessionprice_field_visible(), "sessionprice field is not visible" assert customercreate_page.is_sessionpricekelarefund_field_visible(), "sessionpricekelarefund field is not visible" assert customercreate_page.is_save_button_visible(), "save button field is not visible" customercreate_page.set_customer_fields() customercreate_page.click_save_button() customerlist_page = CustomerListPage(self.driver) assert customerlist_page.is_testcustomer_visible(), "testcustomer card is not visible" def test_can_edit_customer(self): """ Test editing of existing customer Generate 10 test customers and change lastname field by adding text changedlastname to lastname field :return: """ testcustomers = [] testcustomers.extend(CustomerFactory.create_batch(10)) testcustomer = testcustomers.pop() testcustomersearchtext = testcustomer.lastName + ', ' + testcustomer.firstName self.driver.get(self.url) #login testuser mainpageanonymous = MainPageAnonymousUsers(self.driver) assert mainpageanonymous.is_menu_dropdown_visible(), "menu dropdown is not visible" mainpageanonymous.click_menu_dropdown() assert mainpageanonymous.is_login_navitem_visible(), "login navitem is not visible" mainpageanonymous.click_login_navitem() login_page = LoginPage(self.driver) assert login_page.is_username_field(), "username field is not visible" assert login_page.is_password_field(), "password field is not visible" assert login_page.is_signin_button(), "signin button is not visible" login_page.set_username_password() login_page.click_signin_button() mainpageloggedin = MainPageLoggedInUsers(self.driver) assert mainpageloggedin.is_menu_dropdown_visible(), "menu dropdown is not visible" mainpageloggedin.click_menu_dropdown() assert mainpageloggedin.is_customer_navitem_visible(), "customer link is not visible" mainpageloggedin.click_customer_navitem() # customer_list page customerlist_page = CustomerListPage(self.driver) assert customerlist_page.is_customer_navitem_visible(), "customer link is not visible" assert customerlist_page.is_createcustomer_navitem_visible(), "customer create link is not visible" assert customerlist_page.is_created_testcustomer(testcustomersearchtext), "generated test customer is not visible" customerlist_page.click_created_testcustomer(testcustomersearchtext) customerdetail_page = CustomerDetailPage(self.driver) assert customerdetail_page.is_customer_update_button_visible(), "customer update button is not visible at customer_detail page" customerdetail_page.click_customer_update_button() # customer_form page customerform_page = CustomerFormPage(self.driver) assert customerform_page.is_firstname_field_visible(), "firstname field is not visible" assert customerform_page.is_lastname_field_visible(), "lastname field is not visible" assert customerform_page.is_additionalname_field_visible(), "additionalname field is not visible" assert customerform_page.is_ssn_field_visible(), "ssn field is not visible" assert customerform_page.is_address_field_visible(), "address field is not visible" assert customerform_page.is_zipcode_field_visible(), "zipcode field is not visible" assert customerform_page.is_city_field_visible(), "city field is not visible" assert customerform_page.is_telephone_field_visible(), "telephone field is not visible" assert customerform_page.is_email_field_visible(), "email field is not visible" assert customerform_page.is_therapycategory_field_visible(), "therapycategory field is not visible" assert customerform_page.is_status_field_visible(), "status field is not visible" assert customerform_page.is_sessionprice_field_visible(), "sessionprice field is not visible" assert customerform_page.is_sessionpricekelarefund_field_visible(), "sessionpricekelarefund field is not visible" assert customerform_page.is_save_button_visible(), "submit button field is not visible" customerform_page.change_customer_field_lastname() testcustomersearchtext = testcustomer.lastName + 'changedlastname, ' + testcustomer.firstName customerform_page.click_save_button() assert customerdetail_page.is_customer_list_button_visible(), "customer list button is not visible" customerdetail_page.click_customer_list_button() assert customerlist_page.is_created_testcustomer(testcustomersearchtext), "testcustomer card is not visible" def tearDown(self): self.driver.quit()
def setUp(self): # Create MailingList (newsletter) object self.mailing_list_1 = MailingList.objects.create( mailing_list_name="news1", mailing_list_token="token1", list_active=True, ) self.mailing_list_2 = MailingList.objects.create( mailing_list_name="news2", mailing_list_token="token2", contact_frequency_weeks=4, list_active=True, ) # Create MailingList (petition) object self.mailing_list_3 = MailingList.objects.create( mailing_list_name="petition1", mailing_list_token="token3", list_active=True, is_petition=True, ) self.mailing_list_4 = MailingList.objects.create( mailing_list_name="petition2", mailing_list_token="token4", list_active=True, is_petition=True, ) # Create two Petition (petition) object self.petition_1 = Petition.objects.create( mailing_list=self.mailing_list_3, slug="slug1", petition1_md="First sentence", ) self.petition_2 = Petition.objects.create( mailing_list=self.mailing_list_4, slug="slug2", petition1_md="First sentence 2", ) self.user = User.objects.create_user(username='******', password='******', email="*****@*****.**") self.user.save() self.logged_client = Client() self.logged_client.login(username='******', password='******') self.superuser = \ User.objects.create_superuser(username='******', password='******', email="*****@*****.**") self.superuser.save() self.admin_client = Client() self.admin_client.login(username='******', password='******') # Create a topicblog page for testing quick sign up self.home = TopicBlogItem.objects.create( slug="home", date_modified=datetime.now(timezone.utc), publication_date=datetime.now(timezone.utc), first_publication_date=datetime.now(timezone.utc), user=self.superuser, template_name="topicblog/content.html", title="home-title") # Create the default mailing list self.mailing_list_default = MailingList.objects.create( mailing_list_name="general-quarterly", mailing_list_token="general-quarterly", contact_frequency_weeks=12, list_active=True, ) # Create MailingListEvent object self.mailing_event_1 = MailingListEvent.objects.create( user=self.user, mailing_list=self.mailing_list_1, event_type=MailingListEvent.EventType.SUBSCRIBE) self.mailing_event_2 = MailingListEvent.objects.create( user=self.superuser, mailing_list=self.mailing_list_2, event_type=MailingListEvent.EventType.SUBSCRIBE) self.cookie_user = self.logged_client.cookies['sessionid'].value self.cookie_staff = \ self.admin_client.cookies['sessionid'].value options = Options() options.add_argument("--headless") options.add_argument("--disable-extensions") self.selenium = WebDriver(ChromeDriverManager().install(), options=options) self.selenium.implicitly_wait(5)
def setUpClass(cls): super(TasksViewsStaticLiveServerTestCae, cls).setUpClass() cls.selenium = WebDriver() cls.selenium.implicitly_wait(10)
import os.path import re def releaseHandler(releasesList): for x in releasesList: time.sleep(10) driver.get(x) edition = driver.find_element(By.XPATH, "//table[contains(@class,'stripe')]//tr/td[.='Title']/following-sibling::td").text try: jan_code = driver.find_element(By.XPATH, "//table[contains(@class,'stripe')]//tr/td[.='JAN']/following-sibling::td").text except exceptions.NoSuchElementException: jan_code = str(9999999999999) crafted_output = unicode("\n\t\tEdition: " + edition + " JAN: " + jan_code + "\n") vn_file.write(crafted_output.encode("utf8")) driver = WebDriver() driver.get("https://vndb.org/v/all?q=;fil=plat-win.tagspoil-0.lang-ja;o=a;s=title;p=1") novel_URL = [] vn_file = None if os.path.isfile("scrapedVNList.txt"): fp = open("scrapedVNList.txt", 'r') lineList = fp.readlines() fp.close() matched = "" titleSearch = "" flagTripped = False for x in xrange(3): if re.match(r'^\t', lineList[-(x+1)]) is None: matched = lineList[-(x+1)] if "Medium" in matched: titleSearch = re.match(r'(^.*)?\sMedium', matched).group(1)
def sign_up(driver: WebDriver, user_account, user_password, gender=1): """ 登录facebook平台 :param driver: 浏览器驱动 :param account: FB账号 :param password: FB密码 :param gender: 账号性别 :return: """ # 登录FB url = 'https://m.facebook.com/reg/?cid&soft=hjk' driver.get(url) try: # 注册名称 fitst_name = WebDriverWait(driver, 6).until( EC.presence_of_element_located((By.ID, 'firstname_input'))) super_sendkeys(fitst_name, "XIAONING") time.sleep(3) last_name = WebDriverWait(driver, 6).until( EC.presence_of_element_located((By.ID, 'lastname_input'))) super_sendkeys(last_name, "James") time.sleep(3) last_name.send_keys(Keys.ENTER) time.sleep(3) # 生日 year_num = random.randint(18, 26) mouth_num = random.randint(1, 12) day_num = random.randint(1, 27) select_mouth = Select(driver.find_element_by_id('month')) select_day = Select(driver.find_element_by_id('day')) select_year = Select(driver.find_element_by_id('year')) select_mouth.select_by_index(mouth_num) time.sleep(1) select_day.select_by_index(day_num) time.sleep(1) select_year.select_by_index(year_num) time.sleep(1) birthday_button = driver.find_element_by_css_selector( 'button[data-sigil="touchable multi_step_next"]') super_click(birthday_button, driver) time.sleep(3) # email account phone_account = WebDriverWait(driver, 6).until( EC.presence_of_element_located( (By.CSS_SELECTOR, 'a[data-sigil="switch_phone_to_email"]'))) super_click(phone_account, driver) time.sleep(3) # 邮箱 email_account = WebDriverWait(driver, 6).until( EC.presence_of_element_located( (By.CSS_SELECTOR, 'input[id="contactpoint_step_input"]'))) super_sendkeys(email_account, user_account) email_account.send_keys(Keys.ENTER) time.sleep(3) # 性别 gender = driver.find_elements_by_css_selector('input[name="sex"]') n = random.randint(1, 10) if n % 2 == 0: super_click(gender[0], driver) else: super_click(gender[1], driver) gender_button = WebDriverWait(driver, 6).until( EC.presence_of_element_located( (By.CSS_SELECTOR, 'button[data-sigil="touchable multi_step_next"]'))) super_click(gender_button, driver) time.sleep(3) # 密码 new_password = WebDriverWait(driver, 6).until( EC.presence_of_element_located( (By.CSS_SELECTOR, 'input[id="password_step_input"]'))) super_sendkeys(new_password, user_password) new_password.send_keys(Keys.ENTER) time.sleep(3) except Exception as e: logger.error('auto_login exception, stat process..\r\ne={}'.format(e))
def switchtab(driver: WebDriver, tab=0): try: driver.switch_to.window(driver.window_handles[tab]) except IndexError: driver.execute_script('window.open("");') switchtab(driver, tab)
def setUpClass(cls): super(SeleniumLiveTestCase, cls).setUpClass() cls.selenium = WebDriver() cls.selenium.implicitly_wait(cls.DEFAULT_WAIT_TIME) cls.selenium.set_page_load_timeout(cls.DEFAULT_WAIT_TIME)
def __init__(self): self.wd = WebDriver() self.wd.implicitly_wait(1)
# coding:utf-8 # author: Articuly # datetime: 2020/6/12 15:08 # software: PyCharm import time, random, csv from selenium import webdriver from selenium.webdriver.chrome.webdriver import Options, WebDriver from selenium.webdriver import ActionChains # 创建实例 csv_writer = csv.writer(open('taobao_goods.csv', 'a', encoding='utf-8')) options = Options() options.add_experimental_option('excludeSwitches', ['enable-automation']) browser = WebDriver(r'D:\Browser\Chromium\chromedriver.exe', options=options) # 打开网页 browser.get('https://www.taobao.com') # 将浏览器最大化显示 browser.maximize_window() # 隐性等待页面加载完成,如果一个元素获取不到,会等待30s browser.implicitly_wait(30) class TaobaoSpider: def __init__(self, driver, page): """ 初始化驱动 """ self.driver = driver self.action = ActionChains(self.driver)
def close_window(browser: WebDriver) -> object: browser.close()
driver = webdriver.Chrome(options=options) Companies = [] Location = [] Date = [] Job_Title = [] Subspecialty = [] Years_Experience = [] Total_Comp = [] driver.get(URL) page = 1 WebDriver.find_element_by_xpath( driver, "//span[contains(@class, 'btn-group dropup')]/button").click() WebDriver.find_element_by_xpath( driver, "//span[contains(@class, 'btn-group dropup')]/ul/li[4]").click() max_page = WebDriverWait(driver, 10).until( EC.visibility_of_all_elements_located(( By.XPATH, "//html/body/div[2]/div/div[3]/div[3]/div/div[1]/div[1]/div[3]/div[2]/ul/li[8]/a" )))[0].text # max_page = int(max_page) # Had to hard code the 6 for max pages. Re-investigate the crash # error later while page <= 6: rows = WebDriverWait(driver, 10).until(
def setUp(self): self.driver = WebDriver() self.url = self.live_server_url
class Application: def __init__(self): self.wd = WebDriver() self.wd.implicitly_wait(5) self.session = SessionHelper(self) self.payment = PaymentHelper(self) self.localization = LocalizationHelper(self) self.navigation = NavigationHelper(self) self.login_page = LoginPage(self) self.currency = Currency(self) self.payment_systems = PaymentSystems(self) def experiment(self, a): self.wd.find_element(By.cssSelector('span[class=\"title\"]:contains(' + someText + ')')) self.wd.find_element_by_xpath() self.wd.find_element_by_class_name('forgot') self.wd.find_element_by_link_text('Forgot password') self.wd.find_element_by_css_selector() def check_exists_by_css_selector(self, selector): try: self.wd.find_elements_by_css_selector(selector) except NoSuchElementException: return False return True def check_exists_by_xpath(self, xpath): try: self.wd.find_element_by_xpath(xpath) except NoSuchElementException: return False return True def destroy(self): self.wd.quit()
import math from selenium.webdriver.chrome.webdriver import WebDriver string = str(math.ceil(math.pow(math.pi, math.e) * 10000)) con = WebDriver() con.get("http://suninjuly.github.io/find_link_text") con.find_element_by_partial_link_text(string).click() input1 = con.find_element_by_tag_name("input") input1.send_keys("Ivan") input2 = con.find_element_by_name("last_name") input2.send_keys("Petrov") input3 = con.find_element_by_class_name("city") input3.send_keys("Smolensk") input4 = con.find_element_by_id("country") input4.send_keys("Russia") button = con.find_element_by_css_selector("button.btn") button.click()
class Application: def __init__(self): self.wd = WebDriver() self.wd.implicitly_wait(1) def open_home_page(self): wd = self.wd wd.get(Config.main_url) def login(self, username, password): wd = self.wd self.open_home_page() username_box = wd.find_element_by_name("username") username_box.click() username_box.send_keys(username) password_box = wd.find_element_by_name("password") password_box.click() password_box.send_keys(password) wd.find_element_by_name("login").click() def get_username_from_nav_bar(self): wd = self.wd return wd.find_element_by_id("username_logged_in").text def check_is_login_available(self): wd = self.wd return wd.find_element_by_xpath("//*[@title='Login']").text == "Login" def logout(self): wd = self.wd wd.find_element_by_id("username_logged_in").click() wd.find_element_by_xpath("//*[@title='Logout']").click() def get_site_title(self): wd = self.wd return wd.title def nav_to_first_subforum(self): wd = self.wd wd.find_element_by_class_name("forumtitle").click() def nav_to_subforum_by_href(self): wd = self.wd wd.find_element_by_css_selector("a[href$='viewforum.php?f=4']").click() def enter_subforum_by_name(self, name): wd = self.wd subforums = wd.find_elements_by_class_name('forumtitle') for subforum in subforums: if subforum.text == name: subforum.click() break def create_new_topic(self, topic_title, topic_text): wd = self.wd wd.find_element_by_xpath("//a[@class='button']").click() subject_box = wd.find_element_by_id("subject") subject_box.clear() subject_box.send_keys(topic_title) message_box = wd.find_element_by_id("message") message_box.clear() message_box.send_keys(topic_text) time.sleep(1) wd.find_element_by_name("post").click() def enter_last_subject(self, topic_title): wd = self.wd last_subjects = wd.find_element_by_class_name("lastsubject") for last_subject in last_subjects: if last_subject.text == topic_title: last_subject.click() break def check_title_in_topic_titles(self, topic_title): wd = self.wd topic_titles = wd.find_elements_by_class_name("topictitle") for title in topic_titles: if title.text == topic_title: return True return False def topic_cleanup(self, topic_title): wd = self.wd elements = wd.find_elements_by_class_name("topictitle") for topic in elements: if topic.text == topic_title: topic.click() break wd.find_element_by_xpath("//*[@title='Delete post']").click() wd.find_element_by_name("delete_permanent").click() wd.find_element_by_name("confirm").click() def search_by_title(self, topic_title): wd = self.wd search_box = wd.find_element_by_id("keywords") search_box.clear() search_box.send_keys(topic_title) wd.find_element_by_xpath("//*[@title='Search']").click() def post_a_reply(self, reply): wd = self.wd wd.find_element_by_xpath("//*[@title='Post a reply']").click() message_box = wd.find_element_by_id("message") message_box.clear() message_box.send_keys(reply) time.sleep(2) wd.find_element_by_name("post").click() def get_post_content(self, reply): wd = self.wd elements = wd.find_elements_by_class_name("content") for post in elements: if post.text == reply: return post.text def post_and_topic_cleanup(self): wd = self.wd wd.find_element_by_xpath("//*[@title='Delete post']").click() wd.find_element_by_name("delete_permanent").click() wd.find_element_by_name("confirm").click() time.sleep(3) wd.find_element_by_xpath("//*[@title='Delete post']").click() wd.find_element_by_name("delete_permanent").click() wd.find_element_by_name("confirm").click() def enter_private_messages(self): wd = self.wd wd.find_element_by_id("nav-main").find_element_by_partial_link_text( "Private messages").click() def send_private_message(self, temat_wiadomosci, tresc_wiadomosci): wd = self.wd wait = self.waiter(wd) wd.find_element_by_css_selector("[accesskey='n']").click() username_box = wd.find_element_by_id("username_list") username_box.clear() username_box.send_keys(Config.username2) wd.find_element_by_name("add_to").click() subject_box = wd.find_element_by_id("subject") subject_box.clear() subject_box.send_keys(temat_wiadomosci) message_box = wd.find_element_by_id("message") message_box.clear() message_box.send_keys(tresc_wiadomosci) time.sleep(2) wd.find_element_by_css_selector(".default-submit-action").click() wait.until( expected_conditions.visibility_of_element_located( (By.CLASS_NAME, "message-title"))) def waiter(self, wd): wait = WebDriverWait(wd, 10) return wait def check_message_title(self, temat_wiadomosci): wd = self.wd topics = wd.find_elements_by_class_name("topictitle") for topic in topics: if topic.text == temat_wiadomosci: return True return False def enter_outbox(self): self.enter_priv_msg_tab("outbox") def enter_priv_msg_tab(self, name_of_tab): wd = self.wd wait = self.waiter(wd) xpath = "//a[@href='./ucp.php?i=pm&folder=%s']" % name_of_tab wait.until( expected_conditions.visibility_of_element_located( (By.XPATH, xpath))) wd.find_element_by_xpath(xpath).click() def enter_outbox_from_newly_sent_message(self): wd = self.wd wait = self.waiter(wd) wait.until( expected_conditions.visibility_of_element_located( (By.CLASS_NAME, "arrow-left"))) wd.find_element_by_class_name("arrow-left").click() def enter_sent_messages(self): self.enter_priv_msg_tab("sentbox") def check_subforum_name(self, name_of_subforum): wd = self.wd subfora = wd.find_elements_by_class_name('forum-title') for subforum in subfora: if subforum.text == name_of_subforum: return True return False def assert_if_user_in_private_messeges(self): wd = self.wd return wd.find_element_by_css_selector( "li.activetab").text == "Private messages" def check_if_user_has_opened_newly_sent_message_in_outbox(self): wd = self.wd wait = self.waiter(wd) wait.until( expected_conditions.visibility_of_element_located( (By.CLASS_NAME, "arrow-left"))) return wd.find_element_by_class_name( "arrow-left").text == 'Return to “Outbox”' def get_message_confirmation_window_title(self): wd = self.wd return wd.find_element_by_class_name( "message-title").text == "Information" def random_string(self, min_len, max_len): symbols = string.ascii_letters + string.digits + " " + string.punctuation return "".join([ random.choice(symbols) for i in range(random.randrange(min_len, max_len)) ]) def check_highlighted_topic_title(self): wd = self.wd return wd.find_element_by_css_selector(".posthilit").text == "Unikalny" def title_counter(self, temat_wiadomosci): wd = self.wd titles = wd.find_elements_by_class_name("topictitle") wanted_titles = [] for title in titles: if title.text == temat_wiadomosci: wanted_titles.append(title) return wanted_titles def check_site_title(self, site_title): wd = self.wd return wd.title def destroy(self): self.wd.quit()
def setUpClass(cls): super().setUpClass() cls.selenium = WebDriver( executable_path= 'C:/Users/hfuis/venv_private_diary/chromedriver_win32/chromedriver.exe' )
def setUpClass(cls): super().setUpClass() cls.selenium = WebDriver( executable_path='/Users/katuhitohara/katupro003/chromedriver')
class UntitledTestCase(unittest.TestCase): def setUp(self): self.driver = WebDriver() self.driver.implicitly_wait(30) self.base_url = "https://www.katalon.com/" self.verificationErrors = [] self.accept_next_alert = True def test_untitled_test_case(self): driver = self.driver driver.get("https://t-admin.ibolit.pro/login") driver.find_element_by_id("login").click() driver.find_element_by_id("login").clear() driver.find_element_by_id("login").send_keys("*****@*****.**") driver.find_element_by_id("password").click() driver.find_element_by_id("password").clear() driver.find_element_by_id("password").send_keys("123456") driver.find_element_by_xpath("//button[@type='submit']").click() driver.find_element_by_link_text(u"Пациенты").click() driver.find_element_by_link_text(u"Добавить пациента").click() driver.find_element_by_id("full_name").click() driver.find_element_by_id("full_name").clear() driver.find_element_by_id("full_name").send_keys("Patient Test Two") driver.find_element_by_id("email").click() driver.find_element_by_id("email").clear() driver.find_element_by_id("email").send_keys("*****@*****.**") driver.find_element_by_id("phone").click() driver.find_element_by_id("phone").clear() driver.find_element_by_id("phone").send_keys("89600087485") time.sleep(1) driver.find_element_by_id("password").click() driver.find_element_by_id("password").clear() driver.find_element_by_id("password").send_keys("qwerty") driver.find_element_by_id("password_confirmation").click() driver.find_element_by_id("password_confirmation").clear() driver.find_element_by_id("password_confirmation").send_keys("qwerty") driver.find_element_by_id("select2-doctor-container").click() time.sleep(1) driver.find_element_by_xpath( "/html[1]/body[1]/span[1]/span[1]/span[2]/ul[1]/li[8]").click() driver.find_element_by_id("comment").click() driver.find_element_by_id("comment").clear() driver.find_element_by_id("comment").send_keys( "тестовые комментарии о пациенте ") driver.find_element_by_xpath("//button[@type='submit']").click() driver.find_element_by_xpath("//i").click() driver.find_element_by_link_text(u"Выйти").click() def is_element_present(self, how, what): try: self.driver.find_element(by=how, value=what) except NoSuchElementException as e: return False return True def is_alert_present(self): try: self.driver.switch_to_alert() except NoAlertPresentException as e: return False return True def close_alert_and_get_its_text(self): try: alert = self.driver.switch_to_alert() alert_text = alert.text if self.accept_next_alert: alert.accept() else: alert.dismiss() return alert_text finally: self.accept_next_alert = True
import os import time from pprint import pprint from selenium.webdriver.chrome.webdriver import WebDriver from selenium.webdriver.support.ui import Select BASE_DIR = os.path.dirname(__file__) # Create a new instance of the Google driver executable_path = os.path.join(BASE_DIR, 'drivers', 'chromedriver') driver = WebDriver(executable_path=executable_path) # go to the google home page driver.get('https://www.google.com') # find the element that's name attribute is lst-ib (the google search box) search = driver.find_element_by_id('lst-ib') search.send_keys('Hillsong') search.submit() # find the elements that's names attributes are r (the google search box) related_search = driver.find_elements_by_class_name('r') # running script from python with selenium to javascript driver.execute_script("console.log('Hello from python to js')") # search all the links that contain the word Church links = driver.find_elements_by_partial_link_text('Church') pprint([item.text for item in links])
def setUp(self): self.driver = WebDriver() self.driver.implicitly_wait(30) self.base_url = "https://www.katalon.com/" self.verificationErrors = [] self.accept_next_alert = True
def execute(self, driver: WebDriver) -> None: driver.save_screenshot(self.file_name) self.logger.debug('[MakeScreen] %s', self.file_name)
def __init__(self): self.wd = WebDriver() self.wd.implicitly_wait(5) self.session = SessionHelper(self) self.group = GroupHelper(self) self.contact = ContactHelper(self)
class MailingListIntegrationTestCase(LiveServerTestCase): def setUp(self): # Create MailingList (newsletter) object self.mailing_list_1 = MailingList.objects.create( mailing_list_name="news1", mailing_list_token="token1", list_active=True, ) self.mailing_list_2 = MailingList.objects.create( mailing_list_name="news2", mailing_list_token="token2", contact_frequency_weeks=4, list_active=True, ) # Create MailingList (petition) object self.mailing_list_3 = MailingList.objects.create( mailing_list_name="petition1", mailing_list_token="token3", list_active=True, is_petition=True, ) self.mailing_list_4 = MailingList.objects.create( mailing_list_name="petition2", mailing_list_token="token4", list_active=True, is_petition=True, ) # Create two Petition (petition) object self.petition_1 = Petition.objects.create( mailing_list=self.mailing_list_3, slug="slug1", petition1_md="First sentence", ) self.petition_2 = Petition.objects.create( mailing_list=self.mailing_list_4, slug="slug2", petition1_md="First sentence 2", ) self.user = User.objects.create_user(username='******', password='******', email="*****@*****.**") self.user.save() self.logged_client = Client() self.logged_client.login(username='******', password='******') self.superuser = \ User.objects.create_superuser(username='******', password='******', email="*****@*****.**") self.superuser.save() self.admin_client = Client() self.admin_client.login(username='******', password='******') # Create a topicblog page for testing quick sign up self.home = TopicBlogItem.objects.create( slug="home", date_modified=datetime.now(timezone.utc), publication_date=datetime.now(timezone.utc), first_publication_date=datetime.now(timezone.utc), user=self.superuser, template_name="topicblog/content.html", title="home-title") # Create the default mailing list self.mailing_list_default = MailingList.objects.create( mailing_list_name="general-quarterly", mailing_list_token="general-quarterly", contact_frequency_weeks=12, list_active=True, ) # Create MailingListEvent object self.mailing_event_1 = MailingListEvent.objects.create( user=self.user, mailing_list=self.mailing_list_1, event_type=MailingListEvent.EventType.SUBSCRIBE) self.mailing_event_2 = MailingListEvent.objects.create( user=self.superuser, mailing_list=self.mailing_list_2, event_type=MailingListEvent.EventType.SUBSCRIBE) self.cookie_user = self.logged_client.cookies['sessionid'].value self.cookie_staff = \ self.admin_client.cookies['sessionid'].value options = Options() options.add_argument("--headless") options.add_argument("--disable-extensions") self.selenium = WebDriver(ChromeDriverManager().install(), options=options) self.selenium.implicitly_wait(5) def tearDown(self): # Close the browser self.selenium.quit() # def testing_quick_form_logged_out(self): # self.selenium.get('%s%s' % (self.live_server_url, # reverse("topicblog:view_item_by_slug", # kwargs={ # "the_slug": self.home.slug # }))) # email_input = self.selenium.find_element_by_id("id_email") # email_input.send_keys("*****@*****.**") # self.selenium.find_element_by_css_selector( # "form button[type=submit]").click() # # pass the captcha only work on dev mod # captcha_input = self.selenium.find_element_by_id("id_captcha_1") # captcha_input.send_keys("PASSED") # self.selenium.find_element_by_css_selector( # "form button[type=submit]").click() # user = User.objects.filter(email="*****@*****.**").first() # self.assertIsNotNone( # user, # msg="The user was not created during mailing list signup") # mailing_list_event = MailingListEvent.objects.filter(user=user).first() # self.assertIsNotNone(mailing_list_event, # msg="The mailing event is not created" # "on quick sign up") # self.assertEqual( # mailing_list_event.event_type, "sub", # msg="The user is not subscribed to the default mailing list") def testing_quick_form_logged_in(self): # Get on mobilitains website self.selenium.get('%s%s' % (self.live_server_url, reverse("topicblog:view_item_by_slug", kwargs={ "the_slug": self.home.slug }))) # Add a session cookie to the browser (refused if not already on the # website) self.selenium.add_cookie( {'name': 'sessionid', 'value': self.cookie_user, 'secure': False, 'path': '/'}) # Refresh the page to get the proper display self.selenium.refresh() # because we're already logged in, we're subbed to the default # list without captcha self.selenium.find_element_by_css_selector( "form button[type=submit]").click() # We wait until next page is loaded (confirmation page) WebDriverWait(self.selenium, 5).until( EC.url_contains(reverse("mailing_list:quick_signup")) ) # We used the self.user's cookie to connect to the website user = User.objects.filter(email=self.user.email).first() self.assertIsNotNone( user, msg="The user created during setUp does not exist") mailing_list_event = MailingListEvent.objects.filter(user=user).first() self.assertIsNotNone(mailing_list_event, msg="The mailing event was not created " "on quick sign up") self.assertEqual(mailing_list_event.event_type, "sub", msg="The user is not sub on the default mailing list") # def testing_quick_form_fail_captcha_logged_out(self): # self.selenium.get('%s%s' % (self.live_server_url, # reverse("topicblog:view_item_by_slug", # kwargs={ # "the_slug": self.home.slug # }))) # email_input = self.selenium.find_element_by_id("id_email") # email_input.send_keys("*****@*****.**") # self.selenium.find_element_by_css_selector( # "form button[type=submit]").click() # # fail the capcha # captcha_input = self.selenium.find_element_by_id("id_captcha_1") # captcha_input.send_keys("Notgood") # self.selenium.find_element_by_css_selector( # "form button[type=submit]").click() # # pass the captcha only work on dev mod # captcha_input = self.selenium.find_element_by_id("id_captcha_1") # captcha_input.send_keys("PASSED") # self.selenium.find_element_by_css_selector( # "form button[type=submit]").click() # user = User.objects.filter(email="*****@*****.**").first() # self.assertIsNotNone(user, # msg="The user is not created on quick sign up") # mailing_list_event = MailingListEvent.objects.filter(user=user).first() # self.assertIsNotNone(mailing_list_event, # msg="The mailing event is not created" # "on quick sign up") # self.assertEqual(mailing_list_event.event_type, "sub", # msg="The user is not sub on the default mailing list") # def testing_quick_form_fail_captcha_logged_in(self): # self.selenium.get('%s%s' % (self.live_server_url, # reverse("topicblog:view_item_by_slug", # kwargs={ # "the_slug": self.home.slug # }))) # email_input = self.selenium.find_element_by_id("id_email") # email_input.send_keys("*****@*****.**") # self.selenium.find_element_by_css_selector( # "form button[type=submit]").click() # # fail the capcha # captcha_input = self.selenium.find_element_by_id("id_captcha_1") # captcha_input.send_keys("Notgood") # self.selenium.find_element_by_css_selector( # "form button[type=submit]").click() # # pass the captcha only work on dev mod # captcha_input = self.selenium.find_element_by_id("id_captcha_1") # captcha_input.send_keys("PASSED") # self.selenium.find_element_by_css_selector( # "form button[type=submit]").click() # user = User.objects.filter(email="*****@*****.**").first() # self.assertIsNotNone(user, # msg="The user is not created on quick sign up") # mailing_list_event = MailingListEvent.objects.filter(user=user).first() # self.assertIsNotNone(mailing_list_event, # msg="The mailing event is not created" # "on quick sign up") # self.assertEqual(mailing_list_event.event_type, "sub", # msg="The user is not sub on the default mailing list") def testing_acces_with_get_to_the_quick_form(self): quick_signup_url = reverse("mailing_list:quick_signup") self.selenium.get(f"{self.live_server_url}{quick_signup_url}") index_url = f"{self.live_server_url}{reverse('index')}#newsletter" self.assertEqual(self.selenium.current_url, index_url, msg="User SHOULD be redirect to index page") def testing_user_status_page_subscribe_to_newsletter(self): old_event = user_current_state(self.user, self.mailing_list_2) self.assertEqual(old_event.event_type, "unsub") user_status_url = reverse("mailing_list:user_status") self.selenium.get(f"{self.live_server_url}{user_status_url}") self.selenium.add_cookie( {'name': 'sessionid', 'value': self.cookie_user, 'secure': False, 'path': '/'}) self.selenium.get(f"{self.live_server_url}{user_status_url}") self.selenium.find_element_by_css_selector( f"#id-ml-{self.mailing_list_2.id} form button[type=submit]" ).click() a_html = \ self.selenium.find_element_by_css_selector( f"#id-ml-{self.mailing_list_2.id} div a").get_attribute( 'innerHTML') new_event = user_current_state(self.user, self.mailing_list_2) # Check if the event is updated self.assertEqual(new_event.event_type, "sub", msg="The event was not updated") self.assertEqual(a_html, "Se désabonner", msg="The page is not updated") def testing_user_status_page_unsubscribe_to_newsletter(self): old_event = user_current_state(self.user, self.mailing_list_1) self.assertEqual(old_event.event_type, "sub") user_status_url = reverse("mailing_list:user_status") self.selenium.get(f"{self.live_server_url}{user_status_url}") self.selenium.add_cookie( {'name': 'sessionid', 'value': self.cookie_user, 'secure': False, 'path': '/'}) self.selenium.get(f"{self.live_server_url}{user_status_url}") self.selenium.find_element_by_css_selector( f"#id-ml-{self.mailing_list_1.id} a").click() self.selenium.find_element_by_css_selector( "form button[type=submit]").click() button_html = self.selenium.find_element_by_css_selector( f"#id-ml-{self.mailing_list_1.id} div button").get_attribute( 'innerHTML') new_event = user_current_state(self.user, self.mailing_list_2) # Check if the event is updated self.assertEqual(new_event.event_type, "unsub", msg="The event was not updated") self.assertEqual(button_html, "S'abonner", msg="The page was not updated")
class TestsTopicItemForm(LiveServerTestCase): def setUp(self): # all permission edit_permission = Permission.objects.get(codename="tbi.may_edit") view_permission = Permission.objects.get(codename="tbi.may_view") publish_permission = Permission.objects.get(codename="tbi.may_publish") publish_self_permission = Permission.objects.get( codename="tbi.may_publish_self") # Create a user with all permission self.user = User.objects.create_user(username='******', password='******') self.user.user_permissions.add( edit_permission, view_permission, publish_permission, publish_self_permission, ) self.user.is_staff = True self.user.is_superuser = True self.user.save() # Create a user that cant self publish editor 1 self.user_editor = User.objects.create_user(username='******', password='******') self.user_editor.user_permissions.add( edit_permission, view_permission, publish_permission, ) self.user_editor.is_staff = True self.user_editor.save() # Create a user that cant self publish editor 2 self.user_editor_two = User.objects.create_user(username='******', password='******') self.user_editor_two.user_permissions.add( edit_permission, view_permission, publish_permission, ) self.user_editor_two.is_staff = True self.user_editor_two.save() # Create client for user self.user_editor_client = Client() self.user_editor_two_client = Client() # Log user into the client self.client.login(username='******', password='******') self.user_editor_client.login(username='******', password='******') self.user_editor_two_client.login(username='******', password='******') # Take the session id cookie for log into selenium self.cookie_admin = self.client.cookies['sessionid'].value self.cookie_editor = self.user_editor_client.cookies['sessionid'].value self.cookie_editor_two = ( self.user_editor_two_client.cookies['sessionid'].value) """ Launch the browser the path of the browser will be auto added with the webdriver_manager package and wait 10 sec """ options = Options() options.add_argument("--headless") options.add_argument("--disable-extensions") self.selenium = WebDriver(ChromeDriverManager().install(), options=options) self.selenium.implicitly_wait(5) def tearDown(self): # Close the browser self.selenium.quit() def fill_the_form_and_publish(self, slug, title, body_1="body 1", body_2="body 2", body_3="body 3", edit=False): """Fill the topicblog item form and publish """ if not edit: slug_input = self.selenium.find_element_by_name("slug") slug_input.send_keys(slug) title_input = self.selenium.find_element_by_name("title") title_input.clear() title_input.send_keys(title) select = Select(self.selenium.find_element_by_name("template")) select.select_by_value("topicblog/content.html") self.selenium.find_element_by_link_text("Contenu (1)").click() body_text_1_md_input = self.selenium.find_element_by_id( "id_body_text_1_md") body_text_1_md_input.clear() body_text_1_md_input.send_keys(body_1) body_text_2_md_input = self.selenium.find_element_by_id( "id_body_text_2_md") body_text_2_md_input.clear() body_text_2_md_input.send_keys(body_2) self.selenium.find_element_by_link_text("Contenu (2)").click() body_text_3_md_input = self.selenium.find_element_by_id( "id_body_text_3_md") body_text_3_md_input.clear() body_text_3_md_input.send_keys(body_3) self.selenium.find_element_by_name("sauvegarder").click() self.selenium.find_element_by_xpath( "//input[@value='Publier']").click() def test_user_permited_create_auto_publish(self): self.selenium.get( '%s%s' % (self.live_server_url, reverse("topic_blog:new_item"))) self.selenium.add_cookie({ 'name': 'sessionid', 'value': self.cookie_admin, 'secure': False, 'path': '/' }) self.selenium.get( '%s%s' % (self.live_server_url, reverse("topic_blog:new_item"))) self.fill_the_form_and_publish("test-slug-staff", "title item") item_staff = TopicBlogItem.objects.filter(slug="test-slug-staff")[0] self.assertIsNotNone(item_staff, msg="The item created by the super user" " is not in the database") # Go to the user view self.selenium.find_element_by_link_text("Visualiser (usager)").click() """Get the body innerHTML and check if this is what we send in the form """ body_app_content = self.selenium.find_element_by_id("app_content") body_html = body_app_content.get_attribute('innerHTML') self.assertHTMLEqual(body_html, "<p>body 1</p><p>body 2</p><p>body 3</p>", msg="The body innerHTML is not the same" " as what we send to the form") def test_editor_create_item_but_cant_publish(self): self.selenium.get( '%s%s' % (self.live_server_url, reverse("topic_blog:new_item"))) self.selenium.add_cookie({ 'name': 'sessionid', 'value': self.cookie_editor, 'secure': False, 'path': '/' }) self.selenium.get( '%s%s' % (self.live_server_url, reverse("topic_blog:new_item"))) slug = 'test-slug-editor' self.fill_the_form_and_publish(slug, 'title item') # Check if the item is on the databse and the publication should equal to none. item_editor = TopicBlogItem.objects.filter(slug="test-slug-editor")[0] self.assertIsNotNone(item_editor, msg="The item created by the editor" " is not in the database") self.assertIsNone(item_editor.publication_date, msg="The publication date is not none") # Check if the user get the 403 Forbidden body = self.selenium.find_element_by_tag_name("body") body_html = body.get_attribute('innerHTML') self.assertHTMLEqual(body_html, "<h1>403 Forbidden</h1><p></p>", msg="User can't self publish") # Check the user view self.selenium.get('%s%s' % (self.live_server_url, reverse("topic_blog:view_item_by_slug", kwargs={"the_slug": slug}))) """Get the body innerHTML and check if this is not found because this is not published """ body_view = self.selenium.find_element_by_tag_name("body") body_view_html = body_view.get_attribute('innerHTML') self.assertHTMLEqual( body_view_html, "<h1>Not Found</h1><p>The requested resource " "was not found on this server.</p>") def test_editor_create_and_another_publish(self): # Create an item with the first editor that is not published self.item = TopicBlogItem.objects.create( slug="test-slug", user=self.user_editor, template_name="topicblog/content.html", body_text_1_md="body 1", body_text_2_md="body 2", body_text_3_md="body 3", title="Test-title") self.selenium.get( '%s%s' % (self.live_server_url, reverse("topic_blog:new_item"))) self.selenium.add_cookie({ 'name': 'sessionid', 'value': self.cookie_editor_two, 'secure': False, 'path': '/' }) # Go to the admin view of the item that the first editor as created self.selenium.get('%s%s' % (self.live_server_url, reverse("topic_blog:view_item_by_pkid", kwargs={ "pkid": self.item.id, "the_slug": self.item.slug, }))) self.selenium.find_element_by_xpath( "//input[@value='Publier']").click() item_editor = TopicBlogItem.objects.filter(slug="test-slug")[0] # Check if publication date and first publication date is NOT none self.assertIsNotNone(item_editor.publication_date, msg="The publication date should not be none") self.assertIsNotNone(item_editor.first_publication_date, msg="The first publication date" "should not be none") # Check the user view self.selenium.find_element_by_link_text("Visualiser (usager)").click() """Get the body innerHTML and check if this is what we send in the form """ body_app_content = self.selenium.find_element_by_id("app_content") body_html = body_app_content.get_attribute('innerHTML') self.assertHTMLEqual(body_html, "<p>body 1</p><p>body 2</p><p>body 3</p>", msg="The body innerHTML is not the same" " as what we send to the form") def test_edit_and_self_publish(self): self.selenium.get( '%s%s' % (self.live_server_url, reverse("topic_blog:new_item"))) self.selenium.add_cookie({ 'name': 'sessionid', 'value': self.cookie_admin, 'secure': False, 'path': '/' }) self.selenium.get( '%s%s' % (self.live_server_url, reverse("topic_blog:new_item"))) self.fill_the_form_and_publish(slug="test-edited", title="title-edit") # Go to the edit view self.selenium.find_element_by_link_text("Modifier").click() self.fill_the_form_and_publish(slug="", title="new title edited", body_1="new setence 1", body_2="new setence 2", body_3="new setence 3") # Check if the new title is on the database item_edited = TopicBlogItem.objects.filter(title="new title edited")[0] self.assertIsNotNone(item_edited, msg="The item edited by the staff" " is not in the database") # Go to the user view self.selenium.find_element_by_link_text("Visualiser (usager)").click() """Get the body innerHTML and check if this is what we send in the form """ body_app_content = self.selenium.find_element_by_id("app_content") body_html = body_app_content.get_attribute('innerHTML') self.assertHTMLEqual( body_html, "<p>new setence 1</p><p>new setence 2</p><p>new setence 3</p>", msg="The body innerHTML is not the same" " as what we send to the form") def test_publish_an_unpublishable_item(self): self.selenium.get( '%s%s' % (self.live_server_url, reverse("topic_blog:new_item"))) self.selenium.add_cookie({ 'name': 'sessionid', 'value': self.cookie_admin, 'secure': False, 'path': '/' }) self.selenium.get( '%s%s' % (self.live_server_url, reverse("topic_blog:new_item"))) slug_input = self.selenium.find_element_by_name("slug") slug_input.send_keys("unpublishable") select = Select(self.selenium.find_element_by_name("template")) select.select_by_value("topicblog/content.html") self.selenium.find_element_by_name("sauvegarder").click() # Check if the item is on the databse and get the data for faking the publish item_unpublishable = TopicBlogItem.objects.filter( slug="unpublishable")[0] self.assertIsNotNone(item_unpublishable, msg="The item created by the staff" " is not in the database") # testing with the unpublishable item of the staff response_0 = self.client.post( reverse("topicblog:view_item_by_pkid", kwargs={ "pkid": item_unpublishable.id, "the_slug": item_unpublishable.slug })) self.assertEqual(response_0.status_code, 500, msg="try to pubilsh unpublishable item should return" "HttpResponseServerError(code 500)")
def __init__(self): self.wd = WebDriver() self.wd.implicitly_wait(60) self.session = SessionHelper(self) self.mail = MailHelper(self)
def setUp(self): # all permission edit_permission = Permission.objects.get(codename="tbi.may_edit") view_permission = Permission.objects.get(codename="tbi.may_view") publish_permission = Permission.objects.get(codename="tbi.may_publish") publish_self_permission = Permission.objects.get( codename="tbi.may_publish_self") # Create a user with all permission self.user = User.objects.create_user(username='******', password='******') self.user.user_permissions.add( edit_permission, view_permission, publish_permission, publish_self_permission, ) self.user.is_staff = True self.user.is_superuser = True self.user.save() # Create a user that cant self publish editor 1 self.user_editor = User.objects.create_user(username='******', password='******') self.user_editor.user_permissions.add( edit_permission, view_permission, publish_permission, ) self.user_editor.is_staff = True self.user_editor.save() # Create a user that cant self publish editor 2 self.user_editor_two = User.objects.create_user(username='******', password='******') self.user_editor_two.user_permissions.add( edit_permission, view_permission, publish_permission, ) self.user_editor_two.is_staff = True self.user_editor_two.save() # Create client for user self.user_editor_client = Client() self.user_editor_two_client = Client() # Log user into the client self.client.login(username='******', password='******') self.user_editor_client.login(username='******', password='******') self.user_editor_two_client.login(username='******', password='******') # Take the session id cookie for log into selenium self.cookie_admin = self.client.cookies['sessionid'].value self.cookie_editor = self.user_editor_client.cookies['sessionid'].value self.cookie_editor_two = ( self.user_editor_two_client.cookies['sessionid'].value) """ Launch the browser the path of the browser will be auto added with the webdriver_manager package and wait 10 sec """ options = Options() options.add_argument("--headless") options.add_argument("--disable-extensions") self.selenium = WebDriver(ChromeDriverManager().install(), options=options) self.selenium.implicitly_wait(5)
def setUpClass(cls): super().setUpClass() cls.selenium = WebDriver() cls.selenium.implicitly_wait(10)
def extract_recording_metadata( recording_boxes: List[WebElement], driver: WebDriver, old_metadata: List[Dict[str, Any]], download_duplicates: bool, ) -> Tuple[List[Dict[str, Any]], List[int]]: """ For each recording, extracts the message text, date of message, time of message, device on which the message was sent, and the div_id which acts as a unique identifier for each recording. :param recording_boxes: :param driver: :param old_metadata: :param download_duplicates: :return: Outputs a tuple of two things: [0]: A list of all of the metadata for all of the recordings. [1]: A list of indices of which recordings need to be downloaded (and which can be skipped). """ print_log("Extracting the metadata from each recording: ") recording_metadata = [] indices_to_download = [] num_recordings = len(recording_boxes) print_log(f"Total recordings: {num_recordings}.") num_skipped_recordings = 0 for i, recording_box in enumerate(recording_boxes): box_div_id = recording_box.get_property("id") # Skip this recording if it is already documented. if download_duplicates is False: old_metadata_info = find_div_id_in_metadata( box_div_id, old_metadata) if old_metadata_info is not None: recording_metadata.append(old_metadata_info) print_log(f"Skipping recording #{i + 1}.") continue print_log(f"Working on recording #{i + 1}.") recording_date = "" recording_time = "" recording_device = "" message_div = recording_box.find_elements_by_xpath( ".//div[@class='record-summary-preview customer-transcript']") if len(message_div) == 0: audio_not_understood_msg = recording_box.find_elements_by_xpath( ".//div[@class='record-summary-preview replacement-text']") if len(audio_not_understood_msg) == 0: print_log( "Cannot seem to find the transcription of the recording. Going to skip this recording." ) num_skipped_recordings += 1 continue else: message_div = audio_not_understood_msg recording_text = message_div[0].text date_time_info = recording_box.find_elements_by_xpath( ".//div[@class='item']") if len(date_time_info) < 3: print_log( "ERROR: The recording div does not seem to have ALL of the following info: " "Date, Time, and device. Going to error out.") raise_exception( NoSuchElementException( "The recording div does not have all the necessary " "metadata for extraction, or the page layout has changed." ), driver, ) else: recording_date = date_time_info[0].text recording_time = date_time_info[1].text recording_device = date_time_info[2].text metadata = { "message": recording_text, "date": recording_date, "time": recording_time, "device": recording_device, "div_id": box_div_id, } recording_metadata.append(metadata) indices_to_download.append(i - num_skipped_recordings) # Open box for audio ID extraction later expand_button_list = recording_box.find_elements_by_xpath(".//button") if len(expand_button_list) == 0: print_log( "ERROR: The script cannot find the button to expand the recording box. This means that " "this recording cannot be extracted (but the metadata can still be)." ) else: expand_button_list[0].click() driver.implicitly_wait(1) time.sleep(1) return recording_metadata, indices_to_download
def test_fixture_pytest(driver: WebDriver): print('start test method invocation') driver.get('http://google.com') time.sleep(3) print('stop test method invocation')
class KelaStatementFunctionalTest(MyLiveServerTestCase): def setUp(self): self.driver = WebDriver() self.url = self.live_server_url user = UserFactory.create(username = "******", password = "******", is_active = True) g = Group.objects.get_or_create(name=u'therapist') user.groups.add(g[0].pk) CompanyProfileFactory.create_batch(1) KelaContactProfileFactory.create_batch(1) SessionDoneFactory.create_batch(1) def test_user_can_login(self): """ :return: """ # load the customer list page self.driver.get(self.url) mainpage = MainPageAnonymousUsers(self.driver) assert mainpage.is_menu_dropdown_visible(), "menu dropdown is not visible" mainpage.click_menu_dropdown() assert mainpage.is_login_navitem_visible(), "login navitem is not visible" mainpage.click_login_navitem() #login user login_page = LoginPage(self.driver) assert login_page.is_username_field(), "username field is not visible" assert login_page.is_password_field(), "password field is not visible" assert login_page.is_signin_button(), "signin button is not visible" login_page.set_username_password() login_page.click_signin_button() def test_can_create_kelastatement(self): """ Test creating new customer :return: """ self.driver.get(self.url) mainpageanonymous = MainPageAnonymousUsers(self.driver) assert mainpageanonymous.is_menu_dropdown_visible(), "menu dropdown is not visible" mainpageanonymous.click_menu_dropdown() assert mainpageanonymous.is_login_navitem_visible(), "login navitem is not visible" mainpageanonymous.click_login_navitem() login_page = LoginPage(self.driver) assert login_page.is_username_field(), "username field is not visible" assert login_page.is_password_field(), "password field is not visible" assert login_page.is_signin_button(), "signin button is not visible" login_page.set_username_password() login_page.click_signin_button() mainpageloggedin = MainPageLoggedInUsers(self.driver) assert mainpageloggedin.is_menu_dropdown_visible(), "menu dropdown is not visible" mainpageloggedin.click_menu_dropdown() assert mainpageloggedin.is_kelainvoicing_navitem_visible(), "kelastatement link is not visible" mainpageloggedin.click_kelainvoicing_navitem() # kelastatement_list page kelastatementlist_page = KelaStatementListPage(self.driver) assert kelastatementlist_page.is_kelastatement_create_button_visible(), "kelastatment create button is not visible" kelastatementlist_page.click_kelastatement_create_button() # customer_form page kelastatementcreate_page = KelaStatementFormPage(self.driver) assert kelastatementcreate_page.is_date_field_visible(), "date field is not visible" assert kelastatementcreate_page.is_companyname_field_visible(), "companyname field is not visible" assert kelastatementcreate_page.is_firstname_field_visible(), "firstname field is not visible" assert kelastatementcreate_page.is_lastname_field_visible(), "lastname field is not visible" assert kelastatementcreate_page.is_address_field_visible(), "address field is not visible" assert kelastatementcreate_page.is_zipcode_field_visible(), "zipcode field is not visible" assert kelastatementcreate_page.is_city_field_visible(), "city field is not visible" assert kelastatementcreate_page.is_telephone_field_visible(), "telephone field is not visible" assert kelastatementcreate_page.is_email_field_visible(), "email field is not visible" assert kelastatementcreate_page.is_save_button_visible(), "save button field is not visible" kelastatementcreate_page.set_kelastatement_fields() kelastatementcreate_page.click_save_button() kelastatementdetail_page = KelaStatementDetailPage(self.driver) assert kelastatementdetail_page.is_kelastatment_list_button_visible(), "kelastatement list button is not visible" kelastatementdetail_page.click_kelastatement_list_button() # kelastatement_list page kelastatementlist_page = KelaStatementListPage(self.driver) assert kelastatementlist_page.is_kelastatement_create_button_visible(), "kelastatment create button is not visible"