github.com/pingcap/failpoint@v0.0.0-20240412033321-fd0796e60f86/failpoint_test.go (about) 1 // Copyright 2021 PingCAP, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package failpoint_test 16 17 import ( 18 "context" 19 "sync" 20 "testing" 21 "time" 22 23 "github.com/pingcap/failpoint" 24 "github.com/stretchr/testify/require" 25 ) 26 27 func TestWithHook(t *testing.T) { 28 err := failpoint.Enable("TestWithHook-test-0", "return(1)") 29 require.NoError(t, err) 30 31 val, err := failpoint.EvalContext(context.Background(), "TestWithHook-test-0") 32 require.Nil(t, val) 33 require.Error(t, err) 34 35 val, err = failpoint.EvalContext(nil, "TestWithHook-test-0") 36 require.Nil(t, val) 37 require.Error(t, err) 38 39 ctx := failpoint.WithHook(context.Background(), func(ctx context.Context, fpname string) bool { 40 return false 41 }) 42 val, err = failpoint.EvalContext(ctx, "unit-test") 43 require.Error(t, err) 44 require.Nil(t, val) 45 46 ctx = failpoint.WithHook(context.Background(), func(ctx context.Context, fpname string) bool { 47 return true 48 }) 49 err = failpoint.Enable("TestWithHook-test-1", "return(1)") 50 require.NoError(t, err) 51 defer func() { 52 err := failpoint.Disable("TestWithHook-test-1") 53 require.NoError(t, err) 54 }() 55 val, err = failpoint.EvalContext(ctx, "TestWithHook-test-1") 56 require.NoError(t, err) 57 require.Equal(t, 1, val.(int)) 58 } 59 60 func TestConcurrent(t *testing.T) { 61 err := failpoint.Enable("TestWithHook-test-2", "pause") 62 require.NoError(t, err) 63 var wg sync.WaitGroup 64 wg.Add(1) 65 go func() { 66 ctx := failpoint.WithHook(context.Background(), func(ctx context.Context, fpname string) bool { 67 return true 68 }) 69 val, _ := failpoint.EvalContext(ctx, "TestWithHook-test-2") 70 require.Nil(t, val) 71 wg.Done() 72 }() 73 time.Sleep(1 * time.Second) 74 err = failpoint.Enable("TestWithHook-test-3", "return(1)") 75 require.NoError(t, err) 76 err = failpoint.Disable("TestWithHook-test-3") 77 require.NoError(t, err) 78 err = failpoint.Disable("TestWithHook-test-2") 79 require.NoError(t, err) 80 wg.Wait() 81 }