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