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