This repository has been archived by the owner on Aug 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
autograder_test.go
2110 lines (2051 loc) · 71.2 KB
/
autograder_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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"fmt"
"github.com/61c-teach/sp19-proj5-userlib"
"net/http"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
)
/*
* This is a hacky method to make the handler think that it is talking to the web response.
*/
type ResponseWriterTester struct {
http.ResponseWriter
header http.Header
data []byte
statusCode int
}
func (r *ResponseWriterTester) Header() http.Header {
return r.header
}
func (r *ResponseWriterTester) Write(d []byte) (int, error) {
r.data = append(r.data, d...)
return len(d), nil
}
func (r *ResponseWriterTester) WriteHeader(statusCode int) {
r.statusCode = statusCode
}
func genResponseTestWriter() *ResponseWriterTester {
return &ResponseWriterTester{header: http.Header{}}
}
func genRequestUrl(urlpath string) *http.Request {
return &http.Request{URL:&url.URL{Path:urlpath}}
}
func clearCache() {
resp := genResponseTestWriter()
req := genRequestUrl(cacheCloseUrl)
cacheClearHandler(resp, req)
}
var cacheUrl = "/cache"
var cacheCloseUrl = "/cache/close"
func validateFileResponse(readName, expectedName string, dataToBeRead []byte, resp *ResponseWriterTester, expectedCode int, t *testing.T) (failed bool) {
// Finally we validate if we read the correct filename.
if expectedName != "" && expectedName != readName {
failed = true
t.Errorf("The path which was passed in was not correct! Expected: (%s), Actual: (%s)", string(expectedName), string(readName))
}
// We will also assert that we have read the correct bytes just to be certain that everything was saved and forwarded correctly.
if dataToBeRead != nil && !bytes.Equal(dataToBeRead, resp.data) {
failed = true
t.Errorf("The data that was received was not what was expected! Expected (%s), Actual (%s)", string(dataToBeRead), string(resp.data))
}
// Next we check to see if the header has the correct value for the context type.
if resp.header.Get(userlib.ContextType) != userlib.GetContentType(expectedName){
failed = true
t.Errorf("Received the wrong context type for the file. Expected: (%s), Actual: (%s)", string(userlib.GetContentType(expectedName)), string(resp.header.Get(userlib.ContextType)))
}
// We finally wanna check that we set the correct return code.
if resp.statusCode != expectedCode {
failed = true
t.Errorf("Received the wrong status code! Expected: (%v), Actual: (%v)", expectedCode, resp.statusCode)
}
return failed
}
func validateBadFile(badName string, secTimeout int, t *testing.T) (failed bool) {
resp := requestFile(badName, secTimeout, t)
dataToBeRead := []byte(userlib.FILEERRORMSG + "\n")
// We will also assert that we have read the correct bytes just to be certain that everything was saved and forwarded correctly.
if dataToBeRead != nil && !bytes.Equal(dataToBeRead, resp.data) {
failed = true
t.Errorf("The data that was received was not what was expected! Expected (%s), Actual (%s)", string(dataToBeRead), string(resp.data))
}
// We finally wanna check that we set the correct return code.
if resp.statusCode != userlib.FILEERRORCODE {
failed = true
t.Errorf("Received the wrong status code! Expected: (%v), Actual: (%v)", userlib.FILEERRORCODE, resp.statusCode)
}
return failed
}
func validateTimeout(resp *ResponseWriterTester, t *testing.T) (failed bool) {
if !bytes.Equal(resp.data, []byte(userlib.TimeoutString + "\n")) {
failed = true
t.Errorf("I did not receive the timeout string! Expected: (%s), Actual: (%s)!", userlib.TimeoutString + "\n", string(resp.data))
}
return failed
}
func validateCacheSize(items, size int,t *testing.T) (failed bool) {
resp := genResponseTestWriter()
req := genRequestUrl(cacheUrl)
cacheHandler(resp, req)
correctCacheResponse := fmt.Sprintf(userlib.CapacityString, items, size, capacity)
if !bytes.Equal(resp.data, []byte(correctCacheResponse)) {
failed = true
t.Errorf("The expected cache data was not correct! Expected: (%s), Actual: (%s)", correctCacheResponse, string(resp.data))
}
return failed
}
func validateCacheNotExceeded(t *testing.T) (failed bool) {
resp := genResponseTestWriter()
req := genRequestUrl(cacheUrl)
rgx := regexp.MustCompile(`\[(.*?)\]`)
cacheHandler(resp, req)
rs := rgx.FindStringSubmatch(string(resp.data))
if len(rs) < 2 {
failed = true
t.Errorf("Could not read the current cache capacity! Got back: (%s)", string(resp.data))
return failed
}
curCap, err := strconv.ParseInt(rs[1], 10, 32)
if err != nil {
failed = true
t.Error(err)
return failed
}
if curCap > int64(capacity) {
failed = true
t.Errorf("The capacity of the cache has been exceeded! Expected max: (%v), Actual: (%v)", capacity, curCap)
}
return failed
}
func validateNumberOfReads(expected, count uint64, t *testing.T) (failed bool) {
if expected != count {
failed = true
t.Errorf("An incorrect number of reads occurred.")
}
return failed
}
func requestFile(filename string, secTimeout int, t *testing.T) *ResponseWriterTester {
resp := genResponseTestWriter()
req := genRequestUrl(filename)
c := make(chan bool)
go func (chan bool) {
handler(resp, req)
c <- true
}(c)
select {
case <- c: // This means we did not time out.
case <- time.After(time.Duration(secTimeout + 1) * time.Second):
t.Errorf("The handler took too long to respond!")
t.FailNow()
}
return resp
}
var launched = false
//func init() {
// go operateCache()
//}
func launchCache() {
if launched == false {
launched = true
go operateCache()
}
}
// ============ Sanity Tests ============
func TestSanityFileTest(t *testing.T) {
// We first need to define a capacity and timeout so our cache has some parameters.
secCap := 1000
secTimeout := 2
capacity = secCap
timeout = secTimeout
workingDir = ""
launchCache()
// We need to set up a response writer which will be the dummy passed into the handler to make testing easier.
resp := genResponseTestWriter()
// This is the filename which will be passed into the handler as a url.
name := "/cs61c.html"
// For this test, we expect the only change to the file name to be adding a dot in front of it since there is nothing else to replace.
expectedName := "." + name
// I keep a dummy readName variable which will be set by the custom userlib function I defined below.
readName := ""
// This is the data which that fake file will contain.
dataToBeRead := []byte("CS61C is the best class in the world! Emperor Nick shall reign supreme.")
// This is bad data which will be read if the filename is not correct.
badData := []byte("CS61C is the worst class ever!")
// We finally make the http request which the handler can understand.
req := genRequestUrl(name)
// We set the userlib FileRead function to this custom 'read'.
userlib.ReplaceReadFile(func(workingDir, filename string)(data []byte, err error){
// Set the global readName variable to what we read for an error check later.
readName = filename
// If we get the expected name, we will return the correct data.
if filename == expectedName {
data = dataToBeRead
} else {
// Otherwise we return the bad data.
data = badData
}
return
})
// We finally will call the handler. This is where we will get the data from the cache and or filesystem depending
// on if it is in the cache. It will be stored in the dummy Response Writer which was created above.
handler(resp, req)
validateFileResponse(readName, expectedName, dataToBeRead, resp, userlib.SUCCESSCODE, t)
if capacity != secCap {
t.Errorf("The max capacity has been changed when it should not have been!")
os.Exit(61)
}
if timeout != secTimeout {
t.Errorf("The timeout has been changed when it should not have been!")
os.Exit(62)
}
clearCache()
}
func TestSanityFileCheckSize(t *testing.T) {
// We first need to define a capacity and timeout so our cache has some parameters.
secCap := 1000
secTimeout := 2
capacity = secCap
timeout = secTimeout
workingDir = ""
launchCache()
// We need to set up a response writer which will be the dummy passed into the handler to make testing easier.
resp := genResponseTestWriter()
// This is the filename which will be passed into the handler as a url.
name := "/README.md"
// For this test, we expect the only change to the file name to be adding a dot in front of it since there is nothing else to replace.
expected_name := "." + name
// I keep a dummy read_name variable which will be set by the custom userlib function I defined below.
read_name := ""
// This is the data which that fake file will contain.
data_to_be_read := []byte("CS61C is the best class in the world! Emperor Nick shall reign supreme.")
// This is bad data which will be read if the filename is not correct.
bad_data := []byte("CS61C is the worst class ever!")
// We finally make the http request which the handler can understand.
req := genRequestUrl(name)
// We need to count the number of file reads we get.
var reads uint64 = 0
// We set the userlib FileRead function to this custom 'read'.
userlib.ReplaceReadFile(func(workingDir, filename string)(data []byte, err error){
// Increment the read counter
atomic.AddUint64(&reads, 1)
// Set the global read_name variable to what we read for an error check later.
read_name = filename
// If we get the expected name, we will return the correct data.
if filename == expected_name {
data = data_to_be_read
} else {
// Otherwise we return the bad data.
data = bad_data
}
return
})
// We finally will call the handler. This is where we will get the data from the cache and or filesystem depending
// on if it is in the cache. It will be stored in the dummy Response Writer which was created above.
handler(resp, req)
validateFileResponse(read_name, expected_name, data_to_be_read, resp, userlib.SUCCESSCODE, t)
validateCacheSize(1, len(data_to_be_read), t)
validateNumberOfReads(1, reads, t)
if capacity != secCap {
t.Errorf("The max capacity has been changed when it should not have been!")
os.Exit(61)
}
if timeout != secTimeout {
t.Errorf("The timeout has been changed when it should not have been!")
os.Exit(62)
}
clearCache()
}
func TestSanityFileDoubleRead(t *testing.T) {
// We first need to define a capacity and timeout so our cache has some parameters.
secCap := 1000
secTimeout := 2
capacity = secCap
timeout = secTimeout
workingDir = ""
launchCache()
// We need to set up a response writer which will be the dummy passed into the handler to make testing easier.
resp := genResponseTestWriter()
// This is the filename which will be passed into the handler as a url.
name := "/README.md"
// For this test, we expect the only change to the file name to be adding a dot in front of it since there is nothing else to replace.
expected_name := "." + name
// I keep a dummy read_name variable which will be set by the custom userlib function I defined below.
read_name := ""
// This is the data which that fake file will contain.
data_to_be_read := []byte("CS61C is the best class in the world! Emperor Nick shall reign supreme.")
// This is bad data which will be read if the filename is not correct.
bad_data := []byte("CS61C is the worst class ever!")
// We finally make the http request which the handler can understand.
req := genRequestUrl(name)
// We need to count the number of file reads we get.
var reads uint64 = 0
// We set the userlib FileRead function to this custom 'read'.
userlib.ReplaceReadFile(func(workingDir, filename string)(data []byte, err error){
// Increment the read counter
atomic.AddUint64(&reads, 1)
// Set the global read_name variable to what we read for an error check later.
read_name = filename
// If we get the expected name, we will return the correct data.
if filename == expected_name {
data = data_to_be_read
} else {
// Otherwise we return the bad data.
data = bad_data
}
return
})
// We finally will call the handler. This is where we will get the data from the cache and or filesystem depending
// on if it is in the cache. It will be stored in the dummy Response Writer which was created above.
handler(resp, req)
validateFileResponse(read_name, expected_name, data_to_be_read, resp, userlib.SUCCESSCODE, t)
resp = genResponseTestWriter()
handler(resp, req)
validateFileResponse(read_name, expected_name, data_to_be_read, resp, userlib.SUCCESSCODE, t)
validateCacheSize(1, len(data_to_be_read), t)
validateNumberOfReads(1, reads, t)
if capacity != secCap {
t.Errorf("The max capacity has been changed when it should not have been!")
os.Exit(61)
}
if timeout != secTimeout {
t.Errorf("The timeout has been changed when it should not have been!")
os.Exit(62)
}
clearCache()
}
func TestSanityReadCloseRead(t *testing.T) {
// We first need to define a capacity and timeout so our cache has some parameters.
secCap := 1000
secTimeout := 2
capacity = secCap
timeout = secTimeout
workingDir = ""
launchCache()
// We need to set up a response writer which will be the dummy passed into the handler to make testing easier.
resp := genResponseTestWriter()
// This is the filename which will be passed into the handler as a url.
name := "/README.md"
// For this test, we expect the only change to the file name to be adding a dot in front of it since there is nothing else to replace.
expected_name := "." + name
// I keep a dummy read_name variable which will be set by the custom userlib function I defined below.
read_name := ""
// This is the data which that fake file will contain.
data_to_be_read := []byte("CS61C is the best class in the world! Emperor Nick shall reign supreme.")
// This is bad data which will be read if the filename is not correct.
bad_data := []byte("CS61C is the worst class ever!")
// We finally make the http request which the handler can understand.
req := genRequestUrl(name)
// We need to count the number of file reads we get.
var reads uint64 = 0
// We set the userlib FileRead function to this custom 'read'.
userlib.ReplaceReadFile(func(workingDir, filename string)(data []byte, err error){
// Increment the read counter
atomic.AddUint64(&reads, 1)
// Set the global read_name variable to what we read for an error check later.
read_name = filename
// If we get the expected name, we will return the correct data.
if filename == expected_name {
data = data_to_be_read
} else {
// Otherwise we return the bad data.
data = bad_data
}
return
})
// We finally will call the handler. This is where we will get the data from the cache and or filesystem depending
// on if it is in the cache. It will be stored in the dummy Response Writer which was created above.
handler(resp, req)
validateFileResponse(read_name, expected_name, data_to_be_read, resp, userlib.SUCCESSCODE, t)
validateCacheSize(1, len(data_to_be_read), t)
if reads != 1 {
t.Errorf("There should have been only one file read before we close.")
}
clearCache()
validateCacheSize(0, 0, t)
resp = genResponseTestWriter()
req = genRequestUrl(name)
handler(resp, req)
validateFileResponse(read_name, expected_name, data_to_be_read, resp, userlib.SUCCESSCODE, t)
validateCacheSize(1, len(data_to_be_read), t)
validateNumberOfReads(2, reads, t)
if capacity != secCap {
t.Errorf("The max capacity has been changed when it should not have been!")
os.Exit(61)
}
if timeout != secTimeout {
t.Errorf("The timeout has been changed when it should not have been!")
os.Exit(62)
}
clearCache()
}
func TestSanity404(t *testing.T) {
// We first need to define a capacity and timeout so our cache has some parameters.
secCap := 100
secTimeout := 2
capacity = secCap
timeout = secTimeout
workingDir = ""
launchCache()
// This is the filename which will be passed into the handler as a url.
name := "/IDONTEXIST.txt"
// For this test, we expect the only change to the file name to be adding a dot in front of it since there is nothing else to replace.
expectedName := "." + name
// This is the data which that fake file will contain.
dataToBeRead := []byte("CS61C is the best class in the world! Emperor Nick shall reign supreme.")
// This is bad data which will be read if the filename is not correct.
badData := []byte("CS61C is the worst class ever!")
// We need to count the number of file reads we get.
var reads uint64 = 0
// We set the userlib FileRead function to this custom 'read'.
userlib.ReplaceReadFile(func(workingDir, filename string)(data []byte, err error){
// Increment the read counter
atomic.AddUint64(&reads, 1)
// If we get the expected name, we will return the correct data.
if filename == expectedName {
data = dataToBeRead
} else {
// Otherwise we return the bad data.
data = badData
}
err = fmt.Errorf("the file does not exist")
return
})
// We finally will call the handler. This is where we will get the data from the cache and or filesystem depending
// on if it is in the cache. It will be stored in the dummy Response Writer which was created above.
validateBadFile(name, secTimeout, t)
validateCacheSize(0, 0, t)
validateBadFile(name, secTimeout, t)
validateCacheSize(0, 0, t)
validateNumberOfReads(2, reads, t)
if capacity != secCap {
t.Errorf("The max capacity has been changed when it should not have been!")
os.Exit(61)
}
if timeout != secTimeout {
t.Errorf("The timeout has been changed when it should not have been!")
os.Exit(62)
}
clearCache()
}
func TestSanityFileType(t *testing.T) {
// We first need to define a capacity and timeout so our cache has some parameters.
secCap := 100
secTimeout := 2
capacity = secCap
timeout = secTimeout
workingDir = ""
launchCache()
readName := ""
fData := []byte("data")
var reads uint64 = 0
// We set the userlib FileRead function to this custom 'read'.
userlib.ReplaceReadFile(func(workingDir, filename string)(data []byte, err error){
// Increment the read counter
atomic.AddUint64(&reads, 1)
readName = filename
data = fData
return
})
name := "/exam.htm"
resp := requestFile(name, secTimeout, t)
validateFileResponse(readName, "." + name, fData, resp, userlib.SUCCESSCODE, t)
name = "/exam.html"
resp = requestFile(name, secTimeout, t)
validateFileResponse(readName, "." + name, fData, resp, userlib.SUCCESSCODE, t)
name = "/exam.jpeg"
resp = requestFile(name, secTimeout, t)
validateFileResponse(readName, "." + name, fData, resp, userlib.SUCCESSCODE, t)
name = "/exam.jpg"
resp = requestFile(name, secTimeout, t)
validateFileResponse(readName, "." + name, fData, resp, userlib.SUCCESSCODE, t)
name = "/exam.png"
resp = requestFile(name, secTimeout, t)
validateFileResponse(readName, "." + name, fData, resp, userlib.SUCCESSCODE, t)
name = "/exam.css"
resp = requestFile(name, secTimeout, t)
validateFileResponse(readName, "." + name, fData, resp, userlib.SUCCESSCODE, t)
name = "/exam.js"
resp = requestFile(name, secTimeout, t)
validateFileResponse(readName, "." + name, fData, resp, userlib.SUCCESSCODE, t)
name = "/exam.pdf"
resp = requestFile(name, secTimeout, t)
validateFileResponse(readName, "." + name, fData, resp, userlib.SUCCESSCODE, t)
name = "/exam.pdx"
resp = requestFile(name, secTimeout, t)
validateFileResponse(readName, "." + name, fData, resp, userlib.SUCCESSCODE, t)
name = "/exam.txt"
resp = requestFile(name, secTimeout, t)
validateFileResponse(readName, "." + name, fData, resp, userlib.SUCCESSCODE, t)
name = "/exam.txt"
resp = requestFile(name, secTimeout, t)
validateFileResponse(readName, "." + name, fData, resp, userlib.SUCCESSCODE, t)
if capacity != secCap {
t.Errorf("The max capacity has been changed when it should not have been!")
os.Exit(61)
}
if timeout != secTimeout {
t.Errorf("The timeout has been changed when it should not have been!")
os.Exit(62)
}
clearCache()
}
// ============ End of Sanity Tests ============
// ============ Implementation Tests ============
func TestImplIndexFileTests(t *testing.T) {
secCap := 200
secTimeout := 2
capacity = secCap
timeout = secTimeout
workingDir = ""
launchCache()
// This is the filename which will be passed into the handler as a url.
name := "/"
// For this test, we expect the only change to the file name to be adding a dot in front of it since there is nothing else to replace.
expectedName := "." + name + "index.html"
// This is the data which that fake file will contain.
dataToBeRead := []byte("CS61C is the best class in the world! Emperor Nick shall reign supreme.")
// This is bad data which will be read if the filename is not correct.
badData := []byte("CS61C is the worst class ever!")
// We need to count the number of file reads we get.
var reads uint64 = 0
readName := ""
// We set the userlib FileRead function to this custom 'read'.
userlib.ReplaceReadFile(func(workingDir, filename string)(data []byte, err error){
// Increment the read counter
atomic.AddUint64(&reads, 1)
readName = filename
// If we get the expected name, we will return the correct data.
if filename == expectedName {
data = dataToBeRead
} else {
// Otherwise we return the bad data.
data = badData
}
return
})
resp := requestFile(name, secTimeout, t)
validateFileResponse(readName, expectedName, dataToBeRead, resp, userlib.SUCCESSCODE, t)
validateCacheSize(1, len(dataToBeRead), t)
name = "/best/class/ever/"
expectedName = "./best/class/ever/index.html"
resp = requestFile(name, secTimeout, t)
validateCacheSize(2, 2 * len(dataToBeRead), t)
validateFileResponse(readName, expectedName, dataToBeRead, resp, userlib.SUCCESSCODE, t)
name = "/best/class/ever"
expectedName = "./best/class/ever"
resp = requestFile(name, secTimeout, t)
validateFileResponse(readName, expectedName, dataToBeRead, resp, userlib.SUCCESSCODE, t)
validateNumberOfReads(3, reads, t)
if capacity != secCap {
t.Errorf("The max capacity has been changed when it should not have been!")
os.Exit(61)
}
if timeout != secTimeout {
t.Errorf("The timeout has been changed when it should not have been!")
os.Exit(62)
}
clearCache()
}
// ============ End of Implementation Tests ============
// ============ File String Sanitization Tests ============
func TestSanitizationDoubleSlash(t *testing.T) {
// We first need to define a capacity and timeout so our cache has some parameters.
secCap := 1000
secTimeout := 2
capacity = secCap
timeout = secTimeout
workingDir = ""
launchCache()
name := "//test.61c"
expected := "./test.61c"
// We need to set up a response writer which will be the dummy passed into the handler to make testing easier.
resp := genResponseTestWriter()
// We finally make the http request which the handler can understand.
req := genRequestUrl(name)
// We set the userlib FileRead function to this custom 'read'.
userlib.ReplaceReadFile(func(workingDir, filename string)(data []byte, err error){
if filename != expected {
t.Errorf("The filename does not match the expected file name. Expected (%s), Actual (%s)", expected, filename)
}
return
})
// We finally will call the handler. This is where we will get the data from the cache and or filesystem depending
// on if it is in the cache. It will be stored in the dummy Response Writer which was created above.
handler(resp, req)
resp = genResponseTestWriter()
name = "/file//test.61c"
req = genRequestUrl(name)
expected = "./file/test.61c"
handler(resp, req)
resp = genResponseTestWriter()
name = "//file//tool/test.61c"
req = genRequestUrl(name)
expected = "./file/tool/test.61c"
handler(resp, req)
if capacity != secCap {
t.Errorf("The max capacity has been changed when it should not have been!")
os.Exit(61)
}
if timeout != secTimeout {
t.Errorf("The timeout has been changed when it should not have been!")
os.Exit(62)
}
clearCache()
}
func TestSanitizationVSlashPattern(t *testing.T) {
// We first need to define a capacity and timeout so our cache has some parameters.
secCap := 1000
secTimeout := 2
capacity = secCap
timeout = secTimeout
workingDir = ""
launchCache()
name := "\\/Vtest.61c"
expected := "./Vtest.61c"
// We need to set up a response writer which will be the dummy passed into the handler to make testing easier.
resp := genResponseTestWriter()
// We finally make the http request which the handler can understand.
req := genRequestUrl(name)
// We set the userlib FileRead function to this custom 'read'.
userlib.ReplaceReadFile(func(workingDir, filename string)(data []byte, err error){
if filename != expected {
t.Errorf("The filename does not match the expected file name. Expected (%s), Actual (%s)", expected, filename)
}
return
})
// We finally will call the handler. This is where we will get the data from the cache and or filesystem depending
// on if it is in the cache. It will be stored in the dummy Response Writer which was created above.
handler(resp, req)
resp = genResponseTestWriter()
name = "/file\\/Vtest.61c"
req = genRequestUrl(name)
expected = "./file/Vtest.61c"
handler(resp, req)
resp = genResponseTestWriter()
name = "\\/file\\/tool/Vtest.61c"
req = genRequestUrl(name)
expected = "./file/tool/Vtest.61c"
handler(resp, req)
if capacity != secCap {
t.Errorf("The max capacity has been changed when it should not have been!")
os.Exit(61)
}
if timeout != secTimeout {
t.Errorf("The timeout has been changed when it should not have been!")
os.Exit(62)
}
clearCache()
}
func TestSanitizationPreviousDirectory(t *testing.T) {
// We first need to define a capacity and timeout so our cache has some parameters.
secCap := 1000
secTimeout := 2
capacity = secCap
timeout = secTimeout
workingDir = ""
launchCache()
name := "/../Ptest.61c"
expected := "./Ptest.61c"
// We need to set up a response writer which will be the dummy passed into the handler to make testing easier.
resp := genResponseTestWriter()
// We finally make the http request which the handler can understand.
req := genRequestUrl(name)
// We set the userlib FileRead function to this custom 'read'.
userlib.ReplaceReadFile(func(workingDir, filename string)(data []byte, err error){
if filename != expected {
t.Errorf("The filename does not match the expected file name. Expected (%s), Actual (%s)", expected, filename)
}
return
})
// We finally will call the handler. This is where we will get the data from the cache and or filesystem depending
// on if it is in the cache. It will be stored in the dummy Response Writer which was created above.
handler(resp, req)
resp = genResponseTestWriter()
name = "/file/../Ptest.61c"
req = genRequestUrl(name)
expected = "./file/Ptest.61c"
handler(resp, req)
resp = genResponseTestWriter()
name = "/../file/../tool/Ptest.61c"
req = genRequestUrl(name)
expected = "./file/tool/Ptest.61c"
handler(resp, req)
resp = genResponseTestWriter()
if capacity != secCap {
t.Errorf("The max capacity has been changed when it should not have been!")
os.Exit(61)
}
if timeout != secTimeout {
t.Errorf("The timeout has been changed when it should not have been!")
os.Exit(62)
}
clearCache()
}
func TestSanitizationSimpleCombinations(t *testing.T) {
// We first need to define a capacity and timeout so our cache has some parameters.
secCap := 1000
secTimeout := 2
capacity = secCap
timeout = secTimeout
workingDir = ""
launchCache()
name := "//../SCtest.61c"
expected := "./SCtest.61c"
// We need to set up a response writer which will be the dummy passed into the handler to make testing easier.
resp := genResponseTestWriter()
// We finally make the http request which the handler can understand.
req := genRequestUrl(name)
// We set the userlib FileRead function to this custom 'read'.
userlib.ReplaceReadFile(func(workingDir, filename string)(data []byte, err error){
if filename != expected {
t.Errorf("The filename does not match the expected file name. Expected (%s), Actual (%s)", expected, filename)
}
return
})
// We finally will call the handler. This is where we will get the data from the cache and or filesystem depending
// on if it is in the cache. It will be stored in the dummy Response Writer which was created above.
handler(resp, req)
resp = genResponseTestWriter()
name = "//file/../SCtest.61c"
req = genRequestUrl(name)
expected = "./file/SCtest.61c"
handler(resp, req)
resp = genResponseTestWriter()
name = "/../file\\//../tool/SCtest.61c"
req = genRequestUrl(name)
expected = "./file/tool/SCtest.61c"
handler(resp, req)
resp = genResponseTestWriter()
name = "/..//..///../file/..//..//..///../\\//..//..//../exams//\\/SCtest.61c"
req = genRequestUrl(name)
expected = "./file/exams/SCtest.61c"
handler(resp, req)
if capacity != secCap {
t.Errorf("The max capacity has been changed when it should not have been!")
os.Exit(61)
}
if timeout != secTimeout {
t.Errorf("The timeout has been changed when it should not have been!")
os.Exit(62)
}
clearCache()
}
func TestSanitizationSimpleSameEndFile(t *testing.T) {
// We first need to define a capacity and timeout so our cache has some parameters.
secCap := 1000
secTimeout := 2
capacity = secCap
timeout = secTimeout
workingDir = ""
launchCache()
name := "//../test.61c"
expected := "./test.61c"
// We need to set up a response writer which will be the dummy passed into the handler to make testing easier.
resp := genResponseTestWriter()
// We finally make the http request which the handler can understand.
req := genRequestUrl(name)
shouldReadFile := true
// We set the userlib FileRead function to this custom 'read'.
userlib.ReplaceReadFile(func(workingDir, filename string)(data []byte, err error){
if filename != expected {
t.Errorf("The filename does not match the expected file name. Expected (%s), Actual (%s)", expected, filename)
}
if shouldReadFile == false {
t.Errorf("The filename which should have been the same was not cached!")
}
return
})
// We finally will call the handler. This is where we will get the data from the cache and or filesystem depending
// on if it is in the cache. It will be stored in the dummy Response Writer which was created above.
handler(resp, req)
shouldReadFile = false
resp = genResponseTestWriter()
name = "//../../test.61c"
req = genRequestUrl(name)
expected = "./test.61c"
handler(resp, req)
resp = genResponseTestWriter()
name = "/../\\//..//test.61c"
req = genRequestUrl(name)
expected = "./test.61c"
handler(resp, req)
resp = genResponseTestWriter()
name = "/..//..///../\\/..//..//..///../\\//..//..//..///\\/test.61c"
req = genRequestUrl(name)
expected = "./test.61c"
handler(resp, req)
if capacity != secCap {
t.Errorf("The max capacity has been changed when it should not have been!")
os.Exit(61)
}
if timeout != secTimeout {
t.Errorf("The timeout has been changed when it should not have been!")
os.Exit(62)
}
clearCache()
}
func TestSanitizationLongReplace(t *testing.T) {
// We first need to define a capacity and timeout so our cache has some parameters.
secCap := 1000
secTimeout := 2
capacity = secCap
timeout = secTimeout
workingDir = ""
launchCache()
name := "test.61c"
name = strings.Repeat("\\", 200000) + "/" + name
expected := "./test.61c"
//expected := "./" + strings.Repeat("dir/", int(math.Floor(float64(times) / float64(len(comb))))) + "test.61c"
// We need to set up a response writer which will be the dummy passed into the handler to make testing easier.
resp := genResponseTestWriter()
// We finally make the http request which the handler can understand.
req := genRequestUrl(name)
shouldReadFile := true
// We set the userlib FileRead function to this custom 'read'.
userlib.ReplaceReadFile(func(workingDir, filename string)(data []byte, err error){
if filename != expected {
t.Errorf("The filename does not match the expected file name. Expected (%s), Actual (%s)", expected, filename)
}
if shouldReadFile == false {
t.Errorf("The filename which should have been the same was not cached!")
}
return
})
// We finally will call the handler. This is where we will get the data from the cache and or filesystem depending
// on if it is in the cache. It will be stored in the dummy Response Writer which was created above.
handler(resp, req)
if capacity != secCap {
t.Errorf("The max capacity has been changed when it should not have been!")
os.Exit(61)
}
if timeout != secTimeout {
t.Errorf("The timeout has been changed when it should not have been!")
os.Exit(62)
}
clearCache()
}
func TestSanitizationComplexCombinations(t *testing.T) {
// We first need to define a capacity and timeout so our cache has some parameters.
secCap := 1000
secTimeout := 2
capacity = secCap
timeout = secTimeout
workingDir = ""
launchCache()
name := "//../cCtest.61c"
expected := "./cCtest.61c"
// We need to set up a response writer which will be the dummy passed into the handler to make testing easier.
resp := genResponseTestWriter()
// We finally make the http request which the handler can understand.
req := genRequestUrl(name)
// We set the userlib FileRead function to this custom 'read'.
userlib.ReplaceReadFile(func(workingDir, filename string)(data []byte, err error){
if filename != expected {
t.Errorf("The filename does not match the expected file name. Expected (%s), Actual (%s)", expected, filename)
}
return
})
// We finally will call the handler. This is where we will get the data from the cache and or filesystem depending
// on if it is in the cache. It will be stored in the dummy Response Writer which was created above.
handler(resp, req)
resp = genResponseTestWriter()
name = "//file/..//cCtest.61c"
req = genRequestUrl(name)
expected = "./file/cCtest.61c"
handler(resp, req)
resp = genResponseTestWriter()
name = "\\/../file\\/../tool/cCtest.61c"
req = genRequestUrl(name)
expected = "./file/tool/cCtest.61c"
handler(resp, req)
resp = genResponseTestWriter()
name = "/../..//../file/..\\\\\\\\//../..//\\//../\\/../../..\\//..\\//..\\//..\\//..\\//..\\/exams//\\/cCtest.61c"
req = genRequestUrl(name)
expected = "./file/exams/cCtest.61c"
handler(resp, req)
if capacity != secCap {
t.Errorf("The max capacity has been changed when it should not have been!")
os.Exit(61)
}
if timeout != secTimeout {
t.Errorf("The timeout has been changed when it should not have been!")
os.Exit(62)
}
clearCache()
}
// ============ End of File String Sanitization Tests ============
// ============ Timeout Tests ============
func TestTimeoutSimple(t *testing.T) {
// We first need to define a capacity and timeout so our cache has some parameters.
secCap := 1000
secTimeout := 2
capacity = secCap
timeout = secTimeout
workingDir = ""
launchCache()
badname := "/badfile.61c"
goodname := "/goodfile.61c"
gooddata := []byte("I am some really good data that is fun to watch and good to know!")
// We need to set up a response writer which will be the dummy passed into the handler to make testing easier.
resp := genResponseTestWriter()
// We finally make the http request which the handler can understand.
req := genRequestUrl(badname)
// We set the userlib FileRead function to this custom 'read'.
userlib.ReplaceReadFile(func(workingDir, filename string)(data []byte, err error){
if filename == ("." + goodname) {
data = gooddata
} else {
// Inf loop.
for ;filename != filename + "hahaha"; {}
}
return
})
c := make(chan bool)
go func (chan bool) {
handler(resp, req)
c <- true
}(c)
select {
case <- c: // This means we did not time out.
case <- time.After(time.Duration(secTimeout + 1) * time.Second):
t.Errorf("The handler took too long to respond!")
}
validateTimeout(resp, t)
validateCacheSize(0, 0, t)
goodreq := genRequestUrl(goodname)
goodresp := genResponseTestWriter()
handler(goodresp, goodreq)
validateFileResponse("", "", gooddata, goodresp, userlib.SUCCESSCODE, t)
if capacity != secCap {
t.Errorf("The max capacity has been changed when it should not have been!")
os.Exit(61)
}
if timeout != secTimeout {
t.Errorf("The timeout has been changed when it should not have been!")
os.Exit(62)
}
clearCache()
}
func TestTimeoutWithResponse(t *testing.T) {
// We first need to define a capacity and timeout so our cache has some parameters.
secCap := 1000
secTimeout := 2
capacity = secCap
timeout = secTimeout
workingDir = ""
launchCache()
goodname := "/goodfile.61c"
gooddata := []byte("I am some really good data that is fun to watch and good to know!")
var reads uint64 = 0
// We set the userlib FileRead function to this custom 'read'.
userlib.ReplaceReadFile(func(workingDir, filename string)(data []byte, err error) {
// Increment the read counter
atomic.AddUint64(&reads, 1)
time.Sleep(time.Duration(timeout * 2) * time.Second)
data = gooddata
return
})
// We need to set up a response writer which will be the dummy passed into the handler to make testing easier.
resp := requestFile(goodname, secTimeout, t)
validateTimeout(resp, t)
validateCacheSize(0, 0, t)
time.Sleep(time.Duration(timeout) * time.Second + time.Millisecond * time.Duration(250))
validateCacheSize(1, len(gooddata), t)
resp2 := requestFile(goodname, secTimeout, t)
validateFileResponse("", "", gooddata, resp2, userlib.SUCCESSCODE, t)
validateCacheSize(1, len(gooddata), t)
validateNumberOfReads(1, reads, t)
if capacity != secCap {
t.Errorf("The max capacity has been changed when it should not have been!")