How to use Interrupt method of test_helpers Package

Best Ginkgo code snippet using test_helpers.Interrupt

Run Ginkgo automation tests on LambdaTest cloud grid

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

app_examiner_command_factory_test.go

Source: app_examiner_command_factory_test.go Github

copy
1package command_factory_test
2
3import (
4	"errors"
5	"os"
6	"time"
7
8	. "github.com/onsi/ginkgo"
9	. "github.com/onsi/gomega"
10
11	"github.com/codegangsta/cli"
12	"github.com/onsi/gomega/gbytes"
13	"github.com/pivotal-cf-experimental/lattice-cli/app_examiner"
14	"github.com/pivotal-cf-experimental/lattice-cli/app_examiner/command_factory"
15	"github.com/pivotal-cf-experimental/lattice-cli/app_examiner/fake_app_examiner"
16	"github.com/pivotal-cf-experimental/lattice-cli/colors"
17	"github.com/pivotal-cf-experimental/lattice-cli/exit_handler/exit_codes"
18	"github.com/pivotal-cf-experimental/lattice-cli/exit_handler/fake_exit_handler"
19	"github.com/pivotal-cf-experimental/lattice-cli/output"
20	"github.com/pivotal-cf-experimental/lattice-cli/output/cursor"
21	"github.com/pivotal-cf-experimental/lattice-cli/route_helpers"
22	"github.com/pivotal-cf-experimental/lattice-cli/test_helpers"
23	"github.com/pivotal-golang/clock/fakeclock"
24)
25
26var _ = Describe("CommandFactory", func() {
27
28	var (
29		appExaminer  *fake_app_examiner.FakeAppExaminer
30		outputBuffer *gbytes.Buffer
31		clock        *fakeclock.FakeClock
32		osSignalChan chan os.Signal
33		exitHandler  *fake_exit_handler.FakeExitHandler
34	)
35
36	BeforeEach(func() {
37		appExaminer = &fake_app_examiner.FakeAppExaminer{}
38		outputBuffer = gbytes.NewBuffer()
39		osSignalChan = make(chan os.Signal, 1)
40		clock = fakeclock.NewFakeClock(time.Now())
41		exitHandler = &fake_exit_handler.FakeExitHandler{}
42	})
43
44	Describe("ListAppsCommand", func() {
45		var listAppsCommand cli.Command
46
47		BeforeEach(func() {
48			commandFactory := command_factory.NewAppExaminerCommandFactory(appExaminer, output.New(outputBuffer), clock, exitHandler)
49			listAppsCommand = commandFactory.MakeListAppCommand()
50		})
51
52		It("displays all the existing apps, making sure output spacing is correct", func() {
53			listApps := []app_examiner.AppInfo{
54				app_examiner.AppInfo{ProcessGuid: "process1", DesiredInstances: 21, ActualRunningInstances: 0, DiskMB: 100, MemoryMB: 50, Ports: []uint16{54321}, Routes: route_helpers.AppRoutes{route_helpers.AppRoute{Hostnames: []string{"alldaylong.com"}, Port: 54321}}},
55				app_examiner.AppInfo{ProcessGuid: "process2", DesiredInstances: 8, ActualRunningInstances: 9, DiskMB: 400, MemoryMB: 30, Ports: []uint16{1234}, Routes: route_helpers.AppRoutes{route_helpers.AppRoute{Hostnames: []string{"never.io"}, Port: 1234}}},
56				app_examiner.AppInfo{ProcessGuid: "process3", DesiredInstances: 5, ActualRunningInstances: 5, DiskMB: 600, MemoryMB: 90, Ports: []uint16{1234}, Routes: route_helpers.AppRoutes{route_helpers.AppRoute{Hostnames: []string{"allthetime.com", "herewego.org"}, Port: 1234}}},
57				app_examiner.AppInfo{ProcessGuid: "process4", DesiredInstances: 0, ActualRunningInstances: 0, DiskMB: 10, MemoryMB: 10, Routes: route_helpers.AppRoutes{}},
58			}
59			appExaminer.ListAppsReturns(listApps, nil)
60
61			test_helpers.ExecuteCommandWithArgs(listAppsCommand, []string{})
62
63			Expect(outputBuffer).To(test_helpers.Say(colors.Bold("App Name")))
64			Expect(outputBuffer).To(test_helpers.Say(colors.Bold("Instances")))
65			Expect(outputBuffer).To(test_helpers.Say(colors.Bold("DiskMB")))
66			Expect(outputBuffer).To(test_helpers.Say(colors.Bold("MemoryMB")))
67			Expect(outputBuffer).To(test_helpers.Say(colors.Bold("Route")))
68
69			Expect(outputBuffer).To(test_helpers.Say(colors.Bold("process1")))
70			Expect(outputBuffer).To(test_helpers.Say(colors.Red("0/21")))
71			Expect(outputBuffer).To(test_helpers.Say(colors.NoColor("100")))
72			Expect(outputBuffer).To(test_helpers.Say(colors.NoColor("50")))
73			Expect(outputBuffer).To(test_helpers.Say("alldaylong.com => 54321"))
74
75			Expect(outputBuffer).To(test_helpers.Say(colors.Bold("process2")))
76			Expect(outputBuffer).To(test_helpers.Say(colors.Yellow("9/8")))
77			Expect(outputBuffer).To(test_helpers.Say(colors.NoColor("400")))
78			Expect(outputBuffer).To(test_helpers.Say(colors.NoColor("30")))
79			Expect(outputBuffer).To(test_helpers.Say("never.io => 1234"))
80
81			Expect(outputBuffer).To(test_helpers.Say(colors.Bold("process3")))
82			Expect(outputBuffer).To(test_helpers.Say(colors.Green("5/5")))
83			Expect(outputBuffer).To(test_helpers.Say(colors.NoColor("600")))
84			Expect(outputBuffer).To(test_helpers.Say(colors.NoColor("90")))
85			Expect(outputBuffer).To(test_helpers.Say("allthetime.com, herewego.org => 1234"))
86
87			Expect(outputBuffer).To(test_helpers.Say(colors.Bold("process4")))
88			Expect(outputBuffer).To(test_helpers.Say(colors.Green("0/0")))
89			Expect(outputBuffer).To(test_helpers.Say(colors.NoColor("10")))
90			Expect(outputBuffer).To(test_helpers.Say(colors.NoColor("10")))
91
92		})
93
94		It("alerts the user if there are no apps", func() {
95			listApps := []app_examiner.AppInfo{}
96			appExaminer.ListAppsReturns(listApps, nil)
97
98			test_helpers.ExecuteCommandWithArgs(listAppsCommand, []string{})
99
100			Expect(outputBuffer).To(test_helpers.Say("No apps to display."))
101		})
102
103		It("alerts the user if fetching the list returns an error", func() {
104			listApps := []app_examiner.AppInfo{}
105			appExaminer.ListAppsReturns(listApps, errors.New("The list was lost"))
106
107			test_helpers.ExecuteCommandWithArgs(listAppsCommand, []string{})
108
109			Expect(outputBuffer).To(test_helpers.Say("Error listing apps: The list was lost"))
110		})
111	})
112
113	Describe("VisualizeCommand", func() {
114		var visualizeCommand cli.Command
115
116		BeforeEach(func() {
117			commandFactory := command_factory.NewAppExaminerCommandFactory(appExaminer, output.New(outputBuffer), clock, exitHandler)
118			visualizeCommand = commandFactory.MakeVisualizeCommand()
119		})
120
121		It("displays a visualization of cells", func() {
122			listCells := []app_examiner.CellInfo{
123				app_examiner.CellInfo{CellID: "cell-1", RunningInstances: 3, ClaimedInstances: 2},
124				app_examiner.CellInfo{CellID: "cell-2", RunningInstances: 2, ClaimedInstances: 1},
125				app_examiner.CellInfo{CellID: "cell-3", RunningInstances: 0, ClaimedInstances: 0},
126			}
127			appExaminer.ListCellsReturns(listCells, nil)
128
129			test_helpers.ExecuteCommandWithArgs(visualizeCommand, []string{})
130
131			Expect(outputBuffer).To(test_helpers.Say(colors.Bold("Distribution\n")))
132			Expect(outputBuffer).To(test_helpers.Say("cell-1: " + colors.Green("•••") + colors.Yellow("••") + cursor.ClearToEndOfLine() + "\n"))
133			Expect(outputBuffer).To(test_helpers.Say("cell-2: " + colors.Green("••") + colors.Yellow("•") + cursor.ClearToEndOfLine() + "\n"))
134			Expect(outputBuffer).To(test_helpers.Say("cell-3: " + colors.Red("empty")))
135			Expect(outputBuffer).To(test_helpers.SayNewLine())
136		})
137
138		It("alerts the user if fetching the cells returns an error", func() {
139			appExaminer.ListCellsReturns(nil, errors.New("The list was lost"))
140
141			test_helpers.ExecuteCommandWithArgs(visualizeCommand, []string{})
142
143			Expect(outputBuffer).To(test_helpers.Say("Error visualizing: The list was lost"))
144		})
145
146		Context("When a rate flag is provided", func() {
147			var closeChan chan struct{}
148
149			It("dynamically displays the visualization", func() {
150				setNumberOfRunningInstances := func(count int) {
151					appExaminer.ListCellsReturns([]app_examiner.CellInfo{app_examiner.CellInfo{CellID: "cell-0", RunningInstances: count}, app_examiner.CellInfo{CellID: "cell-1", RunningInstances: count, Missing: true}}, nil)
152				}
153
154				setNumberOfRunningInstances(0)
155
156				closeChan = test_helpers.AsyncExecuteCommandWithArgs(visualizeCommand, []string{"-rate", "2s"})
157
158				Eventually(outputBuffer).Should(test_helpers.Say("cell-0: " + colors.Red("empty") + cursor.ClearToEndOfLine() + "\n"))
159				Eventually(outputBuffer).Should(test_helpers.Say("cell-1" + colors.Red("[MISSING]") + ": " + cursor.ClearToEndOfLine() + "\n"))
160
161				setNumberOfRunningInstances(2)
162
163				clock.IncrementBySeconds(1)
164
165				Consistently(outputBuffer).ShouldNot(test_helpers.Say("cell: \n"))
166
167				clock.IncrementBySeconds(1)
168
169				Eventually(outputBuffer).Should(test_helpers.Say(cursor.Hide()))
170				Eventually(outputBuffer).Should(test_helpers.Say(cursor.Up(2)))
171				Eventually(outputBuffer).Should(test_helpers.Say("cell-0: " + colors.Green("••") + cursor.ClearToEndOfLine() + "\n"))
172				Eventually(outputBuffer).Should(test_helpers.Say("cell-1" + colors.Red("[MISSING]") + ": " + colors.Green("••") + cursor.ClearToEndOfLine() + "\n"))
173				Eventually(outputBuffer).Should(test_helpers.Say(cursor.ClearToEndOfDisplay()))
174			})
175
176			It("dynamically displays any errors", func() {
177				appExaminer.ListCellsReturns(nil, errors.New("Spilled the Paint"))
178
179				closeChan = test_helpers.AsyncExecuteCommandWithArgs(visualizeCommand, []string{"-rate", "1s"})
180
181				Eventually(outputBuffer).Should(test_helpers.Say("Error visualizing: Spilled the Paint" + cursor.ClearToEndOfLine() + "\n"))
182
183				clock.IncrementBySeconds(1)
184
185				Eventually(outputBuffer).Should(test_helpers.Say(cursor.Up(1)))
186				Eventually(outputBuffer).Should(test_helpers.Say("Error visualizing: Spilled the Paint" + cursor.ClearToEndOfLine() + "\n"))
187				Eventually(outputBuffer).Should(test_helpers.Say(cursor.ClearToEndOfDisplay()))
188			})
189
190			It("Ensures the user's cursor is visible even if they interrupt ltc", func() {
191				closeChan = test_helpers.AsyncExecuteCommandWithArgs(visualizeCommand, []string{"-rate=1s"})
192
193				Eventually(outputBuffer).Should(test_helpers.Say(cursor.Hide()))
194
195				exitHandler.Exit(exit_codes.SigInt)
196
197				Expect(outputBuffer).Should(test_helpers.Say(cursor.Show()))
198			})
199
200			AfterEach(func() {
201				go exitHandler.Exit(exit_codes.SigInt)
202				Eventually(closeChan).Should(BeClosed())
203			})
204		})
205
206	})
207
208	Describe("StatusCommand", func() {
209		var statusCommand cli.Command
210
211		BeforeEach(func() {
212			commandFactory := command_factory.NewAppExaminerCommandFactory(appExaminer, output.New(outputBuffer), clock, exitHandler)
213			statusCommand = commandFactory.MakeStatusCommand()
214		})
215
216		It("emits a pretty representation of the DesiredLRP", func() {
217			appExaminer.AppStatusReturns(
218				app_examiner.AppInfo{
219					ProcessGuid:            "wompy-app",
220					DesiredInstances:       12,
221					ActualRunningInstances: 1,
222					Stack: "lucid64",
223					EnvironmentVariables: []app_examiner.EnvironmentVariable{
224						app_examiner.EnvironmentVariable{Name: "WOMPY_APP_PASSWORD", Value: "seekreet pass"},
225						app_examiner.EnvironmentVariable{Name: "WOMPY_APP_USERNAME", Value: "mrbigglesworth54"},
226					},
227					StartTimeout: 600,
228					DiskMB:       2048,
229					MemoryMB:     256,
230					CPUWeight:    100,
231					Ports:        []uint16{8887, 9000},
232					Routes:       route_helpers.AppRoutes{route_helpers.AppRoute{Hostnames: []string{"wompy-app.my-fun-domain.com", "cranky-app.my-fun-domain.com"}, Port: 8080}},
233					LogGuid:      "a9s8dfa99023r",
234					LogSource:    "wompy-app-logz",
235					Annotation:   "I love this app. So wompy.",
236					ActualInstances: []app_examiner.InstanceInfo{
237						app_examiner.InstanceInfo{
238							InstanceGuid: "a0s9f-u9a8sf-aasdioasdjoi",
239							CellID:       "cell-12",
240							Index:        3,
241							Ip:           "10.85.12.100",
242							Ports: []app_examiner.PortMapping{
243								app_examiner.PortMapping{
244									HostPort:      1234,
245									ContainerPort: 3000,
246								},
247								app_examiner.PortMapping{
248									HostPort:      5555,
249									ContainerPort: 6666,
250								},
251							},
252							State: "RUNNING",
253							Since: 401120627 * 1e9,
254						},
255						app_examiner.InstanceInfo{
256							Index:          4,
257							State:          "UNCLAIMED",
258							PlacementError: "insufficient resources.",
259							CrashCount:     2,
260						},
261						app_examiner.InstanceInfo{
262							Index:      5,
263							State:      "CRASHED",
264							CrashCount: 7,
265						},
266					},
267				}, nil)
268
269			test_helpers.ExecuteCommandWithArgs(statusCommand, []string{"wompy-app"})
270
271			Expect(appExaminer.AppStatusCallCount()).To(Equal(1))
272			Expect(appExaminer.AppStatusArgsForCall(0)).To(Equal("wompy-app"))
273
274			Expect(outputBuffer).To(test_helpers.Say("wompy-app"))
275
276			Expect(outputBuffer).To(test_helpers.Say("Instances"))
277			Expect(outputBuffer).To(test_helpers.Say("1/12"))
278
279			Expect(outputBuffer).To(test_helpers.Say("Stack"))
280			Expect(outputBuffer).To(test_helpers.Say("lucid64"))
281
282			Expect(outputBuffer).To(test_helpers.Say("Start Timeout"))
283			Expect(outputBuffer).To(test_helpers.Say("600"))
284
285			Expect(outputBuffer).To(test_helpers.Say("DiskMB"))
286			Expect(outputBuffer).To(test_helpers.Say("2048"))
287
288			Expect(outputBuffer).To(test_helpers.Say("MemoryMB"))
289			Expect(outputBuffer).To(test_helpers.Say("256"))
290
291			Expect(outputBuffer).To(test_helpers.Say("CPUWeight"))
292			Expect(outputBuffer).To(test_helpers.Say("100"))
293
294			Expect(outputBuffer).To(test_helpers.Say("Ports"))
295			Expect(outputBuffer).To(test_helpers.Say("8887"))
296			Expect(outputBuffer).To(test_helpers.Say("9000"))
297
298			Expect(outputBuffer).To(test_helpers.Say("Routes"))
299			Expect(outputBuffer).To(test_helpers.Say("wompy-app.my-fun-domain.com => 8080"))
300			Expect(outputBuffer).To(test_helpers.Say("cranky-app.my-fun-domain.com => 8080"))
301
302			Expect(outputBuffer).To(test_helpers.Say("Annotation"))
303			Expect(outputBuffer).To(test_helpers.Say("I love this app. So wompy."))
304
305			Expect(outputBuffer).To(test_helpers.Say("Environment"))
306			Expect(outputBuffer).To(test_helpers.Say(`WOMPY_APP_PASSWORD="seekreet pass"`))
307			Expect(outputBuffer).To(test_helpers.Say(`WOMPY_APP_USERNAME="mrbigglesworth54"`))
308
309			Expect(outputBuffer).To(test_helpers.Say("Instance 3"))
310			Expect(outputBuffer).To(test_helpers.Say("RUNNING"))
311
312			Expect(outputBuffer).To(test_helpers.Say("InstanceGuid"))
313			Expect(outputBuffer).To(test_helpers.Say("a0s9f-u9a8sf-aasdioasdjoi"))
314
315			Expect(outputBuffer).To(test_helpers.Say("Cell ID"))
316			Expect(outputBuffer).To(test_helpers.Say("cell-12"))
317
318			Expect(outputBuffer).To(test_helpers.Say("Ip"))
319			Expect(outputBuffer).To(test_helpers.Say("10.85.12.100"))
320
321			Expect(outputBuffer).To(test_helpers.Say("Port Mapping"))
322			Expect(outputBuffer).To(test_helpers.Say("1234:3000"))
323			Expect(outputBuffer).To(test_helpers.Say("5555:6666"))
324
325			Expect(outputBuffer).To(test_helpers.Say("Since"))
326
327			prettyTimestamp := time.Unix(0, 401120627*1e9).Format(command_factory.TimestampDisplayLayout)
328			Expect(outputBuffer).To(test_helpers.Say(prettyTimestamp))
329
330			Expect(outputBuffer).To(test_helpers.Say("Instance 4"))
331			Expect(outputBuffer).To(test_helpers.Say("UNCLAIMED"))
332
333			Expect(outputBuffer).NotTo(test_helpers.Say("InstanceGuid"))
334			Expect(outputBuffer).To(test_helpers.Say("Placement Error"))
335			Expect(outputBuffer).To(test_helpers.Say("insufficient resources."))
336			Expect(outputBuffer).To(test_helpers.Say("Crash Count"))
337			Expect(outputBuffer).To(test_helpers.Say("2"))
338
339			Expect(outputBuffer).To(test_helpers.Say("Instance 5"))
340			Expect(outputBuffer).To(test_helpers.Say("CRASHED"))
341
342			Expect(outputBuffer).NotTo(test_helpers.Say("InstanceGuid"))
343			Expect(outputBuffer).To(test_helpers.Say("Crash Count"))
344			Expect(outputBuffer).To(test_helpers.Say("7"))
345
346		})
347
348		Context("when there is a placement error on an actualLRP", func() {
349			It("Displays UNCLAIMED in red, and outputs only the placement error", func() {
350				appExaminer.AppStatusReturns(
351					app_examiner.AppInfo{
352						ActualInstances: []app_examiner.InstanceInfo{
353							app_examiner.InstanceInfo{
354								Index:          7,
355								State:          "UNCLAIMED",
356								PlacementError: "insufficient resources.",
357							},
358						},
359					}, nil)
360
361				test_helpers.ExecuteCommandWithArgs(statusCommand, []string{"swanky-app"})
362
363				Expect(outputBuffer).To(test_helpers.Say("Instance 7"))
364				Expect(outputBuffer).To(test_helpers.Say("UNCLAIMED"))
365
366				Expect(outputBuffer).ToNot(test_helpers.Say("InstanceGuid"))
367				Expect(outputBuffer).ToNot(test_helpers.Say("Cell ID"))
368				Expect(outputBuffer).ToNot(test_helpers.Say("Ip"))
369				Expect(outputBuffer).ToNot(test_helpers.Say("Port Mapping"))
370				Expect(outputBuffer).ToNot(test_helpers.Say("Since"))
371
372				Expect(outputBuffer).To(test_helpers.Say("Placement Error"))
373				Expect(outputBuffer).To(test_helpers.Say("insufficient resources."))
374
375			})
376		})
377
378		Context("When no appName is specified", func() {
379			It("Prints usage information", func() {
380				test_helpers.ExecuteCommandWithArgs(statusCommand, []string{})
381				Expect(outputBuffer).To(test_helpers.SayIncorrectUsage())
382			})
383		})
384
385		It("prints any errors from app examiner", func() {
386			appExaminer.AppStatusReturns(app_examiner.AppInfo{}, errors.New("You want the status?? ...YOU CAN'T HANDLE THE STATUS!!!"))
387
388			test_helpers.ExecuteCommandWithArgs(statusCommand, []string{"zany-app"})
389
390			Expect(outputBuffer).To(test_helpers.Say("You want the status?? ...YOU CAN'T HANDLE THE STATUS!!!"))
391		})
392
393		Context("When Annotation is empty", func() {
394			It("omits Annotation from the output", func() {
395				appExaminer.AppStatusReturns(app_examiner.AppInfo{ProcessGuid: "jumpy-app"}, nil)
396
397				test_helpers.ExecuteCommandWithArgs(statusCommand, []string{"jumpy-app"})
398
399				Expect(outputBuffer).NotTo(test_helpers.Say("Annotation"))
400			})
401		})
402	})
403})
404
Full Screen

locket_test.go

Source: locket_test.go Github

copy
1package main_test
2
3import (
4	"fmt"
5	"os"
6	"time"
7
8	"golang.org/x/net/context"
9
10	"code.cloudfoundry.org/clock"
11	"code.cloudfoundry.org/lager"
12	"code.cloudfoundry.org/lager/lagertest"
13	"code.cloudfoundry.org/locket"
14	"code.cloudfoundry.org/routing-api"
15	"code.cloudfoundry.org/routing-api/cmd/routing-api/testrunner"
16	"code.cloudfoundry.org/routing-api/config"
17	"code.cloudfoundry.org/routing-api/test_helpers"
18
19	"code.cloudfoundry.org/locket/lock"
20	locketmodels "code.cloudfoundry.org/locket/models"
21	. "github.com/onsi/ginkgo"
22	. "github.com/onsi/gomega"
23	"github.com/onsi/gomega/gbytes"
24	"github.com/onsi/gomega/gexec"
25	"github.com/tedsuo/ifrit"
26	"github.com/tedsuo/ifrit/ginkgomon"
27)
28
29var _ = Describe("Locket", func() {
30	var (
31		routingAPIConfig *config.Config
32		configFilePath   string
33		session          *gexec.Session
34
35		logger lager.Logger
36	)
37
38	routingAPIShouldBeReachable := func() {
39		Eventually(func() error {
40			_, err := client.Routes()
41			return err
42		}).Should(Succeed())
43	}
44
45	BeforeEach(func() {
46		logger = lagertest.NewTestLogger("locket-test")
47
48		cc := defaultConfig
49		routingAPIConfig = getRoutingAPIConfig(cc)
50	})
51
52	JustBeforeEach(func() {
53		configFilePath = writeConfigToTempFile(routingAPIConfig)
54		args := testrunner.Args{
55			IP:         routingAPIIP,
56			ConfigPath: configFilePath,
57			DevMode:    true,
58		}
59		args.ConfigPath = configFilePath
60		session = RoutingApi(args.ArgSlice()...)
61	})
62
63	AfterEach(func() {
64		if session != nil {
65			session.Kill().Wait(10 * time.Second)
66		}
67
68		err := os.RemoveAll(configFilePath)
69		Expect(err).ToNot(HaveOccurred())
70	})
71
72	Context("with invalid configuration", func() {
73		Context("and the UUID is not present", func() {
74			BeforeEach(func() {
75				routingAPIConfig.UUID = ""
76			})
77
78			It("exits with an error", func() {
79				Eventually(session).Should(gexec.Exit(1))
80			})
81		})
82	})
83	Context("with valid configuration", func() {
84		It("uses the configured UUID as the owner", func() {
85			locketClient, err := locket.NewClient(logger, routingAPIConfig.Locket)
86			Expect(err).NotTo(HaveOccurred())
87
88			var lock *locketmodels.FetchResponse
89			Eventually(func() error {
90				lock, err = locketClient.Fetch(context.Background(), &locketmodels.FetchRequest{
91					Key: "routing_api_lock",
92				})
93				return err
94			}).ShouldNot(HaveOccurred())
95
96			Expect(lock.Resource.Owner).To(Equal(routingAPIConfig.UUID))
97		})
98
99		It("acquires the lock in locket and becomes active", func() {
100			routingAPIShouldBeReachable()
101		})
102
103		Context("and the locking server becomes unreachable after grabbing the lock", func() {
104			JustBeforeEach(func() {
105				routingAPIShouldBeReachable()
106
107				ginkgomon.Interrupt(locketProcess)
108			})
109
110			It("exits", func() {
111				Eventually(session, 30).Should(gexec.Exit(1))
112			})
113		})
114
115		Context("when the lock is not available", func() {
116			var competingProcess ifrit.Process
117
118			BeforeEach(func() {
119				locketClient, err := locket.NewClient(logger, routingAPIConfig.Locket)
120				Expect(err).NotTo(HaveOccurred())
121
122				lockIdentifier := &locketmodels.Resource{
123					Key:      "routing_api_lock",
124					Owner:    "Your worst enemy.",
125					Value:    "Something",
126					TypeCode: locketmodels.LOCK,
127				}
128
129				clock := clock.NewClock()
130				competingRunner := lock.NewLockRunner(logger, locketClient, lockIdentifier, 5, clock, locket.RetryInterval)
131				competingProcess = ginkgomon.Invoke(competingRunner)
132			})
133
134			AfterEach(func() {
135				ginkgomon.Interrupt(competingProcess)
136			})
137
138			It("does not become active", func() {
139				Consistently(func() error {
140					_, err := client.Routes()
141					return err
142				}).ShouldNot(Succeed())
143			})
144
145			Context("and the lock becomes available", func() {
146				JustBeforeEach(func() {
147					Consistently(func() error {
148						_, err := client.Routes()
149						return err
150					}).ShouldNot(Succeed())
151
152					ginkgomon.Interrupt(competingProcess)
153				})
154
155				It("grabs the lock and becomes active", func() {
156					routingAPIShouldBeReachable()
157				})
158			})
159		})
160	})
161
162	Context("when a rolling deploy occurs", func() {
163		It("ensures there is no downtime", func() {
164			Eventually(session, 10*time.Second).Should(gbytes.Say("routing-api.started"))
165
166			session2Port := uint16(test_helpers.NextAvailPort())
167			session2MTLSPort := uint16(test_helpers.NextAvailPort())
168			apiConfig := getRoutingAPIConfig(defaultConfig)
169			apiConfig.API.ListenPort = int(session2Port)
170			apiConfig.API.MTLSListenPort = int(session2MTLSPort)
171			apiConfig.AdminPort = test_helpers.NextAvailPort()
172			configFilePath := writeConfigToTempFile(apiConfig)
173			session2Args := testrunner.Args{
174				IP:         routingAPIIP,
175				ConfigPath: configFilePath,
176				DevMode:    true,
177			}
178			session2 := RoutingApi(session2Args.ArgSlice()...)
179
180			defer func() {
181				session2.Interrupt().Wait(10 * time.Second)
182			}()
183			Eventually(session2, 10*time.Second).Should(gbytes.Say("locket-lock.started"))
184			done := make(chan struct{})
185			goRoutineFinished := make(chan struct{})
186			client2 := routing_api.NewClient(fmt.Sprintf("http://127.0.0.1:%d", session2Port), false)
187
188			go func() {
189				defer GinkgoRecover()
190
191				var err1, err2 error
192
193				ticker := time.NewTicker(time.Second)
194				for range ticker.C {
195					select {
196					case <-done:
197						close(goRoutineFinished)
198						ticker.Stop()
199						return
200					default:
201						_, err1 = client.Routes()
202						_, err2 = client2.Routes()
203						Expect([]error{err1, err2}).To(ContainElement(Not(HaveOccurred())), "At least one of the errors should not have occurred")
204					}
205				}
206			}()
207
208			session.Interrupt().Wait(10 * time.Second)
209
210			Eventually(session2, 10*time.Second).Should(gbytes.Say("locket-lock.acquired-lock"))
211			Eventually(session2, 10*time.Second).Should(gbytes.Say("routing-api.started"))
212
213			close(done)
214			Eventually(done).Should(BeClosed())
215			Eventually(goRoutineFinished).Should(BeClosed())
216
217			_, err := client2.Routes()
218			Expect(err).ToNot(HaveOccurred())
219		})
220	})
221})
222
Full Screen

integration_suite_test.go

Source: integration_suite_test.go Github

copy
1package integration_test
2
3import (
4	"encoding/json"
5	"io/ioutil"
6	"log"
7	"os"
8	"os/exec"
9
10	"google.golang.org/grpc/grpclog"
11
12	"code.cloudfoundry.org/bbs/test_helpers"
13	"code.cloudfoundry.org/bbs/test_helpers/sqlrunner"
14	"code.cloudfoundry.org/consuladapter/consulrunner"
15	"code.cloudfoundry.org/locket/cmd/locket/config"
16	"code.cloudfoundry.org/locket/cmd/locket/testrunner"
17
18	. "github.com/onsi/ginkgo"
19	. "github.com/onsi/gomega"
20	"github.com/onsi/gomega/gbytes"
21	"github.com/onsi/gomega/gexec"
22	"github.com/onsi/gomega/ghttp"
23	"github.com/tedsuo/ifrit"
24	"github.com/tedsuo/ifrit/ginkgomon"
25
26	"fmt"
27	"testing"
28)
29
30var (
31	cfdotPath, locketPath string
32	locketRunner          *ginkgomon.Runner
33	locketProcess         ifrit.Process
34	dbRunner              sqlrunner.SQLRunner
35	dbProcess             ifrit.Process
36	consulRunner          *consulrunner.ClusterRunner
37	locketAPILocation     string
38	locketCACertFile      string
39)
40
41var bbsServer *ghttp.Server
42
43var _ = SynchronizedBeforeSuite(func() []byte {
44	binPath, err := gexec.Build("code.cloudfoundry.org/cfdot")
45	Expect(err).NotTo(HaveOccurred())
46
47	locketBinPath, err := gexec.Build("code.cloudfoundry.org/locket/cmd/locket")
48	Expect(err).NotTo(HaveOccurred())
49
50	bytes, err := json.Marshal([]string{binPath, locketBinPath})
51	Expect(err).NotTo(HaveOccurred())
52
53	return []byte(bytes)
54}, func(data []byte) {
55	grpclog.SetLogger(log.New(ioutil.Discard, "", 0))
56	paths := []string{}
57	err := json.Unmarshal(data, &paths)
58	Expect(err).NotTo(HaveOccurred())
59	cfdotPath = paths[0]
60	locketPath = paths[1]
61})
62
63var _ = SynchronizedAfterSuite(func() {
64}, func() {
65	gexec.CleanupBuildArtifacts()
66})
67
68var _ = BeforeEach(func() {
69	bbsServer = ghttp.NewServer()
70	port := 8090 + GinkgoParallelNode()
71	locketAPILocation = fmt.Sprintf("localhost:%d", port)
72	wd, _ := os.Getwd()
73	locketCACertFile = fmt.Sprintf("%s/fixtures/locketCA.crt", wd)
74
75	dbName := fmt.Sprintf("diego_%d", GinkgoParallelNode())
76	dbRunner = test_helpers.NewSQLRunner(dbName)
77	dbProcess = ginkgomon.Invoke(dbRunner)
78
79	consulRunner = consulrunner.NewClusterRunner(
80		consulrunner.ClusterRunnerConfig{
81			StartingPort: 9001 + GinkgoParallelNode()*consulrunner.PortOffsetLength,
82			NumNodes:     1,
83			Scheme:       "http",
84		},
85	)
86	consulRunner.Start()
87
88	locketRunner = testrunner.NewLocketRunner(locketPath, func(cfg *config.LocketConfig) {
89		cfg.CaFile = locketCACertFile
90		cfg.ListenAddress = locketAPILocation
91		cfg.ConsulCluster = consulRunner.ConsulCluster()
92		cfg.DatabaseDriver = dbRunner.DriverName()
93		cfg.DatabaseConnectionString = dbRunner.ConnectionString()
94	})
95	locketProcess = ginkgomon.Invoke(locketRunner)
96})
97
98var _ = AfterEach(func() {
99	bbsServer.CloseClientConnections()
100	bbsServer.Close()
101	ginkgomon.Interrupt(locketProcess)
102	dbProcess.Signal(os.Interrupt)
103	consulRunner.Stop()
104})
105
106func TestIntegration(t *testing.T) {
107	RegisterFailHandler(Fail)
108	RunSpecs(t, "Integration Suite")
109}
110
111// Pass arguments that would be passed to cfdot
112// i.e. set-domain domain1
113func itValidatesBBSFlags(args ...string) {
114	Context("BBS Flag Validation", func() {
115		It("exits with status 3 when no bbs flags are specified", func() {
116			cmd := exec.Command(cfdotPath, args...)
117
118			sess, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)
119			Expect(err).NotTo(HaveOccurred())
120			Eventually(sess.Exited).Should(BeClosed())
121
122			Expect(sess.ExitCode()).To(Equal(3))
123		})
124	})
125}
126
127// Pass arguments that would be passed to cfdot
128func itValidatesLocketFlags(args ...string) {
129	Context("Locket Flag Validation", func() {
130		It("exits with status 3 when no locket flags are specified", func() {
131			cmd := exec.Command(cfdotPath, args...)
132
133			sess, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)
134			Expect(err).NotTo(HaveOccurred())
135			Eventually(sess.Exited).Should(BeClosed())
136
137			Expect(sess.ExitCode()).To(Equal(3))
138		})
139	})
140}
141
142func itHasNoArgs(command string, locketFlags bool) {
143	var (
144		sess *gexec.Session
145	)
146	Context("when any arguments are passed", func() {
147		BeforeEach(func() {
148			urlFlag := "--bbsURL"
149			url := bbsServer.URL()
150			if locketFlags {
151				urlFlag = "--locketAPILocation"
152				url = locketAPILocation
153			}
154			cfdotCmd := exec.Command(cfdotPath, urlFlag, url, command, "extra-arg")
155
156			var err error
157			sess, err = gexec.Start(cfdotCmd, GinkgoWriter, GinkgoWriter)
158			Expect(err).NotTo(HaveOccurred())
159
160			Eventually(sess.Exited).Should(BeClosed())
161		})
162
163		It("exits with status code of 3", func() {
164			Expect(sess.ExitCode()).To(Equal(3))
165		})
166
167		It("prints the usage to stderr", func() {
168			Expect(sess.Err).To(gbytes.Say(fmt.Sprintf("cfdot %s \\[flags\\]", command)))
169		})
170	})
171}
172
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)