OUnit: assert value is instance of type

586 views Asked by At

Using the OUnit unit testing framework in OCaml, I would like to test that the result of evaluating a function is an instance of a specified type.

Defining such a test in Python's PyTest would be done as follows:

def test_foo():
    assert isinstance(foo(2), int)

How can this logic be translated to OUnit? That is, how are assertions of type membership specified?

I'm aware that, assuming the function under test is annotated with the proper type signature, this testing might be unnecessary.

1

There are 1 answers

0
ivg On BEST ANSWER

This is the job of a type checker, and it is made automatically during the compilation (at static time). The type checker (i.e., the compiler) guarantees that all values that are created by a function has the same type, and the type is defined statically at the compilation time. You will not be able to compile a function, that creates values of different types, as you will get a type error during the compilation. This is an essential property of all statically typed languages, e.g., Java, C and C++ also has the same property.

So, probably, you're using are confusing terminology. It might be the case, that what you're actually trying to test, is that the value belongs to a particular variant of a sum type. For example, if you have a sum type called numbers defined as:

type t = 
  | Float of float
  | Int of int

and you would like to test that function truncate, defined as

 let truncate = function
   | Float x -> Int (truncate x)
   | x -> x

always returns the Int variant, then you can do this as follows:

  let is_float = function Float _ -> true | _ -> false
  let is_int = function Int _ -> true | _ -> false

  assert (is_int (truncate 3.14))