ethersphere / swarm-cli

Manage your Bee node and interact with the Swarm network via the CLI
BSD 3-Clause "New" or "Revised" License
48 stars 21 forks source link

Revamp testing console messages (get rid of exact indices) #432

Closed Cafe137 closed 1 year ago

Cafe137 commented 1 year ago

During test runs, we put every console message (stdout of swarm-cli) to an array. To assert correct output, we check these messages by exact index to match a regex or contain some substring.

This is often annoying and causes off-by-one errors when an extra step is added that shifts the indices.

I propose to change this approach with a less strict helper function linesMatchOrdered which takes an array of expected substrings (or regexes) to appear in the output, respecting the order, but ignoring gaps and omitting the indices.

Before

expect(getNthLastMessage(3)).toContain('Utilization')
expect(getNthLastMessage(3)).toContain('0')
expect(getNthLastMessage(4)).toContain('Usable')
expect(getNthLastMessage(4)).toContain('true')
expect(getNthLastMessage(9)).toContain('Usage')
expect(getNthLastMessage(9)).toContain('0%')
expect(getNthLastMessage(10)).toContain('Label:')
expect(getNthLastMessage(10)).toContain('Alice')
expect(getNthLastMessage(11)).toContain('Stamp ID')
expect(getNthLastMessage(11)).toContain(id)

After

assert(linesMatchOrdered(consoleMessages, [
    `Stamp ID: ${id}`,
    `Label: Alice`,
    'Usage: 0%',
    'Usable: true',
    'Utilization: 0',
]))

Naive implementation

function linesMatchOrdered(lines, expectedLines) {
    let lineIndex = 0
    for (let i = 0; i < expectedLines.length; i++) {
        const expectedLine = expectedLines[i]
        let found = false
        while (!found && lineIndex < lines.length) {
            if (lines[lineIndex].includes(expectedLine)) {
                found = true
            }
            lineIndex++
        }
        if (!found) {
            return false
        }
    }
    return true
}