github.com/go-kivik/kivik/v4@v4.3.2/mockdb/helpers.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 "bytes" 17 "encoding/json" 18 "io/ioutil" 19 "testing" 20 21 "github.com/go-kivik/kivik/v4/driver" 22 ) 23 24 // DocumentT calls Document, and passes any error to t.Fatal. 25 func DocumentT(t *testing.T, i interface{}) *driver.Document { 26 t.Helper() 27 doc, err := Document(i) 28 if err != nil { 29 t.Fatal(err) 30 } 31 return doc 32 } 33 34 // Document converts i, which should be of a supported type (see below), into 35 // a document which can be passed to ExpectedGet.WillReturn(). 36 // 37 // i is checked against the following list of types, in order. If no match 38 // is found, an error is returned. Attachments is not populated by this method. 39 // 40 // - string, []byte, or json.RawMessage (interpreted as a JSON string) 41 // - io.Reader (assumes JSON can be read from the stream) 42 // - any other JSON-marshalable object 43 func Document(i interface{}) (*driver.Document, error) { 44 buf, err := toJSON(i) 45 if err != nil { 46 return nil, err 47 } 48 var meta struct { 49 Rev string `json:"_rev"` 50 } 51 if err := json.Unmarshal(buf, &meta); err != nil { 52 return nil, err 53 } 54 return &driver.Document{ 55 Rev: meta.Rev, 56 Body: ioutil.NopCloser(bytes.NewReader(buf)), 57 Attachments: nil, 58 }, nil 59 } 60 61 func toJSON(i interface{}) ([]byte, error) { 62 switch t := i.(type) { 63 case string: 64 return []byte(t), nil 65 case []byte: 66 return t, nil 67 case json.RawMessage: 68 return t, nil 69 } 70 buf := &bytes.Buffer{} 71 err := json.NewEncoder(buf).Encode(i) 72 return buf.Bytes(), err 73 }