How to use TestLogger method of api Package

Best K6 code snippet using api.TestLogger

service_instances_test.go

Source:service_instances_test.go Github

copy

Full Screen

1package cf_test2import (3 "errors"4 "fmt"5 "io"6 "log"7 "net/http"8 "regexp"9 "github.com/pivotal-cf/on-demand-service-broker/mockhttp"10 "github.com/pivotal-cf/on-demand-service-broker/mockhttp/mockcfapi"11 . "github.com/onsi/ginkgo"12 . "github.com/onsi/gomega"13 "github.com/onsi/gomega/gbytes"14 "github.com/onsi/gomega/ghttp"15 "github.com/pivotal-cf/on-demand-service-broker/cf"16 "github.com/pivotal-cf/on-demand-service-broker/cf/fakes"17)18var _ = Describe("ServiceInstancesClient", func() {19 var (20 server *mockhttp.Server21 testLogger *log.Logger22 logBuffer *gbytes.Buffer23 authHeaderBuilder *fakes.FakeAuthHeaderBuilder24 cfApi *ghttp.Server25 )26 const (27 cfAuthorizationHeader = "auth-header"28 serviceGUID = "06df08f9-5a58-4d33-8097-32d0baf3ce1e"29 )30 BeforeEach(func() {31 authHeaderBuilder = new(fakes.FakeAuthHeaderBuilder)32 authHeaderBuilder.AddAuthHeaderStub = func(req *http.Request, logger *log.Logger) error {33 req.Header.Set("Authorization", cfAuthorizationHeader)34 return nil35 }36 server = mockcfapi.New()37 logBuffer = gbytes.NewBuffer()38 testLogger = log.New(io.MultiWriter(logBuffer, GinkgoWriter), "service-instances-test", log.LstdFlags)39 cfApi = ghttp.NewServer()40 })41 AfterEach(func() {42 server.VerifyMocks()43 })44 Describe("GetServiceInstance", func() {45 It("successfully gets a service instance", func() {46 cfApi.AppendHandlers(ghttp.CombineHandlers(47 ghttp.VerifyRequest(http.MethodGet, "/v2/service_instances/fake-service-instance-guid"),48 ghttp.RespondWith(49 http.StatusOK,50 `{51 "metadata": {52 "guid": "fake-service-instance-guid"53 },54 "entity": {55 "space_guid": "space-id",56 "service_plan_url": "fake-url",57 "maintenance_info": {58 "version": "1.2.3"59 },60 "last_operation": {61 "type": "fake-type",62 "state": "fake-state"63 }64 }65 }`,66 ),67 ))68 client, err := cf.New(cfApi.URL(), authHeaderBuilder, nil, true, testLogger)69 Expect(err).NotTo(HaveOccurred())70 instance, err := client.GetServiceInstance("fake-service-instance-guid", testLogger)71 Expect(err).NotTo(HaveOccurred())72 Expect(instance).To(Equal(cf.ServiceInstanceResource{73 Metadata: cf.Metadata{74 GUID: "fake-service-instance-guid",75 },76 Entity: cf.ServiceInstanceEntity{77 SpaceGUID: "space-id",78 ServicePlanURL: "fake-url",79 MaintenanceInfo: cf.MaintenanceInfo{80 Version: "1.2.3",81 },82 LastOperation: cf.LastOperation{83 Type: "fake-type",84 State: "fake-state",85 },86 },87 }))88 })89 It("returns an error when getting the service instance failed", func() {90 cfApi.AppendHandlers(ghttp.CombineHandlers(91 ghttp.VerifyRequest(http.MethodGet, "/v2/service_instances/fake-service-instance-guid"),92 ghttp.RespondWith(http.StatusInternalServerError, ""),93 ))94 client, err := cf.New(cfApi.URL(), authHeaderBuilder, nil, true, testLogger)95 Expect(err).NotTo(HaveOccurred())96 _, err = client.GetServiceInstance("fake-service-instance-guid", testLogger)97 Expect(err).To(MatchError(ContainSubstring("Unexpected reponse status 500")))98 })99 })100 Describe("GetServiceInstances", func() {101 It("returns a list of instances filtered by the service offering", func() {102 offeringID := "8F3E8998-5FD0-4F32-924A-5478DC390A5F"103 server.VerifyAndMock(104 mockcfapi.ListServiceOfferings().WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_services_response.json")),105 mockcfapi.ListServicePlans("34c08156-5b5d-4cc1-9af1-29cda9ec056f").WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_plans_response.json")),106 mockcfapi.ListServiceInstances("ff717e7c-afd5-4d0a-bafe-16c7eff546ec").WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_instances_for_plan_1_response.json")),107 mockcfapi.ListServiceInstances("2777ad05-8114-4169-8188-2ef5f39e0c6b").WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_instances_for_plan_2_response.json")),108 )109 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)110 Expect(err).NotTo(HaveOccurred())111 instances, err := client.GetServiceInstances(cf.GetInstancesFilter{ServiceOfferingID: offeringID}, testLogger)112 Expect(err).NotTo(HaveOccurred())113 Expect(instances).To(ConsistOf(114 cf.Instance{GUID: "520f8566-b727-4c67-8be8-d9285645e936", PlanUniqueID: "11789210-D743-4C65-9D38-C80B29F4D9C8", SpaceGUID: "a157c861-92bb-4f57-9108-f791260f66ab"},115 cf.Instance{GUID: "f897f40d-0b2d-474a-a5c9-98426a2cb4b8", PlanUniqueID: "22789210-D743-4C65-9D38-C80B29F4D9C8", SpaceGUID: "a157c861-92bb-4f57-9108-f791260f66ab"},116 cf.Instance{GUID: "2f759033-04a4-426b-bccd-01722036c152", PlanUniqueID: "22789210-D743-4C65-9D38-C80B29F4D9C8", SpaceGUID: "a157c861-92bb-4f57-9108-f791260f66ab"},117 ))118 })119 Context("when the list of services spans multiple pages", func() {120 It("returns a list of instance IDs", func() {121 offeringID := "D94A086D-203D-4966-A6F1-60A9E2300F72"122 server.VerifyAndMock(123 mockcfapi.ListServiceOfferings().WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_services_response_page_1.json")),124 mockcfapi.ListServiceOfferingsForPage(2).WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_services_response_page_2.json")),125 mockcfapi.ListServicePlans(serviceGUID).WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_plans_response.json")),126 mockcfapi.ListServiceInstances("ff717e7c-afd5-4d0a-bafe-16c7eff546ec").WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_instances_for_plan_1_response.json")),127 mockcfapi.ListServiceInstances("2777ad05-8114-4169-8188-2ef5f39e0c6b").WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_instances_for_plan_2_response.json")),128 )129 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)130 Expect(err).NotTo(HaveOccurred())131 instances, err := client.GetServiceInstances(cf.GetInstancesFilter{ServiceOfferingID: offeringID}, testLogger)132 Expect(err).NotTo(HaveOccurred())133 Expect(instances).To(ConsistOf(134 cf.Instance{135 GUID: "520f8566-b727-4c67-8be8-d9285645e936",136 PlanUniqueID: "11789210-D743-4C65-9D38-C80B29F4D9C8",137 SpaceGUID: "a157c861-92bb-4f57-9108-f791260f66ab",138 },139 cf.Instance{140 GUID: "f897f40d-0b2d-474a-a5c9-98426a2cb4b8",141 PlanUniqueID: "22789210-D743-4C65-9D38-C80B29F4D9C8",142 SpaceGUID: "a157c861-92bb-4f57-9108-f791260f66ab",143 },144 cf.Instance{145 GUID: "2f759033-04a4-426b-bccd-01722036c152",146 PlanUniqueID: "22789210-D743-4C65-9D38-C80B29F4D9C8",147 SpaceGUID: "a157c861-92bb-4f57-9108-f791260f66ab",148 },149 ))150 })151 })152 Context("when the list of plans spans multiple pages", func() {153 It("returns a list of instance IDs", func() {154 offeringID := "D94A086D-203D-4966-A6F1-60A9E2300F72"155 server.VerifyAndMock(156 mockcfapi.ListServiceOfferings().WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_services_response.json")),157 mockcfapi.ListServicePlans(serviceGUID).WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_plans_response_page_1.json")),158 mockcfapi.ListServicePlansForPage(serviceGUID, 2).WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_plans_response_page_2.json")),159 mockcfapi.ListServiceInstances("ff717e7c-afd5-4d0a-bafe-16c7eff546ec").WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_instances_for_plan_1_response.json")),160 mockcfapi.ListServiceInstances("2777ad05-8114-4169-8188-2ef5f39e0c6b").WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_instances_for_plan_2_response.json")),161 )162 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)163 Expect(err).NotTo(HaveOccurred())164 instances, err := client.GetServiceInstances(cf.GetInstancesFilter{ServiceOfferingID: offeringID}, testLogger)165 Expect(err).NotTo(HaveOccurred())166 Expect(instances).To(ConsistOf(167 cf.Instance{168 GUID: "520f8566-b727-4c67-8be8-d9285645e936",169 PlanUniqueID: "11789210-D743-4C65-9D38-C80B29F4D9C8",170 SpaceGUID: "a157c861-92bb-4f57-9108-f791260f66ab",171 },172 cf.Instance{173 GUID: "f897f40d-0b2d-474a-a5c9-98426a2cb4b8",174 PlanUniqueID: "22789210-D743-4C65-9D38-C80B29F4D9C8",175 SpaceGUID: "a157c861-92bb-4f57-9108-f791260f66ab",176 },177 cf.Instance{178 GUID: "2f759033-04a4-426b-bccd-01722036c152",179 PlanUniqueID: "22789210-D743-4C65-9D38-C80B29F4D9C8",180 SpaceGUID: "a157c861-92bb-4f57-9108-f791260f66ab",181 },182 ))183 })184 })185 Context("when the list of instances spans multiple pages", func() {186 It("returns a list of instance IDs", func() {187 offeringID := "D94A086D-203D-4966-A6F1-60A9E2300F72"188 server.VerifyAndMock(189 mockcfapi.ListServiceOfferings().WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_services_response.json")),190 mockcfapi.ListServicePlans(serviceGUID).WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_plans_response.json")),191 mockcfapi.ListServiceInstances("ff717e7c-afd5-4d0a-bafe-16c7eff546ec").WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_instances_for_plan_1_response.json")),192 mockcfapi.ListServiceInstances("2777ad05-8114-4169-8188-2ef5f39e0c6b").WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_instances_for_plan_2_page_1.json")),193 mockcfapi.ListServiceInstancesForPage("2777ad05-8114-4169-8188-2ef5f39e0c6b", 2).WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_instances_for_plan_2_page_2.json")),194 )195 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)196 Expect(err).NotTo(HaveOccurred())197 instances, err := client.GetServiceInstances(cf.GetInstancesFilter{ServiceOfferingID: offeringID}, testLogger)198 Expect(err).NotTo(HaveOccurred())199 Expect(instances).To(ConsistOf(200 cf.Instance{201 GUID: "520f8566-b727-4c67-8be8-d9285645e936",202 PlanUniqueID: "11789210-D743-4C65-9D38-C80B29F4D9C8",203 SpaceGUID: "a157c861-92bb-4f57-9108-f791260f66ab",204 },205 cf.Instance{206 GUID: "f897f40d-0b2d-474a-a5c9-98426a2cb4b8",207 PlanUniqueID: "22789210-D743-4C65-9D38-C80B29F4D9C8",208 SpaceGUID: "a157c861-92bb-4f57-9108-f791260f66ab",209 },210 cf.Instance{211 GUID: "2f759033-04a4-426b-bccd-01722036c152",212 PlanUniqueID: "22789210-D743-4C65-9D38-C80B29F4D9C8",213 SpaceGUID: "a157c861-92bb-4f57-9108-f791260f66ab",214 },215 ))216 })217 })218 It("when there are no instances, returns an empty list of instances", func() {219 offeringID := "D94A086D-203D-4966-A6F1-60A9E2300F72"220 server.VerifyAndMock(221 mockcfapi.ListServiceOfferings().WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_services_response.json")),222 mockcfapi.ListServicePlans(serviceGUID).WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_plans_response.json")),223 mockcfapi.ListServiceInstances("ff717e7c-afd5-4d0a-bafe-16c7eff546ec").WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_instances_empty_response.json")),224 mockcfapi.ListServiceInstances("2777ad05-8114-4169-8188-2ef5f39e0c6b").WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_instances_empty_response.json")),225 )226 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)227 Expect(err).NotTo(HaveOccurred())228 instances, err := client.GetServiceInstances(cf.GetInstancesFilter{ServiceOfferingID: offeringID}, testLogger)229 Expect(err).NotTo(HaveOccurred())230 Expect(instances).To(Equal([]cf.Instance{}))231 })232 Context("when the list of services cannot be retrieved", func() {233 It("returns an error", func() {234 offeringID := "8F3E8998-5FD0-4F32-924A-5478DC390A5F"235 server.VerifyAndMock(236 mockcfapi.ListServiceOfferings().WithAuthorizationHeader(cfAuthorizationHeader).RespondsInternalServerErrorWith("oops"),237 )238 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)239 Expect(err).NotTo(HaveOccurred())240 _, err = client.GetServiceInstances(cf.GetInstancesFilter{ServiceOfferingID: offeringID}, testLogger)241 Expect(err).To(MatchError(ContainSubstring("oops")))242 })243 })244 Context("when the list of plans for the service cannot be retrieved", func() {245 It("returns an error", func() {246 offeringID := "8F3E8998-5FD0-4F32-924A-5478DC390A5F"247 server.VerifyAndMock(248 mockcfapi.ListServiceOfferings().WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_services_response.json")),249 mockcfapi.ListServicePlans("34c08156-5b5d-4cc1-9af1-29cda9ec056f").WithAuthorizationHeader(cfAuthorizationHeader).RespondsInternalServerErrorWith("oops"),250 )251 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)252 Expect(err).NotTo(HaveOccurred())253 _, err = client.GetServiceInstances(cf.GetInstancesFilter{ServiceOfferingID: offeringID}, testLogger)254 Expect(err).To(MatchError(ContainSubstring("oops")))255 })256 })257 Context("when the list of instances for a plan cannot be retrieved", func() {258 It("returns an error", func() {259 offeringID := "8F3E8998-5FD0-4F32-924A-5478DC390A5F"260 server.VerifyAndMock(261 mockcfapi.ListServiceOfferings().WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_services_response.json")),262 mockcfapi.ListServicePlans("34c08156-5b5d-4cc1-9af1-29cda9ec056f").WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_plans_response.json")),263 mockcfapi.ListServiceInstances("ff717e7c-afd5-4d0a-bafe-16c7eff546ec").WithAuthorizationHeader(cfAuthorizationHeader).RespondsInternalServerErrorWith("oops"),264 )265 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)266 Expect(err).NotTo(HaveOccurred())267 _, err = client.GetServiceInstances(cf.GetInstancesFilter{ServiceOfferingID: offeringID}, testLogger)268 Expect(err).To(MatchError(ContainSubstring("oops")))269 })270 })271 Context("filtering by service offering, org and space", func() {272 var (273 orgName, spaceName, orgGuid, spaceGuid string274 )275 BeforeEach(func() {276 orgName = "cf-org"277 spaceName = "cf-space"278 orgGuid = "an-org-guid"279 spaceGuid = "a-space-guid"280 })281 It("returns a list of instances, filtered by org and spaces", func() {282 offeringID := "8F3E8998-5FD0-4F32-924A-5478DC390A5F"283 server.VerifyAndMock(284 mockcfapi.ListServiceOfferings().WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_services_response.json")),285 mockcfapi.ListServicePlans("34c08156-5b5d-4cc1-9af1-29cda9ec056f").WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_plans_response.json")),286 mockcfapi.ListOrg(orgName).WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("org_response.json")),287 mockcfapi.ListOrgSpace(orgGuid, spaceName).WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("space_response.json")),288 mockcfapi.ListServiceInstancesBySpace("ff717e7c-afd5-4d0a-bafe-16c7eff546ec", spaceGuid).WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(289 fixture("list_service_instances_for_plan_1_response.json"),290 ),291 mockcfapi.ListServiceInstancesBySpace("2777ad05-8114-4169-8188-2ef5f39e0c6b", spaceGuid).WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(292 fixture("list_service_instances_for_plan_2_response.json"),293 ),294 )295 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)296 Expect(err).NotTo(HaveOccurred())297 instances, err := client.GetServiceInstances(cf.GetInstancesFilter{ServiceOfferingID: offeringID, OrgName: orgName, SpaceName: spaceName}, testLogger)298 Expect(err).NotTo(HaveOccurred())299 Expect(instances).To(ConsistOf(300 cf.Instance{301 GUID: "520f8566-b727-4c67-8be8-d9285645e936",302 PlanUniqueID: "11789210-D743-4C65-9D38-C80B29F4D9C8",303 SpaceGUID: "a157c861-92bb-4f57-9108-f791260f66ab",304 },305 cf.Instance{306 GUID: "f897f40d-0b2d-474a-a5c9-98426a2cb4b8",307 PlanUniqueID: "22789210-D743-4C65-9D38-C80B29F4D9C8",308 SpaceGUID: "a157c861-92bb-4f57-9108-f791260f66ab",309 },310 cf.Instance{311 GUID: "2f759033-04a4-426b-bccd-01722036c152",312 PlanUniqueID: "22789210-D743-4C65-9D38-C80B29F4D9C8",313 SpaceGUID: "a157c861-92bb-4f57-9108-f791260f66ab",314 },315 ))316 })317 It("returns an empty list when the org doesn't exist", func() {318 offeringID := "8F3E8998-5FD0-4F32-924A-5478DC390A5F"319 server.VerifyAndMock(320 mockcfapi.ListServiceOfferings().WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_services_response.json")),321 mockcfapi.ListServicePlans("34c08156-5b5d-4cc1-9af1-29cda9ec056f").WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_plans_response.json")),322 mockcfapi.ListOrg(orgName).WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(`{"resources":[]}`),323 )324 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)325 Expect(err).NotTo(HaveOccurred())326 instances, err := client.GetServiceInstances(cf.GetInstancesFilter{ServiceOfferingID: offeringID, OrgName: orgName, SpaceName: spaceName}, testLogger)327 Expect(err).NotTo(HaveOccurred())328 Expect(instances).To(Equal([]cf.Instance{}))329 })330 It("returns an empty list when the space doesn't exist", func() {331 offeringID := "8F3E8998-5FD0-4F32-924A-5478DC390A5F"332 server.VerifyAndMock(333 mockcfapi.ListServiceOfferings().WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_services_response.json")),334 mockcfapi.ListServicePlans("34c08156-5b5d-4cc1-9af1-29cda9ec056f").WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_plans_response.json")),335 mockcfapi.ListOrg(orgName).WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("org_response.json")),336 mockcfapi.ListOrgSpace(orgGuid, spaceName).WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(`{"resources":[]}`),337 )338 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)339 Expect(err).NotTo(HaveOccurred())340 instances, err := client.GetServiceInstances(cf.GetInstancesFilter{ServiceOfferingID: offeringID, OrgName: orgName, SpaceName: spaceName}, testLogger)341 Expect(err).NotTo(HaveOccurred())342 Expect(instances).To(Equal([]cf.Instance{}))343 })344 Context("error cases", func() {345 It("errors when the space url cannot be retrieved", func() {346 offeringID := "8F3E8998-5FD0-4F32-924A-5478DC390A5F"347 server.VerifyAndMock(348 mockcfapi.ListServiceOfferings().WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_services_response.json")),349 mockcfapi.ListServicePlans("34c08156-5b5d-4cc1-9af1-29cda9ec056f").WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_plans_response.json")),350 mockcfapi.ListOrg(orgName).WithAuthorizationHeader(cfAuthorizationHeader).RespondsInternalServerErrorWith("oops"),351 )352 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)353 Expect(err).NotTo(HaveOccurred())354 _, err = client.GetServiceInstances(cf.GetInstancesFilter{ServiceOfferingID: offeringID, OrgName: orgName, SpaceName: spaceName}, testLogger)355 Expect(err).To(MatchError(ContainSubstring("oops")))356 })357 It("errors when the space guid cannot be retrieved", func() {358 offeringID := "8F3E8998-5FD0-4F32-924A-5478DC390A5F"359 server.VerifyAndMock(360 mockcfapi.ListServiceOfferings().WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_services_response.json")),361 mockcfapi.ListServicePlans("34c08156-5b5d-4cc1-9af1-29cda9ec056f").WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("list_service_plans_response.json")),362 mockcfapi.ListOrg(orgName).WithAuthorizationHeader(cfAuthorizationHeader).RespondsOKWith(fixture("org_response.json")),363 mockcfapi.ListOrgSpace(orgGuid, spaceName).WithAuthorizationHeader(cfAuthorizationHeader).RespondsInternalServerErrorWith("oops"),364 )365 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)366 Expect(err).NotTo(HaveOccurred())367 _, err = client.GetServiceInstances(cf.GetInstancesFilter{ServiceOfferingID: offeringID, OrgName: orgName, SpaceName: spaceName}, testLogger)368 Expect(err).To(MatchError(ContainSubstring("oops")))369 })370 })371 })372 })373 Describe("UpgradeServiceInstance", func() {374 It("returns last operation", func() {375 expectedServiceInstanceGUID := "service-instance-guid"376 serviceInstanceResponse := `377 {378 "entity": {379 "last_operation": {380 "type": "update",381 "state": "in progress"382 }383 }384 }`385 cfApi.RouteToHandler(http.MethodPut, regexp.MustCompile(`/v2/service_instances/*`), ghttp.CombineHandlers(386 ghttp.VerifyRequest(http.MethodPut, fmt.Sprintf(`/v2/service_instances/%s`, expectedServiceInstanceGUID), "accepts_incomplete=true"),387 ghttp.VerifyBody([]byte(`{"maintenance_info":{"version":"1.2.3"}}`)),388 ghttp.RespondWith(http.StatusAccepted, serviceInstanceResponse),389 ))390 client, err := cf.New(cfApi.URL(), authHeaderBuilder, nil, true, testLogger)391 Expect(err).NotTo(HaveOccurred())392 actualResponse, err := client.UpgradeServiceInstance(expectedServiceInstanceGUID, cf.MaintenanceInfo{Version: "1.2.3"}, testLogger)393 Expect(err).NotTo(HaveOccurred())394 Expect(actualResponse.State).To(Equal(cf.OperationStateInProgress))395 })396 It("returns error when CF endpoint returns an unexpected HTTP response code", func() {397 expectedServiceInstanceGUID := "service-instance-guid"398 cfApi.RouteToHandler(http.MethodPut, regexp.MustCompile(`/v2/service_instances/*`), ghttp.CombineHandlers(399 ghttp.VerifyRequest(http.MethodPut, fmt.Sprintf(`/v2/service_instances/%s`, expectedServiceInstanceGUID), "accepts_incomplete=true"),400 ghttp.VerifyBody([]byte(`{"maintenance_info":{"version":"1.2.3"}}`)),401 ghttp.RespondWith(http.StatusInternalServerError, ""),402 ))403 client, err := cf.New(cfApi.URL(), authHeaderBuilder, nil, true, testLogger)404 Expect(err).NotTo(HaveOccurred())405 _, err = client.UpgradeServiceInstance(expectedServiceInstanceGUID, cf.MaintenanceInfo{Version: "1.2.3"}, testLogger)406 Expect(err).To(MatchError(`unexpected response status 500 when upgrading service instance "service-instance-guid"; response body ""`))407 })408 It("returns error when CF endpoint returns invalid JSON", func() {409 cfApi := ghttp.NewServer()410 expectedServiceInstanceGUID := "service-instance-guid"411 cfApi.RouteToHandler(http.MethodPut, regexp.MustCompile(`/v2/service_instances/*`), ghttp.CombineHandlers(412 ghttp.VerifyRequest(http.MethodPut, fmt.Sprintf(`/v2/service_instances/%s`, expectedServiceInstanceGUID), "accepts_incomplete=true"),413 ghttp.VerifyBody([]byte(`{"maintenance_info":{"version":"1.2.3"}}`)),414 ghttp.RespondWith(http.StatusAccepted, "this-is-not-json"),415 ))416 client, err := cf.New(cfApi.URL(), authHeaderBuilder, nil, true, testLogger)417 Expect(err).NotTo(HaveOccurred())418 _, err = client.UpgradeServiceInstance(expectedServiceInstanceGUID, cf.MaintenanceInfo{Version: "1.2.3"}, testLogger)419 Expect(err.Error()).To(ContainSubstring(`failed to de-serialise the response body`))420 })421 })422 Describe("DeleteServiceInstance", func() {423 const serviceInstanceGUID = "596736f1-eee4-4249-a201-e21f00a55209"424 Context("when the request is accepted", func() {425 var err error426 BeforeEach(func() {427 server.VerifyAndMock(428 mockcfapi.DeleteServiceInstance(serviceInstanceGUID).429 WithAuthorizationHeader(cfAuthorizationHeader).430 WithContentType("application/x-www-form-urlencoded").431 RespondsAcceptedWith(""),432 )433 var client cf.Client434 client, err = cf.New(server.URL, authHeaderBuilder, nil, true, nil)435 Expect(err).NotTo(HaveOccurred())436 err = client.DeleteServiceInstance(serviceInstanceGUID, testLogger)437 })438 It("does not return an error", func() {439 Expect(err).ToNot(HaveOccurred())440 })441 It("logs the delete request", func() {442 Expect(logBuffer).To(gbytes.Say("DELETE %s/v2/service_instances/%s\\?accepts_incomplete\\=true", server.URL, serviceInstanceGUID))443 })444 })445 Context("when the response is 404 Not Found", func() {446 It("does not return an error", func() {447 server.VerifyAndMock(448 mockcfapi.DeleteServiceInstance(serviceInstanceGUID).449 WithAuthorizationHeader(cfAuthorizationHeader).450 WithContentType("application/x-www-form-urlencoded").451 RespondsNotFoundWith(`{"foo":"bar"}`),452 )453 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)454 Expect(err).NotTo(HaveOccurred())455 err = client.DeleteServiceInstance(serviceInstanceGUID, testLogger)456 Expect(err).NotTo(HaveOccurred())457 })458 })459 Context("when the response has an unexpected status code", func() {460 It("return the error", func() {461 server.VerifyAndMock(462 mockcfapi.DeleteServiceInstance(serviceInstanceGUID).463 WithAuthorizationHeader(cfAuthorizationHeader).464 WithContentType("application/x-www-form-urlencoded").465 RespondsForbiddenWith(`{"foo":"bar"}`),466 )467 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)468 Expect(err).NotTo(HaveOccurred())469 err = client.DeleteServiceInstance(serviceInstanceGUID, testLogger)470 Expect(err).To(HaveOccurred())471 Expect(err.Error()).To(ContainSubstring("Unexpected reponse status 403"))472 Expect(err.Error()).To(ContainSubstring(`"{\"foo\":\"bar\"}"`))473 })474 })475 Context("when the auth header builder returns an error", func() {476 It("returns the error", func() {477 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)478 Expect(err).NotTo(HaveOccurred())479 authHeaderBuilder.AddAuthHeaderReturns(errors.New("no header for you"))480 err = client.DeleteServiceInstance(serviceInstanceGUID, testLogger)481 Expect(err).To(MatchError("no header for you"))482 })483 })484 })485 Describe("GetBindingsForInstance", func() {486 const serviceInstanceGUID = "92d707ce-c06c-421a-a1d2-ed1e750af650"487 It("returns a list of bindings", func() {488 server.VerifyAndMock(489 mockcfapi.ListServiceBindings(serviceInstanceGUID).490 WithAuthorizationHeader(cfAuthorizationHeader).491 RespondsOKWith(fixture("list_bindings_response_page_1.json")),492 mockcfapi.ListServiceBindingsForPage(serviceInstanceGUID, 2).493 WithAuthorizationHeader(cfAuthorizationHeader).494 RespondsOKWith(fixture("list_bindings_response_page_2.json")),495 )496 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)497 Expect(err).NotTo(HaveOccurred())498 bindings, err := client.GetBindingsForInstance(serviceInstanceGUID, testLogger)499 Expect(err).NotTo(HaveOccurred())500 Expect(bindings).To(HaveLen(2))501 Expect(bindings[0].GUID).To(Equal("83a87158-92b2-46ea-be66-9dad6b2cb116"))502 Expect(bindings[0].AppGUID).To(Equal("31809eda-4bdd-44fc-b804-eefe662b3a98"))503 Expect(bindings[1].GUID).To(Equal("9dad-6b2cb116-83a87158-92b2-46ea-be66"))504 Expect(bindings[1].AppGUID).To(Equal("eefe-662b3a98-31809eda-4bdd-44fcb804"))505 })506 Context("when the list bindings request fails", func() {507 It("returns an error", func() {508 server.VerifyAndMock(509 mockcfapi.ListServiceBindings(serviceInstanceGUID).RespondsInternalServerErrorWith("no bindings for you"),510 )511 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)512 Expect(err).NotTo(HaveOccurred())513 _, err = client.GetBindingsForInstance(serviceInstanceGUID, testLogger)514 Expect(err).To(HaveOccurred())515 Expect(err).To(MatchError(`Unexpected reponse status 500, "no bindings for you"`))516 })517 })518 })519 Describe("GetServiceKeysForInstance", func() {520 const serviceInstanceGUID = "92d707ce-c06c-421a-a1d2-ed1e750af650"521 It("return a list of service keys", func() {522 server.VerifyAndMock(523 mockcfapi.ListServiceKeys(serviceInstanceGUID).524 WithAuthorizationHeader(cfAuthorizationHeader).525 RespondsOKWith(fixture("list_service_keys_response_page_1.json")),526 mockcfapi.ListServiceKeysForPage(serviceInstanceGUID, 2).527 WithAuthorizationHeader(cfAuthorizationHeader).528 RespondsOKWith(fixture("list_service_keys_response_page_2.json")),529 )530 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)531 Expect(err).NotTo(HaveOccurred())532 serviceKeys, err := client.GetServiceKeysForInstance(serviceInstanceGUID, testLogger)533 Expect(err).NotTo(HaveOccurred())534 Expect(serviceKeys).To(HaveLen(2))535 Expect(serviceKeys[0].GUID).To(Equal("3c8076a6-0d85-11e7-811e-685b3585cc4e"))536 Expect(serviceKeys[1].GUID).To(Equal("23549ec8-0d85-11e7-82e1-685b3585cc4e"))537 })538 Context("when the list service keys request fails", func() {539 It("returns an error", func() {540 server.VerifyAndMock(541 mockcfapi.ListServiceKeys(serviceInstanceGUID).RespondsInternalServerErrorWith("no service keys for you"),542 )543 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)544 Expect(err).NotTo(HaveOccurred())545 _, err = client.GetServiceKeysForInstance(serviceInstanceGUID, testLogger)546 Expect(err).To(HaveOccurred())547 Expect(err).To(MatchError(`Unexpected reponse status 500, "no service keys for you"`))548 })549 })550 })551})...

Full Screen

Full Screen

capacitycontroller_test.go

Source:capacitycontroller_test.go Github

copy

Full Screen

1/*2Copyright © 2021 Dell Inc. or its subsidiaries. All Rights Reserved.3Licensed under the Apache License, Version 2.0 (the "License");4you may not use this file except in compliance with the License.5You may obtain a copy of the License at6 http://www.apache.org/licenses/LICENSE-2.07Unless required by applicable law or agreed to in writing, software8distributed under the License is distributed on an "AS IS" BASIS,9WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10See the License for the specific language governing permissions and11limitations under the License.12*/13package capacitycontroller14import (15 "context"16 "strconv"17 "testing"18 "github.com/sirupsen/logrus"19 "github.com/stretchr/testify/assert"20 v1 "k8s.io/apimachinery/pkg/apis/meta/v1"21 "k8s.io/apimachinery/pkg/types"22 ctrl "sigs.k8s.io/controller-runtime"23 api "github.com/dell/csi-baremetal/api/generated/v1"24 apiV1 "github.com/dell/csi-baremetal/api/v1"25 accrd "github.com/dell/csi-baremetal/api/v1/availablecapacitycrd"26 "github.com/dell/csi-baremetal/api/v1/drivecrd"27 "github.com/dell/csi-baremetal/api/v1/lvgcrd"28 "github.com/dell/csi-baremetal/pkg/base/k8s"29 "github.com/dell/csi-baremetal/pkg/base/util"30)31var (32 tCtx = context.Background()33 testLogger = logrus.New()34 lvg1Name = "lvg-cr-1"35 drive1UUID = "uuid-drive1"36 ns = "default"37 node1ID = "node1"38 apiDrive1 = api.Drive{39 UUID: drive1UUID,40 VID: "vid-drive1",41 PID: "pid-drive1",42 SerialNumber: "hdd1", // depend on commands.LsblkTwoDevicesStr - /dev/sda43 Health: apiV1.HealthGood,44 Type: apiV1.DriveTypeHDD,45 Size: int64(1000 * util.GBYTE),46 Status: apiV1.DriveStatusOnline,47 Usage: apiV1.DriveUsageInUse,48 NodeId: node1ID,49 IsClean: true,50 }51 drive1CR = drivecrd.Drive{52 TypeMeta: v1.TypeMeta{53 Kind: "Drive",54 APIVersion: apiV1.APIV1Version,55 },56 ObjectMeta: v1.ObjectMeta{57 Name: drive1UUID,58 },59 Spec: apiDrive1,60 }61 lvgCR1 = lvgcrd.LogicalVolumeGroup{62 TypeMeta: v1.TypeMeta{63 Kind: "LogicalVolumeGroup",64 APIVersion: apiV1.APIV1Version,65 },66 ObjectMeta: v1.ObjectMeta{67 Name: lvg1Name,68 },69 Spec: api.LogicalVolumeGroup{70 Name: lvg1Name,71 Node: node1ID,72 Locations: []string{apiDrive1.UUID},73 Size: int64(1024 * 500 * util.GBYTE),74 Status: apiV1.Creating,75 Health: apiV1.HealthGood,76 },77 }78 acSpec = api.AvailableCapacity{79 Location: drive1UUID,80 NodeId: apiDrive1.NodeId,81 StorageClass: apiDrive1.Type,82 Size: apiDrive1.Size,83 }84 acCRName = "ac"85 acCR = accrd.AvailableCapacity{86 TypeMeta: v1.TypeMeta{87 Kind: "AvailableCapacity",88 APIVersion: apiV1.APIV1Version,89 },90 ObjectMeta: v1.ObjectMeta{91 Name: acCRName,92 Namespace: ns,93 },94 Spec: acSpec,95 }96 acSpec2 = api.AvailableCapacity{97 Location: lvg1Name,98 NodeId: lvgCR1.Spec.Node,99 StorageClass: apiV1.StorageClassSystemLVG,100 Size: lvgCR1.Spec.Size,101 }102 acCR1Name = "ac1"103 acCR1 = accrd.AvailableCapacity{104 TypeMeta: v1.TypeMeta{105 Kind: "AvailableCapacity",106 APIVersion: apiV1.APIV1Version,107 },108 ObjectMeta: v1.ObjectMeta{109 Name: acCR1Name,110 Namespace: ns,111 },112 Spec: acSpec2,113 }114)115/* Complementary structures for table tests */116// inputData represents input parameters for drive reconciliation117type inputData struct {118 driveHealth string119 driveACIsPresent bool120 driveIsClean bool121}122// expectedResult represents expected results for drive reconciliation123type expectedResult struct {124 reconcileError error125 acList accrd.AvailableCapacityList126}127func Test_NewLVGController(t *testing.T) {128 c := NewCapacityController(nil, nil, testLogger)129 assert.NotNil(t, c)130}131func TestController_ReconcileDrive(t *testing.T) {132 for _, testData := range []struct {133 testCaseName string134 inputData inputData135 expectedResult expectedResult136 }{137 {138 testCaseName: "Drive is good, AC is not present",139 inputData: inputData{140 driveHealth: apiV1.HealthGood,141 driveACIsPresent: false,142 driveIsClean: true,143 },144 expectedResult: expectedResult{145 reconcileError: nil,146 acList: accrd.AvailableCapacityList{147 Items: []accrd.AvailableCapacity{148 {149 Spec: acSpec,150 },151 },152 },153 },154 },155 {156 testCaseName: "Drive is good, AC is present",157 inputData: inputData{158 driveHealth: apiV1.HealthGood,159 driveACIsPresent: true,160 driveIsClean: true,161 },162 expectedResult: expectedResult{163 reconcileError: nil,164 acList: accrd.AvailableCapacityList{165 Items: []accrd.AvailableCapacity{166 {167 Spec: acSpec,168 },169 },170 },171 },172 },173 {174 testCaseName: "Drive is unknown, AC is not present",175 inputData: inputData{176 driveHealth: apiV1.HealthUnknown,177 driveACIsPresent: false,178 driveIsClean: true,179 },180 expectedResult: expectedResult{181 reconcileError: nil,182 acList: accrd.AvailableCapacityList{183 Items: []accrd.AvailableCapacity{184 {185 Spec: acSpec,186 },187 },188 },189 },190 },191 {192 testCaseName: "Drive is unknown, AC is present",193 inputData: inputData{194 driveHealth: apiV1.HealthGood,195 driveACIsPresent: true,196 driveIsClean: true,197 },198 expectedResult: expectedResult{199 reconcileError: nil,200 acList: accrd.AvailableCapacityList{201 Items: []accrd.AvailableCapacity{202 {203 Spec: acSpec,204 },205 },206 },207 },208 },209 {210 testCaseName: "Drive is bad, AC is not present",211 inputData: inputData{212 driveHealth: apiV1.HealthBad,213 driveACIsPresent: false,214 driveIsClean: true,215 },216 expectedResult: expectedResult{217 reconcileError: nil,218 acList: accrd.AvailableCapacityList{},219 },220 },221 {222 testCaseName: "Drive is bad, AC is present",223 inputData: inputData{224 driveHealth: apiV1.HealthBad,225 driveACIsPresent: true,226 driveIsClean: true,227 },228 expectedResult: expectedResult{229 reconcileError: nil,230 acList: accrd.AvailableCapacityList{231 Items: []accrd.AvailableCapacity{232 {233 Spec: api.AvailableCapacity{234 Location: drive1UUID,235 NodeId: apiDrive1.NodeId,236 StorageClass: apiDrive1.Type,237 Size: 0,238 },239 },240 },241 },242 },243 },244 {245 testCaseName: "Drive is good and not clean, AC is present",246 inputData: inputData{247 driveHealth: apiV1.HealthGood,248 driveACIsPresent: true,249 driveIsClean: false,250 },251 expectedResult: expectedResult{252 reconcileError: nil,253 acList: accrd.AvailableCapacityList{254 Items: []accrd.AvailableCapacity{255 {256 Spec: api.AvailableCapacity{257 Location: drive1UUID,258 NodeId: apiDrive1.NodeId,259 StorageClass: apiDrive1.Type,260 Size: 0,261 },262 },263 },264 },265 },266 },267 {268 testCaseName: "Drive is good and not clean, AC is not present",269 inputData: inputData{270 driveHealth: apiV1.HealthGood,271 driveACIsPresent: false,272 driveIsClean: false,273 },274 expectedResult: expectedResult{275 reconcileError: nil,276 acList: accrd.AvailableCapacityList{277 Items: []accrd.AvailableCapacity{278 {279 Spec: api.AvailableCapacity{280 Location: drive1UUID,281 NodeId: apiDrive1.NodeId,282 StorageClass: apiDrive1.Type,283 Size: 0,284 },285 },286 },287 },288 },289 },290 } {291 t.Run(testData.testCaseName, func(t *testing.T) {292 // preparing fake kubeClient and capacity controller293 kubeClient, err := k8s.GetFakeKubeClient(ns, testLogger)294 assert.Nil(t, err)295 controller := NewCapacityController(kubeClient, kubeClient, testLogger)296 assert.NotNil(t, controller)297 // creating test objects298 testDrive := drive1CR.DeepCopy()299 testDrive.Spec.Health = testData.inputData.driveHealth300 testDrive.Spec.IsClean = testData.inputData.driveIsClean301 err = kubeClient.Create(tCtx, testDrive)302 assert.Nil(t, err)303 if testData.inputData.driveACIsPresent {304 testAC := acCR305 err = kubeClient.Create(tCtx, &testAC)306 assert.Nil(t, err)307 }308 // reconciling controller309 _, err = controller.Reconcile(tCtx, ctrl.Request{NamespacedName: types.NamespacedName{Namespace: ns, Name: testDrive.Name}})310 assert.ErrorIs(t, testData.expectedResult.reconcileError, err)311 // checking capacity results312 acList := &accrd.AvailableCapacityList{}313 err = kubeClient.ReadList(tCtx, acList)314 assert.Nil(t, err)315 assert.Equal(t, len(testData.expectedResult.acList.Items), len(acList.Items))316 for i := 0; i < len(acList.Items); i++ {317 assert.Equal(t, testData.expectedResult.acList.Items[i].Spec, acList.Items[i].Spec)318 }319 })320 }321}322func TestController_ReconcileLVG(t *testing.T) {323 t.Run("LVG is good, lvg doesn't have annotation", func(t *testing.T) {324 kubeClient, err := k8s.GetFakeKubeClient(ns, testLogger)325 assert.Nil(t, err)326 controller := NewCapacityController(kubeClient, kubeClient, testLogger)327 assert.NotNil(t, controller)328 testLVG := lvgCR1329 err = kubeClient.Create(tCtx, &testLVG)330 assert.Nil(t, err)331 _, err = controller.Reconcile(tCtx, ctrl.Request{NamespacedName: types.NamespacedName{Namespace: ns, Name: testLVG.Name}})332 assert.Nil(t, err)333 })334 t.Run("LVG is good, Annotation is present", func(t *testing.T) {335 kubeClient, err := k8s.GetFakeKubeClient(ns, testLogger)336 assert.Nil(t, err)337 controller := NewCapacityController(kubeClient, kubeClient, testLogger)338 assert.NotNil(t, controller)339 testDrive := drive1CR340 testDrive.Spec.IsSystem = true341 err = kubeClient.Create(tCtx, &testDrive)342 assert.Nil(t, err)343 testAC := acCR344 err = kubeClient.Create(tCtx, &testAC)345 assert.Nil(t, err)346 testLVG := lvgCR1347 testLVG.Annotations = map[string]string{apiV1.LVGFreeSpaceAnnotation: strconv.FormatInt(int64(util.GBYTE), 10)}348 err = kubeClient.Create(tCtx, &testLVG)349 assert.Nil(t, err)350 _, err = controller.Reconcile(tCtx, ctrl.Request{NamespacedName: types.NamespacedName{Namespace: ns, Name: testLVG.Name}})351 assert.Nil(t, err)352 acList := &accrd.AvailableCapacityList{}353 err = kubeClient.ReadList(tCtx, acList)354 assert.Nil(t, err)355 assert.Equal(t, 1, len(acList.Items))356 assert.Equal(t, int64(util.GBYTE), acList.Items[0].Spec.Size)357 assert.Equal(t, apiV1.StorageClassSystemLVG, acList.Items[0].Spec.StorageClass)358 })359 t.Run("LVG is good, Annotation is present, wrong annotation value", func(t *testing.T) {360 kubeClient, err := k8s.GetFakeKubeClient(ns, testLogger)361 assert.Nil(t, err)362 controller := NewCapacityController(kubeClient, kubeClient, testLogger)363 assert.NotNil(t, controller)364 testDrive := drive1CR.DeepCopy()365 testDrive.Spec.IsSystem = true366 err = kubeClient.Create(tCtx, testDrive)367 assert.Nil(t, err)368 testLVG := lvgCR1.DeepCopy()369 testLVG.Annotations = map[string]string{apiV1.LVGFreeSpaceAnnotation: "error"}370 err = kubeClient.Create(tCtx, testLVG)371 assert.Nil(t, err)372 _, err = controller.Reconcile(tCtx, ctrl.Request{NamespacedName: types.NamespacedName{Namespace: ns, Name: testLVG.Name}})373 assert.NotNil(t, err)374 assert.Contains(t, err.Error(), "invalid syntax")375 })376 t.Run("LVG is bad, AC is not present", func(t *testing.T) {377 kubeClient, err := k8s.GetFakeKubeClient(ns, testLogger)378 assert.Nil(t, err)379 controller := NewCapacityController(kubeClient, kubeClient, testLogger)380 assert.NotNil(t, controller)381 testLVG := lvgCR1382 testLVG.Spec.Health = apiV1.HealthBad383 err = kubeClient.Create(tCtx, &testLVG)384 assert.Nil(t, err)385 _, err = controller.Reconcile(tCtx, ctrl.Request{NamespacedName: types.NamespacedName{Namespace: ns, Name: testLVG.Name}})386 assert.Nil(t, err)387 })388 t.Run("LVG is bad, AC is present", func(t *testing.T) {389 kubeClient, err := k8s.GetFakeKubeClient(ns, testLogger)390 assert.Nil(t, err)391 controller := NewCapacityController(kubeClient, kubeClient, testLogger)392 assert.NotNil(t, controller)393 testAC := acCR1394 err = kubeClient.Create(tCtx, &testAC)395 assert.Nil(t, err)396 testLVG := lvgCR1397 testLVG.Spec.Health = apiV1.HealthBad398 err = kubeClient.Create(tCtx, &testLVG)399 assert.Nil(t, err)400 _, err = controller.Reconcile(tCtx, ctrl.Request{NamespacedName: types.NamespacedName{Namespace: ns, Name: testLVG.Name}})401 assert.Nil(t, err)402 acList := &accrd.AvailableCapacityList{}403 err = kubeClient.ReadList(tCtx, acList)404 assert.Nil(t, err)405 assert.Equal(t, 1, len(acList.Items))406 assert.Equal(t, int64(0), acList.Items[0].Spec.Size)407 })408 t.Run("LVG is good, AC is not present", func(t *testing.T) {409 kubeClient, err := k8s.GetFakeKubeClient(ns, testLogger)410 assert.Nil(t, err)411 controller := NewCapacityController(kubeClient, kubeClient, testLogger)412 assert.NotNil(t, controller)413 testDrive := drive1CR414 testDrive.Spec.IsSystem = true415 err = kubeClient.Create(tCtx, &testDrive)416 assert.Nil(t, err)417 testLVG := lvgCR1418 testLVG.Annotations = map[string]string{apiV1.LVGFreeSpaceAnnotation: strconv.FormatInt(int64(util.GBYTE), 10)}419 err = kubeClient.Create(tCtx, &testLVG)420 assert.Nil(t, err)421 _, err = controller.Reconcile(tCtx, ctrl.Request{NamespacedName: types.NamespacedName{Namespace: ns, Name: testLVG.Name}})422 assert.Nil(t, err)423 acList := &accrd.AvailableCapacityList{}424 err = kubeClient.ReadList(tCtx, acList)425 assert.Nil(t, err)426 assert.Equal(t, 1, len(acList.Items))427 assert.Equal(t, int64(util.GBYTE), acList.Items[0].Spec.Size)428 assert.Equal(t, apiV1.StorageClassSystemLVG, acList.Items[0].Spec.StorageClass)429 })430}431func TestController_ReconcileResourcesNotFound(t *testing.T) {432 kubeClient, err := k8s.GetFakeKubeClient(ns, testLogger)433 assert.Nil(t, err)434 controller := NewCapacityController(kubeClient, kubeClient, testLogger)435 assert.NotNil(t, controller)436 _, err = controller.Reconcile(tCtx, ctrl.Request{NamespacedName: types.NamespacedName{Namespace: ns, Name: drive1UUID}})437 assert.Nil(t, err)438}439func TestController_filterUpdateEvent_Drive(t *testing.T) {440 t.Run("Drives have different statuses", func(t *testing.T) {441 kubeClient, err := k8s.GetFakeKubeClient(ns, testLogger)442 assert.Nil(t, err)443 controller := NewCapacityController(kubeClient, kubeClient, testLogger)444 assert.NotNil(t, controller)445 testDrive := drive1CR446 testDrive2 := drive1CR447 testDrive2.Spec.Health = apiV1.HealthBad448 assert.True(t, controller.filterUpdateEvent(&testDrive, &testDrive2))449 })450 t.Run("Drives have different health statuses", func(t *testing.T) {451 kubeClient, err := k8s.GetFakeKubeClient(ns, testLogger)452 assert.Nil(t, err)453 controller := NewCapacityController(kubeClient, kubeClient, testLogger)454 assert.NotNil(t, controller)455 testDrive := drive1CR456 testDrive2 := drive1CR457 testDrive2.Spec.Status = apiV1.Failed458 assert.True(t, controller.filterUpdateEvent(&testDrive, &testDrive2))459 })460 t.Run("Drives have different clean", func(t *testing.T) {461 kubeClient, err := k8s.GetFakeKubeClient(ns, testLogger)462 assert.Nil(t, err)463 controller := NewCapacityController(kubeClient, kubeClient, testLogger)464 assert.NotNil(t, controller)465 testDrive := drive1CR466 testDrive2 := drive1CR467 testDrive2.Spec.IsClean = !testDrive.Spec.IsClean468 assert.True(t, controller.filterUpdateEvent(&testDrive, &testDrive2))469 })470 t.Run("Drives are filtered", func(t *testing.T) {471 kubeClient, err := k8s.GetFakeKubeClient(ns, testLogger)472 assert.Nil(t, err)473 controller := NewCapacityController(kubeClient, kubeClient, testLogger)474 assert.NotNil(t, controller)475 testDrive := drive1CR476 testDrive2 := drive1CR477 assert.False(t, controller.filterUpdateEvent(&testDrive, &testDrive2))478 })479}480func TestController_filterUpdateEvent_LVG(t *testing.T) {481 t.Run("LVG have different health statuses", func(t *testing.T) {482 kubeClient, err := k8s.GetFakeKubeClient(ns, testLogger)483 assert.Nil(t, err)484 controller := NewCapacityController(kubeClient, kubeClient, testLogger)485 assert.NotNil(t, controller)486 testLVG := lvgCR1487 testLVG2 := lvgCR1488 testLVG2.Spec.Health = apiV1.HealthBad489 assert.True(t, controller.filterUpdateEvent(&testLVG, &testLVG2))490 })491 t.Run("LVG have different statuses", func(t *testing.T) {492 kubeClient, err := k8s.GetFakeKubeClient(ns, testLogger)493 assert.Nil(t, err)494 controller := NewCapacityController(kubeClient, kubeClient, testLogger)495 assert.NotNil(t, controller)496 testLVG := lvgCR1497 testLVG2 := lvgCR1498 testLVG2.Spec.Status = apiV1.Failed499 assert.True(t, controller.filterUpdateEvent(&testLVG, &testLVG2))500 })501 t.Run("Old lvg has annotation, new one doesn't", func(t *testing.T) {502 kubeClient, err := k8s.GetFakeKubeClient(ns, testLogger)503 assert.Nil(t, err)504 controller := NewCapacityController(kubeClient, kubeClient, testLogger)505 assert.NotNil(t, controller)506 testLVG := lvgCR1507 testLVG2 := lvgCR1508 testLVG.Annotations = map[string]string{apiV1.LVGFreeSpaceAnnotation: "10000"}509 assert.False(t, controller.filterUpdateEvent(&testLVG, &testLVG2))510 })511 t.Run("Old lvg doesn't annotation, new one does", func(t *testing.T) {512 kubeClient, err := k8s.GetFakeKubeClient(ns, testLogger)513 assert.Nil(t, err)514 controller := NewCapacityController(kubeClient, kubeClient, testLogger)515 assert.NotNil(t, controller)516 testLVG := lvgCR1517 testLVG2 := lvgCR1518 testLVG2.Annotations = map[string]string{apiV1.LVGFreeSpaceAnnotation: "10000"}519 assert.True(t, controller.filterUpdateEvent(&testLVG, &testLVG2))520 })521 t.Run("Old lvg doesn't annotation, new one doesn't have annotation", func(t *testing.T) {522 kubeClient, err := k8s.GetFakeKubeClient(ns, testLogger)523 assert.Nil(t, err)524 controller := NewCapacityController(kubeClient, kubeClient, testLogger)525 assert.NotNil(t, controller)526 testLVG := lvgCR1527 testLVG2 := lvgCR1528 assert.False(t, controller.filterUpdateEvent(&testLVG, &testLVG2))529 })530 t.Run("Both LVG have annotation", func(t *testing.T) {531 kubeClient, err := k8s.GetFakeKubeClient(ns, testLogger)532 assert.Nil(t, err)533 controller := NewCapacityController(kubeClient, kubeClient, testLogger)534 assert.NotNil(t, controller)535 testLVG := lvgCR1536 testLVG2 := lvgCR1537 testLVG2.Annotations = map[string]string{apiV1.LVGFreeSpaceAnnotation: "10000"}538 testLVG.Annotations = map[string]string{apiV1.LVGFreeSpaceAnnotation: "5000"}539 assert.True(t, controller.filterUpdateEvent(&testLVG, &testLVG2))540 })541}...

Full Screen

Full Screen

info_test.go

Source:info_test.go Github

copy

Full Screen

1package cf_test2import (3 "fmt"4 "io"5 "log"6 "net/http"7 . "github.com/onsi/ginkgo"8 . "github.com/onsi/ginkgo/extensions/table"9 . "github.com/onsi/gomega"10 "github.com/onsi/gomega/gbytes"11 "github.com/pivotal-cf/on-demand-service-broker/cf"12 "github.com/pivotal-cf/on-demand-service-broker/cf/fakes"13 "github.com/pivotal-cf/on-demand-service-broker/mockhttp"14 "github.com/pivotal-cf/on-demand-service-broker/mockhttp/mockcfapi"15)16var _ = Describe("info", func() {17 var server *mockhttp.Server18 var testLogger *log.Logger19 var logBuffer *gbytes.Buffer20 var authHeaderBuilder *fakes.FakeAuthHeaderBuilder21 const (22 cfAuthorizationHeader = "auth-header"23 serviceGUID = "06df08f9-5a58-4d33-8097-32d0baf3ce1e"24 )25 BeforeEach(func() {26 authHeaderBuilder = new(fakes.FakeAuthHeaderBuilder)27 authHeaderBuilder.AddAuthHeaderStub = func(req *http.Request, logger *log.Logger) error {28 req.Header.Set("Authorization", cfAuthorizationHeader)29 return nil30 }31 server = mockcfapi.New()32 logBuffer = gbytes.NewBuffer()33 testLogger = log.New(io.MultiWriter(logBuffer, GinkgoWriter), "my-app", log.LstdFlags)34 })35 AfterEach(func() {36 server.VerifyMocks()37 })38 Describe("GetAPIVersion", func() {39 It("gets cloudfoundry api version", func() {40 server.VerifyAndMock(41 mockcfapi.GetInfo().RespondsOKWith(42 `{43 "name": "",44 "build": "",45 "support": "http://support.cloudfoundry.com",46 "version": 0,47 "description": "",48 "authorization_endpoint": "https://login.services-enablement-bosh-lite-aws.cf-app.com",49 "token_endpoint": "https://uaa.services-enablement-bosh-lite-aws.cf-app.com",50 "min_cli_version": null,51 "min_recommended_cli_version": null,52 "api_version": "2.57.0",53 "app_ssh_endpoint": "ssh.services-enablement-bosh-lite-aws.cf-app.com:2222",54 "app_ssh_host_key_fingerprint": "a6:d1:08:0b:b0:cb:9b:5f:c4:ba:44:2a:97:26:19:8a",55 "app_ssh_oauth_client": "ssh-proxy",56 "logging_endpoint": "wss://loggregator.services-enablement-bosh-lite-aws.cf-app.com:443",57 "doppler_logging_endpoint": "wss://doppler.services-enablement-bosh-lite-aws.cf-app.com:4443"58 }`,59 ),60 )61 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)62 Expect(err).NotTo(HaveOccurred())63 Expect(client.GetAPIVersion(testLogger)).To(Equal("2.57.0"))64 })65 It("fails, if get info fails", func() {66 server.VerifyAndMock(67 mockcfapi.GetInfo().RespondsInternalServerErrorWith("nothing today, thank you"),68 )69 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)70 Expect(err).NotTo(HaveOccurred())71 _, getVersionErr := client.GetAPIVersion(testLogger)72 Expect(getVersionErr.Error()).To(ContainSubstring("nothing today, thank you"))73 })74 })75 Describe("CheckMinimumOSBAPIVersion", func() {76 When("the specified minimum version is invalid", func() {77 It("logs an error and returns false", func() {78 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)79 Expect(err).NotTo(HaveOccurred())80 Expect(client.CheckMinimumOSBAPIVersion("", testLogger)).To(BeFalse())81 Expect(logBuffer).To(gbytes.Say("error parsing specified OSBAPI version '' to semver:"))82 Expect(client.CheckMinimumOSBAPIVersion("not-semver", testLogger)).To(BeFalse())83 Expect(logBuffer).To(gbytes.Say("error parsing specified OSBAPI version 'not-semver' to semver:"))84 })85 })86 When("the API returns an error", func() {87 It("logs an error and returns false", func() {88 server.VerifyAndMock(89 mockcfapi.GetInfo().RespondsInternalServerErrorWith(""),90 )91 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)92 Expect(err).NotTo(HaveOccurred())93 Expect(client.CheckMinimumOSBAPIVersion("1.2.3", testLogger)).To(BeFalse())94 Expect(logBuffer).To(gbytes.Say("error requesting OSBAPI version: Unexpected reponse status 500"))95 })96 })97 When("the API returns an invalid version", func() {98 It("logs an error and returns false", func() {99 server.VerifyAndMock(100 mockcfapi.GetInfo().RespondsOKWith(`{"osbapi_version": "nonsemver"}`),101 )102 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)103 Expect(err).NotTo(HaveOccurred())104 Expect(client.CheckMinimumOSBAPIVersion("1.2.3", testLogger)).To(BeFalse())105 Expect(logBuffer).To(gbytes.Say("error parsing discovered OSBAPI version 'nonsemver' to semver:"))106 })107 })108 DescribeTable(109 "correctly checking minuimum OSBABI versions",110 func(required, actual string, result bool) {111 server.VerifyAndMock(112 mockcfapi.GetInfo().RespondsOKWith(fmt.Sprintf(`{"osbapi_version": "%s"}`, actual)),113 )114 client, err := cf.New(server.URL, authHeaderBuilder, nil, true, testLogger)115 Expect(err).NotTo(HaveOccurred())116 Expect(client.CheckMinimumOSBAPIVersion(required, testLogger)).To(Equal(result), fmt.Sprintf("%s >= %s = %t", actual, required, result))117 },118 Entry("3 digit above", "1.2.3", "1.2.4", true),119 Entry("3 digit same", "1.2.3", "1.2.3", true),120 Entry("3 digit below", "1.2.3", "1.2.2", false),121 Entry("2 digit above", "1.21", "1.22", true),122 Entry("2 digit same", "1.21", "1.21", true),123 Entry("2 digit below", "1.21", "1.11", false),124 Entry("1 digit above", "1.21", "2", true),125 Entry("1 digit same", "1.21", "1", false),126 Entry("1 digit below", "1.21", "0", false),127 )128 })129})...

Full Screen

Full Screen

TestLogger

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 f, err := os.Create("test.txt")4 if err != nil {5 log.Fatal(err)6 }7 defer func() {8 if err := f.Close(); err != nil {9 log.Fatal(err)10 }11 }()12 _, err = f.Write([]byte("test13 if err != nil {14 log.Fatal(err)15 }16 _, err = f.WriteString("test17 if err != nil {18 log.Fatal(err)19 }20 err = f.Sync()21 if err != nil {22 log.Fatal(err)23 }24 f, err = os.Create("test.txt")25 if err != nil {26 log.Fatal(err)27 }28 defer func() {29 if err := f.Close(); err != nil {30 log.Fatal(err)31 }32 }()33 _, err = f.WriteString("test34 if err != nil {35 log.Fatal(err)36 }37 err = f.Sync()38 if err != nil {39 log.Fatal(err)40 }41 f, err = os.OpenFile("test.txt", os.O_RDWR, 0755)42 if err != nil {43 log.Fatal(err)44 }45 defer func() {46 if err := f.Close(); err != nil {47 log.Fatal(err)48 }49 }()50 b1 := make([]byte, 5)51 n1, err := f.Read(b1)52 if err != nil {53 log.Fatal(err)54 }55 fmt.Printf("%d bytes: %s56", n1, string(b1))57 o2, err := f.Seek(6, 0)58 if err != nil {59 log.Fatal(err)60 }61 b2 := make([]byte, 2)62 n2, err := f.Read(b2)63 if err != nil {64 log.Fatal(err)65 }66 fmt.Printf("%d bytes @ %d:

Full Screen

Full Screen

TestLogger

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 api.TestLogger()5}6import (7func TestLogger() {8 log.Println("Hello, playground")9}

Full Screen

Full Screen

TestLogger

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 api.TestLogger()4}5import (6func TestLogger() {7 log.Println("Hello World")8}

Full Screen

Full Screen

TestLogger

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 api.TestLogger()5}6import (7func TestLogger() {8 fmt.Println("Hello, playground")9 log.Println("Hello, playground")10}

Full Screen

Full Screen

TestLogger

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Starting main")4 api.TestLogger()5 fmt.Println("Ending main")6}7import (8func TestLogger() {9 log.Println("TestLogger")10}11import (12func main() {13 fmt.Println("Starting main")14 api.TestLogger()15 fmt.Println("Ending main")16}17import (18func TestLogger() {19 file, err := os.OpenFile("log.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)20 if err != nil {21 log.Println(err)22 }23 log.SetOutput(file)24 log.Println("TestLogger")25}26You can also use log.SetFlags() method to set the log format. By default, the log format is27log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.LUTC)28log.Println("TestLogger")29You can use log.SetFlags() method with any combination of the following flags

Full Screen

Full Screen

TestLogger

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Main")4 testlogger.TestLogger()5}6import (7func TestLogger() {8 log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)9 log.Println("Hello")10}

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run K6 automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful