get.porter.sh/porter@v1.3.0/pkg/storage/query_test.go (about) 1 package storage 2 3 import ( 4 "encoding/json" 5 "testing" 6 7 "github.com/stretchr/testify/require" 8 "go.mongodb.org/mongo-driver/bson" 9 "go.mongodb.org/mongo-driver/bson/primitive" 10 ) 11 12 var _ Document = TestDocument{} 13 var _ json.Marshaler = TestDocument{} 14 15 type TestDocument struct { 16 SomeName string 17 } 18 19 func (t TestDocument) MarshalJSON() ([]byte, error) { 20 raw := map[string]interface{}{ 21 "_id": t.SomeName + "id", 22 "name": t.SomeName, 23 } 24 return json.Marshal(raw) 25 } 26 27 func (t TestDocument) DefaultDocumentFilter() map[string]interface{} { 28 return map[string]interface{}{"name": t.SomeName} 29 } 30 31 func TestInsertOptions_ToPluginOptions(t *testing.T) { 32 // Test that when we insert documents that we first go through 33 // its json representation, so that the fields have the right 34 // names based on the json tag, and that any custom json marshaling 35 // is used. 36 37 docA := TestDocument{SomeName: "a"} 38 docB := TestDocument{SomeName: "b"} 39 opts := InsertOptions{Documents: []interface{}{docA, docB}} 40 gotOpts, err := opts.ToPluginOptions("mydocs") 41 require.NoError(t, err) 42 43 wantRawDocs := []bson.M{ 44 {"_id": "aid", "name": "a"}, 45 {"_id": "bid", "name": "b"}, 46 } 47 48 require.Equal(t, wantRawDocs, gotOpts.Documents) 49 } 50 51 func TestUpdateOptions_ToPluginOptions(t *testing.T) { 52 // Test that when we update documents that we first go through 53 // its json representation, so that the fields have the right 54 // names based on the json tag, and that any custom json marshaling 55 // is used. 56 57 doc := TestDocument{SomeName: "a"} 58 opts := UpdateOptions{Document: doc} 59 gotOpts, err := opts.ToPluginOptions("mydocs") 60 require.NoError(t, err) 61 62 wantRawDoc := bson.M{"_id": "aid", "name": "a"} 63 require.Equal(t, wantRawDoc, gotOpts.Document) 64 } 65 66 func TestFindOptions_ToPluginOptions(t *testing.T) { 67 so := FindOptions{ 68 Sort: []string{"-_id", "name"}, 69 } 70 po := so.ToPluginOptions("mythings") 71 wantSortDoc := bson.D{ 72 {Key: "_id", Value: -1}, 73 {Key: "name", Value: 1}} 74 require.Equal(t, wantSortDoc, po.Sort) 75 } 76 77 func TestListOptions_ToFindOptions(t *testing.T) { 78 opts := ListOptions{ 79 Namespace: "dev", 80 Name: "name", 81 Labels: map[string]string{"key": "value"}, 82 Skip: 1, 83 Limit: 1, 84 } 85 86 wantOpts := FindOptions{ 87 Sort: []string{"namespace", "name"}, 88 Skip: 1, 89 Limit: 1, 90 Filter: primitive.M{ 91 "labels.key": "value", 92 "name": map[string]interface{}{"$regex": "name"}, 93 "namespace": "dev", 94 }, 95 } 96 97 gotOpts := opts.ToFindOptions() 98 require.Equal(t, wantOpts, gotOpts) 99 }