getgauge-contrib / gauge-go

Go language plugin for Gauge
GNU General Public License v3.0
71 stars 21 forks source link

Add table value accessor methods #3

Open apoorvam opened 8 years ago

apoorvam commented 8 years ago

Table type can have value accessor methods by column name.

Currently table values can be accessed using tbl.Rows[0].Cells[0] to fetch first element of first row. This can be enhanced to access value using column name as: tbl.getColumn("columnName").get(0) so that its more explicit and avoids index out of range exceptions.

Better way?

ferdypruis commented 3 years ago

For anyone looking. I map a Table to a slice of maps, where each row becomes a slice element with the column header being the index in the map, using this;

// TableParameters can be used when a table of parameters is used with a step.
// The function provides a map per row of which the index is the name of the cell from the header.
// https://docs.gauge.org/writing-specifications.html?os=linux&language=python&ide=vscode#table-parameters
func TableParameters(tbl *m.Table) []map[string]string {
    rows := make([]map[string]string, len(tbl.Rows))
    for i, r := range tbl.Rows {
        cells := make(map[string]string, len(r.Cells))
        for col, cell := range r.Cells {
            cells[tbl.Headers.Cells[col]] = cell
        }
        rows[i] = cells
    }

    return rows
}

Having for example this specification;

* Almost all words have vowels 

   |Word  |Vowel Count|
   |------|-----------|
   |Gauge |3          |
   |Mingle|2          |
   |Snap  |1          |
   |GoCD  |1          |
   |Rhythm|0          |

You could do this in your implementation;

var _ = gauge.Step("Almost all words have vowels <table>", func(tbl *m.Table) {
    for _, row := range TableParameters(tbl) {
        word := row[`Word`]
        expectedCount, err := strconv.Atoi(row[`Vowel Count`])

[...]