简体   繁体   中英

OCaml OUnit bracket example: setup and tear-down

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM