Ocaml 如何使用它为测试设置超时?
我有一些关于无限惰性结构的测试,如果测试的函数没有正确实现,这些测试可能会无限期运行,但是我在OUnit文档中找不到如何设置测试超时。我认为OUnit没有提供这种功能。我记得有一段时间我不得不这么做,这是我想出的快速破解方法:Ocaml 如何使用它为测试设置超时?,ocaml,ounit,Ocaml,Ounit,我有一些关于无限惰性结构的测试,如果测试的函数没有正确实现,这些测试可能会无限期运行,但是我在OUnit文档中找不到如何设置测试超时。我认为OUnit没有提供这种功能。我记得有一段时间我不得不这么做,这是我想出的快速破解方法: let race seconds ~f = let ch = Event.new_channel () in let timeout = Thread.create (fun () -> Thread.delay seconds; `
let race seconds ~f =
let ch = Event.new_channel () in
let timeout = Thread.create (fun () ->
Thread.delay seconds;
`Time_out |> Event.send ch |> Event.sync
) () in
let tf = Thread.create (fun () ->
`Result (f ()) |> Event.send ch |> Event.sync) () in
let res = ch |> Event.receive |> Event.sync in
try
Thread.kill timeout;
Thread.kill tf;
res
with _ -> res
let () =
let big_sum () =
let arr = Array.init 1_000_000 (fun x -> x) in
Array.fold_left (+) 0 arr in
match race 0.0001 ~f:big_sum with
| `Time_out -> print_endline "time to upgrade";
| `Result x -> Printf.printf "sum is: %d\n" x
这对于我的用例来说已经足够好了,但我绝对不建议使用它,因为如果
~f
不进行分配或手动调用~Thread.yield
,那么
将不会像您期望的那样工作。我认为它不提供此功能。我记得有一段时间我不得不这么做,这是我想出的快速破解方法:
let race seconds ~f =
let ch = Event.new_channel () in
let timeout = Thread.create (fun () ->
Thread.delay seconds;
`Time_out |> Event.send ch |> Event.sync
) () in
let tf = Thread.create (fun () ->
`Result (f ()) |> Event.send ch |> Event.sync) () in
let res = ch |> Event.receive |> Event.sync in
try
Thread.kill timeout;
Thread.kill tf;
res
with _ -> res
let () =
let big_sum () =
let arr = Array.init 1_000_000 (fun x -> x) in
Array.fold_left (+) 0 arr in
match race 0.0001 ~f:big_sum with
| `Time_out -> print_endline "time to upgrade";
| `Result x -> Printf.printf "sum is: %d\n" x
这对于我的用例来说已经足够好了,但我绝对不建议使用它,因为如果
~f
不进行分配或手动调用~Thread.yield
,那么
将无法像您所期望的那样工作。如果您使用的是OUnit2,以下功能应该可以工作:
let tests =
"suite" >::: [OUnitTest.TestCase (
OUnitTest.Short,
(fun _ -> assert_equal 2 (1+1))
);
OUnitTest.TestCase (
OUnitTest.Long,
(fun _ -> assert_equal 4 (2+2))
)]
类型测试长度定义为:
type test_length =
| Immediate
| Short
| Long
| Huge
| Custom_length of float
如果您使用的是OUnit2,那么以下功能应该可以正常工作:
let tests =
"suite" >::: [OUnitTest.TestCase (
OUnitTest.Short,
(fun _ -> assert_equal 2 (1+1))
);
OUnitTest.TestCase (
OUnitTest.Long,
(fun _ -> assert_equal 4 (2+2))
)]
类型测试长度定义为:
type test_length =
| Immediate
| Short
| Long
| Huge
| Custom_length of float
谢谢,我最终使用timeout
(coreutils软件包)对整个套装使用了超时。谢谢,我最终使用timeout
(coreutils软件包)对整个套装使用了超时。