5

I'd have a library with a single function to safely get a key from a dictionary. Is this possible inside a test suite?

def safe_get(dict_obj, key):
    val = dict_obj.get(key)
    if val is None:
        val = {}
    return val

Is there a way to do this using something like Run_Keyword_If or Set_Variable_If?

4
  • What should be "possible inside a test suite" and what want you to do using Run Keyword If or Set Variable If?
    – Psytho
    Jan 8, 2016 at 10:36
  • Also, do you need just the key or do you need the value associated with that key as well? I'm presuming you'll ultimately aim to get the value, correct?
    – ash9209
    Jan 8, 2016 at 13:31
  • @Alex.S I mean inside the robot test file with nothing external dependencies.
    – Charles L.
    Jan 8, 2016 at 17:02
  • @ash9209 I want the value for that key
    – Charles L.
    Jan 8, 2016 at 17:02

2 Answers 2

9

TL;DR:

Assuming you're using robot 2.9 or later, you can call the get method on the dictionary by using the Evaluate keyword, which will allow you to specify a default value when the key doesn't exist.

For example:

| | ${data}=  | create dictionary | ...
| | ${value}= | evaluate          | $data.get("some key", "default value")

Explanation

Starting with robotframework 2.9 you can directly access variables in expressions by removing the curly braces (see Evaluating Expressions in the BuiltIn library documentation). For example, if you have a dictionary named ${data}, you can use the actual variable in an expression with $data.

This makes it very easy to use variables in python expressions. For example, if you want to provide a default for when a dictionary doesn't have a key you can call the get method of the dictionary by using the Evaluate keyword with something like $data.get(...).

Note also that robot defines the variable ${None} to be the python value None (not the string "None"), which you can use in an expression for checking to see whether a value is None.

The following examples show how to use evaluate to call the get method of the dictionary. The first test shows that you can check for a None value, the second example shows how you can provide a default value.

*** Settings ***
| Library | Collections

*** Test Cases ***
| Get value from dictionary, returning None if key not in dictionary
| | ${data}= | Create dictionary | key1=one | key2=two
| | ${value}= | Evaluate | $data.get("key3")
| | should be equal | ${value} | ${None}

| Get value from dictionary, returning default value if key not in dictionary
| | ${data}= | Create dictionary | key1=one | key2=two
| | ${value}= | Evaluate | $data.get("key3", "default value")
| | should be equal as strings | ${value} | default value

Of course, if you want your default value to be a new dictionary (as implied by your question) you can do that too:

| | ${value}= | Evaluate | $data.get("key3", {})
4
  • Would ${value}= Set_Variable ${data.get("some key")} be preferred?
    – Charles L.
    Jan 12, 2016 at 19:45
  • @CharlesL.: preferred? Not necessarily. I'm not sure there is a preferred way. Jan 12, 2016 at 19:50
  • I ask b/c eval is generally frowned upon in python, but I'm not sure what mechanism ${data.get()} is using.
    – Charles L.
    Jan 12, 2016 at 19:58
  • @CharlesL.: if this is a test where you control the data, it's perfectly safe. If you're really concerned about it, you can write a keyword in python, or string together a whole bunch of robot keywords. Jan 12, 2016 at 20:02
0
*** Variables ***
&{Charles Dictionary}

*** Test Cases ***

Safely Get a Key from Dictionary

    Set To Dictionary       ${Charles Dictionary}
    ... MyInterest              Hiking
    ... YourInterest            Swimming
    Work with Interests         ${Charles Dictionary}

*** Keywords ***

Work with Interests     [Arguments]         ${Charles Dictionary}
    ${val}=     Get This Value From Dictionary      ${Charles Dictionary}       MyInterest
    Run Keyword If      '${val}'!='None'        Log     That key is present in the dictionary!          console=yes
    Run Keyword If      '${val}'=='None'        Log     That key wasn't present in the dictionary!      console=yes


Get This Value From Dictionary      [Arguments]     ${Dictionary Name}      ${Key}
    ${KeyIsPresent}=    Run Keyword And Return Status       Dictionary Should Contain Key       ${Dictionary Name}      ${Key}
    ${Value}=           Run Keyword If      ${KeyIsPresent}     Get From Dictionary             ${Dictionary Name}      ${Key}
    Return From Keyword         ${Value}

Here, Charles Dictionary is a dictionary name that I've declared in the Variables section. I set 2 key-value pairs to it, call a keyword Work with Interests, and pass this dictionary as an argument to it.

The Work with Interests keyword gets values from the dictionary, allowing for both None and not-None values.

If a dictionary has the key present in it, the variable val will get the associated value for that key. If the dictionary does NOT have that key, the variable val will get a value of None.

I have also illustrated how can you can handle None and not None values in order to call different keywords. I've used the Log keyword to illustrate, but really, you can call any keyword you like, a built-in keyword or your own custom keyword.

I hope this helps you. If it does not, please do let me know.

5
  • If the value is None, how can you set it to an empty dictionary? I was having trouble with that because the Run Keyword If and Set Variable If were always setting None for me on the false case.
    – Charles L.
    Jan 8, 2016 at 17:14
  • I'm not sure I understand that perfectly. Could you rephrase? I'm assuming you need to know what if you don't want to pass a value to the keyword? If this is the case, just don't set the key and it's value in the dictionary. From the keyword, if you get the value for that key, it will retrieve it as None and then if the condition for None is satisfied you can call whatever keyword you need.
    – ash9209
    Jan 10, 2016 at 14:26
  • This has an error -- if the value of the dictionary of the literal string None it will treat it as if it doesn't exist. For example, change Hiking to None. Jan 10, 2016 at 20:27
  • You have a syntax error in your example -- you need two or more spaces following .... Jan 10, 2016 at 21:00
  • I have a large dict (full record) with keys that can be dicts (author has email & name). I have keywords to set fields, like setting author.email. I want to have a keyword to get a field that is either an existing dict, or an empty dict when either the key isn't there OR the value is None. Then I set my field inside that dict. So set author email, gets the current author field , or an empty dict using Get This Value From Dictionary then sets the email field within that.
    – Charles L.
    Jan 11, 2016 at 19:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.