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