def cs_get_topo_details(self, topology_path):
        """To get the Cloudshell topology details for a given path

        :Datafile usage:
             NA
        :Arguments:
            1. topology_path(string) = Specify the full topology name. Include
               the full path from the root to the topology, separated by slashes.
               For example: FolderName/Topologies/TopologyName

        :Returns:
            1. status(bool)= True/False
        """

        wdesc = "To get the Cloudshell topology details for a given path"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())

        status = False
        testcase_Utils.pNote("cs_get_topo_details, cs obj-{}".\
                             format(cloud_shell), "info")
        try:
            xml_resp = cloud_shell.GetTopologyDetails(topology_path)
            if xml_resp is not None:
                testcase_Utils.pNote("\n\n *** Get Topolopy \"%s\" successfull\n"\
                                     % (topology_path), "info")
                status = True
            else:
                testcase_Utils.pNote("\n\n *** Get Topolopy \"%s\" failed\n"\
                                     % (topology_path), "warning")
        except Exception as exception:
            print_exception(exception)

        testcase_Utils.report_substep_status(status)
        return status
    def connect_to_cs(self, system_name):
        """Logs in to API host using passed user credentials and domain

        :Datafile usage:
             NA
        :Arguments:
            1. system_name(string) = Name of the system from the datafile

        :Returns:
            1. status(bool)= True/False
        """

        wdesc = "Logon to CloudShell API Host"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())

        global cloud_shell
        cloud_shell = self._create_cs_obj(system_name)
        testcase_Utils.pNote("Login, cs obj-{}".format(cloud_shell), "info")

        status = False
        if cloud_shell is not None:
            testcase_Utils.pNote("\n\n *** Login to Cloudshell System-{}"
                                 " successfull, domain-{}\n".\
                                 format(cloud_shell.host,\
                                 cloud_shell.domain), "info")
            status = True
        else:
            testcase_Utils.pNote(
                "\n\n *** Login to Cloudshell System"
                " failed\n", "warning")

        testcase_Utils.report_substep_status(status)
        return status
예제 #3
0
 def gnmi_subscribe_close(self,
                          system_name=None,
                          external_system=None,
                          external_system_session=None,
                          verify=None):
     """
     For Polling and Streaming this keyword will close/kill the process
     :param system_name: server System name as in data file, server where
      gnmi client will send out its request.
     :param external_system: External system name mentioned as in data file.
                             This is optional if user want to execute gnmi from a different
                             server other than the warrior framework host machine.
     :param external_system_session: External system system session.
     :param verify: user provided string to verify can provide multiple sting separated by ","
                    e.g. '"sftp-server-port": "2202", "sftp-server-enabled": "true"'.
                    Verify string also has regular expression support.
     :return: True or False and dictionary containing output string
     """
     wdesc = "For Polling and Streaming this keyword will close/kill the process"
     testcase_Utils.pSubStep(wdesc)
     status = False
     outputdict = {}
     gnmi_execute = gnmi()
     status, result = gnmi_execute.close(system_name, external_system,
                                         external_system_session)
     if status and verify:
         status = gnmi_execute.verify(result, verify)
     outputdict = {'{}_gnmi_result'.format(system_name): result}
     return status, outputdict
    def cs_logoff(self):
        """To logoff from CS

        :Datafile usage:
             NA
        :Arguments:
             NA
        :Returns:
            1. status(bool)= True/False
        """

        wdesc = "To logoff from CS"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())

        status = False
        testcase_Utils.pNote("cs_logoff, cs obj-{}".format(cloud_shell),
                             "info")
        xml_resp = cloud_shell.Logoff()

        if xml_resp is not None:
            testcase_Utils.pNote(
                "\n\n *** Cloudshell LogOff successfull-%s" %
                (cloud_shell.host), "info")
            status = True
        else:
            testcase_Utils.pNote(
                "\n\n *** Cloudshell LogOff failed-%s" % (cloud_shell.host),
                "warning")

        testcase_Utils.report_substep_status(status)
        return status
    def cs_create_route_in_reservation(self, system_name, reservation_name,
                                       source_resource_full_path,
                                       target_resource_full_path,
                                       override_active_routes, mapping_type,
                                       max_hops, route_alias, is_shared):
        """Creates routes between the specified source and target resources.

        :Arguments:
            1. system_name(string) = Name of the UAP system from the datafile
            2. reservation_name(string) = Specify the name of the reservation.
            3. source_resource_full_path(string) = Specify the source resource
                full path
            4. target_resource_full_path(string) = Specify the target resource
                full path
            5. mapping_type(string) = Specify bi-directional or uni-directional
               as the mapping type
            6. max_hops(integer) = The maximum number of allowed hops.
            7. route_alias(string) = Specify the route alias
            8. override_active_routes(bool) = Specify whether the new route
                can override existing routes.
            9. is_shared(bool) = Specify whether these routes are shared.
        :Returns:
            1. status(bool) = True/False
        """

        wdesc = "Create Route In Reservation in CloudShell API Host"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())

        testcase_Utils.pNote(
            "cs_create_route_in_reservation, cs obj-{}".format(cloud_shell),
            "info")

        status = False
        cs_res_id = data_Utils.get_object_from_datarepository(
            system_name + "_" + reservation_name + "_reservationId")
        try:
            xml_resp = cloud_shell.CreateRouteInReservation(
                cs_res_id, source_resource_full_path,
                target_resource_full_path, override_active_routes,
                mapping_type, int(max_hops), route_alias, is_shared)

            if xml_resp is not None:
                testcase_Utils.pNote(
                    "\n\n *** Cloudshell Create Route In"
                    " Reservation successfull for \"{}\"\n".format(
                        reservation_name), "info")
                status = True
            else:
                testcase_Utils.pNote(
                    "\n\n *** Cloudshell Create Route In"
                    " Reservation failed for \"{}\"".format(reservation_name),
                    "warning")

        except Exception as exception:
            print_exception(exception)

        testcase_Utils.report_substep_status(status)
        return status
    def cs_remove_route_from_reservation(self, system_name, reservation_name,
                                         first_endpoint, second_endpoint,
                                         mapping_type):
        """Disconnects two endpoints and removes the mapped route between
           them

        :Arguments:
            1. system_name(string) = Name of the UAP system from the datafile
            2. reservation_name(string) = Specify the name of the reservation.
            3. first_endpoint(str) = The first endpoint of the two end points
            4. second_endpoint(str) = The second endpoint of the two end points
            5. mapping_type(string) = Specify bi-directional or uni-directional
               as the mapping type
        :Returns:
            1. status(bool) = True/False
        """

        wdesc = "Remove Route From Reservation in CloudShell API Host"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())

        testcase_Utils.pNote(
            "cs_remove_route_from_reservation, cs obj-{}".format(cloud_shell),
            "info")

        status = False
        cs_res_id = data_Utils.get_object_from_datarepository(
            system_name + "_" + reservation_name + "_reservationId")
        list_of_endpoints = [first_endpoint, second_endpoint]
        try:
            xml_resp = cloud_shell.RemoveRoutesFromReservation(
                cs_res_id, list_of_endpoints, mapping_type)
            if xml_resp is not None:
                testcase_Utils.pNote(
                    "\n\n *** Cloudshell Remove Route From"
                    " Reservation successfull for \"{}\"\n".format(
                        reservation_name), "info")
                status = True
            else:
                testcase_Utils.pNote(
                    "\n\n *** Cloudshell Remove Route From"
                    " Reservation failed for \"{}\"".format(reservation_name),
                    "warning")

        except Exception as exception:
            print_exception(exception)

        testcase_Utils.report_substep_status(status)
        return status
    def cs_add_users_to_reservation(self, system_name, reservation_name,
                                    list_of_usernames):
        """Add one or more permitted users to the specified reservation.

        :Datafile usage:
             NA
        :Arguments:
            1. system_name(string) = Name of the UAP system from the datafile
            2. reservation_name(string) = Specify the name of the reservation.
            3. list_of_usernames(list) = list of usernames to permit access to
               reservation.
               For example: To add many users to access the reservation
                            list_of_usernames = ['user1','user2','userx']

        :Returns:
            1. status(bool)= True/False
        """

        wdesc = "Add one or more permitted users to the reservation"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())

        testcase_Utils.pNote("cs_add_users_to_reservation, cs obj-{}".\
                             format(cloud_shell), "info")

        usernames = list_of_usernames[0:]
        testcase_Utils.pNote("cs_add_users_to_reservation, res_name-{},"\
                             "users-{}".format(reservation_name, usernames))

        status = False
        cs_res_id = data_Utils.get_object_from_datarepository\
                    (system_name+"_"+reservation_name+"_reservationId")
        try:
            xml_resp = cloud_shell.AddPermittedUsersToReservation(cs_res_id,\
                                                                  usernames)
            if xml_resp is not None:
                testcase_Utils.pNote("\n\n *** Cloudshell Add users \"{}\" to"
                                     "reservation successfull".\
                                     format(usernames), "info")
                status = True
            else:
                testcase_Utils.pNote(
                    "\n\n *** Cloudshell Add users \"{}\" to"
                    "Reservation failed".format(usernames), "warning")
        except Exception as exception:
            print_exception(exception)

        testcase_Utils.report_substep_status(status)
        return status
    def cs_disconnect_routes(self, system_name, reservation_name,
                             first_endpoint, second_endpoint):
        """Disconnects the routes in the cloud shell

        :Arguments:
            1. system_name(string) = Name of the UAP system from the datafile
            2. reservation_name(string) = Specify the name of the reservation.
            3. first_endpoint(str) = The first endpoint of the two end points
            4. second_endpoint(str) = The second endpoint of the two end points
        :Returns:
            1. status(bool)= True/False
        """

        wdesc = "Disconnect Routes in CloudShell API Host"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())

        testcase_Utils.pNote("cs_disconnect_routes, cs obj-{}".\
                             format(cloud_shell), "info")

        endpoints = [first_endpoint, second_endpoint]

        status = False
        cs_res_id = data_Utils.get_object_from_datarepository\
                (system_name+"_"+reservation_name+"_reservationId")
        try:
            xml_resp = cloud_shell.DisconnectRoutesInReservation(
                cs_res_id, endpoints)
            if xml_resp is not None:
                testcase_Utils.pNote("\n\n *** Cloudshell Disconnect Routes"
                                     " successfull for \"{}\"\n".\
                                     format(reservation_name), "info")
                status = True
            else:
                testcase_Utils.pNote("\n\n *** Cloudshell Disconnect Routes"
                                     " failed for \"{}\"".\
                                     format(reservation_name), "warning")

        except Exception as exception:
            print_exception(exception)

        testcase_Utils.report_substep_status(status)
        return status
    def cs_end_reservation(self, system_name, reservation_name, unmap):
        """End the reservation in Cloudshell

        :Datafile usage:
             NA
        :Arguments:
            1. system_name(string) = Name of the UAP system from the datafile
            2. reservation_name(string) = Specify the name of the reservation.
            3. unmap(string) = true or false, Unmap resources - Specify whether to keep mappings
               or release mapped resources when deleting the reservation.
        :Returns:
            1. status(bool)= True/False
        """

        wdesc = "End Reservation in CloudShell API Host"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())

        testcase_Utils.pNote("cs_end_reservation, cs obj-{}".\
                             format(cloud_shell), "info")

        status = False
        cs_res_id = data_Utils.get_object_from_datarepository\
                   (system_name+"_"+reservation_name+"_reservationId")
        try:
            unmap = unmap.lower()
            xml_resp = cloud_shell.EndReservation(cs_res_id, unmap)
            if xml_resp is not None:
                testcase_Utils.pNote("\n\n *** Cloudshell End reservation"
                                     " successfull for \"{}\"\n".\
                                     format(reservation_name), "info")
                status = True
            else:
                testcase_Utils.pNote("\n\n *** Cloudshell End Reservation"
                                     " failed for \"{}\"".\
                                     format(reservation_name), "warning")

        except Exception as exception:
            print_exception(exception)

        testcase_Utils.report_substep_status(status)
        return status
    def cs_get_reservation_details(self, system_name, reservation_name):
        """Retrieves all details and parameters for a specified reservation

        :Datafile usage:
             NA
        :Arguments:
            1. system_name(string) = Name of the UAP system from the datafile
            2. reservation_name(string) = Specify the name of the reservation.

        :Returns:
            1. status(bool)= True/False
        """

        wdesc = "To retrieve all details and parameters for a specified"\
                "reservation"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())

        status = False
        cs_res_id = data_Utils.get_object_from_datarepository\
                    (system_name+"_"+reservation_name+"_reservationId")
        testcase_Utils.pNote("cs_get_reservation_details, cs obj-{}".\
                             format(cloud_shell), "info")
        try:
            xml_resp = cloud_shell.GetReservationDetails(cs_res_id)
            if xml_resp is not None:
                testcase_Utils.pNote("\n\n *** Get reservation details for "
                                     "\"(%s)\" successfull\n" % (reservation_name),\
                                     "info")
                status = True
            else:
                testcase_Utils.pNote("\n\n *** Get reservation details for "
                                     "\"(%s)\" failed\n" % (reservation_name),\
                                     "warning")
        except Exception as exception:
            print_exception(exception)

        testcase_Utils.report_substep_status(status)
        return status
    def cs_get_current_reservation(self, reservation_owner):
        """Retrieves current reservations for the specified owner

        :Datafile usage:
             NA
        :Arguments:
            1. reservation_owner(string) = Specify the user name of the
               reservation owner.

        :Returns:
            1. status(bool)= True/False
        """

        wdesc = "To retrieve current reservations for the specified owner"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())

        status = False
        testcase_Utils.pNote("cs_get_current_reservation, cs obj-{}".\
                             format(cloud_shell), "info")
        try:
            xml_resp = cloud_shell.GetCurrentReservations(reservation_owner)

            if xml_resp is not None:
                testcase_Utils.pNote("\n\n *** Get current reservation for "
                                     "\"(%s)\" successfull\n" % (reservation_owner),\
                                     "info")
                status = True
            else:
                testcase_Utils.pNote("\n\n *** Get current reservation for "
                                     "\"(%s)\" failed\n" % (reservation_owner),\
                                     "warning")
        except Exception as exception:
            print_exception(exception)

        testcase_Utils.report_substep_status(status)
        return status
    def set_implicit_wait(self, system_name, timeout, browser_name="all",
                          element_config_file=None, element_tag=None):
        """
        This keyword would permanently set the implicit wait time for given
        browser instance(s)

        :Datafile Usage:

            Tags or attributes to be used in input datafile for the system or
            subsystem. If both tag and attribute is provided the attribute will
            be used.

            1. system_name = This attribute can be specified in the datafile as
                             a <system> tag directly under the <credentials>
                             tag. An attribute "name" has to be added to this
                             tag and the value of that attribute would be taken
                             in as value to this keyword attribute.

                             <system name="name_of_thy_system"/>

            2. browser_name = This <browser_name> tag is a child of the
                              <browser> tag in the data file. Each browser
                              instance should have a unique name. This name can
                              be added here

                              Eg: <browser_name>Unique_name_1</browser_name>

            3. timeout = This contains the information of how much time the
                         browser needs to wait for any action to be performed
                         on it

                         Eg: <timeout>15</timeout>

            4. element_config_file = This <element_config_file> tag is a child
                                     of the <browser> tag in the data file. This
                                     stores the location of the element
                                     configuration file that contains all
                                     element locators.

                                  Eg: <element_config_file>
                                      ../Config_files/selenium_config.json
                                      </element_config_file>

            5. element_tag = This element_tag refers to a particular element in
                             the json fie which contains relevant information to
                             that element. If you want to use this one element
                             through out the testcase for a particular browser,
                             you can include it in the data file. If this not
                             the case, then you should create an argument tag
                             in the relevant testcase step and add the value
                             directly in the testcase step.

                             FOR DATA FILE
                             Eg: <element_tag>json_name_1</element_tag>

                             FOR TEST CASE
                             Eg: <argument name="element_tag" value="json_name_1">

        :Arguments:

            1. system_name(str) = the system name.
            2. browser_name(str) = Unique name for this particular browser
            3. timeout(str) = amount of time the browser should wait
            4. element_config_file (str) = location of the element configuration
                                           file that contains all element
                                           locators
            5. element_tag (str) = particular element in the json fie which
                                   contains relevant information to that element

        :Returns:

            1. status(bool)= True / False.

        """
        arguments = locals()
        arguments.pop('self')
        status = True
        wdesc = "This would permanently set the implicit wait time for " \
                "given browser instance(s)"
        pNote("KEYWORD: set_implicit_wait | Description: {0}".format(wdesc))
        pSubStep(wdesc)
        browser_details = {}

        system = xml_Utils.getElementWithTagAttribValueMatch(self.datafile,
                                                             "system",
                                                             "name",
                                                             system_name)
        browser_list = system.findall("browser")
        try:
            browser_list.extend(system.find("browsers").findall("browser"))
        except AttributeError:
            pass

        if not browser_list:
            browser_list.append(1)
            browser_details = arguments

        for browser in browser_list:
            arguments = Utils.data_Utils.get_default_ecf_and_et(arguments,
                                                                self.datafile,
                                                                browser)
            if browser_details == {}:
                browser_details = selenium_Utils. \
                    get_browser_details(browser, datafile=self.datafile, **arguments)
            if browser_details is not None:
                current_browser = Utils.data_Utils.get_object_from_datarepository(system_name + "_" + browser_details["browser_name"])
                if not current_browser:
                    pNote("Browser of system {0} and name {1} not found in the "
                          "datarepository"
                          .format(system_name, browser_details["browser_name"]),
                          "Exception")
                    status = False
                else:
                    self.wait_oper_object.\
                        implicit_wait(current_browser,
                                      browser_details["timeout"])
            browser_details = {}
        Utils.testcase_Utils.report_substep_status(status)
        if current_browser:
            selenium_Utils.save_screenshot_onerror(status, current_browser)
        return status
    def wait_until_visibility_of_element_located(self, system_name, timeout="5",
                                                 locator=None,
                                                 locator_type=None,
                                                 browser_name="all",
                                                 element_tag=None,
                                                 element_config_file=None):
        """
        This keyword would check whether an element is present on the DOM of a
        page and visible.

        :Datafile Usage:

            Tags or attributes to be used in input datafile for the system or
            subsystem. If both tag and attribute is provided the attribute will
            be used.

            1. system_name = This attribute can be specified in the datafile as
                             a <system> tag directly under the <credentials>
                             tag. An attribute "name" has to be added to this
                             tag and the value of that attribute would be taken
                             in as value to this keyword attribute.

                             <system name="name_of_thy_system"/>

            2. browser_name = This <browser_name> tag is a child of the
                              <browser> tag in the data file. Each browser
                              instance should have a unique name. This name can
                              be added here

                              Eg: <browser_name>Unique_name_1</browser_name>

            3. timeout = This contains the information of how much time the
                         browser needs to wait for an element whose existence in
                         the DOM is unknown to become visible

                         Eg: <timeout>15</timeout>

            4. locator_type = This contains information about the type of
                              locator that you want to use. Can be 'xpath',
                              'id', 'css', 'link', 'tag','class', 'name'

            5. locator = This contains the value of the locator. Something like
                         "form", "nav-tags", "//[dh./dhh[yby]"

            6. element_config_file = This contains the location of the json
                                     file that contains information about all
                                     the elements that you require for the
                                     testcase execution
            7. element_tag = This contains the name of the element in that
                             element_config_file which you want to use

            USING LOCATOR_TYPE, LOCATOR, ELEMENT_CONFIG_FILE, AND ELEMENT_TAG
            =================================================================

            None of these arguments are mandatory BUT to search an element,
            you need to provide Warrior with some way to do it.

            a. You can either directly give values for the locator_type and
            locator. So if locator_type = name and locator = navigation-bar,
            then Warrior can search for an element with name "navigation-bar"

            b. You can give location of the element_config_file and a tag inside
            it so that Warrior can search for that tag and get the required
            information from there.

            - Now, if the locator type is given, Warrior
            will search for that locator_type in the children of that element in
            the element_config_file

            - You can also set defaults in the element_config_file, and now,
            even if the locator_type is not given, Warrior will know which
            element to find. If locator_type is given, the default will be
            overridden

            - If locator_type is not f=given, and the defaults are not
            specified, then the first element in the child list of the element
            tag would be picked.

            NOTES:
                For these four arguments to be given correctly, ONE of the
                following conditions must be satisfied.

                1. locator_type and locator must be given
                2. locator_type, element_config_file, and element_tag must be given
                3. element_config_file, and element_tag must be given

                The datafile has the first priority, then the json file, and
                then finally the testcase.

                If all arguments are passed from the same place, then, if
                locator and locator_type are given, then they would have
                priority. Otherwise, the element_config_file would be searched

                The locator_type locator, element_tag can be given the datafile
                as children of the <browser> tag, but these values would remain
                constant for that browser. It is recommended that these values
                be passed from the testcase step.

                The element_config_file typically would not change from step to
                step, so it can be passed from the data file

        :Arguments:

            1. system_name(str) = the system name.
            2. browser_name(str) = Unique name for this particular browser
            3. timeout(str) = amount of time the browser should wait
            4. locator_type(str) = type of the locator - xpath, id, etc.
            5. locator(str) = locator by which the element should be located.
            6. element_config_file(str) = location of the element config file
            7. element_tag(str) = json id of the locator that you want to use
                                  from the element config file

        :Returns:

            1. status(bool)= True / False.

        """
        arguments = locals()
        arguments.pop('self')
        status = True
        wdesc = "Browser would wait until visibility of an element known to " \
                "be is determined"
        pNote("KEYWORD: wait_until_visibility_of_element_located | Description: {0}".format(wdesc))
        pSubStep(wdesc)
        browser_details = {}

        system = xml_Utils.getElementWithTagAttribValueMatch(self.datafile,
                                                             "system",
                                                             "name",
                                                             system_name)
        browser_list = system.findall("browser")
        try:
            browser_list.extend(system.find("browsers").findall("browser"))
        except AttributeError:
            pass

        if not browser_list:
            browser_list.append(1)
            browser_details = arguments

        for browser in browser_list:
            arguments = Utils.data_Utils.get_default_ecf_and_et(arguments,
                                                                self.datafile,
                                                                browser)
            if browser_details == {}:
                browser_details = selenium_Utils. \
                    get_browser_details(browser, datafile=self.datafile, **arguments)
            if browser_details is not None:
                current_browser = Utils.data_Utils.get_object_from_datarepository(system_name + "_" + browser_details["browser_name"])
                if not current_browser:
                    pNote("Browser of system {0} and name {1} not found in the "
                          "datarepository"
                          .format(system_name, browser_details["browser_name"]),
                          "Exception")
                    status = False
                else:
                    status = self.wait_oper_object.\
                        wait_until_visibility_of_element_located(current_browser,
                                                                 browser_details["locator_type"],
                                                                 browser_details["locator"],
                                                                 browser_details["timeout"])
            browser_details = {}
        Utils.testcase_Utils.report_substep_status(status)
        if current_browser:
            selenium_Utils.save_screenshot_onerror(status, current_browser)
        return status
    def create_jira_issue(self,
                          server_url,
                          username,
                          password,
                          issue_summary,
                          issue_description,
                          project_key,
                          issue_type='Bug'):
        """
            connect to jira server and create an issue under a specific project
        """
        status = True
        output_dict = {}
        wdesc = "Creates a JIRA issue"
        pSubStep(wdesc)
        issue_summary = issue_summary.replace('"', " ")
        issue_description = issue_description.replace('"', "-")
        fetchuri = server_url
        postdata_url = fetchuri + '/rest/api/2/issue/'
        postdata = """
        {
            "fields": {
                "project":
                {
                    "key": \"""" + project_key + """\"
                },
                "summary": \"""" + issue_summary + """\",
                "description": \"""" + issue_description + """\",
                "issuetype": {
                    "name": \"""" + issue_type + """\"
                }
            }
        }
        """
        credential_handler = urllib.request.HTTPPasswordMgrWithDefaultRealm()
        credential_handler.add_password(None, postdata_url, username, password)
        auth = urllib.request.HTTPBasicAuthHandler(credential_handler)
        userpassword = username + ":" + password
        password = base64.b64encode(userpassword)
        #Create an Authentication handler
        opener = urllib.request.build_opener(auth)
        urllib.request.install_opener(opener)
        opener = urllib.request.build_opener(
            urllib.request.HTTPHandler(debuglevel=1))
        #Create a POST request
        headers = {
            "Authorization": "Basic " + password,
            "Content-Type": "application/json"
        }
        request = urllib.request.Request(str(postdata_url), postdata, headers)
        try:
            handler = urllib.request.urlopen(request)
            extension = json.loads(handler.read())
            issue_id = str(extension['key'])
            pNote("JIRA Issue Created. Issue-Id: {0}".format(issue_id))
            output_dict["issue_id"] = issue_id
        except Exception as e:
            status = False
            pNote("Problem creating JIRA issue.", "error")
            pNote("JIRA Error Code: ({0})".format(e), "error")

        Utils.data_Utils.update_datarepository(output_dict)
        Utils.testcase_Utils.report_substep_status(status)
        return status
예제 #15
0
    def verify_page_by_property(self,
                                system_name,
                                expected_value,
                                value_type,
                                browser_name="all",
                                element_config_file=None,
                                element_tag=None):
        """
        This keyword will verify page by property.

        :Datafile Usage:

            Tags or attributes to be used in input datafile for the system or
            subsystem. If both tag and attribute is provided the attribute will
            be used.

            1. system_name = This attribute can be specified in the datafile as
                             a <system> tag directly under the <credentials>
                             tag. An attribute "name" has to be added to this
                             tag and the value of that attribute would be taken
                             in as value to this keyword attribute.

                             <system name="name_of_thy_system"/>

            2. browser_name = This <browser_name> tag is a child og the
                              <browser> tag in the data file. Each browser
                              instance should have a unique name. This name can
                              be added here

                              Eg: <browser_name>Unique_name_1</browser_name>

            3. url = The URL that you want to open your browser to can be added
                     in the <url> tag under the <browser> tag.

                     Eg: <url>https://www.google.com</url>

            4. expected_value = This <expected_value> tag is a child og the
                                <browser> tag in the data file. This tag would
                                contain the the value you expect the browser to
                                have. This can be either a  url, page title,
                                page source, or page name

                    Eg: <expected_value>http://www.google.com</expected_value>

            5. value_type = This <value_type> tag is a child of the <browser>
                            tag in the data file. This tag would contain the
                            type of browser information that you want to verify.
                            It can either be current_url, title, name, or
                            page_source

                            Eg: <value_type>title</value_type>

            6. element_config_file = This <element_config_file> tag is a child
                                     of the <browser> tag in the data file. This
                                     stores the location of the element
                                     configuration file that contains all
                                     element locators.

                                  Eg: <element_config_file>
                                      ../Config_files/selenium_config.json
                                      </element_config_file>

            7. element_tag = This element_tag refers to a particular element in
                             the json fie which contains relevant information to
                             that element. If you want to use this one element
                             through out the testcase for a particular browser,
                             you can include it in the data file. If this not
                             the case, then you should create an argument tag
                             in the relevant testcase step and add the value
                             directly in the testcase step.

                             FOR DATA FILE
                             Eg: <element_tag>json_name_1</element_tag>

                             FOR TEST CASE
                             Eg: <argument name="element_tag" value="json_name_1">

        :Arguments:

            1. system_name(str) = the system name.
            2. expected_value (str) = The expected value of the information
                                      retrieved from the web page.
            3. value_type (str) = Type of page information that you wat to
                                  verify: current_url, name, title, or
                                  page_source
            4. browser_name(str) = Unique name for this particular browser
            5. url(str) = URL to which the browser should be directed
            6. element_config_file (str) = location of the element configuration
                                           file that contains all element
                                           locators
            7. element_tag (str) = particular element in the json fie which
                                   contains relevant information to that element

        :Returns:

            1. status(bool)= True / False.

        """
        arguments = locals()
        arguments.pop('self')
        status = True
        wdesc = "The browser will verify page by {0}".format(value_type)
        pNote("KEYWORD: verify_page_by_property | Description: {0}".format(
            wdesc))
        pSubStep(wdesc)
        browser_details = {}

        system = xml_Utils.getElementWithTagAttribValueMatch(
            self.datafile, "system", "name", system_name)
        browser_list = system.findall("browser")
        try:
            browser_list.extend(system.find("browsers").findall("browser"))
        except AttributeError:
            pass

        if not browser_list:
            browser_list.append(1)
            browser_details = arguments

        for browser in browser_list:
            arguments = Utils.data_Utils.get_default_ecf_and_et(
                arguments, self.datafile, browser)
            if browser_details == {}:
                browser_details = selenium_Utils. \
                    get_browser_details(browser, datafile=self.datafile, **arguments)
            if browser_details is not None:
                current_browser = Utils.data_Utils.get_object_from_datarepository(
                    system_name + "_" + browser_details["browser_name"])
                if current_browser:
                    obtained_value = self.verify_oper_object.get_page_property(
                        current_browser, browser_details["value_type"])
                    if str(obtained_value) == expected_value:
                        pNote("The obtained {0}: {1} matches the expected "
                              "value: {2}. Verification success!".format(
                                  value_type, obtained_value, expected_value))
                    else:
                        pNote(
                            "The obtained {0}: {1} does not match the "
                            "expected value: {2}. Verification failed!".format(
                                value_type, obtained_value, expected_value),
                            "Error")
                        status = False
                else:
                    pNote(
                        "Browser of system {0} and name {1} not found in the "
                        "datarepository".format(
                            system_name, browser_details["browser_name"]),
                        "Exception")
                    status = False
            browser_details = {}
        Utils.testcase_Utils.report_substep_status(status)
        if current_browser:
            selenium_Utils.save_screenshot_onerror(status, current_browser)
        return status
예제 #16
0
    def gnmi_operations(self,
                        system_name,
                        q_query,
                        operation,
                        verify=None,
                        external_system=None,
                        external_system_session=None,
                        timestamp="''",
                        user_arg=""):
        """
        will perform the following operations:
        1. Get
        2. Set operation(types: delete/replace/update)
        3. Capabilities
        and store the output JSON in a data dictionary.
        :param system_name: server System name as in data file, server where gnmi client will
        send out its request.
        :param q_query: query xpath as string
        e.g. "/system/services/sftp/sftp-server[sftp-server-port=2202]"
        :param operation: Type of operation(get/set/capabilities).
        :param verify: user provided string to verify can provide multiple sting separated by ","
                       e.g. '"sftp-server-port": "2202", "sftp-server-enabled": "true"'.
                       Verify string also has regular expression support.
        :param external_system_session: External system system session.
                       e.g. '"sftp-server-port": "2202", "sftp-server-enabled": "true"'.
                       Verify string also has regular expression support.
        :param timestamp:  Specify timestamp formatting in output.
                           One of (<empty string>, on, raw, <FORMAT>)
                           where <empty string> is disabled,
                           on is human readable,
                           raw is int64 nanos since epoch,
                           and <FORMAT> is according to golang time.Format(<FORMAT>)
        :param user_arg: Extra argument place for feature use
                         if any new argument user wants to pass on.
        :return: True or False and dictionary containing output string
        """

        wdesc = "***** Executing gnmi " + operation + " operation *****"
        testcase_Utils.pSubStep(wdesc)
        status = False
        result = None
        outputdict = {}
        gnmi_execute = gnmi()
        gnmi_param = [
            'ip', 'gnmi_port', 'username', 'password', 'prompt', 'ca_crt',
            'client_crt', 'client_key'
        ]
        gnmi_param_dic = data_Utils.get_credentials(self.datafile, system_name,
                                                    gnmi_param)
        __gnmi_obj = Utils.data_Utils.get_object_from_datarepository(
            str(system_name) + "_gnmi_session")
        file_dir = os.path.dirname(os.path.abspath(__file__))
        war_dir = os.path.abspath(os.path.join(file_dir, '../..'))
        binary = os.path.join(war_dir, 'Framework/Gnmi/gnmi_cli')
        testcase_Utils.pNote("***** Binary path: {0} *****".format(binary))
        if __gnmi_obj:
            gnmi_obj = __gnmi_obj
        else:
            gnmi_obj = None
        if external_system:
            ext_gnmi_param_dic = data_Utils.get_credentials(
                self.datafile, external_system,
                ['ca_crt', 'client_crt', 'client_key'])

        if external_system == None:
            ca_crt, client_crt, client_key = data_Utils.set_gnmi_cert_params(
                gnmi_param_dic)
        else:
            ca_crt, client_crt, client_key = data_Utils.set_gnmi_cert_params(
                ext_gnmi_param_dic)

        username = gnmi_param_dic.get('username')
        password = gnmi_param_dic.get('password')
        prompt = gnmi_param_dic.get('prompt')

        if operation in "get":
            cmd_string = gnmi_execute.get_cmd_string(
                ip=gnmi_param_dic['ip'],
                gnmi_port=gnmi_param_dic['gnmi_port'],
                username=username,
                password=password,
                ca_crt=ca_crt,
                client_crt_path=client_crt,
                client_key=client_key,
                operation=operation,
                q_query=q_query,
                timestamp=timestamp,
                user_arg=user_arg)
        else:
            cmd_string = gnmi_execute.get_cmd_string(
                ip=gnmi_param_dic['ip'],
                gnmi_port=gnmi_param_dic['gnmi_port'],
                username=username,
                password=password,
                ca_crt=ca_crt,
                client_crt_path=client_crt,
                client_key=client_key,
                operation=operation,
                q_query=q_query)
        print_info("** {0} Operation in progress **".format(operation))
        if cmd_string:
            status, result, child = gnmi_execute.execute(
                binary, cmd_string, username, password, prompt,
                external_system, external_system_session, None, gnmi_obj)
        if status and verify:
            status = gnmi_execute.verify(result, verify)
        outputdict = {'{}_gnmi_result'.format(system_name): result}
        return status, outputdict
예제 #17
0
    def gnmi_subscribe(self,
                       system_name,
                       option,
                       q_query,
                       qt_querytype="once",
                       polling_interval="30s",
                       stop_after=None,
                       verify=None,
                       external_system=None,
                       external_system_session=None,
                       streaming_duration="0s",
                       timestamp="''",
                       user_arg=""):
        """
        gnmi Subscribe Keyword Will perform get(subscribe once is get), Polling
        operation and store the output json in data dictionary.
        :param system_name: server System name as in data file, server where gnmi client
         will send out its request.
        :param q_query: query xpath as string e.g. "/system/services/sftp/sftp-server"
                        can have multiple query separated by ","
                         e.g. "/system/services/sftp/sftp-server,/interfaces/interface"
        :param qt_querytype: Tyep of query as string.
                            qt_querytype must be one of: once, polling or streaming.
                             (default "once")
        :param polling_interval: Interval at which to poll in seconds if polling
        is specified for query_type.(default 30s)
        :param stop_after: User can specify a time after that polling or streaming
        will be stopped. (default None)
        :param verify: user provided string to verify can provide multiple sting separated by ","
                       e.g. '"sftp-server-port": "2202", "sftp-server-enabled": "true"'.
                       Verify string also has regular expression support.
        :param external_system: External system name mentioned as in data file.
                                This is optional if user want to execute gnmi from a different
                                server other than the warrior framework host machine.
        :param external_system_session: External system system session.
        :param streaming_duration: Length of time to collect streaming queries (0 is infinite).
         (default 0s)
        :param timestamp:  Specify timestamp formatting in output.
                           One of (<empty string>, on, raw, <FORMAT>)
                           where <empty string> is disabled,
                           on is human readable,
                           raw is int64 nanos since epoch,
                           and <FORMAT> is according to golang time.Format(<FORMAT>)
        :param user_arg: Extra argument place for feature use
         if any new argument user wants to pass on.
        :return:  True or False and dictionary containing output string and gnmi session
        in case of streaming or polling
        """

        wdesc = "Executing gnmi Subscribe"
        testcase_Utils.pSubStep(wdesc)
        status = False
        result = None
        outputdict = {}
        gnmi_execute = gnmi()
        gnmi_param = [
            'ip', 'gnmi_port', 'username', 'password', 'prompt', 'ca_crt',
            'client_crt', 'client_key'
        ]
        gnmi_param_dic = data_Utils.get_credentials(self.datafile, system_name,
                                                    gnmi_param)
        __gnmi_obj = Utils.data_Utils.get_object_from_datarepository(
            str(system_name) + "_gnmi_session")
        file_dir = os.path.dirname(os.path.abspath(__file__))
        war_dir = os.path.abspath(os.path.join(file_dir, '../..'))
        binary = os.path.join(war_dir, 'Framework/Gnmi/gnmi_cli')

        testcase_Utils.pNote("***** Binary path: {0} *****".format(binary))
        if __gnmi_obj:
            gnmi_obj = __gnmi_obj
        else:
            gnmi_obj = None
        if external_system:
            ext_gnmi_param_dic = data_Utils.get_credentials(
                self.datafile, external_system,
                ['ca_crt', 'client_crt', 'client_key'])

        if external_system == None:
            ca_crt, client_crt, client_key = data_Utils.set_gnmi_cert_params(
                gnmi_param_dic)
        else:
            ca_crt, client_crt, client_key = data_Utils.set_gnmi_cert_params(
                ext_gnmi_param_dic)

        username = gnmi_param_dic.get('username')
        password = gnmi_param_dic.get('password')
        prompt = gnmi_param_dic.get('prompt')

        cmd_string = gnmi_execute.get_cmd_string(
            ip=gnmi_param_dic['ip'],
            gnmi_port=gnmi_param_dic['gnmi_port'],
            ca_crt=ca_crt,
            client_crt_path=client_crt,
            client_key=client_key,
            option=option,
            qt_querytype=qt_querytype,
            q_query=q_query,
            polling_interval=polling_interval,
            timestamp=timestamp,
            streaming_duration=streaming_duration,
            user_arg=user_arg)
        status, result, child = gnmi_execute.execute(binary, cmd_string,
                                                     username, password,
                                                     prompt, external_system,
                                                     external_system_session,
                                                     stop_after, gnmi_obj)
        if status and verify and result:
            status = gnmi_execute.verify(result, verify)

        if external_system or qt_querytype not in ['polling', 'streaming']:
            outputdict = {'{}_gnmi_result'.format(system_name): result}
        else:
            outputdict = {
                '{}_gnmi_result'.format(system_name): result,
                '{}_gnmi_session'.format(system_name): child
            }
        return status, outputdict
    def cs_reservation(self, system_name, reservation_name, duration_in_mins,
                       topology_full_path):
        """
        Defines a reservation to be created.

        This keyword only defines the reservation with all its details by saving
        the details in the data repository. Actual creation is done by using the
        cs_reservation keyword by providing the reservation name
        to it.

        :Datafile usage:
            Tags or attributes to be used in input datafile for the system
            or subsystem.If both tag and attribute is provided the attribute
            will be used.
            1. username   = name of the cloudshell user

        :Arguments:
            1. system_name(string) = Name of the UAP system from the datafile
            2. reservation_name(string) = Specify the name of the reservation.
            3. duration_in_mins(int) = Specify the length of the reservation.
            4. topology_full_path(str) = Specify the full path of the reservation.

        :Returns:
            1. status(bool)= True/False
        """
        try:
            from cloudshell.api.cloudshell_api import CloudShellAPISession
            from cloudshell.api.common_cloudshell_api import CloudShellAPIError
        except ImportError:
            print_info("{0}: Cloudshell Python Package is not installed".\
                       format(os.path.abspath(__file__)))
            print_info("Please install latest Cloudshell Python Package.")

        api = self._create_cs_obj(system_name)
        flag = True
        output_dict = {}
        wdesc = "Save reservation details for the reservation name provided"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())
        testcase_Utils.pNote("save reservation, cs obj-{}".\
                             format(api), "info")
        testcase_Utils.pNote("Login, cs obj-{}".format(api), "info")

        if api is not None:
            testcase_Utils.pNote("\n\n *** Login to Cloudshell System-{}"
                                 " successfull, domain-{}\n".\
                                 format(api.host,\
                                 api.domain), "info")

        keys_for_credentials = ['username']
        credentials = data_Utils.get_credentials(self.datafile, system_name,
                                                 keys_for_credentials)

        pNote("This keyword will only collect the reservation information "\
              "and save the details in data repository.\n")
        res_key = "{0}_{1}_cs_rsrv_details".format(system_name,
                                                   reservation_name)
        output_dict = {
            res_key: {
                "reservation_name": reservation_name,
                "username": credentials['username'],
                "duration": duration_in_mins,
                "topology_full_path": topology_full_path
            },
        }
        pNote("The CloudShell Reservation Provided Details is :{}".format(
            output_dict))

        blueprint_to_reserve = topology_full_path
        reservation_time = duration_in_mins
        blueprint_owner = credentials['username']
        reservation_name = reservation_name
        # Do reservation
        try:
            result = api.CreateImmediateTopologyReservation(reservationName=reservation_name, \
                                                            owner=blueprint_owner,
                                                            durationInMinutes=reservation_time,
                                                            topologyFullPath=\
                                                                blueprint_to_reserve).Reservation

            reservation_id = result.Id
            reservation_details = api.GetReservationDetails(
                reservation_id).ReservationDescription
            # Check for Conflicts
            if reservation_details.Conflicts:
                conflicts_suggested_end_times = []
                for conflicted_resource in reservation_details.Conflicts:
                    planned_end_time = conflicted_resource.ConflictPlannedEndTime
                    if planned_end_time is None:
                        continue
                    if planned_end_time not in conflicts_suggested_end_times:
                        conflicts_suggested_end_times.append(planned_end_time)
                # End the Reservation
                api.EndReservation(reservation_id)
                msg = "Conflicts Found, Planned end time for resources inside \
                is:\n{}".format("\n".join(conflicts_suggested_end_times))
                raise CloudShellAPIError(102, msg, "")

            # Wait for Sandbox to be ready
            wait_timeout = 100  # seconds
            now = datetime.datetime.now()
            while wait_timeout > (datetime.datetime.now() - now).seconds:
                status = api.GetReservationStatus(
                    reservation_id).ReservationSlimStatus
                if status.ProvisioningStatus == "Error":
                    api.EndReservation(reservation_id)
                    raise CloudShellAPIError(102, "Error with Setup workflow",
                                             "")
                elif status.ProvisioningStatus == "Ready" or status.ProvisioningStatus == "Not Run":
                    pNote(
                        " CloudShell Reservation made successfully. ID is: {}".
                        format(reservation_id))
                    flag = True
                    break
                time.sleep(1)
            else:
                api.EndReservation(reservation_id)
                raise CloudShellAPIError(
                    102, "No positive status return for reservation \
                after {} seconds".format(wait_timeout), "")

        except CloudShellAPIError as cs_err:
            # Example error check for user
            if 'User "{}" does not exist'.format(
                    blueprint_owner) == cs_err.message:
                raise Exception("No user name: {}".format(blueprint_owner))
            # Example error check for blueprint
            elif 'Topology \'{}\' was not found'.format(
                    blueprint_to_reserve) == cs_err.message:
                raise Exception(
                    "No blueprint with name: {}".format(blueprint_to_reserve))
            # Generic raise error from cloudshell
            raise Exception(cs_err.message)
        except Exception as e:
            # other non-cloudshell errors
            raise
        else:
            pNote("Sucessfully saved reservation details for reservation_name={0}"\
                  .format(reservation_name))
        return flag
    def cs_create_reservation(self, system_name, reservation_name,
                              duration_in_mins, notify_on_start, notify_on_end,
                              notify_mins_before_end):
        """
        Defines a reservation to be created.

        This keyword only defines the reservation with all its details by saving
        the details in the data repository. Actual creation is done by using the
        cs_add_topology_to_reservation keyword by providing the reservation name
        to it.

        :Datafile usage:
            Tags or attributes to be used in input datafile for the system
            or subsystem.If both tag and attribute is provided the attribute
            will be used.
            1. username   = name of the cloudshell user

        :Arguments:
            1. system_name(string) = Name of the UAP system from the datafile
            2. reservation_name(string) = Specify the name of the reservation.
            3. duration_in_mins(int) = Specify the length of the reservation.
            4. notify_on_start(string) = true or false, Indicate whether to notify the
               reservation owner when the reservation starts.
            5. notify_on_end(string) = true or false, Indicate whether to notify the reservation
               owner when the reservation ends.
            6. notify_mins_before_end(int) = Notification Minutes Before End -
               Indicate the number of minutes before the end of the reservation
               to send out a Notify On End alert to the reservation owner.
               (0 = disabled)

        :Returns:
            1. status(bool)= True/False
            2. output_dict = consists of following key value pairs:
               1. domain_id: Domain Id returned after login to cloudshell.
               2. reservation_id: Reservation Id returned after successful
                  creation of resources.
        """

        wdesc = "Save reservation details for the reservation name provided"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())

        testcase_Utils.pNote("save reservation, cs obj-{}".\
                             format(cloud_shell), "info")

        keys_for_credentials = ['username']
        credentials = data_Utils.get_credentials(self.datafile, system_name,
                                                 keys_for_credentials)

        status = True
        output_dict = {}
        try:
            pNote("This keyword will only collect the reservation information "\
                  "and save the details in data repository.\n")
            pNote("In order to create reservation in cloudshell, execute this keyword and then "\
                  "use the keyword 'cs_add_topology_to_reservation' and provide the "\
                  "reservation_name to it, 'cs_add_topology_to_reservation' keyword will use "\
                  "the reservation  details for he reservation_name provided, create a "\
                  "reservation and add topology to the reservation.")

            res_key = "{0}_{1}_cs_rsrv_details".format(system_name,
                                                       reservation_name)
            notify_on_start = notify_on_start.lower()
            notify_on_end = notify_on_end.lower()
            output_dict = {
                res_key: {
                    "reservation_name": reservation_name,
                    "username": credentials['username'],
                    "duration": duration_in_mins,
                    "notify_on_start": notify_on_start,
                    "notify_on_end": notify_on_end,
                    "notify_mins_before_end": notify_mins_before_end
                }
            }

        except Exception as exception:
            pNote("Saving reservation details for reservation_name={0} failed!!"\
                  .format(reservation_name))
            print_exception(exception)
            status = False
        else:
            pNote("Sucessfully saved reservation details for reservation_name={0}"\
                  .format(reservation_name))

        testcase_Utils.report_substep_status(status)
        return status, output_dict
    def cs_create_topology_reservation(self, system_name, reservation_name,
                                       duration_in_mins, notify_on_start,
                                       notify_on_end, notify_mins_before_end,
                                       topology_full_path):
        """Defines a reservation to be started immediately

        :Datafile usage:
            Tags or attributes to be used in input datafile for the system
            or subsystem.If both tag and attribute is provided the attribute
            will be used.
            1. username   = name of the cloudshell user

        :Arguments:
            1. system_name(string) = Name of the UAP system from the datafile
            2. reservation_name(string) = Specify the name of the reservation.
            3. duration_in_mins(int) = Specify the length of the reservation.
            4. notify_on_start(string) = true or false, Indicate whether to notify the
               reservation owner when the reservation starts.
            5. notify_on_end(string) = true or false, Indicate whether to notify the reservation
               owner when the reservation ends.
            6. notify_mins_before_end(int) = Notification Minutes Before End -
               Indicate the number of minutes before the end of the reservation
               to send out a Notify On End alert to the reservation owner.
               (0 = disabled)
            7. topology_full_path(string) = Specify the full topology name. Include
               the full path from the root to the topology, separated by slashes.
               For example: FolderName/Topologies/TopologyName

        :Returns:
            1. status(bool)= True/False
            2. output_dict = consists of following key value pairs:
               1. domain_id: Domain Id returned after login to cloudshell.
               2. reservation_id: Reservation Id returned after successful
                  creation of resources.
        """

        wdesc = "Create Topology Reservation in CloudShell API Host"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())

        testcase_Utils.pNote("cs_create_topology_reservation, cs obj-{}".\
                             format(cloud_shell), "info")

        keys_for_credentials = ['username']
        credentials = data_Utils.get_credentials(self.datafile, system_name,
                                                 keys_for_credentials)

        status = False
        output_dict = {}
        notify_on_start = notify_on_start.lower()
        notify_on_end = notify_on_end.lower()
        try:
            xml_resp = cloud_shell.CreateImmediateTopologyReservation(
                reservation_name, credentials['username'],
                int(duration_in_mins), notify_on_start, notify_on_end,
                int(notify_mins_before_end), topology_full_path)
            if xml_resp is not None:
                reservation_id = xml_resp.Reservation.Id
                output_dict = {
                    'domain_id':
                    cloud_shell.domain,
                    '{0}_{1}_reservationId'.format(system_name, reservation_name):
                    reservation_id
                }
                testcase_Utils.pNote("\n\n *** Cloudshell CreateTopologyReservation"
                                     " successfull for ResName-\"{}\" ResId-{}\n".\
                                     format(reservation_name,
                                            output_dict['{0}_{1}_reservationId'.\
                                                        format(system_name, reservation_name)]),
                                     "info")
                status = True
            else:
                testcase_Utils.pNote(
                    "\n\n *** Cloudshell CreateTopologyReservation"
                    " failed for \"{}\"".format(reservation_name), "warning")
        except Exception as exception:
            print_exception(exception)

        testcase_Utils.report_substep_status(status)
        return status, output_dict
    def cs_add_topology_to_reservation(self, system_name, reservation_name,
                                       topology_full_path):
        """
        Create the reservation and add topology to the reservation in Cloudshell

        :Datafile usage:
             NA
        :Arguments:
            1. system_name(string) = Name of the UAP system from the datafile
            2. reservation_name(string) = Specify the name of the reservation.
            3. topology_full_path(string) = Specify the full topology name. Include
               the full path from the root to the topology, separated by slashes.
               For example: FolderName/Topologies/TopologyName

        :Returns:
            1. status(bool)= True/False
        """
        wdesc = "Create the reservation and add Topology to Reservation in CloudShell API Host"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())

        status = True
        res_key = "{0}_{1}_cs_rsrv_details".format(system_name,
                                                   reservation_name)
        res_details = data_Utils.get_object_from_datarepository(res_key)
        output_dict = {}

        if res_details:
            username = res_details["username"]
            reservation_name = res_details["reservation_name"]
            duration = int(res_details["duration"])
            notify_on_start = res_details["notify_on_start"]
            notify_on_end = res_details["notify_on_end"]
            notify_mins_before_end = int(res_details["notify_mins_before_end"])
            try:
                xml_resp = cloud_shell.CreateImmediateTopologyReservation(
                    reservation_name, username, duration, notify_on_start,
                    notify_on_end, notify_mins_before_end, topology_full_path)
                if xml_resp is not None:
                    reservation_id = xml_resp.Reservation.Id
                    output_dict = {
                        'domain_id':
                        cloud_shell.domain,
                        '{0}_{1}_reservationId'.format(system_name, reservation_name):
                        reservation_id
                    }

                    testcase_Utils.pNote("\n\n *** Cloudshell CreateReservation"
                                         " successful for ResName-\"{}\" ResId-{}\n".\
                                         format(reservation_name,
                                                output_dict['{0}_{1}_reservationId'.\
                                                            format(system_name,
                                                                   reservation_name)]),
                                         "info")

                    testcase_Utils.pNote("\n\n *** Cloudshell Add Topology \"{}\""
                                         " successful for \"{}\"\n".\
                                         format(topology_full_path, reservation_name),
                                         "info")

                else:
                    testcase_Utils.pNote(
                        "\n\n *** Cloudshell CreateReservation"
                        " failed for \"{}\"".format(reservation_name),
                        "warning")

                    testcase_Utils.pNote("\n\n *** Cloudshell Add Topology \"{}\""
                                         " failed for \"{}\"".\
                                         format(topology_full_path, reservation_name),
                                         "warning")
                    status = False
            except Exception as exception:
                print_exception(exception)
                status = False
        else:
            pNote("Details for reservation_name={0}, for sysem={1} "\
                  "not found in data repository. Please make sure "\
                  "to execute the keyword '{2}' before this"\
                  "step".format(reservation_name, system_name, 'cs_create_reservation'),
                  "warning")
            status = False

        testcase_Utils.report_substep_status(status)
        return status, output_dict
    def cs_activate_topology(self,
                             system_name,
                             reservation_name,
                             topology_full_path,
                             time_out=60):
        """Activate Topology to reservation in Cloudshell

        :Datafile usage:
             NA
        :Arguments:
            1. system_name(string) = Name of the UAP system from the datafile
            2. reservation_name(string) = Specify the name of the reservation.
            3. topology_path(string) = Specify the full topology name. Include
               the full path from the root to the topology, separated by slashes.
               For example: FolderName/Topologies/TopologyName
            4. time_out(int): Before activating topology, we need to check status
                of the reservation. If it is started, then we need to activate the
                topology.
                Need to wait for some time before activating topology for
                reservation status to get started, making the default value of
                time_out as 60 sec and can change the value depending on number
                of resources.
        :Returns:
            1. status(bool)= True/False
        """

        wdesc = "Activate Topology to Reservation in CloudShell API Host"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())

        testcase_Utils.pNote("cs_activate_topology, cs obj-{}".\
                             format(cloud_shell), "info")

        status = True
        cs_res_id = data_Utils.get_object_from_datarepository\
                    (system_name+"_"+reservation_name+"_reservationId")

        #Before entering try block to activate the topology,
        #check whether Reservation status is Started. If status is not Started,
        #then wait for time_out seconds before activating.

        # Check for Conflicts
        reservation_status = cloud_shell.GetReservationDetails(
            cs_res_id).ReservationDescription
        if reservation_status.Conflicts:
            conflicts_suggested_end_times = []
            for conflicted_resource in reservation_status.Conflicts:
                planned_end_time = conflicted_resource.ConflictPlannedEndTime
                if planned_end_time not in conflicts_suggested_end_times:
                    conflicts_suggested_end_times.append(planned_end_time)
            # End the Reservation
            cloud_shell.EndReservation(cs_res_id)
            print_error(
                "Conflicts Found, Planned end time for resources inside is:\n{}"
                .format("\n".join(conflicts_suggested_end_times)))
            status = False
            return status

        reservation_status = cloud_shell.GetReservationDetails(
            cs_res_id).ReservationDescription.Status
        sec = 0
        while reservation_status != "Started":
            sec = sec + 1
            reservation_status = cloud_shell.GetReservationDetails(
                cs_res_id).ReservationDescription.Status
            time.sleep(1)
            if sec == int(time_out):
                testcase_Utils.pNote("Waited for {0} seconds, the current reservation"
                                     " status is {1}, but the"
                                     " expected status is Started".\
                                     format(int(time_out), reservation_status),
                                     "warning")
                status = False
                break
        if status:
            try:
                xml_resp = cloud_shell.ActivateTopology(
                    cs_res_id, topology_full_path)
                if xml_resp is not None:
                    testcase_Utils.pNote("\n\n *** Cloudshell Activate Topology-\"{}\""
                                         " successfull for \"{}\"\n".\
                                         format(topology_full_path, reservation_name),\
                                         "info")
                else:
                    testcase_Utils.pNote("\n\n *** Cloudshell Activate Topology-\"{}\""
                                         " failed for \"{}\"".\
                                         format(topology_full_path, reservation_name),
                                         "warning")
                    status = False
            except Exception as exception:
                print_exception(exception)
                status = False
        testcase_Utils.report_substep_status(status)
        return status