-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathe2e_test.go
488 lines (422 loc) · 13.8 KB
/
e2e_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
package kama_test
import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"unsafe"
"github.com/komuw/kama"
"go.akshayshah.org/attest"
)
const kamaWriteDataForTests = "KAMA_WRITE_DATA_FOR_TESTS"
const longText = `AT last the sleepy atmosphere was stirred—and vigorously: the murder trial came on in the court. It became the absorbing topic of village talk immediately. Tom could not get away from it. Every reference to the murder sent a shudder to his heart, for his troubled conscience and fears almost persuaded him that these remarks were put forth in his hearing as “feelers”; he did not see how he could be suspected of knowing anything about the murder, but still he could not be comfortable in the midst of this gossip. It kept him in a cold shiver all the time. He took Huck to a lonely place to have a talk with him. It would be some relief to unseal his tongue for a little while; to divide his burden of distress with another sufferer. Moreover, he wanted to assure himself that Huck had remained discreet.
“Huck, have you ever told anybody about—that?”
“’Bout what?”
“You know what.”
“Oh—’course I haven’t.”
“Never a word?”
“Never a solitary word, so help me. What makes you ask?”
“Well, I was afeard.”
“Why, Tom Sawyer, we wouldn’t be alive two days if that got found out. You know that.”
Tom felt more comfortable. After a pause:
“Huck, they couldn’t anybody get you to tell, could they?”
“Get me to tell? Why, if I wanted that halfbreed devil to drownd me they could get me to tell. They ain’t no different way.”
“Well, that’s all right, then. I reckon we’re safe as long as we keep mum. But let’s swear again, anyway. It’s more surer.”
“I’m agreed.”
So they swore again with dread solemnities.
“What is the talk around, Huck? I’ve heard a power of it.”
“Talk? Well, it’s just Muff Potter, Muff Potter, Muff Potter all the time. It keeps me in a sweat, constant, so’s I want to hide som’ers.”
“That’s just the same way they go on round me. I reckon he’s a goner. Don’t you feel sorry for him, sometimes?”
“Most always—most always. He ain’t no account; but then he hain’t ever done anything to hurt anybody. Just fishes a little, to get money to get drunk on—and loafs around considerable; but lord, we all do that—leastways most of us—preachers and such like. But he’s kind of good—he give me half a fish, once, when there warn’t enough for two; and lots of times he’s kind of stood by me when I was out of luck.”
“Well, he’s mended kites for me, Huck, and knitted hooks on to my line. I wish we could get him out of there.”
“My! we couldn’t get him out, Tom. And besides, ’twouldn’t do any good; they’d ketch him again.”
“Yes—so they would. But I hate to hear ’em abuse him so like the dickens when he never done—that.”
“I do too, Tom. Lord, I hear ’em say he’s the bloodiest looking villain in this country, and they wonder he wasn’t ever hung before.”
“Yes, they talk like that, all the time. I’ve heard ’em say that if he was to get free they’d lynch him.”
“And they’d do it, too.”
The boys had a long talk, but it brought them little comfort. As the twilight drew on, they found themselves hanging about the neighborhood of the little isolated jail, perhaps with an undefined hope that something would happen that might clear away their difficulties. But nothing happened; there seemed to be no angels or fairies interested in this luckless captive.
The boys did as they had often done before—went to the cell grating and gave Potter some tobacco and matches. He was on the ground floor and there were no guards.`
type Distance uint64
func bigMap() map[int]string {
y := map[int]string{}
for i := 0; i < 10_000; i++ {
y[i] = fmt.Sprintf("%d", i)
}
return y
}
func bigChan() chan int {
z := make(chan int, 10_000)
for i := 0; i < 122; i++ {
z <- i
}
return z
}
func makeDirecteChan() chan<- bool {
directedChan := make(chan<- bool, 13)
directedChan <- true
return directedChan
}
func bigSlice() []int {
bigSlice := []int{}
for i := 0; i < 10_000; i++ {
bigSlice = append(bigSlice, i)
}
return bigSlice
}
func makeSliceOfHttpRequests() []http.Request {
h := []http.Request{}
for i := 0; i < 100; i++ {
h = append(h, http.Request{Method: fmt.Sprint(i)})
}
return h
}
// We just need a type that will implement the `io.ReadCloser` interface
type CustomReadCloser int64
func (c CustomReadCloser) Read(p []byte) (n int, err error) {
return 10, nil
}
func (c CustomReadCloser) Close() error {
return errors.New("CustomReadCloser always fails closing")
}
type FuncWithReturn func(http.ResponseWriter) (uint16, error)
type SomeStruct struct {
SomeInt int16
SomeUintptr uintptr
SliceOfHttpRequest []http.Request
OneHttpRequest http.Request
EmptyString string
SmallString string
LargeString string
DistinctType Distance
SomeNilError error
SomeConcreteError error
LargeSlice []int
LargeMap map[int]string
UndirectedChan chan int
DirectedChan chan<- bool
SomeBool bool
NonIntializedFuncClosure func() (io.ReadCloser, error)
NonIntializedFuncFromStdLib http.HandlerFunc
NonIntializedFuncWithReturn FuncWithReturn
IntializedFuncClosure func() (io.ReadCloser, error)
IntializedFuncFromStdLib http.HandlerFunc
IntializedFuncWithReturn FuncWithReturn
ZeroPointerStruct *url.URL // we won't initiliaze this
NonZeroPointerStruct *url.URL
EvenMoreUrl *url.URL
SliceOfNonZeroPointerStruct []*url.URL
ComplexxySixFour complex64
ComplexyOneTwoEight complex128
NonStructPointer *int8
SomeUnsafety unsafe.Pointer
}
type secretKey string
func (s secretKey) String() string {
if len(s) <= 0 {
return "secretKey(<EMPTY>)"
}
return fmt.Sprintf("secretKey(%s<REDACTED>)", string(s[0]))
}
func (s secretKey) GoString() string {
return s.String()
}
// dealWithTestData asserts that gotContent is equal to data found at path.
//
// If the environment variable [kamaWriteDataForTests] is set, this func
// will write gotContent to path instead.
func dealWithTestData(t *testing.T, path, gotContent string) {
t.Helper()
path = strings.ReplaceAll(path, ".go", "")
p, e := filepath.Abs(path)
attest.Ok(t, e)
writeData := os.Getenv(kamaWriteDataForTests) != ""
if writeData {
errM := os.MkdirAll(filepath.Dir(p), 0o755)
attest.Ok(t, errM)
err := os.WriteFile(path, []byte(gotContent), 0o644)
attest.Ok(t, err)
t.Logf("\n\t written testdata to %s\n", path)
return
}
b, e := os.ReadFile(p)
attest.Ok(t, e)
expectedContent := string(b)
attest.Equal(t, gotContent, expectedContent, attest.Sprintf("path: %s", path))
}
func getDataPath(t *testing.T, testPath, testName string) string { //nolint:unparam
t.Helper()
s := strings.ReplaceAll(testName, " ", "_")
tName := strings.ReplaceAll(s, "/", "_")
path := filepath.Join("testdata", testPath, tName) + ".txt"
return path
}
func TestDir(t *testing.T) {
t.Parallel()
type someStructWithSlice struct {
XX []int
}
structWithSlice := someStructWithSlice{XX: bigSlice()}
type someStructWithMap struct {
XX map[int]string
}
structWithMap := someStructWithMap{XX: bigMap()}
normalString := "heyWorldOkay"
tt := []struct {
tName string
item interface{}
}{
{
tName: "number int",
item: int(44),
},
{
tName: "number int32",
item: int32(32),
},
{
tName: "number int64",
item: int64(64),
},
{
tName: "number float32",
item: float32(32),
},
{
tName: "number float64",
item: float64(64),
},
{
tName: "number uintptr",
item: uintptr(123),
},
{
tName: "number uint64",
item: uint64(88),
},
{
tName: "slice on its own is not compacted",
item: bigSlice(),
},
{
tName: "slice in a struct is not compacted",
item: structWithSlice,
},
{
tName: "map on its own is not compacted",
item: bigMap(),
},
{
tName: "map in a struct is not compacted",
item: structWithMap,
},
{
tName: "normal string",
item: normalString,
},
{
tName: "custom string type",
item: secretKey("ThisIsMyPrivateApiKey"),
},
}
for _, v := range tt {
v := v
t.Run(v.tName, func(t *testing.T) {
t.Parallel()
res := kama.Dir(v.item)
path := getDataPath(t, "e2e_test.go", v.tName)
dealWithTestData(t, path, res)
})
}
t.Run("struct of varying field types", func(t *testing.T) {
t.Parallel()
someIntEight := int8(14)
s := SomeStruct{
SomeInt: 13,
SomeUintptr: uintptr(64_902),
SliceOfHttpRequest: makeSliceOfHttpRequests(),
OneHttpRequest: http.Request{Method: "Hello"},
EmptyString: "",
SmallString: "What up?",
LargeString: longText,
DistinctType: Distance(9131),
SomeNilError: nil,
SomeConcreteError: errors.New("Houston something bad happened"),
LargeSlice: bigSlice(),
LargeMap: bigMap(),
UndirectedChan: bigChan(),
DirectedChan: makeDirecteChan(),
SomeBool: true,
IntializedFuncClosure: func() (io.ReadCloser, error) {
return CustomReadCloser(900), nil
},
IntializedFuncFromStdLib: func(rw http.ResponseWriter, r *http.Request) {
_ = r.Close
_, _ = io.WriteString(rw, "yo")
},
IntializedFuncWithReturn: func(http.ResponseWriter) (uint16, error) {
return uint16(1), nil
},
NonZeroPointerStruct: &url.URL{},
EvenMoreUrl: &url.URL{Path: "/some/path"},
SliceOfNonZeroPointerStruct: []*url.URL{
{Path: "1"},
{Path: "2"},
{Path: "3"},
{Path: "4"},
{Path: "5"},
{Path: "6"},
{Path: "7"},
{Path: "8"},
},
ComplexxySixFour: complex(float32(5), 7),
ComplexyOneTwoEight: complex(float64(5), 7),
NonStructPointer: &someIntEight,
SomeUnsafety: unsafe.Pointer(&someIntEight),
}
res := kama.Dir(s)
path := getDataPath(t, "e2e_test.go", "struct_of_varying_field_types.txt")
dealWithTestData(t, path, res)
})
t.Run("pointer to struct of varying field types", func(t *testing.T) {
t.Parallel()
someIntEight := int8(14)
s := &SomeStruct{
SomeInt: 13,
SomeUintptr: uintptr(64_902),
SliceOfHttpRequest: makeSliceOfHttpRequests(),
OneHttpRequest: http.Request{Method: "Hello"},
EmptyString: "",
SmallString: "What up?",
LargeString: longText,
DistinctType: Distance(9131),
SomeNilError: nil,
SomeConcreteError: errors.New("Houston something bad happened"),
LargeSlice: bigSlice(),
LargeMap: bigMap(),
UndirectedChan: bigChan(),
DirectedChan: makeDirecteChan(),
SomeBool: true,
IntializedFuncClosure: func() (io.ReadCloser, error) {
return CustomReadCloser(900), nil
},
IntializedFuncFromStdLib: func(rw http.ResponseWriter, r *http.Request) {
_ = r.Close
_, _ = io.WriteString(rw, "yo")
},
IntializedFuncWithReturn: func(http.ResponseWriter) (uint16, error) {
return uint16(1), nil
},
NonZeroPointerStruct: &url.URL{},
EvenMoreUrl: &url.URL{Path: "/some/path"},
SliceOfNonZeroPointerStruct: []*url.URL{
{Path: "1"},
{Path: "2"},
{Path: "3"},
{Path: "4"},
{Path: "5"},
{Path: "6"},
{Path: "7"},
{Path: "8"},
},
ComplexxySixFour: complex(float32(5), 7),
ComplexyOneTwoEight: complex(float64(5), 7),
NonStructPointer: &someIntEight,
SomeUnsafety: unsafe.Pointer(&someIntEight),
}
res := kama.Dir(s)
path := getDataPath(t, "e2e_test.go", "pointer_to_struct_of_varying_field_types.txt")
dealWithTestData(t, path, res)
})
t.Run("slice of http.Request value structs", func(t *testing.T) {
t.Parallel()
sliceOfStruct := func() []http.Request {
xx := []http.Request{}
for i := 0; i < 10_000; i++ {
xx = append(xx, http.Request{Method: fmt.Sprintf("%d", i)})
}
return xx
}
s := sliceOfStruct()
res := kama.Dir(s)
path := getDataPath(t, "e2e_test.go", "slice_of_http_Request_value_structs.txt")
dealWithTestData(t, path, res)
})
}
func TestAllAboutInterfaces(t *testing.T) {
t.Parallel()
t.Run("interfaces should be well represented", func(t *testing.T) {
t.Parallel()
var SomeNilError error = nil
var SomeConcreteError error = errors.New("unable to read from ftp file")
var SomeReader io.Reader = strings.NewReader("hello my reader")
var NilEmptyInterface interface{} = nil
var NonNilEmptyInterface interface{} = 9
type SomeStructWithInterfaces struct {
AAA io.Reader
SomeNilError error
SomeConcreteError error
}
someOne := SomeStructWithInterfaces{
AAA: strings.NewReader("hello from strings NewReader"),
SomeConcreteError: errors.New("houston something bad happened"),
}
someTwo := &someOne
tt := []struct {
tName string
item interface{}
}{
{
tName: "SomeNilError",
item: SomeNilError,
},
{
tName: "SomeConcreteError",
item: SomeConcreteError,
},
{
tName: "&SomeConcreteError",
item: &SomeConcreteError,
},
{
tName: "SomeReader",
item: SomeReader,
},
{
tName: "NilEmptyInterface",
item: NilEmptyInterface,
},
{
tName: "NonNilEmptyInterface",
item: NonNilEmptyInterface,
},
{
tName: "someOne",
item: someOne,
},
{
tName: "someTwo",
item: someTwo,
},
}
for _, v := range tt {
v := v
t.Run(v.tName, func(t *testing.T) {
t.Parallel()
res := kama.Dir(v.item)
path := getDataPath(t, "e2e_test.go", v.tName)
dealWithTestData(t, path, res)
})
}
})
}
func ExampleDirp() {
req, _ := http.NewRequest("GET", "https://example.com", nil)
req.Header.Set("Content-Type", "application/octet-stream")
req.AddCookie(&http.Cookie{Name: "hello", Value: "world"})
kama.Dirp(req, kama.Config{ShowColor: false})
}