How to use areEqual method of is Package

Best Is code snippet using is.areEqual

Run Is automation tests on LambdaTest cloud grid

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

simhandler_test.go

Source: simhandler_test.go Github

copy
1package srvr
2
3import (
4	"bufio"
5	"encoding/json"
6	"fmt"
7	"net/http"
8	"strconv"
9	"strings"
10	"testing"
11
12	"github.com/codeafix/orgnetsim/sim"
13	"github.com/google/uuid"
14	"github.com/spaceweasel/mango"
15)
16
17func CreateNetwork() sim.RelationshipMgr {
18	rm := &sim.Network{}
19	agent1 := sim.GenerateRandomAgent("Agent_1", []sim.Color{sim.Blue}, false)
20	rm.AddAgent(agent1)
21	agent2 := sim.GenerateRandomAgent("Agent_2", []sim.Color{sim.Blue}, false)
22	rm.AddAgent(agent2)
23	agent3 := sim.GenerateRandomAgent("Agent_3", []sim.Color{sim.Blue}, false)
24	rm.AddAgent(agent3)
25	rm.AddLink(agent1, agent2)
26	rm.AddLink(agent1, agent3)
27	rm.SetMaxColors(4)
28	rm.PopulateMaps()
29	return rm
30}
31
32func CreateSimHandlerBrowserWithSteps(deleteItemIndex int) (*mango.Browser, *TestFileUpdater, *TestFileUpdater, *TestFileUpdater, []string, string) {
33	simid := uuid.New().String()
34	sim := NewSimInfo(simid)
35	sim.Name = "mySavedSim"
36	sim.Description = "A description of mySavedSim"
37	ids := []string{
38		uuid.NewString(),
39		uuid.NewString(),
40		uuid.NewString(),
41	}
42	steps := make([]string, len(ids))
43	for i, id := range ids {
44		steps[i] = fmt.Sprintf("/api/simulation/%s/step/%s", simid, id)
45	}
46	sim.Steps = steps
47	simfu := &TestFileUpdater{
48		Obj:      sim,
49		Filepath: sim.Filepath(),
50	}
51	tfm := NewTestFileManager(simfu)
52
53	ss := &SimStep{
54		ID:       ids[deleteItemIndex],
55		ParentID: simid,
56		Network:  CreateNetwork(),
57	}
58	ssfu := &TestFileUpdater{
59		Obj:      ss,
60		Filepath: ss.Filepath(),
61	}
62	tfm.Add(ss.Filepath(), ssfu)
63	dfu := &TestFileUpdater{}
64	tfm.Default = dfu
65
66	r := CreateRouter(tfm)
67	br := mango.NewBrowser(r)
68
69	return br, simfu, ssfu, dfu, steps, simid
70}
71
72func TestMarshalling(t *testing.T) {
73	parent := uuid.NewString()
74	s1 := &SimStep{
75		ID:       uuid.NewString(),
76		ParentID: parent,
77		Network:  CreateNetwork(),
78	}
79
80	s2 := &SimStep{
81		ID:       uuid.NewString(),
82		ParentID: parent,
83		Network:  CreateNetwork(),
84	}
85	steps := []*SimStep{s1, s2}
86	b, err := json.Marshal(steps)
87	AssertSuccess(t, err)
88	rstep := []*SimStep{}
89	err = json.Unmarshal(b, &rstep)
90	AssertSuccess(t, err)
91}
92
93func TestGetSimSuccess(t *testing.T) {
94	br, simfu, _, _, _, simid := CreateSimHandlerBrowserWithSteps(0)
95
96	hdrs := http.Header{}
97	resp, err := br.Get(fmt.Sprintf("/api/simulation/%s", simid), hdrs)
98	AssertSuccess(t, err)
99	AreEqual(t, http.StatusOK, resp.Code, "Not OK")
100
101	rsim := &SimInfo{}
102	err = json.Unmarshal(resp.Body.Bytes(), rsim)
103	AssertSuccess(t, err)
104	AreEqual(t, simfu.Obj.(*SimInfo).Name, rsim.Name, "Wrong name in returned SimInfo")
105	AreEqual(t, simfu.Obj.(*SimInfo).Description, rsim.Description, "Wrong description in returned SimInfo")
106}
107
108func TestGetSimInvalidCommand(t *testing.T) {
109	br, _, _, _, _, simid := CreateSimHandlerBrowserWithSteps(0)
110
111	hdrs := http.Header{}
112	resp, err := br.Get(fmt.Sprintf("/api/simulation/%s/somename", simid), hdrs)
113	AssertSuccess(t, err)
114	AreEqual(t, http.StatusNotFound, resp.Code, "Did not return Not Found")
115}
116
117func TestGetSimStepsSuccess(t *testing.T) {
118	br, _, _, _, steps, simid := CreateSimHandlerBrowserWithSteps(0)
119
120	hdrs := http.Header{}
121	resp, err := br.Get(fmt.Sprintf("/api/simulation/%s/step", simid), hdrs)
122	AssertSuccess(t, err)
123	AreEqual(t, http.StatusOK, resp.Code, "Not OK")
124
125	rsteps := []SimStep{}
126	err = json.Unmarshal(resp.Body.Bytes(), &rsteps)
127
128	AssertSuccess(t, err)
129	AreEqual(t, 3, len(rsteps), "Wrong number of Steps in returned SimInfo")
130	AreEqual(t, steps[0][strings.LastIndex(steps[0], "/")+1:], rsteps[0].ID, "Wrong Step 0 in returned SimInfo")
131	AreEqual(t, steps[1][strings.LastIndex(steps[0], "/")+1:], rsteps[1].ID, "Wrong Step 1 in returned SimInfo")
132	AreEqual(t, steps[2][strings.LastIndex(steps[0], "/")+1:], rsteps[2].ID, "Wrong Step 2 in returned SimInfo")
133}
134
135func TestUpdateSimSuccess(t *testing.T) {
136	br, _, _, _, steps, simid := CreateSimHandlerBrowserWithSteps(0)
137
138	hdrs := http.Header{}
139	hdrs.Set("Content-Type", "application/json")
140	data := `{"Name":"myUpdatedSim","Description":"A description of mySavedSim"}`
141	resp, err := br.PutS(fmt.Sprintf("/api/simulation/%s", simid), data, hdrs)
142	AssertSuccess(t, err)
143	AreEqual(t, http.StatusOK, resp.Code, "Not OK")
144
145	rsim := &SimInfo{}
146	err = json.Unmarshal(resp.Body.Bytes(), rsim)
147	AssertSuccess(t, err)
148	AreEqual(t, "myUpdatedSim", rsim.Name, "Wrong name in returned SimInfo")
149	AreEqual(t, "A description of mySavedSim", rsim.Description, "Wrong description in returned SimInfo")
150	AreEqual(t, 3, len(rsim.Steps), "Wrong number of Steps in returned SimInfo")
151	AreEqual(t, steps[0], rsim.Steps[0], "Wrong Step 0 in returned SimInfo")
152	AreEqual(t, steps[1], rsim.Steps[1], "Wrong Step 1 in returned SimInfo")
153	AreEqual(t, steps[2], rsim.Steps[2], "Wrong Step 2 in returned SimInfo")
154}
155
156func TestDeleteSimSuccess(t *testing.T) {
157	br, simfu, ssfu, _, steps, _ := CreateSimHandlerBrowserWithSteps(0)
158
159	hdrs := http.Header{}
160	hdrs.Set("Content-Type", "application/json")
161	resp, err := br.Delete(steps[0], hdrs)
162	AssertSuccess(t, err)
163	AreEqual(t, http.StatusOK, resp.Code, "Not OK")
164
165	AreEqual(t, 2, len(simfu.Obj.(*SimInfo).Steps), "There should be two items in the list")
166	AreEqual(t, steps[1], simfu.Obj.(*SimInfo).Steps[0], "Wrong path in position 0 of step list")
167	AreEqual(t, steps[2], simfu.Obj.(*SimInfo).Steps[1], "Wrong path in position 1 of step list")
168	IsTrue(t, ssfu.DeleteCalled, "Delete was not called on the correct fileupdater")
169}
170
171func TestGenerateNetworkFailsIfStepsExist(t *testing.T) {
172	br, _, _, _, _, simid := CreateSimHandlerBrowserWithSteps(0)
173
174	hs := sim.HierarchySpec{
175		Levels:     2,
176		TeamSize:   2,
177		InitColors: []sim.Color{sim.Blue},
178		MaxColors:  4,
179	}
180	hss, err := json.Marshal(hs)
181	AssertSuccess(t, err)
182
183	hdrs := http.Header{}
184	hdrs.Set("Content-Type", "application/json")
185	resp, err := br.PostS(fmt.Sprintf("/api/simulation/%s/generate", simid), string(hss), hdrs)
186	AssertSuccess(t, err)
187	AreEqual(t, http.StatusBadRequest, resp.Code, "Not Bad Request")
188	AreEqual(t, "Simulation must have no steps when generating a new network", strings.TrimSpace(resp.Body.String()), "Incorrect error response")
189}
190
191func TestParseNetworkFailsIfStepsExist(t *testing.T) {
192	br, _, _, _, _, simid := CreateSimHandlerBrowserWithSteps(0)
193
194	data := []string{
195		"Header row is always skipped ,check_this_is_not_an_Id,,\n",
196		"Should be ignored|||\n",
197		"\n",
198		"Strips ws around Id, my_id\n",
199		"Blank lines are ignored\n",
200	}
201	var payload = []byte{}
202	for _, s := range data {
203		payload = append(payload, []byte(s)...)
204	}
205	pb := ParseBody{
206		ParseOptions: sim.ParseOptions{
207			Delimiter:  ",",
208			Identifier: 1,
209			Parent:     3,
210		},
211		Payload: payload,
212	}
213
214	pbs, err := json.Marshal(pb)
215	AssertSuccess(t, err)
216
217	hdrs := http.Header{}
218	hdrs.Set("Content-Type", "application/json")
219	resp, err := br.PostS(fmt.Sprintf("/api/simulation/%s/parse", simid), string(pbs), hdrs)
220	AssertSuccess(t, err)
221	AreEqual(t, http.StatusBadRequest, resp.Code, "Not Bad Request")
222	AreEqual(t, "Simulation must have no steps when parsing a new network", strings.TrimSpace(resp.Body.String()), "Incorrect error response")
223}
224
225func CreateSimHandlerBrowser() (*mango.Browser, *TestFileUpdater, *TestFileUpdater, string) {
226	simid := uuid.New().String()
227	nsim := NewSimInfo(simid)
228	nsim.Name = "mySavedSim"
229	nsim.Description = "A description of mySavedSim"
230	nsim.Steps = []string{}
231	nsim.Options.LinkedTeamList = []string{}
232	nsim.Options.EvangelistList = []string{}
233	nsim.Options.LoneEvangelist = []string{}
234	nsim.Options.InitColors = []sim.Color{}
235	simfu := &TestFileUpdater{
236		Obj:      nsim,
237		Filepath: nsim.Filepath(),
238	}
239	tfm := NewTestFileManager(simfu)
240	ssfu := &TestFileUpdater{}
241	tfm.SetDefault(ssfu)
242
243	r := CreateRouter(tfm)
244	br := mango.NewBrowser(r)
245
246	return br, simfu, ssfu, simid
247}
248
249func TestParseNetworkSucceeds(t *testing.T) {
250	br, simfu, ssfu, simid := CreateSimHandlerBrowser()
251	savedsim, ok := simfu.Obj.(*SimInfo)
252	IsTrue(t, ok, "Saved object would not cast to *SimInfo")
253	savedsim.Options.MaxColors = 5
254
255	data := []string{
256		"Header always skipped ,check_this_is_not_an_Id\n",
257		"Should be ignored|||\n",
258		"\n",
259		"Strips ws around Id, my_id\n",
260		"Blank lines are ignored\n",
261		"First agent, agent_1, some text,,\n",
262		"Second agent, agent_2, more text, agent_1,\n",
263	}
264	var payload = []byte{}
265	for _, s := range data {
266		payload = append(payload, []byte(s)...)
267	}
268	pb := ParseBody{
269		ParseOptions: sim.ParseOptions{
270			Delimiter:  ",",
271			Identifier: 1,
272			Parent:     3,
273		},
274		Payload: payload,
275	}
276
277	pbs, err := json.Marshal(pb)
278	AssertSuccess(t, err)
279
280	hdrs := http.Header{}
281	hdrs.Set("Content-Type", "application/json")
282	resp, err := br.PostS(fmt.Sprintf("/api/simulation/%s/parse", simid), string(pbs), hdrs)
283	AssertSuccess(t, err)
284	AreEqual(t, http.StatusCreated, resp.Code, "Not Created")
285	simstep, ok := ssfu.Obj.(*SimStep)
286	IsTrue(t, ok, "Saved object would not cast to *SimStep")
287	AreEqual(t, 5, simstep.Network.MaxColors(), "Wrong MaxColors on network")
288	IsTrue(t, simstep.Network.Links() != nil, "Links array is nil")
289	AreEqual(t, len(simstep.Network.Links()), 1, "Links should have a single item")
290	IsTrue(t, simstep.Network.Agents() != nil, "Agents array is nil")
291	AreEqual(t, len(simstep.Network.Agents()), 3, "Agents array should have 3 items")
292}
293
294func TestGenerateNetworkSucceeds(t *testing.T) {
295	br, simfu, ssfu, simid := CreateSimHandlerBrowser()
296
297	hs := sim.HierarchySpec{
298		Levels:     2,
299		TeamSize:   2,
300		InitColors: []sim.Color{sim.Green},
301		MaxColors:  4,
302	}
303	hss, err := json.Marshal(hs)
304	AssertSuccess(t, err)
305
306	hdrs := http.Header{}
307	hdrs.Set("Content-Type", "application/json")
308	resp, err := br.PostS(fmt.Sprintf("/api/simulation/%s/generate", simid), string(hss), hdrs)
309	AssertSuccess(t, err)
310	AreEqual(t, http.StatusCreated, resp.Code, "Not Created")
311	simstep, ok := ssfu.Obj.(*SimStep)
312	IsTrue(t, ok, "Saved object would not cast to *SimStep")
313	AreEqual(t, 4, simstep.Network.MaxColors(), "Wrong MaxColors on network")
314	AreEqual(t, 3, len(simstep.Network.Agents()), "Wrong number of agents on network")
315	AreEqual(t, 4, len(simstep.Results.Colors[0]), "Wrong number of Colors in Color results array")
316	AreEqual(t, 3, simstep.Results.Colors[0][3], "Wrong Green Color count in results array")
317	sim, ok := simfu.Obj.(*SimInfo)
318	IsTrue(t, ok, "Saved object would not cast to *SimInfo")
319	AreEqual(t, 1, len(sim.Options.InitColors), "Wrong InitColors on sim options")
320	AreEqual(t, hs.InitColors[0], sim.Options.InitColors[0], "Wrong InitColors on sim options")
321	AreEqual(t, hs.MaxColors, sim.Options.MaxColors, "Wrong MaxColors on sim options")
322}
323
324func TestPostRunFailsIfNoStepsExist(t *testing.T) {
325	br, _, _, simid := CreateSimHandlerBrowser()
326
327	rs := RunSpec{
328		Iterations: 5,
329		Steps:      5,
330	}
331	rss, err := json.Marshal(rs)
332	AssertSuccess(t, err)
333
334	hdrs := http.Header{}
335	hdrs.Set("Content-Type", "application/json")
336	resp, err := br.PostS(fmt.Sprintf("/api/simulation/%s/run", simid), string(rss), hdrs)
337	AssertSuccess(t, err)
338	AreEqual(t, http.StatusBadRequest, resp.Code, "Not Bad request")
339	AreEqual(t, "The simulation cannot be run without an initial step containing a network", strings.TrimSpace(resp.Body.String()), "Incorrect error response")
340}
341
342func TestPostRunFailsWithZeroIterations(t *testing.T) {
343	br, _, _, _, _, simid := CreateSimHandlerBrowserWithSteps(2)
344
345	rs := RunSpec{
346		Iterations: 0,
347		Steps:      5,
348	}
349	rss, err := json.Marshal(rs)
350	AssertSuccess(t, err)
351
352	hdrs := http.Header{}
353	hdrs.Set("Content-Type", "application/json")
354	resp, err := br.PostS(fmt.Sprintf("/api/simulation/%s/run", simid), string(rss), hdrs)
355	AssertSuccess(t, err)
356	AreEqual(t, http.StatusBadRequest, resp.Code, "Not Bad request")
357	AreEqual(t, "Steps and Iterations cannot be zero", strings.TrimSpace(resp.Body.String()), "Incorrect error response")
358}
359
360func TestPostRunFailsWithZeroStepCount(t *testing.T) {
361	br, _, _, _, _, simid := CreateSimHandlerBrowserWithSteps(2)
362
363	rs := RunSpec{
364		Iterations: 0,
365		Steps:      5,
366	}
367	rss, err := json.Marshal(rs)
368	AssertSuccess(t, err)
369
370	hdrs := http.Header{}
371	hdrs.Set("Content-Type", "application/json")
372	resp, err := br.PostS(fmt.Sprintf("/api/simulation/%s/run", simid), string(rss), hdrs)
373	AssertSuccess(t, err)
374	AreEqual(t, http.StatusBadRequest, resp.Code, "Not Bad request")
375	AreEqual(t, "Steps and Iterations cannot be zero", strings.TrimSpace(resp.Body.String()), "Incorrect error response")
376}
377
378func TestPostRunSucceedsWithOneStep(t *testing.T) {
379	br, _, _, dfu, _, simid := CreateSimHandlerBrowserWithSteps(2)
380	rs := RunSpec{
381		Iterations: 5,
382		Steps:      1,
383	}
384	rss, err := json.Marshal(rs)
385	AssertSuccess(t, err)
386
387	hdrs := http.Header{}
388	hdrs.Set("Content-Type", "application/json")
389	resp, err := br.PostS(fmt.Sprintf("/api/simulation/%s/run", simid), string(rss), hdrs)
390	AssertSuccess(t, err)
391	AreEqual(t, http.StatusCreated, resp.Code, "Not created")
392	ns := dfu.Obj.(*SimStep)
393	NotEqual(t, nil, ns, "New step is nil")
394	AreEqual(t, 4, ns.Network.MaxColors(), "MaxColors not correct on new network")
395	//Check there are 5 items in the results arrays, one for each iteration
396	AreEqual(t, 5, len(ns.Results.Colors), "Wrong number of items in the Colors array")
397	AreEqual(t, 5, len(ns.Results.Conversations), "Wrong number of items in the Conversations array")
398}
399
400func CreateResults(iterations, maxColors int) sim.Results {
401	results := sim.Results{
402		Iterations:    iterations,
403		Colors:        make([][]int, iterations),
404		Conversations: make([]int, iterations),
405	}
406	for i := 0; i < iterations; i++ {
407		results.Conversations[i] = i + 1
408		colorCounts := make([]int, maxColors)
409		for j := 0; j < maxColors; j++ {
410			colorCounts[j] = i + j
411		}
412		results.Colors[i] = colorCounts
413	}
414	return results
415}
416
417func CreateSimHandlerBrowserWithStepsAndResults() (*mango.Browser, string) {
418	simid := uuid.New().String()
419	sim := NewSimInfo(simid)
420	sim.Name = "mySavedSim"
421	sim.Description = "A description of mySavedSim"
422	ids := []string{
423		uuid.New().String(),
424		uuid.New().String(),
425		uuid.New().String(),
426	}
427	simfu := &TestFileUpdater{
428		Obj:      sim,
429		Filepath: sim.Filepath(),
430	}
431	tfm := NewTestFileManager(simfu)
432	steps := make([]string, len(ids))
433	for i, id := range ids {
434		steps[i] = fmt.Sprintf("/api/simulation/%s/step/%s", simid, id)
435		ss := &SimStep{
436			ID:       id,
437			ParentID: simid,
438			Results:  CreateResults(i+1, 4),
439		}
440		ssfu := &TestFileUpdater{
441			Obj:      ss,
442			Filepath: ss.Filepath(),
443		}
444		tfm.Add(ss.Filepath(), ssfu)
445	}
446	sim.Steps = steps
447	r := CreateRouter(tfm)
448	br := mango.NewBrowser(r)
449
450	return br, simid
451}
452
453func TestGetResultsSucceeds(t *testing.T) {
454	br, simid := CreateSimHandlerBrowserWithStepsAndResults()
455
456	hdrs := http.Header{}
457	resp, err := br.Get(fmt.Sprintf("/api/simulation/%s/results", simid), hdrs)
458	AssertSuccess(t, err)
459	AreEqual(t, http.StatusOK, resp.Code, "Not OK")
460	rs := &sim.Results{}
461	json.Unmarshal(resp.Body.Bytes(), rs)
462	AreEqual(t, 6, rs.Iterations, "Wrong number of iterations")
463	AreEqual(t, 1, rs.Conversations[0], "Wrong conversation count")
464	AreEqual(t, 1, rs.Conversations[1], "Wrong conversation count")
465	AreEqual(t, 2, rs.Conversations[2], "Wrong conversation count")
466	AreEqual(t, 1, rs.Conversations[3], "Wrong conversation count")
467	AreEqual(t, 2, rs.Conversations[4], "Wrong conversation count")
468	AreEqual(t, 3, rs.Conversations[5], "Wrong conversation count")
469	AreEqual(t, 3, rs.Colors[0][3], "Wrong color count")
470	AreEqual(t, 3, rs.Colors[1][3], "Wrong color count")
471	AreEqual(t, 4, rs.Colors[2][3], "Wrong color count")
472	AreEqual(t, 3, rs.Colors[3][3], "Wrong color count")
473	AreEqual(t, 4, rs.Colors[4][3], "Wrong color count")
474	AreEqual(t, 5, rs.Colors[5][3], "Wrong color count")
475}
476
477func TestGetResultsSucceedsAsCsv(t *testing.T) {
478	br, simid := CreateSimHandlerBrowserWithStepsAndResults()
479
480	hdrs := http.Header{
481		"Content-Type": []string{"text/csv"},
482	}
483	resp, err := br.Get(fmt.Sprintf("/api/simulation/%s/results", simid), hdrs)
484	AssertSuccess(t, err)
485	AreEqual(t, http.StatusOK, resp.Code, "Not OK")
486	csv := resp.Body.String()
487	scanner := bufio.NewScanner(strings.NewReader(csv))
488
489	//check the headers are correct
490	ct := false
491	for _, header := range resp.Header()[http.CanonicalHeaderKey("content-type")] {
492		if header == "text/csv" {
493			ct = true
494			break
495		}
496	}
497	IsTrue(t, ct, "content-type header incorrect or missing")
498	IsTrue(t, len(resp.Header()[http.CanonicalHeaderKey("content-disposition")]) > 0, "content-disposition missing")
499
500	//Read the header line
501	scanner.Scan()
502	endCol := len(strings.Split(scanner.Text(), ",")) - 1
503
504	//convert the csv into an array of int arrays
505	rs := [][]int{}
506	i := 0
507	for scanner.Scan() {
508		strs := strings.Split(scanner.Text(), ",")
509		vals := make([]int, endCol+1)
510		for j, val := range strs {
511			vals[j], _ = strconv.Atoi(val)
512		}
513		rs = append(rs, vals)
514		i++
515	}
516	//Check the results are correct
517	AreEqual(t, 6, len(rs), "Wrong number of iterations")
518	AreEqual(t, 1, rs[0][endCol], "Wrong conversation count")
519	AreEqual(t, 1, rs[1][endCol], "Wrong conversation count")
520	AreEqual(t, 2, rs[2][endCol], "Wrong conversation count")
521	AreEqual(t, 1, rs[3][endCol], "Wrong conversation count")
522	AreEqual(t, 2, rs[4][endCol], "Wrong conversation count")
523	AreEqual(t, 3, rs[5][endCol], "Wrong conversation count")
524	AreEqual(t, 3, rs[0][3], "Wrong color count")
525	AreEqual(t, 3, rs[1][3], "Wrong color count")
526	AreEqual(t, 4, rs[2][3], "Wrong color count")
527	AreEqual(t, 3, rs[3][3], "Wrong color count")
528	AreEqual(t, 4, rs[4][3], "Wrong color count")
529	AreEqual(t, 5, rs[5][3], "Wrong color count")
530}
531
Full Screen

networkparser_test.go

Source: networkparser_test.go Github

copy
1package sim
2
3import "testing"
4
5func TestParseDelimAgents(t *testing.T) {
6	data := []string{
7		"Header row is always skipped |check_this_is_not_an_Id||",
8		"Strips ws around Id leaves ws in Id|   id _ 1  |   |  ",
9		"Should be ignored|||",
10		"Strips ws around Id| my_id ||",
11		"Should also be ignored|   ||",
12		"Pulls entire Id without ws|1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-+={}[]()!£$%^&*@~#<>/?\\||",
13		"Should also be ignored|",
14		"Regular Id|Some_id7|",
15	}
16	po := ParseOptions{
17		Delimiter:  "|",
18		Identifier: 1,
19		Parent:     -1,
20	}
21	rm, err := po.ParseDelim(data)
22	AssertSuccess(t, err)
23
24	agents := rm.Agents()
25	AreEqual(t, 4, len(agents), "Wrong number of agents parsed from source data")
26	AreEqual(t, "id _ 1", agents[0].Identifier(), "Wrong first agent Id")
27	AreEqual(t, "my_id", agents[1].Identifier(), "Wrong first agent Id")
28	AreEqual(t, "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-+={}[]()!£$%^&*@~#<>/?\\", agents[2].Identifier(), "Wrong first agent Id")
29	AreEqual(t, "Some_id7", agents[3].Identifier(), "Wrong first agent Id")
30}
31
32func TestParseDelimLinks(t *testing.T) {
33	data := []string{
34		"Header row is always skipped |check_this_is_not_an_Id||",
35		"Strips ws around Id leaves ws in Id|   id _ 1  |   |  ",
36		"Should be ignored|||",
37		"Strips ws around Id| my_id ||id _ 1",
38		"Blank lines are ignored",
39		"Should also be ignored|   ||",
40		"Pulls entire Id without ws|1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-+={}[]()!£$%^&*@~#<>/?\\",
41		"Should also be ignored|",
42		"Regular Id|Some_id7||my_id|",
43		"Repeated Agent Id is ignored|Some_id7||id _ 1|",
44		"Another Agent child of my_id|NewId18 || my_id ",
45		"Ignores a link to itself|Id69 || Id69 ",
46		"Child of really long Id|NewId35 || 1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-+={}[]()!£$%^&*@~#<>/?\\",
47	}
48	po := ParseOptions{
49		Delimiter:  "|",
50		Identifier: 1,
51		Parent:     3,
52	}
53	rm, err := po.ParseDelim(data)
54	AssertSuccess(t, err)
55
56	links := rm.Links()
57	AreEqual(t, 4, len(links), "Wrong number of links parsed from source data")
58	for _, link := range links {
59		switch link.Agent2ID {
60		case "my_id":
61			AreEqual(t, "id _ 1", link.Agent1ID, "Wrong parent for Agent 'my_id'")
62		case "Some_id7":
63			AreEqual(t, "my_id", link.Agent1ID, "Wrong parent for Agent 'Some_id7'")
64		case "NewId18":
65			AreEqual(t, "my_id", link.Agent1ID, "Wrong parent for Agent 'NewId18'")
66		case "NewId35":
67			AreEqual(t, "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-+={}[]()!£$%^&*@~#<>/?\\", link.Agent1ID, "Wrong parent for Agent 'NewId35'")
68		}
69	}
70}
71
72func TestParseDelimLinksThrowsErrorWhenLinkTargetDoesntExist(t *testing.T) {
73	data := []string{
74		"Header row is always skipped |check_this_is_not_an_Id||",
75		"Strips ws around Id leaves ws in Id|   id _ 1  |   |  ",
76		"Should be ignored|||",
77		"Strips ws around Id| my_id ||id _ 1",
78		"Blank lines are ignored",
79		"Parent doesn't exist!|Some_id7||Id615|",
80		"Another Agent child of my_id|NewId18 || my_id ",
81		"Ignores a link to itself|Id69 || Id69 ",
82	}
83	po := ParseOptions{
84		Delimiter:  "|",
85		Identifier: 1,
86		Parent:     3,
87	}
88	_, err := po.ParseDelim(data)
89	IsFalse(t, err == nil, "Expecting an error to be thrown")
90}
91
92func TestParseDelimCsv(t *testing.T) {
93	data := []string{
94		"Header row is always skipped ,check_this_is_not_an_Id,,",
95		"Should be ignored|||",
96		"",
97		"Strips ws around Id, my_id",
98		"Blank lines are ignored",
99	}
100	po := ParseOptions{
101		Delimiter:  ",",
102		Identifier: 1,
103		Parent:     3,
104	}
105	rm, err := po.ParseDelim(data)
106	AssertSuccess(t, err)
107
108	agents := rm.Agents()
109	AreEqual(t, 1, len(agents), "Wrong number of agents parsed from source data")
110	AreEqual(t, "my_id", agents[0].Identifier(), "Wrong first agent Id")
111}
112
113func TestParseDelimTsv(t *testing.T) {
114	data := []string{
115		"Header row is always skipped	check_this_is_not_an_Id		",
116		"Should be ignored|||",
117		"",
118		"Strips ws around Id	  my_id ",
119		"Blank lines are ignored",
120	}
121	po := ParseOptions{
122		Delimiter:  "\t",
123		Identifier: 1,
124		Parent:     3,
125	}
126	rm, err := po.ParseDelim(data)
127	AssertSuccess(t, err)
128
129	agents := rm.Agents()
130	AreEqual(t, 1, len(agents), "Wrong number of agents parsed from source data")
131	AreEqual(t, "my_id", agents[0].Identifier(), "Wrong first agent Id")
132}
133
134func TestParseDelimOnlyIncludesRowsWithOtherMatchingColumn(t *testing.T) {
135	data := []string{
136		"Header row is always skipped |check_this_is_not_an_Id||Include",
137		"Strips ws around Id leaves ws in Id|   id _ 1  |   | Include  ",
138		"Should be ignored| id_2 ||",
139		"Should be ignored| id_3",
140		"Blank lines are ignored",
141		"Should be included|id_4|   |Include|",
142	}
143	po := ParseOptions{
144		Delimiter:  "|",
145		Identifier: 1,
146		Regex: map[string]string{
147			"3": `\S+`,
148		},
149	}
150	rm, err := po.ParseDelim(data)
151	AssertSuccess(t, err)
152
153	agents := rm.Agents()
154	AreEqual(t, 2, len(agents), "Wrong number of agents parsed from source data")
155	AreEqual(t, "id _ 1", agents[0].Identifier(), "Wrong first agent Id")
156	AreEqual(t, "id_4", agents[1].Identifier(), "Wrong second agent Id")
157}
158
Full Screen

simlisthandler_test.go

Source: simlisthandler_test.go Github

copy
1package srvr
2
3import (
4	"encoding/json"
5	"fmt"
6	"net/http"
7	"testing"
8
9	"github.com/google/uuid"
10	"github.com/spaceweasel/mango"
11)
12
13func CreateSimListHandlerBrowser() (*mango.Browser, *TestFileUpdater, *TestFileUpdater, *TestFileManager) {
14	sl := NewSimList()
15	sl.Items = []string{
16		"/api/simulation/{someIdHere}",
17	}
18	sl.Notes = "Some notes"
19	slfu := &TestFileUpdater{
20		Obj:      sl,
21		Filepath: sl.Filepath(),
22	}
23	tfm := NewTestFileManager(slfu)
24	dfu := &TestFileUpdater{}
25	tfm.SetDefault(dfu)
26
27	r := CreateRouter(tfm)
28	br := mango.NewBrowser(r)
29
30	return br, slfu, dfu, tfm
31}
32
33func TestUpdateSimListNotesSuccess(t *testing.T) {
34	br, slfu, _, _ := CreateSimListHandlerBrowser()
35
36	hdrs := http.Header{}
37	hdrs.Set("Content-Type", "application/json")
38	data := `{"Notes":"some different notes"}`
39	resp, err := br.PutS("/api/simulation/notes", data, hdrs)
40	AssertSuccess(t, err)
41	AreEqual(t, http.StatusOK, resp.Code, "Not OK")
42
43	AreEqual(t, 1, len(slfu.Obj.(*SimList).Items), "There should still be one item in the list")
44	AreEqual(t, "/api/simulation/{someIdHere}", slfu.Obj.(*SimList).Items[0], "Sim list changed when updating notes")
45
46	rsl := &SimList{}
47	err = json.Unmarshal(resp.Body.Bytes(), rsl)
48	AssertSuccess(t, err)
49	AreEqual(t, 1, len(rsl.Items), "There should be one item in the returned list")
50	AreEqual(t, "/api/simulation/{someIdHere}", rsl.Items[0], "Returned Sim list changed when updating notes")
51	AreEqual(t, "some different notes", rsl.Notes, "Returned notes not updated")
52}
53
54func TestGetSimList(t *testing.T) {
55	br, _, _, _ := CreateSimListHandlerBrowser()
56
57	hdrs := http.Header{}
58	resp, err := br.Get("/api/simulation", hdrs)
59	AssertSuccess(t, err)
60	AreEqual(t, http.StatusOK, resp.Code, "Not OK")
61
62	rsl := &SimListExt{
63		TimestampHolder: TimestampHolder{},
64		Items:           []*SimInfo{},
65		Notes:           "",
66	}
67	json.Unmarshal(resp.Body.Bytes(), rsl)
68	AreEqual(t, 1, len(rsl.Items), "Wrong number of items in returned list")
69	AreEqual(t, "{someIdHere}", rsl.Items[0].ID, "Wrong item in list")
70	AreEqual(t, "Some notes", rsl.Notes, "Wrong notes")
71}
72
73func TestGetSimListReturnErrorWhenReadFails(t *testing.T) {
74	br, slfu, _, _ := CreateSimListHandlerBrowser()
75	slfu.ReadErr = fmt.Errorf("Access denied")
76
77	hdrs := http.Header{}
78	resp, err := br.Get("/api/simulation", hdrs)
79	AssertSuccess(t, err)
80	AreEqual(t, http.StatusInternalServerError, resp.Code, "Not Error")
81	AreEqual(t, "Access denied", resp.Body.String(), "Incorrect error message")
82}
83
84func TestAddSimToSimListSuccess(t *testing.T) {
85	br, slfu, dfu, _ := CreateSimListHandlerBrowser()
86
87	hdrs := http.Header{}
88	hdrs.Set("Content-Type", "application/json")
89	data := `{"Name":"mySim","Description":"A description of my sim"}`
90	resp, err := br.PostS("/api/simulation", data, hdrs)
91	AssertSuccess(t, err)
92	AreEqual(t, http.StatusCreated, resp.Code, "Not OK")
93
94	AreEqual(t, 2, len(slfu.Obj.(*SimList).Items), "There should be two items in the list")
95	AreEqual(t, fmt.Sprintf("/api/simulation/%s", dfu.Obj.(*SimInfo).ID), slfu.Obj.(*SimList).Items[1], "Wrong path added to sim list")
96
97	rsim := &SimInfo{}
98	err = json.Unmarshal(resp.Body.Bytes(), rsim)
99	AssertSuccess(t, err)
100	AreEqual(t, dfu.Obj.(*SimInfo).ID, rsim.ID, "ID of returned SimInfo incorrect")
101	AreEqual(t, "mySim", rsim.Name, "Name of returned SimInfo incorrect")
102	AreEqual(t, "A description of my sim", rsim.Description, "Description of returned SimInfo incorrect")
103}
104
105func TestAddsSimToEmptySimListSuccess(t *testing.T) {
106	br, slfu, dfu, _ := CreateSimListHandlerBrowser()
107	slfu.Obj = NewSimList()
108
109	hdrs := http.Header{}
110	hdrs.Set("Content-Type", "application/json")
111	data := `{"Name":"mySim","Description":"A description of my sim"}`
112	resp, err := br.PostS("/api/simulation", data, hdrs)
113	AssertSuccess(t, err)
114	AreEqual(t, http.StatusCreated, resp.Code, "Not OK")
115
116	AreEqual(t, 1, len(slfu.Obj.(*SimList).Items), "There should be one item in the list")
117	AreEqual(t, fmt.Sprintf("/api/simulation/%s", dfu.Obj.(*SimInfo).ID), slfu.Obj.(*SimList).Items[0], "Wrong path added to sim list")
118
119	rsim := &SimInfo{}
120	err = json.Unmarshal(resp.Body.Bytes(), rsim)
121	AssertSuccess(t, err)
122	AreEqual(t, dfu.Obj.(*SimInfo).ID, rsim.ID, "ID of returned SimInfo incorrect")
123	AreEqual(t, "mySim", rsim.Name, "Name of returned SimInfo incorrect")
124	AreEqual(t, "A description of my sim", rsim.Description, "Description of returned SimInfo incorrect")
125}
126
127func TestAddSimListFailsWithWrongHeaders(t *testing.T) {
128	br, _, _, _ := CreateSimListHandlerBrowser()
129
130	hdrs := http.Header{}
131	data := `{"Name":"mySim","Description":"A description of my sim"}`
132	resp, err := br.PostS("/api/simulation", data, hdrs)
133	AssertSuccess(t, err)
134	AreEqual(t, http.StatusBadRequest, resp.Code, "Not Bad request")
135}
136
137func TestAddSimListReturnsErrorWithFileReadErr(t *testing.T) {
138	br, slfu, _, _ := CreateSimListHandlerBrowser()
139	slfu.ReadErr = fmt.Errorf("Access denied")
140
141	hdrs := http.Header{}
142	hdrs.Set("Content-Type", "application/json")
143	data := `{"Name":"mySim","Description":"A description of my sim"}`
144	resp, err := br.PostS("/api/simulation", data, hdrs)
145	AssertSuccess(t, err)
146	AreEqual(t, http.StatusInternalServerError, resp.Code, "No error reported")
147	Contains(t, "Access denied", resp.Body.String(), "Wrong error reported")
148}
149
150func TestAddSimListReturnsErrorWithFileUpdateErr(t *testing.T) {
151	br, slfu, _, _ := CreateSimListHandlerBrowser()
152	slfu.UpdateErr = fmt.Errorf("Access denied")
153
154	hdrs := http.Header{}
155	hdrs.Set("Content-Type", "application/json")
156	data := `{"Name":"mySim","Description":"A description of my sim"}`
157	resp, err := br.PostS("/api/simulation", data, hdrs)
158	AssertSuccess(t, err)
159	AreEqual(t, http.StatusInternalServerError, resp.Code, "No error reported")
160	Contains(t, "Access denied", resp.Body.String(), "Wrong error reported")
161}
162
163func TestAddSimListReturnsErrorWithFileCreateErr(t *testing.T) {
164	br, _, dfu, _ := CreateSimListHandlerBrowser()
165	dfu.CreateErr = fmt.Errorf("Access denied")
166
167	hdrs := http.Header{}
168	hdrs.Set("Content-Type", "application/json")
169	data := `{"Name":"mySim","Description":"A description of my sim"}`
170	resp, err := br.PostS("/api/simulation", data, hdrs)
171	AssertSuccess(t, err)
172	AreEqual(t, http.StatusInternalServerError, resp.Code, "No error reported")
173	Contains(t, "Access denied", resp.Body.String(), "Wrong error reported")
174}
175
176func SetupForDeleteTests(deleteItemIndex int) (*mango.Browser, *TestFileUpdater, *TestFileUpdater, []string) {
177	br, slfu, _, tfm := CreateSimListHandlerBrowser()
178	sl := NewSimList()
179	ids := []string{
180		uuid.New().String(),
181		uuid.New().String(),
182		uuid.New().String(),
183	}
184	items := make([]string, len(ids))
185	for i, id := range ids {
186		items[i] = fmt.Sprintf("/api/simulation/%s", id)
187	}
188	sl.Items = items
189	slfu.Obj = sl
190	sim := &SimInfo{
191		ID: ids[deleteItemIndex],
192	}
193	simfu := &TestFileUpdater{
194		Obj:      sim,
195		Filepath: sim.Filepath(),
196	}
197	tfm.Add(sim.Filepath(), simfu)
198	return br, slfu, simfu, items
199}
200
201func TestDeleteFirstSimFromSimListSuccess(t *testing.T) {
202	br, slfu, simfu, items := SetupForDeleteTests(0)
203
204	hdrs := http.Header{}
205	resp, err := br.Delete(items[0], hdrs)
206	AssertSuccess(t, err)
207	AreEqual(t, http.StatusOK, resp.Code, "Not OK")
208
209	AreEqual(t, 2, len(slfu.Obj.(*SimList).Items), "There should be two items in the list")
210	AreEqual(t, items[1], slfu.Obj.(*SimList).Items[0], "Wrong path in position 0 of sim list")
211	AreEqual(t, items[2], slfu.Obj.(*SimList).Items[1], "Wrong path in position 1 of sim list")
212	IsTrue(t, simfu.DeleteCalled, "Delete was not called on the correct fileupdater")
213}
214
215func TestDeleteMiddleSimFromSimListSuccess(t *testing.T) {
216	br, slfu, simfu, items := SetupForDeleteTests(1)
217
218	hdrs := http.Header{}
219	resp, err := br.Delete(items[1], hdrs)
220	AssertSuccess(t, err)
221	AreEqual(t, http.StatusOK, resp.Code, "Not OK")
222
223	AreEqual(t, 2, len(slfu.Obj.(*SimList).Items), "There should be two items in the list")
224	AreEqual(t, items[0], slfu.Obj.(*SimList).Items[0], "Wrong path in position 0 of sim list")
225	AreEqual(t, items[2], slfu.Obj.(*SimList).Items[1], "Wrong path in position 1 of sim list")
226	IsTrue(t, simfu.DeleteCalled, "Delete was not called on the correct fileupdater")
227}
228
229func TestDeleteLastSimFromSimListSuccess(t *testing.T) {
230	br, slfu, simfu, items := SetupForDeleteTests(2)
231
232	hdrs := http.Header{}
233	resp, err := br.Delete(items[2], hdrs)
234	AssertSuccess(t, err)
235	AreEqual(t, http.StatusOK, resp.Code, "Not OK")
236
237	AreEqual(t, 2, len(slfu.Obj.(*SimList).Items), "There should be two items in the list")
238	AreEqual(t, items[0], slfu.Obj.(*SimList).Items[0], "Wrong path in position 0 of sim list")
239	AreEqual(t, items[1], slfu.Obj.(*SimList).Items[1], "Wrong path in position 1 of sim list")
240	IsTrue(t, simfu.DeleteCalled, "Delete was not called on the correct fileupdater")
241}
242
243func TestDeleteSimFromSimListReturnsNotFoundWhenListEmpty(t *testing.T) {
244	br, slfu, _, _ := CreateSimListHandlerBrowser()
245	sl := NewSimList()
246	slfu.Obj = sl
247
248	hdrs := http.Header{}
249	resp, err := br.Delete(fmt.Sprintf("/api/simulation/%s", uuid.New().String()), hdrs)
250	AssertSuccess(t, err)
251	AreEqual(t, http.StatusNotFound, resp.Code, "Not Found not reported")
252}
253
254func TestDeleteSimFromSimListReturnsNotFoundWhenNotInList(t *testing.T) {
255	br, _, _, _ := SetupForDeleteTests(0)
256
257	hdrs := http.Header{}
258	resp, err := br.Delete(fmt.Sprintf("/api/simulation/%s", uuid.New().String()), hdrs)
259	AssertSuccess(t, err)
260	AreEqual(t, http.StatusNotFound, resp.Code, "Not Found not reported")
261}
262
263func TestDeleteReturnsErrorWhenSimListReadErr(t *testing.T) {
264	br, slfu, simfu, items := SetupForDeleteTests(0)
265	slfu.ReadErr = fmt.Errorf("Access denied")
266
267	hdrs := http.Header{}
268	resp, err := br.Delete(items[0], hdrs)
269	AssertSuccess(t, err)
270	AreEqual(t, http.StatusInternalServerError, resp.Code, "Not error")
271	Contains(t, "Access denied", resp.Body.String(), "Wrong error reported")
272	IsFalse(t, simfu.DeleteCalled, "Delete was still called on the Sim fileupdater")
273}
274
275func TestDeleteReturnsErrorWhenSimListUpdateErr(t *testing.T) {
276	br, slfu, simfu, items := SetupForDeleteTests(0)
277	slfu.UpdateErr = fmt.Errorf("Access denied")
278
279	hdrs := http.Header{}
280	resp, err := br.Delete(items[0], hdrs)
281	AssertSuccess(t, err)
282	AreEqual(t, http.StatusInternalServerError, resp.Code, "Not error")
283	Contains(t, "Access denied", resp.Body.String(), "Wrong error reported")
284	IsFalse(t, simfu.DeleteCalled, "Delete was still called on the Sim fileupdater")
285}
286
287func TestDeleteReturnsErrorWhenSimDeleteErr(t *testing.T) {
288	br, _, simfu, items := SetupForDeleteTests(0)
289	simfu.DeleteErr = fmt.Errorf("Access denied")
290
291	hdrs := http.Header{}
292	resp, err := br.Delete(items[0], hdrs)
293	AssertSuccess(t, err)
294	AreEqual(t, http.StatusInternalServerError, resp.Code, "Not error")
295	Contains(t, "Access denied", resp.Body.String(), "Wrong error reported")
296	IsTrue(t, simfu.DeleteCalled, "Delete was still called on the Sim fileupdater")
297}
298
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

Trigger areEqual code on LambdaTest Cloud Grid

Execute automation tests with areEqual on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
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)