stretchr / testify

A toolkit with common assertions and mocks that plays nicely with the standard library
MIT License
23.5k stars 1.6k forks source link

mock: add MatchedByRegexp(pattern) #817

Open KrzysztofMadejski opened 5 years ago

KrzysztofMadejski commented 5 years ago

A method that tests string argument if it matches regexp would be helpful.

Currently I'm using MatchedBy(func):

mock.MatchedBy(func(path string) bool {
    return regexp.MustCompile(pathRegexp).MatchString(path)
})

But the error (panic btw) is hard to analyze easily:

mock: Unexpected Method Call
-----------------------------

Create(string)
        0: "/Home/user/development/20190910170936437.csv"

The closest call I have is: 

Create(mock.argumentMatcher)
        0: mock.argumentMatcher{fn:reflect.Value{typ:(*reflect.rtype)(0x9be540), ptr:(unsafe.Pointer)(0xc000021260), flag:0x13}}

Diff: 0: FAIL:  (string=/Home/user/development/20190910170936437.csv) not matched by func(string) bool

It would be a lot nicer to have standard error:

Expected: "^....$" (regexp)
Got: ""
dolmen commented 1 year ago

@KrzysztofMadejski Here is a simple workaround: add this function to your test file:

func mockMatchedByRegexp(pattern string) {
    return mock.MatchedBy(func(path string) bool {
        ok, err := regexp.MatchString(pattern, path)
        if err != nil {
            panic(err)
        }
        return ok
    }
}

EDIT: this is not possible. The mock.MatchedBy signature returns type argumentsMatcher which is unfortunately private. This means that it is not currently possible to write such a wrapper. 😢

dolmen commented 1 year ago

@KrzysztofMadejski Adding a fully runnable example would be helpful to understand your pain. Here is a template: https://go.dev/play/p/AsRNcxCRdWx