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