github.com/Schaudge/grailbase@v0.0.0-20240223061707-44c758a471c0/errors/once_test.go (about) 1 // Copyright 2018 GRAIL, Inc. All rights reserved. 2 // Use of this source code is governed by the Apache-2.0 3 // license that can be found in the LICENSE file. 4 5 package errors_test 6 7 import ( 8 "fmt" 9 "runtime" 10 "testing" 11 12 "github.com/Schaudge/grailbase/errors" 13 "github.com/stretchr/testify/require" 14 ) 15 16 func TestOnce(t *testing.T) { 17 e := errors.Once{} 18 require.NoError(t, e.Err()) 19 20 e.Set(errors.New("testerror")) 21 require.EqualError(t, e.Err(), "testerror") 22 e.Set(errors.New("testerror2")) // ignored 23 require.EqualError(t, e.Err(), "testerror") 24 runtime.GC() 25 require.EqualError(t, e.Err(), "testerror") 26 } 27 28 func BenchmarkReadNoError(b *testing.B) { 29 e := errors.Once{} 30 for i := 0; i < b.N; i++ { 31 if e.Err() != nil { 32 require.Fail(b, "err") 33 } 34 } 35 } 36 37 func BenchmarkReadError(b *testing.B) { 38 e := errors.Once{} 39 e.Set(errors.New("testerror")) 40 for i := 0; i < b.N; i++ { 41 if e.Err() == nil { 42 require.Fail(b, "err") 43 } 44 } 45 } 46 47 func BenchmarkSet(b *testing.B) { 48 e := errors.Once{} 49 err := errors.New("testerror") 50 for i := 0; i < b.N; i++ { 51 e.Set(err) 52 } 53 } 54 55 func ExampleOnce() { 56 e := errors.Once{} 57 fmt.Printf("Error: %v\n", e.Err()) 58 e.Set(errors.New("test error 0")) 59 fmt.Printf("Error: %v\n", e.Err()) 60 e.Set(errors.New("test error 1")) 61 fmt.Printf("Error: %v\n", e.Err()) 62 // Output: 63 // Error: <nil> 64 // Error: test error 0 65 // Error: test error 0 66 }