package_name
stringlengths 2
45
| version
stringclasses 323
values | license
stringclasses 56
values | homepage
stringclasses 396
values | dev_repo
stringclasses 396
values | file_type
stringclasses 6
values | file_path
stringlengths 6
151
| file_content
stringlengths 0
9.28M
|
|---|---|---|---|---|---|---|---|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
dune
|
tezt-4.3.0/lib/dune
|
(library
(name tezt)
(public_name tezt)
(libraries
re
lwt.unix
tezt.json
tezt.core
tezt.scheduler)
(flags
(:standard)
-open Tezt_core))
|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
ml
|
tezt-4.3.0/lib/echo.ml
|
(*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2020-2022 Nomadic Labs <contact@nomadic-labs.com> *)
(* Copyright (c) 2020 Metastate AG <hello@metastate.dev> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
open Base
type t = {
queue : string ref Queue.t;
mutable lwt_channel : Lwt_io.input_channel option;
mutable closed : bool;
mutable pending : int list;
}
let wake_up echo =
let pending = echo.pending in
echo.pending <- [] ;
List.iter (fun pending -> Lwt_unix.send_notification pending) pending
let push echo string =
(* Maintain the invariant that strings in the queue are never empty. *)
if String.length string > 0 then (
Queue.push (ref string) echo.queue ;
wake_up echo)
let close echo =
if not echo.closed then (
echo.closed <- true ;
wake_up echo)
let create () =
let echo =
{queue = Queue.create (); lwt_channel = None; closed = false; pending = []}
in
let rec read bytes ofs len =
match Queue.peek_opt echo.queue with
| None ->
if echo.closed then return 0
else
(* Nothing to read, for now. *)
let promise, resolver = Lwt.task () in
let note =
Lwt_unix.make_notification ~once:true (fun () ->
Lwt.wakeup_later resolver ())
in
echo.pending <- note :: echo.pending ;
let* () = promise in
read bytes ofs len
| Some str_ref ->
(* Note: we rely on the invariant that strings in the queue are never empty. *)
let str_len = String.length !str_ref in
if str_len <= len then (
(* Caller requested more bytes than available in this item of the queue:
return the item in full and remove it from the queue. *)
(* use [Lwt_bytes.blit_from_string] once available *)
Lwt_bytes.blit_from_bytes
(Bytes.of_string !str_ref)
0
bytes
ofs
str_len ;
let (_ : string ref option) = Queue.take_opt echo.queue in
return str_len)
else (
(* Caller requested strictly less bytes than available in this item of the queue:
return what caller requested, and only keep the remainder. *)
(* use [Lwt_bytes.blit_from_string] once available *)
Lwt_bytes.blit_from_bytes (Bytes.of_string !str_ref) 0 bytes ofs len ;
str_ref := String.sub !str_ref len (str_len - len) ;
return len)
in
let lwt_channel = Lwt_io.(make ~mode:input) read in
echo.lwt_channel <- Some lwt_channel ;
echo
let get_lwt_channel echo =
match echo.lwt_channel with
| None ->
(* Impossible: [lwt_channel] is filled by [Some ...] immediately after the [echo]
is created by [create_echo]. *)
assert false
| Some lwt_channel -> lwt_channel
|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
mli
|
tezt-4.3.0/lib/echo.mli
|
(*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2020-2022 Nomadic Labs <contact@nomadic-labs.com> *)
(* Copyright (c) 2020 Metastate AG <hello@metastate.dev> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
(** Process outputs that can be duplicated. *)
(** This module is experimental. *)
(** An [Echo.t] represents the standard output or standard error output of a process.
Those outputs are duplicated: one copy is automatically logged,
the other goes into [lwt_channel] so that the user can read it.
(The logging part is handled by the [Process] module, not [Echo].)
[queue] is the bytes that have been received from the process, but that
have not yet been read by the user of this module. Those bytes are
split into chunks ([string]s). Those chunks are never empty.
Strings of [queue] are references so that we can replace them when we
read them partially. If efficiency becomes a concern, we could store
a reference to an offset to avoid a call to String.sub.
[pending] is a list of [Lwt_unix] notifications. *)
type t = {
queue : string ref Queue.t;
mutable lwt_channel : Lwt_io.input_channel option;
mutable closed : bool;
mutable pending : int list;
}
(** Send all [pending] notifications and clear [pending]. *)
val wake_up : t -> unit
(** Push a string into the [queue] of an echo, if the string is not empty. *)
val push : t -> string -> unit
(** Set [closed] to [true] and call [wake_up_echo]. *)
val close : t -> unit
(** Create an echo. *)
val create : unit -> t
(** Get the [lwt_channel] of an echo. *)
val get_lwt_channel : t -> Lwt_io.input_channel
|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
ml
|
tezt-4.3.0/lib/main.ml
|
(*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2022 Nomadic Labs <contact@nomadic-labs.com> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
open Base
(* [Unix.error_message] is not available in JS, so we register the printer here
instead of in [Base]. *)
let () =
Printexc.register_printer @@ function
| Unix.Unix_error (error, _, _) -> Some (Unix.error_message error)
| _ -> None
let start_time = Unix.gettimeofday ()
module Memory_usage : sig
val get_recursively_for_pid : int -> (int, string) result
end = struct
let kb = 1000
(* Get the memory usage of a single process (not recursively)
by reading from /proc/PID/smaps.
More specifically, we read the Pss field, which gives a more representative memory usage
as it divides shared memory by the number of processes that share this memory. *)
(* https://stackoverflow.com/questions/131303/how-can-i-measure-the-actual-memory-usage-of-an-application-or-process *)
let get_total_pss pid =
let ch = open_in ("/proc/" ^ string_of_int pid ^ "/smaps") in
Fun.protect ~finally:(fun () -> close_in ch) @@ fun () ->
let rec sum_pss acc =
match input_line ch with
| exception End_of_file -> acc
| line ->
let parse_error () =
failwith (Printf.sprintf "failed to parse %S" line)
in
let line = String.trim line in
let value =
if not (String.starts_with ~prefix:"Pss:" line) then 0
else if not (String.ends_with ~suffix:"kB" line) then parse_error ()
else
let value =
String.sub
line
(String.length "Pss:")
(String.length line - String.length "Pss:"
- String.length "kB")
|> String.trim
in
match int_of_string_opt value with
| None -> parse_error ()
| Some value -> value * kb
in
sum_pss (acc + value)
in
sum_pss 0
(* Read all lines from an input channel and return them as a list. *)
let rec input_lines ?(acc = []) ch =
match input_line ch with
| exception End_of_file -> List.rev acc
| line -> input_lines ~acc:(line :: acc) ch
(* Read /proc/PID/task/*/children to get the list of children of a process.
Returns the list of PIDs of all children. *)
let get_children pid =
(* I think a task is the same as a thread. *)
let task_path = "/proc/" ^ string_of_int pid ^ "/task" in
let parse_tid line =
match int_of_string_opt (String.trim line) with
| None ->
failwith (sf "failed to parse %S from %s as a TID" line task_path)
| Some pid -> pid
in
let task_ids =
Sys.readdir task_path |> Array.to_list |> List.map parse_tid
in
let get_task_children tid =
let task_children_path =
task_path ^ "/" ^ string_of_int tid ^ "/children"
in
let ch = open_in task_children_path in
Fun.protect ~finally:(fun () -> close_in ch) @@ fun () ->
let parse_pid line =
match int_of_string_opt line with
| None ->
failwith
(sf "failed to parse %S from %s as a PID" line task_children_path)
| Some pid -> pid
in
input_lines ch
|> List.map (String.split_on_char ' ')
|> List.flatten |> List.map String.trim
|> List.filter (( <> ) "")
|> List.map parse_pid
in
List.flatten (List.map get_task_children task_ids)
let get_recursively_for_pid pid =
let rec get acc pid =
let acc = acc + get_total_pss pid in
let children = get_children pid in
List.fold_left get acc children
in
try Ok (get 0 pid)
with Sys_error message | Failure message -> Error message
end
module Scheduler : Test.SCHEDULER = struct
(* Use the [Scheduler] module from the [tezt.scheduler] library,
with an alias [S] so that we don't confuse it with the [Scheduler] module
we are defining. *)
module S = Scheduler
type request = Run_test of {test_title : string}
type response = Test_result of Test.test_result
let internal_worker_error x =
Printf.ksprintf
(fun s ->
Log.error "internal error in worker: %s" s ;
exit 1)
x
let internal_scheduler_error x =
Printf.ksprintf
(fun s ->
Log.error "internal error in scheduler: %s" s ;
exit 1)
x
let encode_used_seed (seed : Test.used_seed) : S.Message.value =
match seed with Used_fixed -> Unit | Used_random seed -> Int seed
let decode_used_seed (value : S.Message.value) : Test.used_seed =
match value with
| Unit -> Used_fixed
| Int seed -> Used_random seed
| _ -> raise (S.Message.Failed_to_decode (value, "used_seed"))
let test_result_type : Test.test_result S.Message.typ =
let encode ({test_result; seed; peak_memory_usage} : Test.test_result) :
S.Message.value =
Block
[|
(match test_result with
| Successful -> Int 0
| Failed error_message -> String error_message
| Aborted -> Int 1);
encode_used_seed seed;
(match peak_memory_usage with
| None -> Int (-1)
| Some peak_memory_usage -> Int peak_memory_usage);
|]
in
let decode (value : S.Message.value) : Test.test_result =
let fail () = raise (S.Message.Failed_to_decode (value, "test_result")) in
match value with
| Block [|test_result; seed; Int peak_memory_usage|] ->
{
test_result =
(match test_result with
| Int 0 -> Successful
| String error_message -> Failed error_message
| Int 1 -> Aborted
| _ -> fail ());
seed = decode_used_seed seed;
peak_memory_usage =
(if peak_memory_usage >= 0 then Some peak_memory_usage else None);
}
| _ -> fail ()
in
S.Message.typ ~encode ~decode
let run_test ?(temp_start = Temp.start) (test_title : string) :
Test.test_result =
match Test.get_test_by_title test_title with
| None ->
internal_worker_error
"scheduler requested to run test %S, but worker doesn't know about \
this test"
test_title
| Some test ->
let clean_up () =
Lwt.catch Process.clean_up @@ fun exn ->
Log.warn "Failed to clean up processes: %s" (Printexc.to_string exn) ;
unit
in
(* If the following raises an exception, it will be caught by the scheduler
library and sent as a string to the scheduler process.
Any exception-specific handling is better done in the [Test] module
so that other backends can also benefit. *)
Lwt_main.run
@@ Test.run_one
~sleep:Lwt_unix.sleep
~clean_up
~temp_start
~temp_stop:Temp.stop
~temp_clean_up:Temp.clean_up
test
let msg_seed = S.Message.(register int) "Seed"
let add_task_for_request (Run_test {test_title})
(on_response : response -> unit) =
let term_timeout =
let global_timeout =
match Cli.Options.global_timeout with
| None -> None
| Some global_timeout ->
Some (max 0. (start_time +. global_timeout -. Unix.gettimeofday ()))
in
match (global_timeout, Cli.Options.test_timeout) with
| None, None -> None
| (Some _ as x), None | None, (Some _ as x) -> x
| Some a, Some b -> Some (min a b)
in
let kill_timeout =
match term_timeout with
| None -> None
| Some _ -> Some Cli.Options.cleanup_timeout
in
let warn_after_timeout_timer : S.Timer.t option ref = ref None in
let measure_memory_usage_timer : S.Timer.t option ref = ref None in
let peak_memory_usage = ref None in
let already_warned_about_memory_usage = ref false in
let on_start ctx =
let measure_memory_usage_once pid =
match Memory_usage.get_recursively_for_pid pid with
| Ok bytes -> (
if
(not !already_warned_about_memory_usage)
&&
match Cli.Options.mem_warn with
| None -> false
| Some threshold -> bytes >= threshold
then (
already_warned_about_memory_usage := true ;
Log.warn
"Test is using too much memory: %S (%d bytes)"
test_title
bytes) ;
match !peak_memory_usage with
| None -> peak_memory_usage := Some bytes
| Some old -> peak_memory_usage := Some (max old bytes))
| Error _ -> ()
in
let rec warn_after_timeout delay =
warn_after_timeout_timer :=
Some
( S.Timer.on_delay delay @@ fun () ->
Log.warn "Test is still running: %S" test_title ;
warn_after_timeout delay )
in
let rec measure_memory_usage delay =
measure_memory_usage_timer :=
Some
( S.Timer.on_delay delay @@ fun () ->
match S.get_runner_pid ctx with
| None -> ()
| Some pid ->
measure_memory_usage_once pid ;
measure_memory_usage delay )
in
if Cli.Options.mem_warn <> None || Cli.Reports.record_mem_peak then
measure_memory_usage (1. /. Cli.Options.mem_poll_frequency) ;
if Cli.Options.warn_after_timeout > 0. then
warn_after_timeout Cli.Options.warn_after_timeout
in
let random_seed = ref None in
let on_message _ctx message =
S.Message.match_with message msg_seed ~default:(fun () -> ())
@@ fun seed -> random_seed := Some seed
in
let on_finish result =
Option.iter S.Timer.cancel !warn_after_timeout_timer ;
Option.iter S.Timer.cancel !measure_memory_usage_timer ;
let test_result : Test.test_result =
(match (Cli.Options.mem_warn, !peak_memory_usage) with
| None, _ | _, None -> ()
| Some threshold, Some peak ->
if peak >= threshold then
Log.warn
"Test used too much memory: %S (peak: %d bytes)"
test_title
peak) ;
match result with
| Ok test_result ->
{test_result with peak_memory_usage = !peak_memory_usage}
| Error error_message ->
Log.error "%s" error_message ;
let seed : Test.used_seed =
match !random_seed with
| None -> Used_fixed
| Some seed -> Used_random seed
in
{
test_result = Failed error_message;
seed;
peak_memory_usage = !peak_memory_usage;
}
in
on_response (Test_result test_result)
in
let on_term_timeout () =
Log.error
"Sending SIGTERM to test which is taking too long: %S"
test_title
in
let on_kill_timeout () =
Log.error
"Sending SIGKILL to test which is taking too long to stop: %S"
test_title
in
S.add_task
?term_timeout
?kill_timeout
~on_term_timeout
~on_kill_timeout
~on_start
~on_message
~on_finish
test_result_type
@@ fun ctx ->
(* Abuse [~temp_start] to insert something to execute in the context of the test itself.
This works because [temp_start] is executed just before the test function;
more precisely, it is executed after the seed is chosen. *)
let temp_start () =
(* If the test is using a random seed, the main process will need the seed
to tell the user how to reproduce in case of error. *)
(match Test.current_test_seed_specification () with
| Fixed _ -> ()
| Random ->
S.Message.send_to_scheduler ctx msg_seed (Test.current_test_seed ())) ;
Temp.start ()
in
(* Find the test to run, run it and return with the test result. *)
let test_result = run_test ~temp_start test_title in
(* Don't leave logs, they could be printed in case of error in the next test
(or in case of error in an [at_exit]). This is because it is the scheduler
that prints the test report which normally clears logs in single process. *)
Log.clear_error_context_queue () ;
test_result
let next_worker_id = ref 0
let current_worker_id = ref None
let run_multi_process
~(on_worker_available : unit -> (request * (response -> unit)) option)
~worker_count =
(* Register signal handlers meant for the scheduler process.
Doing that overrides existing handlers (i.e. those defined at toplevel
in the [Test] module). The latter are meant for worker processes.
So we store them in [old_sigint_behavior] and [old_sigterm_behavior]
in order to restore them in worker processes. *)
(* SIGINT is received in particular when the user presses Ctrl+C.
In that case terminals tend to send SIGINT to the process group,
so workers should receive SIGINT as well.
The scheduler shall stop starting new tasks,
but should not send SIGINT because that would be a duplicate
and tests would think that the user pressed Ctrl+C twice to force a kill. *)
let old_sigint_behavior =
Sys.(signal sigint)
(Signal_handle
(fun _ ->
(* If the user presses Ctrl+C again, let the program die immediately. *)
Sys.(set_signal sigint) Signal_default ;
S.stop ()))
in
(* SIGTERM is usually received programmatically.
Contrary to SIGINT, we do not clear the signal handler:
the equivalent of "a second SIGTERM to force quit" is SIGKILL. *)
let old_sigterm_behavior =
Sys.(signal sigterm) (Signal_handle (fun _ -> S.stop ()))
in
let on_empty_queue () =
match on_worker_available () with
| None -> ()
| Some (request, on_response) -> add_task_for_request request on_response
in
let on_worker_kill_timeout () =
Log.debug
"Send SIGKILL to worker which is still running despite not running any \
test"
in
let on_unexpected_worker_exit status =
Log.warn
"Worker %s while not running a test"
(S.show_process_status status)
in
let fork () =
let worker_id = !next_worker_id in
incr next_worker_id ;
let pid = Lwt_unix.fork () in
if pid = 0 then (
(* This is a child process.
Reset stuff that only makes sense in the scheduler (signal handlers),
and set stuff that is worker-specific. *)
Sys.(set_signal sigint) old_sigint_behavior ;
Sys.(set_signal sigterm) old_sigterm_behavior ;
Temp.set_pid (Unix.getpid ()) ;
current_worker_id := Some !next_worker_id ;
Log.set_current_worker_id worker_id ;
Log.clear_error_context_queue () ;
Option.iter
(fun filename ->
(* Workers log to [BASENAME-WORKER_ID.EXT] *)
let worker_filename =
Filename.(
concat
(dirname filename)
(remove_extension (basename filename)
^ "-" ^ string_of_int worker_id ^ extension filename))
in
Log.set_file worker_filename)
Cli.Logs.file) ;
pid
in
S.run
~worker_idle_timeout:Cli.Options.cleanup_timeout
~worker_kill_timeout:Cli.Options.cleanup_timeout
~on_worker_kill_timeout
~on_empty_queue
~on_unexpected_worker_exit
~fork
worker_count
let rec run_single_process ~on_worker_available =
Temp.set_pid (Unix.getpid ()) ;
match on_worker_available () with
| None -> ()
| Some (Run_test {test_title}, on_response) ->
let test_result = run_test test_title in
on_response (Test_result test_result) ;
run_single_process ~on_worker_available
let run ~on_worker_available ~worker_count continue =
(match worker_count with
| None -> run_single_process ~on_worker_available
| Some worker_count -> (
try run_multi_process ~on_worker_available ~worker_count
with exn -> internal_scheduler_error "%s" (Printexc.to_string exn))) ;
continue ()
let get_current_worker_id () = !current_worker_id
end
let run () = Test.run_with_scheduler (module Scheduler)
|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
mli
|
tezt-4.3.0/lib/main.mli
|
(*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2022 Nomadic Labs <contact@nomadic-labs.com> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
(** Run registered tests that should be run. *)
val run : unit -> unit
|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
ml
|
tezt-4.3.0/lib/process.ml
|
(*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2020-2022 Nomadic Labs <contact@nomadic-labs.com> *)
(* Copyright (c) 2020 Metastate AG <hello@metastate.dev> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
open Base
type hooks = Process_hooks.t = {
on_log : string -> unit;
on_spawn : string -> string list -> unit;
}
(* Information which is specific to processes that run on remote runners. *)
type remote = {runner : Runner.t; pid : int Lwt.t}
type t = {
id : int;
name : string;
command : string;
arguments : string list;
color : Log.Color.t;
lwt_process : Lwt_process.process_full;
mutable handle : unit Lwt.t;
log_status_on_exit : bool;
stdout : Echo.t;
stderr : Echo.t;
hooks : hooks option;
remote : remote option;
}
type failed_info = {
name : string;
command : string;
arguments : string list;
status : Unix.process_status option;
expect_failure : bool;
reason : String.t option;
}
exception Failed of failed_info
(** Converts the given [status] into a string explaining
why the corresponding process has stopped.
The resulting string is a subject-less sentence that
assumes that the subject will be prepended. *)
let status_to_reason = function
| Unix.WEXITED code -> Format.sprintf "exited with code %d" code
| Unix.WSIGNALED code -> Format.sprintf "was killed by signal %d" code
| Unix.WSTOPPED code -> Format.sprintf "was stopped by signal %d" code
let () =
Printexc.register_printer @@ function
| Failed {name; command; arguments; status; expect_failure; reason} ->
let reason =
Option.value
~default:
(match status with
| Some st -> status_to_reason st
| None -> Printf.sprintf "exited")
reason
in
Some
(Printf.sprintf
"%s%s %s (full command: %s)"
name
(if expect_failure then " was expected to fail," else "")
reason
(String.concat " " (List.map Log.quote_shell (command :: arguments))))
| _ -> None
let get_unique_name =
let name_counts = ref String_map.empty in
fun name ->
let index =
match String_map.find_opt name !name_counts with None -> 0 | Some i -> i
in
name_counts := String_map.add name (index + 1) !name_counts ;
name ^ "#" ^ string_of_int index
let fresh_id =
let next = ref 0 in
fun () ->
let id = !next in
incr next ;
id
module ID_map = Map.Make (Int)
let live_processes = ref ID_map.empty
let wait process =
let* status = process.lwt_process#status and* () = process.handle in
(* If we already removed [process] from [!live_processes], we already logged
the exit status. *)
if ID_map.mem process.id !live_processes then (
live_processes := ID_map.remove process.id !live_processes ;
if process.log_status_on_exit then
match status with
| WEXITED code -> Log.debug "%s exited with code %d." process.name code
| WSIGNALED code ->
Log.debug
"%s was killed by signal %s."
process.name
(Process_common.show_signal code)
| WSTOPPED code ->
Log.debug
"%s was stopped by signal %s."
process.name
(Process_common.show_signal code)) ;
return status
(* Read process outputs and log them.
Also take care of removing the process from [live_processes] on termination. *)
let handle_process ~log_output process =
let rec handle_output name ch echo lines =
let* line = Lwt_io.read_line_opt ch in
match line with
| None ->
Echo.close echo ;
let* () = Lwt_io.close ch in
return (List.rev lines)
| Some line ->
if log_output then Log.debug ~prefix:name ~color:process.color "%s" line ;
let lines =
match process.hooks with None -> lines | Some _ -> line :: lines
in
Echo.push echo line ;
(* TODO: here we assume that all lines end with "\n",
but it may not always be the case:
- there may be lines ending with "\r\n";
- the last line may not end with "\n" before the EOF. *)
Echo.push echo "\n" ;
handle_output name ch echo lines
in
let promise =
let* stdout_lines =
handle_output process.name process.lwt_process#stdout process.stdout []
and* stderr_lines =
handle_output process.name process.lwt_process#stderr process.stderr []
and* _ =
(* Note: [wait] calls [process.handle], which will eventually be [handle_process]
(this function), which calls [wait] (right here). So why is there no deadlock?
Initially, [process.handle] is set to [Lwt.return_unit].
[handle_process] is called only once, in [spawn_with_stdin], just before
setting [process.handle] to [handle_process].
[handle_process] calls [wait] immediately, and [wait] calls [process.handle]
immediately, so it is still [Lwt.return_unit].
This is too subtle though, we need to improve this. *)
wait process
in
match process.hooks with
| None -> unit
| Some hooks ->
List.iter hooks.on_log stdout_lines ;
List.iter hooks.on_log stderr_lines ;
unit
in
(* As long as the process is running, we don't want to stop reading its output.
So we return a non-cancelable promise.
This also makes sure that if [wait] is called twice, and one of the two
instances is canceled, the other instance will not also be canceled.
Indeed, canceling one instance of [wait] would cancel [process.handle],
which is also used by the other instance of [wait].
This can happen in particular if a test is [wait]ing for a process and
the user presses Ctrl+C, which triggers [clean_up], which calls [wait]. *)
Lwt.no_cancel promise
(** [to_key_equal_value kv_map], given that kv_map is {K1->V1; K2->V2}
returns the array ["K1=V1"; "K2=V2"]. See [parse_current_environment]
for a related function *)
let to_key_equal_value (kv_map : string String_map.t) : string array =
kv_map |> String_map.to_seq
|> Seq.map (fun (name, value) -> name ^ "=" ^ value)
|> Array.of_seq
let spawn_with_stdin ?runner ?(log_command = true) ?(log_status_on_exit = true)
?(log_output = true) ?name ?(color = Log.Color.FG.cyan)
?(env = String_map.empty) ?hooks command arguments =
let name = Option.value ~default:(get_unique_name command) name in
Option.iter (fun hooks -> hooks.on_spawn command arguments) hooks ;
if log_command then
Log.command ~color:Log.Color.bold ~prefix:name command arguments ;
let lwt_command =
match runner with
| None -> (command, Array.of_list (command :: arguments))
| Some runner ->
let local_env = String_map.bindings env in
let ssh, ssh_args =
Runner.wrap_with_ssh_pid runner {local_env; name = command; arguments}
in
(ssh, Array.of_list (ssh :: ssh_args))
in
let lwt_process =
match runner with
| None ->
let env =
(* Merge [current_env] and [env], choosing [env] on common keys: *)
String_map.union
(fun _ _ new_val -> Some new_val)
(Process_common.parse_current_environment ())
env
|> to_key_equal_value
in
Lwt_process.open_process_full ~env lwt_command
| Some _runner -> Lwt_process.open_process_full lwt_command
in
let remote =
let open Lwt.Infix in
match runner with
| None -> None
| Some runner ->
let pid =
Lwt_io.read_line lwt_process#stdout >|= fun pid ->
match int_of_string_opt pid with
| Some pid -> pid
| None ->
raise
(Failed
{
name;
command;
arguments;
status = None;
expect_failure = false;
reason = Some "unable to read remote process PID";
})
in
Some {runner; pid}
in
let process =
{
id = fresh_id ();
name;
command;
arguments;
color;
lwt_process;
handle = Lwt.return_unit;
log_status_on_exit;
stdout = Echo.create ();
stderr = Echo.create ();
hooks;
remote;
}
in
live_processes := ID_map.add process.id process !live_processes ;
process.handle <- handle_process ~log_output process ;
(process, process.lwt_process#stdin)
let spawn ?runner ?log_command ?log_status_on_exit ?log_output ?name ?color ?env
?hooks command arguments =
let process, stdin =
spawn_with_stdin
?runner
?log_command
?log_status_on_exit
?log_output
?name
?color
?env
?hooks
command
arguments
in
Background.register (Lwt_io.close stdin) ;
process
(* Propagate the signal in case of remote runner. *)
let signal_remote_if_needed signal process =
match process.remote with
| None -> ()
| Some {pid; runner} ->
let open Lwt in
let open Infix in
Background.register
( ( pid >|= fun pid ->
let command = "kill" in
let arguments =
["-" ^ string_of_int signal; "-P"; string_of_int pid]
in
let shell =
Runner.Shell.(
redirect_stderr (cmd [] command arguments) "/dev/null")
in
Runner.wrap_with_ssh runner shell )
>>= fun (ssh, ssh_args) ->
let cmd = (ssh, Array.of_list (ssh :: ssh_args)) in
Lwt_process.exec cmd >>= fun _ -> Lwt.return_unit )
let kill (process : t) =
Log.debug "Send SIGKILL to %s." process.name ;
(* 9 is the code for SIGKILL *)
signal_remote_if_needed 9 process ;
process.lwt_process#terminate
let terminate ?timeout (process : t) =
Log.debug "Send SIGTERM to %s." process.name ;
(* 15 is the code for SIGTERM *)
signal_remote_if_needed 15 process ;
(match process.remote with
| None ->
process.lwt_process#kill (if Sys.win32 then Sys.sigkill else Sys.sigterm)
| Some _ ->
(* Do not send SIGTERM to SSH. It will die on its own once the
remote process exits, or we will kill it after a timeout.
Note that [signal_remote_if_needed] did not send SIGTERM to SSH,
it sent it (through SSH) to the process that SSH spawned on the remote. *)
()) ;
match timeout with
| None -> ()
| Some timeout ->
let wait_and_ignore_status =
let* (_ : Unix.process_status) = wait process in
unit
in
let kill_after_timeout =
let* () = Lwt_unix.sleep timeout in
kill process ;
unit
in
Background.register
(Lwt.pick [wait_and_ignore_status; kill_after_timeout])
let pid (process : t) = process.lwt_process#pid
let validate_status ?(expect_failure = false) status =
match status with
| Unix.WEXITED n
when (n = 0 && not expect_failure) || (n <> 0 && expect_failure) ->
Ok ()
| _ -> Error (`Invalid_status (status_to_reason status))
let check ?(expect_failure = false) process =
let* status = wait process in
match validate_status ~expect_failure status with
| Ok () -> unit
| Error (`Invalid_status reason) ->
raise
(Failed
{
name = process.name;
command = process.command;
arguments = process.arguments;
status = Some status;
expect_failure;
reason = Some reason;
})
let run ?log_status_on_exit ?name ?color ?env ?hooks ?expect_failure command
arguments =
spawn ?log_status_on_exit ?name ?color ?env ?hooks command arguments
|> check ?expect_failure
let clean_up ?(timeout = Cli.Options.cleanup_timeout) () =
let list = ID_map.bindings !live_processes |> List.map snd in
List.iter (terminate ~timeout) list ;
Lwt_list.iter_p
(fun process ->
let* _ = wait process in
unit)
list
let stdout process = Echo.get_lwt_channel process.stdout
let stderr process = Echo.get_lwt_channel process.stderr
let name (process : t) = process.name
let check_and_read ?expect_failure ~channel_getter process =
let* () = check ?expect_failure process
and* output = Lwt_io.read (channel_getter process) in
return output
let check_and_read_both ?expect_failure process =
let* () = check ?expect_failure process
and* out = Lwt_io.read (stdout process)
and* err = Lwt_io.read (stderr process) in
return (out, err)
let check_and_read_stdout = check_and_read ~channel_getter:stdout
let check_and_read_stderr = check_and_read ~channel_getter:stderr
let run_and_read_stdout ?log_status_on_exit ?name ?color ?env ?hooks
?expect_failure command arguments =
let process =
spawn ?log_status_on_exit ?name ?color ?env ?hooks command arguments
in
check_and_read_stdout ?expect_failure process
let run_and_read_stderr ?log_status_on_exit ?name ?color ?env ?hooks
?expect_failure command arguments =
let process =
spawn ?log_status_on_exit ?name ?color ?env ?hooks command arguments
in
check_and_read_stdout ?expect_failure process
let check_error ?exit_code ?msg process =
let* status = wait process in
let* err_msg = Lwt_io.read (stderr process) in
let error =
{
name = process.name;
command = process.command;
arguments = process.arguments;
status = Some status;
expect_failure = true;
reason = None;
}
in
match status with
| WEXITED n -> (
match exit_code with
| None when n = 0 ->
raise (Failed {error with reason = Some " with any non-zero code"})
| Some exit_code when n <> exit_code ->
let reason = sf " with code %d but failed with code %d" exit_code n in
raise (Failed {error with reason = Some reason})
| _ ->
Option.iter
(fun msg ->
if err_msg =~! msg then
raise
(Failed
{
error with
reason =
Some
(sf " but failed with stderr =~! %s" (show_rex msg));
}))
msg ;
unit)
| _ -> raise (Failed error)
let program_path program =
Lwt.catch
(fun () ->
let* path =
if Sys.win32 then run_and_read_stdout "where.exe" [program]
else run_and_read_stdout "sh" ["-c"; "command -v " ^ program]
in
return (Some (String.trim path)))
(fun _ -> return None)
|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
mli
|
tezt-4.3.0/lib/process.mli
|
(*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2020-2022 Nomadic Labs <contact@nomadic-labs.com> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
(** This module is only available in [tezt], not in [tezt.core] and [tezt.js]. *)
(** A process which was {!spawn}ed. *)
type t
(** Process can have some hooks attached when {!spawn}ed. *)
type hooks = Process_hooks.t = {
on_log : string -> unit;
(** A hook that is called with every line that is being logged. *)
on_spawn : string -> string list -> unit;
(** A hook that is called whenever a process is being spawned. The first
parameter is the command and the second are its arguments. *)
}
(** Create a process which starts running in the background.
Usage: [spawn command arguments]
If [log_command] is [true] (which is the default), log the command
being executed.
If [log_status_on_exit] is [true] (which is the default), log the exit code
when the process terminates.
If [log_output] is [true] (which is the default), log the [stdout] and
[stderr] output.
Parameter [name] specifies the prefix (in brackets) that is added to
each logged output line. Parameter [color] specifies the color of those
output lines.
Parameter [hooks] allows to attach some hooks to the process.
Warning: if you use [hooks], all the process output is stored in memory
until it finishes. So this can use a lot of memory. Also, note that [stdout]
is sent to the hook first, then [stderr]. The two outputs are not interleaved.
This is to make it more predictable for regression tests.
Note that this function can only be called if [Background.register] is
allowed (which is the case inside functions given to [Test.register]).
Parameter [runner] specifies the runner on which to run the process.
If unspecified, the process runs locally. Otherwise, it runs on the given
runner using SSH.
Example: [spawn "git" [ "log"; "-p" ]] *)
val spawn :
?runner:Runner.t ->
?log_command:bool ->
?log_status_on_exit:bool ->
?log_output:bool ->
?name:string ->
?color:Log.Color.t ->
?env:string Base.String_map.t ->
?hooks:hooks ->
string ->
string list ->
t
(** Same as {!spawn}, but with a channel to send data to the process [stdin]. *)
val spawn_with_stdin :
?runner:Runner.t ->
?log_command:bool ->
?log_status_on_exit:bool ->
?log_output:bool ->
?name:string ->
?color:Log.Color.t ->
?env:string Base.String_map.t ->
?hooks:hooks ->
string ->
string list ->
t * Lwt_io.output_channel
(** Send SIGTERM to a process.
If [timeout] is specified, this registers a background promise that
causes SIGKILL to be sent if the process does not terminate
after [timeout] seconds. *)
val terminate : ?timeout:float -> t -> unit
(** Send SIGKILL to a process. *)
val kill : t -> unit
(** Wait until a process terminates and return its status. *)
val wait : t -> Unix.process_status Lwt.t
(** Check the exit status of a process.
If [not expect_failure] and exit code is not 0,
or if [expect_failure] and exit code is 0,
or if the process was killed, return [Error (`Invalid_status reason)].
Else, return [Ok ()]. *)
val validate_status :
?expect_failure:bool ->
Unix.process_status ->
(unit, [`Invalid_status of string]) result
(** Wait until a process terminates and check its status.
See [validate_status] to see status validation rules. *)
val check : ?expect_failure:bool -> t -> unit Lwt.t
(** Wait until a process terminates and check its status.
If [exit_code] is different than [t] exit code,
or if [msg] does not match the stderr output, fail the test.
If [exit_code] is not specified, any non-zero code is accepted.
If no [msg] is given, the stderr is ignored.*)
val check_error : ?exit_code:int -> ?msg:Base.rex -> t -> unit Lwt.t
(** Wait until a process terminates and read its standard output.
Fail the test if the process failed, unless [expect_failure],
in which case fail if the process succeeds. *)
val check_and_read_stdout : ?expect_failure:bool -> t -> string Lwt.t
(** Wait until a process terminates and read its standard error.
Fail the test if the process failed, unless [expect_failure],
in which case fail if the process succeeds. *)
val check_and_read_stderr : ?expect_failure:bool -> t -> string Lwt.t
(** Wait until a process terminates and read both its standard output
and its standard error.
Fail the test if the process failed, unless [expect_failure],
in which case fail if the process succeeds. *)
val check_and_read_both : ?expect_failure:bool -> t -> (string * string) Lwt.t
(** Spawn a process, wait for it to terminate, and check its status. *)
val run :
?log_status_on_exit:bool ->
?name:string ->
?color:Log.Color.t ->
?env:string Base.String_map.t ->
?hooks:hooks ->
?expect_failure:bool ->
string ->
string list ->
unit Lwt.t
(** Terminate all live processes created using {!spawn} and wait for them to terminate.
[timeout] is passed to [terminate], with a default value of [60.] (one minute). *)
val clean_up : ?timeout:float -> unit -> unit Lwt.t
(** Channel from which you can read the standard output of a process. *)
val stdout : t -> Lwt_io.input_channel
(** Channel from which you can read the standard error output of a process. *)
val stderr : t -> Lwt_io.input_channel
(** Get the name which was given to {!spawn}. *)
val name : t -> string
(** Get the PID of the given process. *)
val pid : t -> int
(** Spawn a process such as [run] and return its standard output.
Fail the test if the process failed, unless [expect_failure],
in which case fail if the process succeeds. *)
val run_and_read_stdout :
?log_status_on_exit:bool ->
?name:string ->
?color:Log.Color.t ->
?env:string Base.String_map.t ->
?hooks:hooks ->
?expect_failure:bool ->
string ->
string list ->
string Lwt.t
(** Spawn a process such as [run] and return its standard error.
Fail the test if the process failed, unless [expect_failure],
in which case fail if the process succeeds. *)
val run_and_read_stderr :
?log_status_on_exit:bool ->
?name:string ->
?color:Log.Color.t ->
?env:string Base.String_map.t ->
?hooks:hooks ->
?expect_failure:bool ->
string ->
string list ->
string Lwt.t
(** [program_path p] returns [Some path] if the shell command [command -v p]
succeeds and prints [path]. Returns [None] otherwise. *)
val program_path : string -> string option Lwt.t
|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
ml
|
tezt-4.3.0/lib/process_common.ml
|
(*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2020-2022 Nomadic Labs <contact@nomadic-labs.com> *)
(* Copyright (c) 2020 Metastate AG <hello@metastate.dev> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
open Base
let show_signal code =
if code = Sys.sigabrt then "SIGABRT"
else if code = Sys.sigalrm then "SIGALRM"
else if code = Sys.sigfpe then "SIGFPE"
else if code = Sys.sighup then "SIGHUP"
else if code = Sys.sigill then "SIGILL"
else if code = Sys.sigint then "SIGINT"
else if code = Sys.sigkill then "SIGKILL"
else if code = Sys.sigpipe then "SIGPIPE"
else if code = Sys.sigquit then "SIGQUIT"
else if code = Sys.sigsegv then "SIGSEGV"
else if code = Sys.sigterm then "SIGTERM"
else if code = Sys.sigusr1 then "SIGUSR1"
else if code = Sys.sigusr2 then "SIGUSR2"
else if code = Sys.sigchld then "SIGCHLD"
else if code = Sys.sigcont then "SIGCONT"
else if code = Sys.sigstop then "SIGSTOP"
else if code = Sys.sigtstp then "SIGTSTP"
else if code = Sys.sigttin then "SIGTTIN"
else if code = Sys.sigttou then "SIGTTOU"
else if code = Sys.sigvtalrm then "SIGVTALRM"
else if code = Sys.sigprof then "SIGPROF"
else if code = Sys.sigbus then "SIGBUS"
else if code = Sys.sigpoll then "SIGPOLL"
else if code = Sys.sigsys then "SIGSYS"
else if code = Sys.sigtrap then "SIGTRAP"
else if code = Sys.sigurg then "SIGURG"
else if code = Sys.sigxcpu then "SIGXCPU"
else if code = Sys.sigxfsz then "SIGXFSZ"
else string_of_int code
let parse_current_environment : unit -> string String_map.t =
fun () ->
let parse_env_kv key_value : (string * string) option =
String.index_opt key_value '='
|> Option.map (fun i ->
( Re.Str.string_before key_value i,
Re.Str.string_after key_value (i + 1) ))
in
Unix.environment () |> Array.to_seq
|> Seq.filter_map parse_env_kv
|> String_map.of_seq
|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
mli
|
tezt-4.3.0/lib/process_common.mli
|
(*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2021-2022 Nomadic Labs <contact@nomadic-labs.com> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
(** Common process functions that can be shared with alternate {!Process}
backends. *)
(** Convert a signal to a string like ["SIGTERM"]. *)
val show_signal : int -> string
(** [parse_current_environment ()], given that the current environment
is ["K1=V2; K2=V2"] (see [export] in a terminal)
returns a map [{K1->V1; K2->V2}]. See [to_key_equal_value]
for a related function. *)
val parse_current_environment : unit -> string Base.String_map.t
|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
ml
|
tezt-4.3.0/lib/runner.ml
|
(*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2021-2022 Nomadic Labs <contact@nomadic-labs.com> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
type t = {
id : int;
address : string;
ssh_alias : string option;
ssh_user : string option;
ssh_port : int option;
ssh_id : string option;
options : string list;
}
let local_public_ip = ref "127.0.0.1"
let get_local_public_ip () = !local_public_ip
let set_local_public_ip ip = local_public_ip := ip
let next_id = ref 0
let create ?ssh_alias ?ssh_user ?ssh_port ?ssh_id ?(options = []) ~address () =
let id = !next_id in
incr next_id ;
{id; address; ssh_alias; ssh_user; ssh_port; ssh_id; options}
let address ?(hostname = false) ?from runner =
match (from, runner) with
| None, None -> if hostname then "localhost" else "127.0.0.1"
| None, Some host -> host.address
| Some _peer, None -> get_local_public_ip ()
| Some peer, Some host ->
if peer.address = host.address then "127.0.0.1" else host.address
(* With ssh-agent, the environment variables SSH_AGENT_PID and SSH_AUTH_SOCK
must be added in the environment. *)
let ssh_env () =
match (Sys.getenv_opt "SSH_AGENT_PID", Sys.getenv_opt "SSH_AUTH_SOCK") with
| Some agent, Some sock ->
[|"SSH_AGENT_PID=" ^ agent; "SSH_AUTH_SOCK=" ^ sock|]
| _ ->
(* Here, we assume we don't have an agent running. *)
[||]
module Shell = struct
type command = {
local_env : (string * string) list;
name : string;
arguments : string list;
}
type t =
| Cmd of command
| Seq of t * t
| Echo_pid
| Redirect_stdout of t * string
| Redirect_stderr of t * string
| Or_echo_false of t
let string_of_env env =
List.fold_right
(fun (var, value) str_env -> var ^ "=" ^ value ^ " " ^ str_env)
env
""
let string_of_cmd cmd =
let env = string_of_env cmd.local_env in
let cmd = Log.quote_shell_command cmd.name cmd.arguments in
env ^ cmd
let rec to_string ?(context = `top) shell =
let with_parentheses s =
match context with
| `top ->
(* No need for parentheses in the toplevel context. *)
s
| `operator -> "(" ^ s ^ ")"
in
let in_operator = to_string ~context:`operator in
match shell with
| Cmd cmd ->
(* Commands do not need parentheses, they have the highest precedence. *)
string_of_cmd cmd
| Seq (cmd1, cmd2) ->
with_parentheses @@ in_operator cmd1 ^ " && " ^ in_operator cmd2
| Echo_pid -> "echo $$"
| Redirect_stdout (cmd, file) ->
with_parentheses @@ in_operator cmd ^ " > " ^ Log.quote_shell file
| Redirect_stderr (cmd, file) ->
with_parentheses @@ in_operator cmd ^ " 2> " ^ Log.quote_shell file
| Or_echo_false cmd ->
with_parentheses @@ in_operator cmd ^ " || echo false"
let cmd local_env name arguments = Cmd {local_env; name; arguments}
let seq cmd_1 cmd_2 = Seq (cmd_1, cmd_2)
let redirect_stdout shell file = Redirect_stdout (shell, file)
let redirect_stderr shell file = Redirect_stderr (shell, file)
let or_echo_false shell = Or_echo_false shell
end
let wrap_with_ssh runner shell =
let cmd = Shell.to_string shell in
let ssh_args =
(match runner.ssh_alias with
| None -> [runner.address]
| Some alias -> [alias])
@ (match runner.ssh_user with None -> [] | Some user -> ["-l"; user])
@ (match runner.ssh_port with
| None -> []
| Some port -> ["-p"; string_of_int port])
@
match runner.ssh_id with
| None -> []
| Some id -> ["-o"; "IdentitiesOnly=yes"; "-i"; id]
in
("ssh", runner.options @ ssh_args @ [cmd])
let wrap_with_ssh_pid runner shell =
let open Shell in
wrap_with_ssh
runner
(seq Echo_pid (cmd shell.local_env "exec" (shell.name :: shell.arguments)))
module Sys = struct
type error = {
address : string option;
command : string;
exit_code : Unix.process_status;
stderr : string;
}
exception Remote_error of error
let show_error {address; command; exit_code; stderr} =
let address_msg =
match address with
| None -> "on localhost"
| Some address -> "on " ^ address
in
let exit_msg =
match exit_code with
| Unix.WEXITED code -> "exited with code " ^ string_of_int code
| Unix.WSIGNALED signal -> "was killed by signal " ^ string_of_int signal
| Unix.WSTOPPED signal -> "was stopped by signal " ^ string_of_int signal
in
let stderr_msg = if stderr = "" then "" else " (" ^ stderr ^ ")" in
command ^ " " ^ exit_msg ^ stderr_msg ^ " " ^ address_msg ^ "."
let () =
Printexc.register_printer @@ function
| Remote_error error -> Some (show_error error)
| _ -> None
(* WARNING: synchronous method so it can block. *)
let run_unix_with_ssh runner shell =
let ssh, ssh_args = wrap_with_ssh runner shell in
let unix_cmd = String.concat " " (ssh :: ssh_args) in
let ssh_env = ssh_env () in
Unix.open_process_full unix_cmd ssh_env
let get_stderr (_, _, stderr) = try input_line stderr with End_of_file -> ""
let get_stdout (stdout, _, _) = try input_line stdout with End_of_file -> ""
let file_exists ?runner file =
match runner with
| None -> Sys.file_exists file
| Some runner -> (
let command = "test" in
let arguments = ["-e"; file] in
let shell = Shell.or_echo_false (Shell.cmd [] command arguments) in
let process = run_unix_with_ssh runner shell in
let stdout = get_stdout process in
let stderr = get_stderr process in
let status = Unix.close_process_full process in
match status with
| Unix.WEXITED 0 -> stdout <> "false"
| error ->
let error =
{
command;
address = Some runner.address;
exit_code = error;
stderr;
}
in
raise (Remote_error error))
let is_directory ?runner path =
match runner with
| None -> Sys.is_directory path
| Some runner -> (
let command = "test" in
let arguments = ["-d"; path] in
let shell = Shell.or_echo_false (Shell.cmd [] command arguments) in
let process = run_unix_with_ssh runner shell in
let stdout = get_stdout process in
let stderr = get_stderr process in
let status = Unix.close_process_full process in
match status with
| Unix.WEXITED 0 -> stdout <> "false"
| error ->
let error =
{
command;
address = Some runner.address;
exit_code = error;
stderr;
}
in
raise (Remote_error error))
let mkdir ?runner ?(perms = 0o755) dir =
match runner with
| None -> Unix.mkdir dir perms
| Some runner -> (
let command = "mkdir" in
let arguments = ["-m"; Format.sprintf "%o" perms; dir] in
let shell = Shell.cmd [] command arguments in
let process = run_unix_with_ssh runner shell in
let stderr = get_stderr process in
let status = Unix.close_process_full process in
match status with
| Unix.WEXITED 0 -> ()
| error ->
let error =
{
command;
address = Some runner.address;
exit_code = error;
stderr;
}
in
raise (Remote_error error))
let readdir ?runner dir =
match runner with
| None -> Sys.readdir dir
| Some runner -> (
let command = "ls" in
let arguments = ["-1"; dir] in
let shell = Shell.cmd [] command arguments in
let ((stdout, _, _) as process) = run_unix_with_ssh runner shell in
let rec read_until_eof input acc =
try
let line = input_line input in
read_until_eof input (line :: acc)
with End_of_file -> Array.of_list acc
in
let files = read_until_eof stdout [] in
let stderr = get_stderr process in
let status = Unix.close_process_full process in
match status with
| Unix.WEXITED 0 -> files
| error ->
let error =
{
command;
address = Some runner.address;
exit_code = error;
stderr;
}
in
raise (Remote_error error))
let remove ?runner file =
match runner with
| None -> Sys.remove file
| Some runner -> (
let command = "rm" in
let arguments = [file] in
let shell = Shell.cmd [] command arguments in
let process = run_unix_with_ssh runner shell in
let stderr = get_stderr process in
let status = Unix.close_process_full process in
match status with
| Unix.WEXITED 0 -> ()
| error ->
let error =
{
command;
address = Some runner.address;
exit_code = error;
stderr;
}
in
raise (Remote_error error))
let rm_rf runner file =
let command = "rm" in
let arguments = ["-rf"; file] in
let shell = Shell.cmd [] command arguments in
let process = run_unix_with_ssh runner shell in
let stderr = get_stderr process in
let status = Unix.close_process_full process in
match status with
| Unix.WEXITED 0 -> ()
| error ->
let error =
{command; address = Some runner.address; exit_code = error; stderr}
in
raise (Remote_error error)
let rmdir ?runner dir =
match runner with
| None -> Unix.rmdir dir
| Some runner -> (
let command = "rmdir" in
let arguments = [dir] in
let shell = Shell.cmd [] command arguments in
let process = run_unix_with_ssh runner shell in
let stderr = get_stderr process in
let status = Unix.close_process_full process in
match status with
| Unix.WEXITED 0 -> ()
| error ->
let error =
{
command;
address = Some runner.address;
exit_code = error;
stderr;
}
in
raise (Remote_error error))
let mkfifo ?runner ?(perms = 755) pipe =
match runner with
| None -> Unix.mkfifo pipe perms
| Some runner -> (
let command = "mkfifo" in
let arguments = ["-m"; Format.sprintf "%o" perms; pipe] in
let shell = Shell.cmd [] command arguments in
let process = run_unix_with_ssh runner shell in
let stderr = get_stderr process in
let status = Unix.close_process_full process in
match status with
| Unix.WEXITED 0 -> ()
| error ->
let error =
{
command;
address = Some runner.address;
exit_code = error;
stderr;
}
in
raise (Remote_error error))
end
|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
mli
|
tezt-4.3.0/lib/runner.mli
|
(*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2021-2022 Nomadic Labs <contact@nomadic-labs.com> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
(** Runner specifications for processes spawned remotely using SSH. *)
(** Connection information for a runner.
See {!create}. *)
type t = private {
id : int;
address : string;
ssh_alias : string option;
ssh_user : string option;
ssh_port : int option;
ssh_id : string option;
options : string list;
}
(** Create a runner.
This function does not start any SSH connection, it only stores
SSH connection information in a record.
- [ssh_alias] is the alias in the ssh config file.
- [ssh_user] is the username on the remote machine.
- [ssh_port] is the port on the remote machine.
- [ssh_id] is the path to the identity file.
- [options] is a list of additional arguments to pass to SSH before other arguments.
- [address] is the IP address of the remote machine. *)
val create :
?ssh_alias:string ->
?ssh_user:string ->
?ssh_port:int ->
?ssh_id:string ->
?options:string list ->
address:string ->
unit ->
t
(** Get the IP address of the local machine as perceived by other runners.
Use this if you need a runner to reach a process that is running on the
local machine.
This returns ["127.0.0.1"] by default, but you can set it with
{!set_local_public_ip}. *)
val get_local_public_ip : unit -> string
(** Set the IP address of the local machine as perceived by other runners. *)
val set_local_public_ip : string -> unit
(** Get the IP / DNS address of a runner.
Usage: [address ~from runner]
Return the address at which a source node [from] can contact [runner].
If the source node [from] is not specified, return the [address] of [runner]
as given to {!create}. If [runner] itself is [None], return ["127.0.0.1"]
or ["localhost"] if the [hostname] variable is set to true (default false).
If [from] is specified:
- if [runner] is [None], return [get_local_public_ip ()];
- if [from] and [runner] are the same runner, return ["127.0.0.1"];
- else, return the [address] of [runner]. *)
val address : ?hostname:bool -> ?from:t -> t option -> string
module Shell : sig
(** Shell command representation.
This module is used for the subset of the shell language that is
needed to operate remote runners through SSH. It makes sure that
shell command are properly quoted. *)
(** Commands.
Commands execute a program (whose executable name is [name]),
with some [arguments], possibly with some specific environment
variables [local_env] to add to the current environment. *)
type command = {
local_env : (string * string) list;
name : string;
arguments : string list;
}
(** Shell programs. *)
type t =
| Cmd of command (** run a command *)
| Seq of t * t (** run something, then something else ([;]) *)
| Echo_pid (** echo the current process PID ([echo $$]) *)
| Redirect_stdout of t * string (** redirect stdout to a file ([>]) *)
| Redirect_stderr of t * string (** redirect stderr to a file ([2>]) *)
| Or_echo_false of t
(** run something, if it fails, print "false" ([|| echo false]) *)
(** Convert a shell program into a string.
The result is quoted using shell syntax.
[context] specifies whether parentheses are needed:
- [`top] means no parentheses are needed (default);
- [`operator] means parentheses may be needed because this command is
inside of an operator such as [;] or [||]. *)
val to_string : ?context:[`operator | `top] -> t -> string
(** Make a command to execute a program.
Usage: [cmd local_env name arguments]
Same as: [Cmd { local_env; name; arguments }] *)
val cmd : (string * string) list -> string -> string list -> t
(** Make a sequence.
Usage: [seq command_1 command_2]
Same as: [Seq (command_1, command_2)] *)
val seq : t -> t -> t
(** Make an stdout redirection.
Usage: [redirect_stdout command path]
Same as: [Redirect_stdout (command, path)] *)
val redirect_stdout : t -> string -> t
(** Make an stderr redirection.
Usage: [redirect_stderr command path]
Same as: [Redirect_stderr (command, path)] *)
val redirect_stderr : t -> string -> t
(** Make a shell program that prints "false" if another program fails.
Usage: [or_echo_false command]
Same as: [Or_echo_false command] *)
val or_echo_false : t -> t
end
(** Wrap a shell command into an SSH call.
Usage: [wrap_with_ssh runner shell]
Return [(name, arguments)] where [name] is ["ssh"] and [arguments]
are arguments to pass to SSH to execute [shell] on [runner]. *)
val wrap_with_ssh : t -> Shell.t -> string * string list
(** Same as {!wrap_with_ssh}, but print the PID on stdout first.
The PID can be used later on to, for instance, kill the remote process.
Indeed, killing the local SSH process will not necessarily kill
the remote process. *)
val wrap_with_ssh_pid : t -> Shell.command -> string * string list
module Sys : sig
(** Extension to [Stdlib.Sys] that can also execute on remote runners.
Most functions from this module just call their [Stdlib.Sys] equivalent
when [runner] is not specified. When [runner] is specified, they
instead use SSH to execute a shell command remotely with a similar effect. *)
(** Errors that can occur when executing a [Sys] command on a remote runner. *)
type error
(** Exception raised when failing to execute a [Sys] command remotely.
This is not raised when running a command without a [runner].
Instead, [Sys_error] is raised. *)
exception Remote_error of error
(** Convert an error to an error message. *)
val show_error : error -> string
(** Check if a file exists on the system.
For the local version, see {{: https://ocaml.org/api/Sys.html} Sys.file_exists}. *)
val file_exists : ?runner:t -> string -> bool
(** Create a new directory.
For the local version, see {{: https://ocaml.org/api/Unix.html} Unix.mkdir}. *)
val mkdir : ?runner:t -> ?perms:int -> string -> unit
(** Check if a file exists and is a directory.
For the local version, see {{: https://ocaml.org/api/Sys.html} Sys.is_directory}. *)
val is_directory : ?runner:t -> string -> bool
(** Return the contents of a directory.
For the local version, see {{: https://ocaml.org/api/Sys.html} Sys.readdir}. *)
val readdir : ?runner:t -> string -> string array
(** Remove a file.
For the local version, see {{: https://ocaml.org/api/Sys.html} Sys.remove}. *)
val remove : ?runner:t -> string -> unit
(** Remove recursively with [rm -rf].
Only implemented for remote runners. *)
val rm_rf : t -> string -> unit
(** Remove a directory.
For the local version, see {{: https://ocaml.org/api/Unix.html} Unix.rmdir}. *)
val rmdir : ?runner:t -> string -> unit
(** Create a named pipe.
For the local version, see {{: https://ocaml.org/api/Unix.html} Unix.mkfifo}. *)
val mkfifo : ?runner:t -> ?perms:int -> string -> unit
end
|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
ml
|
tezt-4.3.0/lib/temp.ml
|
(*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2020-2022 Nomadic Labs <contact@nomadic-labs.com> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
open Base
(* Private type to represent a file system. It's used by [clean_up].
[parents] contains the list of parent directories that were created.
[cleanup] will delete them only if they are empty.
If [a/b] and [a/b/c] needed to be created, then [a/b] is after [a/b/c] in
this list, i.e. descendants come before parents. *)
type file_system = {
parents : string list;
dirs : string list;
files : string list;
}
(* Associate one runner with its remote file system. *)
module Runner_map = Map.Make (struct
type t = Runner.t option
let compare = Option.compare compare
end)
let filesystems = ref Runner_map.empty
let get_fs ?runner () =
let fs = Runner_map.find_opt runner !filesystems in
match fs with None -> {parents = []; dirs = []; files = []} | Some fs -> fs
let next_name = ref 0
let pid = ref 0
let set_pid value = pid := value
let base_main_dir () = "tezt-" ^ string_of_int !pid
(* [add_file], [add_dir] and [add_parent] select the file system to use.*)
let add_file ?runner file =
let fs = get_fs ?runner () in
let old_files = fs.files in
filesystems :=
Runner_map.add runner {fs with files = file :: old_files} !filesystems
let add_dir ?runner dir =
let fs = get_fs ?runner () in
let old_dirs = fs.dirs in
filesystems :=
Runner_map.add runner {fs with dirs = dir :: old_dirs} !filesystems
let add_parent ?runner parent =
let fs = get_fs ?runner () in
let old_parents = fs.parents in
filesystems :=
Runner_map.add runner {fs with parents = parent :: old_parents} !filesystems
let fresh_main_dir () =
let index = !next_name in
incr next_name ;
Filename.get_temp_dir_name () // base_main_dir () // string_of_int index
let main_dir_ref = ref @@ fresh_main_dir ()
let main_dir () = !main_dir_ref
let file_aux ?runner ?(perms = 0o755) base_name =
let filename = main_dir () // base_name in
let rec create_parent filename =
let parent = Filename.dirname filename in
if String.length parent < String.length filename then (
create_parent parent ;
if not (Runner.Sys.file_exists ?runner parent) then (
Runner.Sys.mkdir ?runner ~perms parent ;
add_parent ?runner parent))
in
create_parent filename ;
filename
let allowed = ref false
let check_allowed fname arg =
if not !allowed then (
Printf.eprintf
"Error: Temp.%s %S: not allowed outside of Test.run\n%!"
fname
arg ;
exit 1)
let file ?runner ?perms base_name =
check_allowed "file" base_name ;
let filename = file_aux ?runner ?perms base_name in
add_file ?runner filename ;
filename
let dir ?runner ?(perms = 0o755) base_name =
check_allowed "dir" base_name ;
let filename = file_aux ?runner ~perms base_name in
if not (Runner.Sys.file_exists ?runner filename) then (
Runner.Sys.mkdir ?runner ~perms filename ;
add_dir ?runner filename) ;
filename
let rec remove_recursively filename =
match (Unix.lstat filename).st_kind with
| exception Unix.Unix_error (error, _, _) ->
Log.warn
"Failed to read file type for %s: %s"
filename
(Unix.error_message error)
| S_REG | S_LNK | S_FIFO | S_SOCK -> (
(* It is particularly important to not recursively delete symbolic links
to directories but to remove the links instead. *)
try Sys.remove filename
with Sys_error error ->
Log.warn "Failed to remove %s: %s" filename error)
| S_DIR -> (
match Sys.readdir filename with
| exception Sys_error error ->
Log.warn "Failed to read %s: %s" filename error
| contents -> (
let contents = Array.map (Filename.concat filename) contents in
Array.iter remove_recursively contents ;
try Unix.rmdir filename
with Unix.Unix_error (error, _, _) ->
Log.warn
"Failed to remove directory %s: %s"
filename
(Unix.error_message error)))
| S_CHR -> Log.warn "Will not remove character device: %s" filename
| S_BLK -> Log.warn "Will not remove block device: %s" filename
let start () =
if !allowed then invalid_arg "Temp.start: a test is already running" ;
main_dir_ref := fresh_main_dir () ;
allowed := true ;
!main_dir_ref
let stop () = allowed := false
let clean_up_aux (runner : Runner.t option) runner_fs =
List.iter
(fun filename ->
if Runner.Sys.file_exists ?runner filename then
Runner.Sys.remove ?runner filename)
runner_fs.files ;
List.iter
(fun dirname ->
if
Runner.Sys.file_exists ?runner dirname
&& Runner.Sys.is_directory ?runner dirname
then
match runner with
| None -> remove_recursively dirname
| Some runner -> Runner.Sys.rm_rf runner dirname)
runner_fs.dirs ;
List.iter
(fun dirname ->
match Runner.Sys.readdir ?runner dirname with
| [||] -> Runner.Sys.rmdir ?runner dirname
| _ ->
let dirtype =
if Option.is_some runner then "Remote directory" else "Directory"
in
Log.warn "%s is not empty %s" dirtype dirname)
runner_fs.parents
let clean_up () =
stop () ;
let filesystems_to_clean = !filesystems in
filesystems := Runner_map.empty ;
Runner_map.iter clean_up_aux filesystems_to_clean
let check () =
let tmp_dir = Filename.get_temp_dir_name () in
match Sys.readdir tmp_dir with
| exception Sys_error _ -> ()
| contents ->
let tezt_rex = rex "^tezt-[0-9]+$" in
let check_file filename =
if filename =~ tezt_rex then
Log.warn
"Leftover temporary file from previous run: %s"
(tmp_dir // filename)
in
Array.iter check_file contents
let () = check ()
(* FIXME: Add a remote check to verify the existence of a tezt
repository on the remote machine. *)
|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
mli
|
tezt-4.3.0/lib/temp.mli
|
(*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2020-2022 Nomadic Labs <contact@nomadic-labs.com> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
(** Temporary files for tests. *)
(** Get a temporary file name.
For instance:
- [file "hello.ml"] may return something like ["/tmp/tezt-1234/1/hello.ml"];
- [file "some/dir/hello.ml"] may return ["/tmp/tezt-1234/1/some/dir/hello.ml"];
- [file "/dir/hello.ml"] may return ["/tmp/tezt-1234/1/dir/hello.ml"].
This function also creates the directory (and its parents) needed to host the
resulting file.
[perms] is the permissions for parent directories if they are created.
Default is [0o755], i.e. [rwxr-xr-x].
If [runner] is specified, the temporary file is registered to be located
in this remote runner, which means that it will be removed using SSH
by the [clean up] function.
[file base] always returns the same result for a given [base]
and for the same process. *)
val file : ?runner:Runner.t -> ?perms:Unix.file_perm -> string -> string
(** Get a temporary file name and create it as a directory. *)
val dir : ?runner:Runner.t -> ?perms:Unix.file_perm -> string -> string
(** Set the current process identifier.
This affects the main temporary directory, e.g. ["/tmp/tezt-1234"]
where [1234] is the PID set by [set_pid].
The default PID if [set_pid] is not called is [0].
This is automatically called by {!Tezt.Test.run}.
This is, however, not called by {!Tezt_js.Test.run}. *)
val set_pid : int -> unit
(** Allow calls to [file] and [dir] until the next [clean_up] or [stop].
Return the main temporary directory, e.g. ["/tmp/tezt-1234/1"],
so that it can be displayed to users.
Calls to [file] and [dir] which are made before [start] result in an error.
Do not call this directly, it is called by {!Test.run}.
This prevents you from creating temporary files accidentally before your test
actually runs. Indeed, if your test is disabled from the command-line it should
not create temporary files. By using {!Test.run} you also ensure that {!clean_up}
is called. *)
val start : unit -> string
(** Disallow calls to [file] and [dir] until the next [start].
This can be called in place of [clean_up] if you want to keep temporary files. *)
val stop : unit -> unit
(** Delete temporary files and directories.
All files which were returned by [file] are deleted.
All directories which were returned by [dir] are deleted, but only if they
did not already exist.
All parent directories that were created are then deleted, but only if they are empty. *)
val clean_up : unit -> unit
|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
ml
|
tezt-4.3.0/lib/tezt.ml
|
(*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2022 Nomadic Labs <contact@nomadic-labs.com> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
(** Tezt. *)
(** Tezt (pronounced "tezty", as in "tasty" with a "z") is a test framework for OCaml.
It is well suited for writing and executing unit, integration and
regression tests. It integrates well with continuous integration (CI).
Tezt provides a function ({!Test.register}) to register tests.
Tests have a title, some tags, and an implementation (a function).
Titles and tags can be used on the command-line to select which tests to run.
The name of the file in which the test was registered can also be used to do so.
The implementation of the test is ran if the test is selected.
If this implementation does not raise an exception (for instance by calling
{!Test.fail}), the test is considered to be successful.
Along with modules {!Base}, which is supposed to be [open]ed a la [Pervasives]
and which provides a few useful generic functions, and {!Check}, which provides
ways to perform assertions with nice error messages, the result is a framework
that is suitable for unit tests.
Tests can be ran in a CI, optionally producing JUnit reports.
Tezt can automatically compute a partition of the set of tests
where subsets are balanced to take roughly the same amount of time to run.
The intent is that each of those subset can be one CI job, resulting in automatic
balanced parallelisation.
Specific features supporting integration tests include:
- running external processes;
- invoking distant runners through SSH;
- decoding JSON values (e.g. to test REST APIs);
- cleaning up temporary files automatically.
Specific features supporting regression tests include:
- capturing output from local or external processes;
- applying regular-expression-based substitutions to those outputs;
- comparing with previous captured outputs.
Tezt provides a flexible user interface:
- using colors in logs (e.g. to distinguish external processes or to make error
messages easy to see);
- adjusting automatically the verbosity of logs around errors;
- making it easy to copy-paste the invoked commands to reproduce errors;
- giving extensive information to precisely locate errors;
- supporting flaky (randomly failing) tests, by running them repeatedly.
To get started, register tests with {!Test.register}, then call the main function
{!Test.run}. Tests are run from the command-line, for instance with [dune runtest]
or [dune exec]. The latter gives access to a large list of command-line options
to select which tests to run and how. Execute your program with [--help] to
get the list. See also the
{{: https://research-development.nomadic-labs.com/announcing-tezt.html } Tezt mini-tutorial}. *)
(** {2 Backends} *)
(** Tezt executables can be compiled to bytecode, native code, or JavaScript.
This is reflected by three Dune libraries:
- code which is common to all backends is provided by [tezt.core];
- the bytecode and native code backends are provided by [tezt];
- the JavaScript backend is provided by [tezt.js].
Function [Test.run] is only available in [tezt] and [tezt.js].
In other words, to actually run the tests you have to decide whether
to use the JavaScript backend or not.
The difference between [tezt] and [tezt.js] is that [tezt.js] does not provide:
- the [Process] module;
- the [Temp] module;
- the [Runner] module.
So the JavaScript backend is not well suited for integration tests and regression tests.
But it does support unit tests.
If you want to run your tests on multiple backends you have to write
two executables: one linked with [tezt] and one linked with [tezt.js].
To share the code of your tests, you can write your calls to [Test.register]
in a library that depends on [tezt.core]. Here is an example of [dune] files:
{[
; Dune file for the library that calls [Test.register].
(library
(name tezts)
(libraries tezt.core)
(library_flags (:standard -linkall))
(flags (:standard) -open Tezt_core -open Tezt_core.Base))
; Dune file for the executable used to run tests in native or bytecode mode.
(executable (name main) (libraries tezts tezt))
; Dune file for the executable used to run tests using nodejs.
(executable (name main_js) (modes js) (libraries tezts tezt.js))
]} *)
(** {2 Modules} *)
(** Support for running promises in the background.
Background promises are promises that are not bound.
Registering them makes sure that Tezt handles their exceptions correctly. *)
module Background = Background
(** Base primitives useful in writing tests.
This module is intended to be [open]ed, as an extension of [Stdlib].
It contains functions to manage concurrency, I/Os, regular expressions, etc. *)
module Base = Base
(** Support for expressing assertions. *)
module Check = Check
(** Command-line interface options. *)
module Cli = Cli
(** Compute the difference between two sequences of items. *)
module Diff = Diff
(** JSON handling (encoding/decoding, accessors, error management, etc). *)
module JSON = JSON
(** Functions for logging messages. *)
module Log = Log
(** Managing external processes. *)
module Process = Process
(** Process hooks, in particular for use with regression tests. *)
module Process_hooks = Process_hooks
(** Regression test helpers (run tests, capture output, etc). *)
module Regression = Regression
(** Runner specifications for processes spawned remotely using SSH. *)
module Runner = Runner
(** Temporary file management. *)
module Temp = Temp
(** Base test management (registering, initializations, etc). *)
module Test = struct
include Test
(** Run registered tests that should be run.
This function is not available in [tezt.core].
It is available in [tezt] and [tezt.js]. *)
let run = Main.run
end
(**/**)
(* Everything below is not meant for the public API and will not appear
in ocamldoc. *)
(** Support for alternative process backends. *)
module Process_common = Process_common
(** The standard output or standard error output of a process. *)
module Echo = Echo
|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
ml
|
tezt-4.3.0/lib_core/TSL.ml
|
(*****************************************************************************)
(* *)
(* SPDX-License-Identifier: MIT *)
(* Copyright (c) 2023 Nomadic Labs <contact@nomadic-labs.com> *)
(* *)
(*****************************************************************************)
open Base
let parse string =
try
Some (TSL_parser.expression TSL_lexer.token (Lexing.from_string string))
with
| Parsing.Parse_error -> None
| Failure _ (* can be raised by the code generated by ocamllex or ocamlyacc *)
| TSL_lexer.Error _ ->
None
type show_context = SC_not | SC_and | SC_or | SC_toplevel
let show_string_var : TSL_AST.string_var -> string = function
| File -> "file"
| Title -> "title"
let show_int_var : TSL_AST.int_var -> string = function Memory -> "memory"
let show_float_var : TSL_AST.float_var -> string = function
| Duration -> "duration"
let show_numeric_operator : TSL_AST.numeric_operator -> string = function
| EQ -> "="
| NE -> "<>"
| GT -> ">"
| GE -> ">="
| LT -> "<"
| LE -> "<="
(* The list of safe characters should match the rule in [TSL_lexer]. *)
let char_is_unsafe = function
| 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' | '-' | '+' | '/' | '.' -> false
| _ -> true
(* If [true] could be a tag, TSL expressions [true] would select all tests,
even though the user may actually have meant to only select tests with tag [true].
The same applies for [false]. *)
let is_valid_tag = function
| "true" | "false" -> false
| tag ->
let len = String.length tag in
1 <= len && len <= 32
&&
let rec check i =
if i >= len then true
else
match tag.[i] with
| 'a' .. 'z' | '0' .. '9' | '_' -> check (i + 1)
| _ -> false
in
check 0
(* [String.exists] is only from OCaml 4.13.0. *)
let string_exists f s =
let exception Yes in
try
for i = 0 to String.length s - 1 do
if f s.[i] then raise Yes
done ;
false
with Yes -> true
let show_string string =
match string with
| "" -> "\"\""
| "not" -> "\"not\""
| "true" -> "\"true\""
| "false" -> "\"false\""
| _ ->
let needs_quotes =
string.[0] = '/' || string_exists char_is_unsafe string
in
if needs_quotes then (
let buffer = Buffer.create (String.length string * 2) in
Buffer.add_char buffer '"' ;
for i = 0 to String.length string - 1 do
let c = string.[i] in
(match c with '"' | '\\' -> Buffer.add_char buffer '\\' | _ -> ()) ;
Buffer.add_char buffer c
done ;
Buffer.add_char buffer '"' ;
Buffer.contents buffer)
else string
let add_parentheses s = "(" ^ s ^ ")"
let show ?(always_parenthesize = false) expression =
let rec show context (expression : TSL_AST.t) =
let parentheses_for_predicate =
if always_parenthesize then add_parentheses
else
match context with
| SC_not -> add_parentheses
| SC_and | SC_or | SC_toplevel -> Fun.id
in
match expression with
| True -> "true"
| False -> "false"
| String_predicate (var, Is value) ->
parentheses_for_predicate
(show_string_var var ^ " = " ^ show_string value)
| String_predicate (var, Matches value) ->
parentheses_for_predicate
(show_string_var var ^ " =~ " ^ show_string (show_rex value))
| Int_predicate (var, op, value) ->
parentheses_for_predicate
(show_int_var var ^ " " ^ show_numeric_operator op ^ " "
^ show_string (string_of_int value))
| Float_predicate (var, op, value) ->
parentheses_for_predicate
(show_float_var var ^ " " ^ show_numeric_operator op ^ " "
^ show_string (string_of_float value))
| Has_tag tag -> show_string tag
| Not (Has_tag tag) ->
if is_valid_tag tag then "/" ^ tag else "not " ^ show_string tag
| Not p -> "not " ^ show SC_not p
| And (a, b) ->
let parentheses =
if always_parenthesize then add_parentheses
else
match context with
| SC_not -> add_parentheses
| SC_and | SC_or | SC_toplevel -> Fun.id
in
parentheses (show SC_and a ^ " && " ^ show SC_and b)
| Or (a, b) ->
let parentheses =
if always_parenthesize then add_parentheses
else
match context with
| SC_not | SC_and -> add_parentheses
| SC_or | SC_toplevel -> Fun.id
in
parentheses (show SC_or a ^ " || " ^ show SC_or b)
in
show SC_toplevel expression
(* We want to guarantee that, for a given [x],
the set of all tests is equal to the disjoint union of:
- the set of tests such that [memory >= x];
- the set of tests such that [memory < x].
If [memory] could be [None], we could be tempted to have [None <= 1000] be false,
and [None > 1000] be also false at the same time.
So some tests would be in neither subset. *)
type env = {
file : string;
title : string;
tags : string list;
memory : int;
duration : float;
}
let get_string : env -> TSL_AST.string_var -> string =
fun env -> function File -> env.file | Title -> env.title
let get_int : env -> TSL_AST.int_var -> int =
fun env -> function Memory -> env.memory
let get_float : env -> TSL_AST.float_var -> float =
fun env -> function Duration -> env.duration
let apply_string_operator : string -> TSL_AST.string_operator -> bool =
fun value -> function
| Is expected -> String.equal value expected
| Matches rex -> value =~ rex
let apply_numeric_operator (type a) (compare : a -> a -> int) (value1 : a)
(operator : TSL_AST.numeric_operator) (value2 : a) : bool =
let c = compare value1 value2 in
match operator with
| EQ -> c = 0
| NE -> c <> 0
| GT -> c > 0
| GE -> c >= 0
| LT -> c < 0
| LE -> c <= 0
let rec eval : env -> TSL_AST.t -> bool =
fun env -> function
| True -> true
| False -> false
| String_predicate (var, operator) ->
apply_string_operator (get_string env var) operator
| Int_predicate (var, operator, value) ->
apply_numeric_operator Int.compare (get_int env var) operator value
| Float_predicate (var, operator, value) ->
apply_numeric_operator Float.compare (get_float env var) operator value
| Has_tag tag -> List.mem tag env.tags
| Not p -> not (eval env p)
| And (a, b) -> eval env a && eval env b
| Or (a, b) -> eval env a || eval env b
let conjunction = function
| [] -> TSL_AST.True
| head :: tail -> List.fold_left (fun a b -> TSL_AST.And (a, b)) head tail
let tags expression =
let rec gather acc : TSL_AST.t -> _ = function
| True | False
| String_predicate ((File | Title), _)
| Int_predicate _ | Float_predicate _ ->
acc
| Has_tag tag -> String_set.add tag acc
| Not p -> gather acc p
| And (a, b) | Or (a, b) -> gather (gather acc a) b
in
String_set.elements (gather String_set.empty expression)
|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
mli
|
tezt-4.3.0/lib_core/TSL.mli
|
(*****************************************************************************)
(* *)
(* SPDX-License-Identifier: MIT *)
(* Copyright (c) 2023 Nomadic Labs <contact@nomadic-labs.com> *)
(* *)
(*****************************************************************************)
(** Test Selection Language. *)
(** Parse a TSL expression. *)
val parse : string -> TSL_AST.t option
(** Convert a TSL expression to a string. *)
val show : ?always_parenthesize:bool -> TSL_AST.t -> string
(** Environment in which to evaluate TSL expressions. *)
type env = {
file : string;
title : string;
tags : string list;
memory : int;
duration : float;
}
(** Evaluate a TSL expression. *)
val eval : env -> TSL_AST.t -> bool
(** Make a conjunction from a list. *)
val conjunction : TSL_AST.t list -> TSL_AST.t
(** Test whether a string is a valid tag.
Tags:
- must have a length between 1 and 32;
- must only contain characters lowercase letters [a-z], digits [0-9] or underscores [_];
- cannot be ["true"] nor ["false"]. *)
val is_valid_tag : string -> bool
(** Get the list of tags that appear in a TSL expression. *)
val tags : TSL_AST.t -> string list
|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
ml
|
tezt-4.3.0/lib_core/TSL_AST.ml
|
(*****************************************************************************)
(* *)
(* SPDX-License-Identifier: MIT *)
(* Copyright (c) 2023 Nomadic Labs <contact@nomadic-labs.com> *)
(* *)
(*****************************************************************************)
(** Abstract Syntax Tree of the Test Selection Language. *)
open Base
(** Test properties that can be queried using string operators. *)
type string_var = File | Title
(** Test properties that can be queried using integer comparison operators. *)
type int_var = Memory
(** Test properties that can be queried using float comparison operators. *)
type float_var = Duration
(** Comparison operators for strings. *)
type string_operator = Is of string | Matches of rex
(** Comparison operators for numbers. *)
type numeric_operator = EQ | NE | GT | GE | LT | LE
(** AST of TSL. *)
type t =
| True
| False
| String_predicate of string_var * string_operator
| Int_predicate of int_var * numeric_operator * int
| Float_predicate of float_var * numeric_operator * float
| Has_tag of string
| Not of t
| And of t * t
| Or of t * t
|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
ml
|
tezt-4.3.0/lib_core/background.ml
|
(*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2021-2022 Nomadic Labs <contact@nomadic-labs.com> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
open Base
type state =
| Not_started
| Started of {
exception_handler : exn -> unit;
mutable pending : unit Lwt.t list;
}
let state = ref Not_started
let register p =
match !state with
| Not_started -> invalid_arg "Background.register: not started"
| Started started_state ->
let p =
Lwt.catch
(fun () -> p)
(function
| Lwt.Canceled -> unit
| exn ->
started_state.exception_handler exn ;
unit)
in
started_state.pending <- p :: started_state.pending
let start exception_handler =
match !state with
| Not_started -> state := Started {exception_handler; pending = []}
| Started _ -> invalid_arg "Background.start: already started"
let stop () =
match !state with
| Not_started -> unit
| Started started_state ->
let rec loop () =
match started_state.pending with
| [] -> unit
| list ->
started_state.pending <- [] ;
(* Note that when registered promises are rejected, their wrapper
cause them to resolve with unit instead. So this [join]
cannot be rejected. (The user may still cancel it though, by
canceling the promise returned by [stop].) *)
let* () = Lwt.join list in
(* Maybe some new promises were registered. *)
loop ()
in
let* () = loop () in
state := Not_started ;
unit
|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
mli
|
tezt-4.3.0/lib_core/background.mli
|
(*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2021-2022 Nomadic Labs <contact@nomadic-labs.com> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
(** Promises to run in the background during tests. *)
(** Register a promise that will run in the background.
After a test runs, [Test.run] waits for all registered promises to finish.
If a registered promise raises an exception which is not [Lwt.Canceled],
the current test fails immediately, but [Test.run] still waits for
other background promises to finish.
Make sure that the promise you register eventually resolves.
If it doesn't, [stop] (and thus [Test.run], which calls [stop])
will hang forever.
Calls to [register] when no test is running result in an error. *)
val register : unit Lwt.t -> unit
(** Allow calls to [register] until [stop] is called.
If a promise that is later [register]ed is rejected by an exception
which is not [Lwt.Canceled], [start] calls its argument.
This may occur several times, including during [stop].
@raise Invalid_arg if calls to [register] are already allowed,
i.e. if [start] has already been called without a corresponding [stop].
Don't call this directly, it is called by [Test.run]. *)
val start : (exn -> unit) -> unit
(** Let all [register]ed promises resolve, then stop allowing calls to [register].
The promise returned by [stop] is never rejected except if you cancel it.
If you do cancel it, you may have to call [stop] again though as it is not
guaranteed that all background promises have also been canceled.
In other words, canceling the promise returned by [stop] is probably
a bad idea.
Calling [stop] when calls to [register] are not allowed has no effect,
i.e. you can call [stop] even with no corresponding [start].
Don't call this directly, it is called by [Test.run]. *)
val stop : unit -> unit Lwt.t
|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
ml
|
tezt-4.3.0/lib_core/base.ml
|
(*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2020-2022 Nomadic Labs <contact@nomadic-labs.com> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
(* We let some exceptions propagate. They are caught when running tests and
logged as errors. We want to print a human-readable version of those errors.
Exceptions that should be caught, such as [Not_found] or [End_of_file],
do not need a human-readable version. *)
let () =
Printexc.register_printer @@ function
| Failure error -> Some error
| Sys_error error -> Some error
| _ -> None
let ( // ) = Filename.concat
let sf = Printf.sprintf
let ( let* ) = Lwt.bind
let ( and* ) = Lwt.both
let lwt_both_fail_early a b =
let main_promise, main_awakener = Lwt.task () in
let already_woke_up = ref false in
Lwt.on_failure a (fun exn ->
if not !already_woke_up then (
already_woke_up := true ;
Lwt.wakeup_exn main_awakener exn) ;
Lwt.cancel b) ;
Lwt.on_failure b (fun exn ->
if not !already_woke_up then (
already_woke_up := true ;
Lwt.wakeup_exn main_awakener exn) ;
Lwt.cancel a) ;
let both = Lwt.both a b in
Lwt.on_success both (fun x -> Lwt.wakeup main_awakener x) ;
Lwt.on_cancel main_promise (fun () -> Lwt.cancel both) ;
main_promise
let return = Lwt.return
let unit = Lwt.return_unit
let none = Lwt.return_none
let some = Lwt.return_some
let mandatory name = function
| None -> failwith ("no value for " ^ name)
| Some x -> x
let range a b =
let rec range ?(acc = []) a b =
if b < a then acc else range ~acc:(b :: acc) a (b - 1)
in
range a b
let rec list_find_map f = function
| [] -> None
| head :: tail -> (
match f head with None -> list_find_map f tail | Some _ as x -> x)
type rex = string * Re.re
let rec take n l =
if n < 0 then invalid_arg "Tezt.Base.take: argument cannot be negative"
else if n = 0 then []
else match l with [] -> [] | hd :: rest -> hd :: take (n - 1) rest
let rec drop n l =
if n < 0 then invalid_arg "Tezt.Base.drop: argument cannot be negative"
else if n = 0 then l
else match l with [] -> [] | _ :: rest -> drop (n - 1) rest
let span pred =
let rec aux acc = function
| x :: xs when pred x -> aux (x :: acc) xs
| l -> (List.rev acc, l)
in
aux []
let rex ?opts r = (r, Re.compile (Re.Perl.re ?opts r))
let rexf ?opts fmt = Printf.ksprintf (rex ?opts) fmt
let show_rex = fst
let ( =~ ) s (_, r) = Re.execp r s
let ( =~! ) s (_, r) = not (Re.execp r s)
let get_group group index =
match Re.Group.get group index with
| exception Not_found ->
invalid_arg
"regular expression has not enough capture groups for its usage, did \
you forget parentheses?"
| value -> value
let ( =~* ) s (_, r) =
match Re.exec_opt r s with
| None -> None
| Some group -> Some (get_group group 1)
let ( =~** ) s (_, r) =
match Re.exec_opt r s with
| None -> None
| Some group -> Some (get_group group 1, get_group group 2)
let ( =~*** ) s (_, r) =
match Re.exec_opt r s with
| None -> None
| Some group -> Some (get_group group 1, get_group group 2, get_group group 3)
let ( =~**** ) s (_, r) =
match Re.exec_opt r s with
| None -> None
| Some group ->
Some
( get_group group 1,
get_group group 2,
get_group group 3,
get_group group 4 )
let matches s (_, r) = Re.all r s |> List.map (fun g -> get_group g 1)
let replace_string ?pos ?len ?all (_, r) ~by s =
Re.replace_string ?pos ?len ?all r ~by s
let rec repeat n f =
if n <= 0 then unit
else
let* () = f () in
repeat (n - 1) f
let fold n init f =
let rec aux k accu =
if k >= n then return accu
else
let* accu = f k accu in
aux (k + 1) accu
in
aux 0 init
let with_open_out file write_f =
let chan = open_out file in
try
write_f chan ;
close_out chan
with x ->
close_out chan ;
raise x
let with_open_in file read_f =
let chan = open_in file in
try
let value = read_f chan in
close_in chan ;
value
with x ->
close_in chan ;
raise x
let write_file filename ~contents =
with_open_out filename @@ fun ch -> output_string ch contents
let read_file filename =
with_open_in filename @@ fun ch ->
let buffer = Buffer.create 512 in
let bytes = Bytes.create 512 in
let rec loop () =
let len = input ch bytes 0 512 in
if len > 0 then (
Buffer.add_subbytes buffer bytes 0 len ;
loop ())
in
loop () ;
Buffer.contents buffer
module String_map = Map.Make (String)
module String_set = struct
include Set.Make (String)
let pp fmt set =
if is_empty set then Format.fprintf fmt "{}"
else
Format.fprintf
fmt
"@[<hov 2>{ %a }@]"
(Format.pp_print_list
~pp_sep:(fun fmt () -> Format.fprintf fmt ",@ ")
(fun fmt -> Format.fprintf fmt "%S"))
(elements set)
end
let project_root =
match Sys.getenv_opt "DUNE_SOURCEROOT" with
| Some x -> x
| None -> (
match Sys.getenv_opt "PWD" with
| Some x -> x
| None ->
(* For some reason, under [dune runtest], [PWD] and
[getcwd] have different values. [getcwd] is in
[_build/default], and [PWD] is where [dune runtest] was
executed, which is closer to what we want. *)
Sys.getcwd ())
|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
mli
|
tezt-4.3.0/lib_core/base.mli
|
(*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2020-2022 Nomadic Labs <contact@nomadic-labs.com> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
(** Base functions. *)
(** {2 Strings} *)
(** Same as [Filename.concat]. *)
val ( // ) : string -> string -> string
(** Same as [Printf.sprintf]. *)
val sf : ('a, unit, string) format -> 'a
(** {2 Concurrency Monad} *)
(** Same as [Lwt.bind]. *)
val ( let* ) : 'a Lwt.t -> ('a -> 'b Lwt.t) -> 'b Lwt.t
(** Same as [Lwt.both]. *)
val ( and* ) : 'a Lwt.t -> 'b Lwt.t -> ('a * 'b) Lwt.t
(** Same as [Lwt.both], but immediately propagate exceptions.
More precisely, if one of the two promises is rejected
or canceled, cancel the other promise and reject the resulting
promise immediately with the original exception. *)
val lwt_both_fail_early : 'a Lwt.t -> 'b Lwt.t -> ('a * 'b) Lwt.t
(** Same as [Lwt.return]. *)
val return : 'a -> 'a Lwt.t
(** Same as [Lwt.return_unit]. *)
val unit : unit Lwt.t
(** Same as [Lwt.return_none]. *)
val none : 'a option Lwt.t
(** Same as [Lwt.return_some]. *)
val some : 'a -> 'a option Lwt.t
(** Get the value of an option that must not be [None].
Usage: [mandatory name option]
[name] is used in the error message if [option] is [None]. *)
val mandatory : string -> 'a option -> 'a
(** {2 Lists} *)
(** Make a list of all integers between two integers.
If the first argument [a] is greater than the second argument [b],
return the empty list. Otherwise, returns the list [a; ...; b]. *)
val range : int -> int -> int list
(** Backport of [List.find_map] from OCaml 4.10. *)
val list_find_map : ('a -> 'b option) -> 'a list -> 'b option
(** [take n l] returns the first [n] elements of [l] if longer than [n],
else [l] itself. *)
val take : int -> 'a list -> 'a list
(** [drop n l] removes the first [n] elements of [l] if longer than [n],
else the empty list. Raise [invalid_arg] if [n] is negative. *)
val drop : int -> 'a list -> 'a list
(** Split a list based on a predicate.
[span f l] returns a pair of lists [(l1, l2)], where [l1] is the
longest prefix of [l] that satisfies the predicate [f], and [l2] is
the rest of the list. The order of the elements in the input list
is preserved such that [l = l1 @ l2]. *)
val span : ('a -> bool) -> 'a list -> 'a list * 'a list
(** {2 Regular Expressions} *)
(** Compiled regular expressions. *)
type rex
(** Compile a regular expression using Perl syntax. *)
val rex : ?opts:Re.Perl.opt list -> string -> rex
(** Same as [rex @@ sf ...]. *)
val rexf : ?opts:Re.Perl.opt list -> ('a, unit, string, rex) format4 -> 'a
(** Convert a regular expression to a string using Perl syntax. *)
val show_rex : rex -> string
(** Test whether a string matches a regular expression.
Example: ["number 1234 matches" =~ rex "\\d+"] *)
val ( =~ ) : string -> rex -> bool
(** Negation of [=~]. *)
val ( =~! ) : string -> rex -> bool
(** Match a regular expression with one capture group. *)
val ( =~* ) : string -> rex -> string option
(** Match a regular expression with two capture groups. *)
val ( =~** ) : string -> rex -> (string * string) option
(** Match a regular expression with three capture groups. *)
val ( =~*** ) : string -> rex -> (string * string * string) option
(** Match a regular expression with four capture groups. *)
val ( =~**** ) : string -> rex -> (string * string * string * string) option
(** Match a regular expression with one capture group and return all results. *)
val matches : string -> rex -> string list
(** [replace_string ~all rex ~by s] iterates on [s], and replaces every
occurrence of [rex] with [by]. If [all = false], then only the first
occurrence of [rex] is replaced. *)
val replace_string :
?pos:int ->
(* Default: 0 *)
?len:int ->
?all:bool ->
(* Default: true. Otherwise only replace first occurrence *)
rex ->
(* matched groups *)
by:string ->
(* replacement string *)
string ->
(* string to replace in *)
string
(** {2 Promises} *)
(** Repeat something a given amount of times. *)
val repeat : int -> (unit -> unit Lwt.t) -> unit Lwt.t
(** Fold n times a given function. *)
val fold : int -> 'a -> (int -> 'a -> 'a Lwt.t) -> 'a Lwt.t
(** {2 Input/Output} *)
(** Open file, use function to write output then close the output. In case of
error while writing, the channel is closed before raising the exception *)
val with_open_out : string -> (out_channel -> unit) -> unit
(** Open file, use function to read input then close the input. In case of
error while reading, the channel is closed before raising the exception **)
val with_open_in : string -> (in_channel -> 'a) -> 'a
(** Write a string into a file, overwriting the file if it already exists.
Usage: [write_file filename ~contents] *)
val write_file : string -> contents:string -> unit
(** Read the whole contents of a file. *)
val read_file : string -> string
(** {2 Common structures} *)
module String_map : Map.S with type key = string
module String_set : sig
include Set.S with type elt = string
(** Pretty-print a set of strings.
Items are quoted, separated by commas and breakable spaces,
and the result is surrounded by braces. *)
val pp : Format.formatter -> t -> unit
end
(** {2 Environment} *)
(** Path to the root of the project.
This is [DUNE_SOURCEROOT] is defined, [PWD] otherwise. *)
val project_root : string
|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
ml
|
tezt-4.3.0/lib_core/check.ml
|
(*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2021-2022 Nomadic Labs <contact@nomadic-labs.com> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
open Base
type 'a typ =
| E of {pp : Format.formatter -> 'a -> unit; equal : 'a -> 'a -> bool}
| C of {pp : Format.formatter -> 'a -> unit; compare : 'a -> 'a -> int}
let get_pp = function E {pp; _} | C {pp; _} -> pp
let get_equal = function
| E {equal; _} -> equal
| C {compare; _} -> fun a b -> compare a b = 0
let get_compare = function C {compare; _} -> Some compare | E _ -> None
let pp_print_unit fmt () = Format.pp_print_string fmt "()"
let unit = C {pp = pp_print_unit; compare = Unit.compare}
let bool = C {pp = Format.pp_print_bool; compare = Bool.compare}
let pp_print_quoted_char fmt char = Format.fprintf fmt "%C" char
let char = C {pp = pp_print_quoted_char; compare = Char.compare}
let int = C {pp = Format.pp_print_int; compare = Int.compare}
let pp_print_int32 fmt i = Format.pp_print_string fmt (Int32.to_string i)
let int32 = C {pp = pp_print_int32; compare = Int32.compare}
let pp_print_int64 fmt i = Format.pp_print_string fmt (Int64.to_string i)
let int64 = C {pp = pp_print_int64; compare = Int64.compare}
let float = C {pp = Format.pp_print_float; compare = Float.compare}
let json_u =
let pp fmt json = Format.pp_print_string fmt (JSON.encode_u json) in
let equal = JSON.equal_u in
E {pp; equal}
let json =
let pp fmt json = Format.pp_print_string fmt (JSON.encode json) in
let equal = JSON.equal in
E {pp; equal}
let compare_floats_epsilon epsilon a b =
if abs_float (a -. b) <= epsilon then 0 else Float.compare a b
let float_epsilon epsilon =
C {pp = Format.pp_print_float; compare = compare_floats_epsilon epsilon}
let pp_print_quoted_string fmt string =
Format.pp_print_char fmt '"' ;
Format.pp_print_string fmt (String.escaped string) ;
Format.pp_print_char fmt '"'
let string = C {pp = pp_print_quoted_string; compare = String.compare}
let pp_option pp_item fmt = function
| None -> Format.pp_print_string fmt "None"
| Some item ->
Format.pp_print_string fmt "Some " ;
pp_item fmt item
let option = function
| E {pp = pp_item; equal = eq_items} ->
E {pp = pp_option pp_item; equal = Option.equal eq_items}
| C {pp = pp_item; compare = cmp_items} ->
C {pp = pp_option pp_item; compare = Option.compare cmp_items}
let result (type a e) (ok : a typ) (error : e typ) : (a, e) result typ =
let pp fmt = function
| Ok x -> Format.fprintf fmt "@[<hov 2>Ok@ %a@]" (get_pp ok) x
| Error e -> Format.fprintf fmt "@[<hov 2>Error@ %a@]" (get_pp error) e
in
match (ok, error) with
| E _, _ | _, E _ ->
let equal = Result.equal ~ok:(get_equal ok) ~error:(get_equal error) in
E {pp; equal}
| C {compare = cmp_ok; _}, C {compare = cmp_err; _} ->
let compare = Result.compare ~ok:cmp_ok ~error:cmp_err in
C {pp; compare}
let pp_list ?(left = "[") ?(right = "]") pp_item fmt list =
Format.pp_print_string fmt left ;
if list <> [] then (
Format.pp_open_box fmt 1 ;
Format.pp_print_char fmt ' ' ;
let pp_sep fmt () =
Format.pp_print_char fmt ';' ;
Format.pp_print_space fmt ()
in
Format.pp_print_list ~pp_sep pp_item fmt list ;
Format.pp_print_char fmt ' ' ;
Format.pp_close_box fmt ()) ;
Format.pp_print_string fmt right
(* Note: available as List.equal in OCaml 4.12. *)
let rec equal_lists eq_items a b =
match (a, b) with
| [], [] -> true
| [], _ :: _ | _ :: _, [] -> false
| hda :: tla, hdb :: tlb -> eq_items hda hdb && equal_lists eq_items tla tlb
(* Note: available as List.compare in OCaml 4.12. *)
let rec compare_lists cmp_items a b =
match (a, b) with
| [], [] -> 0
| [], _ :: _ -> -1
| _ :: _, [] -> 1
| hda :: tla, hdb :: tlb ->
let c = cmp_items hda hdb in
if c = 0 then compare_lists cmp_items tla tlb else c
let list = function
| E {pp = pp_item; equal = eq_items} ->
E {pp = pp_list pp_item; equal = equal_lists eq_items}
| C {pp = pp_item; compare = cmp_items} ->
C {pp = pp_list pp_item; compare = compare_lists cmp_items}
let pp_array pp_item fmt array =
pp_list ~left:"[|" ~right:"|]" pp_item fmt (Array.to_list array)
let equal_arrays eq_items a b =
let len_a = Array.length a in
let len_b = Array.length b in
len_a = len_b
&&
let rec loop i =
if i >= len_a then true
else if eq_items a.(i) b.(i) then loop (i + 1)
else false
in
loop 0
let compare_arrays cmp_items a b =
let len_a = Array.length a in
let len_b = Array.length b in
let rec loop i =
(* All items up to [i - 1] are equal. *)
match (i >= len_a, i >= len_b) with
| true, true ->
(* Both arrays have the same size. *)
0
| true, false ->
(* [a] is smaller than [b]. *)
-1
| false, true ->
(* [a] is longer than [b]. *)
1
| false, false ->
let c = cmp_items a.(i) b.(i) in
if c = 0 then loop (i + 1) else c
in
loop 0
let array = function
| E {pp = pp_item; equal = eq_items} ->
E {pp = pp_array pp_item; equal = equal_arrays eq_items}
| C {pp = pp_item; compare = cmp_items} ->
C {pp = pp_array pp_item; compare = compare_arrays cmp_items}
type _ tuple_item = Item : 'b typ * ('a -> 'b) -> 'a tuple_item
let tuple (type a) (items : a tuple_item list) : a typ =
let pp fmt value =
Format.pp_open_box fmt 1 ;
Format.pp_print_string fmt "(" ;
List.iteri
(fun i (Item (item_type, get_item)) ->
if i > 0 then (
Format.pp_print_char fmt ',' ;
Format.pp_print_space fmt ()) ;
get_pp item_type fmt (get_item value))
items ;
Format.pp_print_string fmt ")" ;
Format.pp_close_box fmt ()
in
let comparable =
List.for_all
(function Item (E _, _) -> false | Item (C _, _) -> true)
items
in
if comparable then
let compare a b =
let rec loop = function
| [] -> 0
| Item (item_type, get_item) :: tail -> (
match item_type with
| E _ -> assert false (* [comparable] was [true] *)
| C {compare; _} ->
let c = compare (get_item a) (get_item b) in
if c = 0 then loop tail else c)
in
loop items
in
C {pp; compare}
else
let equal a b =
let rec loop = function
| [] -> true
| Item (item_type, get_item) :: tail ->
get_equal item_type (get_item a) (get_item b) && loop tail
in
loop items
in
E {pp; equal}
let tuple2 a b = tuple [Item (a, fst); Item (b, snd)]
let tuple3 a b c =
tuple
[
Item (a, fun (x, _, _) -> x);
Item (b, fun (_, x, _) -> x);
Item (c, fun (_, _, x) -> x);
]
let tuple4 a b c d =
tuple
[
Item (a, fun (x, _, _, _) -> x);
Item (b, fun (_, x, _, _) -> x);
Item (c, fun (_, _, x, _) -> x);
Item (d, fun (_, _, _, x) -> x);
]
let tuple5 a b c d e =
tuple
[
Item (a, fun (x, _, _, _, _) -> x);
Item (b, fun (_, x, _, _, _) -> x);
Item (c, fun (_, _, x, _, _) -> x);
Item (d, fun (_, _, _, x, _) -> x);
Item (e, fun (_, _, _, _, x) -> x);
]
let tuple8 a1 a2 a3 a4 a5 a6 a7 a8 =
tuple
[
Item (a1, fun (x, _, _, _, _, _, _, _) -> x);
Item (a2, fun (_, x, _, _, _, _, _, _) -> x);
Item (a3, fun (_, _, x, _, _, _, _, _) -> x);
Item (a4, fun (_, _, _, x, _, _, _, _) -> x);
Item (a5, fun (_, _, _, _, x, _, _, _) -> x);
Item (a6, fun (_, _, _, _, _, x, _, _) -> x);
Item (a7, fun (_, _, _, _, _, _, x, _) -> x);
Item (a8, fun (_, _, _, _, _, _, _, x) -> x);
]
let convert encode = function
| E {pp; equal} ->
let pp fmt x = pp fmt (encode x) in
let equal a b = equal (encode a) (encode b) in
E {pp; equal}
| C {pp; compare} ->
let pp fmt x = pp fmt (encode x) in
let compare a b = compare (encode a) (encode b) in
C {pp; compare}
let equalable pp equal = E {pp; equal}
let comparable pp compare = C {pp; compare}
module type EQUALABLE = sig
type t
val pp : Format.formatter -> t -> unit
val equal : t -> t -> bool
end
let equalable_module (type a) (m : (module EQUALABLE with type t = a)) =
let module M = (val m) in
equalable M.pp M.equal
module type COMPARABLE = sig
type t
val pp : Format.formatter -> t -> unit
val compare : t -> t -> int
end
let comparable_module (type a) (m : (module COMPARABLE with type t = a)) =
let module M = (val m) in
comparable M.pp M.compare
let fail ?__LOC__ error_msg pp_a a pp_b b =
let error_msg =
let substitution group =
match Re.Group.get group 0 with
| exception Not_found ->
(* Should not happen: groups always contain at least group 0
denoting the whole match. *)
""
| "%L" -> Format.asprintf "%a" pp_a a
| "%R" -> Format.asprintf "%a" pp_b b
| s -> s
in
Re.replace (Re.compile (Re.Perl.re "%[LR]")) ~f:substitution error_msg
in
Test.fail ?__LOC__ "%s" error_msg
let eq a b ?__LOC__ typ ~error_msg =
if not (get_equal typ a b) then
let pp = get_pp typ in
fail ?__LOC__ error_msg pp a pp b
let neq a b ?__LOC__ typ ~error_msg =
if get_equal typ a b then
let pp = get_pp typ in
fail ?__LOC__ error_msg pp a pp b
let comparison function_name predicate a b ?__LOC__ typ ~error_msg =
match typ with
| E _ ->
let pp = get_pp typ in
let message =
Format.asprintf
"Check.%s used on non-comparable type to compare %a and %a with \
~error_msg = %s"
function_name
pp
a
pp
b
error_msg
in
Test.fail ?__LOC__ "%s" message
| C {pp = _; compare} ->
if not (predicate (compare a b)) then
let pp = get_pp typ in
fail ?__LOC__ error_msg pp a pp b
let lt x = comparison "(<)" (fun c -> c < 0) x
let le x = comparison "(<=)" (fun c -> c <= 0) x
let gt x = comparison "(>)" (fun c -> c > 0) x
let ge x = comparison "(>=)" (fun c -> c >= 0) x
let pp_rex fmt rex = Format.pp_print_string fmt (show_rex rex)
let like a b ~error_msg =
if a =~! b then fail error_msg pp_print_quoted_string a pp_rex b
let not_like a b ~error_msg =
if a =~ b then fail error_msg pp_print_quoted_string a pp_rex b
let list_mem typ ?__LOC__ a l ~error_msg =
let eq = get_equal typ in
if not @@ List.exists (eq a) l then
let pp = get_pp typ in
let pp_list = get_pp (list typ) in
fail ?__LOC__ error_msg pp a pp_list l
let list_not_mem typ ?__LOC__ a l ~error_msg =
let eq = get_equal typ in
if List.exists (eq a) l then
let pp = get_pp typ in
let pp_list = get_pp (list typ) in
fail ?__LOC__ error_msg pp a pp_list l
let pp_exn fmt exn = Format.pp_print_string fmt (Printexc.to_string exn)
let pp_exn_option fmt = function
| None -> Format.pp_print_string fmt "no exception"
| Some exn -> pp_exn fmt exn
let raises ?__LOC__ expected_exn f ~error_msg =
match f () with
| exception exn when exn = expected_exn -> ()
| exception exn ->
fail ?__LOC__ error_msg pp_exn expected_exn pp_exn_option (Some exn)
| _ -> fail ?__LOC__ error_msg pp_exn expected_exn pp_exn_option None
let file_exists ?__LOC__ path =
if not (Sys.file_exists path) then
Test.fail ?__LOC__ "expected that file %s exists" path
let file_not_exists ?__LOC__ path =
if Sys.file_exists path then
Test.fail ?__LOC__ "expected that file %s does not exists" path
let directory_exists ?__LOC__ path =
if not (Sys.file_exists path && Sys.is_directory path) then
Test.fail ?__LOC__ "expected that directory %s exists" path
let directory_not_exists ?__LOC__ path =
if Sys.file_exists path && Sys.is_directory path then
Test.fail ?__LOC__ "expected that directory %s does not exists" path
let is_true ?__LOC__ b ~error_msg =
if not b then Test.fail ?__LOC__ "%s" error_msg
let is_false ?__LOC__ b ~error_msg = is_true ?__LOC__ (not b) ~error_msg
(* We define infix operators at the end to avoid using them accidentally. *)
let ( = ) = eq
let ( <> ) = neq
let ( < ) = lt
let ( <= ) = le
let ( > ) = gt
let ( >= ) = ge
let ( =~ ) = like
let ( =~! ) = not_like
|
tezt
|
4.3.0
|
MIT
|
https://gitlab.com/nomadic-labs/tezt/
|
git+https://gitlab.com/nomadic-labs/tezt.git
|
mli
|
tezt-4.3.0/lib_core/check.mli
|
(*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2021-2022 Nomadic Labs <contact@nomadic-labs.com> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
(** Assertions.
This module defines predicates that call [Test.fail] when they do not hold.
Using these predicates gives you more consistent error messages. *)
open Base
(** {2 Comparable Types} *)
(** Type descriptions.
A [t typ] equips a type [t] with a pretty printer, and either an
equality or a comparison function.
All types can be used with [eq] and [neq], but some types will result
in an exception when used with [lt], [le], [gt] and [ge].
Such types are said to be non comparable. *)
type 'a typ
(** The unit type.
Not very useful on its own, but may be useful inside more structured types.
This type is comparable. *)
val unit : unit typ
(** The boolean type.
Not very useful on its own since one can write [if not b then Test.fail ...],
but may be useful inside more structured types.
This type is comparable with [true > false]. *)
val bool : bool typ
(** The character type.
This type is comparable. Characters are compared by comparing their
byte representation. *)
val char : char typ
(** The integer type.
This type is comparable. *)
val int : int typ
(** The 32-bit integer type.
This type is comparable. *)
val int32 : int32 typ
(** The 64-bit integer type.
This type is comparable. *)
val int64 : int64 typ
(** The float type.
Note that testing float equality or inequality is often a bad idea.
Prefer [float_epsilon] when it makes sense.
This type is comparable. *)
val float : float typ
(** The float type with an approximative equality function.
The argument is how much of a difference can two values have and still
be considered equal.
This type is comparable. *)
val float_epsilon : float -> float typ
(** The string type.
This type is comparable in lexicographic order, where each character is
compared using the same comparison function as [char]. *)
val string : string typ
(** The [JSON.u] type.
Objects are compared using [JSON.equal_u]. *)
val json_u : JSON.u typ
(** The [JSON.t] type.
Objects are compared using [JSON.equal]. *)
val json : JSON.t typ
(** Make an option type.
If the item type is comparable, the result is comparable.
[None] is always lesser than [Some _]. *)
val option : 'a typ -> 'a option typ
(** Make a result type.
This type is comparable if both ['a typ] and ['e typ] are comparable. *)
val result : 'a typ -> 'e typ -> ('a, 'e) result typ
(** Make a list type.
If the item type is comparable, the result is comparable in lexicographic order. *)
val list : 'a typ -> 'a list typ
(** Make an array type.
If the item type is comparable, the result is comparable in lexicographic order. *)
val array : 'a typ -> 'a array typ
(** Make a 2-tuple type.
If both item types are comparable, the result is comparable in lexicographic order. *)
val tuple2 : 'a typ -> 'b typ -> ('a * 'b) typ
(** Make a 3-tuple type.
If all item types are comparable, the result is comparable in lexicographic order. *)
val tuple3 : 'a typ -> 'b typ -> 'c typ -> ('a * 'b * 'c) typ
(** Make a 4-tuple type.
If all item types are comparable, the result is comparable in lexicographic order. *)
val tuple4 : 'a typ -> 'b typ -> 'c typ -> 'd typ -> ('a * 'b * 'c * 'd) typ
(** Make a 5-tuple type.
If all item types are comparable, the result is comparable in lexicographic order. *)
val tuple5 :
'a typ -> 'b typ -> 'c typ -> 'd typ -> 'e typ -> ('a * 'b * 'c * 'd * 'e) typ
(** Make a 8-tuple type.
If all item types are comparable, the result is comparable in lexicographic order. *)
val tuple8 :
'a1 typ ->
'a2 typ ->
'a3 typ ->
'a4 typ ->
'a5 typ ->
'a6 typ ->
'a7 typ ->
'a8 typ ->
('a1 * 'a2 * 'a3 * 'a4 * 'a5 * 'a6 * 'a7 * 'a8) typ
(** Make a type by encoding to another.
Usage: [convert encode typ]
Example: [convert (fun { x; y } -> x, y) (tuple2 int string)]
Values are converted to [typ] using [encode] before being pretty-printed
or compared. The result type is comparable if [typ] is comparable. *)
val convert : ('a -> 'b) -> 'b typ -> 'a typ
(** Return the pretty-printer associated to the given type. *)
val get_pp : 'a typ -> Format.formatter -> 'a -> unit
(** Return the equality function associated to the given type. *)
val get_equal : 'a typ -> 'a -> 'a -> bool
(** Return the comparison function associated to the given type if it is
comparable, else return [None]. *)
val get_compare : 'a typ -> ('a -> 'a -> int) option
(** Make a custom type from a pretty-printer and an equality function.
The result is not comparable. *)
val equalable : (Format.formatter -> 'a -> unit) -> ('a -> 'a -> bool) -> 'a typ
(** Make a custom type from a pretty-printer and a comparison function. *)
val comparable : (Format.formatter -> 'a -> unit) -> ('a -> 'a -> int) -> 'a typ
module type EQUALABLE = sig
type t
val pp : Format.formatter -> t -> unit
val equal : t -> t -> bool
end
(** Same as {!equalable} but takes a module.
Example: [equalable_module (module String)]. *)
val equalable_module : (module EQUALABLE with type t = 'a) -> 'a typ
module type COMPARABLE = sig
type t
val pp : Format.formatter -> t -> unit
val compare : t -> t -> int
end
(** Same as {!comparable} but takes a module.
Example: [comparable_module (module String)]. *)
val comparable_module : (module COMPARABLE with type t = 'a) -> 'a typ
(** {2 Predicates} *)
(** For all functions of this section, if the test fails, the function calls
[Test.fail] with the error message given in [~error_msg].
This [~error_msg] may contain placeholders [%L] and [%R] where:
- [%L] is replaced by the left-hand side value of the operator;
- [%R] is replaced by the right-hand side value of the operator.
Here are some examples of [~error_msg] for inspiration:
- ["expected filename = %R, got %L"]
- ["expected list size >= %R, got %L"]
- ["expected f to be monotonous, got f x = %L and f y = %R with x < y"] *)
(** {2 Comparison Operators} *)
(** Check that a value is equal to another.
Example: [Check.((value = expected) int ~error_msg:"expected value = %R, got %L")] *)
val ( = ) : 'a -> 'a -> ?__LOC__:string -> 'a typ -> error_msg:string -> unit
(** Check that a value is not equal to another.
Example: [Check.((value <> wrong) int ~error_msg:"expected value <> %R")] *)
val ( <> ) : 'a -> 'a -> ?__LOC__:string -> 'a typ -> error_msg:string -> unit
(** Check that a value is less than another.
Example: [Check.((value < threshold) int ~error_msg:"expected value < %R, got %L")] *)
val ( < ) : 'a -> 'a -> ?__LOC__:string -> 'a typ -> error_msg:string -> unit
(** Check that a value is less than or equal to another.
Example: [Check.((value <= threshold) int ~error_msg:"expected value <= %R, got %L")] *)
val ( <= ) : 'a -> 'a -> ?__LOC__:string -> 'a typ -> error_msg:string -> unit
(** Check that a value is greater than another.
Example: [Check.((value > threshold) int ~error_msg:"expected value > %R, got %L")] *)
val ( > ) : 'a -> 'a -> ?__LOC__:string -> 'a typ -> error_msg:string -> unit
(** Check that a value is greater than or equal to another.
Example: [Check.((value >= threshold) int ~error_msg:"expected value >= %R, got %L")] *)
val ( >= ) : 'a -> 'a -> ?__LOC__:string -> 'a typ -> error_msg:string -> unit
(** Check that a string matches a regular expression.
Example: [Check.((value =~ rex) ~error_msg:"expected value =~ %R, got %L")] *)
val ( =~ ) : string -> rex -> error_msg:string -> unit
(** Check that a string does not match a regular expression.
Example: [Check.((value =~! rex) ~error_msg:"expected value =~! %R, got %L")] *)
val ( =~! ) : string -> rex -> error_msg:string -> unit
(** {2 Predicates on Lists} *)
(** Check that a value belongs to a list.
Example: [Check.list_mem int i list int ~error_msg:"expected %L to be in the
list")] * *)
val list_mem :
'a typ -> ?__LOC__:string -> 'a -> 'a list -> error_msg:string -> unit
(** Check that a value does not belong to a list.
Example: [Check.list_not_mem int i list int ~error_msg:"expected %L to not
be in the list")] * *)
val list_not_mem :
'a typ -> ?__LOC__:string -> 'a -> 'a list -> error_msg:string -> unit
(** {2 Predicates on Exceptions} *)
(** Check that evaluating the given function raises the expected exception.
Example: [Check.raises f exn ~error_msg:"expected f to raise %L, got %R"] *)
val raises :
?__LOC__:string -> exn -> (unit -> unit) -> error_msg:string -> unit
(** {2 Predicates on files} *)
(** Check that a file with the given name exists. *)
val file_exists : ?__LOC__:string -> string -> unit
(** Check that a file with the given name does not exist. *)
val file_not_exists : ?__LOC__:string -> string -> unit
(** Check that a directory with the given name exists.
This [directory_exists path] succeeds if there is a file at
[path] and it is a directory. *)
val directory_exists : ?__LOC__:string -> string -> unit
(** Check that a directory with the given name does not exist.
This [directory_not_exists path] succeeds either if there is a
non-directory file at [path] or if there is no file at [path]. *)
val directory_not_exists : ?__LOC__:string -> string -> unit
(** {2 Predicates on booleans} *)
(** Check that a boolean is true.
Example: [Check.is_true cond ~error_msg:"expected condition to be true"] *)
val is_true : ?__LOC__:string -> bool -> error_msg:string -> unit
(** Check that a boolean is false.
Example: [Check.is_false cond ~error_msg:"expected condition to be false"] *)
val is_false : ?__LOC__:string -> bool -> error_msg:string -> unit
|
End of preview. Expand
in Data Studio
This is a dataset automatically generated from ocaml/opam:archive. You can find more information about this dataset in this blogpost.
- Downloads last month
- 222