forked from rescript-lang/rescript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathall_ounit_tests.ml
14517 lines (12469 loc) · 424 KB
/
all_ounit_tests.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
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
module OUnitTypes
= struct
#1 "oUnitTypes.ml"
(**
* Commont types for OUnit
*
* @author Sylvain Le Gall
*
*)
(** See OUnit.mli. *)
type node = ListItem of int | Label of string
(** See OUnit.mli. *)
type path = node list
(** See OUnit.mli. *)
type log_severity =
| LError
| LWarning
| LInfo
(** See OUnit.mli. *)
type test_result =
| RSuccess of path
| RFailure of path * string
| RError of path * string
| RSkip of path * string
| RTodo of path * string
(** See OUnit.mli. *)
type test_event =
| EStart of path
| EEnd of path
| EResult of test_result
| ELog of log_severity * string
| ELogRaw of string
(** Events which occur at the global level. *)
type global_event =
| GStart (** Start running the tests. *)
| GEnd (** Finish running the tests. *)
| GResults of (float * test_result list * int)
(* The type of test function *)
type test_fun = unit -> unit
(* The type of tests *)
type test =
| TestCase of test_fun
| TestList of test list
| TestLabel of string * test
type state =
{
tests_planned : (path * (unit -> unit)) list;
results : test_result list;
}
end
module OUnitChooser
= struct
#1 "oUnitChooser.ml"
(**
Heuristic to pick a test to run.
@author Sylvain Le Gall
*)
open OUnitTypes
(** Most simple heuristic, just pick the first test. *)
let simple state =
List.hd state.tests_planned
end
module OUnitUtils
= struct
#1 "oUnitUtils.ml"
(**
* Utilities for OUnit
*
* @author Sylvain Le Gall
*)
open OUnitTypes
let is_success =
function
| RSuccess _ -> true
| RFailure _ | RError _ | RSkip _ | RTodo _ -> false
let is_failure =
function
| RFailure _ -> true
| RSuccess _ | RError _ | RSkip _ | RTodo _ -> false
let is_error =
function
| RError _ -> true
| RSuccess _ | RFailure _ | RSkip _ | RTodo _ -> false
let is_skip =
function
| RSkip _ -> true
| RSuccess _ | RFailure _ | RError _ | RTodo _ -> false
let is_todo =
function
| RTodo _ -> true
| RSuccess _ | RFailure _ | RError _ | RSkip _ -> false
let result_flavour =
function
| RError _ -> "Error"
| RFailure _ -> "Failure"
| RSuccess _ -> "Success"
| RSkip _ -> "Skip"
| RTodo _ -> "Todo"
let result_path =
function
| RSuccess path
| RError (path, _)
| RFailure (path, _)
| RSkip (path, _)
| RTodo (path, _) -> path
let result_msg =
function
| RSuccess _ -> "Success"
| RError (_, msg)
| RFailure (_, msg)
| RSkip (_, msg)
| RTodo (_, msg) -> msg
(* Returns true if the result list contains successes only. *)
let rec was_successful =
function
| [] -> true
| RSuccess _::t
| RSkip _::t ->
was_successful t
| RFailure _::_
| RError _::_
| RTodo _::_ ->
false
let string_of_node =
function
| ListItem n ->
string_of_int n
| Label s ->
s
(* Return the number of available tests *)
let rec test_case_count =
function
| TestCase _ -> 1
| TestLabel (_, t) -> test_case_count t
| TestList l ->
List.fold_left
(fun c t -> c + test_case_count t)
0 l
let string_of_path path =
String.concat ":" (List.rev_map string_of_node path)
let buff_format_printf f =
let buff = Buffer.create 13 in
let fmt = Format.formatter_of_buffer buff in
f fmt;
Format.pp_print_flush fmt ();
Buffer.contents buff
(* Applies function f in turn to each element in list. Function f takes
one element, and integer indicating its location in the list *)
let mapi f l =
let rec rmapi cnt l =
match l with
| [] ->
[]
| h :: t ->
(f h cnt) :: (rmapi (cnt + 1) t)
in
rmapi 0 l
let fold_lefti f accu l =
let rec rfold_lefti cnt accup l =
match l with
| [] ->
accup
| h::t ->
rfold_lefti (cnt + 1) (f accup h cnt) t
in
rfold_lefti 0 accu l
end
module OUnitLogger
= struct
#1 "oUnitLogger.ml"
(*
* Logger for information and various OUnit events.
*)
open OUnitTypes
open OUnitUtils
type event_type = GlobalEvent of global_event | TestEvent of test_event
let format_event verbose event_type =
match event_type with
| GlobalEvent e ->
begin
match e with
| GStart ->
""
| GEnd ->
""
| GResults (running_time, results, test_case_count) ->
let separator1 = String.make (Format.get_margin ()) '=' in
let separator2 = String.make (Format.get_margin ()) '-' in
let buf = Buffer.create 1024 in
let bprintf fmt = Printf.bprintf buf fmt in
let print_results =
List.iter
(fun result ->
bprintf "%s\n%s: %s\n\n%s\n%s\n"
separator1
(result_flavour result)
(string_of_path (result_path result))
(result_msg result)
separator2)
in
let errors = List.filter is_error results in
let failures = List.filter is_failure results in
let skips = List.filter is_skip results in
let todos = List.filter is_todo results in
if not verbose then
bprintf "\n";
print_results errors;
print_results failures;
bprintf "Ran: %d tests in: %.2f seconds.\n"
(List.length results) running_time;
(* Print final verdict *)
if was_successful results then
begin
if skips = [] then
bprintf "OK"
else
bprintf "OK: Cases: %d Skip: %d"
test_case_count (List.length skips)
end
else
begin
bprintf
"FAILED: Cases: %d Tried: %d Errors: %d \
Failures: %d Skip:%d Todo:%d"
test_case_count (List.length results)
(List.length errors) (List.length failures)
(List.length skips) (List.length todos);
end;
bprintf "\n";
Buffer.contents buf
end
| TestEvent e ->
begin
let string_of_result =
if verbose then
function
| RSuccess _ -> "ok\n"
| RFailure (_, _) -> "FAIL\n"
| RError (_, _) -> "ERROR\n"
| RSkip (_, _) -> "SKIP\n"
| RTodo (_, _) -> "TODO\n"
else
function
| RSuccess _ -> "."
| RFailure (_, _) -> "F"
| RError (_, _) -> "E"
| RSkip (_, _) -> "S"
| RTodo (_, _) -> "T"
in
if verbose then
match e with
| EStart p ->
Printf.sprintf "%s start\n" (string_of_path p)
| EEnd p ->
Printf.sprintf "%s end\n" (string_of_path p)
| EResult result ->
string_of_result result
| ELog (lvl, str) ->
let prefix =
match lvl with
| LError -> "E"
| LWarning -> "W"
| LInfo -> "I"
in
prefix^": "^str
| ELogRaw str ->
str
else
match e with
| EStart _ | EEnd _ | ELog _ | ELogRaw _ -> ""
| EResult result -> string_of_result result
end
let file_logger fn =
let chn = open_out fn in
(fun ev ->
output_string chn (format_event true ev);
flush chn),
(fun () -> close_out chn)
let std_logger verbose =
(fun ev ->
print_string (format_event verbose ev);
flush stdout),
(fun () -> ())
let null_logger =
ignore, ignore
let create output_file_opt verbose (log,close) =
let std_log, std_close = std_logger verbose in
let file_log, file_close =
match output_file_opt with
| Some fn ->
file_logger fn
| None ->
null_logger
in
(fun ev ->
std_log ev; file_log ev; log ev),
(fun () ->
std_close (); file_close (); close ())
let printf log fmt =
Printf.ksprintf
(fun s ->
log (TestEvent (ELogRaw s)))
fmt
end
module OUnit : sig
#1 "oUnit.mli"
(***********************************************************************)
(* The OUnit library *)
(* *)
(* Copyright (C) 2002-2008 Maas-Maarten Zeeman. *)
(* Copyright (C) 2010 OCamlCore SARL *)
(* *)
(* See LICENSE for details. *)
(***********************************************************************)
(** Unit test building blocks
@author Maas-Maarten Zeeman
@author Sylvain Le Gall
*)
(** {2 Assertions}
Assertions are the basic building blocks of unittests. *)
(** Signals a failure. This will raise an exception with the specified
string.
@raise Failure signal a failure *)
val assert_failure : string -> 'a
(** Signals a failure when bool is false. The string identifies the
failure.
@raise Failure signal a failure *)
val assert_bool : string -> bool -> unit
(** Shorthand for assert_bool
@raise Failure to signal a failure *)
val ( @? ) : string -> bool -> unit
(** Signals a failure when the string is non-empty. The string identifies the
failure.
@raise Failure signal a failure *)
val assert_string : string -> unit
(** [assert_command prg args] Run the command provided.
@param exit_code expected exit code
@param sinput provide this [char Stream.t] as input of the process
@param foutput run this function on output, it can contains an
[assert_equal] to check it
@param use_stderr redirect [stderr] to [stdout]
@param env Unix environment
@param verbose if a failure arise, dump stdout/stderr of the process to stderr
@since 1.1.0
*)
val assert_command :
?exit_code:Unix.process_status ->
?sinput:char Stream.t ->
?foutput:(char Stream.t -> unit) ->
?use_stderr:bool ->
?env:string array ->
?verbose:bool ->
string -> string list -> unit
(** [assert_equal expected real] Compares two values, when they are not equal a
failure is signaled.
@param cmp customize function to compare, default is [=]
@param printer value printer, don't print value otherwise
@param pp_diff if not equal, ask a custom display of the difference
using [diff fmt exp real] where [fmt] is the formatter to use
@param msg custom message to identify the failure
@raise Failure signal a failure
@version 1.1.0
*)
val assert_equal :
?cmp:('a -> 'a -> bool) ->
?printer:('a -> string) ->
?pp_diff:(Format.formatter -> ('a * 'a) -> unit) ->
?msg:string -> 'a -> 'a -> unit
(** Asserts if the expected exception was raised.
@param msg identify the failure
@raise Failure description *)
val assert_raises : ?msg:string -> exn -> (unit -> 'a) -> unit
val assert_raise_any : ?msg:string -> (unit -> 'a) -> unit
(** {2 Skipping tests }
In certain condition test can be written but there is no point running it, because they
are not significant (missing OS features for example). In this case this is not a failure
nor a success. Following functions allow you to escape test, just as assertion but without
the same error status.
A test skipped is counted as success. A test todo is counted as failure.
*)
(** [skip cond msg] If [cond] is true, skip the test for the reason explain in [msg].
For example [skip_if (Sys.os_type = "Win32") "Test a doesn't run on windows"].
@since 1.0.3
*)
val skip_if : bool -> string -> unit
(** The associated test is still to be done, for the reason given.
@since 1.0.3
*)
val todo : string -> unit
(** {2 Compare Functions} *)
(** Compare floats up to a given relative error.
@param epsilon if the difference is smaller [epsilon] values are equal
*)
val cmp_float : ?epsilon:float -> float -> float -> bool
(** {2 Bracket}
A bracket is a functional implementation of the commonly used
setUp and tearDown feature in unittests. It can be used like this:
["MyTestCase" >:: (bracket test_set_up test_fun test_tear_down)]
*)
(** [bracket set_up test tear_down] The [set_up] function runs first, then
the [test] function runs and at the end [tear_down] runs. The
[tear_down] function runs even if the [test] failed and help to clean
the environment.
*)
val bracket: (unit -> 'a) -> ('a -> unit) -> ('a -> unit) -> unit -> unit
(** [bracket_tmpfile test] The [test] function takes a temporary filename
and matching output channel as arguments. The temporary file is created
before the test and removed after the test.
@param prefix see [Filename.open_temp_file]
@param suffix see [Filename.open_temp_file]
@param mode see [Filename.open_temp_file]
@since 1.1.0
*)
val bracket_tmpfile:
?prefix:string ->
?suffix:string ->
?mode:open_flag list ->
((string * out_channel) -> unit) -> unit -> unit
(** {2 Constructing Tests} *)
(** The type of test function *)
type test_fun = unit -> unit
(** The type of tests *)
type test =
TestCase of test_fun
| TestList of test list
| TestLabel of string * test
(** Create a TestLabel for a test *)
val (>:) : string -> test -> test
(** Create a TestLabel for a TestCase *)
val (>::) : string -> test_fun -> test
(** Create a TestLabel for a TestList *)
val (>:::) : string -> test list -> test
(** Some shorthands which allows easy test construction.
Examples:
- ["test1" >: TestCase((fun _ -> ()))] =>
[TestLabel("test2", TestCase((fun _ -> ())))]
- ["test2" >:: (fun _ -> ())] =>
[TestLabel("test2", TestCase((fun _ -> ())))]
- ["test-suite" >::: ["test2" >:: (fun _ -> ());]] =>
[TestLabel("test-suite", TestSuite([TestLabel("test2", TestCase((fun _ -> ())))]))]
*)
(** [test_decorate g tst] Apply [g] to test function contains in [tst] tree.
@since 1.0.3
*)
val test_decorate : (test_fun -> test_fun) -> test -> test
(** [test_filter paths tst] Filter test based on their path string representation.
@param skip] if set, just use [skip_if] for the matching tests.
@since 1.0.3
*)
val test_filter : ?skip:bool -> string list -> test -> test option
(** {2 Retrieve Information from Tests} *)
(** Returns the number of available test cases *)
val test_case_count : test -> int
(** Types which represent the path of a test *)
type node = ListItem of int | Label of string
type path = node list (** The path to the test (in reverse order). *)
(** Make a string from a node *)
val string_of_node : node -> string
(** Make a string from a path. The path will be reversed before it is
tranlated into a string *)
val string_of_path : path -> string
(** Returns a list with paths of the test *)
val test_case_paths : test -> path list
(** {2 Performing Tests} *)
(** Severity level for log. *)
type log_severity =
| LError
| LWarning
| LInfo
(** The possible results of a test *)
type test_result =
RSuccess of path
| RFailure of path * string
| RError of path * string
| RSkip of path * string
| RTodo of path * string
(** Events which occur during a test run. *)
type test_event =
EStart of path (** A test start. *)
| EEnd of path (** A test end. *)
| EResult of test_result (** Result of a test. *)
| ELog of log_severity * string (** An event is logged in a test. *)
| ELogRaw of string (** Print raw data in the log. *)
(** Perform the test, allows you to build your own test runner *)
val perform_test : (test_event -> 'a) -> test -> test_result list
(** A simple text based test runner. It prints out information
during the test.
@param verbose print verbose message
*)
val run_test_tt : ?verbose:bool -> test -> test_result list
(** Main version of the text based test runner. It reads the supplied command
line arguments to set the verbose level and limit the number of test to
run.
@param arg_specs add extra command line arguments
@param set_verbose call a function to set verbosity
@version 1.1.0
*)
val run_test_tt_main :
?arg_specs:(Arg.key * Arg.spec * Arg.doc) list ->
?set_verbose:(bool -> unit) ->
test -> test_result list
end = struct
#1 "oUnit.ml"
(***********************************************************************)
(* The OUnit library *)
(* *)
(* Copyright (C) 2002-2008 Maas-Maarten Zeeman. *)
(* Copyright (C) 2010 OCamlCore SARL *)
(* *)
(* See LICENSE for details. *)
(***********************************************************************)
open OUnitUtils
include OUnitTypes
(*
* Types and global states.
*)
let global_verbose = ref false
let global_output_file =
let pwd = Sys.getcwd () in
let ocamlbuild_dir = Filename.concat pwd "_build" in
let dir =
if Sys.file_exists ocamlbuild_dir && Sys.is_directory ocamlbuild_dir then
ocamlbuild_dir
else
pwd
in
ref (Some (Filename.concat dir "oUnit.log"))
let global_logger = ref (fst OUnitLogger.null_logger)
let global_chooser = ref OUnitChooser.simple
let bracket set_up f tear_down () =
let fixture =
set_up ()
in
let () =
try
let () = f fixture in
tear_down fixture
with e ->
let () =
tear_down fixture
in
raise e
in
()
let bracket_tmpfile ?(prefix="ounit-") ?(suffix=".txt") ?mode f =
bracket
(fun () ->
Filename.open_temp_file ?mode prefix suffix)
f
(fun (fn, chn) ->
begin
try
close_out chn
with _ ->
()
end;
begin
try
Sys.remove fn
with _ ->
()
end)
exception Skip of string
let skip_if b msg =
if b then
raise (Skip msg)
exception Todo of string
let todo msg =
raise (Todo msg)
let assert_failure msg =
failwith ("OUnit: " ^ msg)
let assert_bool msg b =
if not b then assert_failure msg
let assert_string str =
if not (str = "") then assert_failure str
let assert_equal ?(cmp = ( = )) ?printer ?pp_diff ?msg expected actual =
let get_error_string () =
let res =
buff_format_printf
(fun fmt ->
Format.pp_open_vbox fmt 0;
begin
match msg with
| Some s ->
Format.pp_open_box fmt 0;
Format.pp_print_string fmt s;
Format.pp_close_box fmt ();
Format.pp_print_cut fmt ()
| None ->
()
end;
begin
match printer with
| Some p ->
Format.fprintf fmt
"@[expected: @[%s@]@ but got: @[%s@]@]@,"
(p expected)
(p actual)
| None ->
Format.fprintf fmt "@[not equal@]@,"
end;
begin
match pp_diff with
| Some d ->
Format.fprintf fmt
"@[differences: %a@]@,"
d (expected, actual)
| None ->
()
end;
Format.pp_close_box fmt ())
in
let len =
String.length res
in
if len > 0 && res.[len - 1] = '\n' then
String.sub res 0 (len - 1)
else
res
in
if not (cmp expected actual) then
assert_failure (get_error_string ())
let assert_command
?(exit_code=Unix.WEXITED 0)
?(sinput=Stream.of_list [])
?(foutput=ignore)
?(use_stderr=true)
?env
?verbose
prg args =
bracket_tmpfile
(fun (fn_out, chn_out) ->
let cmd_print fmt =
let () =
match env with
| Some e ->
begin
Format.pp_print_string fmt "env";
Array.iter (Format.fprintf fmt "@ %s") e;
Format.pp_print_space fmt ()
end
| None ->
()
in
Format.pp_print_string fmt prg;
List.iter (Format.fprintf fmt "@ %s") args
in
(* Start the process *)
let in_write =
Unix.dup (Unix.descr_of_out_channel chn_out)
in
let (out_read, out_write) =
Unix.pipe ()
in
let err =
if use_stderr then
in_write
else
Unix.stderr
in
let args =
Array.of_list (prg :: args)
in
let pid =
OUnitLogger.printf !global_logger "%s"
(buff_format_printf
(fun fmt ->
Format.fprintf fmt "@[Starting command '%t'@]\n" cmd_print));
Unix.set_close_on_exec out_write;
match env with
| Some e ->
Unix.create_process_env prg args e out_read in_write err
| None ->
Unix.create_process prg args out_read in_write err
in
let () =
Unix.close out_read;
Unix.close in_write
in
let () =
(* Dump sinput into the process stdin *)
let buff = Bytes.of_string " " in
Stream.iter
(fun c ->
let _i : int =
Bytes.set buff 0 c;
Unix.write out_write buff 0 1
in
())
sinput;
Unix.close out_write
in
let _, real_exit_code =
let rec wait_intr () =
try
Unix.waitpid [] pid
with Unix.Unix_error (Unix.EINTR, _, _) ->
wait_intr ()
in
wait_intr ()
in
let exit_code_printer =
function
| Unix.WEXITED n ->
Printf.sprintf "exit code %d" n
| Unix.WSTOPPED n ->
Printf.sprintf "stopped by signal %d" n
| Unix.WSIGNALED n ->
Printf.sprintf "killed by signal %d" n
in
(* Dump process output to stderr *)
begin
let chn = open_in fn_out in
let buff = String.make 4096 'X' in
let len = ref (-1) in
while !len <> 0 do
len := input chn buff 0 (String.length buff);
OUnitLogger.printf !global_logger "%s" (String.sub buff 0 !len);
done;
close_in chn
end;
(* Check process status *)
assert_equal
~msg:(buff_format_printf
(fun fmt ->
Format.fprintf fmt
"@[Exit status of command '%t'@]" cmd_print))
~printer:exit_code_printer
exit_code
real_exit_code;
begin
let chn = open_in fn_out in
try
foutput (Stream.of_channel chn)
with e ->
close_in chn;
raise e
end)
()
let raises f =
try
f ();
None
with e ->
Some e
let assert_raises ?msg exn (f: unit -> 'a) =
let pexn =
Printexc.to_string
in
let get_error_string () =
let str =
Format.sprintf
"expected exception %s, but no exception was raised."
(pexn exn)
in
match msg with
| None ->
assert_failure str
| Some s ->
assert_failure (s^"\n"^str)
in
match raises f with
| None ->
assert_failure (get_error_string ())
| Some e ->
assert_equal ?msg ~printer:pexn exn e
let assert_raise_any ?msg (f: unit -> 'a) =
let pexn =
Printexc.to_string
in
let get_error_string () =
let str =
Format.sprintf
"expected exception , but no exception was raised."
in
match msg with
| None ->
assert_failure str
| Some s ->
assert_failure (s^"\n"^str)
in
match raises f with
| None ->
assert_failure (get_error_string ())
| Some exn ->
assert_bool (pexn exn) true
(* Compare floats up to a given relative error *)
let cmp_float ?(epsilon = 0.00001) a b =
abs_float (a -. b) <= epsilon *. (abs_float a) ||
abs_float (a -. b) <= epsilon *. (abs_float b)
(* Now some handy shorthands *)
let (@?) = assert_bool
(* Some shorthands which allows easy test construction *)
let (>:) s t = TestLabel(s, t) (* infix *)
let (>::) s f = TestLabel(s, TestCase(f)) (* infix *)
let (>:::) s l = TestLabel(s, TestList(l)) (* infix *)
(* Utility function to manipulate test *)
let rec test_decorate g =
function
| TestCase f ->
TestCase (g f)
| TestList tst_lst ->
TestList (List.map (test_decorate g) tst_lst)
| TestLabel (str, tst) ->
TestLabel (str, test_decorate g tst)
let test_case_count = OUnitUtils.test_case_count
let string_of_node = OUnitUtils.string_of_node
let string_of_path = OUnitUtils.string_of_path
(* Returns all possible paths in the test. The order is from test case
to root
*)
let test_case_paths test =
let rec tcps path test =
match test with
| TestCase _ ->
[path]
| TestList tests ->
List.concat
(mapi (fun t i -> tcps ((ListItem i)::path) t) tests)
| TestLabel (l, t) ->
tcps ((Label l)::path) t
in
tcps [] test
(* Test filtering with their path *)
module SetTestPath = Set.Make(String)
let test_filter ?(skip=false) only test =
let set_test =
List.fold_left
(fun st str -> SetTestPath.add str st)
SetTestPath.empty
only
in
let rec filter_test path tst =
if SetTestPath.mem (string_of_path path) set_test then