github.com/billybanfield/evergreen@v0.0.0-20170525200750-eeee692790f7/db/query_test.go (about) 1 package db 2 3 import ( 4 "testing" 5 6 . "github.com/smartystreets/goconvey/convey" 7 "gopkg.in/mgo.v2/bson" 8 ) 9 10 func TestQueryExecution(t *testing.T) { 11 12 type insertableStruct struct { 13 FieldOne string `bson:"one"` 14 FieldTwo int `bson:"two"` 15 FieldThree string `bson:"three"` 16 } 17 SetGlobalSessionProvider(SessionFactoryFromConfig(dbUtilsTestConf)) 18 collection := "test_query_collection" 19 20 Convey("With a db and collection", t, func() { 21 Convey("inserting a single item into the collection", func() { 22 So(Clear(collection), ShouldBeNil) 23 in := &insertableStruct{ 24 FieldOne: "1", 25 FieldTwo: 1, 26 } 27 So(Insert(collection, in), ShouldBeNil) 28 29 Convey("the item should be findable with a Query", func() { 30 out := &insertableStruct{} 31 query := Query(bson.M{"one": "1"}) 32 err := FindOneQ(collection, query, out) 33 So(err, ShouldBeNil) 34 So(out, ShouldResemble, in) 35 }) 36 }) 37 Convey("inserting a multiple items into the collection", func() { 38 So(Clear(collection), ShouldBeNil) 39 objs := []insertableStruct{ 40 {"X", 1, ""}, 41 {"X", 2, ""}, 42 {"X", 3, ""}, 43 {"X", 4, ""}, 44 {"X", 5, ""}, 45 {"X", 6, ""}, 46 {"X", 7, "COOL"}, 47 } 48 for _, in := range objs { 49 So(Insert(collection, in), ShouldBeNil) 50 } 51 52 BelowFive := Query(bson.M{"two": bson.M{"$lt": 5}}) 53 BelowFiveSorted := BelowFive.Sort([]string{"-two"}) 54 BelowFiveLimit := BelowFive.Limit(2).Skip(1) 55 JustOneField := Query(bson.M{"two": 7}).Project(bson.D{{"three", 1}}) 56 57 Convey("BelowFive should return 4 documents", func() { 58 out := []insertableStruct{} 59 err := FindAllQ(collection, BelowFive, &out) 60 So(err, ShouldBeNil) 61 So(len(out), ShouldEqual, 4) 62 }) 63 64 Convey("BelowFiveSorted should return 4 documents, sorted in reverse", func() { 65 out := []insertableStruct{} 66 err := FindAllQ(collection, BelowFiveSorted, &out) 67 So(err, ShouldBeNil) 68 So(len(out), ShouldEqual, 4) 69 So(out[0].FieldTwo, ShouldEqual, 4) 70 So(out[1].FieldTwo, ShouldEqual, 3) 71 So(out[2].FieldTwo, ShouldEqual, 2) 72 So(out[3].FieldTwo, ShouldEqual, 1) 73 }) 74 75 Convey("BelowFiveLimit should return 2 documents", func() { 76 out := []insertableStruct{} 77 err := FindAllQ(collection, BelowFiveLimit, &out) 78 So(err, ShouldBeNil) 79 So(len(out), ShouldEqual, 2) 80 }) 81 82 Convey("JustOneField should return 1 document", func() { 83 out := []bson.M{} 84 err := FindAllQ(collection, JustOneField, &out) 85 So(err, ShouldBeNil) 86 So(out[0]["three"], ShouldEqual, "COOL") 87 }) 88 }) 89 }) 90 }