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