github.com/go-kivik/kivik/v4@v4.3.2/kiviktest/client/updates.go (about) 1 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 2 // use this file except in compliance with the License. You may obtain a copy of 3 // the License at 4 // 5 // http://www.apache.org/licenses/LICENSE-2.0 6 // 7 // Unless required by applicable law or agreed to in writing, software 8 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 9 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 // License for the specific language governing permissions and limitations under 11 // the License. 12 13 package client 14 15 import ( 16 "context" 17 "fmt" 18 "time" 19 20 kivik "github.com/go-kivik/kivik/v4" 21 "github.com/go-kivik/kivik/v4/kiviktest/kt" 22 ) 23 24 func init() { 25 kt.Register("DBUpdates", updates) 26 } 27 28 func updates(ctx *kt.Context) { 29 ctx.RunRW(func(ctx *kt.Context) { 30 ctx.RunAdmin(func(ctx *kt.Context) { 31 testUpdates(ctx, ctx.Admin) 32 }) 33 ctx.RunNoAuth(func(ctx *kt.Context) { 34 testUpdates(ctx, ctx.NoAuth) 35 }) 36 }) 37 } 38 39 const maxWait = 5 * time.Second 40 41 func testUpdates(ctx *kt.Context, client *kivik.Client) { 42 ctx.Parallel() 43 updates := client.DBUpdates(context.TODO()) 44 if !ctx.IsExpectedSuccess(updates.Err()) { 45 return 46 } 47 // It seems that DBUpdates doesn't always start responding immediately, 48 // so introduce a small delay to ensure we're reporting updates before we 49 // actually do the updates. 50 const delay = 10 * time.Millisecond 51 time.Sleep(delay) 52 dbname := ctx.TestDBName() 53 eventErrors := make(chan error) 54 go func() { 55 for updates.Next() { 56 if updates.DBName() == dbname { 57 if updates.Type() == "created" { 58 break 59 } 60 eventErrors <- fmt.Errorf("Unexpected event type '%s'", updates.Type()) 61 } 62 } 63 eventErrors <- updates.Err() 64 close(eventErrors) 65 }() 66 ctx.T.Cleanup(func() { ctx.DestroyDB(dbname) }) 67 if err := ctx.Admin.CreateDB(context.Background(), dbname, ctx.Options("db")); err != nil { 68 ctx.Fatalf("Failed to create db: %s", err) 69 } 70 timer := time.NewTimer(maxWait) 71 select { 72 case err := <-eventErrors: 73 if err != nil { 74 ctx.Fatalf("Error reading event: %s", err) 75 } 76 case <-timer.C: 77 ctx.Fatalf("Failed to read expected event in %s", maxWait) 78 } 79 if err := updates.Close(); err != nil { 80 ctx.Errorf("Updates close failed: %s", err) 81 } 82 }