def copy_config(self, source, target, system_name, session_name=None): """Create or replace an entire configuration datastore with the contents of another complete configuation datastore :Arguments: 1. source(string) = name of the configuration datastore to use as the source of the copy operation or config element containing the configuration subtree to copy. 2. target(string) = name of the configuration datastore to use as the destination of the copy operation 3. system_name(string) = Name of the system from the input datafile 4. session_name(string) = Name of the session to the system :Returns: 1. status(bool)= True / False 2. Copy Response in the data repository {data:reply(xml)} """ wdesc = "Create or replace an entire configuration datastore with another datastore" pSubStep(wdesc) pNote(system_name) pNote(self.datafile) self.clear_notification_buffer_all(system_name, session_name) session_id = Utils.data_Utils.get_session_id(system_name, session_name) netconf_object = Utils.data_Utils.get_object_from_datarepository( session_id) reply = netconf_object.copy_config(source, target) if reply: reply = parseString(reply).toprettyxml(indent=" ") pNote('copy-config: Reply= {}'.format(reply)) if netconf_object.isCOMPLD: status = True else: status = False pNote('copy-config: Failed {}'.format(netconf_object.ErrorMessage), "error") report_substep_status(status) reply_key = '{}_copy_config_reply'.format(system_name) return status, {reply_key: reply}
def get_schema(self, system_name, identifier, version_number=None, format_type=None, session_name=None): """get-schema rpc :Arguments: 1. system_name(string) = Name of the system from the input datafile 2. identifier(string) = schema id (name of a yang module, e.g. ietf-alarms) 3. version_number(string) = version number (e.g. 1.0) 4. format_type(string) = schema format (e.g. yang) 5. session_name(string) = name if the session to the system :Returns: 1. command_status(bool) 2. {data:reply.data(xml)} """ wdesc = "get-schema" pSubStep(wdesc) pNote(system_name) pNote(self.datafile) self.clear_notification_buffer_all(system_name, session_name) session_id = Utils.data_Utils.get_session_id(system_name, session_name) netconf_object = Utils.data_Utils.get_object_from_datarepository( session_id) reply = netconf_object.get_schema( identifier, version_number, format_type) if reply: reply = parseString(reply).toprettyxml( indent=" ", encoding="UTF-8") pNote('get-schema: Reply= {}'.format(reply)) if netconf_object.isCOMPLD: status = True else: pNote('get-schema: Failed {}'.format(netconf_object.ErrorMessage), "error") status = False report_substep_status(status) reply_key = '{}_get_schema_reply'.format(system_name) return status, {reply_key: reply}
def request_rpc(self, system_name, session_name=None, request="", xmlns="", request_type="", xmlns_tag="xmlns"): """ Request operations through Netconf interface. If value for 'request' is provided, it will be used for request operations else the XML input will be taken from the netconf_data file based on xmlns, request_type, xmlns_tag values. :Arguments: 1. system_name(string) = Name of the system from the input datafile 2. session_name(string) = Name of the session to the system 3. request(string) = command to be sent as xml string 4. xmlns(string) = XML namespace of the particular request 5. Request_type(string) = The operation that we want to perform 6. xmlns_tag(string) = xml tag for the particular request for eg: For request Type: <init-pm xmlns="urn:params:xml:ns:yang:perfmon"> usage: xmlns_tag = xmlns(default value, no need pass this argument) xmlns = "urn:params:xml:ns:yang:perfmon" request_type= "init-pm" For Request Type : <org-openroadm-de-operations:restart xmlns: org-openroadm-de-operations="http://org/openroadm/de/operations"> usage: xmlns_tag = "xmlns:org-openroadm-de-operations" xmlns = "http://org/openroadm/de/operations" request_type = "org-openroadm-de-operations:restart" :Returns: 1. status = True/False/error 2. RPC replies in a list & it will be updated in the data repository in key - [system_name]_request_rpc_reply. """ wdesc = "Request particular operation from the system" pSubStep(wdesc) reply_key = '{}_request_rpc_reply'.format(system_name) reply_list = [] pNote(system_name) pNote(self.datafile) self.clear_notification_buffer_all(system_name, session_name) session_id = Utils.data_Utils.get_session_id(system_name, session_name) netconf_object = Utils.data_Utils.\ get_object_from_datarepository(session_id) config_data_list = [] status = True if request: config_data_list = [request] elif all([xmlns != "", request_type != "", xmlns_tag != ""]): config_datafile = Utils.data_Utils.\ get_filepath_from_system(self.datafile, system_name, 'netconf_data')[0] if config_datafile and Utils.file_Utils.\ fileExists(config_datafile): status, config_data_list = Utils.data_Utils.\ get_nc_request_rpc_string(config_datafile, xmlns, request_type, xmlns_tag) else: status = "error" pNote( "Datafile does not have any value for netconf_data tag " "or the filepath mentioned in the netconf_data tag " "does not exist", 'error') else: status = "error" pNote( "Please provide value(s) for 'request' or 'xmlns &" " request_type'", 'error') if status is True and config_data_list: list_config_data = [] if not isinstance(config_data_list, list): list_config_data.append(config_data_list) else: list_config_data = config_data_list for config_data in list_config_data: if config_data: reply = netconf_object.request_rpc(config_data) reply_list.append(reply) pNote('Request RPC Reply= {}'.format(reply)) if netconf_object.isCOMPLD: sub_status = True else: pNote( 'Request RPC Failed {}'.format( netconf_object.ErrorMessage), "error") sub_status = False else: reply_list.append("error") pNote('Request RPC Failed', "error") sub_status = "error" status = status and sub_status if sub_status != "error" \ else sub_status report_substep_status(status) return status, {reply_key: reply_list}
def connect_netconf(self, system_name, session_name=None): """ Connects to the Netconf interface of the the given system or subsystems :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. ip = IP address of the system/subsystem 2. nc_port = use this tag to provide ssh port to connect to Netconf \ interface, if not provided default port 830 will be used. 3. username = username for the ssh session 4. password = password for the ssh session 5. hostkey_verify = enables hostkey verification from ~/.ssh/known_hosts,\ if not provided the default value is to look into the path ~/.ssh/known_hosts. 6. protocol_version = netconf protocol version (1.0 or 1.1) *** belows are not used, will be ignored. *** 7. timeout = use if you want to set timeout while connecting 8. allow_agent = enables querying SSH agent, if not provided the \ default value is to allow. 9. look_for_keys = enables looking in the usual locations for ssh keys, if value is not provided the default value is to look for keys. 10. unknown_host_cb = This would be used when the server host key is not recognized. 11. key_filename = where the private key can be found. 12. ssh_config = Enables parsing of OpenSSH configuration file. 13. device_params = netconf client device name, by default the name "default" is used. :Arguments: 1. system_name(string) = Name of the system from the input datafile. 2. session_name(string) = Name of the session to the system :Returns: 1. status(bool)= True / False 2. session_id (dict element)= key, value :DESCRIPTION: This Keyword is used to connect to the netconf interface of the system. The keyword upon executing saves the System_name and Session_id, which can be used by all subsequent keywords in the test to interact with the system through netconf interface. """ wdesc = "Connect to the netconf port of the system and creates a session" pSubStep(wdesc) output_dict = {} session_parameters = [ 'ip', 'nc_port', 'username', 'password', 'hostkey_verify', 'protocol_version' ] session_credentials = Utils.data_Utils.get_credentials( self.datafile, system_name, session_parameters) session_credentials["password"] = decrypt( session_credentials["password"]) pNote(system_name) pNote(Utils.file_Utils.getDateTime()) session_id = Utils.data_Utils.get_session_id(system_name, session_name) status = self.netconf_object.open(session_credentials) time.sleep(1) if status: temp = self.netconf_object.session_id if temp is None: status = False else: output_dict[ "netconf_session_id"] = self.netconf_object.session_id pNote("netconf session-id = %s" % self.netconf_object.session_id) output_dict[session_id] = self.netconf_object report_substep_status(status) if output_dict: return status, output_dict else: 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(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 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(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 create_jira_issue(self, server_url, username, password, issue_summary, issue_description, project_key, issue_type='Bug'): 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 = urllib2.HTTPPasswordMgrWithDefaultRealm() credential_handler.add_password(None, postdata_url, username, password) auth = urllib2.HTTPBasicAuthHandler(credential_handler) userpassword = username + ":" + password password = base64.b64encode(userpassword) #Create an Authentication handler opener = urllib2.build_opener(auth) urllib2.install_opener(opener) opener = urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)) #Create a POST request headers = { "Authorization": "Basic " + password, "Content-Type": "application/json" } request = urllib2.Request(str(postdata_url), postdata, headers) try: handler = urllib2.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
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_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(bool) = Indicate whether to notify the reservation owner when the reservation starts. 5. notify_on_end(bool) = 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) 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(bool) = Indicate whether to notify the reservation owner when the reservation starts. 5. notify_on_end(bool) = 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 = {} 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 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(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
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 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
def edit_config(self, datastore, config, system_name, session_name=None, default_operation=None, test_option=None, error_option=None): """ Loads all or part of the specified config(from file) to the datastore :Arguments: 1. datastore(string) = Name of datastore being edited 2. config(string) = The configuration. Must be rooted in the config element. May be a string or Element 3. system_name(string) = Name of the system from the input datafile 4. session_name(string) = Name of the session to the system 5. default_operation(string) = [merge | replace | none (default)] 6. test_option(string) = [test-then-set | set | test-only | none (default)] 7. error_option(string) = [stop-on-error | continue-on-error | rollback-on-error | none (default)] rollback-on-error depends on :rollback-on-error capability :Returns: 1. status(bool)= True / False 2. Edit Responses in the data repository {data:reply(xml)} """ wdesc = "Edit system configuration data" pSubStep(wdesc) pNote(system_name) pNote(self.datafile) reply_key = '{}_edit_config_reply'.format(system_name) reply_list = [] status = True self.clear_notification_buffer_all(system_name, session_name) session_id = Utils.data_Utils.get_session_id(system_name, session_name) netconf_object = Utils.data_Utils.get_object_from_datarepository( session_id) data_parameters = ['netconf_data'] config_datafile = Utils.data_Utils.get_filepath_from_system( self.datafile, system_name, 'netconf_data')[0] var_configfile = Utils.data_Utils.get_filepath_from_system( self.datafile, system_name, 'variable_config') if len(var_configfile) > 0: var_configfile = var_configfile[0] else: var_configfile = None if Utils.file_Utils.fileExists(config_datafile): status, config_data_list = Utils.data_Utils.get_nc_config_string( config_datafile, config, var_configfile) else: config_data_list = [] status = "error" if config_data_list: for config_data in config_data_list: if config_data: reply = netconf_object.edit_config( datastore, config_data, default_operation=default_operation, test_option=test_option, error_option=error_option) reply_list.append(reply) if netconf_object.isCOMPLD: status = status and True if status != "error" else status else: pNote( 'Edit Config Failed {}'.format( netconf_object.ErrorMessage), "error") status = status and False if status != "error" else status break else: reply = "error" pNote('Edit Config Failed', "error") status = status and False pNote('Edit Config Reply= {}'.format(reply_list)) report_substep_status(status) return status, {reply_key: reply_list}
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. 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
def waitfor_subscription(self, system_name, wait_string, namespace_string, namespace_prefix, timeout=600, session_name=None): """Wait for specified notification event :Arguments: 1. system_name(string) = Name of the system from the input datafile 2. waitString(string) = xpath string with namespace prefix e.g. for checking single data waitString = ".//ns:event[./ns:eventClass/text()='fault']" Note that "ns" = namespace prefix for checking multiple data waitString = ".//ns1:event1[text()='fault1'] and .//ns1:event2[text()='fault2']" 3. namespaceString(list of string) = list of namespace string separated by comma e.g., namespaceString = "namespace_value1,namespace_value2" 4. namespacePrefix(list of string) = list of namespace prefix separated by comma e.g., namespaceprefix = "ns1,ns2" 5. timeout(integer) = timeout value in second, default=600 6. session_name(string) = Name of the session to the system :Returns: 1. status(bool)= True / False E.g., Assuming the following notification is the one received: **************************** <?xml version="1.0" encoding="UTF-8"?> <notification xmlns="urn:ietf:params:xml:ns:netconf:notification:1.0"> <eventTime>2015-08-10T10:36:58.427756-07:00</eventTime> <netconf-config-change xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-notifications"> <changed-by> <username>admin</username> <session-id>0</session-id> <source-host>127.0.0.1</source-host> </changed-by> <datastore>running</datastore> <edit> <target xmlns:notif="http://tail-f.com/ns/test/notif">/notif:test</target> <operation>replace</operation> </edit> </netconf-config-change> </notification> **************************** for the notification received above, please find the appropriate argument and its values for checking username, source-host and target in this notification as follows: waitstring = ".//ns1:username[text()='admin'] and .//ns1:source-host[text()='127.0.0.1'] and .//ns2:target[text()='/notif:test']" namespaceString = "urn:ietf:params:xml:ns:netconf:notification:1.0, http://tail-f.com/ns/test/notif" namespacePrefix = "ns1,ns2" Caveat: This keyword does not validate XMLSchema for notification. """ wdesc = ("waitfor_subscription to wait specified netconf event " "notification") pSubStep(wdesc) pNote(system_name) pNote(self.datafile) session_id = Utils.data_Utils.get_session_id(system_name, session_name) netconf_object = Utils.data_Utils.get_object_from_datarepository( session_id) namespace_dict = {} prefixes = [prefix.strip() for prefix in namespace_prefix.split(",")] namespaces = [ns.strip() for ns in namespace_string.split(",")] if len(prefixes) != len(namespaces): pNote("the number of prefixes and namespaces should match", "error") pNote( "Number of prefixes ({}) != Number of namespaces({})".format( len(prefixes), len(namespaces)), "error") return False for (prefix, namespace) in zip(prefixes, namespaces): namespace_dict[prefix] = namespace temp_waitstring = (wait_string, namespace_dict) pNote("waiting for %s timeout=%s ..." % (wait_string, str(timeout))) status = netconf_object.waitfor_subscription(temp_waitstring, int(timeout)) if status: pNote("waitfor %s received" % wait_string) else: pNote("waitfor %s timeouted" % wait_string, "error") report_substep_status(status) return status
def cs_create_routes_in_reservation(self, system_name, reservation_name, list_of_source_resources, list_of_target_resources, override_active_routes, mapping_type, max_hops, route_alias, is_shared): """Creates routes between the listed source and target resources. Routes will be created for each pair of 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. list_of_source_resources(list) = The list of source resource names. 4. list_of_target_resources(list) = The list of target resource names. 5. override_active_routes(bool) = Specify whether the new route can override existing routes. 6. mapping_type(string) = Specify bi-directional or uni-directional as the mapping type 7. max_hops(integer) = The maximum number of allowed hops. 8. route_alias(string) = Specify the route alias 9. is_shared(bool) = Specify whether these routes are shared. :Returns: 1. status(bool) = True/False """ wdesc = "Create Routes In Reservation in CloudShell API Host" testcase_Utils.pSubStep(wdesc) testcase_Utils.pNote(file_Utils.getDateTime()) testcase_Utils.pNote("cs_create_routes_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.CreateRoutesInReservation(cs_res_id, list_of_source_resources, list_of_target_resources, 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 Routes In" " Reservation successfull for \"{}\"\n".\ format(reservation_name), "info") status = True else: testcase_Utils.pNote("\n\n *** Cloudshell Create Routes In" " Reservation failed for \"{}\"".\ format(reservation_name), "warning") except Exception as exception: print_exception(exception) testcase_Utils.report_substep_status(status) return status