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