OCaml OUnit 括号示例:设置和拆卸

OCaml OUnit bracket example: setup and tear-down

我不太明白如何使用 OUnit(版本 2)设置和拆卸支架。 有人想提供一个完整的例子吗?

这里是OUnit2.bracket函数文档:

val bracket : (test_ctxt -> 'a) ->
       ('a -> test_ctxt -> unit) -> test_ctxt -> 'a

bracket set_up tear_down test_ctxt set up an object 
and register it to be tore down in test_ctxt.

您设置了这样的测试套件:

let test_suite =
  "suite" >::: [
    "test1" >:: test1_fun
  ]

而运行是这样的:

let _ =
  run_test_tt_main test_suite

在这个工作流中我应该把括号放在哪里?

Link 到 OUnit documentation.

OUnit 版本 1 的 ounit-2.0.0/examples 测试支架中的文件 test_stack.ml,因此没有用。

好的,看了这个文件就明白了:TestLog.ml

此示例将在每次测试后系统地销毁哈希表作为拆解函数。

open ListLabels (* map with label *)

let test_sentence test_ctxt =
  assert_equal "Foo" "Foo"

(** In my case, clear a hashtable after each test *)
let tear_down () test_ctxt =
  Hashtbl.clear Globals.flags_tbl

(** List of test cases as (name, function) tuples *)
let test_list = [
  "sentence", test_sentence;
]

(** Test suite for all tags *)
let tag_test_suite =
  "tags" >::: (map test_list ~f:(fun (name, test_fn) ->
    name >:: (fun test_ctxt ->
      bracket ignore tear_down test_ctxt;
      test_fn test_ctxt
    )
  ))