File: Tests.hs

package info (click to toggle)
haskell-snap-core 1.0.4.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 788 kB
  • sloc: haskell: 7,612; sh: 47; ansic: 23; makefile: 2
file content (1199 lines) | stat: -rwxr-xr-x 40,918 bytes parent folder | download | duplicates (4)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
{-# LANGUAGE BangPatterns        #-}
{-# LANGUAGE DeriveDataTypeable  #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Snap.Util.FileUploads.Tests
  ( tests ) where

------------------------------------------------------------------------------
import           Control.Applicative            (Alternative ((<|>)), (<$>))
import           Control.DeepSeq                (deepseq)
import           Control.Exception              (ErrorCall (..), evaluate, throwIO)
import           Control.Exception.Lifted       (Exception (fromException, toException), catch, finally, throw)
import           Control.Monad                  (Monad (return, (>>), (>>=)), liftM, void)
import           Control.Monad.IO.Class         (MonadIO (liftIO))
import           Data.ByteString                (ByteString)
import qualified Data.ByteString.Char8          as S
import qualified Data.ByteString.Lazy           as L
import           Data.IORef                     (atomicModifyIORef, newIORef, readIORef, writeIORef)
import           Data.List                      (foldl', length)
import qualified Data.Map                       as Map
import           Data.Maybe                     (Maybe (..), fromJust, maybe)
import qualified Data.Text                      as T
import           Data.Typeable                  (Typeable)
import           Prelude                        (Bool (..), Either (..), Eq (..), FilePath, IO, Int, Num (..), Show (..), const, either, error, filter, map, seq, snd, ($), ($!), (&&), (++), (.))
import           Snap.Internal.Core             (EscapeSnap (TerminateConnection), Snap, getParam, getPostParam, getQueryParam, runSnap)
import           Snap.Internal.Http.Types       (Request (rqBody), Response, setHeader)
import           Snap.Internal.Util.FileUploads (BadPartException (..), FileUploadException (..), FormFile (..), PartDisposition (..), PartInfo (..), PolicyViolationException (..), allowWithMaximumSize, defaultFileUploadPolicy, defaultUploadPolicy, disallow, doProcessFormInputs, fileUploadExceptionReason, foldMultipart, getMaximumNumberOfFormInputs, getMinimumUploadRate, getMinimumUploadSeconds, getUploadTimeout, handleFileUploads, handleFileUploads, handleFormUploads, setMaximumFileSize, setMaximumFormInputSize, setMaximumNumberOfFiles, setMaximumNumberOfFormInputs, setMaximumSkippedFileSize, setMinimumUploadRate, setMinimumUploadSeconds, setProcessFormInputs, setSkipFilesWithoutNames, setUploadTimeout, storeAsLazyByteString, toPartDisposition, withTemporaryStore)
import qualified Snap.Test                      as Test
import           Snap.Test.Common               (coverEqInstance, coverShowInstance, coverTypeableInstance, eatException, expectExceptionH, seconds, waitabit)
import qualified Snap.Types.Headers             as H
import           System.Directory               (createDirectoryIfMissing, doesFileExist, getDirectoryContents, removeDirectoryRecursive, removeFile)
import           System.IO.Streams              (RateTooSlowException)
import qualified System.IO.Streams              as Streams
import           System.Mem                     (performGC)
import           System.Timeout                 (timeout)
import           Test.Framework                 (Test)
import           Test.Framework.Providers.HUnit (testCase)
import           Test.HUnit                     (Assertion, assertBool, assertEqual, assertFailure)
------------------------------------------------------------------------------


------------------------------------------------------------------------------
data TestException = TestException
  deriving (Show, Typeable)

instance Exception TestException

------------------------------------------------------------------------------
tests :: [Test]
tests = [ testFoldMultipart1
        , testFoldMultipart2
        , testFilePolicyViolation1
        , testFilePolicyViolation2
        , testEmptyNamePolicyViolation
        , testEmptyNameStore
        , testEmptyNameSkip
        , testTemporaryStore
        , testTemporaryStoreSafeMove
        , testSuccess1
        , testSuccess2
        , testSuccessUtf8Filename
        , testBadParses
        , testPerPartPolicyViolation1
        , testPerPartPolicyViolation2
        , testFormInputsPolicyViolation
        , testFormSizePolicyViolation
        , testNoFileName
        , testNoFileNameTooBig
        , testTooManyHeaders
        , testNoBoundary
        , testNoMixedBoundary
        , testWrongContentType
        , testSlowEnumerator
        , testSlowEnumerator2
        , testAbortedBody
        , testTrivials
        , testDisconnectionCleanup
        ]

------------------------------------------------------------------------------
testFoldMultipart1 :: Test
testFoldMultipart1 = testCase "fileUploads/fold1" $
     void $ go hndl mixedTestBody

  where
    hndl :: Snap ()
    hndl = do
        (params, files) <- foldMultipart defaultUploadPolicy  hndl' []

        let fileMap = foldl' f Map.empty files
        liftIO $ assertEqual "2 params returned" 2 (length params)
        let [p1, p2] = params

        liftIO $ do
            let Just (a1, a2, a3) = Map.lookup "file1.txt" fileMap
            let Just (b1, b2, b3) = Map.lookup "file2.gif" fileMap
            assertEqual "file1 contents"
                        ("text/plain", file1Contents)
                        (a1, a2)
            assertEqual "file1 header 1"
                        (Just "text/plain")
                        (H.lookup "content-type" a3)
            assertEqual "file1 header 2"
                        (Just "attachment; filename=\"file1.txt\"")
                        (H.lookup "content-disposition" a3)

            assertEqual "file2 contents"
                        ("image/gif", file2Contents)
                        (b1, b2)
            assertEqual "file2 header 1"
                        (Just "image/gif")
                        (H.lookup "content-type" b3)
            assertEqual "file2 header 2"
                        (Just "attachment; filename=\"file2.gif\"")
                        (H.lookup "content-disposition" b3)

            assertEqual "field1 contents"
                        ("field1", formContents1)
                        p1

            assertEqual "field2 contents"
                        ("field2", formContents2)
                        p2

    f mp (fn, ct, x, hdrs) = Map.insert fn (ct,x,hdrs) mp

    hndl' partInfo istream acc = do
       let
         fn = fromJust $ partFileName partInfo
         ct = partContentType partInfo
         hdrs = partHeaders partInfo
       body <- S.concat <$> Streams.toList istream
       return (acc ++ [(fn, ct, body, hdrs)])



------------------------------------------------------------------------------
testFoldMultipart2 :: Test
testFoldMultipart2 = testCase "fileUploads/fold2" $
    void $ go hndl mixedTestBody
  where
    policy = setProcessFormInputs False defaultUploadPolicy

    hndl = do
        (fields, fileCount) <- foldMultipart policy hndl' (0::Int)

        liftIO $ do
             assertEqual "num params" 4 fileCount
             assertEqual "num processed" 0 (length fields)

    hndl' !_ !_ !acc = return $ acc + 1



------------------------------------------------------------------------------
testFilePolicyViolation1 :: Test
testFilePolicyViolation1 = testCase "fileUploads/filePolicyViolation1" $
     assertThrows (go hndl mixedTestBody) h
  where
    h e = assertIsFileSizeException e

    hndl = handleFormUploads defaultUploadPolicy
             (setMaximumFileSize 0 defaultFileUploadPolicy)
             (const storeAsLazyByteString)



------------------------------------------------------------------------------
testFilePolicyViolation2 :: Test
testFilePolicyViolation2 = testCase "fileUploads/filePolicyViolation2" $
     assertThrows (go hndl mixedTestBody) h
  where
    h (PolicyViolationException r) =
        assertBool "correct exception"
                   (T.isInfixOf "number of files exceeded the maximum" r)

    hndl = handleFormUploads defaultUploadPolicy
             (setMaximumNumberOfFiles 0 defaultFileUploadPolicy)
             (const storeAsLazyByteString)


------------------------------------------------------------------------------
testEmptyNamePolicyViolation :: Test
testEmptyNamePolicyViolation = testCase "fileUploads/emptyNamePolicyViolation" $
     assertThrows (go hndl noFileNameTestBody) h
  where
    h e = assertIsFileSizeException e

    hndl = handleFormUploads defaultUploadPolicy
             (setSkipFilesWithoutNames True defaultFileUploadPolicy)
             (const storeAsLazyByteString)


------------------------------------------------------------------------------
assertIsFileSizeException :: PolicyViolationException -> Assertion
assertIsFileSizeException (PolicyViolationException r) =
    assertBool "file size exception"
        (T.isInfixOf "File" r &&
          T.isInfixOf "exceeded maximum allowable size" r)


------------------------------------------------------------------------------
testEmptyNameStore :: Test
testEmptyNameStore = testCase "fileUploads/emptyNameStore" $
     void $ go hndl noFileNameTestBody
  where
    hndl = do
      (inputs, files) <- handleFormUploads defaultUploadPolicy
                         (setSkipFilesWithoutNames False defaultFileUploadPolicy)
                         (const storeAsLazyByteString)
      liftIO $ do
         assertEqual "got both files" 2 (length files)
         let [f1, f2] = files
         assertEqual "file1 contents"
                     (FormFile "files" $ L.fromChunks [file1Contents])
                     f1
         assertEqual "file2 contents"
                     (FormFile "files" $ L.fromChunks [file2Contents])
                     f2
         assertEqual "inputs present" 2 (length inputs)
      return ()


------------------------------------------------------------------------------
testEmptyNameSkip :: Test
testEmptyNameSkip = testCase "fileUploads/emptyNameSkip" $
     void $ go hndl noFileNameTestBody
  where
    hndl = do
      (inputs, files) <- handleFormUploads defaultUploadPolicy
                         (  setMaximumSkippedFileSize 4000
                          . setSkipFilesWithoutNames True
                          $ defaultFileUploadPolicy )
                         (const storeAsLazyByteString)
      liftIO $ do
         assertEqual "files skipped" 0 (length files)
         assertEqual "inputs present" 2 (length inputs)
      return ()


------------------------------------------------------------------------------
testTemporaryStore :: Test
testTemporaryStore = testCase "fileUploads/temporaryStore" $
     harness "tempdir1" hndl mixedTestBody
  where
    hndl = do
      (fn1, fn2) <- withTemporaryStore "tempdir1" "upload" $ \store -> do
          (inputs, files) <- handleFormUploads defaultUploadPolicy
                                               defaultFileUploadPolicy
                                               (const store)
          liftIO $ do
             assertEqual "num files" 2 (length files)
             assertEqual "inputs present" 2 (length inputs)
             let [FormFile name1 fn1, FormFile name2 fn2] = files
             fc1 <- liftIO $ S.readFile fn1
             fc2 <- liftIO $ S.readFile fn2

             assertEqual "file1 content"
                         ("files", file1Contents)
                         (name1, fc1)

             assertEqual "file2 content"
                         ("files", file2Contents)
                         (name2, fc2)
             return (fn1, fn2)
      liftIO $ do
        ex1 <- doesFileExist fn1
        ex2 <- doesFileExist fn2
        assertEqual "file1 deleted" False ex1
        assertEqual "file2 deleted" False ex2


------------------------------------------------------------------------------
testTemporaryStoreSafeMove :: Test
testTemporaryStoreSafeMove = testCase "fileUploads/temporaryStoreSafeMove" $
     harness "tempdir1" hndl mixedTestBody
  where
    hndl = do
      -- should not throw
      withTemporaryStore "tempdir1" "upload" $ \store -> do
          (_, files) <- handleFormUploads defaultUploadPolicy
                                               defaultFileUploadPolicy
                                               (const store)
          liftIO $ do
             assertEqual "num files" 2 (length files)
             let [FormFile _ fn1, FormFile _ fn2] = files
             removeFile fn1
             removeFile fn2



------------------------------------------------------------------------------
testSuccess1 :: Test
testSuccess1 = testCase "fileUploads/success1" $
               harness tmpdir hndl mixedTestBody

  where
    tmpdir = "tempdir1"

    hndl = do
        xs <- handleFileUploads tmpdir
                                defaultUploadPolicy
                                (const $ allowWithMaximumSize 300000)
                                hndl'

        let fileMap = foldl' f Map.empty xs
        p1  <- getParam "field1"
        p1P <- getPostParam "field1"
        p1Q <- getQueryParam "field1"
        p2  <- getParam "field2"

        liftIO $ do
            let Just (a1, a2, a3) = Map.lookup "file1.txt" fileMap
            let Just (b1, b2, b3) = Map.lookup "file2.gif" fileMap
            assertEqual "file1 contents"
                        ("text/plain", file1Contents)
                        (a1, a2)
            assertEqual "file1 header 1"
                        (Just "text/plain")
                        (H.lookup "content-type" a3)
            assertEqual "file1 header 2"
                        (Just "attachment; filename=\"file1.txt\"")
                        (H.lookup "content-disposition" a3)

            assertEqual "file2 contents"
                        ("image/gif", file2Contents)
                        (b1, b2)
            assertEqual "file2 header 1"
                        (Just "image/gif")
                        (H.lookup "content-type" b3)
            assertEqual "file2 header 2"
                        (Just "attachment; filename=\"file2.gif\"")
                        (H.lookup "content-disposition" b3)

            assertEqual "field1 contents"
                        (Just formContents1)
                        p1

            assertEqual "field1 POST contents" (Just formContents1) p1P
            assertEqual "field1 query contents" Nothing p1Q
            assertEqual "field2 contents" (Just formContents2) p2

    f mp (fn, ct, x, hdrs) = Map.insert fn (ct,x,hdrs) mp

    hndl' partInfo =
        either throw
               (\fp -> do
                    x <- liftIO $ S.readFile fp
                    let fn = fromJust $ partFileName partInfo
                    let ct = partContentType partInfo
                    let hdrs = partHeaders partInfo
                    return (fn, ct, x, hdrs))


------------------------------------------------------------------------------
testSuccess2 :: Test
testSuccess2 = testCase "fileUploads/success2" $
               harness tmpdir hndl mixedTestBody

  where
    tmpdir = "tempdir2"

    policy = setProcessFormInputs False defaultUploadPolicy

    hndl = do
        ref <- liftIO $ newIORef (0::Int)
        _ <- handleFileUploads tmpdir
                               policy
                               (const $ allowWithMaximumSize 300000)
                               (hndl' ref)

        n <- liftIO $ readIORef ref
        liftIO $ assertEqual "num params" 4 n

    hndl' !ref !_ !_ = atomicModifyIORef ref (\x -> (x+1, ()))

 ------------------------------------------------------------------------------
testSuccessUtf8Filename :: Test
testSuccessUtf8Filename = testCase "fileUploads/utf8-filename" $
                          harness tmpdir hndl utf8FilenameBody

  where
    tmpdir = "tempdir3"

    hndl = do
        xs <- handleFileUploads tmpdir
                                defaultUploadPolicy
                                (const $ allowWithMaximumSize 300000)
                                hndl'

        liftIO $ assertEqual "filename" [filenameUtf8] xs

    hndl' pinfo _ = return $ fromJust $ partFileName pinfo


------------------------------------------------------------------------------
testBadParses :: Test
testBadParses = testCase "fileUploads/badParses" $ do
                harness tmpdir hndl mixedTestBodyWithBadTypes
  where
    tmpdir = "tempdir_bad_types"

    hndl = do
        xs <- handleFileUploads tmpdir
                                defaultUploadPolicy
                                (const $ allowWithMaximumSize 300000)
                                hndl'

        let fileMap = foldl' f Map.empty xs
        p1   <- getParam "field1"
        p1P  <- getPostParam "field1"
        p1Q  <- getQueryParam "field1"
        p2   <- getParam "field2"
        pBoo <- getParam "boo"

        liftIO $ do
            assertEqual "file1 contents"
                        (Just ("text/plain", file1Contents))
                        (Map.lookup "file1.txt" fileMap)

            assertEqual "file2 contents"
                        (Just ("text/plain", file2Contents))
                        (Map.lookup "file2.gif" fileMap)

            assertEqual "field1 param contents" (Just formContents1) p1
            assertEqual "field1 POST contents" (Just formContents1) p1P
            assertEqual "field1 query contents" Nothing p1Q
            assertEqual "field2 contents" Nothing p2
            assertEqual "boo contents" (Just "boo") pBoo

    f mp (fn, ct, x) = Map.insert fn (ct,x) mp

    hndl' partInfo =
        either throw
               (\fp -> do
                    x <- liftIO $ S.readFile fp
                    let fn = fromJust $ partFileName partInfo
                    let ct = partContentType partInfo
                    return (fn, ct, x))



------------------------------------------------------------------------------
testPerPartPolicyViolation1 :: Test
testPerPartPolicyViolation1 = testCase "fileUploads/perPartPolicyViolation1" $
                              harness tmpdir hndl mixedTestBody
  where
    tmpdir = "tempdir_pol1"

    hndl = do
        _ <- handleFileUploads tmpdir defaultUploadPolicy
                               (const disallow)
                               hndl'

        p1 <- getParam "field1"
        p2 <- getParam "field2"


        liftIO $ do
            assertEqual "field1 contents"
                        (Just formContents1)
                        p1

            assertEqual "field2 contents"
                        (Just formContents2)
                        p2

    hndl' !_ e = either (\i -> show i `deepseq` return $! ())
                        (const $ error "expected policy violation")
                        e


------------------------------------------------------------------------------
testPerPartPolicyViolation2 :: Test
testPerPartPolicyViolation2 = testCase "fileUploads/perPartPolicyViolation2" $
                              harness tmpdir hndl mixedTestBody
  where
    tmpdir = "tempdir_pol2"

    hndl = handleFileUploads tmpdir defaultUploadPolicy
                             (const $ allowWithMaximumSize 4)
                             hndl'

    hndl' partInfo e = (if partFileName partInfo == Just "file1.txt"
                          then ePass
                          else eFail) e

    eFail = either (\i -> show i `deepseq` return ())
                   (const $ error "expected policy violation")

    ePass = either (throw)
                   (\i -> show i `deepseq` return ())



------------------------------------------------------------------------------
testNoFileName :: Test
testNoFileName = testCase "fileUploads/noFileName" $
                 (harness tmpdir hndl noFileNameTestBody)
  where
    tmpdir = "tempdir_noname"

    hndl = handleFileUploads tmpdir defaultUploadPolicy
                             (const $ allowWithMaximumSize 400000)
                             hndl'

    hndl' pinfo !_ = do
        assertEqual "filename" Nothing $ partFileName pinfo
        assertEqual "disposition" DispositionFile $ partDisposition pinfo


------------------------------------------------------------------------------
testNoFileNameTooBig :: Test
testNoFileNameTooBig = testCase "fileUploads/noFileNameTooBig" $
                       assertThrows (harness tmpdir hndl noFileNameTestBody) h
  where
    h !(e :: FileUploadException) = do
        let r = fileUploadExceptionReason e
        assertBool "correct exception"
                   (T.isInfixOf "File" r &&
                    T.isInfixOf "exceeded maximum allowable size" r)

    tmpdir = "tempdir_noname_toobig"

    hndl = handleFileUploads tmpdir defaultUploadPolicy
                             (const $ allowWithMaximumSize 1)
                             hndl'

    hndl' pinfo !e = do
        let (Left !x) = e
        coverShowInstance x
        assertEqual "filename" Nothing $ partFileName pinfo
        assertEqual "disposition" DispositionFile $ partDisposition pinfo
        throwIO x


------------------------------------------------------------------------------
testFormSizePolicyViolation :: Test
testFormSizePolicyViolation =
    testCase "fileUploads/formSizePolicy" $
    assertThrows (harness tmpdir hndl mixedTestBody) h
  where
    h !(e :: FileUploadException) = do
        let r = fileUploadExceptionReason e
        assertBool "correct exception"
                   (T.isInfixOf "form input" r &&
                    T.isInfixOf "exceeded maximum permissible" r)

    tmpdir = "tempdir_formpol"

    policy = setMaximumFormInputSize 2 defaultUploadPolicy

    hndl = handleFileUploads tmpdir policy
                             (const $ allowWithMaximumSize 4)
                             hndl'

    hndl' xs _ = show xs `deepseq` return ()


------------------------------------------------------------------------------
testFormInputsPolicyViolation :: Test
testFormInputsPolicyViolation =
    testCase "fileUploads/formInputsPolicy" $
    assertThrows (harness tmpdir hndl mixedTestBody) h
  where
    h !(e :: FileUploadException) = do
        let r = fileUploadExceptionReason e
        assertBool "correct exception"
                   (T.isInfixOf "number of form inputs" r &&
                    T.isInfixOf "exceeded maximum" r)

    tmpdir = "tempdir_formpol2"

    policy = setMaximumNumberOfFormInputs 0 defaultUploadPolicy

    hndl = handleFileUploads tmpdir policy
                             (\x -> x `seq` allowWithMaximumSize 4000)
                             hndl'

    hndl' xs _ = show xs `deepseq` return ()


------------------------------------------------------------------------------
testNoBoundary :: Test
testNoBoundary = testCase "fileUploads/noBoundary" $
                 expectExceptionH $
                 harness' goBadContentType tmpdir hndl mixedTestBody
  where
    tmpdir = "tempdir_noboundary"

    hndl = handleFileUploads tmpdir
                             defaultUploadPolicy
                             (const $ allowWithMaximumSize 300000)
                             hndl'

    hndl' xs _ = show xs `deepseq` return ()


------------------------------------------------------------------------------
testNoMixedBoundary :: Test
testNoMixedBoundary = testCase "fileUploads/noMixedBoundary" $
                      expectExceptionH $
                      harness' go tmpdir hndl badMixedBody
  where
    tmpdir = "tempdir_mixednoboundary"

    hndl = handleFileUploads tmpdir
                             defaultUploadPolicy
                             (const $ allowWithMaximumSize 300000)
                             hndl'

    hndl' xs _ = show xs `deepseq` return ()


------------------------------------------------------------------------------
testWrongContentType :: Test
testWrongContentType = testCase "fileUploads/wrongContentType" $
                       expectExceptionH $
                       harness' goWrongContentType tmpdir hndl mixedTestBody
  where
    tmpdir = "tempdir_noboundary"

    hndl = handleFileUploads tmpdir
                             defaultUploadPolicy
                             (const $ allowWithMaximumSize 300000)
                             hndl'
           <|> error "expect fail here"

    hndl' xs _ = show xs `deepseq` return ()


------------------------------------------------------------------------------
testTooManyHeaders :: Test
testTooManyHeaders = testCase "fileUploads/tooManyHeaders" $
                     assertThrows (harness tmpdir hndl bigHeadersBody) h
  where
    h (e :: BadPartException) = show e `deepseq` return ()

    tmpdir = "tempdir_tooManyHeaders"

    hndl = handleFileUploads tmpdir defaultUploadPolicy
                             (const $ allowWithMaximumSize 4)
                             hndl'

    hndl' xs _ = show xs `deepseq` return ()


------------------------------------------------------------------------------
testAbortedBody :: Test
testAbortedBody = testCase "fileUploads/abortedBody" $
                  expectExceptionH $
                  harness' goAndAbort tmpdir hndl abortedTestBody
  where
    tmpdir = "tempdir_abort"

    hndl = handleFileUploads tmpdir defaultUploadPolicy
                             (const $ allowWithMaximumSize 400000)
                             hndl'

    hndl' xs _ = show xs `deepseq` return ()



------------------------------------------------------------------------------
testSlowEnumerator :: Test
testSlowEnumerator =
    testCase "fileUploads/tooSlow" $
    assertThrows (harness' goSlowEnumerator tmpdir hndl mixedTestBody) h0
  where
    h0 (e :: EscapeSnap) = do
        let (TerminateConnection se) = e
            (me :: Maybe RateTooSlowException) = fromException se
        maybe (throw e) h me

    h (e :: RateTooSlowException) = coverShowInstance e

    tmpdir = "tempdir_tooslow"

    policy = setMinimumUploadRate 200000 $
             setMinimumUploadSeconds 2 $
             defaultUploadPolicy

    hndl = handleFileUploads tmpdir policy
                             (const $ allowWithMaximumSize 400000)
                             hndl'

    hndl' xs _ = show xs `deepseq` return ()


------------------------------------------------------------------------------
testSlowEnumerator2 :: Test
testSlowEnumerator2 =
    testCase "fileUploads/tooSlow2" $
    assertThrows (harness' goSlowEnumerator tmpdir hndl mixedTestBody) h0
  where
    h0 (e :: EscapeSnap) = do
        let (TerminateConnection se) = e
            (me :: Maybe RateTooSlowException) = fromException se
        maybe (throw e) h me

    h (e :: RateTooSlowException) = e `seq` return ()

    tmpdir = "tempdir_tooslow2"

    policy = setUploadTimeout 2 defaultUploadPolicy

    hndl = handleFileUploads tmpdir policy
                             (const $ allowWithMaximumSize 400000)
                             hndl'

    hndl' xs _ = show xs `deepseq` return ()


------------------------------------------------------------------------------
testTrivials :: Test
testTrivials = testCase "fileUploads/trivials" $ do
    assertEqual "" False $ doProcessFormInputs policy
    assertEqual "" 1000  $ getMinimumUploadRate policy
    assertEqual "" 1000  $ getMinimumUploadRate defaultUploadPolicy
    assertEqual "" 5     $ getMinimumUploadSeconds policy
    assertEqual "" 9     $ getUploadTimeout policy

    let pvi = PolicyViolationException ""
    coverTypeableInstance pvi
    evaluate $ ((fromJust $
                 fromException (toException pvi)) :: PolicyViolationException)
    evaluate $ ((fromJust $
                 fromException (toException pvi)) :: FileUploadException)
    let !_ = policyViolationExceptionReason pvi

    let bpi = BadPartException ""
    coverTypeableInstance bpi
    let !_ = badPartExceptionReason bpi

    coverShowInstance $ WrappedFileUploadException $ BadPartException ""
    coverShowInstance $ PartInfo "" Nothing "" DispositionFile (H.empty)
    coverShowInstance $ toPartDisposition ""
    coverEqInstance $ DispositionOther ""

    let !gfui = WrappedFileUploadException $ BadPartException ""
    evaluate $ fileUploadExceptionReason gfui

    void $ evaluate
         $ getMaximumNumberOfFormInputs
         $ setMaximumNumberOfFormInputs 2 policy

  where
    policy = setProcessFormInputs False $
             setMinimumUploadRate 1000 $
             setMinimumUploadSeconds 5 $
             setUploadTimeout 9 $
             defaultUploadPolicy


------------------------------------------------------------------------------
testDisconnectionCleanup :: Test
testDisconnectionCleanup = testCase "fileUploads/disconnectionCleanup" $ do
    runTest `finally` removeDirectoryRecursive tmpdir
  where
    runTest = do
        eatException $ removeDirectoryRecursive tmpdir
        createDirectoryIfMissing True tmpdir
        rq <- mkDamagedRequest mixedTestBody
        eatException $ liftM snd (runIt hndl rq)
        performGC
        dirs <- liftM (filter (\x -> x /= "." && x /= "..")) $
                getDirectoryContents tmpdir
        assertEqual "files should be cleaned up" [] dirs


    tmpdir = "tempdirC"
    hndl = handleFileUploads tmpdir
                             defaultUploadPolicy
                             (const $ allowWithMaximumSize 300000)
                             hndl'

    hndl' _ _ = return ()


------------------------------------------------------------------------------
harness :: FilePath -> Snap a -> ByteString -> IO ()
harness = harness' go


------------------------------------------------------------------------------
harness' :: (Snap a -> ByteString -> IO Response)
         -> FilePath
         -> Snap a
         -> ByteString
         -> IO ()
harness' g tmpdir hndl body = (do
    createDirectoryIfMissing True tmpdir
    !_ <- g hndl body
    return ()) `finally` removeDirectoryRecursive tmpdir


------------------------------------------------------------------------------
assertThrows :: Exception e => IO a -> (e -> IO ()) -> IO ()
assertThrows act handle = catch action handle
  where
    action = act >> assertFailure "Expected exception to be thrown"


------------------------------------------------------------------------------
mkRequest :: ByteString -> IO Request
mkRequest body = Test.buildRequest $ Test.postRaw "/" ct body
  where
    ct = S.append "multipart/form-data; boundary=" boundaryValue


------------------------------------------------------------------------------
mkDamagedRequest :: ByteString -> IO Request
mkDamagedRequest body = do
    req <- Test.buildRequest $ Test.postRaw "/" ct ""

    e <- newIORef False >>= Streams.makeInputStream . enum

    return $! req { rqBody = e }

  where
    ct = S.append "multipart/form-data; boundary=" boundaryValue
    enum ref = do
        x <- readIORef ref
        if x
           then throw TestException
           else do writeIORef ref True
                   return $! Just $! S.take (S.length body - 1) body


------------------------------------------------------------------------------
go :: Snap a -> ByteString -> IO Response
go m s = do
    rq <- mkRequest s
    liftM snd (runIt m rq)


------------------------------------------------------------------------------
goBadContentType :: Snap a -> ByteString -> IO Response
goBadContentType m s = do
    rq <- mkRequest s
    let rq' = setHeader "Content-Type" "multipart/form-data" rq
    liftM snd (runIt m rq')


------------------------------------------------------------------------------
goWrongContentType :: Snap a -> ByteString -> IO Response
goWrongContentType m s = do
    rq <- mkRequest s
    let rq' = setHeader "Content-Type" "text/plain" rq
    liftM snd (runIt m rq')


------------------------------------------------------------------------------
goSlowEnumerator :: Snap a -> ByteString -> IO Response
goSlowEnumerator m s = do
    rq <- mkRequest s
    e  <- Streams.fromGenerator slowInput
    let rq' = rq { rqBody = e }
    mx <- timeout (20*seconds) (liftM snd (runIt m rq'))
    maybe (error "timeout") return mx

  where
    body = S.unpack s

    slowInput = f body
      where
        f []     = return ()
        f (x:xs) = do
            liftIO waitabit
            Streams.yield $ S.singleton x
            f xs


------------------------------------------------------------------------------
goAndAbort :: Snap a -> ByteString -> IO Response
goAndAbort m s = do
    rq <- mkRequest s
    e  <- Streams.fromGenerator generator
    let rq' = rq { rqBody = e }
    mx <- timeout (20*seconds) (liftM snd (runIt m rq'))
    maybe (error "timeout") return mx

  where
    generator = do
        Streams.yield s
        liftIO $ throwIO
               $ ErrorCall "For in that sleep of death what dreams may come."


------------------------------------------------------------------------------
runIt :: Snap a -> Request -> IO (Request, Response)
runIt m rq = runSnap m d bump rq
  where
    bump !f = let !_ = f 1 in return $! ()

    d :: forall a . Show a => a -> IO ()
    d = \x -> show x `deepseq` return ()


------------------------------------------------------------------------------
-- TEST DATA

formContents1 :: ByteString
formContents1 = "form contents 1"

formContents2 :: ByteString
formContents2 = "form contents 2 zzzzzzzzzzzzzzzzzzzz"

file1Contents :: ByteString
file1Contents = "foo"

file2Contents :: ByteString
file2Contents = "... contents of file2.gif ..."

filenameUtf8 :: ByteString
filenameUtf8 =  "\xd1\x82\xd0\xb5\xd1\x81\xd1\x82.png" -- "ั‚ะตัั‚.png" as UTF-8

boundaryValue :: ByteString
boundaryValue = "fkjldsakjfdlsafldksjf"

subBoundaryValue :: ByteString
subBoundaryValue = "zjkzjjfjskzjzjkz"

crlf :: ByteString
crlf = "\r\n"


------------------------------------------------------------------------------
mixedTestBody :: ByteString
mixedTestBody =
    S.concat
         [ "--"
         , boundaryValue
         , crlf
         , "content-disposition: form-data; name=\"field1\"\r\n"
         , crlf
         , formContents1
         , crlf
         , "--"
         , boundaryValue
         , crlf
         , "content-disposition: form-data; name=\"field2\"\r\n"
         , crlf
         , formContents2
         , crlf
         , "--"
         , boundaryValue
         , crlf
         , "content-disposition: form-data; name=\"files\"\r\n"
         , "Content-type: multipart/mixed; boundary="
         , subBoundaryValue
         , crlf
         , crlf
         , "--"
         , subBoundaryValue
         , crlf
         , "Content-disposition: attachment; filename=\"file1.txt\"\r\n"
         , "Content-Type: text/plain\r\n"
         , crlf
         , file1Contents
         , crlf
         , "--"
         , subBoundaryValue
         , crlf
         , "Content-disposition: attachment; filename=\"file2.gif\"\r\n"
         , "Content-type: image/gif\r\n"
         , "Content-Transfer-Encoding: binary\r\n"
         , crlf
         , file2Contents
         , crlf
         , "--"
         , subBoundaryValue
         , "--\r\n"
         , "--"
         , boundaryValue
         , "--\r\n"
         ]

------------------------------------------------------------------------------
mixedTestBodyWithBadTypes :: ByteString
mixedTestBodyWithBadTypes =
    S.concat
         [ "--"
         , boundaryValue
         , crlf
         , "content-type: ;\x01;\x01;\x01;\r\n"
         , "content-disposition: form-data; name=\"field1\"\r\n\r\n"
         , formContents1
         , crlf
         , "--"
         , boundaryValue
         , crlf
         , "content-disposition: form-data;\x01;;;\x01 name=\"field2\"\r\n"
         , crlf
         , formContents2
         , crlf
         , "--"
         , boundaryValue
         , crlf
         , "content-disposition: \x01\x01\x01\x01\r\n"
         , "Content-type: multipart/mixed; boundary="
         , subBoundaryValue
         , crlf
         , crlf
         , "--"
         , subBoundaryValue
         , crlf
         , "Content-disposition: attachment; filename=\"file1.txt\"\r\n"
         , "Content-Type: ;\x01;\x01;\x01;\r\n"
         , crlf
         , file1Contents
         , crlf
         , "--"
         , subBoundaryValue
         , crlf
         , "Content-disposition: attachment; filename=\"file2.gif\"\r\n"
         , "Content-type: ;\x01;\x01;\x01\r\n"
         , "Content-Transfer-Encoding: binary\r\n"
         , crlf
         , file2Contents
         , crlf
         , "--"
         , subBoundaryValue
         , "--\r\n"
         , "--"
         , boundaryValue
         , crlf
         , "Content-type: multipart/mixed; \x01\x01;;\x01;\r\n"
         , "Content-disposition: form-data; name=boo\r\n"
         , crlf
         , "boo"
         , crlf
         , "--"
         , boundaryValue
         , "--\r\n"
         ]


------------------------------------------------------------------------------
badMixedBody :: ByteString
badMixedBody =
    S.concat
         [ crlf
         , "--"
         , boundaryValue
         , crlf
         , "content-disposition: form-data; name=\"field1\"\r\n"
         , crlf
         , formContents1
         , crlf
         , "--"
         , boundaryValue
         , crlf
         , "content-disposition: form-data; name=\"field2\"\r\n"
         , crlf
         , formContents2
         , crlf
         , "--"
         , boundaryValue
         , crlf
         , "content-disposition: form-data; name=\"files\"\r\n"
         , "Content-type: multipart/mixed"
         , crlf
         , crlf
         , "--"
         , subBoundaryValue
         , crlf
         , "Content-disposition: attachment; filename=\"file1.txt\"\r\n"
         , "Content-Type: text/plain\r\n"
         , crlf
         , file1Contents
         , crlf
         , "--"
         , subBoundaryValue
         , crlf
         , "Content-disposition: attachment; filename=\"file2.gif\"\r\n"
         , "Content-type: image/gif\r\n"
         , "Content-Transfer-Encoding: binary\r\n"
         , crlf
         , file2Contents
         , crlf
         , "--"
         , subBoundaryValue
         , "--\r\n"
         , "--"
         , boundaryValue
         , "--\r\n"
         ]


------------------------------------------------------------------------------
bigHeadersBody :: ByteString
bigHeadersBody =
    S.concat (
         [ "--"
         , boundaryValue
         , crlf
         , "content-disposition: form-data; name=\"field1\"\r\n" ]
         ++
         map (\i -> S.pack ("field_" ++ show i ++ ": bar\r\n")) [1..40000::Int]
         ++
         [ crlf
         , formContents1
         , crlf
         , "--"
         , boundaryValue
         , "--\r\n"
         ])


------------------------------------------------------------------------------
noFileNameTestBody :: ByteString
noFileNameTestBody =
    S.concat
         [ "--"
         , boundaryValue
         , crlf
         , "content-disposition: form-data; name=\"field1\"\r\n"
         , crlf
         , formContents1
         , crlf
         , "--"
         , boundaryValue
         , crlf
         , "content-disposition: form-data; name=\"field2\"\r\n"
         , crlf
         , formContents2
         , crlf
         , "--"
         , boundaryValue
         , crlf
         , "content-disposition: form-data; name=\"files\"\r\n"
         , "Content-type: multipart/mixed; boundary="
         , subBoundaryValue
         , crlf
         , crlf
         , "--"
         , subBoundaryValue
         , crlf
         , "Content-disposition: file\r\n"
         , "Content-Type: text/plain\r\n"
         , crlf
         , file1Contents
         , crlf
         , "--"
         , subBoundaryValue
         , crlf
         , "Content-disposition: file\r\n"
         , "Content-type: image/gif\r\n"
         , "Content-Transfer-Encoding: binary\r\n"
         , crlf
         , file2Contents
         , crlf
         , "--"
         , subBoundaryValue
         , "--\r\n"
         , "--"
         , boundaryValue
         , "--\r\n"
         ]


------------------------------------------------------------------------------
abortedTestBody :: ByteString
abortedTestBody =
 S.concat [ "--"
          , boundaryValue
          , crlf
          , "content-disposition: form-data; name=\"field1\"\r\n"
          , crlf
          , formContents1
          , crlf
          , "--"
          , boundaryValue
          , crlf
          , "content-disposition: form-data; name=\"field2\"\r\n"
          , "fdjkljflsdkjfsd"
          ]


------------------------------------------------------------------------------
utf8FilenameBody :: ByteString
utf8FilenameBody =
    S.concat
         [ "--"
         , boundaryValue
         , crlf
         , "Content-Disposition: form-data; name=\"file\"; filename=\""
         , filenameUtf8
         , "\"\r\n"
         , "Content-Type: image/png\r\n"
         , crlf
         , file2Contents
         , crlf
         , "--"
         , boundaryValue
         , "--\r\n"
         ]