Skip to content

Commit

Permalink
replace bou.ke/monkey with bytedance/mockey (#570)
Browse files Browse the repository at this point in the history
* replace monkey with gomonkey

* add more tests

* replace gomonkey with mockey

* restore wait function

* change the TestOpenLogFail case to work without monkey patching

* use the TempDir to avoid messing with Unix/Windows

---------

Co-authored-by: Pantelis Roditis <[email protected]>
  • Loading branch information
samanhappy and proditis authored Sep 13, 2024
1 parent f5aea0f commit 1ccb321
Show file tree
Hide file tree
Showing 52 changed files with 280 additions and 79 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-13]
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- name: Checkout Source Code
uses: actions/checkout@v4
Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ ${TARGET}: ${SOURCE}
build: all

test:
go test -gcflags=-l -cover -race ${TEST_FLAGS} -v ./...
go test -gcflags=all=-l -cover -race ${TEST_FLAGS} -v ./...

docker:
sudo DOCKER_BUILDKIT=1 docker build -t megaease/easeprobe -f ${MKFILE_DIR}/resources/Dockerfile ${MKFILE_DIR}
Expand Down
2 changes: 1 addition & 1 deletion conf/conf_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ import (
"testing"
"time"

"bou.ke/monkey"
"github.com/megaease/easeprobe/global"
"github.com/megaease/easeprobe/monkey"
"github.com/megaease/easeprobe/notify"
"github.com/megaease/easeprobe/notify/discord"
"github.com/megaease/easeprobe/notify/email"
Expand Down
24 changes: 4 additions & 20 deletions conf/log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,8 @@ import (
"fmt"
"os"
"path/filepath"
"reflect"
"testing"

"bou.ke/monkey"
log "github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"gopkg.in/natefinch/lumberjack.v2"
Expand Down Expand Up @@ -137,14 +135,11 @@ func TestNonSelfRotateLog(t *testing.T) {
}

func TestOpenLogFail(t *testing.T) {
monkey.Patch(os.OpenFile, func(name string, flag int, perm os.FileMode) (*os.File, error) {
return nil, fmt.Errorf("error")
})

file := "failed"
// User a directory to cause failure
file := os.TempDir()

l := NewLog()
l.File = file + ".log"
l.File = file
l.SelfRotate = false
l.InitLog(nil)
assert.Equal(t, true, l.IsStdout)
Expand All @@ -157,20 +152,14 @@ func TestOpenLogFail(t *testing.T) {
w := l.GetWriter()
assert.Equal(t, os.Stdout, w)

monkey.UnpatchAll()

// test rotate error - log file
file = "failed"
l = NewLog()
l.File = file + ".log"
l.SelfRotate = false
l.InitLog(nil)
assert.Equal(t, false, l.IsStdout)

var fp *os.File
monkey.PatchInstanceMethod(reflect.TypeOf(fp), "Close", func(_ *os.File) error {
return fmt.Errorf("error")
})

l.Rotate()
files, _ := filepath.Glob(file + "*")
fmt.Println(files)
Expand All @@ -185,16 +174,11 @@ func TestOpenLogFail(t *testing.T) {
l.InitLog(nil)
assert.Equal(t, false, l.IsStdout)

var lum *lumberjack.Logger
monkey.PatchInstanceMethod(reflect.TypeOf(lum), "Rotate", func(_ *lumberjack.Logger) error {
return fmt.Errorf("error")
})
l.Rotate()
files, _ = filepath.Glob(file + "*")
fmt.Println(files)
assert.Equal(t, 1, len(files))
l.Close()
os.Remove(l.File)

monkey.UnpatchAll()
}
2 changes: 1 addition & 1 deletion daemon/daemon_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ import (
"path/filepath"
"testing"

"bou.ke/monkey"
"github.com/megaease/easeprobe/global"
"github.com/megaease/easeprobe/monkey"

"github.com/stretchr/testify/assert"
)
Expand Down
2 changes: 1 addition & 1 deletion eval/eval_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ import (
"testing"
"time"

"bou.ke/monkey"
"github.com/Knetic/govaluate"
"github.com/megaease/easeprobe/monkey"
"github.com/stretchr/testify/assert"
)

Expand Down
2 changes: 1 addition & 1 deletion eval/extract_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import (
"testing"
"time"

"bou.ke/monkey"
"github.com/megaease/easeprobe/monkey"
"github.com/stretchr/testify/assert"
"golang.org/x/net/html"
)
Expand Down
2 changes: 1 addition & 1 deletion global/easeprobe_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import (
"testing"
"time"

"bou.ke/monkey"
"github.com/megaease/easeprobe/monkey"
"github.com/stretchr/testify/assert"
)

Expand Down
2 changes: 1 addition & 1 deletion global/global_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import (
"testing"
"time"

"bou.ke/monkey"
"github.com/megaease/easeprobe/monkey"
"github.com/stretchr/testify/assert"
"gopkg.in/yaml.v3"
)
Expand Down
10 changes: 8 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
module github.com/megaease/easeprobe

go 1.21
go 1.22

toolchain go1.22.5

require (
bou.ke/monkey v1.0.2
github.com/Knetic/govaluate v3.0.0+incompatible
github.com/antchfx/htmlquery v1.3.2
github.com/antchfx/jsonquery v1.3.5
github.com/antchfx/xmlquery v1.4.1
github.com/aws/aws-sdk-go v1.55.5
github.com/bradfitz/gomemcache v0.0.0-20220106215444-fb4bf637b56d
github.com/bytedance/mockey v1.2.12
github.com/go-chi/chi v4.1.2+incompatible
github.com/go-chi/chi/v5 v5.1.0
github.com/go-co-op/gocron v1.37.0
Expand Down Expand Up @@ -47,17 +48,22 @@ require (
github.com/goccy/go-json v0.10.3 // indirect
github.com/goccy/go-yaml v1.12.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 // indirect
github.com/jinzhu/copier v0.4.0 // indirect
github.com/jtolds/gls v4.20.0+incompatible // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/puzpuzpuz/xsync/v3 v3.4.0 // indirect
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d // indirect
github.com/smartystreets/goconvey v1.6.4 // indirect
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
github.com/yuin/gopher-lua v1.1.1 // indirect
go.uber.org/atomic v1.9.0 // indirect
golang.org/x/arch v0.0.0-20201008161808-52c3e6f60cff // indirect
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
)
Expand Down
17 changes: 15 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
bou.ke/monkey v1.0.2 h1:kWcnsrCNUatbxncxR/ThdYqbytgOIArtYWqcQLQzKLI=
bou.ke/monkey v1.0.2/go.mod h1:OqickVX3tNx6t33n1xvtTtu85YN5s6cKwVug+oHMaIA=
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/Knetic/govaluate v3.0.0+incompatible h1:7o6+MAPhYTCF0+fdvoz1xDedhRb4f6s9Tn1Tt7/WTEg=
Expand Down Expand Up @@ -30,6 +28,8 @@ github.com/bradfitz/gomemcache v0.0.0-20220106215444-fb4bf637b56d h1:pVrfxiGfwel
github.com/bradfitz/gomemcache v0.0.0-20220106215444-fb4bf637b56d/go.mod h1:H0wQNHz2YrLsuXOZozoeDmnHXkNCRmMW0gwFWDfEZDA=
github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs=
github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
github.com/bytedance/mockey v1.2.12 h1:aeszOmGw8CPX8CRx1DZ/Glzb1yXvhjDh6jdFBNZjsU4=
github.com/bytedance/mockey v1.2.12/go.mod h1:3ZA4MQasmqC87Tw0w7Ygdy7eHIc2xgpZ8Pona5rsYIk=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
Expand Down Expand Up @@ -77,6 +77,8 @@ github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeN
github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=
Expand All @@ -92,6 +94,8 @@ github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHW
github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8=
github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU=
github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA=
github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
Expand Down Expand Up @@ -159,6 +163,10 @@ github.com/segmentio/kafka-go v0.4.47 h1:IqziR4pA3vrZq7YdRxaT3w1/5fvIH5qpCwstUan
github.com/segmentio/kafka-go v0.4.47/go.mod h1:HjF6XbOKh0Pjlkr5GVZxt6CsjjwnmhVOfURM5KMd8qg=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s=
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
Expand Down Expand Up @@ -198,6 +206,8 @@ go.mongodb.org/mongo-driver v1.16.1 h1:rIVLL3q0IHM39dvE+z2ulZLp9ENZKThVfuvN/IiN4
go.mongodb.org/mongo-driver v1.16.1/go.mod h1:oB6AhJQvFQL4LEHyXi6aJzQJtBiTQHiAd83l0GdFaiw=
go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
golang.org/x/arch v0.0.0-20201008161808-52c3e6f60cff h1:XmKBi9R6duxOB3lfc72wyrwiOY7X2Jl1wuI+RFOyMDE=
golang.org/x/arch v0.0.0-20201008161808-52c3e6f60cff/go.mod h1:flIaEI6LNU6xOCD5PaJvn9wGP0agmIOqjrtsKGRguv4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
Expand All @@ -207,6 +217,7 @@ golang.org/x/exp v0.0.0-20221031165847-c99f073a8326 h1:QfTh0HpN6hlw6D3vu8DAwC8pB
golang.org/x/exp v0.0.0-20221031165847-c99f073a8326/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
Expand Down Expand Up @@ -251,6 +262,7 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc=
golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
Expand Down Expand Up @@ -282,3 +294,4 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
mellium.im/sasl v0.3.1 h1:wE0LW6g7U83vhvxjC1IY8DnXM+EU095yeo8XClvCdfo=
mellium.im/sasl v0.3.1/go.mod h1:xm59PUYpZHhgQ9ZqoJ5QaCqzWMi8IeS49dhp6plPCzw=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
2 changes: 1 addition & 1 deletion metric/prometheus_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ package metric
import (
"testing"

"bou.ke/monkey"
"github.com/megaease/easeprobe/monkey"
"github.com/prometheus/client_golang/prometheus"
"github.com/stretchr/testify/assert"
)
Expand Down
127 changes: 127 additions & 0 deletions monkey/monkey.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/*
* Copyright (c) 2022, MegaEase
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

// Package monkey is a library to patch functions and methods at runtime for testing
package monkey

import (
"fmt"
"log"
"reflect"
"runtime"
"sync"
"time"

"github.com/bytedance/mockey"
)

var (
patchesMap sync.Map
)

// Patch replaces a function with another
func Patch(target, replacement interface{}) *mockey.Mocker {
key := fmt.Sprintf("%v", target)

// If an existing patch exists, reset and delete it
if existingPatches, ok := patchesMap.Load(key); ok {
existingPatches.(*mockey.Mocker).UnPatch()
patchesMap.Delete(key)
}

// Apply the new patch
patches := mockey.Mock(target).To(replacement).Build()
patchesMap.Store(key, patches)
wait()
return patches
}

// Unpatch removes a patch
func Unpatch(target interface{}) bool {
key := fmt.Sprintf("%v", target)

patches, ok := patchesMap.Load(key)
if !ok {
return false
}
patches.(*mockey.Mocker).UnPatch()
patchesMap.Delete(key)
wait()
return true
}

// PatchInstanceMethod replaces an instance method methodName for the type target with replacement
func PatchInstanceMethod(target reflect.Type, methodName string, replacement interface{}) *mockey.Mocker {
key := fmt.Sprintf("%v:%v", target, methodName)

// If an existing patch exists, reset and delete it
if existingPatches, ok := patchesMap.Load(key); ok {
existingPatches.(*mockey.Mocker).UnPatch()
patchesMap.Delete(key)
}

// Get the method
method, ok := target.MethodByName(methodName)
if !ok {
log.Fatalf("failed to patch by method %s not found", methodName)
return nil
}

// Check if the method is a function
methodValue := method.Func
if methodValue.Kind() != reflect.Func {
log.Fatalf("failed to patch by method %s is not a function", methodName)
return nil
}

// Apply the new patch
patches := mockey.Mock(methodValue.Interface()).To(replacement).Build()
patchesMap.Store(key, patches)
wait()
return patches
}

// UnpatchInstanceMethod removes a patch from an instance method
func UnpatchInstanceMethod(target reflect.Type, methodName string) bool {
key := fmt.Sprintf("%v:%v", target, methodName)

patches, ok := patchesMap.Load(key)
if !ok {
return false
}
patches.(*mockey.Mocker).UnPatch()
patchesMap.Delete(key)
wait()
return true
}

// UnpatchAll removes all patches
func UnpatchAll() {
patchesMap.Range(func(key, value interface{}) bool {
value.(*mockey.Mocker).UnPatch()
patchesMap.Delete(key)
return true
})
wait()
}

// wait ensures that the patches for darwin/arm64 are applied to prevent test failures and runtime errors, such as invalid memory address or nil pointer dereference
func wait() {
if runtime.GOOS == "darwin" {
time.Sleep(100 * time.Millisecond)
}
}
Loading

0 comments on commit 1ccb321

Please sign in to comment.