def test_create_page_uses_page_rank(self): self.driver = WTF_WEBDRIVER_MANAGER.new_driver( "TestPageFactory.test_create_page_uses_page_rank") self.driver.get("http://www.google.com") google_page = PageFactory.create_page( [GoogleSearch, GoogleSearch2], self.driver) self.assertTrue(isinstance(google_page, GoogleSearch2))
def tearDown(self): "This tear down will close the current allocated webdriver" # do_and_ignore() is a handle wrapper that let's you run a statement # and not care if it errors or not. This is helpful for tearDown # routines where the success/failure is not part of the test result. do_and_ignore(lambda: WTF_WEBDRIVER_MANAGER.close_driver())
def __init__(self, webdriver=None, max_time=WTF_TIMEOUT_MANAGER.EPIC, sleep=5, **kwargs): """ Constructor Kwargs: webdriver (WebDriver) - Selenium Webdriver instance max_time (number) - Maximum wait time to keep the browser on stand by. sleep (number) - Number of seconds to wait between sending heart beats. """ if webdriver is None: webdriver = WTF_WEBDRIVER_MANAGER.get_driver() self.webdriver = webdriver self._sleep_time = sleep self._max_time = max_time # This is used by the shortcut method 'start_standby', which is used # with the 'with' statement. self._autostart = False try: if kwargs['_autostart']: self._autostart = True except KeyError: pass
def test_wait_for_page_loads_times_out_on_bad_page(self): self.driver = WTF_WEBDRIVER_MANAGER.new_driver( "TestPageUtils.test_wait_for_page_loads_times_out_on_bad_page") self.driver.get("http://www.yahoo.com") self.assertRaises(PageLoadTimeoutError, page.PageUtils.wait_until_page_loaded, GoogleSearch, self.driver, 1)
def test_create_page_handles_pageobject_with_no_validation(self): self.driver = WTF_WEBDRIVER_MANAGER.new_driver( "TestPageFactory.test_create_page_handles_pageobject_with_no_validation") self.assertRaises(TypeError, PageFactory.create_page, ValidateNotImplementedPageObject, self.driver)
def test_create_page_with_list(self): self.driver = WTF_WEBDRIVER_MANAGER.new_driver("TestPageFactor.test_create_page_with_list") self.driver.get("http://www.google.com") google = PageFactory.create_page([GoogleSearch, YahooSearch], self.driver) self.assertTrue(type(google) == GoogleSearch) self.driver.get("http://www.yahoo.com") yahoo = PageFactory.create_page([GoogleSearch, YahooSearch], self.driver) self.assertTrue(type(yahoo) == YahooSearch)
def create_page(cls, webdriver=None, **kwargs): """ Class method short cut to call PageFactory on itself. @param webdriver: WebDriver to associate with this page. @type webdriver: WebDriver """ if not webdriver: webdriver = WTF_WEBDRIVER_MANAGER.get_driver() return PageFactory.create_page(cls, webdriver=webdriver, **kwargs)
def test_create_page_createsPageWhenExists(self): self.driver = WTF_WEBDRIVER_MANAGER.new_driver( "TestPageFactory.test_create_page_createsPageWhenExists") self.driver.get("http://www.google.com") google = PageFactory.create_page(SearchPage, self.driver) self.assertTrue(type(google) == GoogleSearch) self.driver.get("http://www.yahoo.com") yahoo = PageFactory.create_page(SearchPage, self.driver) self.assertTrue(type(yahoo) == YahooSearch)
def test_using_flows(self): """ Demonstrate abstracting out several steps into 1 call into a flow Let's say we have 2 or 3 steps that are repeated over and over again. Then it's a good idea to make it a workflow ('flow'), that can be reused between different tests. """ webdriver = WTF_WEBDRIVER_MANAGER.new_driver() search_page = perform_search("hello world", webdriver) self.assertTrue(search_page.result_contains("hello world"))
def test_create_page_with_list(self): self.driver = WTF_WEBDRIVER_MANAGER.new_driver( "TestPageFactor.test_create_page_with_list") self.driver.get("http://www.google.com") google = PageFactory.create_page([GoogleSearch, YahooSearch], self.driver) self.assertTrue(type(google) == GoogleSearch) self.driver.get("http://www.yahoo.com") yahoo = PageFactory.create_page([GoogleSearch, YahooSearch], self.driver) self.assertTrue(type(yahoo) == YahooSearch)
def test_createPage_createsPageFromFactory(self): # Mock a webdriver that looks like it's viewing yahoo config_reader = mock() when(config_reader).get("selenium.take_reference_screenshot", False).thenReturn(False) self.driver = WTF_WEBDRIVER_MANAGER.new_driver("TestPageObject.test_createPage_createsPageFromFactory") self.driver.get("http://www.google.com") google = SearchPage.create_page(self.driver, config_reader=config_reader) self.assertTrue(type(google) == GoogleSearch) self.driver.get("http://www.yahoo.com") yahoo = SearchPage.create_page(self.driver, config_reader=config_reader) self.assertTrue(type(yahoo) == YahooSearch)
def test_example_using_abstract_interfaces(self): "Demonstrates creating PageObjects using Abstract Factory pattern." webdriver = WTF_WEBDRIVER_MANAGER.new_driver() webdriver.get("http://www.google.com") # Notice I don't need specify GoogleSearchPage specifically, and # able to construct a ISearchPage of the correct type. search_page = PageFactory.create_page(ISearchPage, webdriver) self.assertEqual(GoogleSearchPage, type(search_page)) webdriver.get("http://www.yahoo.com") search_page = PageFactory.create_page(ISearchPage, webdriver) self.assertEqual(YahooSearchPage, type(search_page))
def wait_until_page_loaded(page_obj_class, webdriver=None, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5, bad_page_classes=[], **kwargs): """ Waits until the page is loaded. Usage Example: webdriver.get("http://www.mysite.com/login") # Wait up to 60 seconds for the page to load. login_page = wait_until_page_loaded(LoginPage, timeout=60) @return: Returns PageObject of type passed in. @rtype: PageObject """ if not webdriver: webdriver = WTF_WEBDRIVER_MANAGER.get_driver() #convert this param to list if not already. if type(bad_page_classes) != list: bad_page_classes = [bad_page_classes] end_time = datetime.now() + timedelta(seconds=timeout) last_exception = None while datetime.now() < end_time: # Check to see if we're at our target page. try: page = PageFactory.create_page(page_obj_class, webdriver=webdriver, **kwargs) PageUtils.wait_until_page_ready(page) return page except Exception as e: last_exception = e pass # Check to see if we're at one of those labled 'Bad' pages. for bad_page_class in bad_page_classes: try: PageFactory.create_page(bad_page_class, webdriver=webdriver, **kwargs) #if the if/else statement succeeds, than we have an error. raise BadPageEncounteredError("Encountered a bad page. " + bad_page_class.__name__) except BadPageEncounteredError as e: raise e except: pass #We didn't hit a bad page class yet. #sleep till the next iteration. time.sleep(sleep) print "Unable to construct page, last exception", last_exception raise PageLoadTimeoutError("Timedout while waiting for {page} to load. Url:{url}". \ format(page=PageUtils.__get_name_for_class__(page_obj_class), url=webdriver.current_url))
def test_home_page_basic(self): webdriver = WTF_WEBDRIVER_MANAGER.new_driver() webdriver.get(ConfigReader('site_credentials').get("default_url")) home_page = PageFactory.create_page(HomePage, webdriver) home_page.search_for_what(u"Бар") home_page.search_for_where(u"Москва") home_page.click_search_button() webdriver.implicitly_wait(3000) results_list_page = PageFactory.create_page(ResultsList, webdriver) self.assertEqual(webdriver.title, "Localway") category = results_list_page.category_filter_list() category_path = PageUtils.get_element_xpath(category) print category_path print('test ok')
def test_capture_file_created_and_valid_png(self): self.driver = WTF_WEBDRIVER_MANAGER.new_driver("TestPageUtils.test_capture_file_created_and_valid_png") self.driver.get("http://www.yahoo.com") fname = "test" prj_root = ProjectUtils.get_project_root() fpath = os.path.join(prj_root, WebScreenShotUtil.SCREEN_SHOT_LOCATION, fname + ".png") try: WebScreenShotUtil.take_screenshot(self.driver, fname) self.assertTrue(os.path.isfile(fpath)) self.assertEquals(imghdr.what(fpath), "png") finally: try: os.remove(fpath) except OSError: pass
def test_wait_for_page_to_load(self): self.driver = WTF_WEBDRIVER_MANAGER.new_driver("TestPageUtils.test_wait_for_page_to_load") start_time = datetime.now() # create a separate thread to load yahoo 10 seconds later. t = threading.Thread(target=self.__load_google_later) t.start() self.page_obj = page.PageUtils.wait_until_page_loaded(GoogleSearch, self.driver, 60, sleep=5) t.join() end_time = datetime.now() # check we get a page object pack. self.assertTrue(isinstance(self.page_obj, GoogleSearch)) # check that the instantiation happened later when the page was loaded. self.assertGreater(end_time - start_time, timedelta(seconds=10))
def __init__(self, webdriver=None, max_time=WTF_TIMEOUT_MANAGER.EPIC, sleep=5): """ Constructor Kwargs: webdriver (WebDriver) - Selenium Webdriver instance max_time (number) - Maximum wait time to keep the browser on stand by. sleep (number) - Number of seconds to wait between sending heart beats. """ if webdriver is None: webdriver = WTF_WEBDRIVER_MANAGER.get_driver() self.webdriver = webdriver self._sleep_time = sleep self._max_time = max_time
def test_createPage_createsPageFromFactory(self): # Mock a webdriver that looks like it's viewing yahoo config_reader = mock() when(config_reader).get("selenium.take_reference_screenshot", False).thenReturn(False) self.driver = WTF_WEBDRIVER_MANAGER.new_driver( "TestPageObject.test_createPage_createsPageFromFactory") self.driver.get("http://www.google.com") google = SearchPage.create_page(self.driver, config_reader=config_reader) self.assertTrue(type(google) == GoogleSearch) self.driver.get("http://www.yahoo.com") yahoo = SearchPage.create_page(self.driver, config_reader=config_reader) self.assertTrue(type(yahoo) == YahooSearch)
def test_capture_file_created_and_valid_png(self): self.driver = WTF_WEBDRIVER_MANAGER.new_driver( "TestPageUtils.test_capture_file_created_and_valid_png") self.driver.get("http://www.yahoo.com") fname = "test" prj_root = ProjectUtils.get_project_root() fpath = os.path.join( prj_root, WebScreenShotUtil.SCREEN_SHOT_LOCATION, fname + ".png") try: WebScreenShotUtil.take_screenshot(self.driver, fname) self.assertTrue(os.path.isfile(fpath)) self.assertEquals(imghdr.what(fpath), "png") finally: try: os.remove(fpath) except OSError: pass
def create_page(cls, webdriver=None, **kwargs): """Class method short cut to call PageFactory on itself. Use it to instantiate this PageObject using a webdriver. Args: webdriver (Webdriver): Instance of Selenium Webdriver. Returns: PageObject Raises: InvalidPageError """ if not webdriver: webdriver = WTF_WEBDRIVER_MANAGER.get_driver() return PageFactory.create_page(cls, webdriver=webdriver, **kwargs)
def test_basic_example(self): "Displays a simple PageObject instantiation example." # WTF_WEBDRIVER_MANAGER provides a easy to access to # the webdriver. A web browser will be instantiated # according to your config settings. # - see 'selenium' settings in 'configs/default.yaml' webdriver = WTF_WEBDRIVER_MANAGER.new_driver() # Simple navigation webdriver.get("http://www.google.com") # Use the PageFactory class to instantiate your page. google_page = PageFactory.create_page(GoogleSearchPage, webdriver) # With your PageObject instantiated, you can call it's methods. google_page.search("hello world") self.assertTrue(google_page.result_contains("hello world"))
def test_wait_for_page_to_load(self): self.driver = WTF_WEBDRIVER_MANAGER.new_driver( "TestPageUtils.test_wait_for_page_to_load") start_time = datetime.now() # create a separate thread to load yahoo 10 seconds later. t = threading.Thread(target=self.__load_google_later) t.start() self.page_obj = page.PageUtils.wait_until_page_loaded(GoogleSearch, self.driver, 60, sleep=5) t.join() end_time = datetime.now() # check we get a page object pack. self.assertTrue(isinstance(self.page_obj, GoogleSearch)) # check that the instantiation happened later when the page was loaded. self.assertGreater(end_time - start_time, timedelta(seconds=10))
def test_using_the_testdata(self): """ Demonstrates getting a setting via testdata package, and WTF_CONFIG_READER By default it'll use google.com, but you can add this line in the config file (by default it's default.yaml) You can override this setting. Insert the line below and run again to see this same test run in Yahoo. search_provider: http://www.yahoo.com By creating testdata functions to abstract directly accessing WTF_CONFIG_READER, we can reduce the number of hard coded strings that needs to be refactored if configuration settings need to be refactored. """ search_url = get_search_provider() webdriver = WTF_WEBDRIVER_MANAGER.new_driver() webdriver.get(search_url) search_page = PageFactory.create_page(ISearchPage, webdriver) search_page.search("hello world") self.assertTrue(search_page.result_contains("hello world"))
def test_assert(self): driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get('http://www.google.com') self.assertEqual(1, 2)
def setUp(self): self.driver = WTF_WEBDRIVER_MANAGER.new_driver() self.driver.get(data.url_address())
def set_up(self): webdriver = WTF_WEBDRIVER_MANAGER.new_driver() webdriver.get(ConfigReader('site_credentials').get("default_url")) return webdriver
def test_forgot_password(self): webdriver = WTF_WEBDRIVER_MANAGER.new_driver() webdriver.get(self.signin_url) signin_page = PageFactory.create_page(SignInPage) self.assertTrue(signin_page.forgot_password())
def test_send_reset_password_email_with_bad_email(self): webdriver = WTF_WEBDRIVER_MANAGER.new_driver() webdriver.get(self.signin_url) signin_page = PageFactory.create_page(SignInPage) self.assertTrue(signin_page.send_reset_password_email_with_bad_email())
def teardown(self): do_and_ignore(lambda: WTF_WEBDRIVER_MANAGER.close_driver())
def test_signup_with_existing_email(self): webdriver = WTF_WEBDRIVER_MANAGER.new_driver() webdriver.get(self.signin_url) signin_page = PageFactory.create_page(SignInPage) self.assertTrue(signin_page.signup_with_existing_email())
def test_create_page_raiseExceptionWhenNoMatch(self): self.driver = WTF_WEBDRIVER_MANAGER.new_driver( "TestPageFactory.test_create_page_raiseExceptionWhenNoMatch") self.driver.get("http://the-internet.herokuapp.com") self.assertRaises( NoMatchingPageError, PageFactory.create_page, SearchPage, self.driver)
def wait_until_page_loaded(page_obj_class, webdriver=None, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5, bad_page_classes=[], message=None, **kwargs): """ Waits until the page is loaded. Args: page_obj_class (Class) : PageObject class Kwargs: webdriver (Webdriver) : Selenium Webdriver. Default uses WTF_WEBDRIVER_MANAGER's instance. timeout (number) : Number of seconds to wait to allow the page to load. sleep (number) : Number of seconds to wait between polling. bad_page_classes (list) : List of PageObject classes to fail if matched. For example, ServerError page. message (string) : Use your own message with PageLoadTimeoutError raised. Returns: PageObject Raises: PageUtilOperationTimeoutError : Timeout occurred before the desired PageObject was matched. BadPageEncounteredError : One or more of the PageObject in the specified 'bad_page_classes' list was matched. Usage Example:: webdriver.get("http://www.mysite.com/login") # Wait up to 60 seconds for the page to load. login_page = wait_until_page_loaded(LoginPage, timeout=60, [ServerErrorPage]) This will wait for the login_page to load, then return a LoginPage() PageObject. """ if not webdriver: webdriver = WTF_WEBDRIVER_MANAGER.get_driver() # convert this param to list if not already. if type(bad_page_classes) != list: bad_page_classes = [bad_page_classes] end_time = datetime.now() + timedelta(seconds=timeout) last_exception = None while datetime.now() < end_time: # Check to see if we're at our target page. try: page = PageFactory.create_page( page_obj_class, webdriver=webdriver, **kwargs) return page except Exception as e: _wtflog.debug("Encountered exception: %s ", e) last_exception = e # Check to see if we're at one of those labled 'Bad' pages. for bad_page_class in bad_page_classes: try: PageFactory.create_page( bad_page_class, webdriver=webdriver, **kwargs) # if the if/else statement succeeds, than we have an error. raise BadPageEncounteredError( u("Encountered a bad page. ") + bad_page_class.__name__) except BadPageEncounteredError as e: raise e except: pass # We didn't hit a bad page class yet. # sleep till the next iteration. time.sleep(sleep) print "Unable to construct page, last exception", last_exception # Attempt to get current URL to assist in debugging try: current_url = webdriver.current_url except: # unable to get current URL, could be a webdriver for a non-webpage like mobile app. current_url = None if message: err_msg = u(message) + u("{page}:{url}")\ .format(page=PageUtils.__get_name_for_class__(page_obj_class), url=current_url) else: err_msg = u("Timed out while waiting for {page} to load. Url:{url}")\ .format(page=PageUtils.__get_name_for_class__(page_obj_class), url=current_url) raise PageLoadTimeoutError(err_msg)
def setUp(self): self.driver = WTF_WEBDRIVER_MANAGER.new_driver() self.driver.get(url_with_credentials())
def setUp(self): self.driver = WTF_WEBDRIVER_MANAGER.new_driver() self.base_url = WTF_CONFIG_READER.get("selenium.baseurl")
def tearDown(self): # tear down any webdrivers we create. do_and_ignore(lambda: WTF_WEBDRIVER_MANAGER.close_driver())
def wait_until_page_loaded(page_obj_class, webdriver=None, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5, bad_page_classes=[], message=None, **kwargs): """ Waits until the page is loaded. Args: page_obj_class (Class) : PageObject class Kwargs: webdriver (Webdriver) : Selenium Webdriver. Default uses WTF_WEBDRIVER_MANAGER's instance. timeout (number) : Number of seconds to wait to allow the page to load. sleep (number) : Number of seconds to wait between polling. bad_page_classes (list) : List of PageObject classes to fail if matched. For example, ServerError page. message (string) : Use your own message with PageLoadTimeoutError raised. Returns: PageObject Raises: PageUtilOperationTimeoutError : Timeout occurred before the desired PageObject was matched. BadPageEncounteredError : One or more of the PageObject in the specified 'bad_page_classes' list was matched. Usage Example:: webdriver.get("http://www.mysite.com/login") # Wait up to 60 seconds for the page to load. login_page = wait_until_page_loaded(LoginPage, timeout=60, [ServerErrorPage]) This will wait for the login_page to load, then return a LoginPage() PageObject. """ if not webdriver: webdriver = WTF_WEBDRIVER_MANAGER.get_driver() # convert this param to list if not already. if type(bad_page_classes) != list: bad_page_classes = [bad_page_classes] end_time = datetime.now() + timedelta(seconds=timeout) last_exception = None while datetime.now() < end_time: # Check to see if we're at our target page. try: page = PageFactory.create_page(page_obj_class, webdriver=webdriver, **kwargs) return page except Exception as e: _wtflog.debug("Encountered exception: %s ", e) last_exception = e # Check to see if we're at one of those labled 'Bad' pages. for bad_page_class in bad_page_classes: try: PageFactory.create_page(bad_page_class, webdriver=webdriver, **kwargs) # if the if/else statement succeeds, than we have an error. raise BadPageEncounteredError( u("Encountered a bad page. ") + bad_page_class.__name__) except BadPageEncounteredError as e: raise e except: pass # We didn't hit a bad page class yet. # sleep till the next iteration. time.sleep(sleep) print "Unable to construct page, last exception", last_exception # Attempt to get current URL to assist in debugging try: current_url = webdriver.current_url except: # unable to get current URL, could be a webdriver for a non-webpage like mobile app. current_url = None if message: err_msg = u(message) + u("{page}:{url}")\ .format(page=PageUtils.__get_name_for_class__(page_obj_class), url=current_url) else: err_msg = u("Timed out while waiting for {page} to load. Url:{url}")\ .format(page=PageUtils.__get_name_for_class__(page_obj_class), url=current_url) raise PageLoadTimeoutError(err_msg)
def create_page(page_object_class_or_interface, webdriver=None, **kwargs): """ Instantiate a page object from a given Interface or Abstract class. Args: page_object_class_or_interface (Class): PageObject class, AbstractBaseClass, or Interface to attempt to consturct. Kwargs: webdriver (WebDriver): Selenium Webdriver to use to instantiate the page. If none is provided, then it was use the default from WTF_WEBDRIVER_MANAGER Returns: PageObject Raises: NoMatchingPageError Instantiating a Page from PageObject from class usage:: my_page_instance = PageFactory.create_page(MyPageClass) Instantiating a Page from an Interface or base class:: import pages.mysite.* # Make sure you import classes first, or else PageFactory will not know about it. my_page_instance = PageFactory.create_page(MyPageInterfaceClass) Instantiating a Page from a list of classes.:: my_page_instance = PageFactory.create_page([PossiblePage1, PossiblePage2]) Note: It'll only be able to detect pages that are imported. To it's best to do an import of all pages implementing a base class or the interface inside the __init__.py of the package directory. """ if not webdriver: webdriver = WTF_WEBDRIVER_MANAGER.get_driver() # will be used later when tracking best matched page. current_matched_page = None # used to track if there is a valid page object within the set of PageObjects searched. was_validate_called = False # Walk through all classes if a list was passed. if type(page_object_class_or_interface) == list: subclasses = [] for page_class in page_object_class_or_interface: # attempt to instantiate class. page = PageFactory.__instantiate_page_object( page_class, webdriver, **kwargs) if isinstance(page, PageObject): was_validate_called = True if (current_matched_page == None or page > current_matched_page): current_matched_page = page elif page is True: was_validate_called = True # check for subclasses subclasses += PageFactory.__itersubclasses(page_class) else: # A single class was passed in, try to instantiate the class. page_class = page_object_class_or_interface page = PageFactory.__instantiate_page_object( page_class, webdriver, **kwargs) # Check if we got a valid PageObject back. if isinstance(page, PageObject): was_validate_called = True current_matched_page = page elif page is True: was_validate_called = True # check for subclasses subclasses = PageFactory.__itersubclasses( page_object_class_or_interface) # Iterate over subclasses of the passed in classes to see if we have a # better match. for pageClass in subclasses: try: page = PageFactory.__instantiate_page_object( pageClass, webdriver, **kwargs) # If we get a valid PageObject match, check to see if the ranking is higher # than our current PageObject. if isinstance(page, PageObject): was_validate_called = True if current_matched_page == None or page > current_matched_page: current_matched_page = page elif page is True: was_validate_called = True except InvalidPageError as e: _wtflog.debug("InvalidPageError: %s", e) pass # This happens when the page fails check. except TypeError as e: _wtflog.debug("TypeError: %s", e) # this happens when it tries to instantiate the original # abstract class. pass except Exception as e: _wtflog.debug("Exception during page instantiation: %s", e) # Unexpected exception. raise e # If no matching classes. if not isinstance(current_matched_page, PageObject): # Check that there is at least 1 valid page object that was passed in. if was_validate_called is False: raise TypeError( "Neither the PageObjects nor it's subclasses have implemented " + "'PageObject._validate(self, webdriver)'.") try: current_url = webdriver.current_url raise NoMatchingPageError( u("There's, no matching classes to this page. URL:{0}"). format(current_url)) except: raise NoMatchingPageError( u("There's, no matching classes to this page. ")) else: return current_matched_page
def set_up_with_suffix(self, suffix): webdriver = WTF_WEBDRIVER_MANAGER.new_driver() webdriver.get(ConfigReader('site_credentials').get("default_url") + suffix) return webdriver
def test_error(self): driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get('http://www.google.com') raise RuntimeError()
def tearDown(self): do_and_ignore(lambda: WTF_WEBDRIVER_MANAGER.close_driver(self.driver))
def create_page(page_object_class_or_interface, \ webdriver=None, **kwargs): """ Instantiate a page object from a given Interface or Abstract class. Instantiating a Page from PageObject from class usage: my_page_instance = PageFactory.create_page(MyPageClass) Instantiating a Page from an Interface or base class import pages.mysite.* my_page_instance = PageFactory.create_page(MyPageInterfaceClass) Instantiating a Page from a list of classes. my_page_instance = PageFactory.create_page([PossiblePage1, PossiblePage2]) Note: It'll only be able to detect pages that are imported. To it's best to do an import of all pages implementing a base class or the interface inside the __init__.py of the package directory. @param page_object_class_or_interface: Class, AbstractBaseClass, or Interface to attempt to consturct. @param webdriver: Selenium Webdriver to use to instantiate the page. @type webdriver: WebDriver """ if not webdriver: webdriver = WTF_WEBDRIVER_MANAGER.get_driver() # will be used later when tracking best matched page. current_matched_page = None # Walk through all classes of this sub class if type(page_object_class_or_interface) == list: subclasses = [] for page_class in page_object_class_or_interface: #attempt to instantiate class. page = PageFactory.__instantiate_page_object(page_class, \ webdriver, \ **kwargs) if isinstance(page, PageObject) and (current_matched_page == None or page > current_matched_page): current_matched_page = page #check for subclasses subclasses += PageFactory.__itersubclasses(page_class) else: # Try the original class page_class = page_object_class_or_interface page = PageFactory.__instantiate_page_object(page_class, webdriver, **kwargs) if isinstance(page, PageObject): current_matched_page = page #check for subclasses subclasses = PageFactory.__itersubclasses(page_object_class_or_interface) # Iterate over subclasses of the passed in classes to see if we have a better match. for pageClass in subclasses: try: page = pageClass(webdriver, **kwargs) if current_matched_page == None or page > current_matched_page: current_matched_page = page except InvalidPageError as e: print_debug("InvalidPageError", e) pass #This happens when the page fails check. except TypeError as e: print_debug("TypeError", e) pass #this happens when it tries to instantiate the original abstract class. except Exception as e: print_debug("Exception", e) #Unexpected exception. raise e # If no matching classes. if not isinstance(current_matched_page, PageObject): raise NoMatchingPageError("There's, no matching classes to this page. URL:%s" \ % webdriver.current_url) else: return current_matched_page
def tearDown(self): #tear down any webdrivers we create. do_and_ignore(lambda: WTF_WEBDRIVER_MANAGER.close_driver())
def testName(self): driver = WTF_WEBDRIVER_MANAGER.new_driver() print("hello")
def test_fail(self): driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get('http://www.google.com') self.fail()
def create_page(page_object_class_or_interface, webdriver=None, **kwargs): """ Instantiate a page object from a given Interface or Abstract class. Args: page_object_class_or_interface (Class): PageObject class, AbstractBaseClass, or Interface to attempt to consturct. Kwargs: webdriver (WebDriver): Selenium Webdriver to use to instantiate the page. If none is provided, then it was use the default from WTF_WEBDRIVER_MANAGER Returns: PageObject Raises: NoMatchingPageError Instantiating a Page from PageObject from class usage:: my_page_instance = PageFactory.create_page(MyPageClass) Instantiating a Page from an Interface or base class:: import pages.mysite.* # Make sure you import classes first, or else PageFactory will not know about it. my_page_instance = PageFactory.create_page(MyPageInterfaceClass) Instantiating a Page from a list of classes.:: my_page_instance = PageFactory.create_page([PossiblePage1, PossiblePage2]) Note: It'll only be able to detect pages that are imported. To it's best to do an import of all pages implementing a base class or the interface inside the __init__.py of the package directory. """ if not webdriver: webdriver = WTF_WEBDRIVER_MANAGER.get_driver() # will be used later when tracking best matched page. current_matched_page = None # used to track if there is a valid page object within the set of PageObjects searched. was_validate_called = False # Walk through all classes if a list was passed. if type(page_object_class_or_interface) == list: subclasses = [] for page_class in page_object_class_or_interface: # attempt to instantiate class. page = PageFactory.__instantiate_page_object(page_class, webdriver, **kwargs) if isinstance(page, PageObject): was_validate_called = True if (current_matched_page == None or page > current_matched_page): current_matched_page = page elif page is True: was_validate_called = True # check for subclasses subclasses += PageFactory.__itersubclasses(page_class) else: # A single class was passed in, try to instantiate the class. page_class = page_object_class_or_interface page = PageFactory.__instantiate_page_object(page_class, webdriver, **kwargs) # Check if we got a valid PageObject back. if isinstance(page, PageObject): was_validate_called = True current_matched_page = page elif page is True: was_validate_called = True # check for subclasses subclasses = PageFactory.__itersubclasses( page_object_class_or_interface) # Iterate over subclasses of the passed in classes to see if we have a # better match. for pageClass in subclasses: try: page = PageFactory.__instantiate_page_object(pageClass, webdriver, **kwargs) # If we get a valid PageObject match, check to see if the ranking is higher # than our current PageObject. if isinstance(page, PageObject): was_validate_called = True if current_matched_page == None or page > current_matched_page: current_matched_page = page elif page is True: was_validate_called = True except InvalidPageError as e: _wtflog.debug("InvalidPageError: %s", e) pass # This happens when the page fails check. except TypeError as e: _wtflog.debug("TypeError: %s", e) # this happens when it tries to instantiate the original # abstract class. pass except Exception as e: _wtflog.debug("Exception during page instantiation: %s", e) # Unexpected exception. raise e # If no matching classes. if not isinstance(current_matched_page, PageObject): # Check that there is at least 1 valid page object that was passed in. if was_validate_called is False: raise TypeError("Neither the PageObjects nor it's subclasses have implemented " + "'PageObject._validate(self, webdriver)'.") try: current_url = webdriver.current_url raise NoMatchingPageError(u("There's, no matching classes to this page. URL:{0}") .format(current_url)) except: raise NoMatchingPageError(u("There's, no matching classes to this page. ")) else: return current_matched_page
def get_element_xpath(element, webdriver=None): if not webdriver: webdriver = WTF_WEBDRIVER_MANAGER.get_driver() element_xpath = webdriver.execute_script("gPt=function(c){if(c.id!==''){return'id(\"'+c.id+'\")'}if(c===document.body){return c.tagName}var a=0;var e=c.parentNode.childNodes;for(var b=0;b<e.length;b++){var d=e[b];if(d===c){return gPt(c.parentNode)+'/'+c.tagName+'['+(a+1)+']'}if(d.nodeType===1&&d.tagName===c.tagName){a++}}};return gPt(arguments[0]).toLowerCase();", element) return element_xpath
def tearDown(self): WTF_WEBDRIVER_MANAGER.close_driver()
def setUp(self): self.driver = WTF_WEBDRIVER_MANAGER.new_driver("TestWebElementSelector")
def create_page(page_object_class_or_interface, \ webdriver=None, **kwargs): """ Instantiate a page object from a given Interface or Abstract class. Args: page_object_class_or_interface (Class): PageObject class, AbstractBaseClass, or Interface to attempt to consturct. Kwargs: webdriver (WebDriver): Selenium Webdriver to use to instantiate the page. Returns: PageObject Raises: NoMatchingPageError Instantiating a Page from PageObject from class usage:: my_page_instance = PageFactory.create_page(MyPageClass) Instantiating a Page from an Interface or base class:: import pages.mysite.* # Make sure you import classes first, or else PageFactory will not know about it. my_page_instance = PageFactory.create_page(MyPageInterfaceClass) Instantiating a Page from a list of classes.:: my_page_instance = PageFactory.create_page([PossiblePage1, PossiblePage2]) Note: It'll only be able to detect pages that are imported. To it's best to do an import of all pages implementing a base class or the interface inside the __init__.py of the package directory. """ if not webdriver: webdriver = WTF_WEBDRIVER_MANAGER.get_driver() # will be used later when tracking best matched page. current_matched_page = None # Walk through all classes of this sub class if type(page_object_class_or_interface) == list: subclasses = [] for page_class in page_object_class_or_interface: #attempt to instantiate class. page = PageFactory.__instantiate_page_object(page_class, \ webdriver, \ **kwargs) if isinstance(page, PageObject) and (current_matched_page == None or page > current_matched_page): current_matched_page = page #check for subclasses subclasses += PageFactory.__itersubclasses(page_class) else: # Try the original class page_class = page_object_class_or_interface page = PageFactory.__instantiate_page_object(page_class, \ webdriver, \ **kwargs) if isinstance(page, PageObject): current_matched_page = page #check for subclasses subclasses = PageFactory.__itersubclasses( page_object_class_or_interface) # Iterate over subclasses of the passed in classes to see if we have a better match. for pageClass in subclasses: try: page = pageClass(webdriver, **kwargs) if current_matched_page == None or page > current_matched_page: current_matched_page = page except InvalidPageError as e: print_debug("InvalidPageError", e) pass #This happens when the page fails check. except TypeError as e: print_debug("TypeError", e) pass #this happens when it tries to instantiate the original abstract class. except Exception as e: print_debug("Exception", e) #Unexpected exception. raise e # If no matching classes. if not isinstance(current_matched_page, PageObject): raise NoMatchingPageError("There's, no matching classes to this page. URL:%s" \ % webdriver.current_url) else: return current_matched_page