Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HaveField: cannot call method with pointer receiver for values #696

Closed
pohly opened this issue Sep 6, 2023 · 1 comment
Closed

HaveField: cannot call method with pointer receiver for values #696

pohly opened this issue Sep 6, 2023 · 1 comment

Comments

@pohly
Copy link

pohly commented Sep 6, 2023

I recently suggested replacing these checks with ConsistOf + HaveField("GetName()", Equal:

	gomega.Expect(len(list.Items)).To(gomega.BeIdenticalTo(2))
	framework.ExpectEqual((list.Items[0].GetName() == name1 && list.Items[1].GetName() == name2) ||
		(list.Items[0].GetName() == name2 && list.Items[1].GetName() == name1), true)

=>

gomega.Expect(list.Items).To(gomega.ConsistOf(gomega.HaveField("GetName()", gomega.Equal(name1)), gomega.HaveField("GetName()", gomega.Equal(name2))))

That didn't work. It turned out that the slice elements are values and their GetName method is only defined for pointers. Go can call it anyway, but Gomega can't (or doesn't). Perhaps it should also support that?

Here's a reproducer:

package gomegatest

import (
	"testing"

	"github.com/onsi/gomega"
)

type pointerobject struct {
	name string
}

func (p *pointerobject) GetName() string {
	return p.name
}

type valueobject struct {
	name string
}

func (v valueobject) GetName() string {
	return v.name
}

type object interface {
	GetName() string
}

var _ object = valueobject{}

// Only pointer implements object interface, not value.
var _ object = &pointerobject{}

// var _ object = pointerobject{}

func TestConsistsOf(t *testing.T) {
	g := gomega.NewGomegaWithT(t)
	e := gomega.ConsistOf(gomega.HaveField("GetName()", gomega.Equal("A")), gomega.HaveField("GetName()", gomega.Equal("B")))

	g.Expect([]valueobject{{"A"}, {"B"}}).To(e)   // works
	g.Expect([]pointerobject{{"A"}, {"B"}}).To(e) // fails
}
thediveo added a commit to thediveo/gomega that referenced this issue Dec 6, 2024
@thediveo
Copy link
Collaborator

thediveo commented Dec 6, 2024

looking into the matcher code base that was originally deliberate; if there is no reason why we should keep this restriction then there's a PR. Yeah, I've just run into this myself 😀

@onsi onsi closed this as completed in 4feb9d7 Dec 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants