agiledragon / gomonkey

gomonkey is a library to make monkey patching in unit tests easy
MIT License
1.92k stars 178 forks source link

ApplyFuncSeq has DATA RACE issue #120

Open ericuni opened 1 year ago

ericuni commented 1 year ago
package playground_test

import (
    "testing"

    "github.com/agiledragon/gomonkey/v2"
    "github.com/stretchr/testify/assert"
    "golang.org/x/sync/errgroup"
)

func foo() int {
    return 0
}

func run() error {
    var eg errgroup.Group

    eg.Go(func() error {
        foo()
        return nil
    })

    eg.Go(func() error {
        foo()
        return nil
    })

    if err := eg.Wait(); err != nil {
        return err
    }

    return nil
}

func TestPlayground(t *testing.T) {
    assert := assert.New(t)

    patches := gomonkey.NewPatches()
    defer patches.Reset()

    patches.ApplyFuncSeq(foo, []gomonkey.OutputCell{
        {
            Values: gomonkey.Params{1},
        },
        {
            Values: gomonkey.Params{2},
        },
    })

    err := run()
    assert.Nil(err)
}

run with go test -race -gcflags=all=-l, would get the following error

==================
WARNING: DATA RACE
Read at 0x00c000222d88 by goroutine 8:
  github.com/agiledragon/gomonkey/v2.getDoubleFunc.func1()
      /data00/home/liuqi.victor/go/pkg/mod/github.com/agiledragon/gomonkey/v2@v2.9.0/patch.go:304 +0xde
  reflect.callReflect()
      /data00/home/liuqi.victor/opt/go/src/reflect/value.go:770 +0x762
  reflect.callReflect()
      <autogenerated>:1 +0x64
  reflect.makeFuncStub()
      /data00/home/liuqi.victor/opt/go/src/reflect/asm_amd64.s:47 +0x79
  golang.org/x/sync/errgroup.(*Group).Go.func1()
      /data00/home/liuqi.victor/go/pkg/mod/golang.org/x/sync@v0.1.0/errgroup/errgroup.go:75 +0x86

Previous write at 0x00c000222d88 by goroutine 9:
  github.com/agiledragon/gomonkey/v2.getDoubleFunc.func1()
      /data00/home/liuqi.victor/go/pkg/mod/github.com/agiledragon/gomonkey/v2@v2.9.0/patch.go:305 +0x108
  reflect.callReflect()
      /data00/home/liuqi.victor/opt/go/src/reflect/value.go:770 +0x762
  reflect.callReflect()
      <autogenerated>:1 +0x64
  reflect.makeFuncStub()
      /data00/home/liuqi.victor/opt/go/src/reflect/asm_amd64.s:47 +0x79
  golang.org/x/sync/errgroup.(*Group).Go.func1()
      /data00/home/liuqi.victor/go/pkg/mod/golang.org/x/sync@v0.1.0/errgroup/errgroup.go:75 +0x86