Skip to content

HaveKeyWithValue with a key matcher that accepts several keys succeeds on some calls and fails on others #929

Closed

Description

@DRMacIver

This is another bug found by our automated process of writing hegel tests in hegel-zoo, filed as asked in #925 and, as before, reviewed by hand first.

When the key matcher passed to HaveKeyWithValue accepts more than one of the map's keys, the result of the same call on the same map changes from call to call: with "bFoo": "Bar" present and three other keys ending in Foo, HaveKeyWithValue(MatchRegexp(.+Foo$), "Bar") comes back true in about one call in eight. When bFoo is the only key ending in Foo, it is true every time:

package main

import (
	"fmt"

	"github.com/onsi/gomega"
)

func count(m map[string]string) {
	pass, fail, errs := 0, 0, 0
	for i := 0; i < 500; i++ {
		ok, err := gomega.HaveKeyWithValue(gomega.MatchRegexp(`.+Foo$`), "Bar").Match(m)
		switch {
		case err != nil:
			errs++
		case ok:
			pass++
		default:
			fail++
		}
	}
	fmt.Printf("%v: true %d, false %d, error %d\n", m, pass, fail, errs)
}

func main() {
	count(map[string]string{"aFoo": "x", "bFoo": "Bar", "cFoo": "y", "dFoo": "z"})
	count(map[string]string{"a": "x", "bFoo": "Bar", "c": "y", "d": "z"})
}

Output:

map[aFoo:x bFoo:Bar cFoo:y dFoo:z]: true 58, false 442, error 0
map[a:x bFoo:Bar c:y d:z]: true 500, false 0, error 0

The counts vary a little between runs (60 true on a second run) but the first map never comes out all true. I expected both maps to match every time, since each has a key matching the key matcher whose value is "Bar"; the doc comment says the matcher succeeds if the map has the passed-in key and value.

Tested on v1.43.1, which is also the current master (47f0f87).

Activity

  1. onsi commented on Sep 24, 2026

    @onsi
    Owner

    I've delegated fixing this to Claude and checked the code it generated. Thanks for reporting!

    HaveKeyWithValue now keeps looking after a key matches but its value does not. It succeeds if any key accepted by the key matcher has a matching value, instead of depending on which matching key the map happens to iterate first. (ffc577a)

    This will be released in v1.44.0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions