user3920295
user3920295

Reputation: 909

Log dictionary to console in `robot framework`

I have a dictionary like this

{ a:{red ,blue, green}, b: {head, eyes, nose} }

and I want to print this in the console formatted in a pretty way like this.

------------
a
------------
red
blue
green
-------------
b
-------------
head
eyes
nose
-------------

Since robot framework does not support nested loops, I find it difficult to do this. I want to handle this in the job console and not the log.html.

Upvotes: 2

Views: 9988

Answers (2)

A. Kootstra
A. Kootstra

Reputation: 6961

Although a Python solution is likely to give you a bit more flexibility with regards to formatting etc, the out-of-the-box keywords in Robot are sufficient to create the desired logic. See below for the code example and the output:

*** Settings ***
Library    Collections    

*** Variables ***
@{a}    red     blue    green
@{b}    head    eyes    nose
&{DIC}    a=${a}    b=${b}


*** Test Cases ***
TC
    Log Structure    ${DIC}

*** Keywords ***
Log Structure
    [Arguments]    ${structure}
    Log To Console    \n
    Log To Console    ------------------------------

    # For Loops only work on Lists, so get all the keys from the Dictionary
    ${keys}     Get Dictionary Keys    ${structure}

    :FOR    ${item}    IN   @{keys}
    \    Log Many To Console    ${item}    ${structure["${item}"]}


Log Many To Console
    [Arguments]    ${name}    ${list}

    Log To Console    ${name}
    Log To Console    ------------------------------

    :FOR    ${item}    IN     @{list}
    \    Log To Console    ${item}

    Log To Console    ------------------------------

This then results in the following console output:

==============================================================================
ConsoleLog.ConsoleLog                                                         
==============================================================================
TC                                                                    

------------------------------
a
------------------------------
red
blue
green
------------------------------
b
------------------------------
head
eyes
nose
------------------------------
| PASS |
------------------------------------------------------------------------------
ConsoleLog.ConsoleLog                                                 | PASS |
1 critical test, 1 passed, 0 failed
1 test total, 1 passed, 0 failed

Upvotes: 2

iacob
iacob

Reputation: 24211

This will print what you want to the console with only one loop:

from robot.api import logger

d = { "a":{"red" ,"blue", "green"}, "b": {"head", "eyes", "nose"} }
divider = "------------"
s = []

for item in d:
    s.append(divider)
    s.append(item)
    s.append(divider)
    s.extend(d[item])

s = "\n".join(s)

logger.console(s)

Upvotes: 5

Related Questions