How to use GinkgoT method of ginkgo Package

Best Ginkgo code snippet using ginkgo.GinkgoT

Run Ginkgo automation tests on LambdaTest cloud grid

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

validation_test.go

Source: validation_test.go Github

copy
1package validation
2
3import (
4	"fmt"
5
6	"time"
7
8	. "github.com/onsi/ginkgo"
9)
10
11var _ = Describe("Testing with Ginkgo", func() {
12	It("date time string", func() {
13
14		if !isValidDateTime("2012-06-03T13:26:00") {
15			GinkgoT().Errorf("WAT!")
16		}
17	})
18	It("badly formatted start at fails", func() {
19
20		args := make(map[string][]string)
21		args["start_at"] = []string{"i am not a time"}
22		expectError(expectation{t: GinkgoT(), args: args})
23	})
24	It("well formatted start at is okay", func() {
25
26		args := make(map[string][]string)
27		args["start_at"] = []string{"2000-02-02T00:02:02 +00:00"}
28		args["end_at"] = []string{"2000-02-09T00:02:02 +00:00"}
29		expectSuccess(expectation{t: GinkgoT(), args: args})
30	})
31	It("multiple start at args fail", func() {
32
33		args := make(map[string][]string)
34		args["start_at"] = []string{"2000-02-02T00:02:02 +00:00", "2000-03-02T00:02:02 +00:00"}
35		expectError(expectation{t: GinkgoT(), args: args})
36	})
37	It("invalid start date fails", func() {
38
39		args := make(map[string][]string)
40		args["start_at"] = []string{"2000-14-28T00:02:02 +00:00"}
41		expectError(expectation{t: GinkgoT(), args: args})
42	})
43	It("date parsing", func() {
44
45		v, err := time.Parse(time.RFC3339, "2000-14-28T00:02:02 +00:00")
46
47		if err == nil {
48			GinkgoT().Errorf("time was parsed as %v", v)
49		}
50	})
51	It("badly formatted end at fails", func() {
52
53		args := make(map[string][]string)
54		args["end_at"] = []string{"i am not a time"}
55		expectError(expectation{t: GinkgoT(), args: args})
56	})
57	It("well formatted end at is allowed", func() {
58
59		args := make(map[string][]string)
60		args["start_at"] = []string{"2000-01-26T00:02:02 +00:00"}
61		args["end_at"] = []string{"2000-02-02T00:02:02 +00:00"}
62		expectSuccess(expectation{t: GinkgoT(), args: args})
63	})
64	It("filter by query requires field and name", func() {
65
66		args := make(map[string][]string)
67		args["filter_by"] = []string{"bar"}
68		expectError(expectation{t: GinkgoT(), args: args})
69	})
70	It("well formatted filter by is okay", func() {
71
72		args := make(map[string][]string)
73		args["filter_by"] = []string{"foo:bar"}
74		expectSuccess(expectation{t: GinkgoT(), args: args})
75	})
76	It("all filter by args are validated", func() {
77
78		args := make(map[string][]string)
79		args["filter_by"] = []string{"foo:bar", "baz"}
80		expectError(expectation{t: GinkgoT(), args: args})
81	})
82	It("filter by field name is validated", func() {
83
84		args := make(map[string][]string)
85		args["filter_by"] = []string{"with-hyphen:bar"}
86		expectError(expectation{t: GinkgoT(), args: args})
87	})
88	It("filter by field name cannot look like mongo thing", func() {
89
90		args := make(map[string][]string)
91		args["filter_by"] = []string{"$foo:bar"}
92		expectError(expectation{t: GinkgoT(), args: args})
93	})
94	It("sort by ascending is okay", func() {
95
96		args := make(map[string][]string)
97		args["sort_by"] = []string{"foo:ascending"}
98		expectSuccess(expectation{t: GinkgoT(), args: args})
99	})
100	It("sort by descending is okay", func() {
101
102		args := make(map[string][]string)
103		args["sort_by"] = []string{"foo:descending"}
104		expectSuccess(expectation{t: GinkgoT(), args: args})
105	})
106	It("sort by anything else fails", func() {
107
108		args := make(map[string][]string)
109		args["sort_by"] = []string{"foo:random"}
110		expectError(expectation{t: GinkgoT(), args: args})
111		args["sort_by"] = []string{"lulz"}
112		expectError(expectation{t: GinkgoT(), args: args})
113	})
114	It("sort by requires a valid field name", func() {
115
116		args := make(map[string][]string)
117		args["sort_by"] = []string{"with-hyphen:ascending"}
118		expectError(expectation{t: GinkgoT(), args: args})
119	})
120	It("limit should be a positive integer", func() {
121
122		args := make(map[string][]string)
123		args["limit"] = []string{"not_a_number"}
124		expectError(expectation{t: GinkgoT(), args: args})
125		args["limit"] = []string{"-3"}
126		expectError(expectation{t: GinkgoT(), args: args})
127		args["limit"] = []string{"3"}
128		expectSuccess(expectation{t: GinkgoT(), args: args})
129	})
130	It("group by on internal name fails", func() {
131
132		args := make(map[string][]string)
133		args["group_by"] = []string{"_internal_field"}
134		expectError(expectation{t: GinkgoT(), args: args})
135	})
136	It("group by on invalid field name fails", func() {
137
138		args := make(map[string][]string)
139		args["group_by"] = []string{"with-hyphen"}
140		expectError(expectation{t: GinkgoT(), args: args})
141	})
142	It("sort by with period only fails", func() {
143
144		args := make(map[string][]string)
145		args["sort_by"] = []string{"foo:ascending"}
146		args["period"] = []string{"week"}
147		args["start_at"] = []string{"2012-11-12T00:00:00Z"}
148		args["end_at"] = []string{"2012-12-03T00:00:00Z"}
149		expectError(expectation{t: GinkgoT(), args: args})
150	})
151	It("sort by with period and group by is okay", func() {
152
153		args := make(map[string][]string)
154		args["sort_by"] = []string{"foo:ascending"}
155		args["period"] = []string{"week"}
156		args["group_by"] = []string{"foobar"}
157		args["start_at"] = []string{"2012-11-12T00:00:00Z"}
158		args["end_at"] = []string{"2012-12-03T00:00:00Z"}
159		expectSuccess(expectation{t: GinkgoT(), args: args})
160	})
161	It("collect without group by fails", func() {
162
163		args := make(map[string][]string)
164		args["collect"] = []string{"bar"}
165		expectError(expectation{t: GinkgoT(), args: args})
166	})
167	It("collect and group by is okay", func() {
168
169		args := make(map[string][]string)
170		args["collect"] = []string{"bar"}
171		args["group_by"] = []string{"foo"}
172		expectSuccess(expectation{t: GinkgoT(), args: args})
173	})
174	It("collect is okay", func() {
175
176		args := make(map[string][]string)
177		args["collect"] = []string{"a_aAbBzZ_"}
178		args["group_by"] = []string{"foo"}
179		expectSuccess(expectation{t: GinkgoT(), args: args})
180	})
181	It("collect with function fails", func() {
182
183		args := make(map[string][]string)
184		args["collect"] = []string{"something);while(1){myBadFunction()}"}
185		args["group_by"] = []string{"foo"}
186		expectError(expectation{t: GinkgoT(), args: args})
187	})
188	It("collect with a hyphen fails", func() {
189
190		args := make(map[string][]string)
191		args["collect"] = []string{"with-hyphen"}
192		args["group_by"] = []string{"foo"}
193		expectError(expectation{t: GinkgoT(), args: args})
194	})
195	It("collect with a mongo thing fails", func() {
196
197		args := make(map[string][]string)
198		args["collect"] = []string{"$foo"}
199		args["group_by"] = []string{"foo"}
200		expectError(expectation{t: GinkgoT(), args: args})
201	})
202	It("collect on same field as group by fails", func() {
203
204		args := make(map[string][]string)
205		args["collect"] = []string{"foo"}
206		args["group_by"] = []string{"foo"}
207		expectError(expectation{t: GinkgoT(), args: args})
208	})
209	It("collect on internal field fails", func() {
210
211		args := make(map[string][]string)
212		args["collect"] = []string{"_foo"}
213		args["group_by"] = []string{"foo"}
214		expectError(expectation{t: GinkgoT(), args: args})
215	})
216	It("multiple collect is okay", func() {
217
218		args := make(map[string][]string)
219		args["collect"] = []string{"bar", "baz"}
220		args["group_by"] = []string{"foo"}
221		expectSuccess(expectation{t: GinkgoT(), args: args})
222	})
223	It("collect with later internal parameter fails", func() {
224
225		args := make(map[string][]string)
226		args["collect"] = []string{"bar", "_baz"}
227		args["group_by"] = []string{"foo"}
228		expectError(expectation{t: GinkgoT(), args: args})
229	})
230	It("collect has a whitelist of methods", func() {
231
232		args := make(map[string][]string)
233		args["group_by"] = []string{"foo"}
234
235		for _, method := range []string{"sum", "count", "set", "mean"} {
236			args["collect"] = []string{fmt.Sprintf("field:%s", method)}
237			expectSuccess(expectation{t: GinkgoT(), args: args})
238		}
239	})
240	It("collect with invalid method fails", func() {
241
242		args := make(map[string][]string)
243		args["group_by"] = []string{"foo"}
244		args["collect"] = []string{"field:foobar"}
245		expectError(expectation{t: GinkgoT(), args: args})
246	})
247	It("duration requires other parameters", func() {
248
249		args := make(map[string][]string)
250		args["duration"] = []string{"3"}
251		expectError(expectation{t: GinkgoT(), args: args})
252	})
253	It("duration must be positive integer", func() {
254
255		args := make(map[string][]string)
256		args["duration"] = []string{"0"}
257		args["period"] = []string{"day"}
258		expectError(expectation{t: GinkgoT(), args: args})
259
260		args["duration"] = []string{"3"}
261		expectSuccess(expectation{t: GinkgoT(), args: args})
262
263		args["duration"] = []string{"-3"}
264		args["period"] = []string{"day"}
265		expectError(expectation{t: GinkgoT(), args: args})
266	})
267	It("duration is a valid number", func() {
268
269		args := make(map[string][]string)
270		args["duration"] = []string{"not_a_number"}
271		args["period"] = []string{"day"}
272		expectError(expectation{t: GinkgoT(), args: args})
273	})
274	It("period and duration with start at is okay", func() {
275
276		args := make(map[string][]string)
277		args["duration"] = []string{"3"}
278		args["period"] = []string{"day"}
279		args["start_at"] = []string{"2000-02-02T00:00:00+00:00"}
280		expectSuccess(expectation{t: GinkgoT(), args: args})
281	})
282	It("start at alone fails", func() {
283
284		args := make(map[string][]string)
285		args["start_at"] = []string{"2000-02-02T00:00:00+00:00"}
286		expectError(expectation{t: GinkgoT(), args: args})
287	})
288	It("end at alone fails", func() {
289
290		args := make(map[string][]string)
291		args["end_at"] = []string{"2000-02-02T00:00:00+00:00"}
292		expectError(expectation{t: GinkgoT(), args: args})
293	})
294	It("duration with start at and end at fails", func() {
295
296		args := make(map[string][]string)
297		args["duration"] = []string{"3"}
298		args["period"] = []string{"day"}
299		args["start_at"] = []string{"2000-02-02T00:00:00+00:00"}
300		args["end_at"] = []string{"2000-02-09T00:00:00+00:00"}
301		expectError(expectation{t: GinkgoT(), args: args})
302	})
303	It("period has a limited vocabulary", func() {
304
305		args := make(map[string][]string)
306		args["duration"] = []string{"3"}
307		args["period"] = []string{"fortnight"}
308		args["start_at"] = []string{"2000-02-02T00:00:00+00:00"}
309		expectError(expectation{t: GinkgoT(), args: args})
310	})
311	It("period with start at and end at is okay", func() {
312
313		args := make(map[string][]string)
314		args["period"] = []string{"week"}
315		args["start_at"] = []string{"2000-02-02T00:00:00+00:00"}
316		args["end_at"] = []string{"2000-02-09T00:00:00+00:00"}
317		expectSuccess(expectation{t: GinkgoT(), args: args, allowRawQueries: true})
318	})
319	It("no raw queries with period with start at and end at on wednesday fails", func() {
320
321		args := make(map[string][]string)
322		args["period"] = []string{"week"}
323		args["start_at"] = []string{"2000-02-02T00:00:00+00:00"}
324		args["end_at"] = []string{"2000-02-09T00:00:00+00:00"}
325		expectError(expectation{t: GinkgoT(), args: args, allowRawQueries: false})
326	})
327	It("no raw queries with period with start at and end at on monday is okay", func() {
328
329		args := make(map[string][]string)
330		args["period"] = []string{"week"}
331		args["start_at"] = []string{"2000-02-07T00:00:00+00:00"}
332		args["end_at"] = []string{"2000-02-14T00:00:00+00:00"}
333		expectSuccess(expectation{t: GinkgoT(), args: args, allowRawQueries: false})
334	})
335	It("no raw queries means use midnight", func() {
336
337		args := make(map[string][]string)
338		args["period"] = []string{"day"}
339		args["start_at"] = []string{"2000-02-02T00:00:00+00:00"}
340		args["end_at"] = []string{"2000-02-09T00:00:00+00:00"}
341		expectSuccess(expectation{t: GinkgoT(), args: args})
342	})
343	It("no raw queries for a day period with hourse in the middle of the day fails", func() {
344
345		args := make(map[string][]string)
346		args["period"] = []string{"day"}
347		args["start_at"] = []string{"2000-02-02T12:00:00+00:00"}
348		args["end_at"] = []string{"2000-02-09T13:00:00+00:00"}
349		expectError(expectation{t: GinkgoT(), args: args})
350	})
351	It("no raw queries for an hour period allows time in the middle of the day", func() {
352
353		args := make(map[string][]string)
354		args["period"] = []string{"hour"}
355		args["start_at"] = []string{"2000-02-02T12:00:00+00:00"}
356		args["end_at"] = []string{"2000-02-09T13:00:00+00:00"}
357		expectSuccess(expectation{t: GinkgoT(), args: args})
358	})
359	It("no raw queries for a day period less than7 days fails", func() {
360
361		args := make(map[string][]string)
362		args["period"] = []string{"day"}
363		args["start_at"] = []string{"2000-02-02T00:00:00+00:00"}
364		args["end_at"] = []string{"2000-02-08T00:00:00+00:00"}
365		expectError(expectation{t: GinkgoT(), args: args})
366	})
367	It("no raw queries for an hour period are allowed", func() {
368
369		args := make(map[string][]string)
370		args["period"] = []string{"hour"}
371		args["start_at"] = []string{"2000-02-02T00:00:00+00:00"}
372		args["end_at"] = []string{"2000-02-08T00:00:00+00:00"}
373		expectSuccess(expectation{t: GinkgoT(), args: args})
374	})
375	It("no raw queries with month period with start at and end at on third fails", func() {
376
377		args := make(map[string][]string)
378		args["period"] = []string{"month"}
379		args["start_at"] = []string{"2000-02-03T00:00:00+00:00"}
380		args["end_at"] = []string{"2000-03-03T00:00:00+00:00"}
381		expectError(expectation{t: GinkgoT(), args: args, allowRawQueries: false})
382	})
383	It("no raw queries with month period with start at and end at on first is okay", func() {
384
385		args := make(map[string][]string)
386		args["period"] = []string{"month"}
387		args["start_at"] = []string{"2000-02-01T00:00:00+00:00"}
388		args["end_at"] = []string{"2000-03-01T00:00:00+00:00"}
389		expectSuccess(expectation{t: GinkgoT(), args: args, allowRawQueries: false})
390	})
391})
392
393type expectation struct {
394	t               GinkgoTInterface
395	args            map[string][]string
396	allowRawQueries bool
397}
398
399func expectError(e expectation) {
400	if ValidateRequestArgs(e.args, e.allowRawQueries) == nil {
401		e.t.Errorf("%v should have failed", e.args)
402	}
403}
404
405func expectSuccess(e expectation) {
406	if err := ValidateRequestArgs(e.args, e.allowRawQueries); err != nil {
407		e.t.Errorf("%v should have been okay but was %v", e.args, err)
408	}
409}
410
Full Screen

golang_test_test.go

Source: golang_test_test.go Github

copy
1package main
2
3import (
4	"encoding/json"
5	"net/http"
6	"net/http/httptest"
7	"strings"
8
9	. "github.com/onsi/ginkgo"
10)
11
12var _ = Describe("Testing with Ginkgo", func() {
13	It("get post", func() {
14
15		mux := http.NewServeMux()
16		mux.HandleFunc("/post/", handlerRequest(&FakePost{}))
17
18		writer := httptest.NewRecorder()
19		request, _ := http.NewRequest("GET", "/post/1", nil)
20		mux.ServeHTTP(writer, request)
21
22		if writer.Code != 200 {
23			GinkgoT().Errorf("Response code is %v", writer.Code)
24		}
25		var post Post
26		json.Unmarshal(writer.Body.Bytes(), &post)
27		if post.Id != 1 {
28			GinkgoT().Errorf("Cannot retrieve JSON post")
29		}
30	})
31
32	It("put post", func() {
33
34		mux := http.NewServeMux()
35		post := &FakePost{}
36		mux.HandleFunc("/post/", handlerRequest(post))
37
38		writer := httptest.NewRecorder()
39		json := strings.NewReader(`{"content": "Updated post", "author": "NAO"}`)
40		request, _ := http.NewRequest("PUT", "/post/1", json)
41		mux.ServeHTTP(writer, request)
42
43		if writer.Code != 200 {
44			GinkgoT().Errorf("Response code is %v", writer.Code)
45		}
46		if post.Content != "Updated post" {
47			GinkgoT().Errorf("Content is not corrent", post.Content)
48		}
49	})
50})
51
Full Screen

lock_watcher_test.go

Source: lock_watcher_test.go Github

copy
1package main
2
3import (
4    "time"
5    "fmt"
6
7    "github.com/stretchr/testify/mock"
8    "github.com/armon/consul-api"
9    "github.com/bluestatedigital/riemann-consul-receiver/consul-mocks"
10)
11
12var _ = Describe("LockWatcher", func() {
13    var receiver *LockWatcher
14    var err error
15    
16    var mockAgent   consulmocks.MockAgent
17    var mockSession consulmocks.MockSession
18    var mockKV      consulmocks.MockKV
19    var mockHealth  consulmocks.MockHealth
20    
21    serviceName := "some-service"
22    keyName     := "some/key"
23    nodeName    := "some-node"
24    sessionID   := "42"
25
26    updateInterval := time.Minute + (time.Second * 42)
27    lockDelay := time.Second * 15
28    
29    BeforeEach(func() {
30        mockAgent = consulmocks.MockAgent{}
31        
32        mockAgent.On("Self").Return(
33            map[string]map[string]interface{}{
34                "Config": map[string]interface{}{
35                    "NodeName": nodeName,
36                },
37            },
38            nil,
39        )
40        
41        receiver, err = NewLockWatcher(
42            &mockAgent,
43            &mockSession,
44            &mockKV,
45            &mockHealth,
46
47            updateInterval,
48            lockDelay,
49
50            serviceName,
51            keyName,
52        )
53        
54        mockAgent.AssertExpectations(GinkgoT())
55
56        Expect(receiver).NotTo(BeNil())
57        Expect(err).To(BeNil())
58        
59        // replace with a fresh instance
60        mockAgent = consulmocks.MockAgent{}
61        
62        // not used in setup
63        mockSession = consulmocks.MockSession{}
64        mockKV      = consulmocks.MockKV{}
65        mockHealth  = consulmocks.MockHealth{}
66    })
67    
68    registersService := func() {
69        // expect the call to ServiceRegister
70        mockAgent.On(
71            "ServiceRegister",
72            mock.AnythingOfType("*consulapi.AgentServiceRegistration"),
73        ).Return(nil)
74        
75        // invoke the object under test
76        receiver.RegisterService()
77        
78        mockAgent.AssertExpectations(GinkgoT())
79        
80        // retrieve the call and its arguments
81        svcRegCall := mockAgent.Calls[0]
82        Expect(svcRegCall.Method).To(Equal("ServiceRegister"))
83        
84        svcReg := svcRegCall.Arguments.Get(0).(*consulapi.AgentServiceRegistration)
85        
86        // verify the service registration
87        Expect(svcReg.ID).To(Equal(serviceName))
88        Expect(svcReg.Name).To(Equal(serviceName))
89        Expect(svcReg.Check.TTL).To(Equal("306s")) // 3 times the update interval
90    }
91    
92    It("registers the service", registersService)
93    
94    passesHealthCheck := func() {
95        mockAgent.On("PassTTL", "service:" + serviceName, "").Return(nil)
96        
97        receiver.UpdateHealthCheck()
98        
99        mockAgent.AssertExpectations(GinkgoT())
100    }
101    
102    It("passes a health check", passesHealthCheck)
103    
104    initsNewSession := func() {
105        var nilQueryMeta *consulapi.QueryMeta = nil
106        
107        // searching for an existing session
108        mockSession.On(
109            "List",
110            mock.AnythingOfType("*consulapi.QueryOptions"),
111        ).Return([]*consulapi.SessionEntry{}, nilQueryMeta, nil)
112        
113        // health check must be passing before creating a session tied to that
114        // health check
115        mockAgent.On("PassTTL", "service:" + serviceName, "").Return(nil)
116        
117        // create the session
118        mockSession.On(
119            "Create",
120            mock.AnythingOfType("*consulapi.SessionEntry"),
121            mock.AnythingOfType("*consulapi.WriteOptions"),
122        ).Return(sessionID, &consulapi.WriteMeta{}, nil)
123        
124        // set it off
125        newSessionId, err := receiver.InitSession()
126        
127        mockAgent.AssertExpectations(GinkgoT())
128        
129        Expect(newSessionId).To(Equal(sessionID))
130        Expect(err).To(BeNil())
131        
132        // verify call to Session.Create()
133        sessCreateCall := mockSession.Calls[1]
134        Expect(sessCreateCall.Method).To(Equal("Create"))
135        
136        sess := sessCreateCall.Arguments.Get(0).(*consulapi.SessionEntry)
137        
138        // verify the session create request
139        Expect(sess.Name).To(Equal(serviceName))
140        Expect(sess.LockDelay).To(Equal(lockDelay))
141        Expect(len(sess.Checks)).To(Equal(2))
142        Expect(sess.Checks).To(ContainElement("serfHealth"))
143        Expect(sess.Checks).To(ContainElement("service:" + serviceName))
144    }
145    
146    It("initializes a new session", initsNewSession)
147    
148    It("finds an existing session", func() {
149        sessionID := "42"
150        
151        // searching for an existing session
152        mockSession.On(
153            "List",
154            mock.AnythingOfType("*consulapi.QueryOptions"),
155        ).Return(
156            []*consulapi.SessionEntry{
157                &consulapi.SessionEntry{
158                    Node: "some-other-node",
159                    Name: "some-other-name",
160                },
161                &consulapi.SessionEntry{
162                    Node: nodeName,
163                    Name: "some-other-name",
164                },
165                &consulapi.SessionEntry{
166                    Node: "some-other-node",
167                    Name: serviceName,
168                },
169                &consulapi.SessionEntry{ // this is the one!
170                    Node: nodeName,
171                    Name: serviceName,
172                    ID:   sessionID,
173                },
174            },
175            new(consulapi.QueryMeta),
176            nil,
177        )
178        
179        // set it off
180        existingSessionId, err := receiver.InitSession()
181        
182        mockAgent.AssertExpectations(GinkgoT())
183        
184        Expect(existingSessionId).To(Equal(sessionID))
185        Expect(err).To(BeNil())
186    })
187
188    Describe("lock acquisition", func() {
189        validSession := &consulapi.SessionEntry{}
190        genericQueryOpts := mock.AnythingOfType("*consulapi.QueryOptions")
191
192        BeforeEach(func() {
193            initsNewSession()
194        })
195        
196        // if the session is invalid, return error
197        // if the key's already locked by this session, return true.
198        // if the key's locked by someone else, return false.
199        // if the key's not locked, try to acquire it and return result
200        It("aborts if the session is invalid", func() {
201            mockSession.On("Info", sessionID, genericQueryOpts).Return(
202                nil,
203                new(consulapi.QueryMeta),
204                nil,
205            )
206            
207            _, err := receiver.AcquireLock()
208            
209            mockSession.AssertExpectations(GinkgoT())
210            mockKV.AssertExpectations(GinkgoT())
211            Expect(err).NotTo(BeNil())
212        })
213        
214        It("is already locked by us", func() {
215            mockSession.On("Info", sessionID, genericQueryOpts).Return(
216                validSession,
217                new(consulapi.QueryMeta),
218                nil,
219            )
220
221            mockKV.On("Get", keyName, genericQueryOpts).Return(
222                &consulapi.KVPair{
223                    Key: keyName,
224                    Session: sessionID,
225                },
226                new(consulapi.QueryMeta),
227                nil,
228            )
229            
230            success, err := receiver.AcquireLock()
231            
232            mockSession.AssertExpectations(GinkgoT())
233            mockKV.AssertExpectations(GinkgoT())
234            
235            Expect(success).To(Equal(true))
236            Expect(err).To(BeNil())
237        })
238        
239        It("is locked by someone else", func() {
240            mockSession.On("Info", sessionID, genericQueryOpts).Return(
241                validSession,
242                new(consulapi.QueryMeta),
243                nil,
244            )
245
246            mockKV.On("Get", keyName, genericQueryOpts).Return(
247                &consulapi.KVPair{
248                    Key: keyName,
249                    Session: "some-other-session",
250                },
251                new(consulapi.QueryMeta),
252                nil,
253            )
254            
255            success, err := receiver.AcquireLock()
256            
257            mockSession.AssertExpectations(GinkgoT())
258            mockKV.AssertExpectations(GinkgoT())
259            
260            Expect(success).To(Equal(false))
261            Expect(err).To(BeNil())
262        })
263
264        It("is able to be successfully locked", func() {
265            mockSession.On("Info", sessionID, genericQueryOpts).Return(
266                validSession,
267                new(consulapi.QueryMeta),
268                nil,
269            )
270
271            mockKV.On("Get", keyName, genericQueryOpts).Return(
272                &consulapi.KVPair{
273                    Key: keyName,
274                    Session: "",
275                },
276                new(consulapi.QueryMeta),
277                nil,
278            )
279            
280            mockKV.On(
281                "Acquire",
282                mock.AnythingOfType("*consulapi.KVPair"),
283                mock.AnythingOfType("*consulapi.WriteOptions"),
284            ).Return(true, new(consulapi.WriteMeta), nil)
285            
286            success, err := receiver.AcquireLock()
287            
288            mockSession.AssertExpectations(GinkgoT())
289            mockKV.AssertExpectations(GinkgoT())
290            
291            // verify call to KV.Acquire()
292            kvAcquire := mockKV.Calls[1]
293            Expect(kvAcquire.Method).To(Equal("Acquire"))
294            
295            kvp := kvAcquire.Arguments.Get(0).(*consulapi.KVPair)
296            Expect(kvp.Key).To(Equal(keyName))
297            Expect(kvp.Session).To(Equal(sessionID))
298            
299            Expect(success).To(Equal(true))
300            Expect(err).To(BeNil())
301        })
302
303        It("is not able to be successfully locked", func() {
304            mockSession.On("Info", sessionID, genericQueryOpts).Return(
305                validSession,
306                new(consulapi.QueryMeta),
307                nil,
308            )
309
310            mockKV.On("Get", keyName, genericQueryOpts).Return(
311                &consulapi.KVPair{
312                    Key: keyName,
313                    Session: "",
314                },
315                new(consulapi.QueryMeta),
316                nil,
317            )
318            
319            mockKV.On(
320                "Acquire",
321                mock.AnythingOfType("*consulapi.KVPair"),
322                mock.AnythingOfType("*consulapi.WriteOptions"),
323            ).Return(false, new(consulapi.WriteMeta), nil)
324            
325            success, err := receiver.AcquireLock()
326            
327            mockSession.AssertExpectations(GinkgoT())
328            mockKV.AssertExpectations(GinkgoT())
329            
330            // verify call to KV.Acquire()
331            kvAcquire := mockKV.Calls[1]
332            Expect(kvAcquire.Method).To(Equal("Acquire"))
333            
334            kvp := kvAcquire.Arguments.Get(0).(*consulapi.KVPair)
335            Expect(kvp.Key).To(Equal(keyName))
336            Expect(kvp.Session).To(Equal(sessionID))
337            
338            Expect(success).To(Equal(false))
339            Expect(err).To(BeNil())
340        })
341        
342        It("subsequent acquires are blocking queries", func() {
343            mockSession.On("Info", sessionID, genericQueryOpts).Return(
344                validSession,
345                new(consulapi.QueryMeta),
346                nil,
347            )
348
349            // initial Acquire(): locked by someone else
350            mockKV.On("Get", keyName, genericQueryOpts).Return(
351                &consulapi.KVPair{
352                    Key: keyName,
353                    Session: "some-other-session",
354                },
355                &consulapi.QueryMeta{
356                    LastIndex: 10,
357                },
358                nil,
359            ).Once()
360            
361            // next Acquire(): still locked, but uses previous LastIndex to it blocks
362            mockKV.On("Get", keyName, genericQueryOpts).Return(
363                &consulapi.KVPair{
364                    Key: keyName,
365                    Session: "some-other-session",
366                },
367                new(consulapi.QueryMeta),
368                nil,
369            ).Once()
370
371            success, err := receiver.AcquireLock()
372            success, err = receiver.AcquireLock()
373            Expect(success).To(Equal(false))
374            Expect(err).To(BeNil())
375
376            mockSession.AssertExpectations(GinkgoT())
377            mockKV.AssertExpectations(GinkgoT())
378            
379            // verify calls to KV.Get()
380            var kvGet mock.Call
381            var queryOpts *consulapi.QueryOptions
382            
383            // first call
384            kvGet = mockKV.Calls[0]
385            Expect(kvGet.Method).To(Equal("Get"))
386            
387            queryOpts = kvGet.Arguments.Get(1).(*consulapi.QueryOptions)
388            Expect(queryOpts).NotTo(BeNil())
389            Expect(queryOpts.WaitIndex).To(Equal(uint64(0)))
390            Expect(queryOpts.WaitTime).To(Equal(lockDelay))
391
392            // second call
393            kvGet = mockKV.Calls[1]
394            Expect(kvGet.Method).To(Equal("Get"))
395            
396            queryOpts = kvGet.Arguments.Get(1).(*consulapi.QueryOptions)
397            Expect(queryOpts).NotTo(BeNil())
398            Expect(queryOpts.WaitIndex).To(Equal(uint64(10)))
399            Expect(queryOpts.WaitTime).To(Equal(lockDelay))
400        })
401        
402        // AcquireLock can return false 
403        Describe("handles errors gracefully", func() {
404            It("returns false when unable to retrieve session info", func() {
405                mockSession.On("Info", sessionID, genericQueryOpts).Return(
406                    nil,
407                    nil,
408                    fmt.Errorf("Unexpected response code: 500 (rpc error: No cluster leader)"),
409                )
410                
411                locked, err := receiver.AcquireLock()
412                
413                mockSession.AssertExpectations(GinkgoT())
414                mockKV.AssertExpectations(GinkgoT())
415                Expect(locked).To(Equal(false))
416                Expect(err).To(BeNil())
417            })
418            
419            It("returns false when unable to retrieve key", func() {
420                mockSession.On("Info", sessionID, genericQueryOpts).Return(
421                    validSession,
422                    new(consulapi.QueryMeta),
423                    nil,
424                )
425
426                mockKV.On("Get", keyName, genericQueryOpts).Return(
427                    nil,
428                    nil,
429                    fmt.Errorf("Unexpected response code: 500 (rpc error: No cluster leader)"),
430                )
431                
432                locked, err := receiver.AcquireLock()
433                
434                mockSession.AssertExpectations(GinkgoT())
435                mockKV.AssertExpectations(GinkgoT())
436                Expect(locked).To(Equal(false))
437                Expect(err).To(BeNil())
438            })
439            
440            It("returns false when error acquiring lock on key", func() {
441                mockSession.On("Info", sessionID, genericQueryOpts).Return(
442                    validSession,
443                    new(consulapi.QueryMeta),
444                    nil,
445                )
446
447                mockKV.On("Get", keyName, genericQueryOpts).Return(
448                    &consulapi.KVPair{
449                        Key: keyName,
450                        Session: "",
451                    },
452                    new(consulapi.QueryMeta),
453                    nil,
454                )
455                
456                mockKV.On(
457                    "Acquire",
458                    mock.AnythingOfType("*consulapi.KVPair"),
459                    mock.AnythingOfType("*consulapi.WriteOptions"),
460                ).Return(
461                    false,
462                    nil,
463                    fmt.Errorf("Unexpected response code: 500 (rpc error: No cluster leader)"),
464                )
465                
466                locked, err := receiver.AcquireLock()
467                
468                mockSession.AssertExpectations(GinkgoT())
469                mockKV.AssertExpectations(GinkgoT())
470                Expect(locked).To(Equal(false))
471                Expect(err).To(BeNil())
472
473            })
474        })
475    })
476
477    Describe("lock watching", func() {
478        BeforeEach(func() {
479            initsNewSession()
480        })
481        
482        It("returns immediately if we don't have the lock", func(done Done) {
483            resultKvp := consulapi.KVPair{
484                Key: keyName,
485                Session: "",
486            }
487            
488            mockKV.On(
489                "Get",
490                keyName,
491                mock.AnythingOfType("*consulapi.QueryOptions"),
492            ).Return(
493                &resultKvp,
494                new(consulapi.QueryMeta),
495                nil,
496            )
497
498            // channel used to notify when lock has been lost; it'll just get
499            // closed
500            c := receiver.WatchLock()
501            
502            // wait for the lock to be lost
503            select {
504                case _, more := <-c:
505                    Expect(more).To(Equal(false))
506            }
507            
508            mockKV.AssertExpectations(GinkgoT())
509
510            // test's done *bing!*
511            close(done)
512        })
513        
514        It("polls the key until the lock is gone", func(done Done) {
515            genericQueryOpts := mock.AnythingOfType("*consulapi.QueryOptions")
516            
517            // first call; we have the lock
518            mockKV.On("Get", keyName, genericQueryOpts).Return(
519                &consulapi.KVPair{
520                    Key: keyName,
521                    Session: sessionID,
522                },
523                &consulapi.QueryMeta{
524                    LastIndex: 10,
525                },
526                nil,
527            ).Once()
528            
529            // 2nd call; lost lock
530            mockKV.On("Get", keyName, genericQueryOpts).Return(
531                &consulapi.KVPair{
532                    Key: keyName,
533                    Session: "",
534                },
535                new(consulapi.QueryMeta),
536                nil,
537            ).Once()
538
539            // channel used to notify when lock has been lost; it'll just get
540            // closed
541            c := receiver.WatchLock()
542            
543            // wait for the lock to be lost
544            select {
545                case _, more := <-c:
546                    Expect(more).To(Equal(false))
547            }
548            
549            mockKV.AssertExpectations(GinkgoT())
550
551            // verify calls to KV.Get()
552            var kvGet mock.Call
553            var queryOpts *consulapi.QueryOptions
554            
555            // first call
556            kvGet = mockKV.Calls[0]
557            Expect(kvGet.Method).To(Equal("Get"))
558            
559            queryOpts = kvGet.Arguments.Get(1).(*consulapi.QueryOptions)
560            Expect(queryOpts).NotTo(BeNil())
561            Expect(queryOpts.WaitIndex).To(Equal(uint64(0)))
562            Expect(queryOpts.WaitTime).To(BeNumerically(">", 0))
563
564            // second call
565            kvGet = mockKV.Calls[1]
566            Expect(kvGet.Method).To(Equal("Get"))
567            
568            queryOpts = kvGet.Arguments.Get(1).(*consulapi.QueryOptions)
569            Expect(queryOpts).NotTo(BeNil())
570            Expect(queryOpts.WaitIndex).To(Equal(uint64(10)))
571            Expect(queryOpts.WaitTime).To(BeNumerically(">", 0))
572
573            // test's done *bing!*
574            close(done)
575        })
576    })
577})
578
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)