Refactor SFC_FullDeploy tests to not use RSP RPCs
[integration/test.git] / csit / libraries / Utils.robot
1 *** Settings ***
2 Documentation     General Utils library. This library has broad scope, it can be used by any robot system tests.
3 Library           SSHLibrary
4 Library           HttpLibrary.HTTP
5 Library           String
6 Library           DateTime
7 Library           Process
8 Library           Collections
9 Library           RequestsLibrary
10 Library           OperatingSystem
11 Library           ${CURDIR}/UtilLibrary.py
12 Resource          ${CURDIR}/SSHKeywords.robot
13 Resource          ${CURDIR}/TemplatedRequests.robot
14 Resource          ${CURDIR}/../variables/Variables.robot
15
16 *** Variables ***
17 # TODO: Introduce ${tree_size} and use instead of 1 in the next line.
18 ${start}          sudo mn --controller=remote,ip=${ODL_SYSTEM_IP} --topo tree,1 --switch ovsk,protocols=OpenFlow13
19
20 *** Keywords ***
21 Start Mininet
22     [Arguments]    ${system}=${TOOLS_SYSTEM_IP}    ${user}=${TOOLS_SYSTEM_USER}    ${password}=${TOOLS_SYSTEM_PASSWORD}    ${prompt}=${DEFAULT_LINUX_PROMPT}    ${timeout}=30s
23     [Documentation]    Basic setup/cleanup work that can be done safely before any system
24     ...    is run.
25     Log    Start the test on the base edition
26     Clean Mininet System
27     ${mininet_conn_id}=    Open Connection    ${system}    prompt=${prompt}    timeout=${timeout}
28     Set Suite Variable    ${mininet_conn_id}
29     SSHKeywords.Flexible Mininet Login    user=${user}    password=${password}
30     Execute Command    sudo ovs-vsctl set-manager ptcp:6644
31     Write    ${start}
32     Read Until    mininet>
33
34 Stop Mininet
35     [Arguments]    ${prompt}=${DEFAULT_LINUX_PROMPT}
36     [Documentation]    Cleanup/Shutdown work that should be done at the completion of all
37     ...    tests
38     Log    Stop the test on the base edition
39     Switch Connection    ${mininet_conn_id}
40     Read
41     Write    exit
42     Read Until    ${prompt}
43     Close Connection
44
45 Report_Failure_Due_To_Bug
46     [Arguments]    ${number}    ${include_bug_in_tags}=True
47     [Documentation]    Report that a test failed due to a known Bugzilla bug whose
48     ...    number is provided as an argument.
49     ...    Not FAILED (incl. SKIPPED) test are not reported.
50     ...    This keyword must be used in the [Teardown] setting of the affected test
51     ...    or as the first line of the test if FastFail module is not being
52     ...    used. It reports the URL of the bug on console and also puts it
53     ...    into the Robot log file.
54     ${test_skipped}=    BuiltIn.Evaluate    len(re.findall('SKIPPED', """${TEST_MESSAGE}""")) > 0    modules=re
55     BuiltIn.Return From Keyword If    ('${TEST_STATUS}' != 'FAIL') or ${test_skipped}
56     ${bug_url}=    BuiltIn.Set_Variable    https://bugs.opendaylight.org/show_bug.cgi?id=${number}
57     ${msg}=    BuiltIn.Set_Variable    This test fails due to ${bug_url}
58     ${newline}=    BuiltIn.Evaluate    chr(10)
59     BuiltIn.Set Test Message    ${msg}${newline}${newline}${TEST_MESSAGE}
60     BuiltIn.Log    ${msg}
61     BuiltIn.Run_Keyword_If    "${include_bug_in_tags}"=="True"    Set Tags    ${bug_url}
62
63 Report_Failure_And_Point_To_Linked_Bugs
64     [Documentation]    Report that a test failed and point to linked Bugzilla bug(s).
65     ...    Linked bugs must contain the ${reference} inside comments (workaround
66     ...    becasue of currently missing suitable field for external references and
67     ...    not correctly working the CONTENT MATCHES filter).
68     ...    Not FAILED (incl. SKIPPED) test are not reported.
69     ...    This keyword must be used in the [Teardown] setting of the affected test
70     ...    or as the first line of the test if FastFail module is not being
71     ...    used. It reports the URL of the bug on console and also puts it
72     ...    into the Robot log file.
73     ${test_skipped}=    BuiltIn.Evaluate    len(re.findall('SKIPPED', """${TEST_MESSAGE}""")) > 0    modules=re
74     BuiltIn.Return From Keyword If    ('${TEST_STATUS}' != 'FAIL') or ${test_skipped}
75     ${newline}=    BuiltIn.Evaluate    chr(10)
76     ${reference}=    String.Replace_String_Using_Regexp    ${SUITE_NAME}_${TEST_NAME}    [ /\.-]    _
77     ${reference}=    String.Convert_To_Lowercase    ${reference}
78     ${msg}=    BuiltIn.Set_Variable    ... click for list of related bugs or create a new one if needed (with the${newline}"${reference}"${newline}reference somewhere inside)
79     ${bugs}=    BuiltIn.Set_Variable    "https://bugs.opendaylight.org/buglist.cgi?f1=cf_external_ref&o1=substring&v1=${reference}&order=bug_status"
80     BuiltIn.Set Test Message    ${msg}${newline}${bugs}${newline}${newline}${TEST_MESSAGE}
81     BuiltIn.Log    ${msg}${newline}${bugs}
82
83 Check Nodes Stats
84     [Arguments]    ${node}    ${session}=session
85     [Documentation]    A GET on the /node/${node} API is made and specific flow stat
86     ...    strings are checked for existence.
87     ${resp}    RequestsLibrary.Get Request    ${session}    ${OPERATIONAL_NODES_API}/node/${node}
88     Should Be Equal As Strings    ${resp.status_code}    200
89     Should Contain    ${resp.content}    flow-capable-node-connector-statistics
90     Should Contain    ${resp.content}    flow-table-statistics
91
92 Check For Specific Number Of Elements At URI
93     [Arguments]    ${uri}    ${element}    ${expected_count}    ${session}=session
94     [Documentation]    A GET is made to the specified ${URI} and the specific count of a
95     ...    given element is done (as supplied by ${element} and ${expected_count})
96     ${resp}    RequestsLibrary.Get Request    ${session}    ${uri}
97     Log    ${resp.content}
98     Should Be Equal As Strings    ${resp.status_code}    200
99     Should Contain X Times    ${resp.content}    ${element}    ${expected_count}
100
101 Log Content
102     [Arguments]    ${resp_content}
103     ${resp_json} =    BuiltIn.Run Keyword If    '''${resp_content}''' != '${EMPTY}'    RequestsLibrary.To Json    ${resp_content}    pretty_print=True
104     ...    ELSE    BuiltIn.Set Variable    ${EMPTY}
105     BuiltIn.Log    ${resp_json}
106     [Return]    ${resp_json}
107
108 Check For Elements At URI
109     [Arguments]    ${uri}    ${elements}    ${session}=session    ${pretty_print_json}=False
110     [Documentation]    A GET is made at the supplied ${URI} and every item in the list of
111     ...    ${elements} is verified to exist in the response
112     ${resp}    RequestsLibrary.Get Request    ${session}    ${uri}
113     BuiltIn.Run Keyword If    "${pretty_print_json}" == "True"    Log Content    ${resp.content}
114     ...    ELSE    BuiltIn.Log    ${resp.content}
115     Should Be Equal As Strings    ${resp.status_code}    200
116     : FOR    ${i}    IN    @{elements}
117     \    Should Contain    ${resp.content}    ${i}
118
119 Check For Elements Not At URI
120     [Arguments]    ${uri}    ${elements}    ${session}=session    ${pretty_print_json}=False
121     [Documentation]    A GET is made at the supplied ${URI} and every item in the list of
122     ...    ${elements} is verified to NOT exist in the response
123     ${resp}    RequestsLibrary.Get Request    ${session}    ${uri}
124     BuiltIn.Run Keyword If    "${pretty_print_json}" == "True"    Log Content    ${resp.content}
125     ...    ELSE    BuiltIn.Log    ${resp.content}
126     Should Be Equal As Strings    ${resp.status_code}    200
127     : FOR    ${i}    IN    @{elements}
128     \    Should Not Contain    ${resp.content}    ${i}
129
130 Clean Mininet System
131     [Arguments]    ${system}=${TOOLS_SYSTEM_IP}
132     Run Command On Mininet    ${system}    sudo mn -c
133     Run Command On Mininet    ${system}    sudo ps -elf | egrep 'usr/local/bin/mn' | egrep python | awk '{print "sudo kill -9",$4}' | sh
134
135 Clean Up Ovs
136     [Arguments]    ${system}=${TOOLS_SYSTEM_IP}
137     [Documentation]    Cleans up the OVS instance and remove any existing common known bridges.
138     ${output}=    Run Command On Mininet    ${system}    sudo ovs-vsctl list-br
139     Log    ${output}
140     : FOR    ${i}    IN    ${output}
141     \    Run Command On Mininet    ${system}    sudo ovs-vsctl --if-exists del-br ${i}
142     Run Command On Mininet    ${system}    sudo ovs-vsctl del-manager
143
144 Extract Value From Content
145     [Arguments]    ${content}    ${index}    ${strip}=nostrip
146     [Documentation]    Will take the given response content and return the value at the given index as a string
147     ${value}=    Get Json Value    ${content}    ${index}
148     ${value}=    Convert To String    ${value}
149     ${value}=    Run Keyword If    '${strip}' == 'strip'    Strip Quotes    ${value}
150     [Return]    ${value}
151
152 Get Process ID Based On Regex On Remote System
153     [Arguments]    ${system}    ${regex_string_to_match_on}    ${user}=${TOOLS_SYSTEM_USER}    ${password}=${EMPTY}    ${prompt}=${DEFAULT_LINUX_PROMPT}    ${prompt_timeout}=30s
154     [Documentation]    Uses ps to find a process that matches the supplied regex. Returns the PID of that process
155     ...    The ${regex_string_to_match_on} should produce a unique process otherwise the PID returned may not be
156     ...    the expected PID
157     # doing the extra -v grep in this command to exclude the grep process itself from the output
158     ${cmd}=    Set Variable    ps -elf | grep -v grep | grep ${regex_string_to_match_on} | awk '{print $4}'
159     ${output}=    Run Command On Remote System    ${system}    ${cmd}    user=${user}    password=${password}    prompt=${prompt}
160     ...    prompt_timeout=${prompt_timeout}
161     # ${output} contains the system prompt and all we want is the value of the number
162     ${pid}=    Fetch From Left    ${output}    \r
163     # TODO: Get Process * keywords have perhaps non-standard default credentials.
164     # ...    Should there be * On Mininet and * On Controller specializations?
165     [Return]    ${pid}
166
167 Get Process Thread Count On Remote System
168     [Arguments]    ${system}    ${pid}    ${user}=${TOOLS_SYSTEM_USER}    ${password}=${EMPTY}    ${prompt}=${DEFAULT_LINUX_PROMPT}    ${prompt_timeout}=30s
169     [Documentation]    Executes the ps command to retrieve the lightweight process (aka thread) count.
170     ${cmd}=    Set Variable    ps --no-headers -o nlwp ${pid}
171     ${output}=    Run Command On Remote System    ${system}    ${cmd}    user=${user}    password=${password}    prompt=${prompt}
172     ...    prompt_timeout=${prompt_timeout}
173     # ${output} contains the system prompt and all we want is the value of the number
174     ${thread_count}=    Fetch From Left    ${output}    \r
175     [Return]    ${thread_count}
176
177 Strip Quotes
178     [Arguments]    ${string_to_strip}
179     [Documentation]    Will strip ALL quotes from given string and return the new string
180     ${string_to_return}=    Replace String    ${string_to_strip}    "    \    count=-1
181     [Return]    ${string_to_return}
182
183 Run Command On Remote System
184     [Arguments]    ${system}    ${cmd}    ${user}=${DEFAULT_USER}    ${password}=${EMPTY}    ${prompt}=${DEFAULT_LINUX_PROMPT}    ${prompt_timeout}=${DEFAULT_TIMEOUT}
185     ...    ${return_stdout}=True    ${return_stderr}=False
186     [Documentation]    Reduces the common work of running a command on a remote system to a single higher level
187     ...    robot keyword, taking care to log in with a public key and. The command given is written and the return value
188     ...    depends on the passed argument values of return_stdout (default: True) and return_stderr (default: False).
189     ...    At least one should be True, or the keyword will exit and FAIL. If both are True, the resulting return value
190     ...    will be a two element list containing both. Otherwise the resulting return value is a string.
191     ...    No test conditions are checked.
192     Run Keyword If    "${return_stdout}"!="True" and "${return_stderr}"!="True"    Fail    At least one of {return_stdout} or {return_stderr} args should be set to True
193     ${current_ssh_connection}=    SSHLibrary.Get Connection
194     BuiltIn.Log    Attempting to execute command "${cmd}" on remote system "${system}" by user "${user}" with keyfile pass "${keyfile_pass}" and prompt "${prompt}" and password "${password}"
195     ${conn_id}=    SSHLibrary.Open Connection    ${system}    prompt=${prompt}    timeout=${prompt_timeout}
196     SSHKeywords.Flexible SSH Login    ${user}    ${password}
197     ${stdout}    ${stderr}    SSHLibrary.Execute Command    ${cmd}    return_stderr=True
198     SSHLibrary.Close Connection
199     Log    ${stderr}
200     Run Keyword If    "${return_stdout}"!="True"    Return From Keyword    ${stderr}
201     Run Keyword If    "${return_stderr}"!="True"    Return From Keyword    ${stdout}
202     [Teardown]    SSHKeywords.Restore_Current_SSH_Connection_From_Index    ${current_ssh_connection.index}
203     [Return]    ${stdout}    ${stderr}
204
205 Run Command On Remote System And Log
206     [Arguments]    ${system}    ${cmd}    ${user}=${DEFAULT_USER}    ${password}=${EMPTY}    ${prompt}=${DEFAULT_LINUX_PROMPT}    ${prompt_timeout}=${DEFAULT_TIMEOUT}
207     [Documentation]    Reduces the common work of running a command on a remote system to a single higher level
208     ...    robot keyword, taking care to log in with a public key and. The command given is written
209     ...    and the output returned. No test conditions are checked.
210     ${output} =    Run Command On Remote System    ${system}    ${cmd}    ${user}    ${password}    ${prompt}
211     ...    ${prompt_timeout}
212     Log    ${output}
213     [Return]    ${output}
214
215 Run Command On Mininet
216     [Arguments]    ${system}=${TOOLS_SYSTEM_IP}    ${cmd}=echo    ${user}=${TOOLS_SYSTEM_USER}    ${password}=${TOOLS_SYSTEM_PASSWORD}    ${prompt}=${TOOLS_SYSTEM_PROMPT}
217     [Documentation]    Call Run Comand On Remote System, but with default values suitable for Mininet machine.
218     BuiltIn.Run Keyword And Return    Run Command On Remote System    ${system}    ${cmd}    ${user}    ${password}    prompt=${prompt}
219
220 Run Command On Controller
221     [Arguments]    ${system}=${ODL_SYSTEM_IP}    ${cmd}=echo    ${user}=${ODL_SYSTEM_USER}    ${password}=${ODL_SYSTEM_PASSWORD}    ${prompt}=${ODL_SYSTEM_PROMPT}
222     [Documentation]    Call Run Comand On Remote System, but with default values suitable for Controller machine.
223     BuiltIn.Run Keyword And Return    Run Command On Remote System    ${system}    ${cmd}    ${user}    ${password}    prompt=${prompt}
224
225 Run Command On Existing Connection
226     [Arguments]    ${conn_id}=${EMPTY}    ${cmd}=echo    ${return_stdout}=True    ${return_stderr}=False
227     [Documentation]    Switch to and run command on an already existing SSH connection and switch back
228     Run Keyword If    "${return_stdout}"!="True" and "${return_stderr}"!="True"    Fail    At least one of {return_stdout} or {return_stderr} args should be set to True
229     ${current_ssh_connection}=    SSHLibrary.Get Connection
230     BuiltIn.Log    Attempting to execute command "${cmd}" on existing connection "${conn_id}
231     SSHLibrary.Switch Connection    ${conn_id}
232     ${stdout}    ${stderr}    SSHLibrary.Execute Command    ${cmd}    return_stderr=True
233     Log    ${stderr}
234     Run Keyword If    "${return_stdout}"!="True"    Return From Keyword    ${stderr}
235     Run Keyword If    "${return_stderr}"!="True"    Return From Keyword    ${stdout}
236     [Teardown]    SSHKeywords.Restore_Current_SSH_Connection_From_Index    ${current_ssh_connection.index}
237     [Return]    ${stdout}    ${stderr}
238
239 Verify File Exists On Remote System
240     [Arguments]    ${system}    ${file}    ${user}=${TOOLS_SYSTEM_USER}    ${password}=${TOOLS_SYSTEM_PASSWORD}    ${prompt}=${DEFAULT_LINUX_PROMPT}    ${prompt_timeout}=5s
241     [Documentation]    Will create connection with public key and will PASS if the given ${file} exists,
242     ...    otherwise will FAIL
243     ${conn_id}=    Open Connection    ${system}    prompt=${prompt}    timeout=${prompt_timeout}
244     SSHKeywords.Flexible SSH Login    ${user}    ${password}
245     SSHLibrary.File Should Exist    ${file}
246     Close Connection
247
248 Check Karaf Log File Does Not Have Messages
249     [Arguments]    ${ip}    ${message}    ${user}=${ODL_SYSTEM_USER}    ${password}=${ODL_SYSTEM_PASSWORD}    ${prompt}=${ODL_SYSTEM_PROMPT}    ${log_file}=${WORKSPACE}/${BUNDLEFOLDER}/data/log/karaf.log
250     [Documentation]    Fails if the provided ${message} is found in the karaf.log file. Uses grep to search. The
251     ...    karaf.log file can be overridden with ${log_file} to be any file on the given system @ ${ip}
252     ${output}=    Run Command On Controller    ${ip}    grep -c '${message}' ${log_file}    user=${user}    password=${password}    prompt=${prompt}
253     Should Be Equal As Strings    ${output}    0
254
255 Verify Controller Is Not Dead
256     [Arguments]    ${controller_ip}=${ODL_SYSTEM_IP}
257     [Documentation]    Will execute any tests to verify the controller is not dead. Some checks are
258     ...    Out Of Memory Execptions.
259     Check Karaf Log File Does Not Have Messages    ${controller_ip}    java.lang.OutOfMemoryError
260     # TODO: Should Verify Controller * keywords also accept user, password, prompt and karaf_log arguments?
261
262 Verify Controller Has No Null Pointer Exceptions
263     [Arguments]    ${controller_ip}=${ODL_SYSTEM_IP}
264     [Documentation]    Will execute any tests to verify the controller is not having any null pointer eceptions.
265     Check Karaf Log File Does Not Have Messages    ${controller_ip}    java.lang.NullPointerException
266
267 Get Epoch Time
268     [Arguments]    ${time}
269     [Documentation]    Get the Epoc time from MM/DD/YYYY HH:MM:SS
270     ${epoch_time}=    Convert Date    ${time}    epoch    exclude_milles=True    date_format=%m/%d/%Y %H:%M:%S
271     ${epoch_time}=    Convert To Integer    ${epoch_time}
272     [Return]    ${epoch_time}
273
274 Remove Space on String
275     [Arguments]    ${str}    ${count}=-1
276     [Documentation]    Remove the empty space from given string.count is optional,if its given
277     ...    that many occurence of space will be removed from left
278     ${x}=    Convert To String    ${str}
279     ${x}=    Replace String    ${str}    ${SPACE}    ${EMPTY}    count=${count}
280     [Return]    ${x}
281
282 Split Value from String
283     [Arguments]    ${str}    ${splitter}
284     [Documentation]    Split the String based on given splitter and return as list
285     @{x}=    Split String    ${str}    ${splitter}
286     [Return]    @{x}
287
288 Concatenate the String
289     [Arguments]    ${str1}    ${str2}
290     [Documentation]    Catenate the two non-string objects and return as String
291     ${str1}=    Convert to String    ${str1}
292     ${str2}=    Convert to String    ${str2}
293     ${output}=    Catenate    ${str1}    ${str2}
294     [Return]    ${output}
295
296 Post Elements To URI
297     [Arguments]    ${rest_uri}    ${data}    ${headers}=${headers}    ${session}=session
298     [Documentation]    Perform a POST rest operation, using the URL and data provided
299     ${resp} =    RequestsLibrary.Post Request    ${session}    ${rest_uri}    data=${data}    headers=${headers}
300     Log    ${resp.content}
301     Should Contain    ${ALLOWED_STATUS_CODES}    ${resp.status_code}
302
303 Remove All Elements At URI
304     [Arguments]    ${uri}    ${session}=session
305     ${resp}    RequestsLibrary.Delete Request    ${session}    ${uri}
306     Should Contain    ${ALLOWED_STATUS_CODES}    ${resp.status_code}
307
308 Remove All Elements At URI And Verify
309     [Arguments]    ${uri}    ${session}=session
310     ${resp}    RequestsLibrary.Delete Request    ${session}    ${uri}
311     Should Contain    ${ALLOWED_STATUS_CODES}    ${resp.status_code}
312     ${resp}    RequestsLibrary.Get Request    ${session}    ${uri}
313     Should Be Equal As Strings    ${resp.status_code}    404
314
315 Remove All Elements If Exist
316     [Arguments]    ${uri}    ${session}=session
317     [Documentation]    Delete all elements from an URI if the configuration was not empty
318     ${resp}    RequestsLibrary.Get Request    ${session}    ${uri}
319     Run Keyword If    '${resp.status_code}'!='404'    Remove All Elements At URI    ${uri}    ${session}
320
321 Add Elements To URI From File
322     [Arguments]    ${dest_uri}    ${data_file}    ${headers}=${headers}    ${session}=session
323     [Documentation]    Put data from a file to a URI
324     ${body}    OperatingSystem.Get File    ${data_file}
325     ${resp}    RequestsLibrary.Put Request    ${session}    ${dest_uri}    data=${body}    headers=${headers}
326     Should Contain    ${ALLOWED_STATUS_CODES}    ${resp.status_code}
327
328 Add Elements To URI From File And Verify
329     [Arguments]    ${dest_uri}    ${data_file}    ${headers}=${headers}    ${session}=session
330     [Documentation]    Put data from a file to a URI and verify the HTTP response
331     ${body}    OperatingSystem.Get File    ${data_file}
332     Add Elements to URI And Verify    ${dest_uri}    ${body}    ${headers}    ${session}
333
334 Add Elements To URI And Verify
335     [Arguments]    ${dest_uri}    ${data}    ${headers}=${headers}    ${session}=session
336     [Documentation]    Put data to a URI and verify the HTTP response
337     ${resp}    RequestsLibrary.Put Request    ${session}    ${dest_uri}    ${data}    headers=${headers}
338     Should Contain    ${ALLOWED_STATUS_CODES}    ${resp.status_code}
339     ${resp}    RequestsLibrary.Get Request    ${session}    ${dest_uri}
340     Should Not Be Equal    ${resp.status_code}    404
341
342 Add Elements To URI From File And Check Validation Error
343     [Arguments]    ${dest_uri}    ${data_file}    ${headers}=${headers}    ${session}=session
344     [Documentation]    Shorthand for PUTting data from file and expecting status code 400.
345     BuiltIn.Comment    TODO: Does this have any benefits, considering TemplatedRequests can also do this in one line?
346     ${body}    OperatingSystem.Get File    ${data_file}
347     ${resp}    RequestsLibrary.Put Request    ${session}    ${dest_uri}    data=${body}    headers=${headers}
348     Should Contain    ${DATA_VALIDATION_ERROR}    ${resp.status_code}
349
350 Add Elements To URI From File And Check Server Error
351     [Arguments]    ${dest_uri}    ${data_file}    ${headers}=${headers}    ${session}=session
352     [Documentation]    Shorthand for PUTting data from file and expecting status code 500.
353     ...    Consider opening a Bug against ODL, as in most test cases, 400 is the http code to expect.
354     BuiltIn.Comment    TODO: Does this have any benefits, considering TemplatedRequests can also do this in one line?
355     ${body}    OperatingSystem.Get File    ${data_file}
356     ${resp}    RequestsLibrary.Put Request    ${session}    ${dest_uri}    data=${body}    headers=${headers}
357     Should Contain    ${INTERNAL_SERVER_ERROR}    ${resp.status_code}
358
359 Post Elements To URI From File
360     [Arguments]    ${dest_uri}    ${data_file}    ${headers}=${headers}    ${session}=session
361     ${body}    OperatingSystem.Get File    ${data_file}
362     ${resp}    RequestsLibrary.Post Request    ${session}    ${dest_uri}    data=${body}    headers=${headers}
363     Should Contain    ${ALLOWED_STATUS_CODES}    ${resp.status_code}
364
365 Run Process With Logging And Status Check
366     [Arguments]    @{proc_args}
367     [Documentation]    Execute an OS command, log STDOUT and STDERR output and check exit code to be 0
368     ${result}=    Run Process    @{proc_args}
369     Log    ${result.stdout}
370     Log    ${result.stderr}
371     Should Be Equal As Integers    ${result.rc}    0
372     [Return]    ${result}
373
374 Get Data From URI
375     [Arguments]    ${session}    ${uri}    ${headers}=${NONE}
376     [Documentation]    Issue a GET request and return the data obtained or on error log the error and fail.
377     ...    Issues a GET request for ${uri} in ${session} using headers from
378     ...    ${headers}. If the request returns a HTTP error, fails. Otherwise
379     ...    returns the data obtained by the request.
380     ${response}=    RequestsLibrary.Get Request    ${session}    ${uri}    ${headers}
381     Builtin.Return_From_Keyword_If    ${response.status_code} == 200    ${response.text}
382     Builtin.Log    ${response.text}
383     Builtin.Fail    The request failed with code ${response.status_code}
384
385 Get URI And Verify
386     [Arguments]    ${uri}    ${session}=session    ${headers}=${NONE}
387     [Documentation]    Issue a GET request and verify a successfull HTTP return.
388     ...    Issues a GET request for ${uri} in ${session} using headers from ${headers}.
389     ${response} =    RequestsLibrary.Get Request    ${session}    ${uri}    ${headers}
390     Builtin.Log    ${response.status_code}
391     Should Contain    ${ALLOWED_STATUS_CODES}    ${response.status_code}
392
393 No Content From URI
394     [Arguments]    ${session}    ${uri}    ${headers}=${NONE}
395     [Documentation]    Issue a GET request and return on error 404 (No content) or will fail and log the content.
396     ...    Issues a GET request for ${uri} in ${session} using headers from
397     ...    ${headers}. If the request returns a HTTP error, fails. Otherwise
398     ...    returns the data obtained by the request.
399     ${response}=    RequestsLibrary.Get Request    ${session}    ${uri}    ${headers}
400     Builtin.Return_From_Keyword_If    ${response.status_code} == 404
401     Builtin.Log    ${response.text}
402     Builtin.Fail    The request failed with code ${response.status_code}
403
404 Get Index From List Of Dictionaries
405     [Arguments]    ${dictionary_list}    ${key}    ${value}
406     [Documentation]    Extract index for the dictionary in a list that contains a key-value pair. Returns -1 if key-value is not found.
407     ${length}=    Get Length    ${dictionary_list}
408     ${index}=    Set Variable    -1
409     : FOR    ${i}    IN RANGE    ${length}
410     \    ${dictionary}=    Get From List    ${dictionary_list}    ${i}
411     \    Run Keyword If    """&{dictionary}[${key}]""" == """${value}"""    Set Test Variable    ${index}    ${i}
412     [Return]    ${index}
413
414 Check Item Occurrence
415     [Arguments]    ${string}    ${dictionary_item_occurrence}
416     [Documentation]    Check string for occurrences of items expressed in a list of dictionaries {item=occurrences}. 0 occurences means item is not present.
417     : FOR    ${item}    IN    @{dictionary_item_occurrence}
418     \    Should Contain X Times    ${string}    ${item}    &{dictionary_item_occurrence}[${item}]
419
420 Post Log Check
421     [Arguments]    ${uri}    ${body}    ${status_code}=200    ${session}=session
422     [Documentation]    Post body to ${uri}, log response content, and check status
423     ${resp}=    RequestsLibrary.Post Request    ${session}    ${uri}    ${body}
424     Log    ${resp.content}
425     Should Be Equal As Strings    ${resp.status_code}    ${status_code}
426     [Return]    ${resp}
427
428 Get Log File Name
429     [Arguments]    ${testtool}    ${testcase}=${EMPTY}
430     [Documentation]    Get the name of the suite sanitized to be usable as a part of filename.
431     ...    These names are used to constructs names of the log files produced
432     ...    by the testing tools so two suites using a tool wont overwrite the
433     ...    log files if they happen to run in one job.
434     ${name}=    BuiltIn.Evaluate    """${SUITE_NAME}""".replace(" ","-").replace("/","-").replace(".","-")
435     ${suffix}=    BuiltIn.Set_Variable_If    '${testcase}' != ''    --${testcase}    ${EMPTY}
436     ${date} =    DateTime.Get Current Date
437     ${timestamp} =    DateTime.Convert Date    ${date}    epoch
438     [Return]    ${testtool}--${name}${suffix}.${timestamp}.log
439
440 Set_User_Configurable_Variable_Default
441     [Arguments]    ${name}    ${value}
442     [Documentation]    Set a default value for an user configurable variable.
443     ...    This keyword is needed if your default value is calculated using
444     ...    a complex expression which needs BuiltIn.Evaluate or even more
445     ...    complex keywords. It sets the variable ${name} (the name of the
446     ...    variable MUST be specified WITHOUT the ${} syntactic sugar due
447     ...    to limitations of Robot Framework) to ${value} but only if the
448     ...    variable ${name} was not set previously. This keyword is intended
449     ...    for user configurable variables which are supposed to be set only
450     ...    with pybot -v; calling this keyword on a variable that was already
451     ...    set by another keyword will silently turn the call into a NOP and
452     ...    thus is a bug in the suite or resource trying to call this
453     ...    keyword.
454     # TODO: Figure out how to make the ${value} evaluation "lazy" (meaning
455     #    evaluating it only when the user did not set anything and thus the
456     #    default is needed). This might be needed to avoid potentially costly
457     #    keyword invocations when they are not needed. Currently no need for
458     #    this was identified, thus leaving it here as a TODO. Based on
459     #    comments the best approach would be to create another keyword that
460     #    expects a ScalarClosure in the place of ${value} and calls the
461     #    closure to get the value but only if the value is needed).
462     #    The best idea how to implement this "laziness" would be to have the
463     #    used to define another keyword that will be responsible for getting
464     #    the default value and then passing the name of this getter keyword
465     #    to this keyword. Then this keyword would call the getter (to obtain
466     #    the expensive default value) only if it discovers that this value
467     #    is really needed (because the variable is not set yet).
468     # TODO: Is the above TODO really necessary? Right now we don't have any
469     #    examples of "expensive default values" where to obtain the default
470     #    value is so expensive on resources (e.g. need to SSH somewhere to
471     #    check something) that we would want to skip the calculation if the
472     #    variable for which it is needed has a value already provided by the
473     #    user using "pybot -v" or something. One example would be
474     #    JAVA_HOME if it would be designed as user-configurable variable
475     #    (currently it is not; users can specify "use jdk7" or "use jdk8"
476     #    but not "use the jdk over there"; and there actually is no JAVA_HOME
477     #    present in the resource, rather the Java invocation command uses the
478     #    Java invocation with a full path). The default value of JAVA_HOME
479     #    has to be obtained by issuing commands on the SSH connection where
480     #    the resulting Java invocation command will be used (to check
481     #    multiple candidate paths until one that fits is found) and we could
482     #    skip all this checking if a JAVA_HOME was supplied by the user using
483     #    "pybot -v".
484     ${value}=    BuiltIn.Get_Variable_Value    \${${name}}    ${value}
485     BuiltIn.Set_Suite_Variable    \${${name}}    ${value}
486
487 Convert_To_Minutes
488     [Arguments]    ${time}
489     [Documentation]    Convert a Robot time string to an integer expressing the time in minutes, rounded up
490     ...    This is a wrapper around DateTime.Convert_Time which does not
491     ...    provide this functionality directly nor is even able to produce
492     ...    an integer directly. It is needed for RestPerfClient which
493     ...    cannot accept floats for its --timeout parameter and interprets
494     ...    the value supplied in this parameter in minutes.
495     ${seconds}=    DateTime.Convert_Time    ${time}    result_format=number
496     ${minutes}=    BuiltIn.Evaluate    int(math.ceil(${seconds}/60.0))    modules=math
497     [Return]    ${minutes}
498
499 Write Commands Until Expected Prompt
500     [Arguments]    ${cmd}    ${prompt}    ${timeout}=30s
501     [Documentation]    quick wrapper for Write and Read Until Prompt Keywords to make test cases more readable
502     SSHLibrary.Set Client Configuration    timeout=${timeout}
503     SSHLibrary.Read
504     SSHLibrary.Write    ${cmd}
505     ${output}=    SSHLibrary.Read Until    ${prompt}
506     [Return]    ${output}
507
508 Install Package On Ubuntu System
509     [Arguments]    ${package_name}    ${system}=${TOOLS_SYSTEM_IP}    ${user}=${TOOLS_SYSTEM_USER}    ${password}=${TOOLS_SYSTEM_PASSWORD}    ${prompt}=${DEFAULT_LINUX_PROMPT}    ${prompt_timeout}=30s
510     [Documentation]    Keyword to install packages for testing to Ubuntu Mininet VM
511     Log    Keyword to install package to Mininet Ubuntu VM
512     Open Connection    ${system}    prompt=${prompt}    timeout=${prompt_timeout}
513     SSHKeywords.Flexible Mininet Login    user=${user}    password=${password}
514     Write    sudo apt-get install -y ${package_name}
515     Read Until    ${prompt}
516
517 Json Parse From String
518     [Arguments]    ${plain_string_with_json}
519     [Documentation]    Parse given plain string into json (dictionary)
520     ${json_data}    Evaluate    json.loads('''${plain_string_with_json}''')    json
521     [Return]    ${json_data}
522
523 Json Parse From File
524     [Arguments]    ${json_file}
525     [Documentation]    Parse given file content into json (dictionary)
526     ${json_plain_string}    OperatingSystem.Get file    ${json_file}
527     ${json_data}    Json Parse From String    ${json_plain_string}
528     [Return]    ${json_data}
529
530 Modify Iptables On Remote System
531     [Arguments]    ${remote_system_ip}    ${iptables_rule}    ${user}=${ODL_SYSTEM_USER}    ${password}=${ODL_SYSTEM_PASSWORD}    ${prompt}=${ODL_SYSTEM_PROMPT}
532     [Documentation]    Wrapper keyword to run iptables with any given ${iptables_rule} string on the remote system given
533     ...    by ${remote_system_ip}. The iptables listing will be output before and after the command is run
534     ${list_iptables_command} =    BuiltIn.Set Variable    sudo /sbin/iptables -L -n
535     ${output} =    Utils.Run Command On Remote System    ${remote_system_ip}    ${list_iptables_command}    ${user}    ${password}    prompt=${prompt}
536     BuiltIn.Log    ${output}
537     Utils.Run Command On Remote System    ${remote_system_ip}    sudo /sbin/iptables ${iptables_rule}    ${user}    ${password}    prompt=${prompt}
538     ${output} =    Utils.Run Command On Remote System    ${remote_system_ip}    ${list_iptables_command}    ${user}    ${password}    prompt=${prompt}
539     BuiltIn.Log    ${output}
540
541 Get_Sysstat_Statistics
542     [Arguments]    ${ip_address}=${ODL_SYSTEM_IP}
543     [Documentation]    Store current connection index, open new connection to ip_address. Run command to get sysstat results from script,
544     ...    which is running on all children nodes. Returns cpu, network, memory usage statistics from the node for each 10 minutes
545     ...    that node was running. Used for debug purposes. Returns whole output of sysstat.
546     ${current_connection}=    SSHLibrary.Get_Connection
547     SSHKeywords.Open_Connection_To_ODL_System    ${ip_address}
548     SSHLibrary.Write    sar -A -f /var/log/sa/sa*
549     ${output}    SSHLibrary.Read_Until_Prompt
550     BuiltIn.Log    ${output}
551     SSHLibrary.Close_Connection
552     [Teardown]    SSHKeywords.Restore_Current_SSH_Connection_From_Index    ${current_connection.index}
553     [Return]    ${output}
554
555 Check Diagstatus
556     [Arguments]    ${ip_address}=${ODL_SYSTEM_IP}    ${check_status}=True    ${expected_status}=${200}
557     [Documentation]    GET http://${ip_address}:${RESTCONFPORT}/diagstatus and return the response. ${check_status}
558     ...    and ${expected_status_code} can be used to ignore the status code, or validate any status code value.
559     ...    By default, this keyword will pass if the status code returned is 200, and fail otherwise.
560     RequestsLibrary.Create Session    diagstatus_session    http://${ip_address}:${RESTCONFPORT}
561     ${resp}    RequestsLibrary.Get Request    diagstatus_session    /diagstatus
562     Run Keyword If    "${check_status}" == "True"    BuiltIn.Should Be Equal As Strings    ${resp.status_code}    ${expected_status}
563     [Return]    ${resp}