How to use Get method of watch Package

Best Ginkgo code snippet using watch.Get

Run Ginkgo automation tests on LambdaTest cloud grid

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

Watch.go

Source: Watch.go Github

copy
1package datastore
2
3import (
4	"database/sql"
5	"encoding/json"
6	"log"
7	"strconv"
8	"strings"
9)
10
11// WatchInsert type used to insert records into the db
12type WatchInsert struct {
13	SubscriptionRecordID string   `json:"subscription_record_id,omitempty" col:"subscription_id"`
14	Kind                 string   `json:"kind,omitempty" col:"kind"`
15	Path                 string   `json:"path,omitempty" col:"path"`
16	CRNFull              []string `json:"crnMasks,omitempty" col:"crn_full"`
17	Wildcards            string   `json:"wildcards,omitempty" col:"wildcards"`
18	RecordIDToWatch      []string `json:"recordIDToWatch,omitempty" col:"record_id_to_watch"`
19	SubscriptionEmail    string   `json:"subscriptionEmail,omitempty" col:"subscription_email"`
20}
21
22// WatchGet type used to get records from the db
23type WatchGet struct {
24	RecordID             string         `json:"record_id,omitempty"`
25	SubscriptionRecordID string         `json:"subscription_record_id,omitempty"`
26	Kind                 sql.NullString `json:"kind,omitempty"`
27	Path                 sql.NullString `json:"path,omitempty"`
28	CRNFull              sql.NullString `json:"crnMasks,omitempty"`
29	Wildcards            sql.NullBool   `json:"wildcards,omitempty"`
30	RecordIDToWatch      sql.NullString `json:"recordIDToWatch,omitempty"`
31	SubscriptionEmail    sql.NullString `json:"subscriptionEmail,omitempty"`
32}
33
34// This is for the case when offset is beyond the result set, and ends up with all Null in all columns in the returned row, except total_count
35type WatchGetNull struct {
36	RecordID             sql.NullString `json:"record_id,omitempty"`
37	SubscriptionRecordID sql.NullString `json:"subscription_record_id,omitempty"`
38	Kind                 sql.NullString `json:"kind,omitempty"`
39	Path                 sql.NullString `json:"path,omitempty"`
40	CRNFull              sql.NullString `json:"crnMasks,omitempty"`
41	Wildcards            sql.NullBool   `json:"wildcards,omitempty"`
42	RecordIDToWatch      sql.NullString `json:"recordIDToWatch,omitempty"`
43	SubscriptionEmail    sql.NullString `json:"subscriptionEmail,omitempty"`
44}
45
46// WatchReturn type used to pass records back to the API request
47type WatchReturn struct {
48	Href            string   `json:"href,omitempty"`
49	RecordID        string   `json:"record_id,omitempty"`
50	SubscriptionURL Href     `json:"subscription,omitempty"`
51	Kind            string   `json:"kind,omitempty"`
52	Path            string   `json:"path,omitempty"`
53	CRNFull         []string `json:"crnMasks,omitempty"`
54	Wildcards       string   `json:"wildcards,omitempty"`
55	RecordIDToWatch []string `json:"recordIDToWatch,omitempty"`
56	SubscriptionEmail string `json:"subscriptionEmail,omitempty"`
57}
58
59// WatchResponse type used to multiple records back to an API request
60type WatchResponse struct {
61	WatchURL  string        `json:"href,omitempty"`
62	Resources []WatchReturn `json:"resources"`
63}
64
65// ConvertWatchReturnToWatchIns converts from a return type to an insert type
66func ConvertWatchReturnToWatchIns(watchReturn WatchReturn) WatchInsert {
67	//FCT := "ConvertWatchReturnToWatchIns: "
68	tmpWatchInsert := WatchInsert{}
69	tmpWatchInsert.SubscriptionRecordID = strings.Split(strings.Split(watchReturn.SubscriptionURL.URL, "/subscriptions/")[0], "/")[0]
70	tmpWatchInsert.Kind = watchReturn.Kind
71	tmpWatchInsert.Path = watchReturn.Path
72	tmpWatchInsert.CRNFull = watchReturn.CRNFull
73	tmpWatchInsert.RecordIDToWatch = watchReturn.RecordIDToWatch
74	tmpWatchInsert.SubscriptionEmail = watchReturn.SubscriptionEmail
75
76	tmpWatchInsert.Wildcards = watchReturn.Wildcards
77	return tmpWatchInsert
78
79}
80
81// ConvertWatchGetToWatchIns from the Get type to an Insert type
82func ConvertWatchGetToWatchIns(watchGet WatchGet) WatchInsert {
83	FCT := "ConvertWatchGetToWatchIns: "
84	tmpWatchInsert := WatchInsert{}
85	tmpWatchInsert.SubscriptionRecordID = watchGet.SubscriptionRecordID
86	if watchGet.Kind.Valid {
87		tmpWatchInsert.Kind = watchGet.Kind.String
88	}
89	if watchGet.Path.Valid {
90		tmpWatchInsert.Path = watchGet.Path.String
91	}
92	if watchGet.CRNFull.Valid {
93		var tmpArray []string
94		err := json.Unmarshal([]byte(watchGet.CRNFull.String), &tmpArray)
95		if err != nil {
96			log.Println(FCT+" Error on unmarshal :", err.Error())
97			tmpWatchInsert.CRNFull = []string{}
98		}
99		tmpWatchInsert.CRNFull = tmpArray
100	} else {
101		tmpWatchInsert.CRNFull = []string{}
102	}
103	if watchGet.RecordIDToWatch.Valid {
104
105		var tmpArr []string
106		err := json.Unmarshal([]byte(watchGet.RecordIDToWatch.String), &tmpArr)
107		if err != nil {
108			log.Print(FCT+": Error : ", err.Error())
109			return WatchInsert{}
110		}
111		tmpWatchInsert.RecordIDToWatch = tmpArr
112	} else {
113		tmpWatchInsert.RecordIDToWatch = []string{}
114	}
115	if watchGet.SubscriptionEmail.Valid {
116		tmpWatchInsert.SubscriptionEmail = watchGet.SubscriptionEmail.String
117	}
118	if watchGet.Wildcards.Valid {
119		tmpWatchInsert.Wildcards = strconv.FormatBool(watchGet.Wildcards.Bool)
120	} else {
121		tmpWatchInsert.Wildcards = "false"
122	}
123	return tmpWatchInsert
124
125}
126
127// ConvertWatchGetToWatchReturn converts from a Get type to a Return type
128func ConvertWatchGetToWatchReturn(watchGet WatchGet, url string) WatchReturn {
129	FCT := "ConvertWatchGetToWatchReturn: "
130	url = strings.TrimRight(url, "/") + "/"
131	tmpWatchReturn := WatchReturn{}
132	tmpWatchReturn.Href = url + watchGet.SubscriptionRecordID + "/watches/" + watchGet.RecordID
133	tmpWatchReturn.RecordID = watchGet.RecordID
134	tmpWatchReturn.SubscriptionURL = Href{URL: url + watchGet.SubscriptionRecordID}
135	if watchGet.Kind.Valid {
136		tmpWatchReturn.Kind = strings.TrimRight(watchGet.Kind.String, "s") + "Watch"
137	}
138	if watchGet.Path.Valid {
139		tmpWatchReturn.Path = watchGet.Path.String
140	}
141	if watchGet.CRNFull.Valid {
142		watchGet.CRNFull.String = strings.Trim(watchGet.CRNFull.String, "{}")
143		tmp := strings.Split(watchGet.CRNFull.String, ",")
144		crnsString := ""
145		if watchGet.CRNFull.String != "" {
146			for i, v := range tmp {
147				crnsString += "\"" + v + "\""
148				if i < len(tmp)-1 {
149					crnsString += ","
150				}
151			}
152		}
153		watchGet.CRNFull.String = "[" + crnsString + "]"
154		err := json.Unmarshal([]byte(watchGet.CRNFull.String), &tmpWatchReturn.CRNFull)
155		if err != nil {
156			log.Print(FCT+": Error : ", err.Error())
157			return WatchReturn{}
158		}
159
160	} else {
161		tmpWatchReturn.CRNFull = []string{}
162	}
163	if watchGet.RecordIDToWatch.Valid {
164		watchGet.RecordIDToWatch.String = strings.Trim(watchGet.RecordIDToWatch.String, "{}")
165		tmp := strings.Split(watchGet.RecordIDToWatch.String, ",")
166
167		recordString := ""
168		for i, v := range tmp {
169			if v != "" {
170				recordString += "\"" + v + "\""
171				if i < len(tmp)-1 {
172					recordString += ","
173				}
174			}
175		}
176
177		watchGet.RecordIDToWatch.String = "[" + recordString + "]"
178		err := json.Unmarshal([]byte(watchGet.RecordIDToWatch.String), &tmpWatchReturn.RecordIDToWatch)
179		if err != nil {
180			log.Print(FCT+": Error : ", err.Error())
181			return WatchReturn{}
182		}
183	} else {
184
185		tmpWatchReturn.RecordIDToWatch = []string{}
186	}
187	if watchGet.SubscriptionEmail.Valid {
188		tmpWatchReturn.SubscriptionEmail = watchGet.SubscriptionEmail.String
189	}
190	if watchGet.Wildcards.Valid {
191		tmpWatchReturn.Wildcards = strconv.FormatBool(watchGet.Wildcards.Bool)
192	} else {
193		tmpWatchReturn.Wildcards = "false"
194	}
195	return tmpWatchReturn
196
197}
198
Full Screen

logfetcher_test.go

Source: logfetcher_test.go Github

copy
1package logfetcher
2
3import (
4	"fmt"
5	"io/ioutil"
6	"log"
7	"os"
8	"path/filepath"
9	"reflect"
10	"strings"
11	"sync"
12	"testing"
13	"time"
14
15	"koding/klient/testutil"
16
17	"github.com/koding/kite"
18	"github.com/koding/kite/dnode"
19)
20
21var (
22	lf      *kite.Kite
23	remote  *kite.Client
24	remote2 *kite.Client
25)
26
27func init() {
28	lf := kite.New("logfetcher", "0.0.1")
29	lf.Config.DisableAuthentication = true
30	lf.Config.Port = 3639
31	lf.HandleFunc("tail", Tail)
32
33	go lf.Run()
34	<-lf.ServerReadyNotify()
35
36	remoteKite := kite.New("remote", "0.0.1")
37	remoteKite.Config.Username = "remote"
38	remote = remoteKite.NewClient("http://127.0.0.1:3639/kite")
39	err := remote.Dial()
40	if err != nil {
41		log.Fatalf("err")
42	}
43
44	remoteKite2 := kite.New("remote2", "0.0.1")
45	remoteKite2.Config.Username = "remote2"
46	remote2 = remoteKite2.NewClient("http://127.0.0.1:3639/kite")
47	err = remote2.Dial()
48	if err != nil {
49		log.Fatalf("err")
50	}
51}
52
53func makeTempAndCopy(copyFrom string) (dir, path string, err error) {
54	tmpDir, err := ioutil.TempDir("", "logfetcher")
55	if err != nil {
56		return "", "", err
57	}
58
59	tmpFile := filepath.Join(tmpDir, "file")
60
61	// Create a new file for testing, so we can test offsetting and watching.
62	if err := testutil.FileCopy(copyFrom, tmpFile); err != nil {
63		return "", "", err
64	}
65
66	return tmpDir, tmpFile, nil
67}
68
69func TestTail(t *testing.T) {
70	tmpDir, tmpFile, err := makeTempAndCopy("testdata/testfile1.txt")
71	if err != nil {
72		t.Fatal(err)
73	}
74	defer os.RemoveAll(tmpDir)
75
76	var watchCount int
77	var watchResult []string
78	var watchMu sync.Mutex
79
80	watchFunc := dnode.Callback(func(r *dnode.Partial) {
81		watchCount++
82		line := r.One().MustString()
83
84		watchMu.Lock()
85		watchResult = append(watchResult, line)
86		watchMu.Unlock()
87	})
88
89	_, err = remote.Tell("tail", &Request{
90		Path:  tmpFile,
91		Watch: watchFunc,
92	})
93	if err != nil {
94		t.Fatal(err)
95	}
96
97	fmt.Println("Waiting for the results..")
98	time.Sleep(time.Second * 1)
99
100	// Should return empty by default, since no new lines were given.
101	watchMu.Lock()
102	n := len(watchResult)
103	watchMu.Unlock()
104
105	if n != 0 {
106		t.Errorf("WatchFunc should not be called for pre-existing lines.\nWant: 0\nGot : %d\n", n)
107	}
108
109	file, err := os.OpenFile(tmpFile, os.O_APPEND|os.O_WRONLY, 0600)
110	if err != nil {
111		t.Fatal(err)
112	}
113
114	file.WriteString("Tail2\n")
115	file.WriteString("Tail3\n")
116	file.WriteString("Tail4\n")
117	file.Close()
118
119	// wait so the watch function picked up the tail changes
120	time.Sleep(time.Second * 5)
121
122	var modifiedLines = []string{"Tail2", "Tail3", "Tail4"}
123
124	watchMu.Lock()
125	if !reflect.DeepEqual(modifiedLines, watchResult) {
126		err = fmt.Errorf("\nWatchFunc should not be called for pre-existing lines.\n"+
127			"Want: %#v\nGot : %#v\n", modifiedLines, watchResult)
128	}
129	watchMu.Unlock()
130
131	if err != nil {
132		t.Error(err)
133	}
134}
135
136// TestMultipleTail compares two log.tail calls on a single file, and ensures that
137// they both receive the same input.
138func TestMultipleTail(t *testing.T) {
139	tmpDir, tmpFile, err := makeTempAndCopy("testdata/testfile2.txt")
140	if err != nil {
141		t.Fatal(err)
142	}
143	defer os.RemoveAll(tmpDir)
144
145	watchResult := []string{}
146	watchFunc := dnode.Callback(func(r *dnode.Partial) {
147		line := r.One().MustString()
148		watchResult = append(watchResult, line)
149	})
150
151	_, err = remote.Tell("tail", &Request{
152		Path:  tmpFile,
153		Watch: watchFunc,
154	})
155	if err != nil {
156		t.Fatal(err)
157	}
158
159	watchResult2 := []string{}
160	watchFunc2 := dnode.Callback(func(r *dnode.Partial) {
161		line := r.One().MustString()
162		watchResult2 = append(watchResult2, line)
163	})
164
165	_, err = remote2.Tell("tail", &Request{
166		Path:  tmpFile,
167		Watch: watchFunc2,
168	})
169	if err != nil {
170		t.Fatal(err)
171	}
172
173	time.Sleep(time.Second * 2)
174
175	file, err := os.OpenFile(tmpFile, os.O_APPEND|os.O_WRONLY, 0600)
176	if err != nil {
177		t.Fatal(err)
178	}
179	defer file.Close()
180
181	file.WriteString("Tail2\n")
182	file.WriteString("Tail3\n")
183
184	// wait so the watch function picked up the tail changes
185	time.Sleep(time.Second)
186	t.Logf("watchResult = %+v\n", watchResult)
187	t.Logf("watchResult2 = %+v\n", watchResult2)
188
189	// Now check the new two results
190	if !reflect.DeepEqual(
191		watchResult[len(watchResult)-2:],
192		watchResult2[len(watchResult2)-2:],
193	) {
194		t.Errorf("\nWant: %v\nGot : %v\n",
195			watchResult[len(watchResult)-2:],
196			watchResult2[len(watchResult2)-2:],
197		)
198	}
199
200	// Now let us disconnect the second connection, we should receive any new
201	// changes for watchResult2 (From watchFunc2) anymore
202
203	currentWatchLen := len(watchResult)
204	currentWatch2Len := len(watchResult2)
205	remote2.Close()
206
207	// wait so onDisconnect get recognized on Kite
208	time.Sleep(time.Second)
209
210	file.WriteString("Tail4\n")
211	file.WriteString("Tail5\n")
212
213	// wait so the watch function picked up the tail changes
214	time.Sleep(time.Second)
215
216	if currentWatch2Len != len(watchResult2) {
217		t.Errorf("WatchFunc2 is still triggered, got %d should have %d", len(watchResult2), currentWatch2Len)
218	}
219
220	if currentWatchLen+2 != len(watchResult) {
221		t.Errorf("WatchFunc2 is not triggered, got %d should have %d", len(watchResult), currentWatchLen+2)
222	}
223}
224
225func TestTailOffset(t *testing.T) {
226	t.Skip("this test is correct but prefetcher implementation is not: #10840")
227
228	tmpDir, tmpFile, err := makeTempAndCopy("testdata/testfile1.txt")
229	if err != nil {
230		t.Fatal(err)
231	}
232	defer os.RemoveAll(tmpDir)
233
234	var (
235		offset    = 3 // Read the last 3 lines of the file.
236		linesC    = make(chan string, 10)
237		watchFunc = dnode.Callback(func(r *dnode.Partial) {
238			linesC <- r.One().MustString()
239		})
240	)
241
242	if _, err = remote.Tell("tail", &Request{
243		Path:       tmpFile,
244		Watch:      watchFunc,
245		LineOffset: offset,
246	}); err != nil {
247		t.Fatal(err)
248	}
249
250	// Write some data to file
251	file, err := os.OpenFile(tmpFile, os.O_APPEND|os.O_WRONLY, 0600)
252	if err != nil {
253		t.Fatal(err)
254	}
255
256	for _, data := range []string{"DataA\n", "DataB\n"} {
257		if _, err = file.WriteString(data); err != nil {
258			t.Fatal(err)
259		}
260	}
261
262	if err = file.Close(); err != nil {
263		t.Fatal(err)
264	}
265
266	t.Log("....Waiting for the results..")
267	var offsetAll = offset + 2 // We wrote two more lines.
268	lines := make([]string, 0, offsetAll)
269	for i := 0; i < offsetAll; i++ {
270		select {
271		case line := <-linesC:
272			t.Log(line)
273			lines = append(lines, line)
274		case <-time.After(2 * time.Second): // Wait each time.
275			t.Fatalf("test timed out after %v", 2*time.Second)
276		}
277	}
278
279	// Read the file, and get the offset lines to compare against.
280	sourceText, err := ioutil.ReadFile(tmpFile)
281	if err != nil {
282		t.Fatal(err)
283	}
284	// wait so the watch function picked up the tail changes
285	offsetLines := strings.Split(strings.TrimSpace(string(sourceText)), "\n")
286	offsetLines = offsetLines[len(offsetLines)-offsetAll:]
287	if !reflect.DeepEqual(offsetLines, lines) {
288		t.Errorf("want offset lines = %#v\n; got %#v\n", offsetLines, lines)
289	}
290}
291
292func TestGetOffsetLines(t *testing.T) {
293	tmpDir, tmpFile, err := makeTempAndCopy("testdata/testfile1.txt")
294	if err != nil {
295		t.Fatal(err)
296	}
297	defer os.RemoveAll(tmpDir)
298
299	// Read the file, and get the offset lines to compare against.
300	sourceText, err := ioutil.ReadFile(tmpFile)
301	if err != nil {
302		t.Fatal(err)
303	}
304	sourceLines := strings.Split(strings.TrimSpace(string(sourceText)), "\n")
305
306	// Open our file, to pass to the func
307	file1, err := os.Open(tmpFile)
308	if err != nil {
309		t.Fatal(err)
310	}
311	defer file1.Close()
312
313	offset := 3
314	result, err := GetOffsetLines(file1, 4, offset)
315	if err != nil {
316		t.Error(err)
317	}
318
319	expected := sourceLines[len(sourceLines)-offset:]
320	if !reflect.DeepEqual(expected, result) {
321		t.Errorf(
322			"\nIt should return offset lines.\nWant: %#v\nGot : %#v\n",
323			expected, result,
324		)
325	}
326
327	// Set the offset to the entire file.
328	offset = len(sourceLines) + 1
329	result, err = GetOffsetLines(file1, 4, offset)
330	if err != nil {
331		t.Error(err)
332	}
333
334	expected = sourceLines
335	if !reflect.DeepEqual(expected, result) {
336		t.Errorf(
337			"\nIt should return all the lines, if offset is larger than total.\nWant: %#v\nGot : %#v\n",
338			expected, result,
339		)
340	}
341
342	// Create the 2nd test file to be empty (Create truncates by default)
343	file2, err := os.Create(tmpFile)
344	if err != nil {
345		t.Fatal(err)
346	}
347
348	fmt.Println("Requesting empty lines")
349	offset = 3
350	result, err = GetOffsetLines(file2, 4, offset)
351	if err != nil {
352		t.Error(err)
353	}
354
355	expected = nil
356	if !reflect.DeepEqual(expected, result) {
357		t.Errorf(
358			"\nIt should callback with no lines.\nWant: %#v\nGot : %#v\n",
359			expected, result,
360		)
361	}
362
363	tmpDir2, tmpFile, err := makeTempAndCopy("testdata/testfile1.txt")
364	if err != nil {
365		t.Fatal(err)
366	}
367	defer os.RemoveAll(tmpDir2)
368
369	// Open our file, to pass to the func
370	file1, err = os.Open(tmpFile)
371	if err != nil {
372		t.Fatal(err)
373	}
374	defer file1.Close()
375
376	offset = 3
377	result, err = GetOffsetLines(file1, defaultOffsetChunkSize, offset)
378	if err != nil {
379		t.Error(err)
380	}
381
382	expected = sourceLines[len(sourceLines)-offset:]
383	if !reflect.DeepEqual(expected, result) {
384		t.Errorf(
385			"\nIt should return offset lines with a chunkSize larger than the file.\nWant: %#v\nGot : %#v\n",
386			expected, result,
387		)
388	}
389}
390
Full Screen

testSubscriptionWatch.go

Source: testSubscriptionWatch.go Github

copy
1package test
2
3import (
4	"database/sql"
5	"log"
6	"net/http"
7	"strings"
8
9	"github.ibm.com/cloud-sre/pnp-abstraction/db"
10	"github.ibm.com/cloud-sre/pnp-abstraction/datastore"
11)
12
13const (
14	API_URL = "apiUrl"
15)
16
17func TestSubscriptionWatch(database *sql.DB) int {
18	FCT := "TestSubscriptionWatch "
19	failed := 0
20
21	log.Println("======== "+FCT+" Test 1 ========")
22	subscription := datastore.SubscriptionInsert {
23		Name:            "test_name1",
24		TargetAddress:   "target1",
25		TargetToken:     "token1",
26		Expiration:      "2018-08-01T10:00:00Z",
27	}
28
29	subscription_id, err, status := db.InsertSubscriptionStatement(database, &subscription)
30	if status != http.StatusOK {
31		log.Println("Insert Subscription failed: ", err.Error())
32		failed++
33	} else {
34		log.Println("record_id: ", subscription_id)
35		log.Println("Insert Subscription passed")
36	}
37
38
39	log.Println("Test get Subscription")
40	subscriptionReturn, err1,_ := db.GetSubscriptionByRecordIDStatement(database, subscription_id)
41	if err1 != nil {
42		log.Println("Get Subscription failed: ", err1.Error())
43		failed++
44	} else {
45
46		log.Println("Get result: ", subscriptionReturn)
47
48		if subscriptionReturn.Name == subscription.Name &&
49			subscriptionReturn.TargetAddress == subscription.TargetAddress &&
50			subscriptionReturn.TargetToken == subscription.TargetToken { //&&
51//			subscriptionReturn.Expiration == subscription.Expiration  {
52
53			log.Println("Test 1: Get Subscription PASSED")
54		} else {
55			log.Println("Test 1: Get Subscription FAILED")
56			failed++
57		}
58
59	}
60
61
62	log.Println("======== "+FCT+" Test 2 ========")
63	crnFull2 := []string{"crn:v1:BLUEMIX:PUBLIC:service-NAME2:location2::::",
64						 "crn:v1:aa:dedicated:service-name2:LOCATION3::::",
65				}
66	recordIDToWatch2 := []string {"INC00001"}
67
68	watch2 := datastore.WatchInsert {
69		SubscriptionRecordID: subscription_id,
70		Kind:                 "incident",
71		Path:                 "new",
72		CRNFull:              crnFull2,
73		Wildcards:            "true",
74		RecordIDToWatch:      recordIDToWatch2,
75		SubscriptionEmail:	  "[email protected]",
76	}
77
78	watchReturn2, err2,_ := db.InsertWatchByTypeForSubscriptionStatement(database, &watch2, API_URL)
79	if err2 != nil {
80		log.Println("Insert Watch failed: ", err2.Error())
81		failed++
82	} else {
83		log.Println("record_id: ", watchReturn2.RecordID)
84		log.Println("Insert Watch passed")
85	}
86
87	log.Println("Test get Watch")
88	watchReturn2b, err2b,_ := db.GetWatchByRecordIDStatement(database, watchReturn2.RecordID, API_URL)
89	if err2b != nil {
90		log.Println("Get Watch failed: ", err2b.Error())
91		failed++
92	} else {
93		log.Println("Get result: ", watchReturn2b)
94
95		if strings.Contains(watchReturn2b.SubscriptionURL.URL, watch2.SubscriptionRecordID) &&
96			watchReturn2b.Kind == watch2.Kind+"Watch" &&
97			watchReturn2b.Path == watch2.Path &&
98			len(watchReturn2b.CRNFull) == len(watch2.CRNFull) &&
99			watchReturn2b.CRNFull[0] == strings.ToLower(watch2.CRNFull[0]) &&
100			watchReturn2b.CRNFull[1] == strings.ToLower(watch2.CRNFull[1]) &&
101			watchReturn2b.Wildcards == watch2.Wildcards &&
102			len(watchReturn2b.RecordIDToWatch) == len(watch2.RecordIDToWatch) &&
103			watchReturn2b.RecordIDToWatch[0] == watch2.RecordIDToWatch[0] &&
104			watchReturn2b.SubscriptionEmail == watch2.SubscriptionEmail {
105
106			log.Println("Test 2: Get Watch PASSED")
107		} else {
108			log.Println("Test 2: Get Watch FAILED")
109			failed++
110		}
111	}
112
113	log.Println("======== "+FCT+" Test 3 ========")
114	crnFull3 := []string{"crn:v1:bluemix:public:service-name1:location1::service-instance1:resource-type1:",
115				}
116	recordIDToWatch3 := []string {db.CreateRecordIDFromSourceSourceID("source1", "INC00011")}
117
118	watch3 := datastore.WatchInsert {
119		SubscriptionRecordID: subscription_id,
120		Kind:                 "maintenance",
121		Path:                 "new",
122		CRNFull:              crnFull3,
123		Wildcards:            "false",
124		RecordIDToWatch:      recordIDToWatch3,
125		SubscriptionEmail:	  "[email protected]",
126	}
127
128	watchReturn3, err3,_ := db.InsertWatchByTypeForSubscriptionStatement(database, &watch3, API_URL)
129	if err3 != nil {
130		log.Println("Insert Watch failed: ", err3.Error())
131		failed++
132	} else {
133		log.Println("record_id: ", watchReturn3.RecordID)
134		log.Println("Insert Watch passed")
135	}
136
137	log.Println("Test get Watch")
138	watchReturn3b, err3b,_ := db.GetWatchByRecordIDStatement(database, watchReturn3.RecordID, API_URL)
139	if err3b != nil {
140		log.Println("Get Watch failed: ", err3b.Error())
141		failed++
142	} else {
143		log.Println("Get result: ", watchReturn3b)
144
145		if strings.Contains(watchReturn3b.SubscriptionURL.URL, watch3.SubscriptionRecordID) &&
146			watchReturn3b.Kind == watch3.Kind+"Watch" &&
147			watchReturn3b.Path == watch3.Path &&
148			len(watchReturn3b.CRNFull) == len(watch3.CRNFull) &&
149			watchReturn3b.CRNFull[0] == strings.ToLower(watch3.CRNFull[0]) &&
150			watchReturn3b.Wildcards == watch3.Wildcards &&
151			len(watchReturn3b.RecordIDToWatch) == len(watch3.RecordIDToWatch) &&
152			watchReturn3b.RecordIDToWatch[0] == watch3.RecordIDToWatch[0] &&
153			watchReturn3b.SubscriptionEmail == watch3.SubscriptionEmail {
154
155			log.Println("Test 3: Get Watch PASSED")
156		} else {
157			log.Println("Test 3: Get Watch FAILED")
158			failed++
159		}
160	}
161
162
163	log.Println("======== "+FCT+" Test 4 ========")
164	queryStr4 := db.RESOURCE_QUERY_CRN + "=crn:v1:aa:dedicated:service-name2:LOCation3::::"
165	log.Println("query: ", queryStr4)
166	watchReturn4, total_count4, err4,_ := db.GetWatchesByQuery(database, queryStr4, 0, 0, API_URL)
167
168	if err4 != nil {
169		log.Println("Get Watches failed: ", err4.Error())
170		log.Println("Test 4: Get Watches FAILED")
171		failed++
172	} else if total_count4 == 1 {
173		log.Println("total_count4: ", total_count4)
174		log.Println("watchReturn4: ", watchReturn4)
175
176		if len(*watchReturn4) != 1 {
177			log.Printf("Error: Number of returned: %d, expecting: 1\n", len(*watchReturn4))
178			log.Println("Test 4: Get Watches FAILED")
179			failed++
180		} else {
181			match := 0
182			for _,r := range *watchReturn4 {
183
184				if strings.Contains(r.SubscriptionURL.URL, watch2.SubscriptionRecordID) &&
185					r.Kind == watch2.Kind+"Watch" &&
186					r.Path == watch2.Path &&
187					len(r.CRNFull) == len(watch2.CRNFull) &&
188					r.CRNFull[0] == strings.ToLower(watch2.CRNFull[0]) &&
189					r.CRNFull[1] == strings.ToLower(watch2.CRNFull[1]) &&
190					r.Wildcards == watch2.Wildcards &&
191					len(r.RecordIDToWatch) == len(watch2.RecordIDToWatch) &&
192					r.RecordIDToWatch[0] == watch2.RecordIDToWatch[0] &&
193					r.SubscriptionEmail == watch2.SubscriptionEmail {
194
195					match++
196				}
197			}
198
199			if (match <= 0){
200				log.Println("There are rows unmatched, failed")
201				log.Println("Test 4: Get Watches FAILED")
202				failed++
203			} else {
204				log.Println("Test 4: Get Watches PASSED")
205			}
206		}
207	} else {
208		log.Printf("total_count is %d, expecting 1, failed", total_count4)
209		log.Println("Test 4: Get Watches FAILED")
210		failed++
211	}
212
213	log.Println("======== "+FCT+" Test 5 ========")
214	queryStr5, err5a := db.CreateNonWildcardCRNQueryString(crnFull3[0])
215	if err5a != nil {
216		log.Println("Error: ", err5a)
217	}
218	log.Println("query: ", queryStr5)
219
220	watchReturn5, total_count5, err5,_ := db.GetWatchesByQuery(database, queryStr5, 0, 0, API_URL)
221
222	if err5 != nil {
223		log.Println("Get Watches failed: ", err5.Error())
224		log.Println("Test 5: Get Watches FAILED")
225		failed++
226	} else if total_count5 == 1 {
227		log.Println("total_count5: ", total_count5)
228		log.Println("watchReturn5: ", watchReturn5)
229
230		if len(*watchReturn5) != 1 {
231			log.Printf("Error: Number of returned: %d, expecting: 1\n", len(*watchReturn5))
232			log.Println("Test 5: Get Watches FAILED")
233			failed++
234		} else {
235			match := 0
236			for _,r := range *watchReturn5 {
237
238				if strings.Contains(r.SubscriptionURL.URL, watch3.SubscriptionRecordID) &&
239					r.Kind == watch3.Kind+"Watch" &&
240					r.Path == watch3.Path &&
241					len(r.CRNFull) == len(watch3.CRNFull) &&
242					r.CRNFull[0] == strings.ToLower(watch3.CRNFull[0]) &&
243					r.Wildcards == watch3.Wildcards &&
244					len(r.RecordIDToWatch) == len(watch3.RecordIDToWatch) &&
245					r.RecordIDToWatch[0] == watch3.RecordIDToWatch[0] &&
246					r.SubscriptionEmail == watch3.SubscriptionEmail {
247
248					match++
249				}
250			}
251
252			if (match <= 0){
253				log.Println("There are rows unmatched, failed")
254				log.Println("Test 5: Get Watches FAILED")
255				failed++
256			} else {
257				log.Println("Test 5: Get Watches PASSED")
258			}
259		}
260	} else {
261		log.Printf("total_count is %d, expecting 1, failed", total_count5)
262		log.Println("Test 5: Get Watches FAILED")
263		failed++
264	}
265
266	log.Println("======== "+FCT+" Test 6 ========")
267	subscription6 := datastore.SubscriptionInsert {
268		Name:            "test_name6",
269		TargetAddress:   "target6",
270		TargetToken:     "token6",
271		Expiration:      "2018-12-01T06:06:00Z",
272	}
273
274	subscription_id6, err6,_ := db.InsertSubscriptionStatement(database, &subscription6)
275	if err6 != nil {
276		log.Println("Insert Subscription failed: ", err6.Error())
277		failed++
278	} else {
279		log.Println("record_id: ", subscription_id6)
280		log.Println("Insert Subscription passed")
281	}
282
283
284	log.Println("Test get Subscription")
285	subscriptionReturn6, err61,_ := db.GetSubscriptionByRecordIDStatement(database, subscription_id6)
286	if err61 != nil {
287		log.Println("Get Subscription failed: ", err61.Error())
288		failed++
289	} else {
290
291		log.Println("Get result: ", subscriptionReturn6)
292
293		if subscriptionReturn6.Name == subscription6.Name &&
294			subscriptionReturn6.TargetAddress == subscription6.TargetAddress &&
295			subscriptionReturn6.TargetToken == subscription6.TargetToken { //&&
296			//subscriptionReturn6.Expiration == subscription6.Expiration  {
297
298			log.Println("Get Subscription passed")
299		} else {
300			log.Println("Get Subscription failed")
301			failed++
302		}
303
304	}
305
306	crnFull6 := []string{"crn:v1:blueMIX:public:service-naME1:location1::::",
307				}
308	recordIDToWatch6 := []string {db.CreateRecordIDFromSourceSourceID("source1", "INC00006")}
309
310	watch6 := datastore.WatchInsert {
311		SubscriptionRecordID: subscription_id6,
312		Kind:                 "incident",
313		Path:                 "new",
314		CRNFull:              crnFull6,
315		Wildcards:            "true",
316		RecordIDToWatch:      recordIDToWatch6,
317		SubscriptionEmail: 	  "[email protected]",
318	}
319
320	watchReturn6, err62,_ := db.InsertWatchByTypeForSubscriptionStatement(database, &watch6, API_URL)
321	if err62 != nil {
322		log.Println("Insert Watch failed: ", err62.Error())
323		failed++
324	} else {
325		log.Println("record_id: ", watchReturn6.RecordID)
326		log.Println("Insert Watch passed")
327	}
328
329	log.Println("Test get Watch")
330	queryStr6 := db.RESOURCE_QUERY_CRN + "=crn:v1:bluemix:public:service-name1:::::&" + db.WATCH_QUERY_KIND + "=incident,maintenance"
331	log.Println("query: ", queryStr6)
332	watchReturn6b, total_count6, err6b,_ := db.GetWatchesByQuery(database, queryStr6, 0, 0, API_URL)
333
334	if err6b != nil {
335		log.Println("Get Watches failed: ", err6b.Error())
336		log.Println("Test 6: Get Watches FAILED")
337		failed++
338	} else if total_count6 == 2 {
339		log.Println("total_count6: ", total_count6)
340		log.Println("watchReturn6: ", watchReturn6b)
341
342		if len(*watchReturn6b) != 2 {
343			log.Printf("Error: Number of returned: %d, expecting: 2\n", len(*watchReturn6b))
344			log.Println("Test 6: Get Watches FAILED")
345			failed++
346		} else {
347			match := 0
348			for _,r := range *watchReturn6b {
349
350				if strings.Contains(r.SubscriptionURL.URL, watch3.SubscriptionRecordID) &&
351					r.Kind == watch3.Kind+"Watch" &&
352					r.Path == watch3.Path &&
353					len(r.CRNFull) == len(watch3.CRNFull) &&
354					r.CRNFull[0] == strings.ToLower(watch3.CRNFull[0]) &&
355					r.Wildcards == watch3.Wildcards &&
356					len(r.RecordIDToWatch) == len(watch3.RecordIDToWatch) &&
357					r.RecordIDToWatch[0] == watch3.RecordIDToWatch[0] &&
358					r.SubscriptionEmail == watch3.SubscriptionEmail {
359
360					match++
361				} else if strings.Contains(r.SubscriptionURL.URL, watch6.SubscriptionRecordID) &&
362					r.Kind == watch6.Kind+"Watch" &&
363					r.Path == watch6.Path &&
364					len(r.CRNFull) == len(watch6.CRNFull) &&
365					r.CRNFull[0] == strings.ToLower(watch6.CRNFull[0]) &&
366					r.Wildcards == watch6.Wildcards &&
367					len(r.RecordIDToWatch) == len(watch6.RecordIDToWatch) &&
368					r.RecordIDToWatch[0] == watch6.RecordIDToWatch[0] &&
369					r.SubscriptionEmail == watch6.SubscriptionEmail {
370
371					match++
372				}
373			}
374
375			if (match <= 1){
376				log.Println("There are rows unmatched, failed")
377				log.Println("Test 6: Get Watches FAILED")
378				failed++
379			} else {
380				log.Println("Test 6: Get Watches PASSED")
381			}
382		}
383	} else {
384		log.Printf("total_count is %d, expecting 2, failed", total_count6)
385		log.Println("Test 6: Get Watches FAILED")
386		failed++
387	}
388
389	log.Println("======== "+FCT+" Test 7 ========")
390	log.Println("Test get Watch")
391	queryStr7 := db.WATCH_QUERY_KIND + "=incident,maintenance&" + db.WATCH_QUERY_SUBSCRIPTION_ID + "=" + subscription_id
392	log.Println("query: ", queryStr7)
393	watchReturn7, total_count7, err7,_ := db.GetWatchesByQuery(database, queryStr7, 0, 0, API_URL)
394
395	if err7 != nil {
396		log.Println("Get Watches failed: ", err7.Error())
397		log.Println("Test 7: Get Watches FAILED")
398		failed++
399	} else if total_count7 == 2 {
400		log.Println("total_count7: ", total_count7)
401		log.Println("watchReturn7: ", watchReturn7)
402
403		if len(*watchReturn7) != 2 {
404			log.Printf("Error: Number of returned: %d, expecting: 2\n", len(*watchReturn7))
405			log.Println("Test 7: Get Watches FAILED")
406			failed++
407		} else {
408			match := 0
409			for _,r := range *watchReturn7 {
410
411				if strings.Contains(r.SubscriptionURL.URL, watch2.SubscriptionRecordID) &&
412					r.Kind == watch2.Kind+"Watch" &&
413					r.Path == watch2.Path &&
414					len(r.CRNFull) == len(watch2.CRNFull) &&
415					r.CRNFull[0] == strings.ToLower(watch2.CRNFull[0]) &&
416					r.Wildcards == watch2.Wildcards &&
417					len(r.RecordIDToWatch) == len(watch2.RecordIDToWatch) &&
418					r.RecordIDToWatch[0] == watch2.RecordIDToWatch[0] &&
419					r.SubscriptionEmail == watch2.SubscriptionEmail {
420
421					match++
422				} else if strings.Contains(r.SubscriptionURL.URL, watch3.SubscriptionRecordID) &&
423					r.Kind == watch3.Kind+"Watch" &&
424					r.Path == watch3.Path &&
425					len(r.CRNFull) == len(watch3.CRNFull) &&
426					r.CRNFull[0] == strings.ToLower(watch3.CRNFull[0]) &&
427					r.Wildcards == watch3.Wildcards &&
428					len(r.RecordIDToWatch) == len(watch3.RecordIDToWatch) &&
429					r.RecordIDToWatch[0] == watch3.RecordIDToWatch[0] &&
430					r.SubscriptionEmail == watch3.SubscriptionEmail {
431
432					match++
433				}
434			}
435
436			if (match <= 1){
437				log.Println("There are rows unmatched, failed")
438				log.Println("Test 7: Get Watches FAILED")
439				failed++
440			} else {
441				log.Println("Test 7: Get Watches PASSED")
442			}
443		}
444	} else {
445		log.Printf("total_count is %d, expecting 2, failed", total_count7)
446		log.Println("Test 7: Get Watches FAILED")
447		failed++
448	}
449
450	log.Println("======== "+FCT+" Test 8 ========")
451
452	log.Println("Test delete expired subscription")
453	err8,_ := db.DeleteExpiredSubscriptions(database)
454	if err8 != nil {
455		log.Println("Delete expired subscription failed: ", err8.Error())
456		failed++
457	}
458	subscriptionReturn8, err8c,_ := db.GetSubscriptionByRecordIDStatement(database, subscription_id)
459	if subscriptionReturn8 != nil {
460		log.Println("Delete Maintenance failed, Maintenance still exists: ", err8c.Error())
461		log.Println("Test 8: Delete expired subscription FAILED")
462		failed++
463	} else {
464		log.Println("Test 8: Delete expired subscription PASSED")
465	}
466
467
468	// Summary
469	log.Println("**** SUMMARY ****")
470	if failed > 0 {
471		log.Println("**** "+FCT+"FAILED ****")
472	} else {
473		log.Println("**** "+FCT+"PASSED ****")
474	}
475	return failed
476}
477
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)