class RegisterCoursesTests(unittest.TestCase):
    @pytest.fixture(autouse=True)
    def classSetup(self, oneTimeSetUp):
        self.courses = RegisterCoursesPage(self.driver)
        self.ts = T_estStatus(self.driver)
        self.lg = LoginPage(self.driver)
        self.util = Util()

    @pytest.mark.run(order=1)
    @data(("JavaScript", "EG", "121212"), ("JavaS", "IR", "101010"))
    @unpack
    def test_invalidEnrollment(self, course_name, country_name, postal_code):
        self.lg.login("*****@*****.**", "abcabc")
        self.courses.clickAllCoursesButton()
        self.courses.enterCourseName(courseName=course_name)
        self.courses.clickJavaScriptCourse()
        self.courses.scrollToBottom()
        self.courses.clickEnrollButton()
        self.courses.scrollToBottom()
        self.courses.selectCountryDropDown(countryName=country_name)
        self.courses.enterPostalCode(code=postal_code)
        self.courses.clickSubmitButton()
        self.courses.scrollToTop()
        self.util.sleep(3)
        result1 = self.courses.verifyTextOnPage(
            "Sorry, there was an error completing your purchase -- please try again."
        )
        self.ts.mark(result1, "Text verified")
        self.driver.back()
        self.courses.logOut()
        result2 = self.courses.verifyUserLogOut()
        self.ts.markFinal("test_invalidEnrollment", result2,
                          "logout successful")
        self.util.sleep(2)
コード例 #2
0
 def element_click(self, locator: str, locator_type: str="id", element: WebElement=None):
     try:
         if element is not None:
             element_sub = self.get_element(locator=locator, locator_type=locator_type, element=element)
             element_sub.click()
             self.log.info("Clicked on sub element with locator: "
             + locator
             + " locator type: "
             + locator_type)
         else:
             element_main = self.get_element(locator, locator_type)
             element_main.click()
             self.log.info(
                 "Clicked on element with locator: "
                 + locator
                 + " locator type: "
                 + locator_type
             )
         Util.sleep(Util, sec=1, info="Give page time to react")
     except:
         self.log.error(
             "Cannot click on the element with locator: "
             + locator
             + " locator_type: "
             + locator_type
         )
         self.screen_shot("Element_click_not_found_" + locator)
         print_stack()
コード例 #3
0
 def alert_text(self) -> str:
     Util.sleep(Util, sec=2, info="Give alert time to react")
     try:
         alert = self.driver.switch_to.alert
         return alert.text
     except Exception as e:
         self.log.info(e)
コード例 #4
0
class LoginPage(BasePage):

    log = cl.customLogger(logging.DEBUG)

    def __init__(self, driver):
        super().__init__(driver)
        self.driver = driver
        self.nav = NavigationPage(driver)
        self.util = Util()

    #locators
    _adm_login_locators1 = "//li/a[@href='#']"
    _adm_login_locators2 = "//img[@class='brand-img']"
    _adm_login_locators3 = "//img[@ng-if='current.user.avatar']"
    _adm_login_locators4 = "//a[@kp-icon-svg='attention']"
    _adm_login_locators5 = "//a[@kp-icon-svg='globe']"
    _adm_login_locators6 = "//div[@class='btn btn-default navbar-btn dropdown-toggle']"
    _username_field = "//input[contains(@class, 'login-name')]"
    _password_field = "//input[contains(@class, 'login-password')]"
    _login_btn = "//input[@type='submit']"
    _logout_btn = "//a[@ng-click='logout()']"

    def enterEmail(self, email):
        self.elementClear(self._username_field)
        self.sendKeys(email, self._username_field)

    def enterPassword(self, password):
        self.elementClear(self._password_field)
        self.sendKeys(password, self._password_field)

    def clickLoginBtn(self):
        self.elementClick(self._login_btn)

    def login(self, email="", password=""):
        self.enterEmail(email)
        self.enterPassword(password)
        self.clickLoginBtn()
        self.util.sleep(2)

    def logout(self):
        self.nav.openUserSettings()
        self.elementClick(self._logout_btn)

    def verifyAdmLogin(self):
        res1 = self.elementPresenceCheck(self._adm_login_locators1)
        res2 = self.elementPresenceCheck(self._adm_login_locators2)
        res3 = self.elementPresenceCheck(self._adm_login_locators3)
        res4 = self.elementPresenceCheck(self._adm_login_locators4)
        res5 = self.elementPresenceCheck(self._adm_login_locators5)
        res6 = self.elementPresenceCheck(self._adm_login_locators6)
        if res1 and res2 and res3 and res4 and res5 and res6 == True:
            return True
コード例 #5
0
class VATRegistrationDetailsWindows(BasePage):
    log = cl.custom_logger(logging.DEBUG)

    def __init__(self, driver):
        super().__init__(driver)
        self.driver = driver
        self.util = Util()

    # LOCATORS
    _help_link = "Help"  # LINK_TEXT
    _personalize_link = "Personalize"  # LINK_TEXT
    _find_link = "Find"  # LINK_TEXT
    _country = "VNDR_VAT_RGSTRN_COUNTRY$0"
    _vat_registration_id = "VNDR_VAT_RGSTRN_VAT_RGSTRN_ID$0"
    _ok_button = "#ICSave"
    _cancel_button = "#ICCancel"

    def enter_country(self):
        self.sendkeys(("LUX", Keys.TAB), self._country)
        self.util.sleep(2, "the Country to be recognized by the app.")

    def enter_vat_registration_id(self):
        random_number = randint(100000000000000, 999999999999999)
        self.sendkeys(random_number, self._vat_registration_id)
        self.util.sleep(
            2,
            "the VAT Registration ID, {}, to be recognized by the application."
            .format(random_number))

    def click_save_button(self):
        self.element_click(self._ok_button)

        wait = WebDriverWait(self.driver, 10, poll_frequency=1)
        wait.until(ec.visibility_of_element_located((By.ID, "ptifrmtgtframe")))

        try:
            self.driver.switch_to.frame("ptifrmtgtframe")
        except Exception as e:
            print(e)

    """ METHOD CALLED FROM IDENTIFYING INFO PAGE """

    def enter_vat_registration_details(self):
        self.enter_country()
        self.enter_vat_registration_id()
        self.click_save_button()
コード例 #6
0
ファイル: add_new_value_page.py プロジェクト: KayJayTea/vMDM
class SupplierInformationANV(BasePage):
    log = cl.custom_logger(logging.DEBUG)

    def __init__(self, driver):
        super().__init__(driver)
        self.driver = driver
        self.util = Util()

    """ Unless otherwise noted, locator type is ID"""
    # LOCATORS
    _new_window_link = "New Window"  # LINK_TEXT
    _help_link = "Help"  # LINK_TEXT
    _find_existing_value_tab = "ICTAB_0"
    _keyword_search_tab = "ICTAB_1"
    _set_id_field = "VENDOR_ADD_VW_SETID"
    _supplier_id_field = "VENDOR_ADD_VW_VENDOR_ID"
    _persistence_select = "VENDOR_ADD_VW_VENDOR_PERSISTENCE"
    _add_button = "#ICSearch"

    def click_add_button(self):
        self.util.sleep(1, "Add New Value page to open.")
        self.element_click(self._add_button)
コード例 #7
0
class FindExistingValuePage(BasePage):
    log = cl.custom_logger(logging.DEBUG)

    def __init__(self, driver):
        super().__init__(driver)
        self.driver = driver
        self.util = Util()

    """ Unless otherwise noted, locator_type is 'ID' """
    # LOCATORS
    _new_window_link = "New Window"  # LINK_TEXT
    _help_link = "Help"  # LINK_TEXT
    _keyword_search_tab = "ICTAB_1"
    _add_new_value_tab = "ICTAB_2"
    _supplier_id_txt = "VENDOR_AP_VW_VENDOR_ID"
    _persistence_select = "VENDOR_AP_VW_VENDOR_PERSISTENCE"
    _short_supplier_name_txt = "VENDOR_AP_VW_VENDOR_NAME_SHORT"
    _our_customer_number_txt = "VENDOR_AP_VW_AR_NUM"
    _supplier_name = "VENDOR_AP_VW_NAME1"
    _search_btn = "#ICSearch"
    _clear_btn = "#ICClear"
    _basic_search_link = "Basic Search"  # LINK_TEXT
    _save_search_criteria_link = "Save Search Criteria"  # LINK_TEXT
    _find_existing_value_link = "Find an Existing Value"  # LINK_TEXT
    _keyword_search_link = "Keyword Search"  # LINK_TEXT
    _add_new_value_link = "Add a New Value"  # LINK_TEXT

    def click_add_new_value_tab(self):
        self.element_click(self._add_new_value_tab)

    def add_a_new_value(self):
        self.driver.switch_to.frame("ptifrmtgtframe")
        self.util.sleep(1, "the active window to be recognized by the app.")
        self.click_add_new_value_tab()

    def search_for_supplier(self):
        self.driver.switch_to_frame("ptifrmtgtframe")
        self.util.sleep(1, "the active window to be recognized by the app.")

    def enter_supplier_id(self, supplier):
        self.driver.switch_to_frame("ptifrmtgtframe")
        self.util.sleep(1, "the active window to be recognized by the app.")

        self.sendkeys(supplier, self._supplier_id_txt)

    def click_search_btn(self):
        self.element_click(self._search_btn)
        self.util.sleep(2, "the Summary page to open.")
コード例 #8
0
class RegisterCoursesCSVDataTests(unittest.TestCase):
    @pytest.fixture(autouse=True)
    def objectSetup(self, oneTimeSetUp):
        self.courses = RegisterCoursesPage(self.driver)
        self.ts = T_estStatus(self.driver)
        self.lg = LoginPage(self.driver)
        self.util = Util()
        self.nav = NavigationPage(self.driver)

    def setUp(self):
        self.nav.navigateToAllCourses()

    @pytest.mark.run(order=1)
    @data(
        *getCSVData(r"C:\Users\Owner\workspace_python\letskodeit\testdata.csv")
    )
    @unpack
    def test_invalidEnrollment(self, course_name, country_name, postal_code):
        #       self.lg.login("*****@*****.**", "abcabc")
        #    self.courses.clickAllCoursesButton()
        self.courses.enterCourseName(courseName=course_name)
        self.courses.clickJavaScriptCourse()
        self.courses.scrollToBottom()
        self.courses.clickEnrollButton()
        self.courses.scrollToBottom()
        self.courses.selectCountryDropDown(countryName=country_name)
        self.courses.enterPostalCode(code=postal_code)
        self.courses.clickSubmitButton()
        self.courses.scrollToTop()
        self.util.sleep(3)
        result1 = self.courses.verifyTextOnPage(
            "Sorry, there was an error completing your purchase -- please try again."
        )
        #    self.ts.mark(result1, "Text verified")
        self.ts.markFinal("test_invalidEnrollment", result1, "Text verified")

        self.driver.back()
コード例 #9
0
class ClickItems(SeleniumDriver):
    """
    this class implements this test case :
        automation will click on one of the elements then check if the element added successfully to the cart and the
        price is valid .
    """

    log = cl.customLogger(logging.DEBUG)

    def __init__(self, driver):
        super().__init__(driver)
        self.driver = driver
        self.nav = NavigationPage(driver)
        self.action = ActionChains(driver)
        self.util = Util()

    # locators :

    # element from the main page (chair , table ...) .
    element_locator = '//*[@id="post-19"]/div/div/div/div/section[3]/div/div/div/div/div/div[4]/div//h2[contains(text(), "{0}")]'
    # after click on some element -> on the page that pops up -> locator for 'add to cart' .
    add_to_cart_locator = "//button[contains(text(), 'Add to cart')]"
    # at the top of all pages -> cart icon locator .
    cart_locator = '//*[@id="ast-site-header-cart"]/div[1]/a/div/span'
    # check the number inside the cart icon -> if the text inside it is greater then 0 -> item added to cart .
    text_in_cart_locator = '//*[@id="ast-site-header-cart"]/div[1]/a/div/span'
    # plus_locator on add to cart page .
    plus_locator = '//div[2]/form/div/a[2]'
    # price_locator
    price_locator = '//*[@id="post-5"]/div/div/form/table/tbody/tr[1]/td[4]/span'
    # total_locator
    total_locator = '//*[@id="post-5"]/div/div/div[2]/div/table/tbody/tr[2]/td/strong/span'

    def click_on_item(self, item):
        """
        automation will locate an 'item' -> click on it .
        the item will be added to the cart .
        :param item: The item from the items collection .
        :return:
        """
        # using method from 'base.selenium_driver import SeleniumDriver' file -> find element and click on it .
        self.elementClick(locator=self.element_locator.format(item),
                          locatorType="xpath")
        self.util.sleep(2)

    def add_to_cart(self, amount):
        """
        Automation finds an elements from the collection -> click on the element -> on specific product page -> finds
        the 'plus' element -> and click on it accordint to the 'amount' entered .
        :param amount: add 'amount' elements to the card .
        :return:
        """
        # get the 'plus' element every time and click on it .
        for i in range(0, int(amount)):
            element = self.getElement(locator=self.plus_locator,
                                      locatorType="xpath")
            self.elementClick(element=element)
            self.util.sleep(1)
        # after the automation done clicking on the 'plus' element -> finds 'add to cart' element and click it .
        self.elementClick(locator=self.add_to_cart_locator,
                          locatorType="xpath")
        self.util.sleep(2)
        # then click on the cart icon on the top right of the web page .
        self.elementClick(locator=self.cart_locator, locatorType="xpath")

    def verify_item_added_successfully(self, amount):
        """
        this function checks if the right number of items added to the cart .
        after the automation add 'amount' of specific items to the cart -> the function checks 2 things :
        1. there is 'amount' elements on the cart on the final page before purchase .
        2. the price is valid by check if 'total_locator' / 'price_locator' = 'amount' + 1 .
        :param amount:
        :return:
        """
        # two boolean statements to check 1 and 2 .
        statement_one = False
        statement_two = False

        # get the text inside cart icon .
        text_in_cart = self.getElement(self.text_in_cart_locator, "xpath")
        text = text_in_cart.text
        self.log.info("THE TEXT IS : {}".format(text))
        # the text should be amount + 1 if the items added successfully .
        if int(text) == int(amount) + 1:
            statement_one = True
        else:
            statement_one = False

        # get the 'price' element per one unit and the 'total price' element .
        price_element = self.getElement(locator=self.price_locator,
                                        locatorType="xpath")
        total_price_element = self.getElement(locator=self.total_locator,
                                              locatorType="xpath")
        price_text = price_element.text[1:]
        total_price_text = total_price_element.text[1:]
        self.log.info("price per one : {} ||| total price : {}".format(
            price_text, total_price_text))
        # make the math check and initialize 'statement_two' boolean variable .
        if float(total_price_text) / float(price_text) == float(amount) + 1:
            statement_two = True
        else:
            statement_two = False

        # if both statements are 'True' then the test passed .
        if statement_one and statement_two == True:
            self.log.info("Items added successfully and price is valid .")
            return True
        # if one of the tests (or both) are false then -> print the right message to the log and return false .
        else:
            if statement_one == False:
                self.log.info("Add to cart test did not passed successfully .")
            if statement_two == False:
                self.log.info("Price test did not passed successfully .")
            return False
コード例 #10
0
ファイル: address_page.py プロジェクト: KayJayTea/vMDM
class AddressPage(BasePage):
    log = cl.custom_logger(logging.DEBUG)

    def __init__(self, driver):
        super().__init__(driver)
        self.driver = driver
        self.util = Util()

    # LOCATORS
    _summary_tab = "//a//span[contains(text(), 'ummary')]"  # XPATH
    _identifying_info_tab = "//a//span[contains(text(), 'dentifying Information')]"  # XPATH
    _contacts_tab = "//a//span[contains(text(), 'ontacts')]"  # XPATH
    _location_tab = "//span[text() = 'ocation']"  # XPATH
    _custom_tab = "//a//span[contains(text(), 'C')]"  # XPATH
    _supplier_name = "VENDOR_NAME1"
    _description_field = "VNDR_ADDR_SCROL_DESCR$0"
    _sam_address_type = "VNDR_ADDR_SCROL_CCR_ADDR_TYPE$0"
    _add_new_address_btn = "$ICField2$new$0$$0"
    _country = "VENDOR_ADDR_COUNTRY$0"
    _address_1 = "VENDOR_ADDR_ADDRESS1$0"
    _address_2 = "VENDOR_ADDR_ADDRESS2$0"
    _address_3 = "VENDOR_ADDR_ADDRESS3$0"
    _address_4 = "VENDOR_ADDR_ADDRESS4$0"
    _number = "VENDOR_ADDR_NUM1$0"
    _door = "VENDOR_ADDR_NUM2$0"
    _city = "VENDOR_ADDR_CITY$0"
    _county = "VENDOR_ADDR_COUNTY$0"
    _state = "VENDOR_ADDR_STATE$0"
    _postal = "VENDOR_ADDR_POSTAL$0"
    _email_id = "VENDOR_ADDR_EMAILID$0"
    _override_address_box = "CLN_OVERRIDE_ADDRESS"
    _alt_names_arrow = "VNDR_ADDR_WRK_VNDR_WTHD_LBL$0"
    _pmnt_alt_name_1 = "VENDOR_ADDR_NAME1$17$$0"
    _pmnt_alt_name_2 = "VENDOR_ADDR_NAME2$0"
    _wh_alt_name_1 = "VENDOR_ADDR_NAME1_WTHD$21$$0"
    _wh_alt_name_2 = "VENDOR_ADDR_NAME2_WTHD$0"
    _phone_type = "VENDOR_ADDR_PHN_PHONE_TYPE$0"
    _telephone_field = "VENDOR_ADDR_PHN_PHONE$0"
    _add_new_row_phone = "VENDOR_ADDR_PHN$new$0$$0"
    _search_state = "VENDOR_ADDR_STATE$prompt$img$0"
    _effective_date = "VENDOR_ADDR_EFFDT$0"
    """ Get the elements """

    def get_sam_address_type(self):
        return self.driver.find_element(By.ID, self._sam_address_type)

    def get_phone_type(self):
        return self.driver.find_element(By.ID, self._phone_type)

    """ Do something with the elements """

    def click_location_tab(self):
        self.element_click(self._location_tab, "xpath")
        self.util.sleep(2, "the Location page to open.")

    def enter_description(self):
        sup_name = self.driver.find_element(By.ID, "VENDOR_NAME1").text
        self.sendkeys(sup_name, self._description_field)

    def select_sam_address_type(self, sam_type):
        sel = Select(self.get_sam_address_type())
        sel.select_by_visible_text(sam_type)

    def enter_country_code(self, country_code):
        self.clear_element(self._country)
        self.sendkeys(country_code, self._country)
        self.sendkeys(Keys.TAB, self._country)
        self.util.sleep(1, "the country code to be recognized by the app.")

    def click_add_new_address_btn(self):
        self.element_click(self._add_new_address_btn)
        self.util.sleep(1)

    def enter_address_one(self):
        fake_data = Faker()
        fake_street_address = fake_data.street_address()
        self.sendkeys(fake_street_address, self._address_1)

    def enter_address_two(self):
        random_num = randint(1, 10)
        self.sendkeys("Bldg. " + str(random_num), self._address_2)

    def enter_address_three(self):
        self.sendkeys("N/A", self._address_3)

    def enter_city(self):
        fake_data = Faker()
        fake_city = fake_data.city()
        self.sendkeys(fake_city, self._city)

    def enter_postal_code(self):
        fake_data = Faker()
        fake_postal_code = fake_data.postalcode()
        self.sendkeys(fake_postal_code, self._postal)
        self.util.sleep(1, "the postal code to be recognized by the app.")

    def enter_random_state(self):
        self.sendkeys(str(choice(STATE_ABBR)), self._state)
        self.util.sleep(1, "the state to be recognized by the app.")

    def enter_email_id(self):
        fake_data = Faker()
        fake_email = fake_data.safe_email()
        self.sendkeys(fake_email, self._email_id)
        self.util.sleep(1, "the email to be recognized by the app.")

    def click_override_address_verification_chkbx(self):
        self.element_click(self._override_address_box)
        self.util.sleep(1, "the app recognizes the override.")

    def expand_alternate_names(self):
        self.element_click(self._alt_names_arrow)

    def click_add_new_phone_btn(self):
        self.element_click(self._add_new_row_phone)

    def search_for_state(self):
        self.element_click(self._search_state)

    def enter_random_gb_county(self):
        self.sendkeys(str(choice(GBR_COUNTIES)), self._state)
        self.util.sleep(2, "the state to be recognized by the app.")

    """ THIS IS THE MODULE THAT IS CALLED BY THE TEST """

    def enter_pmnt_alt_name_1(self):
        fake_data = Faker()
        fake_name = fake_data.name()
        self.sendkeys(fake_name, self._pmnt_alt_name_1)

    def enter_pmnt_alt_name_2(self):
        fake_data = Faker()
        fake_name = fake_data.name()
        self.sendkeys(fake_name, self._pmnt_alt_name_2)

    def enter_business_phone(self):
        sel = Select(self.get_phone_type())
        sel.select_by_visible_text("Business Phone")

        fake_data = Faker()
        fake_phone = fake_data.random_int(min=2000000, max=9999999)

        self.sendkeys("555" + str(fake_phone), self._telephone_field)
        self.element_click(self._add_new_row_phone)
        self.util.sleep(1, "the new phone row to be recognized by the app.")

    def enter_fax(self):
        sel = Select(self.get_phone_type())
        sel.select_by_visible_text("FAX")

        fake_data = Faker()
        fake_phone = fake_data.random_int(min=2000000, max=9999999)

        self.sendkeys("555" + str(fake_phone), self._telephone_field)
        self.element_click(self._add_new_row_phone)
        self.util.sleep(1, "the new phone row to be recognized by the app.")

    def enter_trilogie_dm_fax(self):
        sel = Select(self.get_phone_type())
        sel.select_by_visible_text("Trilogie DM Fax Number")

        fake_data = Faker()
        fake_phone = fake_data.random_int(min=2000000, max=9999999)

        self.sendkeys("555" + str(fake_phone), self._telephone_field)
        self.element_click(self._add_new_row_phone)
        self.util.sleep(1, "the new phone row to be recognized by the app.")

    def enter_all_phone_types(self):
        phone_type_list = ['Business Phone', 'FAX', 'Trilogie DM Fax Number']
        # phone_type_list = ['Business Phone', 'FAX']

        for phone_type in phone_type_list:
            sel = Select(self.get_phone_type())
            sel.select_by_visible_text(phone_type)

            fake_data = Faker()
            fake_phone = fake_data.random_int(min=2000000, max=9999999)

            self.sendkeys("555" + str(fake_phone), self._telephone_field)
            self.element_click(self._add_new_row_phone)
            self.util.sleep(1,
                            "the new phone row to be recognized by the app.")

    def enter_domestic_master_vendor_address(self, sam_type):
        self.select_sam_address_type(sam_type)
        self.enter_address_one()
        self.enter_address_two()
        self.enter_city()
        self.enter_postal_code()
        self.enter_random_state()

    def enter_foreign_master_vendor_address(self, sam_type, country_code):
        self.select_sam_address_type(sam_type)
        self.enter_country_code(country_code)
        self.click_override_address_verification_chkbx()
        self.enter_address_one()
        self.enter_address_two()
        self.enter_city()
        self.enter_postal_code()

        if country_code == "GBR":
            self.search_for_state()
            county = LookUpStateWindow(self.driver)
            county.select_county(str(choice(GBR_COUNTIES)))
        else:
            self.search_for_state()
            state = LookUpStateWindow(self.driver)
            state.select_random_state()

    """ BEGIN CLEAN ADDRESS DEFINITIONS """

    def ca_enter_description(self, desc_text):
        self.sendkeys(desc_text, self._description_field)

    def ca_enter_effective_date(self):
        self.clear_element(self._effective_date)
        self.sendkeys("01/01/1901", self._effective_date)

    def ca_enter_address_one(self, address_1):
        self.sendkeys(address_1, self._address_1)

    def ca_enter_address_two(self, address_2):
        self.sendkeys(address_2, self._address_2)

    def ca_enter_location(self, location):
        self.sendkeys(location, self._address_2)

    def ca_enter_street(self, street):
        self.sendkeys(street, self._address_3)

    def ca_enter_address_four(self, address_4):
        self.sendkeys(address_4, self._address_4)

    def ca_enter_po_address(self, po_box):
        self.sendkeys(po_box, self._address_4)

    def ca_enter_city(self, city):
        self.sendkeys(city, self._city)

    def ca_enter_area(self, area):
        self.sendkeys(area, self._county)

    def ca_enter_district(self, district):
        self.sendkeys(district, self._city)

    def ca_enter_neighborhood(self, neighborhood):
        self.sendkeys(neighborhood, self._country)

    def ca_enter_postal(self, postal):
        self.sendkeys(postal, self._postal)
        self.util.sleep(1, "the postal to be recognized by the app.")

    def ca_enter_postal_code(self, postal_code):
        self.sendkeys(postal_code, self._postal)
        self.util.sleep(1, "the postal code to be recognized by the app.")

    def ca_enter_cap(self, cap):
        self.sendkeys(cap, self._postal)
        self.util.sleep(1, "the CAP to be recognized by the app.")

    def clear_state_field(self):
        self.clear_element(self._state)
        self.util.sleep(1, "the field to be cleared.")

    def search_for_canton(self):
        self.element_click(self._search_state)
        self.util.sleep(1, "the 'Look Up State' window to open.")

    def search_for_community(self):
        self.element_click(self._search_state)
        self.util.sleep(1, "the 'Look Up State' window to open.")

    def search_for_county(self):
        self.element_click(self._search_state)
        self.util.sleep(1, "the 'Look Up State' window to open.")

    def search_for_department(self):
        self.element_click(self._search_state)
        self.util.sleep(1, "the 'Look Up State' window to open.")

    def search_for_prefecture(self):
        self.element_click(self._search_state)
        self.util.sleep(1, "the 'Look Up State' window to open.")

    def search_for_province(self):
        self.element_click(self._search_state)
        self.util.sleep(1, "the 'Look Up State' window to open.")

    """ END CLEAN ADDRESS DEFINITIONS """
    """ CLEAN ADDRESSES """

    def clean_domestic_us_addresses(
            self,
            desc_text="UNITED STATES",
            sam_type="Corporate Info",
            address_1="The Westin New Orleans Canal Place",
            address_2="100 Rue Iberville",
            city="New Orleans",
            postal="70130"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_postal(postal)

    """ ANGUILLA """

    def clean_anguillian_address(self,
                                 desc_text="ANGUILLA",
                                 sam_type="Corporate Info",
                                 country_code="AIA",
                                 address_1="Carimar BCH Club",
                                 address_2="P.O. Box 327",
                                 city="Meads Bay",
                                 post_code="AI 2640"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.ca_enter_effective_date()
        self.select_sam_address_type(sam_type)
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_postal_code(post_code)

    """ ARGENTINA """

    def clean_argentine_address(self,
                                desc_text="ARGENTINA",
                                sam_type="Corporate Info",
                                country_code="ARG",
                                address_1="Avenida Leandro",
                                address_2="N. Alem 1193",
                                city="Bueno Aires",
                                postal="1001",
                                state="BA"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_postal(postal)
        self.search_for_state()

        sel_state = LookUpStateWindow(self.driver)
        sel_state.select_state(state)

    """ AUSTRALIA """

    def clean_australian_address(self,
                                 desc_text="AUSTRALIA",
                                 sam_type="Corporate Info",
                                 country_code="AUS",
                                 address_1="The Australian",
                                 address_2="100 Cumberland St",
                                 city="Sydney",
                                 postal="2000",
                                 state="NSW"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_postal(postal)

        self.search_for_state()
        sel_state = LookUpStateWindow(self.driver)
        sel_state.select_state(state)

    """ BARBADOS """

    def clean_barbados_address(self,
                               desc_text="BARBADOS",
                               sam_type="Corporate Info",
                               country_code="BRB",
                               address_1="The Garrison Historic Area",
                               address_2="Hastings, Christ Church",
                               city="Bridgetown",
                               post_code="BB15028"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_postal_code(post_code)

    """ BELGIUM """

    def ca_enter_number_for_belgium(self, num):
        self.sendkeys(num, self._number)

    def clean_belgian_address(self,
                              desc_text="BELGIUM",
                              sam_type="Corporate Info",
                              country_code="BEL",
                              location="Monsiuer Alain Dupont",
                              street="Rue Du Vivier",
                              number="7",
                              city="Bruxelles",
                              postal="1000",
                              province="BC"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_location(location)
        self.ca_enter_street(street)
        self.ca_enter_number_for_belgium(number)
        self.ca_enter_city(city)
        self.ca_enter_postal(postal)
        self.clear_state_field()
        self.search_for_province()

        sel_prov = LookUpStateWindow(self.driver)
        sel_prov.select_state(province)

    """ BRAZIL """

    def clean_brazilian_address(self,
                                desc_text="BRAZIL",
                                sam_type="Corporate Info",
                                country_code="BRA",
                                address_1="Rua Escritor Jorge de Limao",
                                address_2="58",
                                city="Barra de Sao Miguel",
                                neighborhood="Barra mar",
                                postal="57180-000",
                                state="AL"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_neighborhood(neighborhood)
        self.ca_enter_postal(postal)
        self.clear_state_field()

        self.search_for_state()
        sel_state = LookUpStateWindow(self.driver)
        sel_state.select_state(state)

    """ BIOT """

    def clean_british_indian_ocean_territory_address(
            self,
            desc_text="BIOT",
            sam_type="Corporate Info",
            country_code="IOT",
            address_1="BIOT Administration",
            address_2="King Charles Street",
            city="N/A",
            post_code="SW1A 2AH"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_postal_code(post_code)

    """ CANADA """

    def clean_canadian_address(self,
                               desc_text="CANADA",
                               sam_type="Corporate Info",
                               country_code="CAN",
                               address_1="Sheraton Hotel",
                               address_2="35 Rue Laurier",
                               city="Gatineau",
                               post_code="J8X 4E9",
                               province="QC"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_postal_code(post_code)

        self.search_for_province()
        sel_prov = LookUpStateWindow(self.driver)
        sel_prov.select_state(province)

    """ CHINA """

    def clean_china_address(self,
                            desc_text="CHINA",
                            sam_type="Corporate Info",
                            country_code="CHN",
                            address_1="16 Bin Shui Road",
                            address_2="He Xi District",
                            city="Tianjin",
                            post_code="300061"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_postal_code(post_code)

    """ FRANCE """

    def clean_french_address(
            self,
            desc_text="FRANCE",
            sam_type="Corporate Info",
            country_code="FRA",
            address_1="Holiday Inn Paris - Gare de Lyon Bastille",
            address_2="11 Rue de Lyon",
            city="Paris",
            postal="75012",
            department="75"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_postal(postal)
        self.clear_state_field()  # Clear Department field

        self.search_for_department()
        sel_dept = LookUpStateWindow(self.driver)
        sel_dept.select_state(department)

    """ GERMANY """

    def clean_germany_address(self,
                              desc_text="GERMANY",
                              sam_type="Corporate Info",
                              country_code="DEU",
                              address_1="Moxy Munich Messe",
                              address_2="Otto-Hahn 21",
                              city="Aschheim",
                              postal="85609",
                              state="BY"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_postal_code(postal)

        self.search_for_state()
        sel_state = LookUpStateWindow(self.driver)
        sel_state.select_state(state)

    def clean_germany_po_address(self,
                                 desc_text="GERMANY (PO BOX)",
                                 sam_type="Corporate Info",
                                 country_code="DEU",
                                 address_1="Sitfung Warentest",
                                 po_box="Postfach 3 14 41",
                                 city="Berlin",
                                 postal="10724",
                                 state="BE"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_po_address(po_box)
        self.ca_enter_city(city)
        self.ca_enter_postal_code(postal)

        self.search_for_state()
        sel_state = LookUpStateWindow(self.driver)
        sel_state.select_state(state)

    """ HONG KONG """

    def clean_hong_kong_address(self,
                                desc_text="HONG KONG",
                                sam_type="Corporate Info",
                                country_code="HKG",
                                address_1="International Commerce Center",
                                address_2="No. 1 Austin Road West",
                                district="Kowloon",
                                area="Kowloon"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_district(district)
        self.ca_enter_area(area)

    """ ISRAEL """

    def clean_israel_address(self,
                             desc_text="ISRAEL",
                             sam_type="Corporate Info",
                             country_code="ISR",
                             address_1="The Drisco Hotel",
                             address_2="Rehov Auerbach 6",
                             city="Tel Aviv",
                             postal="6100002"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_postal(postal)

    """ ITALY """

    def clean_italian_address(self,
                              desc_text="ITALY",
                              sam_type="Corporate Info",
                              country_code="ITA",
                              address_1="Via Bruno Buozzi, 35",
                              address_2="Bldg. 3",
                              city="Bozano",
                              cap="39100",
                              province="BZ"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_cap(cap)

        self.search_for_province()
        sel_prov = LookUpStateWindow(self.driver)
        sel_prov.select_state(province)

    """ JAPANESE """

    def clean_japanese_address(self,
                               desc_text="JAPAN",
                               sam_type="Corporate Info",
                               country_code="JPN",
                               address_1="1-1-43 ABENO-SUJI",
                               address_2="ABENO-KU",
                               city="Osaka",
                               postal="545-0052",
                               prefecture="27"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_postal(postal)

        self.clear_state_field()  # Clear Prefecture field
        self.search_for_prefecture()
        sel_pref = LookUpStateWindow(self.driver)
        sel_pref.select_state(prefecture)

    """ MALAYSIA """

    def clean_malaysian_address(self,
                                desc_text="MALAYSIA",
                                sam_type="Corporate Info",
                                country_code="MYS",
                                address_1="Jalan Pantai 3",
                                address_2="Dessaru",
                                city="Bandar Penawar",
                                postal="81930",
                                state="01"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_postal(postal)

        self.search_for_state()
        sel_state = LookUpStateWindow(self.driver)
        sel_state.select_state(state)

    """ MEXICO """

    def clean_mexican_address(self,
                              desc_text="MEXICO",
                              sam_type="Corporate Info",
                              country_code="MEX",
                              street_and_num_1="Mission De Los Lagos 9020",
                              street_and_num_2="Partido Iglesias",
                              colony="Ciudad",
                              city="Juarez",
                              post_code="32688",
                              state="CHIH"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(street_and_num_1)
        self.ca_enter_address_two(street_and_num_2)
        self.ca_enter_address_three(colony)
        self.ca_enter_city(city)
        self.ca_enter_postal_code(post_code)

        self.search_for_state()
        sel_state = LookUpStateWindow(self.driver)
        sel_state.select_state(state)

    """ NETHERLANDS """

    def enter_number_for_netherlands(self, num):
        self.sendkeys(num, self._number)

    def clean_netherlands_address(self,
                                  desc_text="NETHERLANDS",
                                  sam_type="Corporate Info",
                                  country_code="NLD",
                                  location="Amsterdam Marriott Hotel",
                                  street="Stadhouderskade",
                                  number="12",
                                  city="Amsterdam",
                                  postal="1054 ES",
                                  community="0776"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_location(location)
        self.ca_enter_street(street)
        self.enter_number_for_netherlands(number)
        self.ca_enter_city(city)
        self.ca_enter_postal_code(postal)

        self.search_for_community()
        sel_comm = LookUpStateWindow(self.driver)
        sel_comm.select_state(community)

    """ NEW ZEALAND """

    def clean_new_zealand_address(self,
                                  desc_text="NEW ZEALAND",
                                  sam_type="Corporate Info",
                                  country_code="NZL",
                                  address_1="The St. James",
                                  address_2="20 Chisholm Crescent",
                                  city="Hanmer Springs",
                                  postal="7360"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_postal(postal)

    """ PANAMA """

    def clean_panama_address(self,
                             desc_text="PANAMA",
                             sam_type="Corporate Info",
                             country_code="PAN",
                             address_1="La Rotunda Avenue",
                             address_2="Costa del Este",
                             city="Panama",
                             postal="1001"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_postal(postal)

    """ PHILIPPINES """

    def clean_philippines_address(self,
                                  desc_text="PHILIPPINES",
                                  sam_type="Corporate Info",
                                  country_code="PHL",
                                  address_1="1588 Pedro Gil St",
                                  address_2="Corner MH del Pilar",
                                  city="Manila",
                                  postal="1004"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_postal(postal)

    """ PORTUGAL """

    def clean_portugal_address(self,
                               desc_text="PORTUGAL",
                               sam_type="Corporate Info",
                               country_code="PRT",
                               address_1="Rua das Palmeiras",
                               address_2="Lote 5 Quinta da Marinha",
                               city="Cascais",
                               postal="2750-005"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_postal(postal)

    """ SINGAPORE """

    def clean_singapore_address(self,
                                desc_text="SINGAPORE",
                                sam_type="Corporate Info",
                                country_code="SGP",
                                address_1="Courtyard Singapore Novena",
                                address_2="99 Irrawaddy Road",
                                postal="329568"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_postal(postal)

    """ SPAIN """

    def enter_number_for_spain(self, num):
        self.sendkeys(num, self._number)

    def enter_door_for_spain(self, door):
        self.sendkeys(door, self._door)

    def clean_spain_address(self,
                            desc_text="SPAIN",
                            sam_type="Corporate Info",
                            country_code="ESP",
                            address_1="AC Hotel Coruna",
                            address_2="Enrique Marinas",
                            number="34",
                            door="A",
                            city="Coruna",
                            postal_code="15009",
                            province="C"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.enter_number_for_spain(number)
        self.enter_door_for_spain(door)
        self.ca_enter_city(city)
        self.ca_enter_postal_code(postal_code)

        self.search_for_province()
        sel_prov = LookUpStateWindow(self.driver)
        sel_prov.select_state(province)

    """ SWAZILAND """

    def clean_swaziland_address(self,
                                desc_text="SWAZILAND",
                                sam_type="Corporate Info",
                                country_code="SWZ",
                                address_1="Summerfield Botanical Garden",
                                address_2="Matshpa Valley Rd.",
                                city="Manzini",
                                postal="M200"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_postal(postal)

    """ SWITZERLAND """

    def clean_swiss_address(self,
                            desc_text="SWITZERLAND",
                            sam_type="Corporate Info",
                            country_code="CHE",
                            address_1="The Cambrian, Abelboden",
                            address_2="Dorfstrasse 7",
                            city="Adelboden",
                            postal="3715",
                            canton="BE"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_postal(postal)

        self.search_for_canton()
        sel_canton = LookUpStateWindow(self.driver)
        sel_canton.select_state(canton)

    """ UNITED KINGDOM """

    def clean_united_kingdom_address(self,
                                     desc_text="UNITED KINGDOM",
                                     sam_type="Corporate Info",
                                     country_code="GBR",
                                     address_1="160 Warfside Street",
                                     address_2="The Mailbox",
                                     city="Birmingham",
                                     post_code="B1 1RL",
                                     state="WSTMID"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_postal_code(post_code)

        self.search_for_county()
        sel_county = LookUpStateWindow(self.driver)
        sel_county.select_state(state)

    """ VIRGIN ISLANDS (BRITISH) """

    def clean_virgin_islands_british_address(
            self,
            desc_text="BRITISH VIRGIN ISLANDS",
            sam_type="Corporate Info",
            country_code="VGB",
            address_1="Frenchmans (Hotel)",
            address_2="Frenchman's Cay",
            city="Tortola",
            postal="VG100"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_postal(postal)

    """ INDIA """

    def clean_indian_address(self,
                             desc_text="INDIA",
                             sam_type="Corporate Info",
                             country_code="IND",
                             address_1="1234 Test Street",
                             address_2="BLDG 3",
                             city="Chennai",
                             post_code="600073",
                             state="TN"):
        self.clear_element(self._description_field)
        self.ca_enter_description(desc_text)
        self.select_sam_address_type(sam_type)
        self.ca_enter_effective_date()
        self.enter_country_code(country_code)
        self.ca_enter_address_one(address_1)
        self.ca_enter_address_two(address_2)
        self.ca_enter_city(city)
        self.ca_enter_postal_code(post_code)

        self.search_for_state()
        sel_state = LookUpStateWindow(self.driver)
        sel_state.select_state(state)
コード例 #11
0
class BasePage(SeleniumDriver):

    log = cl.customLogger(logging.DEBUG)

    def __init__(self, driver):

        super(BasePage, self).__init__(driver)
        self.driver = driver
        self.util = Util()
        self.bh = bh

    # === verify_title ===
    def verify_page_title(self, title_to_verify: str) -> bool:
        try:
            actual_title = self.get_title()
            return self.util.verifyTextContains(actual_title, title_to_verify)
        except:
            self.log.error("Failed to get page title")
            print_stack()
            return False

    # === css_builder ===
    def css_builder(self, element: BeautifulSoup) -> str:
        css_build = ""
        for at in element.attrs:
            value = element[at]
            css_build = css_build + "[" + at + "="
            if isinstance(value, str):
                css_build = css_build + '"' + value
            else:
                l = len(value)
                i = 1
                for v in value:
                    if i == 1:
                        css_build = css_build + '"' + v + ""
                    else:
                        css_build = css_build + '"' + v + ""
                    i = i + 1
            css_build = css_build + '"]'
        return css_build

    # === click_on_button ===
    def click_on_button(self, label: str):
        self.util.sleep(2)
        bs = self.bh(self.driver.page_source)
        button = bs.find_clickable_element(label)
        if len(button) > 0:
            css = self.css_builder(button[1])
            self.log.info(button[0] + css)
            self.element_click(button[0] + css, "css")
        else:
            self.screen_shot(result_message="button_not_found")

    # === click_on_button_given_parent ===
    def click_on_button_given_parent(self, label: str, parent: BeautifulSoup):
        self.util.sleep(2)
        bs = self.bh(self.driver.page_source)
        button = bs.find_clickable_element_sibling(text=label, parent=parent)
        if len(button) > 0:
            css = self.css_builder(button[1])
            self.log.info(button[0] + css)
            self.element_click(button[0] + css, "css")
        else:
            self.screen_shot(result_message="button_not_found")

    # === click_on_button_partial_text ===
    def click_on_button_partial_text(self, label: str):
        self.util.sleep(2)
        bs = self.bh(self.driver.page_source)
        button = bs.find_clickable_element_partial_text(partialtext=label)
        if len(button) > 0:
            css = self.css_builder(button[1])
            self.log.info(button[0] + css)
            self.element_click(button[0] + css, "css")
        else:
            self.screen_shot(result_message="button_not_found")

    # === click_on_delete_button_with_alert ===
    def click_on_delete_button_with_alert(self):
        self.click_on_button(label="Delete")
        self.util.sleep(3)
        alert_obj = self.driver.switch_to.alert
        alert_obj.accept()

    # === scroll_to_bottom ===
    def scroll_to_bottom(self):
        last_height = self.driver.execute_script(
            "return document.body.scrollHeight")
        while True:
            # Scroll down to bottom
            self.driver.execute_script(
                "window.scrollTo(0, document.body.scrollHeight);")
            # Wait to load page
            self.util.sleep(0.5)
            # Calculate new scroll height and compare with last scroll height
            new_height = self.driver.execute_script(
                "return document.body.scrollHeight")
            if new_height == last_height:
                break
            last_height = new_height

    # === click_on_link ===
    def click_on_link(self, displayText: str):
        self.driver.find_element_by_link_text(displayText).click()

    # === concate_string ===
    def concate_string(self, createString: list) -> str:
        returnString: str = ""
        for string in createString:
            returnString = returnString + string + " "
        return returnString.rstrip()

    # === tableRow ===
    def getRowReturnList(self) -> list:
        self.wait_for_element("tbody", "css", timeout=30)
        bs = self.bh(self.driver.page_source)
        return bs.get_table_rows()

    # === compare_alert_text ===
    def compare_alert_text(self, text: str) -> bool:
        return self.util.verifyTextMatch(actualText=self.alert_text(),
                                         expectedText=text)
コード例 #12
0
class Helpers:

    log = cl.customLogger(logging.DEBUG)

    def __init__(self, section):
        self.bs = BeautifulSoup(section, "html5lib")
        self.util = Util()
    
    # ===get_all_anchors===
    def get_anchor_elements(self) -> list:
        urls: list = []
        for a in self.bs.find_all('a'):
            urls.append(dict(text=a.get_text(), link=a['href']))
        return urls

    # ===get_text_all===
    def get_text_all(self, tag: str = "", attributes: dict = {}) -> str:
        elements = self.bs.find_all(tag, attributes)
        result = ""
        for element in elements:
            result = result + element.get_text() + " "
        return result
    
    # ===get_text===
    def get_text(self, tag: str = "", attributes: dict = {}) -> str:
        element = self.bs.find(tag, attributes)
        return element.get_text()

    # ===get_text_element_sibling===
    def get_text_element_sibling(
        self,
        tag: str = "",
        attributes: dict = {},
        sib_tag: str = "",
        sib_attributes: dict = {},
    ) -> str:
        parent = self.bs.find(tag, attributes)
        elements = parent.find_all(sib_tag, sib_attributes)
        result = ""
        for element in elements:
            result = result + element.get_text() + " "
        return result

    # ===count_sibling===
    def count_sibling(
        self,
        tag: str = "",
        attributes: dict = {},
        sib_tag: str = "",
        sib_attributes: dict = {},
        sib_text: str = None,
    ) -> int:
        self.util.sleep(2)
        parent = self.bs.find(tag, attributes)
        if sib_text:
            elements = parent.find_all(sib_tag, text=sib_text)
        else:
            elements = parent.find_all(sib_tag, sib_attributes)
        return len(elements)

    # === get_table_rows ===
    def get_table_rows(self) -> list:
        table = self.bs.find("table")
        tbody = table.find("tbody")
        return tbody.findAll("tr")

    # === search_row_for_element ===
    def search_row_for_element(
        self, rows: list, tag: str, attributes: dict
    ) -> BeautifulSoup:
        for row in rows:
            candidate = row.find(tag, attributes)
            if candidate:
                return row

    # === get_all_sibling_divs ===
    def get_all_sibling_divs(
        self, parent: BeautifulSoup, tag: str, attributes: dict
    ) -> list:
        return parent.find(tag, attributes).findAll("div")

    # ===get_attribute_button===
    @staticmethod
    def get_attribute_button(parent: BeautifulSoup, att: str) -> str:
        button = parent.find("button")
        return button[att]

    # ===find_clickable_element===
    def find_clickable_element(self, text: str = "") -> list:
        button = self.bs.find_all("button")
        input = self.bs.find_all("input")
        if len(button) > 0:
            self.log.info("button length: " + str(len(button)))
            for but in button:
                if self.util.verifyTextMatch(actualText=re.sub(r"\s+", "", but.get_text()), expectedText=re.sub(r"\s+", "", text)):
                    return ["button", but]
        if len(input) > 0:
            self.log.info("input length: " + str(len(input)))
            for but in input:
                if but.has_attr('value'):
                    if self.util.verifyTextMatch(actualText=but["value"], expectedText=text):
                        return ["input", but]
        return None

    # ===find_clickable_element_sibling===
    def find_clickable_element_sibling(self, text: str, parent: BeautifulSoup) -> list:
        button = parent.find_all("button")
        input = parent.find_all("input")
        if len(button) > 0:
            for but in button:
                if self.util.verifyTextMatch(actualText=re.sub(r"\s+", "", but.get_text()), expectedText=re.sub(r"\s+", "", text)):
                    return ["button", but]
        if len(input) > 0:
            for but in input:
                if but.has_attr('value'):
                    if self.util.verifyTextMatch(actualText=but["value"], expectedText=text):
                        return ["input", but]
        return None
    
    # ===find_clickable_element_partial_text===
    def find_clickable_element_partial_text(self, partialtext: str = "") -> list:
        button = self.bs.find_all("button")
        input = self.bs.find_all("input")
        if len(button) > 0:
            for but in button:
                if self.util.verifyTextContains(actualText=but.get_text(), expectedText=partialtext):
                    return ["button", but]
        if len(input) > 0:
            for but in input:
                if but.has_attr('value'):
                    if self.util.verifyTextContains(actualText=but["value"], expectedText=partialtext):
                        return ["input", but]
        return None
コード例 #13
0
class VmsPage(BasePage):

    log = cl.customLogger(logging.DEBUG)

    def __init__(self, driver):
        super().__init__(driver)
        self.driver = driver
        self.util = Util()

    # locators
    _compute = 'id-compute'
    _compute_vms = 'MenuView_vmsAnchor'
    _compute_hosts = 'MenuView_hostsAnchor'

    _new_vm_btn = 'ActionPanelView_NewVm'
    _new_host_btn = 'ActionPanelView_New'
    _management_dropdown_btn = 'ActionPanelView_Management'
    _management_dropdown_maintenance = "//div[@id='ActionPanelView_Management']//a[ contains(text(),'Maintenance') ]"
    _maintenance_dialog_ok_btn = 'HostMaintenanceConfirmationPopupView_OnMaintenance'
    _template_dropDown = "//div[@id='VmPopupWidget_templateWithVersion']/div/input"
    _cluster_dropDown = "//div[@id='VmPopupWidget_dataCenterWithCluster']//button"
    _vm_name_lbl = 'VmPopupWidget_name'
    _advanced_options_btn = 'VmPopupView_OnAdvanced'
    _resource_allocation_sideBar = "//div[@id='VmPopupWidget']//ul[@class='list-group']/li[8]"
    _thinDisk_radio = 'VmPopupWidget_provisioningThin'
    _ok_btn = 'VmPopupView_OnSave'
    _search_lbl = 'SearchPanelView_searchStringInput'
    _search_btn = 'SearchPanelView_searchButton'
    _new_vm_dialog = "class='popup-content ui-draggable'"
    _reboot_vm_btn = 'ActionPanelView_Reboot'
    _reboot_confirmation_btn = 'DefaultConfirmationPopupView_OnReboot'
    _clear_search_btn = "//div//button[@data-tooltip-content='Clear Search']"
    _run_vm_btn = "//div[@id='ActionPanelView_Run']/button[1]"

    # new hosts dialog
    _host_cluster_dropDown_btn = "//div[@id='HostPopupView_cluster']//button"
    _host_cluster_dropDown_menu = "//div[@id='HostPopupView_cluster']//ul[starts-with(@class, 'dropdown-menu')]"  # for scrolling
    _name_lbl = 'HostPopupView_name'
    _host_name_lbl = 'HostPopupView_host'  # for IP
    _password = '******'
    _ok_false_btn = 'HostPopupView_OnSaveFalse'
    _power_management_ok_btn = 'DefaultConfirmationPopupView_OnSaveInternalNotFromApprove'

    # table elements
    _table_first_column = '//table//tbody/tr[{0}]/td[1]'  # used for clicking the row. formatted to use it in multiple rows
    _vm_name_field = "//table//tbody/tr[1]//td[3]//a[contains(text(),'{0}')]"  # {0} used for inserting vm name
    _no_items_to_display = "//tbody//div[text()='No items to display']"

    # dashboard iframe
    _dashboard_iframe = "//div//iframe"
    _elem_with_virtualResources_text = "//div[contains(text(),'Virtual resources')]"
    _elem_with_lastUpdated_text = "//b[contains(text(),'Last Updated')]"

    def hover_over_compute(self):
        element_to_hover = self.getElement(self._compute)
        ActionChains(self.driver).move_to_element(element_to_hover).perform()
        time.sleep(2)
        self.util.sleep(1, 'Hover over compute to work')

    def click_new(self):
        self.elementClick(self._new_vm_btn)

    def choose_template_from_dropdown(self, template_name):
        self.util.sleep(4, 'Create vm Dialog settle down')
        tmp = self.waitForElement(self._template_dropDown, 'xpath')
        self.elementClick(self._template_dropDown, 'xpath')
        self.elementClick("//td[contains(text(), '%s')]" % template_name,
                          'xpath')

    def enter_vm_name(self):
        self.name = 'vm_selenium' + str(round(time.time() * 1000))
        self.sendKeys(self.name, self._vm_name_lbl)
        return self.name

    def enter_name_for_new_host(self):
        self.name = 'host_selenium' + str(round(time.time() * 1000))
        self.sendKeys(self.name, self._name_lbl)
        return self.name

    def select_thinDisk(self):
        self.waitForElement(self._advanced_options_btn)

        advanced_btn_text = self.getElement(self._advanced_options_btn).text
        if 'Show' in advanced_btn_text:
            self.elementClick(self._advanced_options_btn)

        self.elementClick(self._resource_allocation_sideBar, 'xpath')
        self.waitForElement(self._thinDisk_radio)
        self.elementClick(self._thinDisk_radio)

    def validate_vm_status(self, status):
        # element = self.waitForElement("//tbody//div[contains(text(),'%s')]" % status, 'xpath', timeout=60)
        element = self.waitForElement("//tbody//div[(text()='%s')]" % status,
                                      'xpath',
                                      timeout=120)
        return element is not None

    def validate_vm_name(self, vm_name):
        elem = self.waitForElement(self._vm_name_field.format(vm_name),
                                   locatorType='xpath',
                                   timeout=180)
        return elem is not None

    def search_for_selenium_vms(self, search_query, pause=3):
        self.waitForElementToDissapear(self._new_vm_dialog)
        self.waitForElementToApear(self._search_lbl)
        search_query = 'name=' + search_query
        self.sendKeys(data=search_query, locator=self._search_lbl)
        self.util.sleep(pause, 'Flickering when searching')
        self.elementClick(self._search_btn)
        self.util.sleep(pause, 'Search results settling down')

    def navigate_to_vms_page(self):
        self.hover_over_compute()
        self.elementClick(self._compute_vms)

    def navigate_to_hosts_page(self):
        self.hover_over_compute()
        self.elementClick(self._compute_hosts)

    def choose_cluster_from_dropdown(self, cluster_name):
        tmp = self.waitForElement(self._cluster_dropDown, 'xpath')
        self.elementClick(self._cluster_dropDown, 'xpath')
        self.elementClick("//li/a[contains(text(), '%s')]" % cluster_name,
                          'xpath')

    def create_new_vm_from_template(self, template_name, cluster_name):
        self.hover_over_compute()
        self.elementClick(self._compute_vms)
        self.elementClick(self._new_vm_btn)
        # self.util.sleep(3, 'Create vm Dialog settle down')
        self.choose_cluster_from_dropdown(cluster_name)
        self.choose_template_from_dropdown(template_name)

        vm_name = self.enter_vm_name()
        self.select_thinDisk()
        self.elementClick(self._ok_btn)
        self.waitForElementToDissapear(self._new_vm_dialog, 'xpath')
        return vm_name

    def create_new_host_with_ip(self, password, cluster, ip='172.16.12.223'):
        self.hover_over_compute()
        self.elementClick(self._compute_hosts)
        self.waitForElement(self._new_host_btn)
        time.sleep(1)
        self.elementClick(self._new_host_btn)
        tmp = self.waitForElement(self._host_cluster_dropDown_btn, 'xpath')
        self.elementClick(self._host_cluster_dropDown_btn, 'xpath')
        time.sleep(1)

        # drop_down_to_scroll = self.getElement(self._host_cluster_dropDown_menu, 'xpath')
        elem_to_scroll_to = self.getElement(
            "//li/a[contains(text(), '%s')]" % cluster, 'xpath')
        self.scroll_down_till_element_in_view(elem_to_scroll_to)
        self.elementClick("//li/a[contains(text(), 'L3')]//parent::*", 'xpath')
        name = self.enter_name_for_new_host()
        self.sendKeys(ip, self._host_name_lbl)
        self.sendKeys(password, self._password)
        self.elementClick(self._ok_false_btn)
        self.elementClick(self._power_management_ok_btn)
        return name

    def get_amount_of_rows_in_table(self, expected_rows_mnt):
        return self.verifyAmountOfRowsInTable(expected_rows_mnt)

    def is_iframe_rendered(self):
        self.waitForElementToApear(locator=self._dashboard_iframe,
                                   locatorType='xpath')
        self.switch_to_iframe(locator=self._dashboard_iframe,
                              locatorType='xpath')
        elems_with_virtualElements_text = self.getElements(
            self._elem_with_virtualResources_text, 'xpath')
        time.sleep(0.2)
        elem_with_lastUpdated_text = self.getElement(
            self._elem_with_lastUpdated_text, 'xpath')
        elems_with_virtualElements_text.append(elem_with_lastUpdated_text)
        result = self.are_all_elems_displayed(elems_with_virtualElements_text)
        self.driver.switch_to_default_content()
        return result

    def are_all_elems_displayed(self, elems_list):
        for elem in elems_list:
            if not self.isElementDisplayed(element=elem):
                return False
        return True

    def select_nth_row_of_the_table(self, row_number):
        # first row is 1. repeating because sometimes selection fails.
        for i in range(2):
            self.elementClick(
                locator=self._table_first_column.format(row_number),
                locatorType='xpath')

    def select_multiple_rows_from_table(self, untill_row, from_row=1):
        # from_row=1 meaning first row will be selected
        self.select_nth_row_of_the_table(row_number=from_row)
        for i in range(2):
            self.elementClickShift(
                locator=self._table_first_column.format(untill_row),
                locatorType='xpath')

    def reboot_vms(self):
        self.waitForElement(self._reboot_vm_btn)
        self.elementClick(self._reboot_vm_btn)
        self.elementClick(self._reboot_confirmation_btn)

    def clear_search_field(self):
        self.elementClick(self._clear_search_btn, locatorType='xpath')

    def search_vms_in_reboot_with_js(self):
        self.driver.execute_script(
            "document.getElementById('SearchPanelView_searchStringInput').value=''"
        )
        self.driver.execute_script(
            "document.getElementById('SearchPanelView_searchStringInput').value='name=*L1* and status=rebootinprogress'"
        )
        self.driver.execute_script(
            "document.getElementById('SearchPanelView_searchButton').click()")
        self.util.sleep(
            sec=1, info='Waiting 1 sec after search_vms_in_reboot_with_js ')
        self.log.info('Attempted to Executed JS search_vms_in_reboot_with_js')

    def wait_till_results_table_starts_painting(self):
        self.waitForElement(self._table_first_column.format('1'),
                            locatorType='xpath',
                            timeout=30)
        print('started painting')

    def wait_till_NoItemsToDisplay_appears(self):
        return self.waitForElement(self._no_items_to_display,
                                   locatorType='xpath',
                                   timeout=120)

    def click_run_vm_btn(self):
        self.waitForElement(self._run_vm_btn, 'xpath')
        self.elementClick(self._run_vm_btn, 'xpath')
コード例 #14
0
class SeleniumDrivers():
    log = cl.customLogger(logging.DEBUG)

    def __init__(self, driver):
        self.driver = driver
        self.util = Util()

    def screenShot(self, resultMessage):
        """
        Takes screenshot of the current page:
        """
        filename = resultMessage + "." + str(round(
            time.time() * 1000)) + ".png"
        screenShotDir = "../screenshots/"
        # Mindig a jelenlegi mappából számol
        relativeFileName = screenShotDir + filename
        # Get the directory name of the current file
        currentDir = os.path.dirname(__file__)
        destinationFile = os.path.join(currentDir, relativeFileName)
        destinationDir = os.path.join(currentDir, screenShotDir)

        try:
            # Check if destinationDir is exist
            if not os.path.exists(destinationDir):
                # Ha nincs ilyen mappa, létrehozza
                os.makedirs(destinationDir)
            self.driver.save_screenshot(destinationFile)
            self.log.info("Screenshot saved to directory: " + destinationFile)
        except:
            self.log.error("### Screenshot error Occured")
            #print_stack()

    def getElementList(self, locator, locatorType="xpath"):
        """
        Get list of elements
        Return: list of elements
        """
        element = None
        try:
            locatorType = locatorType.lower()
            byType = self.getByType(locatorType)
            element = self.driver.find_elements(byType, locator)
            self.log.info("Element list found with locator: " + locator +
                          " and  locatorType: " + locatorType)
            self.log.info("Elements in list :: " + element)
        except:
            self.log.info("Element list not found with locator: " + locator +
                          " and  locatorType: " + locatorType)
        return element

    def getByType(self, locatorType="xpath"):
        locatorType = locatorType.lower()
        if locatorType == "id":
            return By.ID
        elif locatorType == "name":
            return By.NAME
        elif locatorType == "xpath":
            return By.XPATH
        elif locatorType == "css":
            return By.CSS_SELECTOR
        elif locatorType == "class":
            return By.CLASS_NAME
        elif locatorType == "link":
            return By.LINK_TEXT
        elif locatorType == "tag":
            return By.TAG_NAME
        else:
            self.log.info("Locator type " + locatorType +
                          " not correct/supported")
        return False

    def getElement(self, locator, locatorType="id"):
        element = None
        try:
            locatorType = locatorType.lower()
            byType = self.getByType(locatorType)
            element = self.driver.find_element(byType, locator)
            self.log.info("Element Found with locator: " + locator +
                          " and locator type: " + locatorType)
        except:
            self.log.info("Element not found with locator: " + locator +
                          " and locator type: " + locatorType)
        return element

    def elementClick(self,
                     locator="",
                     locatorType="xpath",
                     clickNumber=1,
                     secBetweenClicks=0,
                     element=None):
        """
        Click on an element
        Either provide element or a combination of locator and locatorType
        """
        try:
            if locator:  # locator is not empty
                element = self.getElement(locator, locatorType)
            for i in range(clickNumber):
                element.click()
                self.util.sleep(secBetweenClicks)
            self.log.info("Clicked on element with locator: " + locator +
                          " locatorType: " + locatorType)
        except:
            self.log.info("Cannot click on the element with locator: " +
                          locator + " locatorType: " + locatorType)
            #print_stack()
            self.screenShot(locator + " not found")
            assert False

    def clickNearElement(self,
                         locator="",
                         xOffset=0,
                         yOffset=0,
                         locatorType="xpath"):
        """
        Click near an element
        """
        try:
            element = self.getElement(locator, locatorType)
            ActionChains(self.driver).move_to_element(
                to_element=element).move_by_offset(
                    xoffset=xOffset,
                    yoffset=yOffset).click_and_hold().release().perform()
            self.log.info("Clicked on element with locator: " + locator +
                          " locatorType: " + locatorType)
        except:
            self.log.info("Cannot click on the element with locator: " +
                          locator + " locatorType: " + locatorType)
            self.screenShot(locator + " not found")
            assert False

    def sendKeys(self, data, locator="", locatorType="xpath", element=None):
        """
        Send keys to an element
        Either provide element or a combination of locator and locatorType
        """
        try:
            if locator:  # locator is not empty
                element = self.getElement(locator, locatorType)
            element.send_keys(data)
            self.log.info("Sent data on element with locator: " + locator +
                          " locatorType: " + locatorType)
        except:
            self.log.info("Cannot send data on the element with locator: " +
                          locator + " locatorType: " + locatorType)
            #print_stack()

    def sendKeysWithEnter(self,
                          data,
                          locator="",
                          locatorType="xpath",
                          element=None):
        """
        Send keys to an element then press enter at the end
        Either provide element or a combination of locator and locatorType
        """
        try:
            if locator:  # This means if locator is not empty
                element = self.getElement(locator, locatorType)
            element.send_keys(data)
            element.send_keys(Keys.ENTER)
            self.log.info("Sent data :: " + str(data) +
                          " :: on element with locator: " + locator +
                          " locatorType: " + locatorType)
        except:
            self.log.info("Cannot send data on the element with locator: " +
                          locator + " locatorType: " + locatorType)
            #print_stack()

    def getTextByAttribute(self,
                           locator,
                           locatorType="xpath",
                           attribute="value"):
        """
        Get text from element by the element's attribute. Default attribute is "value" because its mostly used with
        input fields.
        :return: Text in element string
        """
        element = self.getElement(locator, locatorType)
        textInElement = element.get_attribute(attribute)
        return str(textInElement)

    def getText(self, locator="", locatorType="xpath", element=None, info=""):
        """
        Get 'Text' on an element
        Either provide element or a combination of locator and locatorType
        """
        try:
            if locator:  # Locator is not empty
                element = self.getElement(locator, locatorType)
            text = element.text
            self.log.debug("After finding element, size is: " + str(len(text)))
            if len(text) == 0:
                text = element.get_attribute("innerText")
            if len(text) != 0:
                self.log.info("The text is :: '" + text + "'")
                text = text.strip()
        except:
            self.log.error("Failed to get text on element " + info)
            #print_stack()
            text = None
        return text

    def getTexts(self, locator="", locatorType="xpath"):
        textList = []
        """
        Get 'Texts' from elements, and put the elements into a list
        """
        try:
            elementList = self.getElementList(locator, locatorType)
            self.log.debug("Element length: " + str(len(elementList)))
            for element in range(len(elementList)):
                text = elementList[element].text
                textList.append(text)
        except:
            self.log.error("Failed to get text on element")
        self.log.info("Elements in list :: " + str(textList))
        return textList

    def clearKeys(self, locator, locatorType="xpath"):
        try:
            element = self.getElement(locator, locatorType)
            element.clear()
        except:
            self.log.info("Cannot clear data on the element: " + locator +
                          " LocatorType: " + locatorType)

    def isElementPresent(self, locator="", locatorType="xpath", element=None):
        """
        Check if element is present
        Either provide element or a combination of locator and locatorType
        """
        try:
            if locator:  # This means if locator is not empty
                element = self.getElement(locator, locatorType)
            if element is not None:
                self.log.info("Element present with locator: " + locator +
                              " locatorType: " + locatorType)
                return True
            else:
                self.log.info("Element not present with locator: " + locator +
                              " locatorType: " + locatorType)
                return False
        except:
            print("Element not found")
            return False

    def isElementDisplayed(self,
                           locator="",
                           locatorType="xpath",
                           element=None):
        """
        Check if element is displayed
        Either provide element or a combination of locator and locatorType
        """
        isDisplayed = False
        try:
            if locator:  # This means if locator is not empty
                element = self.getElement(locator, locatorType)
            if element is not None:
                isDisplayed = element.is_displayed()
                self.log.info("Element is displayed with locator: " + locator +
                              " locatorType: " + locatorType)
            else:
                self.log.info("Element not displayed with locator: " +
                              locator + " locatorType: " + locatorType)
            return isDisplayed
        except:
            print("Element not found")
            return False

    def isElementNotDisplayed(self, element, locatorType="xpath"):
        """
        :param element: Element to check
        :param locatorType: Locatory type, default xpath
        :return: True if element is NOT displayed, False if element is displayed
        """
        isElementDisplayed = self.getElementList(element, locatorType)
        self.log.info("Element length (0 if NOT displayed) :: " +
                      str(len(isElementDisplayed)))
        if len(isElementDisplayed) == 0:
            return True
        else:
            return False

    def waitUntilElementIsDisplayed(self,
                                    locator,
                                    locatorType="xpath",
                                    timeout=10,
                                    pollFrequency=0.5):
        try:
            wait = WebDriverWait(self.driver,
                                 timeout=timeout,
                                 poll_frequency=pollFrequency,
                                 ignored_exceptions=[
                                     NoSuchElementException,
                                     ElementNotSelectableException
                                 ])
            element = self.getElement(locator, locatorType="xpath")
            displayedElement = wait.until(
                EC.visibility_of_element_located(element))
            self.log.info("Element " + locator + " is displayed")
            return displayedElement

        except:
            self.log.info("Element not found")

    def elementPresenceCheck(self, locator, byType="xpath"):
        try:
            elementList = self.driver.find_elements(byType, locator)
            if len(elementList) > 0:
                self.log.info("Element presence is Found with locator: " +
                              locator + "with type: " + byType)
                return True
            else:
                self.log.info("Element not found with locator: " + locator +
                              "with type: " + byType)
                return False
        except:
            self.log.info("Element not found")
            return False

    def waitForElement(self,
                       locator,
                       locatorType="xpath",
                       timeout=10,
                       pollFrequency=0.5):
        element = None
        try:
            byType = self.getByType(locatorType)
            self.log.info("Waiting for maximum :: " + str(timeout) +
                          " :: seconds for element to be clickable")
            wait = WebDriverWait(self.driver,
                                 timeout=timeout,
                                 poll_frequency=pollFrequency,
                                 ignored_exceptions=[
                                     NoSuchElementException,
                                     ElementNotVisibleException,
                                     ElementNotSelectableException
                                 ])
            element = wait.until(EC.element_to_be_clickable((byType, locator)))
            self.log.info("Element " + locator + " appeared on the web page")
        except:
            self.log.info("Element " + locator +
                          " not appeared on the web page")
            #print_stack()
        return element

    def isElementEnabled(self, locator, locatorType="xpath"):
        """
        Megnézi egy elem-ben van-e 'disabled' parameter
        :param locator:
        :param locatorType:
        :return: Boolean
        """
        element = self.getElement(locator, locatorType)
        elementStatus = element.is_enabled()
        if elementStatus == True:
            self.log.info("Element with locator: " + locator + " is enabled.")
        elif elementStatus == False:
            self.log.info("Element with locator: " + locator +
                          " is NOT enabled.")
        return elementStatus

    def getPageTitle(self):
        return self.driver.title

    def webScroll(self, value, direction="down"):
        if direction == "up":
            # Scroll Up
            self.driver.execute_script(
                "window.scrollBy(0, {}});".format(value))

        if direction == "down":
            # Scroll Down
            self.driver.execute_script("window.scrollBy(0, {});".format(value))

    def mouseHover(self, locator, locatorType="xpath"):
        actions = ActionChains(self.driver)
        elementToHover = self.getElement(locator, locatorType)
        actions.move_by_offset(0, 0).perform()
        actions.move_to_element(elementToHover).perform()
        self.log.info("Hoovering on element :: " + locator)

    def selectFromDropDownWithKeys(self, element, selection):
        self.elementClick(element)
        dropDown = self.getElement(element)
        try:
            for i in range(0, selection):
                dropDown.send_keys(Keys.ARROW_DOWN)
                self.log.info("Moving down on dropdown by: " + str(i + 1))
            dropDown.send_keys(Keys.ENTER)
        except:
            self.screenShot("DropDownSelectionFailed")
            self.log.error("Moving down on dropdown list failed")

    # def webScrollToElement(self, locator, locatoryType="xpath"):
    #     element = self.getElement(locator, locatoryType)
    #     self.driver.execute_script("arguments[0].scrollIntoView(true)", element)

    def webScrollToElement(self, locator, locatorType="xpath"):
        ActionChains(self.driver).move_to_element(
            self.getElement(locator, locatorType)).perform()
        self.log.info("Scrolled to element :: " + locator)

    def getAttributeValue(self, attribute, locator, locatorType="xpath"):
        element = self.getElement(locator, locatorType)
        elementAttributeValue = element.get_attribute(attribute)
        self.log.info("Locator: '" + locator + "' attribute value = " +
                      elementAttributeValue)
        return elementAttributeValue

    def checkFieldMaxLenght(self,
                            maxLenght,
                            charNumber,
                            locator,
                            locatorType="xpath"):
        """
        Létrehoz egy 'maxlenght' hosszú random karaktersorozatot + 1 karaktert (a plusz karatkernek nem szabadna belekerülnie az input mezőbe)
        összehasonlítja a maxHossz + 1 karakterek hosszát a beírt karakterek hosszával
        maxLenght: Field max hossza, bussinnes logic alapján
        charNumber: Beütni kívánt karakterek száma
        """
        inputChars = self.util.getAlphaNumeric(charNumber, "mix")
        self.sendKeys(inputChars, locator, locatorType)
        self.log.info("Random chars: " + inputChars)
        # With attribute "value" it gives back the characters in the input field
        wroteText = self.getAttributeValue("value", locator, locatorType)
        self.log.info("Wrote chars: " + wroteText)
        assert maxLenght == len(wroteText)

    def rowCountInTable(self, locator, locatorType="xpath", headerRows=0):
        # Counts the rows in table
        # headerRows: Skip the given rows. Useful if there is a header row
        rows = len(self.getElementList(locator, locatorType))
        self.log.info("Rows in table = " + str(rows - headerRows))
        return rows

    def columnCountInTable(self, tableXpath, rowColumnCount=0):
        # Return the width of a table
        # rowColumnNum: From which row should we count the columns
        columns = len(
            self.getElementList(
                tableXpath + "/tbody/tr[" + str(rowColumnCount) + "]/td",
                "xpath"))
        self.log.info("Columns in table = " + str(columns))
        return columns

    def getSizeofTable(self,
                       locator,
                       locatorType,
                       headerRows=0,
                       rowColumnCount=0):
        return {
            "Rows": self.rowCountInTable(locator, locatorType, headerRows),
            "Columns": self.columnCountInTable(rowColumnCount)
        }

    def getAllData(self):
        allData = []
        rowNum = self.rowCountInTable("//tbody/tr", "xpath")
        columnWidth = self.columnCountInTable()
        for i in range(0, rowNum):
            ro = []
            for j in range(1, columnWidth):
                element = self.getElement(
                    "//tbody/tr[" + str(i + 1) + "]/td[" + str(j) + "]",
                    "xpath")
                text = element.text
                text = text.strip()
                ro.append(text)
            allData.append(ro)
        self.log.info("Alldata: " + str(allData))
        return allData

    def presence_of_data(self, data, locator, locatorType="xpath"):
        dataSize = len(
            self.getElement("//*[contains(text(),'" + data + "')]", "xpath"))
        presence = False
        if dataSize > 0:
            presence = True
            self.log.info("The following data is presence :: " + data)
        else:
            self.log.info("The following data is not presence :: " + data)
        return presence

    def getRowData(self,
                   tableXpath,
                   columnWidth,
                   rowNum=1,
                   headerRow=1,
                   locatorType="xpath"):
        #self.log.debug("Method " + str(__name__) + " started")
        rowData = []
        rowElements = self.getElementList(
            tableXpath + "//tr[" + str(rowNum + headerRow) + "]/td",
            locatorType)
        for rowElement in range(columnWidth):
            elementText = rowElements[rowElement].text
            rowData.append(elementText)
        self.log.info("Data in row number :: " + str(rowNum) + " is: " +
                      str(rowData))
        return rowData

    def getColumnData(self,
                      tableXpath,
                      column,
                      rowsInColumn,
                      headerRow=0,
                      locatorType="xpath",
                      infoText=""):
        columnData = []
        columnElements = self.getElementList(tableXpath + "//tr/td[" +
                                             str(column) + "]")
        for columnElement in range(rowsInColumn):
            elementText = columnElements[columnElement].text
            columnData.append(elementText)
        self.log.info("Data in column number :: " + str(column) + " is: " +
                      str(columnData) + " " + infoText)
        return columnData

    def tableColumnSorterCheck(self,
                               tableXpath,
                               column,
                               rowsInColumn,
                               sortingBtnLocator,
                               sortingBtnLocatorType="xpath",
                               numberOfClicks=1,
                               sortMethod="asc"):
        unsortedColumnData = self.getColumnData(tableXpath, column,
                                                rowsInColumn)
        sortedList = self.util.sortingList(list=unsortedColumnData,
                                           method=sortMethod)
        for i in range(0, numberOfClicks):
            self.elementClick(sortingBtnLocator, sortingBtnLocatorType)
        sortedListByWeb = self.getColumnData(tableXpath, column, rowsInColumn)
        if sortMethod == "asc":
            self.log.info("The list is ascending")
        else:
            self.log.info("The list is descending")
        self.log.info("The two lists are equal.")
        self.log.info("List sorted by code :: " + str(sortedList))
        self.log.info("List sorted by web :: " + str(sortedListByWeb))
        if sortedList == sortedListByWeb:
            return True
        else:
            return False

#//table[@id='myTable2']//tr/td[1]
# unsortedColumnData = self.basePage.getColumnData(tableXpath=self.appUsersPage._appUsersTable, column=1, rowsInColumn=3, infoText="Raw column data")
# descSortedList = self.util.sortingList(list=unsortedColumnData, method="desc")
# self.appUsersPage.clickOnNameFilter()
# descSort = self.basePage.getColumnData(tableXpath=self.appUsersPage._appUsersTable, column=1, rowsInColumn=3, infoText="Desc sort by web")
# assert descSortedList == descSort

    def getPageTitle(self):
        actualTitle = self.driver.title
        self.log.info("The page title is: " + str(actualTitle))
        return actualTitle

    def assertTitle(self, actualTitle, exceptedTitle):
        self.log.debug("Title assertation function started")
        self.log.debug("Actual title :: " + str(actualTitle))
        self.log.debug("exceptedTitle :: " + str(exceptedTitle))
        if actualTitle == exceptedTitle:
            self.log.debug("Title assert True")
            return True
        else:
            self.log.debug("Title assert False")
            return False

    ### Select option(s) from dropdown

    def selectFromDropdownByVisibleText(self,
                                        visibleText,
                                        locator,
                                        locatorType="xpath"):
        dropDownElement = Select(self.getElement(locator, locatorType))
        dropDownElement.select_by_visible_text(visibleText)
        self.log.info("Option with visible text:: " + str(visibleText) +
                      " :: selected from dropdown")

    def selectFromDropdownByIndex(self, index, locator, locatorType="xpath"):
        dropDownElement = Select(self.getElement(locator, locatorType))
        dropDownElement.select_by_index(index)
        self.log.info("Option with index :: " + str(index) +
                      " :: selected from dropdown")

    def selectFromDropdownByValue(self, value, locator, locatorType="xpath"):
        dropDownElement = Select(self.getElement(locator, locatorType))
        dropDownElement.select_by_value(value)
        self.log.info("Option with value :: " + str(value) +
                      " :: selected from dropdown")

    def getParentRowElementsByChildFromTable(self, elementText):
        """
        "//td[contains(text(), 'List test 3')]//parent::tr"
        :param elementText: Text on child element (text in a record)
        :return: List of elements from the parent (all elements from the childs row)
        """
        tableRowElements = []
        elementsInRow = self.getElementList(
            "//td[contains(text(), '" + str(elementText) +
            "')]//parent::tr/td[@class='MuiTableCell-root MuiTableCell-body material-table__cell']"
        )
        self.log.info("list len " + str(len(elementsInRow)))
        for elements in range(1, len(elementsInRow)):
            textInElement = elementsInRow[elements].text
            self.log.debug("textOnElement: " + textInElement)
            tableRowElements.append(textInElement)
        self.log.info("Elements in row :: " + str(tableRowElements) +
                      " from child: " + str(elementText))
        return tableRowElements
コード例 #15
0
class AddressPage(BasePage):
    log = cl.custom_logger(logging.DEBUG)

    def __init__(self, driver):
        super().__init__(driver)
        self.driver = driver
        self.util = Util()
        self.check = SeleniumDriver(self.driver)
        self.id_info = IdentifyingInformationPage(self.driver)

    # LOCATORS
    _summary_tab = "//a//span[contains(text(), 'ummary')]"  # XPATH
    _identifying_info_tab = "//a//span[contains(text(), 'dentifying Information')]"  # XPATH
    _contacts_tab = "//a//span[contains(text(), 'ontacts')]"  # XPATH
    _location_tab = "//span[text() = 'ocation']"  # XPATH
    _custom_tab = "//a//span[contains(text(), 'C')]"  # XPATH
    _supplier_name = "VENDOR_NAME1"
    _description_field = "VNDR_ADDR_SCROL_DESCR$0"
    _sam_address_type = "VNDR_ADDR_SCROL_CCR_ADDR_TYPE$0"
    _add_new_address_btn = "$ICField2$new$0$$0"
    _country = "VENDOR_ADDR_COUNTRY$0"
    _address_1 = "VENDOR_ADDR_ADDRESS1$0"
    _address_2 = "VENDOR_ADDR_ADDRESS2$0"
    _address_3 = "VENDOR_ADDR_ADDRESS3$0"
    _address_4 = "VENDOR_ADDR_ADDRESS4$0"
    _number = "VENDOR_ADDR_NUM1$0"
    _door = "VENDOR_ADDR_NUM2$0"
    _city = "VENDOR_ADDR_CITY$0"
    _county = "VENDOR_ADDR_COUNTY$0"
    _state = "VENDOR_ADDR_STATE$0"
    _postal = "VENDOR_ADDR_POSTAL$0"
    _email_id = "VENDOR_ADDR_EMAILID$0"
    _override_address_box = "CLN_OVERRIDE_ADDRESS"
    _expand_alt_names_arrow = "//a[@class='PSHYPERLINK PTEXPAND_ARROW']"  # XPATH
    _collapse_alt_names_arrow = "//a[@class='PSHYPERLINK PTCOLLAPSE_ARROW']"  # XPATH
    _pmnt_alt_name_1 = "VENDOR_ADDR_NAME1$17$$0"
    _pmnt_alt_name_2 = "VENDOR_ADDR_NAME2$0"
    _wh_alt_name_1 = "VENDOR_ADDR_NAME1_WTHD$21$$0"
    _wh_alt_name_2 = "VENDOR_ADDR_NAME2_WTHD$0"
    _phone_type = "VENDOR_ADDR_PHN_PHONE_TYPE$0"
    _telephone_field = "VENDOR_ADDR_PHN_PHONE$0"
    _extension_field = "VENDOR_ADDR_PHN_EXTENSION$0"
    _add_new_row_phone = "VENDOR_ADDR_PHN$new$0$$0"
    _search_for_country = "VENDOR_ADDR_COUNTRY$prompt$0"
    _search_for_state = "VENDOR_ADDR_STATE$prompt$0"
    _effective_date = "VENDOR_ADDR_EFFDT$0"

    """ Get the elements """
    def get_sam_address_type(self):
        return self.driver.find_element(By.ID, self._sam_address_type)

    def get_phone_type(self):
        return self.driver.find_element(By.ID, self._phone_type)

    """ Do something with the elements """
    def click_location_tab(self):
        self.element_click(self._location_tab, "xpath")
        wait = WebDriverWait(self.driver, 10, poll_frequency=1)
        wait.until(ec.visibility_of_element_located((By.LINK_TEXT, "Payables")))

    def click_contacts_tab(self):
        self.element_click(self._contacts_tab, "xpath")
        self.util.sleep(2, "the Contacts page to open.")

    def enter_description(self):
        sup_name = self.driver.find_element(By.ID, "VENDOR_NAME1").text
        self.sendkeys(sup_name, self._description_field)

    def select_sam_address_type(self, sam_type):
        sel = Select(self.get_sam_address_type())
        sel.select_by_visible_text(sam_type)

    def enter_country_code(self, country_code):
        self.clear_element(self._country)
        self.sendkeys(country_code, self._country)
        self.sendkeys(Keys.TAB, self._country)
        self.util.sleep(1, "the country code to be recognized by the app.")

    def click_add_new_address_btn(self):
        self.element_click(self._add_new_address_btn)
        self.util.sleep(1)

    def enter_address_one(self):
        fake_data = Faker()
        fake_street_address = fake_data.street_address()
        self.sendkeys(fake_street_address, self._address_1)

    def enter_address_two(self):
        random_num = randint(1, 10)
        self.sendkeys("Bldg. " + str(random_num), self._address_2)

    def enter_address_three(self):
        self.sendkeys("N/A", self._address_3)

    def enter_city(self):
        fake_data = Faker()
        fake_city = fake_data.city()
        self.sendkeys(fake_city, self._city)

    def enter_postal_code(self):
        fake_data = Faker()
        fake_postal_code = fake_data.postalcode()
        self.sendkeys(fake_postal_code, self._postal)
        self.util.sleep(1, "the postal code to be recognized by the app.")

    def enter_random_state(self):
        self.sendkeys(str(choice(STATE_ABBR)), self._state)
        self.util.sleep(1, "the state to be recognized by the app.")

    def enter_email_id(self):
        fake_data = Faker()
        fake_email = fake_data.safe_email()
        self.sendkeys(fake_email, self._email_id)
        self.util.sleep(1, "the email to be recognized by the app.")

    def click_override_address_verification_chkbx(self):
        self.element_click(self._override_address_box)
        self.util.sleep(1, "the app recognizes the override.")

    def expand_alternate_names(self):
        self.element_click(self._expand_alt_names_arrow, "xpath")

    def collapse_alternate_names(self):
        self.element_click(self._collapse_alt_names_arrow, "xpath")

    def click_add_new_phone_btn(self):
        self.element_click(self._add_new_row_phone)

    def search_for_state(self):
        self.element_click(self._search_for_state)

    def enter_random_gb_county(self):
        self.sendkeys(str(choice(GBR_COUNTIES)), self._state)
        self.util.sleep(2, "the state to be recognized by the app.")

    def enter_pmnt_alt_name_1(self):
        fake_data = Faker()
        fake_name = fake_data.name()
        self.sendkeys(fake_name, self._pmnt_alt_name_1)

    def enter_pmnt_alt_name_2(self):
        fake_data = Faker()
        fake_name = fake_data.name()
        self.sendkeys(fake_name, self._pmnt_alt_name_2)

    def enter_withholding_alt_name_1(self):
        fake_data = Faker()
        fake_name = fake_data.name()
        self.sendkeys(fake_name, self._wh_alt_name_1)

    def enter_withholding_alt_name_2(self):
        fake_data = Faker()
        fake_name = fake_data.name()
        self.sendkeys(fake_name, self._wh_alt_name_2)

    """ THIS IS THE MODULE THAT IS CALLED BY THE TEST """
    def enter_payment_withholding_alt_names(self):
        # expanded = self.check.element_presence_check(self._pmnt_alt_name_1)
        expanded = self.check.is_element_present(self._pmnt_alt_name_1)
        print(expanded)
        if expanded:
            self.enter_pmnt_alt_name_1()
            self.enter_pmnt_alt_name_2()
            self.enter_withholding_alt_name_1()
            self.enter_withholding_alt_name_2()
        else:
            self.expand_alternate_names()
            self.check.wait_for_element(self._pmnt_alt_name_1)
            self.enter_pmnt_alt_name_1()
            self.enter_pmnt_alt_name_2()
            self.enter_withholding_alt_name_1()
            self.enter_withholding_alt_name_2()

    def enter_business_phone(self):
        sel = Select(self.get_phone_type())
        sel.select_by_visible_text("Business Phone")

        fake_data = Faker()
        fake_phone = fake_data.random_int(min=2000000, max=9999999)

        self.sendkeys("555" + str(fake_phone), self._telephone_field)
        self.element_click(self._add_new_row_phone)
        self.util.sleep(2, "the new phone row to be recognized by the app.")

    def enter_fax(self):
        sel = Select(self.get_phone_type())
        sel.select_by_visible_text("FAX")

        fake_data = Faker()
        fake_phone = fake_data.random_int(min=2000000, max=9999999)

        self.sendkeys("555" + str(fake_phone), self._telephone_field)
        self.element_click(self._add_new_row_phone)
        self.util.sleep(2, "the new phone row to be recognized by the app.")

    def enter_trilogie_dm_fax(self):
        sel = Select(self.get_phone_type())
        sel.select_by_visible_text("Trilogie DM Fax Number")

        fake_data = Faker()
        fake_phone = fake_data.random_int(min=2000000, max=9999999)

        self.sendkeys("555" + str(fake_phone), self._telephone_field)
        self.element_click(self._add_new_row_phone)
        self.util.sleep(2, "the new phone row to be recognized by the app.")

    def enter_all_phone_types(self):
        phone_type_list = ['Business Phone', 'FAX', 'Trilogie DM Fax Number']

        for phone_type in phone_type_list:
            sel = Select(self.get_phone_type())
            sel.select_by_visible_text(phone_type)

            fake_data = Faker()
            fake_phone = fake_data.random_int(min=2000000, max=9999999)

            self.sendkeys("555" + str(fake_phone), self._telephone_field)
            self.element_click(self._add_new_row_phone)
            self.util.sleep(2, "the new phone row to be recognized by the app.")

    def enter_domestic_master_vendor_address(self, sam_type):
        self.select_sam_address_type(sam_type)

        result = self.driver.find_element(By.ID, self._override_address_box).is_selected()
        if result:
            print('Checkbox already selected')
        else:
            self.driver.find_element(By.ID, self._override_address_box).click()
            print('Checkbox selected')

        self.enter_address_one()
        self.enter_address_two()
        self.enter_city()
        self.enter_postal_code()
        self.enter_random_state()

    def enter_corporate_info_address_domestic(self):
        self.enter_domestic_master_vendor_address("Corporate Info")
        self.enter_email_id()
        self.enter_business_phone()
        self.enter_fax()
        self.enter_trilogie_dm_fax()

    def enter_remit_address_domestic(self):
        self.enter_domestic_master_vendor_address("Remit")
        self.enter_email_id()
        self.enter_business_phone()
        self.enter_fax()
        self.enter_trilogie_dm_fax()

    def enter_po_address_domestic(self):
        self.enter_domestic_master_vendor_address("Trilogie PO Address")
        self.enter_email_id()
        self.enter_business_phone()
        self.enter_fax()
        self.enter_trilogie_dm_fax()

    def enter_foreign_master_vendor_address(self, sam_type, country_code):
        self.select_sam_address_type(sam_type)
        self.element_click(self._search_for_country)
        country = LookUpCountryWindow(self.driver)
        country.select_country(country_code)
        result = self.driver.find_element(By.ID, self._override_address_box).is_selected()
        if result:
            print('Checkbox already selected')
        else:
            self.driver.find_element(By.ID, self._override_address_box).click()
            print('Checkbox selected')

        self.enter_address_one()
        self.enter_address_two()
        self.enter_city()
        self.enter_postal_code()

        if country_code == "GBR":
            self.search_for_state()
            county = LookUpStateWindow(self.driver)
            county.select_county(str(choice(GBR_COUNTIES)))
        else:
            self.search_for_state()
            state = LookUpStateWindow(self.driver)
            state.select_random_state()
コード例 #16
0
class LocationPage(BasePage):
    log = cl.custom_logger(logging.DEBUG)

    def __init__(self, driver):
        super().__init__(driver)
        self.driver = driver

        self.util = Util()

    # LOCATORS
    _navbar_actions_list = "pthdr2ActionList"
    _actions_list_sign_out = "pthdr2signout"
    _summary_tab = "//a//span[contains(text(), 'ummary')]"  # XPATH
    _identifying_info_tab = "//a//span[contains(text(), 'dentifying Information')]"  # XPATH
    _address_tab = "//a//span[contains(text(), 'ddress')]"  # XPATH
    _contacts_tab = "//a//span[contains(text(), 'ontacts')]"  # XPATH
    _custom_tab = "//a//span[contains(text(), 'C')]"  # XPATH
    _location_field = "VNDR_LOC_SCROL_VNDR_LOC$0"
    _description_field = "VNDR_LOC_SCROL_DESCR$0"
    _sam_type = "VNDR_LOC_SCROL_CCR_ADDR_TYPE$0"
    _add_location_btn = "$ICField5$new$0$$0"
    _payables_link = "Payables"  # LINK_TEXT
    _procurement_link = "Procurement"  # LINK_TEXT
    _sales_use_tax_link = "Sales/Use Tax"  # LINK_TEXT
    _global_1099_withholding_link = "Global/1099 Withholding"  # LINK_TEXT
    _fei_trilogie_xref_link = "FEI Trilogie Xref"  # LINK_TEXT
    _save_button = "#ICSave"
    # SAVE WARNING
    _yes_button = "ptpopupmsgbtn1"
    _no_button = "ptpopupmsgbtn2"
    """ GET ELEMENT """

    def get_sam_type(self):
        return self.driver.find_element(By.ID, self._sam_type)

    """ DO SOMETHING WITH ELEMENTS """

    def click_summary_tab(self):
        wait = WebDriverWait(self.driver, 30, poll_frequency=1)
        wait.until(
            ec.visibility_of_element_located((By.XPATH, self._summary_tab)))
        self.element_click(self._summary_tab, "xpath")
        wait.until(
            ec.visibility_of_element_located(
                (By.XPATH, "//span[contains(text(), 'Last Modified By')]")))

    def enter_location(self, location):
        self.sendkeys(location, self._location_field)

    def enter_description(self, description):
        self.sendkeys(description, self._description_field)

    def select_sam_type(self):
        sel = Select(self.get_sam_type())
        sel.select_by_visible_text("Remit")

    def click_add_location_btn(self):
        self.element_click(self._add_location_btn)
        self.util.sleep(2, "'Location' field is cleared")

    def click_payables_link(self):
        self.element_click(self._payables_link, "link")
        self.driver.switch_to.default_content()
        wait = WebDriverWait(self.driver, 10, poll_frequency=1)
        wait.until(
            ec.visibility_of_element_located(
                (By.XPATH, "//iframe[contains(@id, 'ptModFrame_')]")))
        try:
            iframe = self.driver.find_element(
                By.XPATH, "//iframe[contains(@id, 'ptModFrame_')]")
            self.driver.switch_to.frame(iframe)
        except Exception as e:
            print(e)

    def click_procurement_link(self):
        self.element_click(self._procurement_link, "link")
        self.driver.switch_to.default_content()
        wait = WebDriverWait(self.driver, 10, poll_frequency=1)
        wait.until(
            ec.visibility_of_element_located(
                (By.XPATH, "//iframe[contains(@id, 'ptModFrame_')]")))
        try:
            iframe = self.driver.find_element(
                By.XPATH, "//iframe[contains(@id, 'ptModFrame_')]")
            self.driver.switch_to.frame(iframe)
        except Exception as e:
            print(e)

    def click_fei_trilogie_xref_link(self):
        self.element_click(self._fei_trilogie_xref_link, "link")

        self.driver.switch_to.default_content()

        wait = WebDriverWait(self.driver, 10, poll_frequency=1)
        wait.until(
            ec.visibility_of_element_located(
                (By.XPATH, "//iframe[contains(@id, 'ptModFrame_')]")))

        try:
            iframe = self.driver.find_element(
                By.XPATH, "//iframe[contains(@id, 'ptModFrame_')]")
            self.driver.switch_to.frame(iframe)
        except Exception as e:
            print(e)

    def click_save_btn(self):
        self.element_click(self._save_button)

        self.util.sleep(10,
                        "a warning message to be displayed, if applicable.")

        self.driver.switch_to.default_content()
        warning_msg = self.is_element_present(
            "//div[contains(@id, 'ptModTable_')]", "xpath")

        if warning_msg:
            print("Warning Message Displayed!")
            ok_btn = self.driver.find_element(By.ID, "#ICOK")
            ok_btn.click()

            try:
                iframe = self.driver.find_element(By.ID, "ptifrmtgtframe")
                self.driver.switch_to.frame(iframe)
            except Exception as e:
                print(e)
        else:
            print("No Warning Message!")
            self.driver.switch_to.frame("ptifrmtgtframe")

    def click_actions_list_icon(self):
        self.element_click(self._navbar_actions_list)

    def click_sign_out(self):
        self.element_click(self._actions_list_sign_out)
        wait = WebDriverWait(self.driver, 10, poll_frequency=1)
        wait.until(ec.visibility_of_element_located((By.ID, "userid")))

    """ SAVE WARNING Elements """

    def click_no_button(self):
        self.driver.switch_to.default_content()
        self.element_click(self._no_button)

    """ THESE MODULES ARE CALLED BY THE TEST """

    def add_location(self, location, description):
        self.enter_location(location)
        self.enter_description(description)
        self.select_sam_type()

    def sign_out_location_page(self):
        self.driver.switch_to.default_content()
        self.click_actions_list_icon()
        self.click_sign_out()
        self.click_no_button()

    def verify_supplier_id(self):
        result = self.is_element_present("//span[@id='VENDOR_VENDOR_ID']",
                                         locator_type="path")

        return result
コード例 #17
0
class IdentifyingInformationPage(BasePage):
    log = cl.custom_logger(logging.DEBUG)

    def __init__(self, driver):
        super().__init__(driver)
        self.driver = driver
        self.util = Util()

    # LOCATORS
    _new_window_link = "New Window"  # LINK_TEXT
    _help_link = "Help"  # LINK_TEXT
    _personalize_page = "Personalize Page"  # LINK_TEXT
    _summary_tab = "//span[contains(text(), 'ummary')]"  # XPATH
    _address_tab = "//span[contains(text(), 'ddress')]"  # XPATH
    _contacts_tab = "//span[contains(text(), 'ontacts')]"  # XPATH
    _location_tab = "//span[contains(text(), 'ocation')]"  # XPATH
    _custom_tab = "//span[contains(text(), 'C')]"  # XPATH
    _supplier_name_txt = "VENDOR_NAME1"
    _supplier_short_name_txt = "VENDOR_VNDR_NAME_SHRT_USR"
    _fei_trl_attributes_link = "FEI TRL Attributes"  # LINK_TEXT
    _additional_id_numbers_arrow = "VNDR_MAINT_WRK_VNDR_ID_PB"
    _customer_id = "VENDOR_CUST_ID"
    _id_num_type = "STD_ID_NUM_QUAL$0"
    _id_number = "STD_ID_NUM$0"
    _add_id_number_btn = "BUS_UNIT_IDS_AP$new$0$$0"

    def enter_supplier_name(self):
        fake_data = Faker()
        fake_company = fake_data.company()
        self.sendkeys("TEST_QA_" + fake_company, self._supplier_name_txt)

    def enter_supplier_short_name(self):
        random_num = randint(999, 9999)
        self.sendkeys("QATST_" + (str(random_num)),
                      self._supplier_short_name_txt)

    def click_fei_trl_attr_link(self):
        self.element_click(self._fei_trl_attributes_link, locator_type="link")
        self.util.sleep(1, "the active window to be recognized by the app.")
        self.driver.switch_to.default_content()
        try:
            iframe = self.driver.find_element(
                By.XPATH, "//iframe[contains(@id, 'ptModFrame_')]")
            self.driver.switch_to.frame(iframe)
        except Exception as e:
            print(e)

    def expand_additional_id_numbers(self):
        self.element_click(self._additional_id_numbers_arrow)

    def enter_id_type(self, id_type):
        self.sendkeys(id_type, self._id_num_type)

    def enter_id_number(self):
        self.util.sleep(2, "the ID Type to be recognized by the app.")
        random_num = randint(100000000, 999999999)
        self.sendkeys(random_num, self._id_number)

    def click_add_id_number_btn(self):
        self.element_click(self._add_id_number_btn)

    def click_address_tab(self):
        self.element_click(self._address_tab, "xpath")
        self.util.sleep(2, "the Address page to open.")

    """ THE MODULE THAT GETS CALLED BY THE TEST """

    def enter_identifying_info(self, id_type):
        self.enter_supplier_name()
        self.enter_supplier_short_name()

        self.util.sleep(
            1, "the Supplier's Short Name to be recognized by the app.")
        """ SELECT FEI Trl Attribute """
        self.click_fei_trl_attr_link()

        supplier_attr = SupplierAttributesWindow(self.driver)
        supplier_attr.select_type()

        # Expand Additional ID Numbers section
        self.expand_additional_id_numbers()
        self.enter_id_type(id_type)
        self.element_click(self._id_number)
        self.enter_id_number()
コード例 #18
0
class ProductButtonsCheck(SeleniumDriver):
    """
    this class checks the 'product' tags (chair/table/sofa elements) .
    the test move to 'product' element -> click on one of the elements (chair/table/sofa elements) -> check the displayed
    items (check that all the items displayed are valid) .
    """

    log = cl.customLogger(logging.DEBUG)

    def __init__(self, driver):
        super().__init__(driver)
        self.driver = driver
        self.nav = NavigationPage(driver)
        self.util = Util()

    # locators :
    product_tag_locator = '//*[@id="menu-item-37"]/a'
    product_sofa_locator = '//*[@id="menu-item-228"]/a'
    product_chair_locator = '//*[@id="menu-item-102"]/a'
    product_table_locator = '//*[@id="menu-item-292"]/a'

    all_items = '//*[@id="main"]/div/ul/li//h2'

    list_for_sofa_check = ['sofa', 'couch', 'chair']

    list_for_chair_check = ['chair', 'recliner', 'couch', 'stool']

    list_for_table_check = ['table']

    def check_tag(self, option):
        """
        moves to 'product element' -> moves to the 'option' item and click it .
        :param option: (chair/table/sofa) .
        :return:
        """
        self.moveToElement(name="product",
                           locator=self.product_tag_locator,
                           locatorType="xpath")
        self.util.sleep(2)
        if option == 'sofa':
            self.moveToElement(name=option,
                               locator=self.product_sofa_locator,
                               locatorType="xpath")
            self.util.sleep(2)
            self.elementClick(self.product_sofa_locator, "xpath")
        elif option == 'chair':
            self.moveToElement(name=option,
                               locator=self.product_chair_locator,
                               locatorType="xpath")
            self.util.sleep(2)
            self.elementClick(self.product_chair_locator, "xpath")
        elif option == 'table':
            self.moveToElement(name=option,
                               locator=self.product_table_locator,
                               locatorType="xpath")
            self.util.sleep(2)
            self.elementClick(self.product_table_locator, "xpath")

    def check_elements_text(self, option):
        """
        according to the selected option -> check the text of the items displayed .
        :param option:
        :return:
        """
        # gets all the item .
        items = self.getElementList(locator=self.all_items,
                                    locatorType="xpath")

        # for each item in the items list .
        for item in items:
            # get the text .
            text = item.text
            self.log.debug("check text : {}".format(text))

            # create boolean variable -> if i find an item that do not contain any word from 'list_for_sofa_check'
            # then i return false .
            statement = False

            # according to the option entered (option = chair/table/sofa on product element on main page)
            if option == 'sofa':
                for word in self.list_for_sofa_check:
                    # text contains one of the word -> 'statement' = True -> go for the next element .
                    if word in str(text).lower():
                        statement = True
                        break
                # if the text did not become True in the loop above -> this item should not be in the display .
                if statement == False:
                    self.log.error(
                        "ITEM with text : {}  -> should not be in the display ."
                        .format(text))
                    return False

            elif option == 'table':
                for word in self.list_for_table_check:
                    # text contains one of the word -> 'statement' = True -> go for the next element .
                    if word in str(text).lower():
                        statement = True
                        break
                # if the text did not become True in the loop above -> this item should not be in the display .
                if statement == False:
                    self.log.error(
                        "ITEM with text : {}  -> should not be in the display ."
                        .format(text))
                    return False

            elif option == 'chair':
                for word in self.list_for_chair_check:
                    # text contains one of the word -> 'statement' = True -> go for the next element .
                    if word in str(text).lower():
                        statement = True
                        break
                # if the text did not become True in the loop above -> this item should not be in the display .
                if statement == False:
                    self.log.error(
                        "ITEM with text : {}  -> should not be in the display ."
                        .format(text))
                    return False

        return True
コード例 #19
0
class ContactsPage(BasePage):
    log = cl.custom_logger(logging.DEBUG)

    def __init__(self, driver):
        super().__init__(driver)
        self.driver = driver
        self.util = Util()

    # LOCATORS
    _contacts_tab = "ICTAB_2"
    _description_field = "VNDR_CNTCT_SCR_DESCR$0"
    _sam_type = "VNDR_CNTCT_SCR_CCR_ADDR_TYPE$0"
    _type = "VENDOR_CNTCT_CONTACT_TYPE$0"
    _name_field = "VENDOR_CNTCT_CONTACT_NAME$0"
    _title_field = "VENDOR_CNTCT_CONTACT_TITLE$0"
    _address = "VENDOR_CNTCT_ADDRESS_SEQ_NUM$0"
    _internet_field = "VENDOR_CNTCT_URL$0"
    _email_field = "VENDOR_CNTCT_EMAILID$0"
    """ GET ELEMENTS """

    def get_sam_type(self):
        return self.driver.find_element(By.ID, self._sam_type)

    def get_type(self):
        return self.driver.find_element(By.ID, self._type)

    """ DO SOMETHING WITH ELEMENTS """

    def click_contacts_tab(self):
        self.element_click(self._contacts_tab)
        self.util.sleep(1, "the Contacts page to open.")

    def enter_description(self, description):
        self.sendkeys(description, self._description_field)

    def select_random_sam_type(self):
        self.get_sam_type().send_keys(choice(SAM_TYPE), Keys.TAB)
        self.util.sleep(1, "the SAM Type to be recognized by the app.")

    def select_random_type(self):
        self.get_type().send_keys(choice(TYPE), Keys.TAB)

    def enter_name(self):
        fake_data = Faker()
        fake_name = fake_data.name()
        self.sendkeys(fake_name, self._name_field)

    def enter_title(self, title):
        self.sendkeys(title, self._title_field)

    def enter_address(self):
        address_number = ["1", "2", "3"]
        self.sendkeys(str(choice(address_number)), self._address)
        # self.sendkeys("1", self._address)

    def enter_email(self):
        fake_data = Faker()
        fake_email = fake_data.safe_email()
        self.sendkeys(fake_email, self._email_field)

    """ THESE MODULES ARE CALLED BY THE TEST """

    def enter_contacts_details(self, description, title):
        self.enter_description(description)
        self.select_random_sam_type()
        self.select_random_type()
        self.enter_name()
        self.enter_title(title)
        self.enter_address()
        self.clear_element(self._internet_field)
        self.sendkeys("http://www.google.com", self._internet_field)
        self.enter_email()
コード例 #20
0
class ProductCategoriesCheck(SeleniumDriver):
    """
    test 1 :
        on shop page -> product categories -> there are 10 categories .
        on the right of each category there is a number in format (number) -> symbolize the amount of items from
        this category .
        this test checks if the web page display the right amount of item for each category .
        using : 'click_on_category' , 'check_displayed_item_for_category' , 'check_displayed_items_amount' , 'check_amount' .

    test 2 :
        on shop page -> product categories -> there are 10 categories .
        this test click on each category then check the item displayed for every category supposed to displayed .
        using : 'click_on_category' , 'check_items_displayed' .

    """

    log = cl.customLogger(logging.DEBUG)

    def __init__(self, driver):
        super().__init__(driver)
        self.driver = driver
        self.nav = NavigationPage(driver)
        self.util = Util()

    # locator :
    product_categories_locator = '//*[@id="woocommerce_product_categories-1"]/ul/li/a[contains(text(), "{}")]'
    items_amount_locator = '//*[@id="woocommerce_product_categories-1"]/ul/li[{}]/span'

    # items_display_locators :
    items_amount_display_locator = '//*[@id="main"]/div/ul/li'
    items_text_locator = '//*[@id="main"]/div/ul/li/div//h2'

    list_chair = ["chair", "chairs", "recliner", "couch", "armchair", "stool"]

    list_sofa = ["sofa", "chair", "couch"]

    list_table = ["table"]

    list_two_seaters = ["sofa", "chair"]

    def click_on_category(self, category):
        """
        used in : test case 1 , test case 2 .
        this function click on 'category' element displayed under 'Product categories' on
        https://letskodeit.com/automationpractice/shop/ web page .
        :param category:
        :return:
        """
        self.elementClick(
            locator=self.product_categories_locator.format(category),
            locatorType="xpath")
        self.util.sleep(2)

    def check_displayed_item_for_category(self, number):
        """
        used in : test case 1 .
        this function return the text located on the right of each category under 'Product categories' on
        https://letskodeit.com/automationpractice/shop/ web page .
        :param number:
        :return:
        """
        item_amount_element = self.getElement(
            locator=self.items_amount_locator.format(number),
            locatorType="xpath")
        item_amount_text = item_amount_element.text
        self.log.info("TEXT AMOUNT IS : {}".format(item_amount_text))
        return item_amount_text

    def check_displayed_items_amount(self):
        """
        used in : test case 1 .
        this function will get the amount of item displayed on the web page for each category .
        (the elements displayed after the automation clicks on on of the categories .)
        :return:
        """
        items = self.getElementList(locator=self.items_amount_display_locator,
                                    locatorType="xpath")
        self.log.info("ITEMS AMOUNT : {}".format(len(items)))
        return len(items)

    def check_amount(self, items_amount, displayed_items_amount):
        """
        used in : test case 1 .
        checks if the returned values from 'check_displayed_item_for_category' , 'check_displayed_items_amount' are
        the same .
        :param items_amount:
        :param displayed_items_amount:
        :return:
        """
        if str(items_amount) == "({})".format(displayed_items_amount):
            return True
        else:
            return False

    def check_items_displayed(self, category):
        """
        used in : test case 2 .
        this function gets list of items that displayed for some category -> get all text of the items displayed ->
        according to the category check if there is any items that Shouldn't be displayed .
        :return:
        """
        # gets the list if texts .
        all_items = self.getElementList(locator=self.items_text_locator,
                                        locatorType="xpath")
        self.log.info("######## ITEMS DISPLAYED : #########")

        # print to the log all the texts .
        for i in all_items:
            self.log.info("TEXT : {}".format(i.text))

        # if it finds one text that should not be displayed then 'overall_statement' will be false .
        # if all the items should be displayed then 'overall_statement' stay true then will be returned at the end .
        overall_statement = True
        # using 'statement' boolean variable to spot if the specific item should or Shouldn't be displayed .
        statement = False

        # if the category clicked is : chair/stool/armchair/recliner
        if str(category).lower() == "chair" or str(category).lower(
        ) == "stool" or str(category).lower() == "armchair" or str(
                category).lower() == "recliner":
            # loop inside every items (the text of the item) -> get the text .
            for i in all_items:
                text = i.text
                # check if any key word from 'list_chair' is in this text .
                for item in self.list_chair:
                    if item in str(text).lower():
                        statement = True

                # if 'statement' stay false -> this items should not be in this category .
                if statement == False:
                    self.log.error(
                        "ITEM : {} should not be displayed .".format(text))
                    overall_statement = False

                statement = False

        # same comments as above only for category : table/study table/computer table .
        elif str(category).lower() == "computer table" or str(category).lower(
        ) == "study table" or str(category).lower() == "table":
            for i in all_items:
                text = i.text
                for item in self.list_table:
                    if item in str(text).lower():
                        statement = True

                if statement == False:
                    self.log.error(
                        "ITEM : {} should not be displayed .".format(text))
                    overall_statement = False

                statement = False

        # same comments as above only for category : two seaters .
        elif str(category).lower() == "two seaters":
            for i in all_items:
                text = i.text
                for item in self.list_two_seaters:
                    if item in str(text).lower():
                        statement = True

                if statement == False:
                    self.log.error(
                        "ITEM : {} should not be displayed .".format(text))
                    overall_statement = False

                statement = False

        # same comments as above only for category : sofa .
        elif str(category).lower() == "sofa":
            for i in all_items:
                text = i.text
                for item in self.list_sofa:
                    if item in str(text).lower():
                        statement = True

                if statement == False:
                    self.log.error(
                        "ITEM : {} should not be displayed .".format(text))
                    overall_statement = False

                statement = False

        return overall_statement