-
Notifications
You must be signed in to change notification settings - Fork 1
/
diagram_test.go
530 lines (485 loc) · 13.3 KB
/
diagram_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
package spectest
import (
"html/template"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
)
// MockFS is a mock implementation of the fileSystem interface
type MockFS struct {
// CapturedCreateName is the name captured by the create method
CapturedCreateName string
// CapturedCreateFile is the file path (full path) captured by the create method
CapturedCreateFile string
// CapturedMkdirAllPath is the path captured by the mkdirAll method
CapturedMkdirAllPath string
}
// create creates a file at the given path
func (m *MockFS) create(name string) (*os.File, error) {
m.CapturedCreateName = name
file, err := os.CreateTemp("/tmp", "spectest")
if err != nil {
panic(err)
}
m.CapturedCreateFile = file.Name()
return file, nil
}
// mkdirAll creates a directory at the given path
func (m *MockFS) mkdirAll(path string, _ os.FileMode) error {
m.CapturedMkdirAllPath = path
return nil
}
func TestDiagramBadgeCSSClass(t *testing.T) {
tests := []struct {
status int
class string
}{
{status: http.StatusOK, class: "badge badge-success"},
{status: http.StatusInternalServerError, class: "badge badge-danger"},
{status: http.StatusBadRequest, class: "badge badge-warning"},
}
for _, test := range tests {
t.Run(test.class, func(t *testing.T) {
class := badgeCSSClass(test.status)
assert.Equal(t, test.class, class)
})
}
}
func TestFormatBodyContentShouldReplaceBody(t *testing.T) {
stream := io.NopCloser(strings.NewReader("lol"))
val, err := formatBodyContent(stream, func(replacementBody io.ReadCloser) {
stream = replacementBody
})
assert.NoError(t, err)
assert.Equal(t, "lol", val)
valSecondRun, errSecondRun := formatBodyContent(stream, func(replacementBody io.ReadCloser) {
stream = replacementBody
})
assert.NoError(t, errSecondRun)
assert.Equal(t, "lol", valSecondRun)
}
func TestWebSequenceDiagramGeneratesDSL(t *testing.T) {
t.Run("should generate a valid web sequence diagram", func(t *testing.T) {
wsd := webSequenceDiagramDSL{
meta: &Meta{},
}
wsd.addRequestRow("A", "B", "request1")
wsd.addRequestRow("B", "C", "request2")
wsd.addResponseRow("C", "B", "response1")
wsd.addResponseRow("B", "A", "response2")
actual := wsd.String()
expected := `"A"->"B": (1) request1
"B"->"C": (2) request2
"C"->>"B": (3) response1
"B"->>"A": (4) response2
`
if expected != actual {
t.Fatalf("expected=%s != \nactual=%s", expected, actual)
}
})
t.Run("use custom consumer name and custom testing target name", func(t *testing.T) {
wsd := webSequenceDiagramDSL{
meta: &Meta{},
}
wsd.addRequestRow(ConsumerDefaultName, SystemUnderTestDefaultName, "request1")
wsd.addRequestRow(SystemUnderTestDefaultName, "C", "request2")
wsd.addResponseRow("C", SystemUnderTestDefaultName, "response1")
wsd.addResponseRow(SystemUnderTestDefaultName, ConsumerDefaultName, "response2")
actual := wsd.String()
expected := `"client"->"server": (1) request1
"server"->"C": (2) request2
"C"->>"server": (3) response1
"server"->>"client": (4) response2
`
if expected != actual {
t.Fatalf("expected=%s != \nactual=%s", expected, actual)
}
})
t.Run("use custom consumer name and custom testing target name", func(t *testing.T) {
wsd := webSequenceDiagramDSL{
meta: &Meta{
ConsumerName: "custom-consumer",
TestingTargetName: "custom-testing-target",
},
}
wsd.addRequestRow(ConsumerDefaultName, SystemUnderTestDefaultName, "request1")
wsd.addRequestRow(SystemUnderTestDefaultName, "C", "request2")
wsd.addResponseRow("C", SystemUnderTestDefaultName, "response1")
wsd.addResponseRow(SystemUnderTestDefaultName, ConsumerDefaultName, "response2")
actual := wsd.String()
expected := `"custom-consumer"->"custom-testing-target": (1) request1
"custom-testing-target"->"C": (2) request2
"C"->>"custom-testing-target": (3) response1
"custom-testing-target"->>"custom-consumer": (4) response2
`
if expected != actual {
t.Fatalf("expected=%s != \nactual=%s", expected, actual)
}
})
}
func TestNewSequenceDiagramFormatterStoragePath(t *testing.T) {
t.Run("should use default storage path", func(t *testing.T) {
formatter := SequenceDiagram()
v, ok := formatter.(*SequenceDiagramFormatter)
if !ok {
t.Fatalf("expected SequenceDiagramFormatter, got %T", formatter)
}
assert.Equal(t, ".sequence", v.storagePath)
})
t.Run("should use custom storage path", func(t *testing.T) {
formatter := SequenceDiagram(".sequence-diagram")
v, ok := formatter.(*SequenceDiagramFormatter)
if !ok {
t.Fatalf("expected SequenceDiagramFormatter, got %T", formatter)
}
assert.Equal(t, ".sequence-diagram", v.storagePath)
})
}
func TestRecorderBuilder(t *testing.T) {
recorder := aRecorder()
assert.Equal(t, 4, len(recorder.Events))
assert.Equal(t, "title", recorder.Title)
assert.Equal(t, "subTitle", recorder.SubTitle)
assert.Equal(t,
&Meta{
Path: "/user",
Name: "some test",
Host: "example.com",
Method: "GET",
}, recorder.Meta)
assert.Equal(t, "reqSource", recorder.Events[0].(HTTPRequest).Source)
assert.Equal(t, "mesReqSource", recorder.Events[1].(MessageRequest).Source)
assert.Equal(t, "mesResSource", recorder.Events[2].(MessageResponse).Source)
assert.Equal(t, "resSource", recorder.Events[3].(HTTPResponse).Source)
}
func TestNewHTMLTemplateModelErrorsIfNoEventsDefined(t *testing.T) {
recorder := NewTestRecorder()
s := SequenceDiagramFormatter{
storagePath: ".sequence",
fs: &MockFS{},
}
_, err := s.newHTMLTemplateModel(recorder)
assert.Equal(t, "no events are defined", err.Error())
}
func TestNewHTMLTemplateModelSuccess(t *testing.T) {
recorder := aRecorder()
s := SequenceDiagramFormatter{
storagePath: ".sequence",
fs: &MockFS{},
}
model, err := s.newHTMLTemplateModel(recorder)
assert.True(t, err == nil)
assert.Equal(t, 4, len(model.LogEntries))
assert.Equal(t, "title", model.Title)
assert.Equal(t, "subTitle", model.SubTitle)
assert.Equal(t, template.JS(`{"host":"example.com","method":"GET","name":"some test","path":"/user"}`), model.MetaJSON)
assert.Equal(t, http.StatusNoContent, model.StatusCode)
assert.Equal(t, "badge badge-success", model.BadgeClass)
assert.True(t, strings.Contains(model.WebSequenceDSL, "GET /abcdef"))
}
func aRecorder() *Recorder {
return NewTestRecorder().
AddTitle("title").
AddSubTitle("subTitle").
AddHTTPRequest(aRequest()).
AddMessageRequest(MessageRequest{Header: "A", Body: "B", Source: "mesReqSource"}).
AddMessageResponse(MessageResponse{Header: "C", Body: "D", Source: "mesResSource"}).
AddHTTPResponse(aResponse()).
AddMeta(&Meta{
Path: "/user",
Name: "some test",
Host: "example.com",
Method: "GET",
})
}
func TestNewHttpRequestLogEntry(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/path", strings.NewReader(`{"a": 12345}`))
logEntry, err := NewHTTPRequestLogEntry(req)
assert.True(t, err == nil)
assert.True(t, strings.Contains(logEntry.Header, "GET /path"))
assert.True(t, strings.Contains(logEntry.Header, "HTTP/1.1"))
assert.JSONEq(t, logEntry.Body, `{"a": 12345}`)
}
func TestNewHttpResponseLogEntryJSON(t *testing.T) {
response := &http.Response{
ProtoMajor: 1,
ProtoMinor: 1,
StatusCode: http.StatusOK,
ContentLength: 21,
Body: io.NopCloser(strings.NewReader(`{"a": 12345}`)),
}
logEntry, err := NewHTTPResponseLogEntry(response)
assert.True(t, err == nil)
assert.True(t, strings.Contains(logEntry.Header, `HTTP/1.1 200 OK`))
assert.True(t, strings.Contains(logEntry.Header, `Content-Length: 21`))
assert.JSONEq(t, logEntry.Body, `{"a": 12345}`)
}
func TestNewHttpResponseLogEntryPlainText(t *testing.T) {
response := &http.Response{
ProtoMajor: 1,
ProtoMinor: 1,
StatusCode: http.StatusOK,
ContentLength: 21,
Body: io.NopCloser(strings.NewReader(`abcdef`)),
}
logEntry, err := NewHTTPResponseLogEntry(response)
assert.True(t, err == nil)
assert.True(t, strings.Contains(logEntry.Header, `HTTP/1.1 200 OK`))
assert.True(t, strings.Contains(logEntry.Header, `Content-Length: 21`))
assert.Equal(t, logEntry.Body, `abcdef`)
}
func aRequest() HTTPRequest {
req := httptest.NewRequest(http.MethodGet, "http://example.com/abcdef?name=abc", nil)
req.Header.Set("Content-Type", "application/json")
return HTTPRequest{Value: req, Source: "reqSource", Target: "reqTarget"}
}
func aResponse() HTTPResponse {
return HTTPResponse{
Value: &http.Response{
StatusCode: http.StatusNoContent,
ProtoMajor: 1,
ProtoMinor: 1,
ContentLength: 0,
},
Source: "resSource",
Target: "resTarget",
}
}
func TestExtractContentType(t *testing.T) {
tests := []struct {
name string
headers string
want string
}{
{
name: "should extract content type",
headers: "GET /path HTTP/1.1\r\nHost: example.com\r\nContent-Type: application/json\r\n\r\n",
want: "application/json",
},
{
name: "should return empty string if content type is not found",
headers: "GET /path HTTP/1.1\r\nHost: example.com\r\n\r\n",
want: "",
},
{
name: "should return empty string if headers is empty",
headers: "",
want: "",
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
if got := extractContentType(tt.headers); got != tt.want {
t.Errorf("extractContentType() = %v, want %v", got, tt.want)
}
})
}
}
func TestIsImage(t *testing.T) {
tests := []struct {
name string
contentType string
want bool
}{
{
name: "should return true if content type is image/jpeg",
contentType: "image/jpeg",
want: true,
},
{
name: "should return true if content type is image/png",
contentType: "image/png",
want: true,
},
{
name: "should return true if content type is image/gif",
contentType: "image/gif",
want: true,
},
{
name: "should return true if content type is image/svg+xml",
contentType: "image/svg+xml",
want: true,
},
{
name: "should return true if content type is image/bmp",
contentType: "image/bmp",
want: true,
},
{
name: "should return true if content type is image/webp",
contentType: "image/webp",
want: true,
},
{
name: "should return true if content type is image/tiff",
contentType: "image/tiff",
want: true,
},
{
name: "should return true if content type is image/x-icon",
contentType: "image/x-icon",
want: true,
},
{
name: "should return false if content type is not an image",
contentType: "application/json",
want: false,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
if got := isImage(tt.contentType); got != tt.want {
t.Errorf("isImage() = %v, want %v", got, tt.want)
}
})
}
}
func Test_imagePath(t *testing.T) {
type args struct {
dir string
name string
contentType string
index int
}
tests := []struct {
name string
args args
want string
}{
{
name: "should return image path",
args: args{
dir: "/tmp",
name: "image",
contentType: "image/png",
index: 1,
},
want: "/tmp/image_1.png",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := imagePath(tt.args.dir, tt.args.name, tt.args.contentType, tt.args.index); got != tt.want {
t.Errorf("imagePath() = %v, want %v", got, tt.want)
}
})
}
}
func Test_toImageExt(t *testing.T) {
type args struct {
contentType string
}
tests := []struct {
name string
args args
want string
}{
{
name: "image/png should return png",
args: args{
contentType: "image/png",
},
want: "png",
},
{
name: "image/jpeg should return jpeg",
args: args{
contentType: "image/jpeg",
},
want: "jpeg",
},
{
name: "image/gif should return gif",
args: args{
contentType: "image/gif",
},
want: "gif",
},
{
name: "image/svg+xml should return svg",
args: args{
contentType: "image/svg+xml",
},
want: "svg",
},
{
name: "image/bmp should return bmp",
args: args{
contentType: "image/bmp",
},
want: "bmp",
},
{
name: "image/webp should return webp",
args: args{
contentType: "image/webp",
},
want: "webp",
},
{
name: "image/tiff should return tiff",
args: args{
contentType: "image/tiff",
},
want: "tiff",
},
{
name: "image/x-icon should return ico",
args: args{
contentType: "image/x-icon",
},
want: "ico",
},
{
name: "application/json should return empty string",
args: args{
contentType: "application/json",
},
want: "",
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
if got := toImageExt(tt.args.contentType); got != tt.want {
t.Errorf("toImageExt() = %v, want %v", got, tt.want)
}
})
}
}
func Test_imageName(t *testing.T) {
type args struct {
name string
contentType string
index int
}
tests := []struct {
name string
args args
want string
}{
{
name: "should return image name",
args: args{
name: "image",
contentType: "image/png",
index: 1,
},
want: "image_1.png",
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
if got := imageName(tt.args.name, tt.args.contentType, tt.args.index); got != tt.want {
t.Errorf("imageName() = %v, want %v", got, tt.want)
}
})
}
}