0

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.

David Shaked
  • 3,171
  • 3
  • 20
  • 31
  • 2
    It's also unnecessary if the function is not annotated :-) OCaml is a strongly typed language, you can't compute a value of the wrong type. This is one reason we like it. It of course makes sense to think in terms of *values* that are and aren't allowed. – Jeffrey Scofield Jan 04 '17 at 20:36
  • @JeffreyScofield. I should have mentioned this earlier, but I can't test for a particular value because the function under test randomly generates instances of a type. I'm really not sure how to unit test such a function... – David Shaked Jan 06 '17 at 07:27

1 Answers1

2

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))
ivg
  • 34,431
  • 2
  • 35
  • 63