ocaml-iteratees / tests_common.ml

  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
open Ops
;

open Types
;

(*
module IO = Direct_IO
;
*)

open Iteratees
;

module Tests_functor(IO : MonadIO)
=
struct

value runIO = IO.runIO
;

module P = Printf;
value sprintf fmt = P.sprintf fmt;
value () = P.printf "before functor app\n%!";
module I = Make(IO);
value () = P.printf "after functor app\n%!";

open I;


(* Primitive Tests *)

value () =
  Iteratees.enum_fd_buffer_size.val := 5
  (* for tests; in real life, there should be 1024 or so *)
;

value test_iteratee : iteratee char (char * char) =
   drop 1 >>= fun () ->
   head >>= fun v1 ->
   drop 2 >>= fun () ->
   head >>= fun v2 ->
   return (v1, v2)
;


value string_of_e e =
  let (e, p) =
    match e with
    [ Iteratees_err_msg e -> (e, "")
    | EIO (e, p) -> (e, p)
    | e -> (e, "")
    ]
  in
  sprintf "error: %s%s\n"
    (Printexc.to_string e)
    (if p = "" then "" else sprintf " (at %S)" p)
;


value print_res f r =
  match r with
  [ `Ok v -> P.printf "res: ok: %s\n" (f v)
  | `Error e -> P.printf "%s\n" & string_of_e e
  ]
;

value print_char_tuple (c1, c2) = sprintf "(%C, %C)" c1 c2
;

value (runA : IO.m (iteratee 'el 'a) -> res 'a) i =
  runIO (i >>% run)
;

value run_print f i =
  let r = runA i
  in
    print_res f r
;

value expl s =
  inner [] (String.length s - 1)
  where rec inner acc i =
    if i < 0
    then acc
    else inner [s.[i] :: acc] (i-1)
;

value test12 n =
  let i = enum_pure_nchunk (expl "abcde") n test_iteratee
  and pr = print_char_tuple in
  run_print pr i
;

value test3 () =
  let i = enum_pure_nchunk (expl "abc") 2 test_iteratee >>%
          enum_pure_nchunk (expl "de") 1
  and pr = print_char_tuple in
  run_print pr i
;


module H = Iteratees_http.It_http(IO)
;

open H
;

(* Pure tests, requiring no IO *)

value test_str1 = expl &
    "header1: v1\rheader2: v2\r\nheader3: v3\nheader4: v4\n" ^
    "header5: v5\r\nheader6: v6\r\nheader7: v7\r\n\nrest\n"
;

value read_lines_and_one_more_line : iteratee 'a 'b =
  joinI (enum_lines stream2list) >>= fun lines ->
  line >>= fun after ->
  return (lines,after)
;


value with_err iter =
  iter >>= fun v ->
  is_stream_finished >>= fun e ->
  return (v, e)
;


value testp12 enum =
  let res = runA &
    enum read_lines_and_one_more_line
  in
  match res with
  [ `Error e -> failwith & string_of_e e
  | `Ok (lines, rest) ->
       ( assert (lines =
           [ "header1: v1"; "header2: v2"; "header3: v3"; "header4: v4"
           ; "header5: v5"; "header6: v6"; "header7: v7"
           ])
       ; assert (rest = (`Term, "rest"))
       )
  ]
;


value testp1 () = testp12 (enum_pure_1chunk test_str1)
;

value testp2 () = testp12 (enum_pure_nchunk test_str1 5)
;

value testw1 () =
  let test_str = expl "header1: v1\rheader2: v2\r\nheader3:\t v3"
  and expected = ["header1:"; "v1"; "header2:"; "v2"; "header3:"; "v3"] in
  let run_test test_str = runA &
     (enum_pure_nchunk test_str 5)
       (joinI (enum_words stream2list))
  in
  (
    print_res (String.concat (String.make 1 '|' (* to rewrite back*) )
                % List.map (sprintf "%S")
              )
    & run_test test_str
  ;
    assert (
         run_test test_str = `Ok expected
    )
  ; assert (
         run_test (List.append test_str [' ']) = `Ok expected
    )
   )
;


value (print_headers : list string -> IO.m unit) h =
  io_iter (fun i -> mprintf "header: %S\n" i >>% fun () -> IO.return ()) h
;


value string_of_termline (t, l) =
  sprintf "%S(%s)" l
    (match t with [ `Term -> "terminated" | `No_term -> "non-terminated" ])
;


(* + *)
(*
value () =
let line_collector = stream2list
in
  let read_lines_and_one_more_line
  : iteratee char ((list string * 'a) * ('b * string)) =
    joinI (enum_lines line_collector) >>= fun lines ->
let () = dbg "rl: lines got\n" in
    is_stream_finished >>= fun e ->
let () = dbg "rl: e got\n" in
    line >>= fun after ->
let () = dbg "rl: rest got\n" in
    return ((lines, e), after)
  in
  let (r : res _) =
  runIO
  (
    runA (
    enum_file "NUL" & read_lines_and_one_more_line
      )
  )
  in
  match r with
  [ `Ok _ -> printf "ok\n"
  | `Error ep -> printf "error: %s\n" & string_of_ep ep
  ]
;
value () = exit 0;
*)


(* Test Fd driver *)

value test_driver (line_collector : iteratee line 'a) filepath : IO.m unit
 =
  let read_lines_and_one_more_line : iteratee char 'y =
    joinI (enum_lines line_collector) >>= fun lines ->
    is_stream_finished >>= fun e ->
    line >>= fun after ->
    return ((lines, e), after)
  in
  mprintf "Opening file %S\n" filepath >>% fun () ->
  IO.open_in filepath >>% fun inch ->
  mprintf "About to read headers\n" >>% fun () ->
  mres (run %<< enum_fd inch read_lines_and_one_more_line) >>% fun result ->
  IO.close_in inch >>% fun () ->
  mprintf "Closed file %S\n" filepath >>% fun () ->
  mprintf "Finished reading headers\n" >>% fun () ->
  match result with
  [ `Ok ((_headers, None), after) ->
      mprintf "The line after headers is: %s\n"
        (string_of_termline after) >>% fun () ->
      mprintf "Complete headers.\n" >>% fun () ->
      IO.return ()
  | `Ok ((_headers, Some e), _after) ->
      mprintf "Problem: %s\n" (Printexc.to_string e) >>% fun () ->
      mprintf "Incomplete headers.\n" >>% fun () ->
      IO.return ()
  | `Error e ->
      mprintf "enumerator's error: %s\n" (string_of_e e) >>% fun () ->
      IO.error e
  ]
;


value dev_null = if Sys.os_type = "Win32" then "NUL" else "/dev/null";



value tests_driver () =
  let p i = ignore ((runIO & i) : res unit) in
  (
    (* Complete headers, up to "header7: v7" *)
    p & test_driver stream2list "test-files/test1.txt"

    (* The same *)
  ; p & test_driver stream2list "test-files/test2.txt"

    (* "header3: v3", then EOF *)
  ; p & test_driver stream2list "test-files/test3.txt"

    (* Incomplete headers [], EOF *)
  ; p & test_driver stream2list dev_null

  ; p & test_driver print_lines "test-files/test1.txt"
  ; p & test_driver print_lines "test-files/test2.txt"
  ; p & test_driver print_lines "test-files/test3.txt"
  ; p & test_driver print_lines dev_null
  )
;

           
(* Run the complete test, reading the headers and the body *)

(* This simple iteratee is used to process a variety of streams:
   embedded, interleaved, etc.
*)

(* +
   Don't know why, but there is no "joinI" in original sources.
*)

value line_printer : iteratee char unit =
  joinI & enum_lines print_lines
;


(* Two sample processors *)

(* Read the headers, print the headers, read the lines of the chunk-encoded
   body and print each line as it has been read
*)

value read_headers_print_body : iteratee char unit =
  (with_err & joinI & enum_lines stream2list) >>= fun headers'err ->
  (match headers'err with
   [ (headers, None) -> lift &
      mprintf "Complete headers\n" >>% fun () ->
      print_headers headers
   | (headers, Some e) -> lift &
      mprintf "Incomplete headers due to %s\n" (Printexc.to_string e)
        >>% fun () ->
      print_headers headers
   ]) >>= fun () ->
   (lift%mprintf) "\nLines of the body follow:\n" >>= fun () ->
   joinI & enum_chunk_decoded line_printer
;


(* Read the headers and print the header right after it has been read
   Read the lines of the chunk-encoded body and print each line as
   it has been read.
*)

(* +
   "()"-argument is here to suppress printing before actual call.
*)

value print_headers_print_body () : iteratee 'a unit =
  (lift%mprintf) "\nLines of the headers follow:\n" >>= fun () ->
  line_printer >>= fun () ->
  (lift%mprintf) "\nLines of the body follow:\n" >>= fun () ->
  joinI & enum_chunk_decoded line_printer
;


value test_driver_full iter filepath =
  mprintf "test_driver_full: %S\n" filepath >>% fun () ->
  IO.open_in filepath >>% fun inch ->
  mprintf "About to read headers\n" >>% fun () ->
  run %<< enum_fd inch iter >>% fun () ->
  IO.close_in inch >>% fun () ->
  mprintf "Finished reading\n"
;


value print_unit_res r =
  match r with
  [ `Ok () -> P.printf "ok.\n"
  | `Error e -> P.printf "%s\n" & string_of_e e
  ]
;


value tests_driver_full () =
  let p i = print_unit_res & runIO & i in
  ( ()

  ; p & test_driver_full read_headers_print_body "test-files/test_full1.txt"
    (*
       Complete headers
       ["header1: v1","header2: v2","header3: v3","header4: v4"]
       Problem Just "EOF"
       Incomplete body
       ["body line 1","body line    2","body line       3","body line          4"]
    *)
    (* +
       my observations: test_full1.txt has unfinished "body line 5",
       so it is reported (and should be reported) as "non-terminated
       body line 5".  This differs from Oleg's picture.
    *)

  ; p & test_driver_full read_headers_print_body "test-files/test_full2.txt"
    (* Exception: control message: Just Chunk decoding exc: Frame error *)

  ; p & test_driver_full read_headers_print_body "test-files/test_full3.txt"
    (* Complete headers
       ["header1: v1","header2: v2","header3: v3","header4: v4"]
       Problem Just "EOF"
       Incomplete body
       ["body line 1","body line    2","body line       3"
       ,"body line          4","body line             5"]
     *)

  ; p & test_driver_full (print_headers_print_body ())
          "test-files/test_full3.txt"

  )
;


(* +
   This is my test for enumeratee that transforms iteratee over
   utf8 chars (type [I.UTF8.uchar]) to iteratee over octets (type [char]).
*)

module U = I.UTF8;

value (dump_utf8_chars : iteratee U.uchar unit) =
 let pr s = mprintf "dump_utf8_chars: %s\n" s in
 ie_cont inner
 where rec inner s =
  match s with
  [ EOF opt_err ->
      match opt_err with
      [ None -> pr "natural end"
      | Some e -> pr & sprintf "unnatural end: \"%s\"" & Printexc.to_string e
      ]
      >>% fun () ->
      match opt_err with
      [ None -> ie_doneM () s
      | Some e -> IO.return & (throw_err e, s)
      ]
  | Chunk c ->
      pr
       (sprintf "chunk of %i chars: [%s]"
        (S.length c)
        (String.concat "" &
         List.map (fun c -> sprintf "&#x%X;" (c : U.uchar :> int)) &
         S.to_list c)
       )
      >>% fun () ->
      ie_contM inner
  ]
;


value utf8_chars = expl "Мама мыла раму.  Qwert."
;

exception Myexc;

value test_utf8_enumeratee () =
(
  assert ((
    runA & enum_pure_nchunk utf8_chars 3
           (joinI & U.utf8_of_char dump_utf8_chars)
    ) = `Ok ()
  )
;
  let res =
      runA & (enum_pure_nchunk utf8_chars 3 >>> enum_err Myexc)
             (joinI & U.utf8_of_char dump_utf8_chars)
  in
(*
  match res with
  [ `Ok () -> assert False
  | `Error e -> P.printf "exn: %s\n%!" (Printexc.to_string e)
  ]
*)
    assert (res = `Error (Iteratees_err_msg Myexc))
;
  ()
)
;



value limit_chars = expl "12345678abcdefgh"
;


exception Bad_int of string
;


value limited_iteratee : iteratee char int =
  let is_digit = fun [ '0'..'9' -> True | _ -> False ] in
  break_chars (not % is_digit) >>= fun num_str ->
  try return & int_of_string num_str
  with [ Failure _ -> throw_err & Bad_int num_str ]
;


value test_limit ~feed_cont n =
 let () = P.printf "test_limit: n=%i, feed_cont=%b\n%!" n feed_cont in
 let ctch ~b it =
   if not b
   then
     it
   else
     catchk
      it
      (fun err_msg _cont ->
         let () = P.printf "limited: caught %s%!" &
           match err_msg with
           [ Iteratees_err_msg e | e -> Printexc.to_string e ]
         in
           throw_err err_msg
      )
 in
 try
  let res = runA &
    (enum_pure_nchunk limit_chars 3)
    ( ctch ~b:True
        ( (limit n limited_iteratee) >>= fun it ->
          ( match it with
            [ IE_done i -> return & Some i
            | IE_cont None cont ->
                let () = P.printf "limited: cont wants more data, %!" in
                if not feed_cont
                then
                  let () = P.printf "ignoring.\n%!" in
                  lift (cont (EOF None)) >>= fun _ ->
                  return None
                else
                  let () = P.printf "feeding.\n%!" in
                  ie_cont cont >>= fun i ->
                  return & Some i
            | IE_cont (Some e) _ ->
                let () = P.printf "limited: error: %s\n" & Printexc.to_string e
                in
                  return None
            ]) >>= fun oi ->
          break_chars (fun _ -> False) >>= fun str ->
          return (oi, str)
        )
    )
  in
  match res with
  [ `Ok (oi, str) ->
      P.printf "limited: i=%s str=%S\n\n%!"
        (match oi with
         [ None -> "None"
         | Some i -> string_of_int i
         ])
        str
  | `Error e -> P.printf "exn: %s\n\n%!" &
      match e with
      [ Iteratees_err_msg e | e -> Printexc.to_string e
      ]
  ]
 with
 [ e -> P.printf "ACHTUNG!  uncaught exn: %s\n%!" & Printexc.to_string e ]
;


(*

    ( ctch ~b:True
        ( (joinI & limit n limited_iteratee) >>= fun i ->
          break_chars (fun _ -> False) >>= fun str ->
          return (i, str)
        )
    )

*)


value test_limits () =
  ( P.printf "\n%!"
  ; test_limit ~feed_cont:False 10
  ; test_limit ~feed_cont:False 5
  ; test_limit ~feed_cont:True 5
  )
;


value () =
  ( P.printf "TESTS BEGIN.\n"

  ; test12 5
  ; test12 2
  ; test3 ()
  ; testp1 ()
  ; testp2 ()

  ; testw1 ()

  ; tests_driver ()

  ; tests_driver_full ()

  ; test_utf8_enumeratee ()

  ; test_limits ()

  ; P.printf "TESTS END.\n"
  );

end;
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.