github.com/go-kivik/kivik/v4@v4.3.2/mockdb/driver.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 mockdb 14 15 import ( 16 "errors" 17 "fmt" 18 "sync" 19 "testing" 20 21 kivik "github.com/go-kivik/kivik/v4" 22 "github.com/go-kivik/kivik/v4/driver" 23 ) 24 25 var pool *mockDriver 26 27 func init() { 28 pool = &mockDriver{ 29 clients: make(map[string]*Client), 30 } 31 kivik.Register("mock", pool) 32 } 33 34 type mockDriver struct { 35 sync.Mutex 36 counter int 37 clients map[string]*Client 38 } 39 40 var _ driver.Driver = &mockDriver{} 41 42 func (d *mockDriver) NewClient(dsn string, _ driver.Options) (driver.Client, error) { 43 d.Lock() 44 defer d.Unlock() 45 46 c, ok := d.clients[dsn] 47 if !ok { 48 return nil, errors.New("mockdb: no available connection found") 49 } 50 c.opened++ 51 return &driverClient{Client: c}, nil 52 } 53 54 // New creates a kivik client connection and a mock to manage expectations. 55 func New() (*kivik.Client, *Client, error) { 56 pool.Lock() 57 dsn := fmt.Sprintf("mockdb_%d", pool.counter) 58 pool.counter++ 59 60 kmock := &Client{dsn: dsn, drv: pool, ordered: true} 61 pool.clients[dsn] = kmock 62 pool.Unlock() 63 64 return kmock.open() 65 } 66 67 // NewT works exactly as New, except that any error will be passed to t.Fatal. 68 func NewT(t *testing.T) (*kivik.Client, *Client) { 69 t.Helper() 70 client, mock, err := New() 71 if err != nil { 72 t.Fatal(err) 73 } 74 return client, mock 75 }