Question

I need to define a 2 dimensional array variable.
I have been able to use a list variable but now the project I'm working on requires an array.

How is this done?
How can I "loop" through the 2 dimensional array?

Was it helpful?

Solution

Try using a list of lists. You can use the extended variable syntax to access an item in the inner list.

*** Settings ***
Library           Collections

*** Variables ***
@{colors}         red    green    blue
@{animals}        cow    pig    dog
@{things}         ${animals}    ${colors}

*** Test Cases ***
2-Dimensional List
    Log List    ${things}
    Log    The ${things[0][1]} is ${things[1][1]}

List length is 2 and it contains following items: 0: [u'cow', u'pig', u'dog'] 1: [u'red', u'green', u'blue']

The pig is green

OTHER TIPS

Using lists

Robot's term for an array variable is "list". You can use @{...} to designate a variable as a list. Here's an example that shows how to create a list in a variable table, and how to do it within a test using the Create List keyword:

*** Variables ***
| # create a list in a variable table
| @{Colors} | red | orange | green | blue

*** Test Cases ***
| Example of using lists

| | # create an array inside a test
| | @{Names}= | Create list | homer | marge | bart

| | # Verify that the elements are arrays
| | Length should be | ${Colors} | 4
| | Length should be | ${Names} | 3

To create a two dimensional list, you can create a list of lists:

| | ${array}= | Create list | ${Names} | ${Colors}

The extended variable syntax lets you access individual elements:

| | log | element 1,1: ${array[1][1]}

For more information, see the section titled List variables in the Robot Framework User Guide

Using dictionaries

You can use a dictionary to simulate a multi-dimensional array. For example:

*** Settings ***
| Library | Collections

*** Test Cases ***
| Example of using a dictionary to simulate a two dimensional array
| | ${array}= | Create dictionary 
| | ... | 0,0 | zero, zero
| | ... | 0,1 | zero, one
| | ... | 1,0 | one, zero
| | ... | 1,1 | one, one
| | Should be equal | ${array["1,0"]} | one, zero

I found a way to loop through a list of lists:

*** Settings ***
Library           Collections

*** Variables ***
@{colors}         red    green    blue
@{animals}        cow    pig    dog
@{things}         ${animals}    ${colors}

*** Test Cases ***
Nested for loop example
    : FOR    ${x}    IN    @{animals}
    \    Keyword with for loop    ${x}

*** Keywords ***
Keyword with for loop
    [Arguments]    ${x}
    :FOR    ${y}    IN    @{colors}
    \    Log  The ${x} is ${y}

The credit goes to ombre42. Thanks!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top