Best Gauge code snippet using util.ListContains
query_test.go
Source:query_test.go
1package query_test2import (3 "context"4 "encoding/json"5 "github.com/Peripli/service-manager/pkg/util"6 "github.com/Peripli/service-manager/pkg/web"7 "net/http"8 "testing"9 "time"10 "github.com/Peripli/service-manager/pkg/query"11 "github.com/Peripli/service-manager/pkg/types"12 "github.com/Peripli/service-manager/storage"13 "github.com/gofrs/uuid"14 "github.com/Peripli/service-manager/pkg/env"15 "github.com/Peripli/service-manager/pkg/sm"16 "github.com/Peripli/service-manager/test/common"17 . "github.com/onsi/ginkgo"18 . "github.com/onsi/gomega"19)20func TestQuery(t *testing.T) {21 RegisterFailHandler(Fail)22 RunSpecs(t, "Query Tests Suite")23}24var _ = Describe("Service Manager Query", func() {25 var ctx *common.TestContext26 var repository storage.Repository27 BeforeSuite(func() {28 ctx = common.NewTestContextBuilder().WithSMExtensions(func(ctx context.Context, smb *sm.ServiceManagerBuilder, e env.Environment) error {29 repository = smb.Storage30 return nil31 }).Build()32 })33 AfterEach(func() {34 if repository != nil {35 err := repository.Delete(context.Background(), types.NotificationType)36 if err != nil {37 expectedErrMsg := "not found"38 Expect(err.Error()).To(Equal(expectedErrMsg))39 }40 }41 })42 AfterSuite(func() {43 if ctx != nil {44 ctx.Cleanup()45 }46 })47 Context("Named Query", func() {48 Context("Service instance and last operations query test", func() {49 var serviceInstance1, serviceInstance2 *types.ServiceInstance50 BeforeEach(func() {51 _, serviceInstance1 = common.CreateInstanceInPlatform(ctx, ctx.TestPlatform.ID)52 _, serviceInstance2 = common.CreateInstanceInPlatform(ctx, ctx.TestPlatform.ID)53 })54 AfterEach(func() {55 ctx.CleanupAdditionalResources()56 })57 It("should return the last operation for a newly created resource", func() {58 queryParams := map[string]interface{}{59 "id_list": []string{serviceInstance1.ID},60 "resource_type": types.ServiceInstanceType,61 }62 list, err := repository.QueryForList(context.Background(), types.OperationType, storage.QueryForLastOperationsPerResource, queryParams)63 Expect(err).ShouldNot(HaveOccurred())64 lastOperation := list.ItemAt(0).(*types.Operation)65 Expect(err).ShouldNot(HaveOccurred())66 Expect(list.Len()).To(BeEquivalentTo(1))67 Expect(lastOperation.State).To(Equal(types.SUCCEEDED))68 Expect(lastOperation.Type).To(Equal(types.CREATE))69 Expect(lastOperation.ResourceID).To(Equal(serviceInstance1.ID))70 })71 When("new operation is created for the resource", func() {72 BeforeEach(func() {73 operation := &types.Operation{74 Base: types.Base{75 ID: "my_test_op_latest",76 CreatedAt: time.Now(),77 UpdatedAt: time.Now(),78 Labels: make(map[string][]string),79 Ready: true,80 },81 Description: "my_test_op_latest",82 Type: types.CREATE,83 State: types.SUCCEEDED,84 ResourceID: serviceInstance1.ID,85 ResourceType: web.ServiceInstancesURL,86 CorrelationID: "test-correlation-id",87 Reschedule: false,88 DeletionScheduled: time.Time{},89 }90 _, err := repository.Create(context.Background(), operation)91 Expect(err).ShouldNot(HaveOccurred())92 })93 It("should return the new operation as last operation", func() {94 queryParams := map[string]interface{}{95 "id_list": []string{serviceInstance1.ID},96 "resource_type": types.ServiceInstanceType,97 }98 list, err := repository.QueryForList(context.Background(), types.OperationType, storage.QueryForLastOperationsPerResource, queryParams)99 Expect(err).ShouldNot(HaveOccurred())100 lastOperation := list.ItemAt(0).(*types.Operation)101 Expect(list.Len()).To(BeEquivalentTo(1))102 Expect(lastOperation.State).To(Equal(types.SUCCEEDED))103 Expect(list.Len()).To(BeEquivalentTo(1))104 Expect(lastOperation.ID).To(Equal("my_test_op_latest"))105 })106 })107 When("Operations exists for other resources", func() {108 BeforeEach(func() {109 operation := &types.Operation{110 Base: types.Base{111 ID: "my_test_op_latest_instance2",112 CreatedAt: time.Now(),113 UpdatedAt: time.Now(),114 Labels: make(map[string][]string),115 Ready: true,116 },117 Description: "my_test_op_latest",118 Type: types.UPDATE,119 State: types.SUCCEEDED,120 ResourceID: serviceInstance2.ID,121 ResourceType: web.ServiceInstancesURL,122 CorrelationID: "test-correlation-id",123 Reschedule: false,124 DeletionScheduled: time.Time{},125 }126 _, err := repository.Create(context.Background(), operation)127 Expect(err).ShouldNot(HaveOccurred())128 })129 It("should return only the last operations associated to the resource in query", func() {130 queryParams := map[string]interface{}{131 "id_list": []string{serviceInstance1.ID},132 "resource_type": types.ServiceInstanceType,133 }134 list, err := repository.QueryForList(context.Background(), types.OperationType, storage.QueryForLastOperationsPerResource, queryParams)135 Expect(err).ShouldNot(HaveOccurred())136 Expect(list.Len()).To(BeEquivalentTo(1))137 Expect(list.ItemAt(0).GetID()).ToNot(Equal("my_test_op_latest_instance2"))138 })139 })140 It("should return the last operation for every instances in the query", func() {141 queryParams := map[string]interface{}{142 "id_list": []string{serviceInstance2.ID, serviceInstance1.ID},143 "resource_type": types.ServiceInstanceType,144 }145 list, err := repository.QueryForList(context.Background(), types.OperationType, storage.QueryForLastOperationsPerResource, queryParams)146 Expect(err).ShouldNot(HaveOccurred())147 Expect(err).ShouldNot(HaveOccurred())148 Expect(list.Len()).To(BeEquivalentTo(2))149 lastOperation1 := list.ItemAt(0).(*types.Operation)150 lastOperation2 := list.ItemAt(1).(*types.Operation)151 Expect(lastOperation1.State).To(Equal(types.SUCCEEDED))152 Expect(lastOperation2.State).To(Equal(types.SUCCEEDED))153 })154 })155 })156 Context("ByExists/ByNotExists SubQuery", func() {157 Context("ByExists", func() {158 When("there are multiple operations for each instance", func() {159 BeforeEach(func() {160 serviceInstance1 := &types.ServiceInstance{161 Base: types.Base{162 ID: "instance1",163 },164 }165 serviceInstance2 := &types.ServiceInstance{166 Base: types.Base{167 ID: "instance2",168 },169 }170 oldestOpForInstance1 := &types.Operation{171 Base: types.Base{172 ID: "oldestOpForInstance1",173 },174 Type: types.CREATE,175 State: types.SUCCEEDED,176 ResourceID: serviceInstance1.ID,177 ResourceType: web.ServiceInstancesURL,178 }179 latestOpForInstance1 := &types.Operation{180 Base: types.Base{181 ID: "latestOpForInstance1",182 },183 Type: types.CREATE,184 State: types.SUCCEEDED,185 ResourceID: serviceInstance1.ID,186 ResourceType: web.ServiceInstancesURL,187 }188 oldestOpForInstance2 := &types.Operation{189 Base: types.Base{190 ID: "oldestOpForInstance2",191 },192 Type: types.CREATE,193 State: types.SUCCEEDED,194 ResourceID: serviceInstance2.ID,195 ResourceType: web.ServiceInstancesURL,196 }197 latestOpForInstance2 := &types.Operation{198 Base: types.Base{199 ID: "latestOpForInstance2",200 },201 Type: types.CREATE,202 State: types.SUCCEEDED,203 ResourceID: serviceInstance2.ID,204 ResourceType: web.ServiceInstancesURL,205 }206 //_, err = repository.Create(context.Background(), serviceInstance1)207 //Expect(err).ShouldNot(HaveOccurred())208 //_, err = repository.Create(context.Background(), serviceInstance2)209 //Expect(err).ShouldNot(HaveOccurred())210 _, err := repository.Create(context.Background(), oldestOpForInstance1)211 Expect(err).ShouldNot(HaveOccurred())212 _, err = repository.Create(context.Background(), latestOpForInstance1)213 Expect(err).ShouldNot(HaveOccurred())214 _, err = repository.Create(context.Background(), oldestOpForInstance2)215 Expect(err).ShouldNot(HaveOccurred())216 _, err = repository.Create(context.Background(), latestOpForInstance2)217 Expect(err).ShouldNot(HaveOccurred())218 })219 AfterEach(func() {220 err := common.RemoveAllInstances(ctx)221 Expect(err).ShouldNot(HaveOccurred())222 common.RemoveAllOperations(ctx.SMRepository)223 })224 It("should return only the operations being last operation for their corresponding instances", func() {225 criteria := []query.Criterion{query.ByExists(storage.GetSubQuery(storage.QueryForAllLastOperationsPerResource))}226 list, err := repository.List(context.Background(), types.OperationType, criteria...)227 Expect(err).ToNot(HaveOccurred())228 Expect(list.Len()).To(BeEquivalentTo(2))229 Expect(listContains(list, "latestOpForInstance1"))230 Expect(listContains(list, "latestOpForInstance2"))231 })232 It("should return only the operations being NOT last operation for their corresponding instances", func() {233 criteria := []query.Criterion{query.BySubquery(query.InSubqueryOperator, "id", storage.GetSubQuery(storage.QueryForAllNotLastOperationsPerResource))}234 list, err := repository.List(context.Background(), types.OperationType, criteria...)235 Expect(err).ToNot(HaveOccurred())236 Expect(list.Len()).To(BeEquivalentTo(2))237 Expect(listContains(list, "oldestOpForInstance1"))238 Expect(listContains(list, "oldestOpForInstance2"))239 })240 })241 })242 Context("ByExists with template parameters", func() {243 When("There is an operation is associated to a resource and another operation that is resource-less", func() {244 BeforeEach(func() {245 resource := &types.Platform{246 Base: types.Base{ID: "test-resource"},247 }248 opForInstance1 := &types.Operation{249 Base: types.Base{250 ID: "opForInstance1",251 },252 Type: types.CREATE,253 State: types.SUCCEEDED,254 ResourceID: "test-resource",255 ResourceType: web.ServiceInstancesURL,256 }257 resourcelessOperation := &types.Operation{258 Base: types.Base{259 ID: "resourcelessOp",260 },261 Type: types.CREATE,262 State: types.SUCCEEDED,263 ResourceID: "NON_EXISTENT_RESOURCE",264 ResourceType: web.ServiceInstancesURL,265 }266 _, err := repository.Create(context.Background(), resource)267 Expect(err).ShouldNot(HaveOccurred())268 _, err = repository.Create(context.Background(), opForInstance1)269 Expect(err).ShouldNot(HaveOccurred())270 _, err = repository.Create(context.Background(), resourcelessOperation)271 Expect(err).ShouldNot(HaveOccurred())272 })273 AfterEach(func() {274 common.RemoveAllPlatforms(ctx.SMRepository)275 err := common.RemoveAllInstances(ctx)276 Expect(err).ShouldNot(HaveOccurred())277 common.RemoveAllOperations(ctx.SMRepository)278 })279 It("should retrieve only the operation that is not associated to a resource", func() {280 params := storage.SubQueryParams{281 "RESOURCE_TABLE": "platforms",282 }283 subQuery, err := storage.GetSubQueryWithParams(storage.QueryForOperationsWithResource, params)284 Expect(err).ToNot(HaveOccurred())285 criterion := query.ByNotExists(subQuery)286 criteria := []query.Criterion{criterion}287 list, err := repository.List(context.Background(), types.OperationType, criteria...)288 Expect(err).ToNot(HaveOccurred())289 Expect(list.Len()).To(BeEquivalentTo(1))290 Expect(listContains(list, "resourcelessOp"))291 })292 It("should retrieve only the operation that is associated to a resource", func() {293 params := storage.SubQueryParams{294 "RESOURCE_TABLE": "platforms",295 }296 subQuery, err := storage.GetSubQueryWithParams(storage.QueryForOperationsWithResource, params)297 Expect(err).ToNot(HaveOccurred())298 criterion := query.ByExists(subQuery)299 criteria := []query.Criterion{criterion}300 list, err := repository.List(context.Background(), types.OperationType, criteria...)301 Expect(err).ToNot(HaveOccurred())302 Expect(list.Len()).To(BeEquivalentTo(1))303 Expect(listContains(list, "opForInstance1"))304 })305 })306 When("There are tenant specific services", func() {307 var tenantServiceMap map[string]interface{}308 BeforeEach(func() {309 tenantPlan := common.GenerateFreeTestPlan()310 globalPlan := common.GenerateFreeTestPlan()311 tenantService := common.GenerateTestServiceWithPlans(tenantPlan)312 globalService := common.GenerateTestServiceWithPlans(globalPlan)313 tenantServiceMap = make(map[string]interface{})314 if err := json.Unmarshal([]byte(tenantService), &tenantServiceMap); err != nil {315 panic(err)316 }317 tenantCatalog := common.NewEmptySBCatalog()318 tenantCatalog.AddService(tenantService)319 labels := common.Object{320 "labels": common.Object{321 "tenant_id": common.Array{"tenant_id_value"},322 },323 }324 ctx.RegisterBrokerWithCatalogAndLabels(tenantCatalog, labels, http.StatusCreated)325 globalCatalog := common.NewEmptySBCatalog()326 globalCatalog.AddService(globalService)327 ctx.RegisterBrokerWithCatalog(globalCatalog)328 })329 AfterEach(func() {330 err := common.RemoveAllInstances(ctx)331 Expect(err).ShouldNot(HaveOccurred())332 common.RemoveAllOperations(ctx.SMRepository)333 })334 It("should find query for tenant scoped service offerings", func() {335 params := storage.SubQueryParams{336 "TENANT_KEY": "tenant_id",337 }338 subQuery, err := storage.GetSubQueryWithParams(storage.QueryForTenantScopedServiceOfferings, params)339 Expect(err).ToNot(HaveOccurred())340 criteria := []query.Criterion{query.ByExists(subQuery)}341 list, err := repository.List(context.Background(), types.ServiceOfferingType, criteria...)342 Expect(err).ToNot(HaveOccurred())343 Expect(list.Len()).To(BeEquivalentTo(1))344 service := list.ItemAt(0).(*types.ServiceOffering)345 Expect(service.CatalogID).To(Equal(tenantServiceMap["id"]))346 })347 })348 })349 })350 Context("Query Notifications", func() {351 Context("with 2 notification created at different times", func() {352 var now time.Time353 var id1, id2 string354 BeforeEach(func() {355 now = time.Now()356 id1 = createNotification(repository, now)357 id2 = createNotification(repository, now.Add(-30*time.Minute))358 })359 It("notifications older than the provided time should not be found", func() {360 operand := util.ToRFCNanoFormat(now.Add(-time.Hour))361 criteria := query.ByField(query.LessThanOperator, "created_at", operand)362 list := queryNotification(repository, criteria)363 expectNotifications(list)364 })365 It("only 1 should be older than the provided time", func() {366 operand := util.ToRFCNanoFormat(now.Add(-20 * time.Minute))367 criteria := query.ByField(query.LessThanOperator, "created_at", operand)368 list := queryNotification(repository, criteria)369 expectNotifications(list, id2)370 })371 It("2 notifications should be found newer than the provided time", func() {372 operand := util.ToRFCNanoFormat(now.Add(-time.Hour))373 criteria := query.ByField(query.GreaterThanOperator, "created_at", operand)374 list := queryNotification(repository, criteria)375 expectNotifications(list, id1, id2)376 })377 It("only 1 notifications should be found newer than the provided time", func() {378 operand := util.ToRFCNanoFormat(now.Add(-10 * time.Minute))379 criteria := query.ByField(query.GreaterThanOperator, "created_at", operand)380 list := queryNotification(repository, criteria)381 expectNotifications(list, id1)382 })383 It("no notifications should be found newer than the last one created", func() {384 operand := util.ToRFCNanoFormat(now.Add(10 * time.Minute))385 criteria := query.ByField(query.GreaterThanOperator, "created_at", operand)386 list := queryNotification(repository, criteria)387 expectNotifications(list)388 })389 })390 })391})392func expectNotifications(list types.ObjectList, ids ...string) {393 Expect(list.Len()).To(Equal(len(ids)))394 for i := 0; i < list.Len(); i++ {395 Expect(ids).To(ContainElement(list.ItemAt(i).GetID()))396 }397}398func createNotification(repository storage.Repository, createdAt time.Time) string {399 uid, err := uuid.NewV4()400 Expect(err).ShouldNot(HaveOccurred())401 notification := &types.Notification{402 Base: types.Base{403 ID: uid.String(),404 CreatedAt: createdAt,405 Ready: true,406 },407 Payload: []byte("{}"),408 Resource: "empty",409 Type: "CREATED",410 }411 _, err = repository.Create(context.Background(), notification)412 Expect(err).ShouldNot(HaveOccurred())413 return notification.ID414}415func listContains(list types.ObjectList, itemId string) bool {416 for i := 0; i < list.Len(); i++ {417 if list.ItemAt(i).GetID() == itemId {418 return true419 }420 }421 return false422}423func queryNotification(repository storage.Repository, criterias ...query.Criterion) types.ObjectList {424 list, err := repository.List(context.Background(), types.NotificationType, criterias...)425 Expect(err).ShouldNot(HaveOccurred())426 return list427}...
describe_test.go
Source:describe_test.go
...38func testDeleteAll(t *testing.T, td *testData) {39 // Delete volume. Only clone and snapshot must exist40 test.PxTestDeleteVolume(t, td.volName)41 vols := test.PxTestGetAllVolumes(t)42 assert.False(t, util.ListContains(vols, td.volName), "Volume delete failed")43 assert.True(t, util.ListContains(vols, td.snapName), "Volume delete failed")44 assert.True(t, util.ListContains(vols, td.cloneName), "Volume delete failed")45 // Delete clone, Only snapshot must exist46 test.PxTestDeleteVolume(t, td.cloneName)47 vols = test.PxTestGetAllVolumes(t)48 assert.False(t, util.ListContains(vols, td.volName), "Volume delete failed")49 assert.False(t, util.ListContains(vols, td.cloneName), "Volume delete failed")50 assert.True(t, util.ListContains(vols, td.snapName), "Volume delete failed")51 // Delete clone, Only snapshot must exist52 test.PxTestDeleteVolume(t, td.snapName)53 vols = test.PxTestGetAllVolumes(t)54 assert.False(t, util.ListContains(vols, td.volName), "Volume delete failed")55 assert.False(t, util.ListContains(vols, td.cloneName), "Volume delete failed")56 assert.False(t, util.ListContains(vols, td.snapName), "Volume delete failed")57}58func getKeyValue(s string) (string, string) {59 x := strings.Split(s, ":")60 x[0] = strings.Trim(x[0], " ")61 x[1] = strings.Trim(x[1], " ")62 return x[0], x[1]63}64func verifyKeyValue(65 t *testing.T,66 key string,67 value string,68 expectedKey string,69 expectedValue string,70) {...
misc_test.go
Source:misc_test.go
...67 if IsMap(object) {68 t.Errorf("IsSlice test failure")69 }70}71func TestListContains(t *testing.T) {72 if !ListContains([]string{"foo", "bar"}, "foo") {73 t.Errorf("ListContains test failure")74 }75 if ListContains([]string{"foo", "bar"}, "spam") {76 t.Errorf("ListContains test failure")77 }78 if ListContains(nil, "foo") {79 t.Errorf("ListContains test failure")80 }81}82func TestMaxLineLength(t *testing.T) {83 lines := []string{"12345", "1234567890"}84 if MaxLineLength(lines) != 10 {85 t.Errorf("MaxLineLength test failure")86 }87}88func TestRemoveBlankLines(t *testing.T) {89 expected := "foo\nbar"90 actual := RemoveBlankLines("foo\n\nbar")91 if expected != actual {92 t.Errorf("Error removing blank lines: '%s' != '%s'", expected, actual)93 }...
ListContains
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello World!")4 fmt.Println(util.ListContains([]string{"a", "b", "c"}, "b"))5 fmt.Println(util.ListContains([]string{"a", "b", "c"}, "d"))6}7func ListContains(list []string, str string) bool {8 for _, v := range list {9 if v == str {10 }11 }12}13import "util"
ListContains
Using AI Code Generation
1import (2func main() {3 list := []string{"one", "two", "three"}4 exists := util.ListContains(list, "two")5 fmt.Printf("Exists: %v6}7func ListContains(list []string, value string) bool {8 for _, v := range list {9 if v == value {10 }11 }12}
ListContains
Using AI Code Generation
1import (2func main() {3 var a = []int{1, 2, 3, 4}4 fmt.Println(util.ListContains(a, b))5}6func ListContains(a []int, b int) bool {7 for _, v := range a {8 if v == b {9 }10 }11}12import (13func main() {14 var a = []int{1, 2, 3, 4}
ListContains
Using AI Code Generation
1import (2func main() {3 fmt.Println(util.ListContains([]string{"hello", "world"}, "hello"))4}5func ListContains(list []string, item string) bool {6 for _, i := range list {7 if i == item {8 }9 }10}11 /usr/local/go/src/github.com/mypackage/util (from $GOROOT)12 /Users/username/go/src/github.com/mypackage/util (from $GOPATH)13 /usr/local/go/src/github.com/mypackage/util (from $GOROOT)
ListContains
Using AI Code Generation
1import (2func main() {3 list := []int{1, 2, 3}4 fmt.Println(util.ListContains(list, 3))5}6Related Posts: Golang: How to use the rand.Intn() method?7Golang: How to use the rand.Seed() method?8Golang: How to use the rand.Float64() method?9Golang: How to use the rand.Float32() method?10Golang: How to use the rand.Int() method?11Golang: How to use the rand.Int31() method?12Golang: How to use the rand.Int31n() method?13Golang: How to use the rand.Int63() method?14Golang: How to use the rand.Int63n() method?15Golang: How to use the rand.Uint32() method?16Golang: How to use the rand.Uint64() method?17Golang: How to use the rand.Read() method?18Golang: How to use the rand.Shuffle() method?19Golang: How to use the rand.Perm() method?20Golang: How to use the rand.New() method?21Golang: How to use the rand.NewSource() method?22Golang: How to use the rand.NewSource() method?23Golang: How to use the rand.New() method?24Golang: How to use the rand.Perm() method?25Golang: How to use the rand.Shuffle() method?26Golang: How to use the rand.Read() method?27Golang: How to use the rand.Uint64() method?28Golang: How to use the rand.Uint32() method?29Golang: How to use the rand.Int63n() method?30Golang: How to use the rand.Int63() method?31Golang: How to use the rand.Int31n() method?32Golang: How to use the rand.Int31() method?33Golang: How to use the rand.Int() method?34Golang: How to use the rand.Float32() method?35Golang: How to use the rand.Float64() method?36Golang: How to use the rand.Seed() method?37Golang: How to use the rand.Intn() method?38Golang: How to use the math.Abs() method?39Golang: How to use the math.Abs() method?
ListContains
Using AI Code Generation
1if util.ListContains(list, "foo") {2 println("foo is in the list")3}4func ListContains(list []string, s string) bool {5 for _, item := range list {6 if item == s {7 }8 }9}10import (11func main() {12 list := []string{"foo", "bar", "baz"}13 if util.ListContains(list, "foo") {14 fmt.Println("foo is in the list")15 }16}
ListContains
Using AI Code Generation
1import (2func main() {3 var list = []string{"a", "b", "c", "d"}4 var contains = util.ListContains(list, "a")5 fmt.Println(contains)6}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!