예제 #1
0
class AlertWindow(EnvironmentSetup):
    log = cl.customLogger(logging.DEBUG)

    def is_alert_present(self, time_to_wait):
        try:
            wait_ext = WaitExtensions()
            if wait_ext.Wait_for_alert_present(time_to_wait):
                EnvironmentSetup.get_driver().switch_to_alert()
                self.log.info(
                    "Switch to Alert is executed, so returning 'True' value")
                return True
        except exception.NoAlertPresentException:
            self.log.warning(
                "Given alert is not present, so returning 'False' value")
            return False

    def get_text_in_alert(self):
        var_text = Alert(EnvironmentSetup.get_driver()).text
        self.log.info("Text from the Alert is '{}'".format(var_text))
        return var_text

    def accept_alert(self):
        Alert(EnvironmentSetup.get_driver()).accept()

    def dismiss_alert(self):
        Alert(EnvironmentSetup.get_driver()).dismiss()
예제 #2
0
class LoginPage(element):
    log = cl.customLogger(logging.DEBUG)

    def login(self, user_name, pass_word, json_file_version):

        self.log.info(
            "##########################################################################"
        )
        self.log.info(
            "###################Enter Login page########################################"
        )
        try:
            time.sleep(4)
            if json_file_version != '1':
                element.click_on_element("circle_image")
            #pdb.set_trace()
            element.click_on_element_using_javascript("click_here_banner")
            time.sleep(3)
            element.set_text("user_name", user_name)
            element.set_text("password", pass_word)
            element.click_on_element("login_button")
            # verify image "TBM CONNECT"
            element.wait_for("tbm_allow_button")
            if element.is_element_displayed("tbm_connect_image"):
                # click on allow button
                element.click_on_element("tbm_allow_button")
                element.wait_for("image_site_logo")
                if (element.is_element_displayed_format("image_site_logo")):
                    self.log.info(
                        "'{}' Element present in the application ".format(
                            "image_site_logo"))
                    is_pass = True
                else:
                    is_pass = False
            else:
                is_pass = False
            return is_pass
        except Exception as e:
            self.log.exception("Exception thrown in login page {} ".format(e))
            raise

    def logout(self):
        self.log.info("Enter logout method")
        try:
            element.click_on_element("user_profile_image")
            element.click_on_element("logout")
            self.log.info(
                "###################Log out from application ########################################"
            )
        except Exception as e:
            self.log.info(
                "Exception thrown while logging out from application {}".
                format(e))
            raise Exception("Log out failed")
예제 #3
0
class WaitExtensions(Env_setup):
    (by, value) = (None, None)
    log = cl.customLogger(logging.DEBUG)

    # wait for element to visible
    def Wait_for_element_visible(self, by, waitTime_seconds):
        try:
            driver = self.get_driver()
            wait = WebDriverWait(driver, int(waitTime_seconds))
            return wait.until(
                EC.visibility_of_element_located((eval(by[0]), by[1])))
        except Exception:
            self.log.exception(
                "'{}' Element is not visible so returning False".format(by))
            return False

    # Wait for text present in the element
    def Wait_for_text_present(self, element_to_be_visible, text_value,
                              waitTime_InMilliseconds):
        try:
            wait = WebDriverWait(self.get_driver(), waitTime_InMilliseconds)
            return wait.until(
                EC.text_to_be_present_in_element(element_to_be_visible,
                                                 text_value))
        except seleniumexceptions.NoSuchElementException as e:
            self.log.exception(
                "Exception thrown 'Wait_for_text_present' ".format(e))
            raise
        except seleniumexceptions.StaleElementReferenceException as e:
            self.log.exception(
                "Exception thrown 'Wait_for_text_present' ".format(e))
            raise

    # Wait for title contains
    def Wait_for_title_contains(self, waitTime_InMilliseconds, page_title):
        try:
            wait = WebDriverWait(self.get_driver(), waitTime_InMilliseconds)
            return wait.until(EC.title_contains(page_title))
        except seleniumexceptions.NoSuchElementException as e:
            self.log.exception(
                "Exception thrown 'Wait_for_title_contains' ".format(e))
            raise
        except seleniumexceptions.WebDriverException as e:
            self.log.exception(
                "Exception thrown 'Wait_for_title_contains' ".format(e))
            raise

    def Wait_for_title_is(self, waitTime_InMilliseconds, page_title):
        try:
            wait = WebDriverWait(self.get_driver(), waitTime_InMilliseconds)
            return wait.until(EC.title_is(page_title))
        except seleniumexceptions.NoSuchElementException as e:
            self.log.exception(
                "Exception thrown 'Wait_for_title_is' ".format(e))
            raise
        except seleniumexceptions.WebDriverException as b:
            self.log.exception(
                "Exception thrown 'Wait_for_title_is' ".format(b))
            raise

    # Wait for alert present
    def Wait_for_alert_present(self, waitTime_InMilliseconds):
        try:
            wait = WebDriverWait(self.get_driver(), waitTime_InMilliseconds)
            return wait.until(EC.alert_is_present())
        except seleniumexceptions.TimeoutException as e:
            self.log.exception(
                "Exception thrown 'Wait_for_alert_present' ".format(e))
            return False
        except seleniumexceptions.WebDriverException as b:
            self.log.exception(
                "Exception thrown 'Wait_for_alert_present' ".format(b))
            return False

    def Wait_for_element(self, element, waitTime_InMilliseconds):
        try:
            driver = self.get_driver()
            wait = WebDriverWait(driver, 10)
            return wait.until(EC.visibility_of(element))
        except Exception as v:
            self.log.exception(
                "Exception thrown 'Wait_for_alert_present' ".format(v))
            return False
예제 #4
0
import csv, time, os, logging
from apptio_automation.Framework.Environment_setup import EnvironmentSetup

import apptio_automation.Framework.Extensions.Custom_logger as cl
log = cl.customLogger(logging.DEBUG)
pass_list, fail_list = [], []

details_results_list = []

framework_path = getattr(EnvironmentSetup, "var_parent_folder_path")

current_run_folder_name = getattr(
    EnvironmentSetup, "var_dynamic_name"
)  #time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))


def collect_details_results(modified, same, current_category_value,
                            parent_category):
    #__val = 1
    __result_dict = {}
    __result_dict["Top Level"] = parent_category
    __result_dict["Current Testing Node"] = current_category_value
    if bool(modified):
        __result_dict["Matching Keys"] = ""
        __result_dict["Non Matching Keys"] = list(modified)
        __result_dict["Status"] = "Fail"

    elif bool(same):
        __result_dict["Matching Keys"] = list(same)
        __result_dict["Non Matching Keys"] = ""
        __result_dict["Status"] = "Pass"
예제 #5
0
class DriverSetup:
    # driver = None
    log = cl.customLogger(logging.DEBUG)

    def set_driver(self, framework_path, type_of_driver):
        driver = None
        print("Enter create_driver function for creating driver")
        driver_folder_path = os.path.normpath(
            os.path.join(framework_path, 'Drivers'))
        print("Driver folder path is '{}'".format(driver_folder_path))

        try:
            if type_of_driver.lower() == 'chrome':
                driver = webdriver.Chrome(
                    os.path.normpath(
                        os.path.join(driver_folder_path, "chromedriver.exe")))
                print("Creation of 'CHROME' driver is successful")
                self.log.info("Creation of 'CHROME' driver is successful")
            elif type_of_driver.lower() == 'firefox':
                firefox_capabilities = DesiredCapabilities.FIREFOX
                firefox_capabilities['marionette'] = True
                #firefox_capabilities['binary'] = 'C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe'
                driver = webdriver.Firefox(capabilities=firefox_capabilities)
                print("Creation of 'FIREFOX' driver is successful")
                self.log.info("Creation of 'FIREFOX' driver is successful")
            elif type_of_driver.lower() == 'edge':
                driver = webdriver.Edge(
                    os.path.normpath(
                        os.path.join(driver_folder_path,
                                     "MicrosoftWebDriver.exe")))
                print("Creation of 'EDGE' driver is successful")
                self.log.info("Creation of 'EDGE' driver is successful")
            elif type_of_driver.lower() == 'ie':
                driver = webdriver.Ie(
                    os.path.normpath(
                        os.path.join(driver_folder_path,
                                     "IEDriverServer.exe")), self.ie_options())
                print("Creation of 'IE' driver is successful")
                self.log.info("Creation of 'IE' driver is successful")
            elif type_of_driver.lower() == 'safari':
                # safari driver location : http://selenium-release.storage.googleapis.com/index.html?path=2.48/,
                # https://github.com/SeleniumHQ/selenium/wiki/SafariDriver#getting-started
                driver = webdriver.Safari()
                self.log.info("Creation of 'SAFARI' driver is successful")

            else:
                print(
                    "Given driver {} is not matching with chrome,ie,edge,firefox.Please provide valid value"
                    .format(type_of_driver))
                self.log.warning(
                    "Given driver {} is not matching with chrome,ie,edge,firefox.Please provide valid value"
                    .format(type_of_driver))
        except web_driver_exceptions.WebDriverException as e:
            traceback.print_exc()
            self.log.error("Creation of driver failed {}".format(e))
            pytest.fail("Creation of driver is failed")
        except Exception as ex:
            traceback.print_exc()  # print exception details
            self.log.error("Creation of driver failed {}".format(e))
            #self.log.err
            pytest.fail("Creation of driver is failed")
        return driver

    def ie_options(self):
        ie_options = DesiredCapabilities.INTERNETEXPLORER
        ie_options['ignoreProtectedModeSettings'] = True
        return ie_options
예제 #6
0
class Test_Functional():

    log = cl.customLogger(logging.DEBUG)
    col1_id_value, col1_label_value = None, None

    ###################################################################################################################################
    # Validate first column values in the application
    ###################################################################################################################################

    def test_1_login_into_application(self, jsonfileversion):
        try:
            time.sleep(3)
            #pdb.set_trace()
            print(jsonfileversion)
            obj_login_page = LoginPage()
            user_name = ConfigValuesToDictionary.get_key_value('loginuser')
            pass_word = ConfigValuesToDictionary.get_key_value("loginpassword")
            if obj_login_page.login(user_name, pass_word, jsonfileversion):
                time.sleep(3)
            else:
                pytest.fail("Test case failed")
        except Exception as e:
            self.log.exception("Exception . Test case failed")
            pytest.fail(e)

###################################################################################################################################
# Validate first column values in the application
###################################################################################################################################

    def test_2_validate_first_column_category_values_with_given_json(
            self, json_data):
        try:
            #pdb.set_trace()
            __local_tbm_page_obj = tbmpage()
            Test_Functional.col1_id_value, Test_Functional.col1_label_value = __local_tbm_page_obj.check_and_get_category_values(
                0)  # get first col values from application
            # get first child values from JSON
            __local_json_helper_class_obj = JsonHelpers()
            __local_json_first_child_label_list = __local_json_helper_class_obj.get_first_col_value(
                json_data)
            # comparing lists from application and json files
            if len(__local_json_first_child_label_list) == len(
                    Test_Functional.col1_label_value):
                assert Test_Functional.col1_label_value == __local_json_first_child_label_list
            else:
                raise (
                    "Values in the first column are not matching.Test case is failed"
                )
        except Exception as e:
            self.log.exception("Exception ####  {}".format(e))
            pytest.fail(e)

    def test_3_sample(self):
        assert False
#
# ###################################################################################################################################
# # Validate images and children for a selected category
# ###################################################################################################################################
#

    def test_4_validate_images_and_children_for_each_category(self, json_data):
        __local_tbm_page_obj = tbmpage()
        try:
            __local_tbm_page_obj.validate_cloud_details_images_and_children_for_category(
                json_data, Test_Functional.col1_id_value)
            results = getattr(__local_tbm_page_obj, "child_validation_results")
            #pdb.set_trace()
            val = [
                d["Key_value"] for d in results if d["FinalStatus"] == "Fail"
            ]  # get the list of failed values from the results collected
            Apptio_Common.write_category_details_to_csv(
                "ChildrenValidationResults",
                Constant_Values.children_validation_col_list,
                results)  # write all the results in csv
            if len(
                    val
            ) > 0:  # if the length of failed list is > 1 , then fail the test case
                pytest.fail("Test case is failed")
        except Exception as e:
            self.log.exception("Exception #####  {}".format(e))
            raise
# #####################################################################################################################################
# # Validate details of a category
# #####################################################################################################################################

    def test_5_validate_details_of_each_category(self, json_data):
        __local_tbm_page_obj = tbmpage()
        try:
            __local_tbm_page_obj.validate_details_of_each_category_in_columns(
                json_data, Test_Functional.col1_id_value,
                Test_Functional.col1_label_value)
            results_list = getattr(Apptio_Common, "details_results_list")
            Apptio_Common.write_category_details_to_csv(
                "CategoryDetailsResults",
                Constant_Values.detail_validation_col_list, results_list)
            fail_list = [d for d in results_list if d["Status"] == "Fail"]
            if len(fail_list) > 0:
                pytest.fail("Test case is failed")
            setattr(Apptio_Common, "details_results_list", [])
        except Exception as e:
            self.log.exception("Exception #####  {}".format(e))
            raise

#####################################################################################################################################
# Validate include and exclude values
#####################################################################################################################################

    def test_6_validate_include_and_exclude_details_of_each_category(
            self, json_data):
        __local_tbm_page_obj = tbmpage()
        try:
            __local_tbm_page_obj.validate_exclude_and_include_of_each_category(
                json_data, Test_Functional.col1_id_value,
                Test_Functional.col1_label_value)
            results_list = getattr(Apptio_Common, "details_results_list")
            Apptio_Common.write_category_details_to_csv(
                "IncludesandExcludesResults",
                Constant_Values.detail_validation_col_list, results_list)
            fail_list = [d for d in results_list if d["Status"] == "Fail"]
            if len(fail_list) > 0:
                pytest.fail("Test case is failed")
            setattr(Apptio_Common, "details_results_list", None)
        except Exception as e:
            self.log.exception("Exception #####  {}".format(e))
            pytest.fail(e)

#####################################################################################################################################
# Logout from application
#####################################################################################################################################

    def test_7_Logout_from_application(self):
        try:
            obj_login_page = LoginPage()
            obj_login_page.logout()
        except Exception as e:
            self.log.exception("Exception #####  {}".format(e))
            pytest.fail(e)


########################################################################################################################
##########################TEMP##########################################################################################
# def test_5_validate_description_details_of_each_category(self,json_data):
#     __local_tbm_page_obj = tbmpage()
#     row_no = 0
#     categorypage = CategoryDetailsPage()
#     try:
#         col1_id_list, col1_value_list = __local_tbm_page_obj.check_and_get_category_values(0)
#         for x in range(0, len(col1_id_list)):
#             __local_col1_child1 = json_data["children"][x]
#             __local_tbm_page_obj.click_on_child_element(col1_id_list[x])  # click on child element
#             col2_id_list, col2_value_list = __local_tbm_page_obj.check_and_get_category_values(1)  # check and get child count in col2 from application
#             __local_tbm_page_obj.click_on_image_element_of_selected_category(col1_id_list[x])
#             time.sleep(1)
#             categorypage.compare_app_json_details_data(__local_col1_child1,col1_id_list[x])
#             __local_tbm_page_obj.come_out_of_details_section(row_no)
#             time.sleep(1)
#             Test_Functional.first_col_value  = col1_id_list[x]
#             if len(col2_value_list) != 0:  # if child are present
#                 #__local_tbm_page_obj.validate_details_of_each_category_updated(col2_id_list, __local_col1_child1,2,row_no+1)
#                 pass
#
#         else:
#             print("there are no list values to run")
#         __pass = getattr(categorypage, "pass_list")
#         __pass_list = zip(*[d.values() for d in __pass])
#         __fail = getattr(categorypage, "fail_list")
#         with open("test.txt", "a") as myfile:
#             myfile.write("\n pass "+str(__pass))
#             myfile.write("\n fail " +str(__fail))
#         with open(".\\Results\\test1.csv",'wb') as csvfile:
#             fieldnames = ['firstcolvalue','currentkey','values','status']
#             writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
#             writer.writerow(dict((fn, fn) for fn in fieldnames))
#             #writer.writeheader()
#             for row in __pass:
#                 writer.writerow(row)
#
#
#     except Exception:
#         raise
# def test_3_validate_child_values_for_parent_with_values_displayed_in_json(self, json_data):
#     __local_tbm_page_obj = tbmpage()
#     __local_json_data_obj = JsonHelpers()
#     try:
#         col1_id_list, col1_value_list = __local_tbm_page_obj.check_and_get_category_values(0)
#         for x in range(0, len(col1_id_list)):
#             __local_col1_child1 = json_data["children"][x]
#             __local_tbm_page_obj.click_on_child_element(col1_id_list[x])  # click on child element
#             __local_tbm_page_obj.check_image_for_category(col1_id_list[x]) # check image
#             __local_tbm_page_obj.check_for_public_cloud_in_application_and_json(__local_col1_child1, col1_id_list[x]) # check cloud image
#             col2_id_list, col2_value_list = __local_tbm_page_obj.check_and_get_category_values(1)  # check and get child count in col2 from app
#             __local_json_col2_child_list = __local_json_data_obj.get_child_names_in_list(__local_col1_child1)  # json child count in col2
#             print(col1_id_list[x])
#             #print("length of jsonlist and app in col2 {},{}".format(str(len(__local_json_col2_child_list)),str(len(col2_value_list))))
#             if __local_json_col2_child_list == col2_value_list and len(__local_json_col2_child_list) != 0 and len(col2_value_list) != 0:  # if child2 in json and app are matching
#                 #print('\t\t' + "col2 values from application are matching with Json")
#                 __local_tbm_page_obj.validate_col_values(col2_id_list, __local_col1_child1, 2)
#             else:
#                 if len(__local_json_col2_child_list) > len(col2_value_list):
#                     pytest.fail("Json data have more values than application..Please check")
#                 elif len(__local_json_col2_child_list) < len(col2_value_list):
#                     pytest.fail("Application values in col2 are not matching with Json")
#                 else:
#                     print("No child present in col2 for given col1 value in Json and application")
#         else:
#             print("there are no list values to run")
#     except Exception:
#         raise
class ElementExtensions(Page_elements,Env_setup):
    log = cl.customLogger(logging.DEBUG)
    @classmethod
    def get_web_element(cls,element_identifier_name):
        try:
            by = Page_elements().get_element_identifier(element_identifier_name)
            by = eval(by)
            __obj_wait = WaitExtensions()
            return __obj_wait.Wait_for_element_visible(by,1)
        except webdriver_exceptions.NoSuchElementException as e:
            cls.log.exception("Exception thrown in 'get_web_element' method '{}' ".format(e))
            raise
        except webdriver_exceptions.WebDriverException as e:
            cls.log.exception("Exception thrown in 'get_web_element' method '{}' ".format(e))
            raise
    @classmethod
    def find_element_using_parent_element(cls,parent_element,element_identifier_name):
        try:
            by = Page_elements().get_element_identifier(element_identifier_name)
            by = eval(by)
            return parent_element.find_element_by_xpath(by[1])
        except webdriver_exceptions.WebDriverException as e:
            cls.log.exception("Exception thrown in 'get_web_element' method '{}' ".format(e))

    @classmethod
    def find_elements_using_parent_element(cls,parent_element,element_identifier_name):
        try:
            by = Page_elements().get_element_identifier(element_identifier_name)
            by = eval(by)
            return parent_element.find_elements((eval(by[0]),by[1]))
        except webdriver_exceptions.WebDriverException as e:
            cls.log.exception("Exception thrown in 'get_web_element' method '{}' ".format(e))


    @classmethod
    def get_web_element_format(cls, element_identifier_name,value_to_format):
        try:
            __obj_wait_extensions = WaitExtensions()
            by = Page_elements().get_element_identifier(element_identifier_name)
            by = eval(by)
            __val2 = by[1]
            if value_to_format != None :
                by[1] = __val2.format(value_to_format)
            __ele_ = __obj_wait_extensions.Wait_for_element_visible(by, 10)
            return __ele_
        except webdriver_exceptions.NoSuchElementException as e:
            cls.log.exception("Exception thrown in 'get_web_element_format' method '{}' ".format(e))
            raise
        except webdriver_exceptions.WebDriverException as e:
            cls.log.exception("Exception thrown in 'get_web_element_format' method '{}' ".format(e))
            raise

    @classmethod
    def get_elements_in_list(cls, element_identifier_name, value_to_format=None):
        cls.log.info("Enter 'get_elements_in_list' method")
        try:
            by = Page_elements().get_element_identifier(element_identifier_name)
            by = eval(by)
            if value_to_format != None:
                __val2 = by[1]
                by[1] = __val2.format(value_to_format)
            elements = cls.get_driver().find_elements(eval(by[0]), by[1])
            return elements
        except webdriver_exceptions.NoSuchElementException as e:
            cls.log.exception("Exception thrown in 'get_elements_in_list' method {}".format(e))
            raise
        except Exception as g:
            cls.log.exception("Exception thrown in 'get_elements_in_list' method {}".format(g))
            raise

    ##############################

    ##############################

    @classmethod
    def set_text(cls,element_identifier_name,text_to_be_entered):
        try:
            local_element = cls.get_web_element(element_identifier_name)
            if local_element != False:
                local_element.clear()
                local_element.send_keys(text_to_be_entered)
                cls.log.info("Input text '{}' in the field '{}' is successful ".format(text_to_be_entered,
                                                                                       element_identifier_name))
            else:
                raise webdriver_exceptions.NoSuchElementException("Unable to find element with given identifier {}".format(element_identifier_name))
        except webdriver_exceptions.NoSuchElementException as k:
            cls.log.exception("Exception thrown in 'set_text' method '{}' ".format(k))
            raise k
        except Exception as c:
            cls.log.exception("Exception thrown in 'set_text' method '{}' ".format(c))
            raise c

    @classmethod
    def get_text(cls,element_identifier_name):
        __var_val = None
        try:
            local_element = cls.get_web_element(element_identifier_name)
            __var_val = local_element.text
            cls.log.info("Value returned from the application is '{}'".format(__var_val))
            return __var_val
        except webdriver_exceptions.NoSuchElementException as e:
            cls.log.exception("Exception thrown in 'get_text' method '{}' ".format(e))
            raise e
        except Exception as c:
            cls.log.exception("Exception thrown in 'get_text' method '{}' ".format(c))
            raise c
    @classmethod
    def get_text_in_list(cls, element_identifier_name,format_value=None):
        __var_val = []
        try:
            local_element = cls.get_elements_in_list(element_identifier_name,format_value)
            for ele in local_element: # for each element in the list
                try:
                    ele.location_once_scrolled_into_view
                except:
                    pass
                __var_val.append(ele.text)  # get the text of the element
            cls.log.info("Value returned from the application is '{}'".format(str(len(__var_val))))
            return __var_val
        except webdriver_exceptions.NoSuchElementException as e:
            cls.log.exception("Exception thrown in 'get_text' method '{}' ".format(e))
            raise e
        except Exception as c:
            cls.log.exception("Exception thrown in 'get_text' method '{}' ".format(c))
            raise c

    @classmethod
    def get_text_for_given_element(cls,web_element):
        try:
            __var_val = web_element.text
            cls.log.info("Value returned from the application is '{}'".format(__var_val))
            return __var_val
        except webdriver_exceptions.NoSuchElementException as e:
            cls.log.exception("Exception thrown in 'get_text_for_given_element' method '{}' ".format(e))
            raise e
        except Exception as c:
            cls.log.exception("Exception thrown in 'get_text_for_given_element' method '{}' ".format(c))
            raise c

    @classmethod
    def get_innerHtml_for_given_element(cls,web_element):
        try:
            __var_val = cls.get_driver().execute_script("return $(arguments[0]).text()",web_element)
            cls.log.info("Value returned from the application is '{}'".format(__var_val))
            return __var_val
        except webdriver_exceptions.NoSuchElementException as e:
            cls.log.exception("Exception thrown in 'get_innerHtml_for_given_element' method '{}' ".format(e))
            raise e
        except Exception as c:
            cls.log.exception("Exception thrown in 'get_innerHtml_for_given_element' method '{}' ".format(c))
            raise c

    @classmethod
    def get_innerHtml(cls, element_identifier_name):
        try:
            local_element = cls.get_web_element(element_identifier_name)
            __var_val = cls.get_driver().execute_script("return $(arguments[0]).innerHTML", local_element)
            cls.log.info("Value returned from the application is '{}' for web element '{}'".format(__var_val,element_identifier_name))
            return __var_val
        except webdriver_exceptions.NoSuchElementException as e:
            cls.log.exception("Exception thrown in 'get_innerHtml_for_given_element' method '{}' ".format(e))
            raise e
        except Exception as c:
            cls.log.exception("Exception thrown in 'get_innerHtml_for_given_element' method '{}' ".format(c))
            raise c

    @classmethod
    def click_on_element_format(cls,element_identifier_name,value_to_format=None):
        try:
            __obj_wait_extension = WaitExtensions()
            by = Page_elements().get_element_identifier(element_identifier_name)
            by = eval(by)
            __val2 = by[1]
            if value_to_format != None :
                by[1] = __val2.format(value_to_format)
                cls.log.info("Formatted value for the element '{}' is {}".format(element_identifier_name,by[1]))
            element = __obj_wait_extension.Wait_for_element_visible(by,10)
            if element != False:
                #element = cls.get_driver().find_element(eval(by[0]), by[1])  # find element
                # action_chains.ActionChains(Env_setup.get_driver()).move_to_element(element).perform()  #scroll to element
                # element.click() # click on element
                cls.click_on_element_based_on_browser(element)
                cls.log.info("Click on element '{}' is successful ".format(element_identifier_name))
            else:
                cls.log.info("Element '{}' is not identified ".format(element_identifier_name))
        except webdriver_exceptions.NoSuchElementException as b:
            cls.log.exception("Exception thrown while finding element '{}' in 'click_on_element_format' method".format(element_identifier_name))
            raise b
        except Exception as f:
            raise f

    @classmethod
    def click_on_element_based_on_browser(cls,web_element):
        browser = cls.driver_type
        try:
            if browser.lower() == 'firefox':
                web_element.click()
            elif browser.lower() == 'chrome':
                cls.get_driver().execute_script(
                    "var evt = document.createEvent('MouseEvents');" + "evt.initMouseEvent('click',true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0,null);" + "arguments[0].dispatchEvent(evt);",
                    web_element)
            elif browser.lower() == "edge":
                actions = action_chains.ActionChains(cls.get_driver())
                actions.move_to_element_with_offset(web_element, 0, -250)
                actions.move_to_element(web_element)
                actions.click(web_element).perform()
        except:
            raise

    @classmethod
    def click_on_element_format_javascript(cls, element_identifier_name, value_to_format=None):
        try:
            by = Page_elements().get_element_identifier(element_identifier_name)
            by = eval(by)
            __val2 = by[1]
            if value_to_format == None:
                pass
            else:
                by[1] = __val2.format(value_to_format)
            script = "return $('"+by[1]+"').get(0);"
            element_obj = cls.get_driver().execute_script(script)
            cls.click_on_element_using_actions(element_obj)
            cls.log.exception("Click on element using java script '{}' ".format(script))
        except webdriver_exceptions.NoSuchElementException as b:
            cls.log.exception("Exception thrown in 'click_on_element_format_javascript' method '{}' ".format(b))
            raise b
        except Exception as f:
            cls.log.exception("Exception thrown in 'click_on_element_format_javascript' method '{}' ".format(f))
            raise f
            #cls.get_driver().execute_script("arguments[0].scrollIntoView(true);", element_obj)
            #cls.get_driver().execute_script('window.scrollTo(0, '+ str(element_obj.location['y'])+ ');')

    @classmethod
    def click_on_element(cls,element_identifier_name):
        try:
            local_element = cls.get_web_element(element_identifier_name)
            if local_element != False:
                local_element.click()
                cls.log.info("Click on element '{}' is successful ".format(element_identifier_name))
            else:
                raise webdriver_exceptions.NoSuchElementException
        except webdriver_exceptions.NoSuchElementException as b:
            cls.log.exception("Exception thrown in 'click_on_element' method '{}' ".format(b))
            raise b
        except Exception as f:
            cls.log.exception("Exception thrown in 'click_on_element' method '{}' ".format(f))
            raise f

    @classmethod
    def click_on_element_using_javascript(cls, element_identifier_name):
        try:
            # print ("field is present in the application")
            element = cls.get_web_element(element_identifier_name)
            Env_setup.get_driver().execute_script("$(arguments[0]).click();", element)
            cls.log.info("Click on element '{}' is successful ".format(element_identifier_name))
        except webdriver_exceptions.NoSuchElementException as a:
            cls.log.exception("Exception thrown in 'click_on_element' method '{}' ".format(a))
            raise a
        except Exception as e:
            cls.log.exception("Exception thrown in 'click_on_element' method '{}' ".format(e))
            raise e


# actions.move_to_element_with_offset(__tspan_elements[1],0,-250)
# http://stackoverflow.com/questions/11908249/debugging-element-is-not-clickable-at-point-error
# print("Click on element '{}' is successful ".format(element_identifier_name))
##
    @classmethod
    def click_on_element_id_in_apptio_columns(cls, element_id_value):
        try:
            category_element = cls.get_web_element_format("category_text_element",element_id_value)
            image_element_for_selected_category = "g[id='{}'] g".format(element_id_value)

            cls.click_on_element_based_on_browser(category_element)
            __val1 = "g[id='{}'] rect".format(element_id_value)
            __element_class_value = cls.get_driver().find_element_by_css_selector(__val1).get_attribute("class")
            cls.log.info("Attribute value of the class is '{}'".format(__element_class_value))
            if __element_class_value != 'atumRectSelected':
                __tspan_elements = category_element.find_elements_by_css_selector("tspan")
                if len(__tspan_elements) > 1:
                    if cls.driver_type.lower() == 'chrome':
                        cls.get_driver().execute_script(
                            "var evt = document.createEvent('MouseEvents');" + "evt.initMouseEvent('click',true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0,null);" + "arguments[0].dispatchEvent(evt);",
                            __tspan_elements[0])
                        __element_class_value1 = cls.get_driver().find_element_by_css_selector(__val1).get_attribute("class")
                        if __element_class_value1 != 'atumRectSelected':
                            cls.get_driver().execute_script(
                                "var evt = document.createEvent('MouseEvents');" + "evt.initMouseEvent('click',true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0,null);" + "arguments[0].dispatchEvent(evt);",
                                __tspan_elements[1])
                    else:
                        __scroll_script = "window.scrollTo({},{});".format(__tspan_elements[1].location["x"], __tspan_elements[1].location["y"])
                        cls.get_driver().execute_script(__scroll_script)
                        cls.click_on_element_using_actions(__tspan_elements[1])

        except webdriver_exceptions.NoSuchElementException as a:
            cls.log.exception("Exception thrown in 'click_on_element_id_in_apptio_columns1' method '{}' ".format(a))
            raise a
        except Exception as e:
            cls.log.exception("Exception thrown in 'click_on_element_id_in_apptio_columns1' method '{}' ".format(e))
            raise e

    # select check box
    @classmethod
    def select_check_box_format(cls, element_identifier_name,state,value_to_format):
        is_selected = False
        try:
            __obj_wait_extension = WaitExtensions()
            by = Page_elements().get_element_identifier(element_identifier_name)
            by = eval(by)
            __val2 = by[1]
            if value_to_format != None : # check if there is an option to format
                by[1] = __val2.format(value_to_format)

            if (__obj_wait_extension.Wait_for_element_visible(by, 10)):
                ele = Env_setup.get_driver().find_element(eval(by[0]), by[1])
                action_chains.ActionChains(Env_setup.get_driver()).move_to_element(ele).perform()
                if (state.upper() == "ON"):
                    if ele.is_selected() :
                        cls.log.info("Check box selection is successful '{}'".format(element_identifier_name))
                        is_selected = True
                    else:
                        ele.click()          # if check box is not selected, then select
                        is_selected = True
                else:                       # to un select check box
                    ele.click()
                    cls.log.info("Check box is unselected {}".format(element_identifier_name))
        except webdriver_exceptions.NoSuchElementException as e:
            cls.log.exception("Exception thrown in 'select_check_box_format' method '{}' ".format(e))
            raise e
        except Exception as a:
            cls.log.exception("Exception thrown in 'select_check_box_format' method '{}' ".format(a))
            raise a
        cls.log.exception("Value of 'is_selected' is '{}' ".format(is_selected))
        return is_selected

    # Select methods
    @classmethod
    def select_element_by_value(cls,element_identifier_name,value_tobe_selected):
        try:
            local_element = cls.get_web_element(element_identifier_name)
            Select(local_element).select_by_value(value_tobe_selected)
            cls.log.info(" Value '{}' is selected in the drop down '{}'".format(value_tobe_selected,element_identifier_name))
        except webdriver_exceptions.NoSuchElementException as e:
            cls.log.exception("Exception thrown in 'select_check_box_format' method '{}' ".format(e))
            raise e
        except Exception as a:
            cls.log.exception("Exception thrown in 'select_check_box_format' method '{}' ".format(a))
            raise a

    @classmethod
    def select_element_by_id(cls, element_identifier_name, value_tobe_selected):
        try:
            local_element = cls.get_web_element(element_identifier_name)
            Select(local_element).select_by_index(value_tobe_selected)
            cls.log.info(
                " Value '{}' is selected in the drop down '{}'".format(value_tobe_selected, element_identifier_name))
        except webdriver_exceptions.NoSuchElementException as e:
            cls.log.exception("Exception thrown in 'select_element_by_id' method '{}' ".format(e))
            raise e
        except Exception as e:
            cls.log.exception("Exception thrown in 'select_element_by_id' method '{}' ".format(e))
            raise e

    @classmethod
    def get_selected_value_from_drop_down(cls,element_identifier_name):
        try:
            local_element = cls.get_web_element(element_identifier_name)
            __val = Select(local_element).first_selected_option
            cls.log.info(
                "Value from the drop down is '{}' ".format(element_identifier_name))
        except webdriver_exceptions.NoSuchElementException as e:
            cls.log.exception("Exception thrown in 'get_selected_value_from_drop_down' method '{}' ".format(e))
            raise e
        except Exception as a:
            cls.log.exception("Exception thrown in 'get_selected_value_from_drop_down' method '{}' ".format(a))
            raise a
        return __val

    #
    # @classmethod
    # def get_all_options_in_drop_down(cls, web_element_name):
    #     option_text_list = []
    #     try:
    #         local_element = cls.get_web_element(web_element_name)
    #         select = Select(local_element)
    #         for option in select.options:
    #                 #print (option.text)
    #             option_text_list.append(option.text)
    #         print ("count of options is {}".format(str(len(option_text_list))))
    #         return option_text_list
    #     except webdriver_exceptions.NoSuchElementException as a:
    #         raise a
    #     except Exception as e:
    #         raise e

    @classmethod
    def click_on_menu(cls,element_identifier_name):
        element = cls.get_web_element(element_identifier_name)
        action_chains.ActionChains(Env_setup.get_driver()).move_to_element(element).perform()
        cls.log.info("Click on menu item '{}'".format(element_identifier_name))

    @classmethod
    def scroll_to_element(cls,element_identifier_name):
        element = cls.get_web_element(element_identifier_name)
        action_chains.ActionChains(Env_setup.get_driver()).move_to_element(element).perform()
        cls.log.info("Scroll to element '{}'".format(element_identifier_name))

    @classmethod
    def scroll_to_element_using_x_y_coordinates(cls,element):
        try:
            __scroll_script = "window.scrollTo({},{});".format(element.location["x"], element.location["y"])
            cls.get_driver().execute_script(__scroll_script)
        except:
            raise

    @classmethod
    def scroll_to_element_using_java_script(cls, web_element):
        try:
            cls.get_driver().execute_script('arguments[0].scrollTop = arguments[0].scrollHeight', web_element)
        except:
            raise

    @classmethod
    def scroll_to_web_element_location(cls,web_element):
        try:
            web_element.location_once_scrolled_into_view
        except:
            raise


########################################################################################################################
# Waits for Element to be visible
# Implicit Wait is used here
########################################################################################################################

    @classmethod
    def wait_for(cls,element_identifier_name):
        try:
            by = Page_elements().get_element_identifier(element_identifier_name)
            __obj_wait = WaitExtensions()
            cls.log.info("Waiting for the object.... '{}'".format(element_identifier_name))
            if __obj_wait.Wait_for_element_visible(eval(by),10) != False:
                pass
            else:
                raise webdriver_exceptions.NoSuchElementException
        except Exception as e:
            cls.log.exception("Exception thrown in 'Wait_for' method '{}'".format(e))
            raise e

########################################################################################################################

########################################################################################################################
    @classmethod
    def close_browser(cls):
        Env_setup.get_driver().close()

    def refresh_page(self):
        Env_setup.get_driver().refresh()

    @classmethod
    def get_current_window_handle(cls,handle_number):
        return Env_setup.get_driver().window_handles[handle_number]

    @classmethod
    def switch_to_give_window_handle(cls,window_handle):
        Env_setup.get_driver().switch_to.window(window_handle)

    @classmethod
    def is_element_displayed(cls,element_identifier_name):
        try:
            element = cls.get_web_element(element_identifier_name)
            cls.log.info("Element is displayed so returning True")
            return element.is_displayed()
        except Exception:
            cls.log.exception("Element is not displayed so returning False")
            return False

    @classmethod
    def is_element_displayed_format(cls,element_identifier_name,value_to_format = None):
        cls.log.info("Enter 'is_element_displayed_format' method")
        try:
            by = Page_elements().get_element_identifier(element_identifier_name)
            by = eval(by)
            __val2 = by[1]
            if value_to_format != None :
                by[1] = __val2.format(value_to_format)
                cls.log.info("Formatted value of the by is '{}' ".format(by[1]))
            element = cls.get_driver().find_element(eval(by[0]), by[1])
            __is_displayed =  element.is_displayed()
            cls.log.info("'Is displayed' value of '{}' is '{}'".format(element_identifier_name,__is_displayed))
            return __is_displayed
        except Exception:
            cls.log.exception("'{}' Element is not displayed so returning False".format(element_identifier_name))
            return False

    @classmethod
    def is_element_enabled(cls,element_identifier_name):
        try:
            element = cls.get_web_element(element_identifier_name)
            return element.is_enabled()
        except Exception:
            cls.log.info("Element is not enabled so returning False")
            return False

    @classmethod
    def is_text_available(cls,element_identifier_name):
        try:
            element = cls.get_web_element(element_identifier_name)
            return element.text
        except:
            return None
    @classmethod
    def get_attribute_value(cls,element_identifier_name,attribute_name):
        try:
            element = cls.get_web_element(element_identifier_name)
            __val=  element.get_attribute(attribute_name)
            #cls.log.info("Attribute value of the element is '{}' ".format(__val))
            return __val
        except Exception as e:
            cls.log.exception("Exception thrown while getting attribute value for an element {}".format(e))
            raise

    @classmethod
    def get_attribute_value_of_element(cls,web_element,attribute_name):
        try:
            try:
                web_element.location_once_scrolled_into_view
            except:
                pass
            cls.scroll_to_element_using_java_script(web_element)
            return web_element.get_attribute(attribute_name)
        except Exception as e:
            cls.log.exception("Exception thrown in 'get_attribute_value_of_element' method {}".format(e))
            raise

    @classmethod
    def get_attribute_values_in_list(cls, element_identifier_name,attribute_name,value_to_format):
        __local_value_list = []
        try:
            by = Page_elements().get_element_identifier(element_identifier_name)
            by = eval(by)
            __val2 = by[1]
            if value_to_format != None :
                by[1] = __val2.format(value_to_format)
                elements = cls.get_driver().find_elements(eval(by[0]),by[1])
                for element in elements:
                    __loc_val = element.get_attribute(attribute_name)
                    __local_value_list.append(__loc_val.strip())
            return __local_value_list
        except webdriver_exceptions.NoSuchElementException as e:
            cls.log.exception("Exception thrown in 'get_attribute_value_of_element' method {}".format(e))
            raise
        except Exception as e:
            cls.log.exception("Exception thrown in 'get_attribute_value_of_element' method {}".format(e))
            raise



    @classmethod
    def click_on_element_using_actions(cls,web_element):
        cls.log.info("Enter 'click_on_element_using_actions' method")
        actions = action_chains.ActionChains(cls.get_driver())
        actions.move_to_element(web_element)
        actions.click(web_element).perform()

    @classmethod
    def move_with_offset_and_click_on_element_using_actions(cls, web_element):
        cls.log.info("Enter 'move_with_offset_and_click_on_element_using_actions' method")
        actions = action_chains.ActionChains(cls.get_driver())
        actions.move_to_element_with_offset(web_element, 0, -250)
        actions.click(web_element).perform()
        #__class_val = web_element.get_attribute("class")


    # @classmethod
    # def get_attribute_value_in_list1(cls,element,attribute_name):
    #     __local_value_list = []
    #     elements = []
    #     try:
    #         elements = element.find_elements("By.XPATH","/g")
    #         print (len(elements))
    #         for element in elements:
    #             __local_value_list.append(element.get_attribute('id'))
    #         print(len(__local_value_list))
    #         return __local_value_list
    #     except webdriver_exceptions.NoSuchElementException:
    #         raise
    #     except Exception:
    #         raise



##########################Autforms specific########################################
    @classmethod
    def get_preceding_sibling_count_ingrid_byXpath(cls,element_identifier_name,col_name = None):

        try:
            by = Page_elements().get_element_identifier(element_identifier_name)
            by = eval(by)
            __val2 = by[1]
            if col_name == None :
                __val1 = __val2
            else:
                __val1 = __val2.format(col_name)
            print ("Formated column xpath value is '{}'".format(__val1))
            __element_list = []
            __element_list = cls.get_driver().find_elements_by_xpath(__val1)
            return __element_list.__len__()
        except webdriver_exceptions.NoSuchElementException as e:
            raise e

    def get_column_value(self,element_identifier_name,index_value):
        try:
            by = Page_elements().get_element_identifier(element_identifier_name)
            by = eval(by)
            __val1 = by[1].format(index_value)
            #print (__val1)
            #element = Env_setup.get_driver().find_element(eval(by[0]), str(__val1))
            element = Env_setup.get_driver().find_element_by_xpath(__val1)
            action_chains.ActionChains(Env_setup.get_driver()).move_to_element(element).perform()
            return element.text
        except webdriver_exceptions.NoSuchElementException as e:
            #traceback.print_exc()
            raise e

    @classmethod
    def get_row_count_in_table(self,element_identifier_name):
        __element_list = []
        try:
            by = Page_elements().get_element_identifier(element_identifier_name)
            by = eval(by)
            __element_list = Env_setup.get_driver().find_elements_by_xpath(by[1])
            return __element_list.__len__()
        except webdriver_exceptions.NoSuchElementException as e:
            raise e
class CategoryDetailsPage(element):

    log = cl.customLogger(logging.DEBUG)
    constant = Constant_Values()
    def get_list_of_details_header_names(self):
        __header_list = []
        try:
            __list =  element.get_elements_in_list("h3_details_header")
            for x in range(0,len(__list)):
                __header_list.append(element.get_attribute_value_of_element(__list[x],"innerText"))
            self.log.info("Length of details header list is {} ".format(str(__list)))
            return __header_list
        except Exception as e:
            self.log.exception("Exception thrown in 'get_list_of_details_header_in_details' method as {}".format(e))
            raise

# for each tag get the child items from application

    def compare_app_json_details_data(self,json_data_object,app_id_value,col1_parent_name):
        __json_obj = JsonHelpers()
        __header_list = self.get_list_of_details_header_names()
        json_expected_details = __json_obj.get_atum_entry_details1(json_data_object, __header_list)
        app_details = self.get_child_items_for_each_element(__header_list)
        added,removed,modified,same = compare_dict(json_expected_details,app_details)
        print("##########Values that are not matching##############33")
        print (modified)
        print("##########Values that are matching##############")
        print (same)
        if bool(modified):
            modified["child_name"] = app_id_value
            write_category_details_in_log("DataMismatch",modified)
        collect_details_results(modified,same,app_id_value,col1_parent_name)

    def get_child_items_for_each_element(self, header_list):
        app_dict = {}
        for x in range(0, len(header_list)):
            __app_header_value = header_list[x]
            if __app_header_value == "":
                description_value = element.get_attribute_value("description_text1", "innerHTML")
                if '<p>' not in description_value:
                    description_value = element.get_attribute_value("description_text1", "innerText")
                if "&amp;" in description_value:
                    description_value = unicode.replace(description_value, '&amp;', "&")
                app_dict["Description"] = unicode(description_value)
            elif __app_header_value == "Unit of Measure List":
                __uom_element_list = element.get_attribute_values_in_list("description_children_text_values", "innerHTML", __app_header_value)
                __uom_element_list = [val.replace("&amp;","&")for val in __uom_element_list]
                app_dict[__app_header_value] = __uom_element_list
            elif __app_header_value in self.constant.app_to_json_mapping:
                __user_list = element.get_text_in_list("description_children_text_values", __app_header_value)  # Need to check with constant dictionary
                app_dict[__app_header_value] = __user_list
            else:
                self.log.info("There are no matching values in dictionary")
        return app_dict

#
# ########################################################################################################################
# # Get include and exclude values from the application and compare values
# ########################################################################################################################

    def compare_exclude_and_include_in_app_and_json(self,json_data_object,app_id_value,col1_parent_name):
        __json_obj = JsonHelpers()
        json_expected_details = __json_obj.get_include_and_excludes_from_json(json_data_object)
        app_details = self.get_include_and_exclude_details_from_application()
        # write data to notepad for reference
        write_category_details_in_log("ExcludeandIncludeData", app_id_value)
        write_category_details_in_log("ExcludeandIncludeData",json_expected_details)
        write_category_details_in_log("ExcludeandIncludeData", app_details)

        # Compare data between application and Json
        diffvalues,samevalues= compare_list_of_dictionaries1(json_expected_details,app_details)
        # write data to notepad for reference
        if len(diffvalues) >= 1:
            write_category_details_in_log("ExcludeDataMismatch", app_id_value)
            write_category_details_in_log("ExcludeDataMismatch", diffvalues)

        collect_details_results(diffvalues,samevalues,app_id_value,col1_parent_name)

    def get_include_and_exclude_details_from_application(self):
        try:
            __include_list = self._get_include_and_exclude_from_application("include_elements","include_header1","include_list1")
            __exclude_list = self._get_include_and_exclude_from_application("exclude_elements","exclude_header1","exclude_list1")
            __include_list = __include_list + __exclude_list
            return __include_list
        except:
            return []

    def _get_include_and_exclude_from_application(self,parent_element,span_element_name,li_element_name):
        _val_list = []
        try:
            __list__div_elements = element.get_elements_in_list(parent_element)
            x= 0
            for div_element in __list__div_elements:
                _dic_1 = {}
                _list_val = []
                x = x+1
                element.scroll_to_web_element_location(div_element)
                _span_element = element.get_web_element_format(span_element_name,x)
                parent_name = unicode(element.get_attribute_value_of_element(_span_element,"parentname"))
                _name = unicode(element.get_attribute_value_of_element(_span_element, "name"))
                if parent_name == "cost_pools":
                    parent_name = parent_name[:-1]
                _dic_1[parent_name] = _name
                _ul_element = element.get_elements_in_list(li_element_name,x)
                for ele in _ul_element:
                    element.scroll_to_web_element_location(ele)
                    __val1 = element.get_attribute_value_of_element(ele,"innerText")
                    _list_val.append(__val1)
                _dic_1["list"] = _list_val
                _val_list.append(_dic_1)
            return _val_list
        except:
            #raise
            return _val_list





            # def collect_results(self,modified,same,current_category_value,):
    #     #__val = TbmCouncilPage.col1_parent_name
    #     #__val = getattr(tbmpage,"col1_parent_name")
    #     __val = 1
    #     if bool(modified):
    #         fail_dict ={}
    #         fail_dict["firstcolvalue"] = __val
    #         fail_dict["currentkey"] = current_category_value
    #         fail_dict["values"] = modified
    #         fail_dict["status"] = "Fail"
    #         CategoryDetailsPage.fail_list.append(fail_dict)
    #     elif bool(same):
    #         pass_dict = {}
    #         pass_dict["firstcolvalue"] = __val
    #         pass_dict["currentkey"] = current_category_value
    #         pass_dict["values"] = same
    #         pass_dict["status"] = "Pass"
    #         CategoryDetailsPage.pass_list.append(pass_dict)




# for each tag get child from json

# compare values between json and app

# store pas and fail list

        # with open(".\\Results\\differencedata.txt", "a") as myfile:
        #     myfile.write("\n")
        #     myfile.write(app_id_value)
        #     myfile.write("\n Header list from application ")
        #     myfile.write(str(header_list))
        #     myfile.write("\n Header values that are not matching")
        #     myfile.write("\n")
        #     myfile.write(str(modified))

#
# def get_atum_entry_details(self, json_data_object, application_header_list_values):
#     __json_atum_entry_values = {}
#     const = Constant_Values()
#     child = json_data_object["atum_entry"]
#     try:
#         for x in range(0, len(application_header_list_values)):  # need to change based on the constant file
#             application_header_value = application_header_list_values[x]
#             if application_header_value == "":
#                 key_value = const.app_to_json_mapping["Description"]  # get the json key value from constant file
#                 __json_atum_entry_values["Description"] = unicode(child[key_value])  # add the description details
#             elif application_header_value == "Target Users":
#                 key_value = const.app_to_json_mapping["Target Users"]  # get the json key value from constant file
#                 __users_list = [x.strip() for x in child[key_value][0]["users"]]  # trim the extra spaces in the list
#                 __json_atum_entry_values["Target Users"] = __users_list  # add the list to the json dictionary
#             elif application_header_value == "Unit of Measure List":
#                 __uom_list = []
#                 key_value = const.app_to_json_mapping[
#                     "Unit of Measure List"]  # get the json key value from constant file
#                 for uomlist in child[key_value]:  # for each UOM dictionary in the UOM list
#                     for k, v in uomlist.items():
#                         __uom_list.append(k + ": " + v)
#                 __json_atum_entry_values["Unit of Measure List"] = __uom_list
#             elif application_header_value == "Children":
#                 __child_label_list = []
#                 key_value = const.app_to_json_mapping["Children"]  # get the json key value from constant file
#                 for children_name in json_data_object[key_value]:  # for each child in the list,
#                     __child_label_list.append(children_name["label"])  # get label name
#                 __json_atum_entry_values["Children"] = __child_label_list  # add values to dictionary
#             elif application_header_value == "Service Offering Levers":
#                 key_value = const.app_to_json_mapping[
#                     "Service Offering Levers"]  # get the json key value from constant file
#                 __services_list = [x.strip() for x in child[key_value]]
#                 __json_atum_entry_values["Service Offering Levers"] = __services_list  # add values to dictionary
#             elif application_header_value == "Service Level KPIs":
#                 key_value = const.app_to_json_mapping["Service Level KPIs"]  # get the json key value from constant file
#                 __kpi_list = [x.strip() for x in child[key_value]]
#                 __json_atum_entry_values["Service Level KPIs"] = __kpi_list  # add values to dictionary
#                 # elif application_header_value == "Examples":
#                 #     pass
#                 #     # pending, need to know how to handle values like below. need to check
#                 #     # "examples": [
#                 #     #     "AWS \u2013 Lambda",
#                 #     #     "Azure \u2013 Batch"
#                 #     # ]
#     except:
#         raise
#     return __json_atum_entry_values


#     def get_list_exclude_includes_header_names(self):
#         __exclude_header_list = []
#         try:
#             __includelist = element.get_elements_in_list("includes_header")
#             __excludelist = element.get_elements_in_list("excludes_header")
#             for y in range(0, len(__includelist)):
#                 __includelist_name = str("Includes-"+element.get_attribute_value_of_element(__includelist[y],"innerHTML"))
#                 __attributelist = []
#                 __attributelist.append(__includelist_name)
#                 __attributelist.append(str(element.get_attribute_value_of_element(__includelist[y],"parentname")))
#                 __attributelist.append(str(element.get_attribute_value_of_element(__includelist[y], "name")))
#                 __exclude_header_list.append({'Includes':__attributelist})
#
#             for z in range(0, len(__excludelist)):
#                 __excludelist_name = str("Excludes-"+element.get_attribute_value_of_element(__excludelist[z],"innerHTML"))
#                 __attributelist = []
#                 __attributelist.append(__excludelist_name)
#                 __attributelist.append(str(element.get_attribute_value_of_element(__excludelist[z],"parentname")))
#                 __attributelist.append(str(element.get_attribute_value_of_element(__excludelist[z], "name")))
#                 __exclude_header_list.append({'Excludes':__attributelist})
#             return __exclude_header_list
#         except Exception as e:
#             self.log.exception("Exception thrown in 'get_list_of_details_header_in_details' method as {}".format(e))
#             raise
#
#     # def get_include_exclude_details(self,header_list):
#     #     app_dict_ = {}
#     #     for x in range(0, len(header_list)):
#     #         __app_header_value = header_list[x]
#     #         if "Includes" in __app_header_value:
#     #             key = __app_header_value.keys()
#     #             __header_value = __app_header_value[key[0]][0].replace("Includes-", "")
#     #             __user_list = element.get_text_in_list("includes_children_text_values", __header_value)  # Need to check with constant dictionary
#     #             app_dict_[__app_header_value[key[0]][0]] = __user_list
#     #         elif "Excludes" in __app_header_value:
#     #             key = __app_header_value.keys()
#     #             __header_value = __app_header_value[key[0]][0].replace("Excludes-", "")
#     #             __user_list = element.get_text_in_list("excludes_children_text_values", __header_value)  # Need to check with constant dictionary
#     #             app_dict_[__app_header_value[key[0]][0]] = __user_list
#     #         elif __app_header_value in self.constant.app_to_json_mapping:
#     #             __user_list = element.get_text_in_list("description_children_text_values", __app_header_value)  # Need to check with constant dictionary
#     #             app_dict_[__app_header_value] = __user_list
#     #         else:
#     #             self.log.info("There are no matching values in dictionary")
#     #     return app_dict_
예제 #9
0
class TbmCouncilPage(element, JsonHelpers):
    log = cl.customLogger(logging.DEBUG)

    categorydetailspageobject = CategoryDetailsPage()
    col1_parent_name = None
    child_validation_results = []

    def check_and_get_category_values(self, format_value):
        __local_list_ids, __local_list_values = [], []
        try:
            if self.check_for_child_elements("column_0", format_value):
                __local_list_ids = self.get_attribute_values_in_list(
                    "column_element_list", "id", format_value)
                for x in range(0, len(__local_list_ids)):
                    __local_list_values.append(__local_list_ids[x][4:])
            else:
                __local_list_ids = []
                __local_list_values = []
            return __local_list_ids, __local_list_values
        except Exception as e:
            self.log.exception(
                "Exception thrown in 'check_and_get_category_values' method {}"
                .format(e))
            raise

    def click_on_child_element(self, child_id):
        try:
            element.click_on_element_id_in_apptio_columns(child_id)
        except Exception as e:
            self.log.exception(
                "Exception thrown in 'click_on_child_element' method {}".
                format(e))
            raise

    def click_on_image_element_of_selected_category(self, child_id):
        if self.check_image_for_category(child_id):
            self.click_on_element_format("image_element", child_id)

    def come_out_of_details_section(self, row_no):
        try:
            self.click_on_element_format("come_out_of_details", row_no)
        except:
            raise

    def check_image_for_category(self, child_id):
        try:
            __is_displayed = element.is_element_displayed_format(
                "image_element", child_id)
        except:
            raise
        return __is_displayed

    def check_image_for_category1(self, child_id):
        try:
            if element.is_element_displayed_format("image_element", child_id):
                print("image is present")
            else:
                print("image is not present")
        except:
            raise

    def check_for_child_elements(self, name, column_no):
        try:
            time.sleep(1)
            return element.is_element_displayed_format(name, column_no)
        except Exception:
            self.log.exception(
                "Child elements are not displayed so returning False")
            return False

    def check_for_child_elements1(self, column_no):
        try:
            time.sleep(1)
            return element.is_element_displayed_format("column_0", column_no)
        except Exception:
            return False

    def get_headings_from_details_section_in_a_list(self):
        pass
        __h3_name_list = []
        __local_elements_list = element.get_elements_in_list(
            "get_all_header_elements")
        for x in range(1, len(__local_elements_list)):
            __h3_name_list.append((element.get_text_for_given_element(
                __local_elements_list[x])).strip())
        return __h3_name_list

    def validate_col_values(self, col1_id_list, json_data_obj, n):
        for x in range(0, len(col1_id_list)):
            print(col1_id_list[x])
            __local_col1_child = json_data_obj["children"][x]
            self.click_on_child_element(col1_id_list[x])
            self.check_image_for_category(col1_id_list[x])
            col_id_list, col_value_list = self.check_and_get_category_values(
                n)  # check and get child count in col2 from app
            __local_json_col_child_list = self.get_child_names_in_list(
                __local_col1_child)  # json child count in col2
            self.check_for_public_cloud_in_application_and_json(
                __local_col1_child, col1_id_list[x])
            #print("length of jsonlist and app in col2 {},{}".format(str(len(__local_json_col_child_list)),str(len(col_value_list))))
            if __local_json_col_child_list == col_value_list and len(
                    __local_json_col_child_list) != 0 and len(
                        col_value_list
                    ) != 0:  # if child2 in json and app are matching
                self.validate_col_values(col_id_list, __local_col1_child,
                                         n + 1)
            else:
                if len(__local_json_col_child_list) > len(col_value_list):
                    pytest.fail(
                        "Json data have more values than application..Please check "
                    )
                elif len(__local_json_col_child_list) < len(col_value_list):
                    pytest.fail(
                        "Application values in col3 are not matching with Json"
                    )
                else:
                    print(
                        '\t\t' +
                        "No child present for a given value in Json and application"
                    )

    def check_for_public_cloud_in_application_and_json(
            self, json_object, col_id_value):  # need to return only one value
        __jsonhelp = JsonHelpers()
        __cloud_json = __jsonhelp.check_for_public_cloud_in_json(
            json_object)  # check json
        __cloud_app = element.is_element_displayed_format(
            "cloud_image_element", col_id_value)

        if __cloud_json and __cloud_app:
            return True
        elif not __cloud_json and not __cloud_app:
            return True
        else:
            return False

################################3#######################################################################################
# Function to validate images and children for each category
################################3#######################################################################################

    def validate_cloud_details_images_and_children_for_category(
            self, json_data, col1_id_list):
        image_col_no = 0
        col_no = 0
        try:
            #col1_id_list, col1_value_list = self.check_and_get_category_values(col_no)
            self.validate_image_and_children(col1_id_list, json_data,
                                             col_no + 1, image_col_no)
        except:
            raise

    def validate_image_and_children(self, col1_id_list, json_data, col_no,
                                    image_col_no):
        try:
            for x in range(0, len(col1_id_list)):
                __dic_ = {}
                __local_col1_child1 = json_data["children"][x]
                keyval = col1_id_list[x][4:]

                self.click_on_child_element(
                    col1_id_list[x])  # click on child element
                ###################################################################################

                imagepresent = self.check_image_for_category(col1_id_list[x])

                cloudimage = self.check_for_public_cloud_in_application_and_json(
                    __local_col1_child1,
                    col1_id_list[x])  # check for cloud image

                ###################################################################################
                ## Click on on next child item
                col2_id_list, col2_value_list = self.check_and_get_category_values(
                    col_no)  # check and get child count in col2 from app
                __local_json_col2_child_list = self.get_child_names_in_list(
                    __local_col1_child1)  # json child count in col2

                if self.check_count_of_children_in_json_app(
                        __local_json_col2_child_list, col2_value_list
                ):  #__local_json_col2_child_list == col2_value_list and len(__local_json_col2_child_list) != 0 and len(col2_value_list) != 0  # if child2 in json and app are matching
                    childlist = __local_json_col2_child_list
                    Childrenmatching = True
                    if Childrenmatching and cloudimage and imagepresent:
                        finalstatus = "Pass"
                    else:
                        finalstatus = "Fail"
                    __dic_ = self.add_values_to_dic(
                        keyval=keyval,
                        imagepresent=imagepresent,
                        cloud=cloudimage,
                        childrenmatching=Childrenmatching,
                        finalstatus=finalstatus,
                        child_list=childlist)
                    TbmCouncilPage.child_validation_results.append(__dic_)
                    #self.validate_image_and_children(col2_id_list, __local_col1_child1, col_no+1, image_col_no + 1)
                else:
                    self.compare_json_app_child_counts_in_else(
                        __local_json_col2_child_list, col2_value_list,
                        imagepresent, cloudimage, keyval)
        except:
            raise

    def check_count_of_children_in_json_app(self, __local_json_col2_child_list,
                                            col2_value_list):
        if __local_json_col2_child_list == col2_value_list and len(
                __local_json_col2_child_list) != 0 and len(
                    col2_value_list
                ) != 0:  # if child2 in json and app are matching
            return True
        else:
            return False

    def compare_json_app_child_counts_in_else(self,
                                              __local_json_col2_child_list,
                                              col2_value_list, imagepresent,
                                              cloudimage, keyvalue):
        __child = None
        if len(__local_json_col2_child_list) > len(col2_value_list):
            __child = "Json children count is more than application children count"
            childmatching = False
            self.log.error(__local_json_col2_child_list + " " +
                           col2_value_list)
        elif len(__local_json_col2_child_list) < len(col2_value_list):
            __child = "Application children count is more than json children count"
            childmatching = False
            self.log.error(__local_json_col2_child_list + " " +
                           col2_value_list)
        else:
            __child = "No children present in json and application"
            childmatching = True

        if childmatching and imagepresent and cloudimage:
            finalstatus = "Pass"
        else:
            finalstatus = "Fail"
        __dic_ = self.add_values_to_dic(keyval=keyvalue,
                                        imagepresent=imagepresent,
                                        cloud=cloudimage,
                                        childrenmatching=childmatching,
                                        finalstatus=finalstatus,
                                        child_list=__child)
        TbmCouncilPage.child_validation_results.append(__dic_)
        #
        # def add_values_to_dic(self,val1,val2,val3,__dic_,child_list=None):
        #     __dic_["Key_value"] = val1
        #     __dic_["Imagepresent"] = val1
        #     __dic_["Cloudimagepresent"] = val2
        return __dic_

    def add_values_to_dic(self,
                          keyval,
                          imagepresent,
                          cloud,
                          childrenmatching,
                          finalstatus,
                          child_list=None):
        __dic_ = {}
        __dic_["Key_value"] = keyval
        __dic_["Imagepresent"] = imagepresent
        __dic_["Cloudimagepresent"] = cloud
        __dic_["Childlist"] = child_list
        __dic_["Childrenmatching"] = childrenmatching
        __dic_["FinalStatus"] = finalstatus
        return __dic_

########################################################################################################################
# Functions to validate details for each category
################################3#######################################################################################

    def validate_details_of_each_category_in_columns(self, json_data,
                                                     col1_id_list,
                                                     col1_value_list):
        try:
            image_column_no = 0
            #col1_id_list, col1_value_list = self.check_and_get_category_values(0)
            for x in range(0, len(col1_id_list)):
                __local_col1_child1 = json_data["children"][x]
                self.click_on_child_element(
                    col1_id_list[x])  # click on child element
                TbmCouncilPage.col1_parent_name = col1_value_list[x]
                col2_id_list, col2_value_list = self.check_and_get_category_values(
                    1)  # check and get child count in col2 from application
                self.click_on_image_element_of_selected_category(
                    col1_id_list[x])
                time.sleep(1)
                self.categorydetailspageobject.compare_app_json_details_data(
                    __local_col1_child1, col1_id_list[x][4:],
                    TbmCouncilPage.col1_parent_name)
                self.come_out_of_details_section(image_column_no)
                #time.sleep(1)
                if len(col2_value_list) != 0:  # if child are present
                    #self.validate_details_of_children(col2_id_list, __local_col1_child1,2,image_column_no+1)
                    pass
            else:
                print("there are no list values to run")
        except Exception as e:
            #self.log.exception("Exception #####  {} ".format(e))
            raise

    def validate_details_of_children(self, col1_id_list, json_data_obj,
                                     child_col_no, image_col_no):
        try:
            for x in range(0, len(col1_id_list)):
                print(col1_id_list[x])
                __local_col1_child = json_data_obj["children"][x]
                self.click_on_child_element(col1_id_list[x])
                self.click_on_image_element_of_selected_category(
                    col1_id_list[x])
                time.sleep(1)
                __parent_name = TbmCouncilPage.col1_parent_name
                self.categorydetailspageobject.compare_app_json_details_data(
                    __local_col1_child, col1_id_list[x][4:], __parent_name,
                    "details")
                self.come_out_of_details_section(image_col_no)
                col_id_list, col_value_list = self.check_and_get_category_values(
                    child_col_no)  # check and get child count in col2 from app
                if len(col_value_list
                       ) != 0:  # if child2 in json and app are matching
                    self.validate_details_of_children(col_id_list,
                                                      __local_col1_child,
                                                      child_col_no + 1,
                                                      image_col_no + 1)
                #pass
        except:
            raise

########################################################################################################################
# Functions to validate exclude and include details for each category
################################3#######################################################################################

    def validate_exclude_and_include_of_each_category(self, json_data,
                                                      col1_id_list,
                                                      col1_value_list):
        try:
            image_column_no = 0
            #col1_id_list, col1_value_list = self.check_and_get_category_values(0)
            for x in range(0, len(col1_id_list)):
                __local_col1_child1 = json_data["children"][x]
                self.click_on_child_element(
                    col1_id_list[x])  # click on child element
                TbmCouncilPage.col1_parent_name = col1_value_list[x]
                col2_id_list, col2_value_list = self.check_and_get_category_values(
                    1)  # check and get child count in col2 from application
                self.click_on_image_element_of_selected_category(
                    col1_id_list[x])
                time.sleep(1)
                self.categorydetailspageobject.compare_exclude_and_include_in_app_and_json(
                    __local_col1_child1, col1_id_list[x][4:],
                    TbmCouncilPage.col1_parent_name)
                self.come_out_of_details_section(image_column_no)
                # time.sleep(1)
                if len(col2_value_list) != 0:  # if child are present
                    # self.validate_exclude_and_include_of_children(col2_id_list, __local_col1_child1,2,image_column_no+1)
                    pass
            else:
                print("there are no list values to run")
        except Exception as e:
            # self.log.exception("Exception #####  {} ".format(e))
            raise

    def validate_exclude_and_include_of_children(self, col1_id_list,
                                                 json_data_obj, n, row_no):
        for x in range(0, len(col1_id_list)):
            print(col1_id_list[x])
            __local_col1_child = json_data_obj["children"][x]
            self.click_on_child_element(col1_id_list[x])
            col_id_list, col_value_list = self.check_and_get_category_values(
                n)  # check and get child count in col2 from app
            __local_json_col_child_list = self.get_child_names_in_list(
                __local_col1_child)  # json child count in col2
            self.click_on_image_element_of_selected_category(col1_id_list[x])
            time.sleep(1)
            self.categorydetailspageobject.compare_exclude_and_include_in_app_and_json(
                __local_col1_child, col1_id_list[x][4:],
                TbmCouncilPage.col1_parent_name)
            self.come_out_of_details_section(row_no)
            if len(col_value_list
                   ) != 0:  # if child2 in json and app are matching
                self.validate_exclude_and_include_of_children(
                    col_id_list, __local_col1_child, n + 1, row_no + 1)
            else:
                if len(__local_json_col_child_list) > len(col_value_list):
                    pytest.fail(
                        "Json data have more values than application..Please check "
                    )
                elif len(__local_json_col_child_list) < len(col_value_list):
                    pytest.fail(
                        "Application values in col3 are not matching with Json"
                    )
                else:
                    print(
                        '\t\t' +
                        "No child present for a given value in Json and application"
                    )