go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/gae/filter/txndefer/filter_test.go (about) 1 // Copyright 2020 The LUCI Authors. 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 txndefer 16 17 import ( 18 "context" 19 "errors" 20 "fmt" 21 "testing" 22 23 "go.chromium.org/luci/gae/impl/memory" 24 "go.chromium.org/luci/gae/service/datastore" 25 26 . "github.com/smartystreets/goconvey/convey" 27 ) 28 29 func ExampleFilterRDS() { 30 ctx := FilterRDS(memory.Use(context.Background())) 31 32 datastore.RunInTransaction(ctx, func(ctx context.Context) error { 33 Defer(ctx, func(context.Context) { fmt.Println("1") }) 34 Defer(ctx, func(context.Context) { fmt.Println("2") }) 35 return nil 36 }, nil) 37 38 // Output: 39 // 2 40 // 1 41 } 42 43 func TestFilter(t *testing.T) { 44 t.Parallel() 45 46 Convey("With filter", t, func() { 47 ctx := FilterRDS(memory.Use(context.Background())) 48 49 Convey("Successful txn", func() { 50 ctx := context.WithValue(ctx, "123", "random extra value") 51 called := false 52 53 err := datastore.RunInTransaction(ctx, func(ctx context.Context) error { 54 Defer(ctx, func(ctx context.Context) { 55 So(datastore.CurrentTransaction(ctx), ShouldBeNil) 56 So(ctx.Value("123"), ShouldEqual, "random extra value") 57 called = true 58 }) 59 return nil 60 }, nil) 61 62 So(err, ShouldBeNil) 63 So(called, ShouldBeTrue) 64 }) 65 66 Convey("Fatal txn error", func() { 67 called := false 68 69 datastore.RunInTransaction(ctx, func(ctx context.Context) error { 70 Defer(ctx, func(context.Context) { called = true }) 71 return errors.New("boom") 72 }, nil) 73 74 So(called, ShouldBeFalse) 75 }) 76 77 Convey("Txn retries", func() { 78 attempt := 0 79 calls := 0 80 81 err := datastore.RunInTransaction(ctx, func(ctx context.Context) error { 82 attempt++ 83 Defer(ctx, func(context.Context) { calls++ }) 84 if attempt < 3 { 85 return datastore.ErrConcurrentTransaction 86 } 87 return nil 88 }, nil) 89 90 So(err, ShouldBeNil) 91 So(attempt, ShouldEqual, 3) 92 So(calls, ShouldEqual, 1) 93 }) 94 }) 95 }