OCaml OUnit bracket example: setup and tear-down

泪湿孤枕 提交于 2019-12-07 19:46:20

问题


I do not really get how to use bracket setup and tear-down with OUnit (version 2). Anyone feel like supplying a full example ?

Here is the OUnit2.bracket function documentation:

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.

You setup a test suite like this:

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

And run it like this:

let _ =
  run_test_tt_main test_suite

Where do I put the bracket in this workflow ?

Link to OUnit documentation.

The file test_stack.ml in ounit-2.0.0/examples test bracket for OUnit version 1, so that's not useful.


回答1:


OK, got it after having a look at this file: TestLog.ml

This example will systematically destroy the hashtables after each test as a teardown function.

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
    )
  ))


来源:https://stackoverflow.com/questions/29336082/ocaml-ounit-bracket-example-setup-and-tear-down

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!