go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/gae/impl/memory/race_test.go (about) 1 // Copyright 2015 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 memory 16 17 import ( 18 "context" 19 "fmt" 20 "sync" 21 "sync/atomic" 22 "testing" 23 24 ds "go.chromium.org/luci/gae/service/datastore" 25 ) 26 27 func TestRaceGetPut(t *testing.T) { 28 t.Parallel() 29 30 value := int32(0) 31 num := int32(0) 32 33 c := Use(context.Background()) 34 35 wg := sync.WaitGroup{} 36 37 for i := 0; i < 100; i++ { 38 wg.Add(1) 39 go func() { 40 defer wg.Done() 41 42 err := ds.RunInTransaction(c, func(c context.Context) error { 43 atomic.AddInt32(&num, 1) 44 45 obj := pmap("$key", ds.MakeKey(c, "Obj", 1)) 46 if err := ds.Get(c, obj); err != nil && err != ds.ErrNoSuchEntity { 47 panic(fmt.Sprintf("error get: %s", err)) 48 } 49 cur := int64(0) 50 if ps := obj.Slice("Value"); len(ps) > 0 { 51 cur = ps[0].Value().(int64) 52 } 53 54 cur++ 55 obj["Value"] = prop(cur) 56 57 return ds.Put(c, obj) 58 }, &ds.TransactionOptions{Attempts: 200}) 59 60 if err != nil { 61 panic(fmt.Sprintf("error during transaction: %s", err)) 62 } 63 64 atomic.AddInt32(&value, 1) 65 }() 66 } 67 wg.Wait() 68 69 obj := pmap("$key", ds.MakeKey(c, "Obj", 1)) 70 if ds.Get(c, obj) != nil { 71 t.FailNow() 72 } 73 t.Logf("Ran %d inner functions", num) 74 if int64(value) != obj.Slice("Value")[0].Value().(int64) { 75 t.Fatalf("value wrong value %d v %d", value, obj.Slice("Value")[0].Value().(int64)) 76 } 77 } 78 79 func TestRaceNonConflictingPuts(t *testing.T) { 80 t.Parallel() 81 82 c := Use(context.Background()) 83 84 num := int32(0) 85 86 wg := sync.WaitGroup{} 87 88 for i := 0; i < 100; i++ { 89 wg.Add(1) 90 go func() { 91 defer wg.Done() 92 93 err := ds.RunInTransaction(c, func(c context.Context) error { 94 return ds.Put(c, pmap( 95 "$kind", "Thing", Next, 96 "Value", 100)) 97 }, nil) 98 if err != nil { 99 panic(fmt.Sprintf("error during transaction: %s", err)) 100 } 101 atomic.AddInt32(&num, 1) 102 }() 103 } 104 wg.Wait() 105 106 if num != 100 { 107 t.Fatal("expected 100 runs, got", num) 108 } 109 }