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