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