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