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